@ujet/websdk-headless 6.39.1 → 6.40.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 CHANGED
@@ -1,5 +1,5 @@
1
1
  "use strict";var h6=Object.defineProperty;var WC=r=>{throw TypeError(r)};var p6=(r,e,t)=>e in r?h6(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var oe=(r,e,t)=>p6(r,typeof e!="symbol"?e+"":e,t),HC=(r,e,t)=>e.has(r)||WC("Cannot "+t);var Ic=(r,e,t)=>(HC(r,e,"read from private field"),t?t.call(r):e.get(r)),Cy=(r,e,t)=>e.has(r)?WC("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),ky=(r,e,t,n)=>(HC(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function v6(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 g6{constructor(){oe(this,"_hostPath","")}setPath(e){this._hostPath=e}getPath(){return this._hostPath}}const $O=new g6;let m6=class{constructor(){oe(this,"currentAudio",null);oe(this,"cleanupCallback",null)}async playPing(){$O.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 ll=(r=>(r.WAITING="waiting",r.READY="ready",r.IN_PROGRESS="in_progress",r.FINISHED="finished",r))(ll||{}),xO=(r=>(r.CONFIRMED="confirmed",r.EXITED="exited",r.PENDING="pending",r.REQUESTED="requested",r.SKIPPED="skipped",r.TIMED_OUT="timed_out",r))(xO||{}),Hu=(r=>(r.UJET="ujet_conversations",r.TWILIO="twilio_conversations",r.NEXMO="nexmo_conversations",r.MOCK="mock",r))(Hu||{}),yv=(r=>(r.INBOUND_CALL="inbound_call",r.VOICEMAIL="voicemail",r))(yv||{}),xr=(r=>(r.TEXT="text",r.NOTI="noti",r.SERVER_MESSAGE="server_message",r.TYPING="typing",r.PREVIEW="preview",r.TRANSLATION_UPDATE="translation_update",r))(xr||{}),mr=(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))(mr||{}),Jn=(r=>(r.END_USER="end_user",r.USER="user",r.VIRTUAL_AGENT="virtual_agent",r.SYSTEM="system",r))(Jn||{});function Qp(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:MO,setPrototypeOf:VC,isFrozen:y6,getPrototypeOf:_6,getOwnPropertyDescriptor:b6}=Object;let{freeze:Si,seal:Ss,create:Wb}=Object,{apply:Hb,construct:Vb}=typeof Reflect<"u"&&Reflect;Si||(Si=function(e){return e});Ss||(Ss=function(e){return e});Hb||(Hb=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)});Vb||(Vb=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 Mh=wi(Array.prototype.forEach),S6=wi(Array.prototype.lastIndexOf),GC=wi(Array.prototype.pop),id=wi(Array.prototype.push),w6=wi(Array.prototype.splice),Zp=wi(String.prototype.toLowerCase),Ry=wi(String.prototype.toString),Iy=wi(String.prototype.match),sd=wi(String.prototype.replace),T6=wi(String.prototype.indexOf),E6=wi(String.prototype.trim),js=wi(Object.prototype.hasOwnProperty),vi=wi(RegExp.prototype.test),ad=C6(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 Hb(r,e,n)}}function C6(r){return function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return Vb(r,t)}}function or(r,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Zp;VC&&VC(r,null);let n=e.length;for(;n--;){let i=e[n];if(typeof i=="string"){const s=t(i);s!==i&&(y6(e)||(e[n]=s),i=s)}r[i]=!0}return r}function k6(r){for(let e=0;e<r.length;e++)js(r,e)||(r[e]=null);return r}function la(r){const e=Wb(null);for(const[t,n]of MO(r))js(r,t)&&(Array.isArray(n)?e[t]=k6(n):n&&typeof n=="object"&&n.constructor===Object?e[t]=la(n):e[t]=n);return e}function od(r,e){for(;r!==null;){const n=b6(r,e);if(n){if(n.get)return wi(n.get);if(typeof n.value=="function")return wi(n.value)}r=_6(r)}function t(){return null}return t}const zC=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"]),Py=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"]),Ay=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"]),R6=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"]),Oy=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"]),I6=Si(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),KC=Si(["#text"]),JC=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"]),$y=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"]),YC=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"]),Dh=Si(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),P6=Ss(/\{\{[\w\W]*|[\w\W]*\}\}/gm),A6=Ss(/<%[\w\W]*|[\w\W]*%>/gm),O6=Ss(/\$\{[\w\W]*/gm),$6=Ss(/^data-[\-\w.\u00B7-\uFFFF]+$/),x6=Ss(/^aria-[\-\w]+$/),DO=Ss(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),M6=Ss(/^(?:\w+script|data):/i),D6=Ss(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),NO=Ss(/^html$/i),N6=Ss(/^[a-z][.\w]*(-[.\w]+)+$/i);var XC=Object.freeze({__proto__:null,ARIA_ATTR:x6,ATTR_WHITESPACE:D6,CUSTOM_ELEMENT:N6,DATA_ATTR:$6,DOCTYPE_NAME:NO,ERB_EXPR:A6,IS_ALLOWED_URI:DO,IS_SCRIPT_OR_DATA:M6,MUSTACHE_EXPR:P6,TMPLIT_EXPR:O6});const ud={element:1,text:3,progressingInstruction:7,comment:8,document:9},L6=function(){return typeof window>"u"?null:window},F6=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}},QC=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function LO(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:L6();const e=vt=>LO(vt);if(e.version="3.3.1",e.removed=[],!r||!r.document||r.document.nodeType!==ud.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:p,trustedTypes:y}=r,w=o.prototype,k=od(w,"cloneNode"),P=od(w,"remove"),A=od(w,"nextSibling"),B=od(w,"childNodes"),L=od(w,"parentNode");if(typeof a=="function"){const vt=t.createElement("template");vt.content&&vt.content.ownerDocument&&(t=vt.content.ownerDocument)}let $,F="";const{implementation:G,createNodeIterator:K,createDocumentFragment:D,getElementsByTagName:he}=t,{importNode:X}=n;let ve=QC();e.isSupported=typeof MO=="function"&&typeof L=="function"&&G&&G.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:Q,ERB_EXPR:Oe,TMPLIT_EXPR:He,DATA_ATTR:Ze,ARIA_ATTR:Xe,IS_SCRIPT_OR_DATA:Re,ATTR_WHITESPACE:Je,CUSTOM_ELEMENT:Ke}=XC;let{IS_ALLOWED_URI:Y}=XC,Ee=null;const Ct=or({},[...zC,...Py,...Ay,...Oy,...KC]);let Nt=null;const Et=or({},[...JC,...$y,...YC,...Dh]);let wt=Object.seal(Wb(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(Wb(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,Ue=!1,vr=!1,er=!1,Lr=!1,dr=!0,tn=!1;const yn="user-content-";let hn=!0,Kt=!1,Ht={},kt=null;const yt=or({},["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 nn=or({},["audio","video","img","source","image","track"]);let Qr=null;const Mn=or({},["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",sr="http://www.w3.org/1999/xhtml";let Fr=sr,ke=!1,Pe=null;const _e=or({},[kn,Rn,sr],Ry);let we=or({},["mi","mo","mn","ms","mtext"]),de=or({},["annotation-xml"]);const xe=or({},["title","style","font","a","script"]);let Le=null;const pe=["application/xhtml+xml","text/html"],be="text/html";let se=null,ge=null;const ue=t.createElement("form"),Qe=function(ce){return ce instanceof RegExp||ce instanceof Function},Me=function(){let ce=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(ge&&ge===ce)){if((!ce||typeof ce!="object")&&(ce={}),ce=la(ce),Le=pe.indexOf(ce.PARSER_MEDIA_TYPE)===-1?be:ce.PARSER_MEDIA_TYPE,se=Le==="application/xhtml+xml"?Ry:Zp,Ee=js(ce,"ALLOWED_TAGS")?or({},ce.ALLOWED_TAGS,se):Ct,Nt=js(ce,"ALLOWED_ATTR")?or({},ce.ALLOWED_ATTR,se):Et,Pe=js(ce,"ALLOWED_NAMESPACES")?or({},ce.ALLOWED_NAMESPACES,Ry):_e,Qr=js(ce,"ADD_URI_SAFE_ATTR")?or(la(Mn),ce.ADD_URI_SAFE_ATTR,se):Mn,Xt=js(ce,"ADD_DATA_URI_TAGS")?or(la(nn),ce.ADD_DATA_URI_TAGS,se):nn,kt=js(ce,"FORBID_CONTENTS")?or({},ce.FORBID_CONTENTS,se):yt,te=js(ce,"FORBID_TAGS")?or({},ce.FORBID_TAGS,se):la({}),ne=js(ce,"FORBID_ATTR")?or({},ce.FORBID_ATTR,se):la({}),Ht=js(ce,"USE_PROFILES")?ce.USE_PROFILES:!1,It=ce.ALLOW_ARIA_ATTR!==!1,Zt=ce.ALLOW_DATA_ATTR!==!1,rt=ce.ALLOW_UNKNOWN_PROTOCOLS||!1,cn=ce.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Ot=ce.SAFE_FOR_TEMPLATES||!1,$e=ce.SAFE_FOR_XML!==!1,_t=ce.WHOLE_DOCUMENT||!1,vr=ce.RETURN_DOM||!1,er=ce.RETURN_DOM_FRAGMENT||!1,Lr=ce.RETURN_TRUSTED_TYPE||!1,Ue=ce.FORCE_BODY||!1,dr=ce.SANITIZE_DOM!==!1,tn=ce.SANITIZE_NAMED_PROPS||!1,hn=ce.KEEP_CONTENT!==!1,Kt=ce.IN_PLACE||!1,Y=ce.ALLOWED_URI_REGEXP||DO,Fr=ce.NAMESPACE||sr,we=ce.MATHML_TEXT_INTEGRATION_POINTS||we,de=ce.HTML_INTEGRATION_POINTS||de,wt=ce.CUSTOM_ELEMENT_HANDLING||{},ce.CUSTOM_ELEMENT_HANDLING&&Qe(ce.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(wt.tagNameCheck=ce.CUSTOM_ELEMENT_HANDLING.tagNameCheck),ce.CUSTOM_ELEMENT_HANDLING&&Qe(ce.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(wt.attributeNameCheck=ce.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),ce.CUSTOM_ELEMENT_HANDLING&&typeof ce.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(wt.allowCustomizedBuiltInElements=ce.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Ot&&(Zt=!1),er&&(vr=!0),Ht&&(Ee=or({},KC),Nt=[],Ht.html===!0&&(or(Ee,zC),or(Nt,JC)),Ht.svg===!0&&(or(Ee,Py),or(Nt,$y),or(Nt,Dh)),Ht.svgFilters===!0&&(or(Ee,Ay),or(Nt,$y),or(Nt,Dh)),Ht.mathMl===!0&&(or(Ee,Oy),or(Nt,YC),or(Nt,Dh))),ce.ADD_TAGS&&(typeof ce.ADD_TAGS=="function"?ut.tagCheck=ce.ADD_TAGS:(Ee===Ct&&(Ee=la(Ee)),or(Ee,ce.ADD_TAGS,se))),ce.ADD_ATTR&&(typeof ce.ADD_ATTR=="function"?ut.attributeCheck=ce.ADD_ATTR:(Nt===Et&&(Nt=la(Nt)),or(Nt,ce.ADD_ATTR,se))),ce.ADD_URI_SAFE_ATTR&&or(Qr,ce.ADD_URI_SAFE_ATTR,se),ce.FORBID_CONTENTS&&(kt===yt&&(kt=la(kt)),or(kt,ce.FORBID_CONTENTS,se)),ce.ADD_FORBID_CONTENTS&&(kt===yt&&(kt=la(kt)),or(kt,ce.ADD_FORBID_CONTENTS,se)),hn&&(Ee["#text"]=!0),_t&&or(Ee,["html","head","body"]),Ee.table&&(or(Ee,["tbody"]),delete te.tbody),ce.TRUSTED_TYPES_POLICY){if(typeof ce.TRUSTED_TYPES_POLICY.createHTML!="function")throw ad('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof ce.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw ad('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');$=ce.TRUSTED_TYPES_POLICY,F=$.createHTML("")}else $===void 0&&($=F6(y,i)),$!==null&&typeof F=="string"&&(F=$.createHTML(""));Si&&Si(ce),ge=ce}},ot=or({},[...Py,...Ay,...R6]),tt=or({},[...Oy,...I6]),it=function(ce){let je=L(ce);(!je||!je.tagName)&&(je={namespaceURI:Fr,tagName:"template"});const st=Zp(ce.tagName),Jt=Zp(je.tagName);return Pe[ce.namespaceURI]?ce.namespaceURI===Rn?je.namespaceURI===sr?st==="svg":je.namespaceURI===kn?st==="svg"&&(Jt==="annotation-xml"||we[Jt]):!!ot[st]:ce.namespaceURI===kn?je.namespaceURI===sr?st==="math":je.namespaceURI===Rn?st==="math"&&de[Jt]:!!tt[st]:ce.namespaceURI===sr?je.namespaceURI===Rn&&!de[Jt]||je.namespaceURI===kn&&!we[Jt]?!1:!tt[st]&&(xe[st]||!ot[st]):!!(Le==="application/xhtml+xml"&&Pe[ce.namespaceURI]):!1},at=function(ce){id(e.removed,{element:ce});try{L(ce).removeChild(ce)}catch{P(ce)}},ht=function(ce,je){try{id(e.removed,{attribute:je.getAttributeNode(ce),from:je})}catch{id(e.removed,{attribute:null,from:je})}if(je.removeAttribute(ce),ce==="is")if(vr||er)try{at(je)}catch{}else try{je.setAttribute(ce,"")}catch{}},jt=function(ce){let je=null,st=null;if(Ue)ce="<remove></remove>"+ce;else{const Ar=Iy(ce,/^[\r\n\t ]+/);st=Ar&&Ar[0]}Le==="application/xhtml+xml"&&Fr===sr&&(ce='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+ce+"</body></html>");const Jt=$?$.createHTML(ce):ce;if(Fr===sr)try{je=new p().parseFromString(Jt,Le)}catch{}if(!je||!je.documentElement){je=G.createDocument(Fr,"template",null);try{je.documentElement.innerHTML=ke?F:Jt}catch{}}const ur=je.body||je.documentElement;return ce&&st&&ur.insertBefore(t.createTextNode(st),ur.childNodes[0]||null),Fr===sr?he.call(je,_t?"html":"body")[0]:_t?je.documentElement:ur},pt=function(ce){return K.call(ce.ownerDocument||ce,ce,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},bt=function(ce){return ce instanceof h&&(typeof ce.nodeName!="string"||typeof ce.textContent!="string"||typeof ce.removeChild!="function"||!(ce.attributes instanceof d)||typeof ce.removeAttribute!="function"||typeof ce.setAttribute!="function"||typeof ce.namespaceURI!="string"||typeof ce.insertBefore!="function"||typeof ce.hasChildNodes!="function")},Pt=function(ce){return typeof c=="function"&&ce instanceof c};function Ur(vt,ce,je){Mh(vt,st=>{st.call(e,ce,je,ge)})}const ln=function(ce){let je=null;if(Ur(ve.beforeSanitizeElements,ce,null),bt(ce))return at(ce),!0;const st=se(ce.nodeName);if(Ur(ve.uponSanitizeElement,ce,{tagName:st,allowedTags:Ee}),$e&&ce.hasChildNodes()&&!Pt(ce.firstElementChild)&&vi(/<[/\w!]/g,ce.innerHTML)&&vi(/<[/\w!]/g,ce.textContent)||ce.nodeType===ud.progressingInstruction||$e&&ce.nodeType===ud.comment&&vi(/<[/\w]/g,ce.data))return at(ce),!0;if(!(ut.tagCheck instanceof Function&&ut.tagCheck(st))&&(!Ee[st]||te[st])){if(!te[st]&&Dn(st)&&(wt.tagNameCheck instanceof RegExp&&vi(wt.tagNameCheck,st)||wt.tagNameCheck instanceof Function&&wt.tagNameCheck(st)))return!1;if(hn&&!kt[st]){const Jt=L(ce)||ce.parentNode,ur=B(ce)||ce.childNodes;if(ur&&Jt){const Ar=ur.length;for(let sn=Ar-1;sn>=0;--sn){const _n=k(ur[sn],!0);_n.__removalCount=(ce.__removalCount||0)+1,Jt.insertBefore(_n,A(ce))}}}return at(ce),!0}return ce instanceof o&&!it(ce)||(st==="noscript"||st==="noembed"||st==="noframes")&&vi(/<\/no(script|embed|frames)/i,ce.innerHTML)?(at(ce),!0):(Ot&&ce.nodeType===ud.text&&(je=ce.textContent,Mh([Q,Oe,He],Jt=>{je=sd(je,Jt," ")}),ce.textContent!==je&&(id(e.removed,{element:ce.cloneNode()}),ce.textContent=je)),Ur(ve.afterSanitizeElements,ce,null),!1)},qt=function(ce,je,st){if(dr&&(je==="id"||je==="name")&&(st in t||st in ue))return!1;if(!(Zt&&!ne[je]&&vi(Ze,je))){if(!(It&&vi(Xe,je))){if(!(ut.attributeCheck instanceof Function&&ut.attributeCheck(je,ce))){if(!Nt[je]||ne[je]){if(!(Dn(ce)&&(wt.tagNameCheck instanceof RegExp&&vi(wt.tagNameCheck,ce)||wt.tagNameCheck instanceof Function&&wt.tagNameCheck(ce))&&(wt.attributeNameCheck instanceof RegExp&&vi(wt.attributeNameCheck,je)||wt.attributeNameCheck instanceof Function&&wt.attributeNameCheck(je,ce))||je==="is"&&wt.allowCustomizedBuiltInElements&&(wt.tagNameCheck instanceof RegExp&&vi(wt.tagNameCheck,st)||wt.tagNameCheck instanceof Function&&wt.tagNameCheck(st))))return!1}else if(!Qr[je]){if(!vi(Y,sd(st,Je,""))){if(!((je==="src"||je==="xlink:href"||je==="href")&&ce!=="script"&&T6(st,"data:")===0&&Xt[ce])){if(!(rt&&!vi(Re,sd(st,Je,"")))){if(st)return!1}}}}}}}return!0},Dn=function(ce){return ce!=="annotation-xml"&&Iy(ce,Ke)},Ri=function(ce){Ur(ve.beforeSanitizeAttributes,ce,null);const{attributes:je}=ce;if(!je||bt(ce))return;const st={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Nt,forceKeepAttr:void 0};let Jt=je.length;for(;Jt--;){const ur=je[Jt],{name:Ar,namespaceURI:sn,value:_n}=ur,li=se(Ar),Ii=_n;let Gr=Ar==="value"?Ii:E6(Ii);if(st.attrName=li,st.attrValue=Gr,st.keepAttr=!0,st.forceKeepAttr=void 0,Ur(ve.uponSanitizeAttribute,ce,st),Gr=st.attrValue,tn&&(li==="id"||li==="name")&&(ht(Ar,ce),Gr=yn+Gr),$e&&vi(/((--!?|])>)|<\/(style|title|textarea)/i,Gr)){ht(Ar,ce);continue}if(li==="attributename"&&Iy(Gr,"href")){ht(Ar,ce);continue}if(st.forceKeepAttr)continue;if(!st.keepAttr){ht(Ar,ce);continue}if(!cn&&vi(/\/>/i,Gr)){ht(Ar,ce);continue}Ot&&Mh([Q,Oe,He],ea=>{Gr=sd(Gr,ea," ")});const Zs=se(ce.nodeName);if(!qt(Zs,li,Gr)){ht(Ar,ce);continue}if($&&typeof y=="object"&&typeof y.getAttributeType=="function"&&!sn)switch(y.getAttributeType(Zs,li)){case"TrustedHTML":{Gr=$.createHTML(Gr);break}case"TrustedScriptURL":{Gr=$.createScriptURL(Gr);break}}if(Gr!==Ii)try{sn?ce.setAttributeNS(sn,Ar,Gr):ce.setAttribute(Ar,Gr),bt(ce)?at(ce):GC(e.removed)}catch{ht(Ar,ce)}}Ur(ve.afterSanitizeAttributes,ce,null)},Bn=function vt(ce){let je=null;const st=pt(ce);for(Ur(ve.beforeSanitizeShadowDOM,ce,null);je=st.nextNode();)Ur(ve.uponSanitizeShadowNode,je,null),ln(je),Ri(je),je.content instanceof s&&vt(je.content);Ur(ve.afterSanitizeShadowDOM,ce,null)};return e.sanitize=function(vt){let ce=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},je=null,st=null,Jt=null,ur=null;if(ke=!vt,ke&&(vt="<!-->"),typeof vt!="string"&&!Pt(vt))if(typeof vt.toString=="function"){if(vt=vt.toString(),typeof vt!="string")throw ad("dirty is not a string, aborting")}else throw ad("toString is not a function");if(!e.isSupported)return vt;if(zt||Me(ce),e.removed=[],typeof vt=="string"&&(Kt=!1),Kt){if(vt.nodeName){const _n=se(vt.nodeName);if(!Ee[_n]||te[_n])throw ad("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===ud.element&&st.nodeName==="BODY"||st.nodeName==="HTML"?je=st:je.appendChild(st);else{if(!vr&&!Ot&&!_t&&vt.indexOf("<")===-1)return $&&Lr?$.createHTML(vt):vt;if(je=jt(vt),!je)return vr?null:Lr?F:""}je&&Ue&&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(vr){if(er)for(ur=D.call(je.ownerDocument);je.firstChild;)ur.appendChild(je.firstChild);else ur=je;return(Nt.shadowroot||Nt.shadowrootmode)&&(ur=X.call(n,ur,!0)),ur}let sn=_t?je.outerHTML:je.innerHTML;return _t&&Ee["!doctype"]&&je.ownerDocument&&je.ownerDocument.doctype&&je.ownerDocument.doctype.name&&vi(NO,je.ownerDocument.doctype.name)&&(sn="<!DOCTYPE "+je.ownerDocument.doctype.name+`>
2
- `+sn),Ot&&Mh([Q,Oe,He],_n=>{sn=sd(sn,_n," ")}),$&&Lr?$.createHTML(sn):sn},e.setConfig=function(){let vt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Me(vt),zt=!0},e.clearConfig=function(){ge=null,zt=!1},e.isValidAttribute=function(vt,ce,je){ge||Me({});const st=se(vt),Jt=se(ce);return qt(st,Jt,je)},e.addHook=function(vt,ce){typeof ce=="function"&&id(ve[vt],ce)},e.removeHook=function(vt,ce){if(ce!==void 0){const je=S6(ve[vt],ce);return je===-1?void 0:w6(ve[vt],je,1)[0]}return GC(ve[vt])},e.removeHooks=function(vt){ve[vt]=[]},e.removeAllHooks=function(){ve=QC()},e}var FO=LO();const Gb={ALLOWED_TAGS:["b","i","em","strong","p","br","ul","ol","li","a"],ALLOWED_ATTR:["href","alt","title","target","class","id"],ALLOW_DATA_ATTR:!1,FORBID_TAGS:["img","iframe","object","input","style","script","embed","svg","video","audio","body","form","link"],FORBID_ATTR:["onerror","onclick","onload","onmouseover","onfocus","onblur","onchange","onsubmit","src","href","style","action","value"],IN_PLACE:!0},U6={...Gb,FORBID_ATTR:Gb.FORBID_ATTR.filter(r=>r!=="href"),ALLOWED_URI_REGEXP:/^(?:https|mailto|tel):/i},UO="javascript:";var Lu;let Fu=(Lu=class extends Error{constructor(t,n,i){super(t);oe(this,"code",Lu.CODE);oe(this,"refusedBy");this.name="UnauthorizedError",this.refusedBy=n,i&&"cause"in i&&(this.cause=i.cause)}},oe(Lu,"CODE","UNAUTHORIZED"),Lu);function j6(r){return(r==null?void 0:r.constructor)===Object}async function ZC(r,e=3){let t=0,n;for(;t<=e;){t+=1;try{return await r()}catch(i){if(i instanceof Fu)throw i;n=i,console.error(i),await tf(1e3*Math.pow(2,t))}}throw n}function tf(r){return new Promise(e=>{setTimeout(()=>{e(0)},r)})}function Vw(){return Math.random().toString(36).slice(2)}const B6=new TextDecoder,jO=r=>{const e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return B6.decode(t)},q6=r=>jO(r.replace(/-/g,"+").replace(/_/g,"/")),W6=r=>r.length===0,H6=(...r)=>r.every(W6),Gw=r=>{const e=FO.sanitize(r,Gb);return e.includes(UO)?(console.warn("Suspicious content detected and removed."),""):e};let Nh;function V6(){return Nh||(Nh=FO(window),Nh.addHook("afterSanitizeAttributes",r=>{r.tagName==="A"&&r.hasAttribute("href")&&(r.setAttribute("target","_blank"),r.setAttribute("rel","noopener noreferrer"))})),Nh}const G6=r=>{const e=V6().sanitize(r,U6);return e.includes(UO)?(console.warn("Suspicious content detected and removed."),""):e},z6=[8,4,4,4,12],xy=()=>{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 z6.map(i=>{const s=t.slice(n,n+i);return n+=i,s}).join("-")},K6="prod",zw="6.39.1",ek="https://main.api.ujet.co",zn={companyId:"",tenant:"",trackerId:"",deviceId:"",application:"websdk",version:zw};class J6{constructor(e){oe(this,"buffer");oe(this,"writeIndex",0);oe(this,"size",0);oe(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){oe(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(Kw);Lo.logHandlers.forEach(i=>i(this.channel,e,...n)),Lo.logHistory.push({date:new Date().toISOString(),channel:this.channel,level:e,args:n})}};oe(Lo,"logHandlers",[]),oe(Lo,"logHistory",new J6(1e3));let Jr=Lo;const Y6=(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:Q6(n),message:Kw(t.join(" "))}},tk=["user","phone","phone_number","phoneNumber","email","token","access_token","accessToken","authorization","Authorization"],X6=[/(?: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 Kw(r){return Uc(r,new WeakSet)}function Uc(r,e){if(!r)return r;if(typeof r=="string")return X6.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"||(tk.indexOf(n)!==-1?t[n]="__MASKED__":t[n]=Uc(r[n],e));return t}return j6(r)&&(r={...r},Object.keys(r).forEach(t=>{tk.indexOf(t)!==-1?r[t]="__MASKED__":r[t]=Uc(r[t],e)})),r}function Q6(r){if(r.error){const e=r.error;return{error:{name:e.name,message:e.message,stack:e.stack}}}return Kw(r.data)}const Z6=new Jr("chat-provider"),qd="$superseded",BO="_sendReady",zb="_taskStateSignal";class ng{constructor(e,t,n,i){oe(this,"audio");oe(this,"issueChatToken");oe(this,"identity");oe(this,"channelId");oe(this,"region");oe(this,"inTask",!1);oe(this,"muted",!1);oe(this,"providerContext");oe(this,"events");this.events=e,this.region=t.region,this.audio=new m6,this.issueChatToken=n,this.providerContext=i}async reconnect(){}ping(){if(!this.muted)try{this.audio.playPing()}catch(e){Z6.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)}get tracksSends(){return!1}get canPublish(){return!1}publishTracked(e){return Promise.reject(new Error("this provider does not track sends"))}attachmentKeyOf(e){return""}trackInTask(e){if(e.type===xr.NOTI&&e.event===mr.TASK_VA_STARTED)this.inTask=!0;else if(e.type===xr.NOTI&&(e.event===mr.TASK_VA_FINISHED||e.event===mr.TASK_VA_FAILED))this.inTask=!1;else return;this.events.triggerEvent(zb)}}oe(ng,"type","base");const qO={};function ig(r){qO[r.type]=r}function eW(r){return qO[r]}const zv=class zv extends Error{constructor(t){super("Cannot send a message: the chat has already ended");oe(this,"code",zv.CODE);oe(this,"status");this.name="ChatEndedError",this.status=t}};oe(zv,"CODE","CHAT_ENDED");let dl=zv;const rk=new Jr("MediaStore"),tW=window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB||window.OIndexedDB||window.msIndexedDB,rW="chat-media",nk=1,_v="file";class WO{constructor(){oe(this,"db")}store(){return new Promise((e,t)=>{if(this.db)return e(ik(this.db));const n=tW.open(rW,nk);n.onerror=()=>{t(new Error("indexedDB open failed"))},n.onsuccess=()=>{const i=n.result;this.db=i,e(ik(i))},n.onupgradeneeded=i=>{const s=n.result;i.oldVersion>0&&i.oldVersion<nk&&(rk.info("deprecating media store"),s.deleteObjectStore(_v)),rk.info("creating media store"),s.createObjectStore(_v)}})}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 ik(r){return r.transaction(_v,"readwrite").objectStore(_v)}const nW=new Jr("EventManager");class sg{constructor(){oe(this,"handlers",{})}addEventListener(e,t){this.handlers[e]||(this.handlers[e]=[]),this.handlers[e].push(t)}triggerEvent(e,t){nW.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 iW(r,e){const t={};return e.forEach(n=>{t[n.id]=n}),r.map(n=>{if(n.type===xr.SERVER_MESSAGE){const i=n.server_message_id??n.message_id,s=t[i];HO(n,s.content)}return n})}function sW(r,e){return HO(r,e.content)}function HO(r,e){return Object.keys(e).forEach(t=>{r[t]=e[t]}),r}const sk={photo:2,video:2,audio:1,document:1};function aW(r){return r.toSorted((e,t)=>!e.groupMessageId||!t.groupMessageId||e.groupMessageId!==t.groupMessageId?0:(sk[t.type]||0)-(sk[e.type]||0))}function oW(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 uW(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=oW(n.url)))}})}const VO="chat-5565-surface-subscription-end",cW="chat-5580-nonblocking-history-hint",lW="chat-5566-history-recovery-job",dW="chat-5862-emulated-authorization-header",ak=new Jr("Outbox"),fW=45e3,hW=1e3,pW=1,vW=2,gW=3,mW=4,yW=7,_W=10,bW=11,SW=409;function wW(r){return(r==null?void 0:r.code)===SW}function GO(r,e=new WeakSet){if(r!==null&&typeof r=="object"&&!e.has(r)){e.add(r),Object.freeze(r);for(const t of Object.values(r))GO(t,e)}return r}function TW(r){if(r instanceof dl)return{reason:"chat_ended",retryable:!1};const{code:e,temporary:t}=r??{};switch(e){case pW:return{reason:"timeout",retryable:!0};case vW:case _W:case bW:return{reason:"disconnected",retryable:!0};case gW:case mW:case yW:return{reason:"disconnected",retryable:!1};default:return{reason:"rejected",retryable:t===!0}}}const Lh=Symbol("skipped");class EW{constructor(e){oe(this,"slots",new Map);oe(this,"inFlight",null);oe(this,"handedOff",new Set);oe(this,"resumeTimer");oe(this,"windowMs");this.options=e,this.windowMs=e.windowMs??fW}enqueue(e,t){this.slots.has(e)||this.start({client_message_id:e,payload:GO(t),status:"sending",attempt:1,$timestamp:new Date})}confirm(e){const t=this.slots.get(e);return t?(this.finish(t,{...t.entry,status:"sent",error:void 0}),!0):!1}wasHandedOff(e){return this.handedOff.has(e)}retry(e){var n;const t=this.slots.get(e);return(t==null?void 0:t.entry.status)!=="failed"||((n=t.entry.error)==null?void 0:n.reason)==="chat_ended"?!1:(this.slots.delete(e),this.start({...t.entry,status:"sending",attempt:t.entry.attempt+1,$timestamp:new Date,error:void 0}),!0)}discard(e){const t=this.slots.get(e);return(t==null?void 0:t.entry.status)!=="failed"?!1:(this.finish(t,{...t.entry,status:"discarded"}),!0)}resume(){clearTimeout(this.resumeTimer),this.resumeTimer=void 0;let e=!1;for(const t of this.slots.values())t.waiting&&Date.now()>=t.deadline?(this.failExpired(t),e=!0):t.waiting&&(t.waiting=!1,t.entry={...t.entry,attempt:t.entry.attempt+1,error:void 0},this.notify(t.entry),e=!0);e&&this.pump()}failAll(e){for(const t of this.slots.values())t.entry.status==="sending"&&this.fail(t,{reason:e,retryable:!1})}release(){var t;clearTimeout(this.resumeTimer),this.resumeTimer=void 0;const e=(t=this.inFlight)!=null&&t.onWire?this.inFlight:null;for(const n of[...this.slots.values()])n.entry.status==="sending"&&(clearTimeout(n.timer),this.slots.delete(n.entry.client_message_id),this.handedOff.delete(n.entry.client_message_id),n!==e&&this.options.send(n.entry).catch(()=>{}),this.notify({...n.entry,status:"sent",error:void 0}))}snapshot(){return Object.freeze([...this.slots.values()].map(({entry:e})=>Object.freeze({...e,$timestamp:new Date(e.$timestamp),error:e.error&&Object.freeze({...e.error})})))}destroy(){for(const e of this.slots.values())clearTimeout(e.timer);clearTimeout(this.resumeTimer),this.resumeTimer=void 0,this.slots.clear(),this.handedOff.clear(),this.inFlight=null}start(e){const t={entry:e,deadline:Date.now()+this.windowMs,timer:void 0,waiting:!1,onWire:!1};t.timer=setTimeout(()=>this.expire(t),this.windowMs),this.slots.set(e.client_message_id,t),this.notify(e),this.pump()}isCurrent(e){return this.slots.get(e.entry.client_message_id)===e&&e.entry.status==="sending"}pump(){const e=this.nextToSend();e&&(this.inFlight=e,Promise.resolve().then(()=>this.isCurrent(e)?(e.onWire=!0,this.handedOff.add(e.entry.client_message_id),this.options.send(e.entry)):Lh).then(t=>this.settle(e,t===Lh?Lh:null),t=>this.settle(e,t)))}nextToSend(){for(;;){if(this.inFlight)return;const e=[...this.slots.values()].find(t=>t.entry.status==="sending");if(!e||e.waiting)return;if(Date.now()<e.deadline)return e;this.failExpired(e)}}settle(e,t){if(e.onWire=!1,this.inFlight===e&&(this.inFlight=null),t===Lh||!this.isCurrent(e)){this.pump();return}if(t===null||wW(t))this.finish(e,{...e.entry,status:"sent",error:void 0});else{const n=TW(t);!n.retryable||Date.now()>=e.deadline?this.fail(e,n):(e.entry={...e.entry,error:n},e.waiting=!0,this.notify(e.entry),this.options.isReady()&&this.scheduleResume())}this.pump()}scheduleResume(){this.resumeTimer===void 0&&(this.resumeTimer=setTimeout(()=>{this.resumeTimer=void 0,this.resume()},hW))}expire(e){e.timer=void 0,!(e.entry.status!=="sending"||this.inFlight===e)&&(this.failExpired(e),this.pump())}failExpired(e){this.fail(e,e.entry.error??{reason:"timeout",retryable:!0})}fail(e,t){clearTimeout(e.timer),e.timer=void 0,e.waiting=!1,e.entry={...e.entry,status:"failed",error:{...t,retryable:!1}},ak.warn("send failed",{data:{client_message_id:e.entry.client_message_id,reason:t.reason,attempt:e.entry.attempt}}),this.notify(e.entry)}notify(e){try{this.options.onChange(e)}catch(t){ak.warn("status listener threw",{data:{client_message_id:e.client_message_id,error:t}})}}finish(e,t){clearTimeout(e.timer),this.slots.delete(t.client_message_id),this.handedOff.delete(t.client_message_id),this.notify(t),this.pump()}}const Fh=new Jr("chat-originals"),CW="web-4258-local-original-cache",kW=1e3,RW=4,ok=1e4,IW=100;function uk(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}class PW{constructor(){oe(this,"byClientMessageId",new Map);oe(this,"byRedactionRef",new Map);oe(this,"inFlight",new Map);oe(this,"queue",[]);oe(this,"active",0);oe(this,"generation",0)}get currentGeneration(){return this.generation}remember(e,t){!e||!t||My(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?My(this.byRedactionRef,e,null):Fh.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"?(Fh.warn("original lookup returned an unusable payload",{redactionRef:t}),null):(My(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<RW?n():this.queue.length>=IW?(Fh.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),Fh.info("original lookup gave up waiting for a slot"),i(null)},ok);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"}))},ok);e.then(s=>{clearTimeout(i),t(s)},s=>{clearTimeout(i),n(s)})})}}function My(r,e,t){r.delete(e),r.set(e,t),r.size>kW&&r.delete(r.keys().next().value)}const zO=["assigned","va_assigned"],KO=["dismissed","va_dismissed"],AW=["va_assigned","va_dismissed"],OW=["queued","check_in_timeout",...zO,...KO],$W=["timeout","canceled","failed","finished"],xW=new Jr("task-state-resync"),MW=6e4;function DW(r){return r instanceof Error?{error:r}:{data:{status:r==null?void 0:r.status}}}class NW{constructor(e,t,n,i,s,a=MW){oe(this,"seq",0);oe(this,"inFlight",!1);oe(this,"dirty",!1);oe(this,"owed",!1);oe(this,"timer",null);oe(this,"stopped",!1);this.fetchActive=e,this.apply=t,this.isInTask=n,this.isEnabled=i,this.isLive=s,this.pollMs=a}signal(){this.stopped||(this.seq+=1,this.isEnabled()&&(this.owed=!0),this.inFlight?this.dirty=!0:this.canApply()&&this.run(),this.syncPoll())}stop(){this.stopped=!0,this.clearTimer()}canApply(){return this.isEnabled()&&this.isLive()}async run(){this.inFlight=!0;try{do{this.dirty=!1;const e=this.seq;let t,n=!1;try{t=await this.fetchActive()}catch(i){n=!0,xW.warn("task state read failed",DW(i))}if(this.stopped)return;e!==this.seq?this.dirty=!0:!n&&this.canApply()&&(typeof t=="boolean"&&this.apply(t),this.owed=!1)}while(this.dirty&&this.canApply())}finally{this.inFlight=!1,this.syncPoll()}}shouldPoll(){return!this.stopped&&this.isLive()&&(this.isInTask()||this.owed)}syncPoll(){if(!this.shouldPoll()){this.clearTimer();return}this.timer||(this.timer=setInterval(()=>this.tick(),this.pollMs))}tick(){if(!this.shouldPoll()){this.clearTimer();return}!this.isEnabled()||this.inFlight||this.run()}clearTimer(){this.timer&&(clearInterval(this.timer),this.timer=null)}}const Yi=new Jr("Chat"),LW=Symbol("owner-conflict"),Dy=1e3;function FW(r){return typeof WeakRef=="function"?new WeakRef(r):{deref:()=>r}}const UW="web-4206-media-pairing-guard",jW="chat-5362-send-retry",BW=1e4,qW="chat-5821-late-echo-pairing",WW="chat-5808-task-va-resync",HW=[mr.TASK_VA_STARTED,mr.TASK_VA_FINISHED,mr.TASK_VA_FAILED];function VW(r){return r.type===xr.NOTI&&!!r.event&&HW.includes(r.event)}const GW=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function ck(r){return typeof r=="string"&&GW.test(r)?r.toLowerCase():void 0}function Ny(r){return r==="photo"||r==="video"||r==="document"}function zW(r,e){const t={client_message_id:r.client_message_id,status:r.status,$timestamp:new Date(r.$timestamp),attempt:r.attempt,error:r.error&&Object.freeze({...r.error})};return Object.freeze(e?{...t,type:r.payload.type,file:e.file,media_id:typeof e.mediaId=="number"?e.mediaId:void 0}:{...t,type:"text",content:r.payload.content??""})}function lk(r,e){return r.type!==e.type?!1:e.type===xr.TEXT?r.content===e.content:e.media_id!=null&&r.media_id===e.media_id}const JO="web-4512-inbound-sanitize-paths",KW="web-4534-inbound-https-links";function YO(r){return r(KW)??!0?G6:Gw}function XO(r,e){typeof r.title=="string"&&(r.title=e(r.title))}function Kb(r,e){typeof r.content=="string"&&(r.content=e(r.content)),XO(r,e)}class JW{constructor(e,t,n={},i){oe(this,"provider");oe(this,"store");oe(this,"globalEvents");oe(this,"state");oe(this,"connected",!1);oe(this,"allowSkipVirtualAgent",!1);oe(this,"inEscalation",!1);oe(this,"events");oe(this,"cachedFiles");oe(this,"hooks");oe(this,"originals",new PW);oe(this,"cacheOwner",null);oe(this,"restoredMessages",new Map);oe(this,"nextTrackedSweepAt",Dy);oe(this,"destroying",!1);oe(this,"leaveSent",!1);oe(this,"beaconAttempted",!1);oe(this,"connecting",!1);oe(this,"connectEnd","none");oe(this,"outbox",null);oe(this,"sendTrackingReleased",!1);oe(this,"newestSid");oe(this,"sendFloors",new Map);oe(this,"sentAwaitingEcho",new Map);oe(this,"pairedEchoIds",new Map);oe(this,"sentFiles",new Map);oe(this,"taskStateResync",null);oe(this,"onTaskStateSignal",()=>{var e;(e=this.taskStateResync)==null||e.signal()});this.state=e,this.store=new WO,this.cachedFiles={},this.events=new sg,this.hooks=n;const s=eW(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;const i=this.inboundSanitizer();n.content=i(n.content),this.sanitizesInboundPaths()&&XO(n,i),this.noteSid(n);const s=n[qd]===!0;if(delete n[qd],this.syncCacheOwner(),n.type===xr.SERVER_MESSAGE){const a=n.server_message_id??n.message_id;t(this.id,a).then(c=>{this.destroying||(n=sW(n,c),this.sanitizesInboundPaths()&&Kb(n,i),e.triggerEvent("chat.message",n))})}else if(Ny(n.type))this.settleOwnEcho(n),this.pairSentFile(n),setTimeout(()=>{if(this.destroying)return;const a=n.$index.toString();n.file=this.cachedFiles[a],e.triggerEvent("chat.message",n)},100);else{this.settleOwnEcho(n);const a=this.restoreOwnOriginal(n);e.triggerEvent("chat.message",n),s||this.registerMessageEvents(n),a&&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=>{Yi.warn("Chat connection ended",{error:n}),this.handleConnectionEnded()}),this.on(BO,()=>{var n;(n=this.outbox)==null||n.resume()})}handleConnectionEnded(){this.connecting&&this.connectEnd==="none"&&this.surfacesSubscriptionEnd()&&(this.connectEnd=this.connected?"done":"pending"),this.connected&&this.endConnection()}endConnection(){var e;this.connected=!1,this._stopTaskStateResync(),(e=this.outbox)==null||e.failAll("disconnected"),this.triggerEvent("connectionEnded",this),this.triggerEvent("disconnected",this),this.provider&&this.provider.destroy().catch(t=>Yi.warn("provider destroy failed",{error:t}))}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 AW.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===Jn.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 OW.indexOf(this.status)!=-1}get assigned(){return zO.indexOf(this.status)!=-1}get dismissed(){return KO.indexOf(this.status)!=-1}get ended(){return $W.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===ll.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){var i;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(),this.ended&&((i=this.outbox)==null||i.failAll("chat_ended")),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(){var e;if(!this.provider)return Yi.info("connecting interrupted"),!1;this.connecting=!0,this.connectEnd="none",this.startTaskStateResync();try{if(await ZC(()=>this.provider.create(),3),await ZC(()=>this.connectEnd!=="none"?Promise.resolve():this.provider.join(this.state.provider_channel_id),3),this.settleEndedConnect())return Yi.info("connect abandoned: connection ended before it was announced"),!1;this.syncCacheOwner(),this.connected=!0;const t=await this.fetchMessages();if(this.destroying)return Yi.info("connect abandoned: chat destroyed while loading history"),!1;if(this.settleEndedConnect())return Yi.info("connect abandoned: connection ended while loading history"),!1;this.inTask&&((e=this.taskStateResync)==null||e.signal());const n={chat:this,messages:t};return this.triggerEvent("connectedMessages",n),this.triggerEvent("connected",this),this.registerProviderEvents(),Yi.info("connected with provider",this.state.provider_type),!0}catch(t){return this.settleEndedConnect(),Yi.error("Failed to connect with provider",t),!1}finally{this.connecting=!1}}async disconnect(){var e;this.connected=!1,this._stopTaskStateResync(),(e=this.outbox)==null||e.failAll("disconnected"),this.triggerEvent("disconnected",this),await this.sendLeave(),this.events.destroy(),this.provider&&(await this.provider.destroy(),Yi.info("disconnect with provider",this.state.provider_type))}async sendLeave(){var e;if(!this.leaveSent&&((e=this.state)==null?void 0:e.provider_type)===Hu.UJET&&this.hooks.leaveChat)try{await this.hooks.leaveChat(),this.leaveSent=!0}catch(t){Yi.warn("leaveChat failed",{error:t})}}leaveBeacon(){var e;this.leaveSent||this.beaconAttempted||((e=this.state)==null?void 0:e.provider_type)===Hu.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 dl(this.status);const n=await this.provider.sendMessage(e),i=((a=(s=this.hooks).isRiskFlagEnabled)==null?void 0:a.call(s,UW))??!0;return t&&(!i||n!=null&&n!=="")&&this.saveMedia(n,t),typeof n=="number"?n:-1}get tracksSends(){var e,t,n;return!this.destroying&&!this.sendTrackingReleased&&(((e=this.provider)==null?void 0:e.tracksSends)??!1)&&(((n=(t=this.hooks).isRiskFlagEnabled)==null?void 0:n.call(t,jW))??!0)}get outgoingMessages(){var e;return Object.freeze((((e=this.outbox)==null?void 0:e.snapshot())??[]).map(t=>this.statusOf(t)))}enqueueMessage(e,t,n){if(this.ended)throw new dl(this.status);this.outbox??(this.outbox=new EW({send:i=>this.provider?this.provider.publishTracked(i.payload):Promise.reject(new Error("chat destroyed")),onChange:i=>{const s=this.statusOf(i);i.status==="sent"?(this.awaitEcho(i.client_message_id,i.payload),this.saveSentFile(i)):i.status==="discarded"&&this.sendFloors.delete(i.client_message_id),i.status==="discarded"&&this.sentFiles.delete(i.client_message_id),this.triggerEvent("messageSendStatusChanged",s)},isReady:()=>{var i;return((i=this.provider)==null?void 0:i.canPublish)??!1}})),this.sendFloors.has(e)||this.sendFloors.set(e,this.newestSid),n&&!this.sentFiles.has(e)&&this.sentFiles.set(e,{file:n,type:t.type,mediaId:t.media_id}),this.outbox.enqueue(e,{...t,client_message_id:e})}saveSentFile(e){var i;const t=this.sentFiles.get(e.client_message_id),n=t&&((i=this.provider)==null?void 0:i.attachmentKeyOf(e.payload));t&&n!=null&&n!==""&&this.cachedFiles[n.toString()]!==t.file&&this.saveMedia(n,t.file)}statusOf(e){return zW(e,this.sentFiles.get(e.client_message_id))}pairSentFile(e){const t=e.client_message_id?this.sentFiles.get(e.client_message_id):this.sentFileByMediaId(e);if(!t)return;const n=e.$index;return n!=null&&n!==""&&this.cachedFiles[n.toString()]!==t.file&&this.saveMedia(n,t.file),t.file}sentFileByMediaId(e){if(!(e.media_id==null||e.$userType!==Jn.END_USER||e.$userId!==this.ownUserId)){for(const t of this.sentFiles.values())if(t.type===e.type&&t.mediaId===e.media_id)return t}}retryMessage(e){return this.ended||!this.outbox?!1:this.outbox.retry(e)}discardMessage(e){var t;return((t=this.outbox)==null?void 0:t.discard(e))??!1}settleOwnEcho(e){const t=this.outbox;if(!t)return;if(e.client_message_id){t.confirm(e.client_message_id),this.forgetSent(e.client_message_id);return}if(e.type!==xr.TEXT&&!Ny(e.type)||e.$userType!==Jn.END_USER||e.$userId!==this.ownUserId)return;const n=e.$sid!=null?this.pairedEchoIds.get(String(e.$sid)):void 0;if(n){e.client_message_id=n;return}if(this.pairLateEcho(e))return;const i=t.snapshot().find(s=>lk(s.payload,e)&&t.wasHandedOff(s.client_message_id)&&this.isAfterSend(s.client_message_id,e));i&&(Yi.warn("outbox released: own echo without client_message_id",{data:{sid:e.$sid}}),this.givePairedId(e,i.client_message_id),t.confirm(i.client_message_id),this.forgetSent(i.client_message_id),this.sendTrackingReleased=!0,t.release())}pairLateEcho(e){var n;const t=(n=[...this.sentAwaitingEcho].find(([i,s])=>lk(s.payload,e)&&this.isAfterSend(i,e)))==null?void 0:n[0];return t?(this.givePairedId(e,t),this.forgetSent(t),!0):!1}givePairedId(e,t){e.client_message_id=t,e.$sid!=null&&e.$sid!==""&&this.pairedEchoIds.set(String(e.$sid),t)}awaitEcho(e,t){var n,i,s;if(!(((i=(n=this.hooks).isRiskFlagEnabled)==null?void 0:i.call(n,qW))??!0)){this.forgetSent(e);return}clearTimeout((s=this.sentAwaitingEcho.get(e))==null?void 0:s.timer),this.sentAwaitingEcho.set(e,{payload:t,timer:setTimeout(()=>this.forgetSent(e),BW)})}forgetSent(e){var t;clearTimeout((t=this.sentAwaitingEcho.get(e))==null?void 0:t.timer),this.sentAwaitingEcho.delete(e),this.sendFloors.delete(e)}isAfterSend(e,t){const n=this.sendFloors.get(e);if(n===void 0)return!0;const i=ck(t.$sid);return i!==void 0&&i>n}noteSid(e){const t=ck(e.$sid);t!==void 0&&(this.newestSid===void 0||t>this.newestSid)&&(this.newestSid=t)}preview(e){if(!this.inTask)return this.provider.preview(e)}async fetchMessages(){var e;if(this.connected){const t=await this.store.getAllFiles(),n=await this.provider.fetchMessages(t);if(this.destroying||!this.state||!this.provider)return[];const i=this.sanitizesInboundPaths(),s=this.inboundSanitizer();for(const c of n)delete c[qd],i&&Kb(c,s);return this.syncCacheOwner(),n.forEach(c=>{if(this.noteSid(c),this.settleOwnEcho(c),!c.file&&Ny(c.type)){const o=this.pairSentFile(c);o&&(c.file=o)}}),n.filter(c=>this.restoreOwnOriginal(c)).forEach(c=>this.lookupOwnOriginal(c)),n.some(VW)&&((e=this.taskStateResync)==null||e.signal()),n}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(LW),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=Dy,e.forEach(t=>{const n=t.deref();!n||n.unredacted===void 0||(delete n.unredacted,this.triggerEvent("messageUpdated",n))})}trackRestored(e){const t=FW(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(Dy,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,VO))??!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,CW))??!0}sanitizesInboundPaths(){var e,t;return((t=(e=this.hooks).isRiskFlagEnabled)==null?void 0:t.call(e,JO))??!0}inboundSanitizer(){return YO(e=>{var t,n;return(n=(t=this.hooks).isRiskFlagEnabled)==null?void 0:n.call(t,e)})}restoreOwnOriginal(e){if(this.destroying||e.$userType!==Jn.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(!uk(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?Gw(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||!uk(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=>{Yi.warn("original lookup failed",{error:c})})}startTyping(){return this.provider.startTyping()}stopTyping(){return this.provider.stopTyping()}saveMedia(e,t){this.cachedFiles[e.toString()]=t;const n=i=>Yi.warn(`media not saved: ${e}`,{error:i});try{Promise.resolve(this.store.save(e,t)).catch(n)}catch(i){n(i)}}async destroy(){var e;this.destroying=!0,this._stopTaskStateResync(),(e=this.outbox)==null||e.destroy(),this.outbox=null,this.sendFloors.clear(),this.sentAwaitingEcho.forEach(({timer:t})=>clearTimeout(t)),this.sentAwaitingEcho.clear(),this.pairedEchoIds.clear(),this.sentFiles.clear(),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()}startTaskStateResync(){var t;(t=this.taskStateResync)==null||t.stop(),this.taskStateResync=null;const e=this.hooks.fetchTaskVaActive;e&&(this.taskStateResync=new NW(e,n=>{this.provider&&(this.provider.inTask=n)},()=>this.inTask,()=>{var n,i;return((i=(n=this.hooks).isRiskFlagEnabled)==null?void 0:i.call(n,WW))??!0},()=>!this.destroying&&!!this.provider&&this.connected&&this.ongoing),this.off(zb,this.onTaskStateSignal),this.on(zb,this.onTaskStateSignal))}_stopTaskStateResync(){var e;(e=this.taskStateResync)==null||e.stop(),this.taskStateResync=null}async clearMediaStore(){await this.store.clear()}_handleChatEndedEvent(e){var t;this.state&&((t=this.outbox)==null||t.failAll("chat_ended"),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 mr.COBROWSE_REQUESTED_FROM_AGENT:this.events.triggerEvent("_requestCobrowse","agent");break;case mr.COBROWSE_REQUESTED_FROM_END_USER:this.events.triggerEvent("_requestCobrowse","end_user");break;case mr.CHAT_DISMISSED:this.state&&(this.state.status="dismissed",this.triggerEvent("dismissed",this));break;case mr.CHAT_ENDED:this.events.triggerEvent("_chatEnded",e);break;case mr.ESCALATION_STARTED:this.inEscalation=!0;break;case mr.ESCALATION_FAILED:case mr.ESCALATION_ACCEPTED:this.inEscalation=!1;break;case mr.CHECK_IN_REQUIRED:this.events.triggerEvent("checkInRequired");break;case mr.CHECK_IN_TIMED_OUT:this.events.triggerEvent("checkInTimedOut");break}}}const ev={LOADED:"cobrowse.loaded",UPDATED:"cobrowse.updated",ENDED:"cobrowse.ended"},dk=1e4,YW=3e4,XW=9e5,QO={UPDATED:"riskFlagsUpdated"},wu=new Jr("Communicator"),QW="web-4503-base64url-jwt-decode";var Uo,ff;class ZW{constructor(e,t){oe(this,"user");oe(this,"clientEventManager");oe(this,"clientAuthenticate");oe(this,"config");oe(this,"channel");oe(this,"channelReady",!1);oe(this,"hasAuthenticated",!1);oe(this,"hasInitializedLogProxy",!1);oe(this,"queuedMessagesToBridge",[]);oe(this,"pendingBridgeRequests",{});oe(this,"bridgeIframe");oe(this,"bridgeMessageHandlers");oe(this,"tokenRefreshTimeout");oe(this,"logProxyQueue",[]);Cy(this,Uo,"");Cy(this,ff,0);oe(this,"authRefreshInFlight",null);oe(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 Ic(this,Uo);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(!Ic(this,Uo)||!((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 ${Ic(this,Uo)}`,"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 Fu))throw e;if(e.refusedBy==="client")throw e.cause;wu.error(e.message)}}isAuthTokenFresh(){return!!Ic(this,Uo)&&Ic(this,ff)-Date.now()>YW}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 Fu("Client authenticate callback rejected","client",{cause:i})}const t=await this.serverAuthenticate(e.token);if(t.error)throw new Fu("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){ky(this,Uo,e),ky(this,ff,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(QO.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=Vw()+"_"+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=ek.replace("main.api",e.tenant):t=ek);const n=e.lang||"en",i=!!((l=e.cobrowse)!=null&&l.enabled),a=(e.bridge||"https://websdk.ujet.co/v3/bridge.html")+"?6.39.1",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.39.1",bridge:a,bridgeOrigin:c,modules:o}}initLogProxyHandler(e){!this.hasInitializedLogProxy&&e.log_proxy_url&&(this.hasInitializedLogProxy=!0,Jr.addHandler((t,n,...i)=>{if(n==="debug")return;const s=Y6(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()-dk,dk);this.tokenRefreshTimeout=setTimeout(()=>{this.onRefreshToken()},n)}decodeJwt(e){const t=e.split(".")[1],n=this.isRiskFlagEnabled(QW)?q6:jO;return JSON.parse(n(t))}normalizeJwtExp(e){return e.toString().length===13?e:e.toString().length===10?e*1e3:Date.now()+XW}}Uo=new WeakMap,ff=new WeakMap;const eH={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"},tH={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"},rH={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"},nH={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"},iH={confirmSessionTitle:"共同ブラウジングセッションリクエスト",confirmSessionContent:"現在の画面を担当者と共有したいですか。",endSessionText:"共同ブラウジングセッションを終了",confirmRemoteControlTitle:"リモートアクセスリクエスト",confirmRemoteControlContent:"担当者は、お客様をさらにお手伝いするために、現在共有中の画面へのアクセスを希望しています。許可しますか。",confirmFullDeviceTitle:"画面共有リクエスト",confirmFullDeviceContent:"画面全体を担当者と共有したいですか。担当者は画面上で一切の操作ができません。",allowText:"許可",denyText:"拒否"},sH={confirmSessionTitle:"코브라우징 세션 요청",confirmSessionContent:"현재 화면을 상담원과 공유하시겠습니까?",endSessionText:"코브라우징 세션 종료",confirmRemoteControlTitle:"원격 액세스 요청",confirmRemoteControlContent:"상담원이 추가 지원을 위해 현재 공유된 화면에 액세스할 수 있기를 원합니다. 허용하시겠습니까?",confirmFullDeviceTitle:"화면 공유 요청",confirmFullDeviceContent:"상담원과 전체 화면을 공유하시겠습니까? 상담원은 화면의 어떤 부분도 제어할 수 없습니다.",allowText:"허용",denyText:"거절"},aH={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"},oH={confirmSessionTitle:"同步浏览会话请求",confirmSessionContent:"您是否要向该客服代表共享当前的屏幕?",endSessionText:"结束同步浏览会话",confirmRemoteControlTitle:"远程访问请求",confirmRemoteControlContent:"为了进一步协助您,客服代表想访问您当前的共享屏幕。您是否允许这样做?",confirmFullDeviceTitle:"屏幕共享请求",confirmFullDeviceContent:"您是否要向该客服代表共享全屏?客服代表将不能控制屏幕上的任何东西。",allowText:"允许",denyText:"拒绝"},uH={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"},cH={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"},lH={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ä"},dH={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"},fH={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"},hH={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"},pH={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"},vH={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"},gH={confirmSessionTitle:"ขอเซสชันเรียกดูร่วม",confirmSessionContent:"คุณต้องการแชร์หน้าจอปัจจุบันกับตัวแทนหรือไม่",endSessionText:"สิ้นสุดเซสชันเรียกดูร่วม",confirmRemoteControlTitle:"ขอการเข้าถึงระยะไกล",confirmRemoteControlContent:"ตัวแทนต้องการเข้าถึงหน้าจอของคุณที่แชร์อยู่ในปัจจุบันเพื่อให้ความช่วยเหลือคุณต่อไป คุณจะอนุญาตหรือไม่",confirmFullDeviceTitle:"ขอแชร์หน้าจอ",confirmFullDeviceContent:"คุณต้องการแชร์ทั้งหน้าของคุณกับตัวแทนหรือไม่ ตัวแทนจะไม่สามารถควบคุมอะไรบนหน้าจอ",allowText:"ยินยอม",denyText:"ปฏิเสธ"},mH={confirmSessionTitle:"طلب جلسة تصفح مشترك",confirmSessionContent:"هل تريد مشاركة شاشتك الحالية مع الموظف؟",endSessionText:"إنهاء جلسة التصفح المشترك",confirmRemoteControlTitle:"طلب التحكم عن بعد",confirmRemoteControlContent:"يرغب مسئول الدعم في رؤية شاشتك المشاركة حالياً لمساعدتك بشكلٍ أكبر. هل تسمح بذلك؟",confirmFullDeviceTitle:"طلب مشاركة الشاشة",confirmFullDeviceContent:"هل تريد مشاركة شاشتك الكاملة مع مسئول الدعم؟ لن يتمكن المسئول من التحكم في أي شيء على الشاشة.",allowText:"السماح",denyText:"الرفض"},yH={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"},_H={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"},bH={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"},SH={confirmSessionTitle:"Запрос сеанса совместного просмотра веб-страниц",confirmSessionContent:"Хотите поделиться вашим текущим экраном с представителем?",endSessionText:"Завершить сеанс совместного просмотра веб-страниц",confirmRemoteControlTitle:"Запрос на удаленный доступ",confirmRemoteControlContent:"Представитель хочет получить доступ к вашему текущему экрану, которым вы делитесь, чтобы помочь вам. Хотите разрешить это?",confirmFullDeviceTitle:"Запрос на совместный просмотр экрана",confirmFullDeviceContent:"Хотите поделиться вашим полный экраном с представителем? Агент не сможет выполнять никаких действий на экране.",allowText:"Разрешить",denyText:"Отказать"},wH={confirmSessionTitle:"सह-ब्राउज़ सत्र अनुरोध किया गया",confirmSessionContent:"क्या आप अपनी वर्तमान स्क्रीन को एजेंट के साथ साझा करना चाहते हैं?",endSessionText:"सह-ब्राउज़ सत्र समाप्त करें",confirmRemoteControlTitle:"रिमोट पहुँच का अनुरोध किया गया",confirmRemoteControlContent:"एजेंट आपकी वर्तमान साझा स्क्रीन तक पहुँच प्राप्त करना चाहेगा ताकि वह आपकी और सहायता कर सके। क्या आप इसकी अनुमति देना चाहते हैं?",confirmFullDeviceTitle:"स्क्रीन साझाकरण अनुरोध",confirmFullDeviceContent:"क्या आप अपनी पूरी स्क्रीन एजेंट के साथ साझा करना चाहते हैं? एजेंट स्क्रीन पर कुछ भी नियंत्रित नहीं कर पाएगा।",allowText:"अनुमति दें",denyText:"अस्वीकार करें"},TH={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"},EH={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"},CH={confirmSessionTitle:"Запит на сесію спільного перегляду",confirmSessionContent:"Чи Ви хочете поділитись з агентом своїм поточним екраном?",endSessionText:"Завершити сесію спільного перегляду",confirmRemoteControlTitle:"Запит на віддалений доступ",confirmRemoteControlContent:"Агент хоче отримати доступ до Вашого поточного екрану, який переглядається спільно, щоб допомогти Вам. Ви дозволяєте?",confirmFullDeviceTitle:"Запит на спільний перегляд екрану",confirmFullDeviceContent:"Чи Ви хочете поділитись з агентом своїм екраном повністю? Агент не зможе нічого на ньому контролювати.",allowText:"Дозволити",denyText:"Відмовити"},kH={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"},cd={en:eH,es:tH,"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:rH,"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:nH,ja:iH,ko:sH,it:aH,zh:oH,"zh-Hant":{confirmSessionTitle:"共同瀏覽工作階段要求",confirmSessionContent:"要與專員分享您目前的畫面嗎?",endSessionText:"結束共同瀏覽工作階段",confirmRemoteControlTitle:"遠端存取要求",confirmRemoteControlContent:"專員想要存取您目前分享的螢幕畫面以進一步協助您。要允許嗎?",confirmFullDeviceTitle:"螢幕畫面分享要求",confirmFullDeviceContent:"要與專員分享全螢幕嗎?專員將無法控制畫面上的任何項目。",allowText:"允許",denyText:"拒絕"},sv:uH,pt:cH,"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:lH,nb:dH,da:fH,nl:hH,tr:pH,vi:vH,th:gH,ar:mH,cs:yH,pl:_H,hu:bH,ru:SH,hi:wH,ro:TH,hr:EH,uk:CH,tl:kH};function RH(r){const e=r.split("-")[0];return cd[r]?r===e?cd[r]:{...cd[e],...cd[r]}:cd[e]}async function IH(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 PH(a)}function PH(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 AH=()=>typeof navigator<"u"&&/Android/.test(navigator.userAgent),OH=()=>typeof navigator<"u"&&/Chrome/.test(navigator.userAgent),ZO=()=>typeof navigator>"u"?!1:/Android|iPhone|iPad|iPod/.test(navigator.userAgent)?!0:navigator.platform==="MacIntel"&&(navigator.maxTouchPoints??0)>1,Ly=()=>OH()&&!AH();function fk(r){return r.chats=r.chats.map(e=>{const t=e.entries.map((n,i)=>$H(n,`${e.comm_id}-${i}`));return e.entries=aW(t),e}),r}function $H(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 xH={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 MH(r){var t,n;return{languages:r.languages.filter(i=>i.enabled).map(i=>({lang:i.lang,name:i.name,localeName:xH[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 e$(r){return r.map(DH).filter(e=>e.enabled)}function DH(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=NH(r);if(t&&(e.redirection=r.redirection),r.children&&r.children.length){const n=e$(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}=LH(r.channels);e.deflection=i,t||(e.channels=n),e.enabled=n.length>0||t}return e}function NH(r){let e=!1;const t=r.redirection;return t&&(t.option==="message"||t.option==="url")&&(e=!!t.data),e}function LH(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:yv.INBOUND_CALL}),r.voice_call&&r.voice_call.deflected&&r.voice_call.voicemail_reason&&i({...r.voice_call,type:yv.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 FH="ujet_voice_call",t$="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"},Jw=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)},UH=(r,e)=>!!r&&typeof r=="object"&&"code"in r&&r.code===e,r$=r=>{if(r&&typeof r=="object"&&"status"in r){const e=r.status;if(typeof e=="number")return e}};class Ts extends Error{constructor(t,n,i){super(t,i!==void 0?{cause:i}:void 0);oe(this,"code");this.name="VoiceCallError",this.code=n,i!==void 0&&(this.cause=i)}}const Kv=class Kv extends Ts{constructor(e="End user has a call in progress"){super(e,Kv.CODE),this.name="CallInProgressError"}};oe(Kv,"CODE","CALL_IN_PROGRESS");let Vu=Kv;const Jv=class Jv extends Ts{constructor(e="Inbound voice is disabled for this menu"){super(e,Jv.CODE),this.name="InboundDisabledError"}};oe(Jv,"CODE","INBOUND_DISABLED");let fl=Jv;const Yv=class Yv extends Ts{constructor(e="Outside operation hours"){super(e,Yv.CODE),this.name="OperationHoursError"}};oe(Yv,"CODE","OPERATION_HOURS");let Gu=Yv;const Xv=class Xv extends Ts{constructor(e="Inbound voice feature is not enabled for this tenant"){super(e,Xv.CODE),this.name="FeatureNotEnabledError"}};oe(Xv,"CODE","FEATURE_NOT_ENABLED");let hl=Xv;const Qv=class Qv extends Ts{constructor(e="Microphone permission denied",t){super(e,Qv.CODE,t),this.name="MicPermissionDeniedError"}};oe(Qv,"CODE","MIC_PERMISSION_DENIED");let pl=Qv;const Zv=class Zv extends Ts{constructor(e="No active voice call"){super(e,Zv.CODE),this.name="NoActiveVoiceCallError"}};oe(Zv,"CODE","NO_ACTIVE_VOICE_CALL");let Fo=Zv;const eg=class eg extends Ts{constructor(e="A voice call is active in another tab"){super(e,eg.CODE),this.name="AnotherTabVoiceCallError"}};oe(eg,"CODE","ANOTHER_TAB_VOICE_CALL");let vl=eg;const tg=class tg extends Ts{constructor(e,t){super(e,tg.CODE,t),this.name="ProviderError"}};oe(tg,"CODE","PROVIDER_ERROR");let fa=tg;const Qc=class Qc extends Ts{constructor(e,t){super(e,Qc.CODE,t),this.name="SmartActionError"}get isAlreadyEnded(){return this.message===Qc.ENDED_MESSAGE}};oe(Qc,"CODE","SMART_ACTION_ERROR"),oe(Qc,"ENDED_MESSAGE","smart action is already ended");let ii=Qc;const rg=class rg extends Ts{constructor(e,t){super(`Unrecognized voice error: ${e}`,rg.CODE,t),this.name="UnknownVoiceError"}};oe(rg,"CODE","UNKNOWN_VOICE_ERROR");let bv=rg;const jH=r=>r instanceof Gu||r instanceof fl||r instanceof hl||r instanceof Vu,qa=new Jr("BackgroundKeepAlive");class BH{constructor(e={}){oe(this,"active",!1);oe(this,"currentAgentName",null);oe(this,"wakeLock",null);oe(this,"audioCtx",null);oe(this,"silentSource",null);oe(this,"visibilityListener",null);oe(this,"pagehideListener",null);oe(this,"pageshowListener",null);oe(this,"resumeListener",null);oe(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){qa.debug("onCleanup threw during unload",n)}this.stop().catch(n=>qa.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=>qa.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){qa.debug("wakeLock.request failed",t)}}async releaseWakeLock(){if(this.wakeLock){try{await this.wakeLock.release()}catch(e){qa.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){qa.debug("mediaSession.metadata set failed",n)}}clearMediaSession(){if(typeof navigator>"u")return;const e=navigator.mediaSession;if(e)try{e.metadata=null}catch(t){qa.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){qa.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=>qa.debug("audioCtx.close failed",s)),this.audioCtx=null}}const vs={CONNECTED:"voice:internal:connected",DISCONNECTED:"voice:internal:disconnected",ERROR:"voice:internal:error"},n$="_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"},Hc=new Set(["finished","failed","canceled","timeout","recovered","voicemail"]),Fy=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 qH{constructor(e){oe(this,"_status");this._status=e}get status(){return this._status}get isTerminal(){return Hc.has(this._status)}transitionTo(e){if(this.isTerminal)return null;const t=this._status;return this._status=e,t}}const Uy="ujet:",Sr={set(r,e){try{localStorage.setItem(Uy+r,e)}catch{}},get(r){try{return localStorage.getItem(Uy+r)}catch{return null}},del(r){try{localStorage.removeItem(Uy+r)}catch{}}},Sv="voice",WH=r=>{Sr.set(Sv,String(r))},hk=()=>{const r=Sr.get(Sv);if(!r)return null;const e=Number(r);return Number.isFinite(e)&&e>0?e:(Sr.del(Sv),null)},Vc=()=>{Sr.del(Sv)},HH=new Set(["connected","va_connected"]),jy=r=>HH.has(r),VH=new Set(["finished","canceled","expired"]),GH=[Kn.RECONNECTING,Kn.RECONNECTED,Kn.CONNECTION_QUALITY];class zH{constructor(e,t,n,i,s){oe(this,"_state");oe(this,"_publicState",null);oe(this,"events");oe(this,"provider");oe(this,"methods");oe(this,"globalEvents");oe(this,"logger");oe(this,"destroyed",!1);oe(this,"isProviderConnected",!1);oe(this,"isUnloading",!1);oe(this,"startedAt",null);oe(this,"fetchEpoch",0);oe(this,"keepAlive",null);oe(this,"stateMachine");oe(this,"handledSmartActionIds",new Set);oe(this,"smartActionQueue",[]);oe(this,"currentCobrowseSmartActionId",null);oe(this,"recordingPermissionAsked",!1);oe(this,"speakerOn",!1);oe(this,"cobrowseStarter");this._state=e,this.methods=t,this.events=new sg,this.logger=new Jr(`VoiceCall:${e.id}`),this.provider=new n(this.events,e,t.issueToken),this.globalEvents=i,this.cobrowseStarter=s,this.stateMachine=new qH(e.status),jy(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:Fy(e),prevStatus:Fy(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 Fy(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=>!VH.has(n.status));for(const n of e)this.handleSmartActionRequested(n);this.keepAlive=new BH({onCleanup:()=>{this.isUnloading=!0;const n=this._state.status;jy(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=jy(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 fa("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 ii("uploadVideos not configured");await this.methods.uploadVideos(this.id,t,e)}else{if(!this.methods.uploadPhotos)throw new ii("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 ii("call destroyed");if(t==="video"){if(!this.methods.uploadOneVideo)throw new ii("uploadOneVideo not configured");return{ref:await this.methods.uploadOneVideo(this.id,e,n),kind:t}}if(!this.methods.uploadOnePhoto)throw new ii("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 ii("call destroyed");if(n.length===0)throw new ii("submitMediaRefsForSmartAction called with empty refs");const i=n.find(a=>a.kind!==t);if(i)throw new ii(`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 ii("registerVideos not configured");await this.methods.registerVideos(this.id,s,e)}else{if(!this.methods.registerPhotos)throw new ii("registerPhotos not configured");await this.methods.registerPhotos(this.id,t,s,e)}this.markSmartActionHandled(e)}registerProviderEvents(){this.events.addEventListener(vs.CONNECTED,async()=>{this.destroyed||(await this.fetchAndUpdateState(),!(this.destroyed||this._state.status==="finished")&&(this.startedAt=this.resolveStartedAtFromState()))}),this.events.addEventListener(vs.DISCONNECTED,()=>{this.destroyed||this.stateMachine.isTerminal||(this.isProviderConnected=!1,this.setStatus("finished"),this.fetchAndUpdateState())}),this.events.addEventListener(vs.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 GH)this.events.addEventListener(e,t=>{this.globalEvents.triggerEvent(e,t)});this.events.addEventListener(n$,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}}),!Hc.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 ii("updateSmartAction not configured");try{await this.methods.updateSmartAction(this.id,e,t),this.markSmartActionHandled(e)}catch(n){const i=Jw(n);if(i===ii.ENDED_MESSAGE){this.markSmartActionHandled(e);return}throw new ii(i,n)}}}class Yw{constructor(e,t,n){oe(this,"events");oe(this,"state");oe(this,"issueVoiceToken");this.events=e,this.state=t,this.issueVoiceToken=n}getRemoteStream(){return null}sendMessage(e){return null}}oe(Yw,"type","base");const i$={},s$=r=>{i$[r.type]=r},a$=r=>i$[r],Uh=new Jr("methods"),pk=!0,KH="web-4191-refresh-unknown-chat-agent";class JH{constructor(e,t,n,i){oe(this,"request");oe(this,"lastDapRequestId",null);oe(this,"lastDirectAccessKeyId",null);oe(this,"dapPollGeneration",0);oe(this,"beaconLeaveChat");oe(this,"authContext");oe(this,"isRiskFlagEnabled");oe(this,"getCustomFormData",async e=>{const t=`forms/${e}/details`;try{return await this.get(t)}catch(n){Uh.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 MH(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:Uh.warn("unexpected /menus response shape; rendering an empty menu list"),{menus:e$(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 Uh.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 tf(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:pk})).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===ll.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 fk(t)}else{const{data:t}=await this.get(`/chats/histories?page=${e}&per_page=1`);return fk(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};Ly()&&(a.file=await Jb(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=h=>this.getChatMessageOriginal(e.id,h),c=async()=>(await this.getChat(e.id)).task_virtual_agent_active,o=new JW(e,n,{leaveChat:i,leaveChatBeacon:s,isRiskFlagEnabled:this.isRiskFlagEnabled,fetchMessageOriginal:a,fetchTaskVaActive:c},this.buildProviderContext(e.id)),l=async h=>{if(o.status==="va_assigned"){const p=await this.getSkipVirtualAgentSettings(o.menuId,o.lang);o.allowSkipVirtualAgent=p,o.update(h)}};o.on("initialized",async()=>{if(o.status==="queued"){const h=await this.getChat(o.id);o.update(h)}}),o.on("memberJoined",async()=>{const h=await this.getChat(o.id);o.update(h)}),o.on("memberLeft",async()=>{const h=await this.getChat(o.id);o.update(h)});let d=!1;if(o.on("message",h=>{var p;!o.connected||!o.ongoing||d||h.$userType!==Jn.USER||!Number.isSafeInteger(h.$userId)||h.$userId<=0||o.allAgents.human.some(y=>y.id===h.$userId)||((p=this.isRiskFlagEnabled)==null?void 0:p.call(this,KH))===!1||(d=!0,this.getChat(o.id).then(y=>{o.connected&&o.ongoing&&o.update(y)}).catch(()=>{Uh.warn("Unable to refresh chat agents after an unknown human message")}).finally(()=>{d=!1}))}),o.on("_chatEnded",async h=>{const p=await this.getChat(o.id);o.update(p),(!o.state||o.ended)&&o._handleChatEndedEvent(h)}),o.on("_menuChanged",async h=>{const p=await this.getChat(h.id);l(p)}),o.on("checkInRequired",async()=>{const h=await this.getChat(o.id);o.update(h)}),o.on("checkInTimedOut",async()=>{const h=await this.getChat(o.id);o.update(h)}),o.channelId)o.connect(),l(e);else{let h;for(;!h;)await this.getChat(o.id).then(p=>{p.provider_channel_id&&o.state?(h=!0,o.update(p),o.connect(),l(p)):(p.status==="canceled"||p.status==="finished")&&(h=!0)}),h||await tf(1500)}return o}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(ZO())return await IH(s.data.url,t,s.data.fields,n);const a={file:t,fields:s.data.fields};return Ly()&&(a.file=await Jb(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,$,F)=>await this.failVoiceCall(L,$,F),l=async L=>await this.escalateVoiceCall(L),d=async(L,$)=>await this.updateVoiceCallRecordingPermission(L,$),h=async(L,$,F)=>await this.updateVoiceSmartAction(L,$,F),p=async(L,$,F,G)=>{await this.uploadVoiceCallPhotos(L,$,F,G)},y=async(L,$,F)=>{await this.uploadVoiceCallVideos(L,$,F)},w=async(L,$,F)=>await this.uploadVoiceCallPhotoSingle(L,$,F),k=async(L,$,F)=>await this.uploadVoiceCallVideoSingle(L,$,F),P=async(L,$,F,G)=>{await this.registerVoiceCallPhotos(L,$,F,G)},A=async(L,$,F)=>{await this.registerVoiceCallVideos(L,$,F)},B=a$(this.resolveVoiceProviderType(e));if(!B)throw new fa(`No voice provider registered for ${e.voip_provider}`);return new zH(e,{issueToken:s,fetchCall:a,finishCall:c,failCall:o,escalateCall:l,updateRecordingPermission:d,updateSmartAction:h,uploadPhotos:p,uploadVideos:y,uploadOnePhoto:w,uploadOneVideo:k,registerPhotos:P,registerVideos:A},B,n,i)}resolveVoiceProviderType(e){return e.voip_provider==="voip_provider_twilio"?t$: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:pk,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&&Ly()?i["email_attachments[]"]=await YH(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 YH(r){return Promise.all(r.map(Jb))}function Jb(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 o$=new Jr("CobrowseService");async function XH(r){return window.CobrowseIO?window.CobrowseIO:await QH(r)}async function QH(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(){o$.error("Failed to load cobrowse script",r),e(null)}})}const vk="https://js.cobrowse.io/CobrowseIO.js";function ZH(r){return!r||r.toLowerCase()==="https://cobrowse.io"?vk:r.toLowerCase().startsWith("https://")?`${r}/sdk-js/CobrowseIO.js`:(o$.warn("customCobrowseDomain must use HTTPS; falling back to default",{cobrowseDomain:r}),vk)}async function eV(r,e){let t=r.instance;if(!t){const n=ZH(e);t=await XH(n)}return new tV(t,r)}class tV{constructor(e,t){oe(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 rV=Date.now(),u$={href:window.location.href,interval:24*60*60};function nV(r){if(!Array.isArray(r)||!r.length)return null;const e=uV(),t=e===0,n=e+1;return cV(n),r.filter(s=>{const a=sV(s,u$.href),c=aV(s.visitor_type,t),o=n>=s.page_visit_count,l=!oV(s.id);return a&&c&&o&&l}).sort((s,a)=>s.stay_time-a.stay_time)[0]||null}function iV(r,e){const t=r.stay_time*1e3,n=Math.max(t-(Date.now()-rV),0);setTimeout(()=>{e(r),Sr.set(`trigger:${r.id}`,(Date.now()/1e3).toString())},n)}const sV=(r,e)=>{const{keywords_included_or:t=[],keywords_excluded_or:n=[],keywords_included:i=[],keywords_excluded:s=[]}=r;if(H6(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 aV(r,e){return r==="visitor_type_new"?e:r==="visitor_type_returning"?!e:!0}function oV(r){try{const e=parseInt(Sr.get(`trigger:${r}`),10);return Date.now()/1e3-e<u$.interval}catch(e){return console.error("Couldn't parse trigger time",e),!1}}function uV(){try{const r=Sr.get("visits");return r?parseInt(r,10):0}catch(r){return console.error("Couldn't get visit count",r),0}}function cV(r){try{Sr.set("visits",r.toString())}catch(e){console.error(e)}}function lV(r){return r.replace(/\/+$/,"")}const By=new Jr("VoiceMultiTab"),Yb="voice:tab-lock",dV=5e3,fV=2e3,hV=250,qy=()=>{const r=Sr.get(Yb);if(!r)return null;try{return JSON.parse(r)}catch{return null}},Wy=()=>{var i;const r=qy();if(r&&typeof r.ts=="number"&&Date.now()-r.ts<dV)throw new vl;const e=Vw(),t=()=>{Sr.set(Yb,JSON.stringify({id:e,ts:Date.now()}))};if(t(),((i=qy())==null?void 0:i.id)!==e)throw new vl;const n=setInterval(t,fV);return{release(){clearInterval(n);const s=qy();(!s||s.id===e)&&Sr.del(Yb)}}},gk=async()=>{if(typeof BroadcastChannel>"u")return Wy();let r;try{r=new BroadcastChannel(FH)}catch{return Wy()}const e=Vw();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){By.debug("BC postMessage(claim) failed; falling back to localStorage path",n);try{r.close()}catch{}return Wy()}if(await new Promise(n=>setTimeout(n,hV)),t)throw r.close(),new vl;return r.onmessage=n=>{const i=n.data;if(i.kind==="claim"&&i.id!==e)try{r.postMessage({kind:"present",id:e})}catch(s){By.debug("BC postMessage(present) failed",s)}},{release(){try{r.postMessage({kind:"release",id:e})}catch(n){By.debug("BC postMessage(release) failed",n)}r.close()}}},pV=["photo","video","audio","document"],oa=new Jr("client");function vV(r){const e=r==null?void 0:r.status;return typeof e=="number"&&e>=400&&e<500}let gV=class{constructor(e){oe(this,"VERSION",zw);oe(this,"options");oe(this,"communicator");oe(this,"methods");oe(this,"events",new sg);oe(this,"request");oe(this,"chat");oe(this,"_cobrowse");oe(this,"_voiceCall",null);oe(this,"_voiceTabLock",null);oe(this,"redactionSendQueue",Promise.resolve());oe(this,"fileSendQueue",Promise.resolve());oe(this,"noCryptoLogged",!1);oe(this,"_rehydratePromise",null);oe(this,"onPageHide");oe(this,"onPageShow");this.options=e.host?{...e,host:lV(e.host)}:e,this.communicator=new ZW(this.options,this.events);const t=this.communicator.request.bind(this.communicator),n=this.communicator.leaveChatBeacon.bind(this.communicator);this.methods=new JH(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&&$O.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:Sr.get("lang")||"en"}set lang(e){this.options.lang||Sr.set("lang",e)}get cobrowse(){return this._cobrowse.cobrowseIO}get cobrowseEnabled(){var e;return!!((e=this.options.cobrowse)!=null&&e.enabled)}destroy(){var e;(e=this.chat)==null||e._stopTaskStateResync(),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=nV(t);n&&iV(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&&Sr.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):(Sr.del("chat"),Sr.del("cobrowse")),t}catch(t){throw Sr.del("chat"),Sr.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=Sr.get("chat");if(!e)return Sr.del("chat"),null;try{const t=await this.loadChat(e);return t&&t.ongoing?t:(Sr.del("chat"),null)}catch(t){throw Sr.del("chat"),t}}async restoreCobrowseSession(){var t;const e=Sr.get("cobrowse");if(!(!e||!((t=this.options.cobrowse)!=null&&t.enabled)))try{await this.initializeCobrowse(this.lang),oa.debug("cobrowse session restored with nonce:",e)}catch(n){oa.error("Failed to restore cobrowse session",n),Sr.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===ll.FINISHED||e===ll.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){oa.warn("finishChat during destroy failed",{error:e})}await this.chat.destroy(),this.chat=null,zn.trackerId=""}}get voiceCall(){return this._voiceCall}hasStoredVoiceCall(){return hk()!==null}async startVoiceCall(e,t={}){var i;if(this._voiceCall&&!Hc.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 mV()}catch(s){const a=s instanceof pl?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 gk();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(),mk(s)}this._voiceCall=n;try{await n._connect()}catch(s){throw await n._destroy().catch(()=>{}),this._voiceCall=null,this.releaseVoiceTabLock(),s}return WH(n.id),n}async loadVoiceCall(e){if(this._voiceCall&&!Hc.has(this._voiceCall.serverStatus()))return this._voiceCall;let t=null;if(e!==void 0?t=Number(e):t=hk(),t===null)return null;this.releaseVoiceTabLock(),this._voiceTabLock=await gk();let n;try{n=await this.methods.fetchVoiceCall(t)}catch(s){if(r$(s)===404)return Vc(),this.releaseVoiceTabLock(),null;throw this.releaseVoiceTabLock(),mk(s)}if(Hc.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=>{oa.warn("cobrowse restore failed during voice restore",s)}),i}async endVoiceCall(){this._voiceCall&&(Hc.has(this._voiceCall.serverStatus())||await this._voiceCall._abandonOrFinish())}async escalateVoiceCall(){if(!this._voiceCall)throw new Fo;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 Fo;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 Fo;return await this.methods.getVoiceCallSurvey(this._voiceCall.id)}async submitVoiceCallSurvey(e){if(!this._voiceCall)throw new Fo;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);uW(e,t)}catch(t){oa.warn("[fetchMessages] Failed to fetch chat documents",t)}if(e.filter(t=>t.type===xr.SERVER_MESSAGE).length>0){const t=await this.methods.listChatTaskMessages(this.chat.id);return this.sanitizeFetchedMessages(iW(e,t))}return this.sanitizeFetchedMessages(e)}catch{return[]}}sanitizeFetchedMessages(e){if(this.communicator.isRiskFlagEnabled(JO)){const t=YO(n=>this.communicator.isRiskFlagEnabled(n));e.forEach(n=>Kb(n,t))}return e}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 oa.warn("[sendFileMessage] upload failed",s),-1}if(this.chat.tracksSends&&!this.chat.inTask&&!this.chat.state.redaction_enabled){const s=xy();if(s)return this.chat.enqueueMessage(s,i,e),-1;this.warnNoCrypto()}return this.chat.sendMessage(i,e)});return this.fileSendQueue=n.catch(()=>{}),await n}async sendTextMessage(e){const t=Gw(e);if(t){if(this.chat.inTask){const n=await this.methods.sendChatTaskMessage(this.chat.id,t);this.chat.sendMessage({type:xr.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=xy();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&&vV(c)&&n.forgetOwnOriginal(s),c}return}if(this.chat.tracksSends){const n=xy();if(n)return this.chat.enqueueMessage(n,{type:xr.TEXT,content:t}),n;this.warnNoCrypto()}this.chat.sendMessage({type:xr.TEXT,content:t})}}warnNoCrypto(){this.noCryptoLogged||(this.noCryptoLogged=!0,oa.warn("outbox disabled: no crypto"))}retryMessage(e){var t;return((t=this.chat)==null?void 0:t.retryMessage(e))??!1}discardMessage(e){var t;return((t=this.chat)==null?void 0:t.discardMessage(e))??!1}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=Sr.get("cobrowse");i||(i=Date.now().toString(),Sr.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=Sr.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 Fo;const n=this._voiceCall.id,i={callId:`call_${n}`},s=await this.createCobrowseCode(e||this.lang,i);if(!s)return"";const a=Sr.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!==Jn.END_USER&&pV.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=Jr.logHistory.toArray();return{bridgeLogs:e,rootLogs:t}}async printLogs(){const e=await this.getLogs();console.log("Printing bridge logs:"),e.bridgeLogs.forEach(t=>{Jr.printLogHistoryData(t)}),console.log("Printing root logs:"),e.rootLogs.forEach(t=>{Jr.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||RH(e),i={...this.options.cobrowse,messages:n,lang:e};this._cobrowse=await eV(i,t.cobrowse_domain),await this._cobrowse.start(),[["session.loaded",ev.LOADED],["session.updated",ev.UPDATED],["session.ended",ev.ENDED]].forEach(([a,c])=>{this.cobrowse.on(a,o=>{this.events.triggerEvent(c,o)})}),oa.debug("cobrowse has been initialized"),this.events.triggerEvent("cobrowse.initialized",this._cobrowse)}}registerOngoingChat(e){this.chat&&this.chat!==e&&this.chat._stopTaskStateResync(),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=>{oa.error("Failed to initialize cobrowse on request",n)}),this.events.triggerEvent("cobrowse.request",{from:t})}),e.on("disconnected",()=>{Sr.del("chat"),Sr.del("cobrowse")}),this.chat=e,zn.trackerId=`chat_${e.id}`,Sr.set("chat",e.id.toString()),e.cobrowsable&&Sr.get("cobrowse")&&this.initializeCobrowse(e.lang).catch(t=>{oa.error("Failed to initialize cobrowse for ongoing chat",t)})}_triggerEvent(e,t){this.events.triggerEvent(e,t)}};const mV=async()=>{var r;if(typeof navigator>"u"||!((r=navigator.mediaDevices)!=null&&r.getUserMedia))throw new pl("Browser does not support microphone access");try{(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(t=>t.stop())}catch(e){throw new pl(Jw(e),e)}},yV=new Map([["call_in_progress",Vu],["inbound_disabled",fl],["outside_operation_hours",Gu],["operation_hours",Gu],["feature_not_enabled",hl],["invalid_call_type",hl]]),_V=new Map([[409,Gu],[403,fl],[400,Vu]]),mk=r=>{var a,c;if(r instanceof Ts)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?yV.get(t):void 0;if(i)return new i(n);const s=e.status!==void 0?_V.get(e.status):void 0;return s?new s(n):new bv(n,r)};var Ye=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ag(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}function c$(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 Xb={exports:{}},Zo=wv;function wv(){}wv.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}};wv.mixin(wv);var l$={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,p=arguments.length,y;h<p;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 p=d.methodFactory,y=d.name||"",w=s[y]||s[""]||n;function k(P,A,B){var L=p(P,A,B),$=s[B]||s[""],F=$.template.indexOf("%t")!==-1,G=$.template.indexOf("%l")!==-1,K=$.template.indexOf("%n")!==-1;return function(){for(var D="",he=arguments.length,X=Array(he),ve=0;ve<he;ve++)X[ve]=arguments[ve];if(y||!s[B]){var Q=$.timestampFormatter(new Date),Oe=$.levelFormatter(P),He=$.nameFormatter(B);$.format?D+=$.format(Oe,He,Q):(D+=$.template,F&&(D=D.replace(/%t/,Q)),G&&(D=D.replace(/%l/,Oe)),K&&(D=D.replace(/%n/,He))),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})})(l$);var bV=l$.exports,d$={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 p(k,P,A){return l(k)||h.apply(this,arguments)}function y(k,P){var A=this,B,L,$,F="loglevel";typeof k=="string"?F+=":"+k:typeof k=="symbol"&&(F=void 0);function G(ve){var Q=(i[ve]||"silent").toUpperCase();if(!(typeof window===t||!F)){try{window.localStorage[F]=Q;return}catch{}try{window.document.cookie=encodeURIComponent(F)+"="+Q+";"}catch{}}}function K(){var ve;if(!(typeof window===t||!F)){try{ve=window.localStorage[F]}catch{}if(typeof ve===t)try{var Q=window.document.cookie,Oe=encodeURIComponent(F),He=Q.indexOf(Oe+"=");He!==-1&&(ve=/^([^;]+)/.exec(Q.slice(He+Oe.length+1))[1])}catch{}return A.levels[ve]===void 0&&(ve=void 0),ve}}function D(){if(!(typeof window===t||!F)){try{window.localStorage.removeItem(F)}catch{}try{window.document.cookie=encodeURIComponent(F)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function he(ve){var Q=ve;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: "+ve)}A.name=k,A.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},A.methodFactory=P||p,A.getLevel=function(){return $??L??B},A.setLevel=function(ve,Q){return $=he(ve),Q!==!1&&G($),d.call(A)},A.setDefaultLevel=function(ve){L=he(ve),K()||A.setLevel(ve,!1)},A.resetLevel=function(){$=null,D(),d.call(A)},A.enableAll=function(ve){A.setLevel(A.levels.TRACE,ve)},A.disableAll=function(ve){A.setLevel(A.levels.SILENT,ve)},A.rebuild=function(){if(a!==A&&(B=he(a.getLevel())),d.call(A),a===A)for(var ve in s)s[ve].rebuild()},B=he(a?a.getLevel():"WARN");var X=K();X!=null&&($=he(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})})(d$);var Yr=d$.exports;const SV=ag(Yr),wV=v6({__proto__:null,default:SV},[Yr]);var Qb={exports:{}},TV={"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=TV,n=Yr;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}})(Qb,Qb.exports);var Es=Qb.exports,Zb={exports:{}},Xw={},og={},eo={},hf={},va={},pf={},ro={},kl={},vf={},ga={};Object.defineProperty(ga,"__esModule",{value:!0});ga.ERROR_PACKET=ga.PACKET_TYPES_REVERSE=ga.PACKET_TYPES=void 0;const _a=Object.create(null);ga.PACKET_TYPES=_a;_a.open="0";_a.close="1";_a.ping="2";_a.pong="3";_a.message="4";_a.upgrade="5";_a.noop="6";const f$=Object.create(null);ga.PACKET_TYPES_REVERSE=f$;Object.keys(_a).forEach(r=>{f$[_a[r]]=r});const EV={type:"error",data:"parser error"};ga.ERROR_PACKET=EV;Object.defineProperty(vf,"__esModule",{value:!0});vf.encodePacket=void 0;vf.encodePacketToBinary=kV;const CV=ga,h$=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",p$=typeof ArrayBuffer=="function",v$=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r&&r.buffer instanceof ArrayBuffer,g$=({type:r,data:e},t,n)=>h$&&e instanceof Blob?t?n(e):yk(e,n):p$&&(e instanceof ArrayBuffer||v$(e))?t?n(e):yk(new Blob([e]),n):n(CV.PACKET_TYPES[r]+(e||""));vf.encodePacket=g$;const yk=(r,e)=>{const t=new FileReader;return t.onload=function(){const n=t.result.split(",")[1];e("b"+(n||""))},t.readAsDataURL(r)};function _k(r){return r instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let Hy;function kV(r,e){if(h$&&r.data instanceof Blob)return r.data.arrayBuffer().then(_k).then(e);if(p$&&(r.data instanceof ArrayBuffer||v$(r.data)))return e(_k(r.data));g$(r,!1,t=>{Hy||(Hy=new TextEncoder),e(Hy.encode(t))})}var ug={},gl={};Object.defineProperty(gl,"__esModule",{value:!0});gl.decode=gl.encode=void 0;const Gc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Od=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let r=0;r<Gc.length;r++)Od[Gc.charCodeAt(r)]=r;const RV=r=>{let e=new Uint8Array(r),t,n=e.length,i="";for(t=0;t<n;t+=3)i+=Gc[e[t]>>2],i+=Gc[(e[t]&3)<<4|e[t+1]>>4],i+=Gc[(e[t+1]&15)<<2|e[t+2]>>6],i+=Gc[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};gl.encode=RV;const IV=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=Od[r.charCodeAt(n)],a=Od[r.charCodeAt(n+1)],c=Od[r.charCodeAt(n+2)],o=Od[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};gl.decode=IV;Object.defineProperty(ug,"__esModule",{value:!0});ug.decodePacket=void 0;const jh=ga,PV=gl,AV=typeof ArrayBuffer=="function",OV=(r,e)=>{if(typeof r!="string")return{type:"message",data:m$(r,e)};const t=r.charAt(0);return t==="b"?{type:"message",data:$V(r.substring(1),e)}:jh.PACKET_TYPES_REVERSE[t]?r.length>1?{type:jh.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:jh.PACKET_TYPES_REVERSE[t]}:jh.ERROR_PACKET};ug.decodePacket=OV;const $V=(r,e)=>{if(AV){const t=(0,PV.decode)(r);return m$(t,e)}else return{base64:!0,data:r}},m$=(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=vf;Object.defineProperty(r,"encodePacket",{enumerable:!0,get:function(){return e.encodePacket}});const t=ug;Object.defineProperty(r,"decodePacket",{enumerable:!0,get:function(){return t.decodePacket}});const n=ga,i="",s=(p,y)=>{const w=p.length,k=new Array(w);let P=0;p.forEach((A,B)=>{(0,e.encodePacket)(A,!1,L=>{k[B]=L,++P===w&&y(k.join(i))})})};r.encodePayload=s;const a=(p,y)=>{const w=p.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(p,y){(0,e.encodePacketToBinary)(p,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))}p.data&&typeof p.data!="string"&&(P[0]|=128),y.enqueue(P),y.enqueue(w)})}})}let o;function l(p){return p.reduce((y,w)=>y+w.length,0)}function d(p,y){if(p[0].length===y)return p.shift();const w=new Uint8Array(y);let k=0;for(let P=0;P<y;P++)w[P]=p[0][k++],k===p[0].length&&(p.shift(),k=0);return p.length&&k<p[0].length&&(p[0]=p[0].slice(k)),w}function h(p,y){o||(o=new TextDecoder);const w=[];let k=0,P=-1,A=!1;return new TransformStream({transform(B,L){for(w.push(B);;){if(k===0){if(l(w)<1)break;const $=d(w,1);A=($[0]&128)===128,P=$[0]&127,P<126?k=3:P===126?k=1:k=2}else if(k===1){if(l(w)<2)break;const $=d(w,2);P=new DataView($.buffer,$.byteOffset,$.length).getUint16(0),k=3}else if(k===2){if(l(w)<8)break;const $=d(w,8),F=new DataView($.buffer,$.byteOffset,$.length),G=F.getUint32(0);if(G>Math.pow(2,21)-1){L.enqueue(n.ERROR_PACKET);break}P=G*Math.pow(2,32)+F.getUint32(4),k=3}else{if(l(w)<P)break;const $=d(w,P);L.enqueue((0,t.decodePacket)(A?$:o.decode($),y)),k=0}if(P===0||P>p){L.enqueue(n.ERROR_PACKET);break}}}})}r.protocol=4})(kl);function bi(r){if(r)return xV(r)}function xV(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 MV=Object.freeze(Object.defineProperty({__proto__:null,Emitter:bi},Symbol.toStringTag,{value:"Module"})),Rl=c$(MV);var Ys={},Li={};Object.defineProperty(Li,"__esModule",{value:!0});Li.defaultBinaryType=Li.globalThisShim=Li.nextTick=void 0;Li.createCookieJar=DV;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 DV(){}Object.defineProperty(Ys,"__esModule",{value:!0});Ys.pick=NV;Ys.installTimerFunctions=UV;Ys.byteLength=BV;Ys.randomString=WV;const No=Li;function NV(r,...e){return e.reduce((t,n)=>(r.hasOwnProperty(n)&&(t[n]=r[n]),t),{})}const LV=No.globalThisShim.setTimeout,FV=No.globalThisShim.clearTimeout;function UV(r,e){e.useNativeTimers?(r.setTimeoutFn=LV.bind(No.globalThisShim),r.clearTimeoutFn=FV.bind(No.globalThisShim)):(r.setTimeoutFn=No.globalThisShim.setTimeout.bind(No.globalThisShim),r.clearTimeoutFn=No.globalThisShim.clearTimeout.bind(No.globalThisShim))}const jV=1.33;function BV(r){return typeof r=="string"?qV(r):Math.ceil((r.byteLength||r.size)*jV)}function qV(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 WV(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}var gf={};Object.defineProperty(gf,"__esModule",{value:!0});gf.encode=HV;gf.decode=VV;function HV(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function VV(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 eS={exports:{}},Vy,bk;function GV(){if(bk)return Vy;bk=1;var r=1e3,e=r*60,t=e*60,n=t*24,i=n*7,s=n*365.25;Vy=function(d,h){h=h||{};var p=typeof d;if(p==="string"&&d.length>0)return a(d);if(p==="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 p=parseFloat(h[1]),y=(h[2]||"ms").toLowerCase();switch(y){case"years":case"year":case"yrs":case"yr":case"y":return p*s;case"weeks":case"week":case"w":return p*i;case"days":case"day":case"d":return p*n;case"hours":case"hour":case"hrs":case"hr":case"h":return p*t;case"minutes":case"minute":case"mins":case"min":case"m":return p*e;case"seconds":case"second":case"secs":case"sec":case"s":return p*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return p;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,p,y){var w=h>=p*1.5;return Math.round(d/p)+" "+y+(w?"s":"")}return Vy}function zV(r){t.debug=t,t.default=t,t.coerce=o,t.disable=a,t.enable=i,t.enabled=c,t.humanize=GV(),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 p=0;p<d.length;p++)h=(h<<5)-h+d.charCodeAt(p),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(d){let h,p=null,y,w;function k(...P){if(!k.enabled)return;const A=k,B=Number(new Date),L=B-(h||B);A.diff=L,A.prev=h,A.curr=B,h=B,P[0]=t.coerce(P[0]),typeof P[0]!="string"&&P.unshift("%O");let $=0;P[0]=P[0].replace(/%([a-zA-Z%])/g,(G,K)=>{if(G==="%%")return"%";$++;const D=t.formatters[K];if(typeof D=="function"){const he=P[$];G=D.call(A,he),P.splice($,1),$--}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:()=>p!==null?p:(y!==t.namespaces&&(y=t.namespaces,w=t.enabled(d)),w),set:P=>{p=P}}),typeof t.init=="function"&&t.init(k),k}function n(d,h){const p=t(this.namespace+(typeof h>"u"?":":h)+d);return p.log=this.log,p}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 p of h)p[0]==="-"?t.skips.push(p.slice(1)):t.names.push(p)}function s(d,h){let p=0,y=0,w=-1,k=0;for(;p<d.length;)if(y<h.length&&(h[y]===d[p]||h[y]==="*"))h[y]==="*"?(w=y,k=p,y++):(p++,y++);else if(w!==-1)y=w+1,k++,p=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 KV=zV;(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,p=>{p!=="%%"&&(d++,p==="%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=KV(e);const{formatters:c}=r.exports;c.j=function(o){try{return JSON.stringify(o)}catch(l){return"[UnexpectedJSONParseError]: "+l.message}}})(eS,eS.exports);var Xs=eS.exports,JV=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 YV=kl,XV=Rl,QV=Ys,ZV=gf,e5=JV(Xs),t5=(0,e5.default)("engine.io-client:transport");class y$ extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}ro.TransportError=y$;class r5 extends XV.Emitter{constructor(e){super(),this.writable=!1,(0,QV.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 y$(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):t5("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=(0,YV.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,ZV.encode)(e);return t.length?"?"+t:""}}ro.Transport=r5;var n5=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(pf,"__esModule",{value:!0});pf.Polling=void 0;const i5=ro,s5=Ys,Sk=kl,a5=n5(Xs),Ns=(0,a5.default)("engine.io-client:polling");class o5 extends i5.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,s5.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}pf.Polling=o5;var cg={};Object.defineProperty(cg,"__esModule",{value:!0});cg.hasCORS=void 0;let _$=!1;try{_$=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}cg.hasCORS=_$;var u5=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(va,"__esModule",{value:!0});va.XHR=va.Request=va.BaseXHR=void 0;const c5=pf,l5=Rl,wk=Ys,b$=Li,d5=cg,f5=u5(Xs),tS=(0,f5.default)("engine.io-client:polling");function h5(){}class S$ extends c5.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(){tS("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}}va.BaseXHR=S$;let Uu=class tv extends l5.Emitter{constructor(e,t,n){super(),this.createRequest=e,(0,wk.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,wk.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{tS("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))},tS("xhr data %s",this._data),n.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=tv.requestsCount++,tv.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=h5,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete tv.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()}};va.Request=Uu;Uu.requestsCount=0;Uu.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Tk);else if(typeof addEventListener=="function"){const r="onpagehide"in b$.globalThisShim?"pagehide":"unload";addEventListener(r,Tk,!1)}}function Tk(){for(let r in Uu.requests)Uu.requests.hasOwnProperty(r)&&Uu.requests[r].abort()}const p5=function(){const r=w$({xdomain:!1});return r&&r.responseType!==null}();class v5 extends S${constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=p5&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Uu(w$,this.uri(),e)}}va.XHR=v5;function w$(r){const e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||d5.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new b$.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Jo={},g5=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 m5=ro,Ek=Ys,y5=kl,rS=Li,_5=g5(Xs),b5=(0,_5.default)("engine.io-client:websocket"),T$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class E$ extends m5.Transport{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=T$?{}:(0,Ek.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,y5.encodePacket)(n,this.supportsBinary,s=>{try{this.doWrite(n,s)}catch{b5("websocket closed before onclose event")}i&&(0,rS.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,Ek.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}Jo.BaseWS=E$;const Gy=rS.globalThisShim.WebSocket||rS.globalThisShim.MozWebSocket;class S5 extends E${createSocket(e,t,n){return T$?new Gy(e,t,n):t?new Gy(e,t):new Gy(e)}doWrite(e,t){this.ws.send(t)}}Jo.WS=S5;var mf={},w5=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(mf,"__esModule",{value:!0});mf.WT=void 0;const T5=ro,E5=Li,Ck=kl,C5=w5(Xs),ld=(0,C5.default)("engine.io-client:webtransport");class k5 extends T5.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(()=>{ld("transport closed gracefully"),this.onClose()}).catch(e=>{ld("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){ld("session is closed");return}ld("received chunk: %o",o),this.onPacket(o),s()}).catch(c=>{ld("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,E5.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}mf.WT=k5;Object.defineProperty(hf,"__esModule",{value:!0});hf.transports=void 0;const R5=va,I5=Jo,P5=mf;hf.transports={websocket:I5.WS,webtransport:P5.WT,polling:R5.XHR};var lg={};Object.defineProperty(lg,"__esModule",{value:!0});lg.parse=$5;const A5=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,O5=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function $5(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=A5.exec(r||""),s={},a=14;for(;a--;)s[O5[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=x5(s,s.path),s.queryKey=M5(s,s.query),s}function x5(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 M5(r,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,s){i&&(t[i]=s)}),t}var D5=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 N5=hf,kk=Ys,L5=gf,Rk=lg,F5=Rl,C$=kl,zy=Li,U5=D5(Xs),Kr=(0,U5.default)("engine.io-client:socket"),nS=typeof addEventListener=="function"&&typeof removeEventListener=="function",Wd=[];nS&&addEventListener("offline",()=>{Kr("closing %d connection(s) because the network was lost",Wd.length),Wd.forEach(r=>r())},!1);class to extends F5.Emitter{constructor(e,t){if(super(),this.binaryType=zy.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,Rk.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,Rk.parse)(t.host).host);(0,kk.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,L5.decode)(this.opts.query)),nS&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(Kr("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Wd.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,zy.createCookieJar)()),this._open()}createTransport(e){Kr('creating transport "%s"',e);const t=Object.assign({},this.opts.query);t.EIO=C$.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 Kr("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){Kr("setting transport %s",e.name),this.transport&&(Kr("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(){Kr("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(Kr('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 Kr('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();Kr("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,kk.byteLength)(i)),n>0&&t>this._maxPayload)return Kr("only send %d out of %d packets",n,this.writeBuffer.length),this.writeBuffer.slice(0,n);t+=2}return Kr("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&&(Kr("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,zy.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"),Kr("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(Kr("socket error %j",e),to.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return Kr("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(Kr('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),nS&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=Wd.indexOf(this._offlineEventListener);n!==-1&&(Kr("removing listener for the 'offline' event"),Wd.splice(n,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}eo.SocketWithoutUpgrade=to;to.protocol=C$.protocol;class k$ extends to{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){Kr("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){Kr('probing transport "%s"',e);let t=this.createTransport(e),n=!1;to.priorWebsocketSuccess=!1;const i=()=>{n||(Kr('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(Kr('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;to.priorWebsocketSuccess=t.name==="websocket",Kr('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{n||this.readyState!=="closed"&&(Kr("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{Kr('probe transport "%s" failed',e);const p=new Error("probe error");p.transport=t.name,this.emitReserved("upgradeError",p)}}))};function s(){n||(n=!0,d(),t.close(),t=null)}const a=h=>{const p=new Error("probe error: "+h);p.transport=t.name,s(),Kr('probe transport "%s" failed because of error: %s',e,h),this.emitReserved("upgradeError",p)};function c(){a("transport closed")}function o(){a("socket closed")}function l(h){t&&h.name!==t.name&&(Kr('"%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=k$;let j5=class extends k${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=>N5.transports[i]).filter(i=>!!i)),super(e,n)}};eo.Socket=j5;var dg={};Object.defineProperty(dg,"__esModule",{value:!0});dg.Fetch=void 0;const B5=pf;class q5 extends B5.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})}}dg.Fetch=q5;(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=hf;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=lg;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=dg;Object.defineProperty(r,"Fetch",{enumerable:!0,get:function(){return o.Fetch}});var l=va;Object.defineProperty(r,"NodeXHR",{enumerable:!0,get:function(){return l.XHR}});var d=va;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 p=Jo;Object.defineProperty(r,"WebSocket",{enumerable:!0,get:function(){return p.WS}});var y=mf;Object.defineProperty(r,"WebTransport",{enumerable:!0,get:function(){return y.WT}})})(og);var W5=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Xw,"__esModule",{value:!0});Xw.url=G5;const H5=og,V5=W5(Xs),Ik=(0,V5.default)("socket.io-client:url");function G5(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)||(Ik("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),Ik("parse %s",r),n=(0,H5.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 fg={},yf={},Zi={},hg={},_f={};Object.defineProperty(_f,"__esModule",{value:!0});_f.isBinary=I$;_f.hasBinary=rv;const z5=typeof ArrayBuffer=="function",K5=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,R$=Object.prototype.toString,J5=typeof Blob=="function"||typeof Blob<"u"&&R$.call(Blob)==="[object BlobConstructor]",Y5=typeof File=="function"||typeof File<"u"&&R$.call(File)==="[object FileConstructor]";function I$(r){return z5&&(r instanceof ArrayBuffer||K5(r))||J5&&r instanceof Blob||Y5&&r instanceof File}function rv(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,n=r.length;t<n;t++)if(rv(r[t]))return!0;return!1}if(I$(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return rv(r.toJSON(),!0);for(const t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&rv(r[t]))return!0;return!1}Object.defineProperty(hg,"__esModule",{value:!0});hg.deconstructPacket=Q5;hg.reconstructPacket=Z5;const X5=_f;function Q5(r){const e=[],t=r.data,n=r;return n.data=iS(t,e),n.attachments=e.length,{packet:n,buffers:e}}function iS(r,e){if(!r)return r;if((0,X5.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]=iS(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]=iS(r[n],e));return t}return r}function Z5(r,e){return r.data=sS(r.data,e),delete r.attachments,r}function sS(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]=sS(r[t],e);else if(typeof r=="object")for(const t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=sS(r[t],e));return r}Object.defineProperty(Zi,"__esModule",{value:!0});Zi.Decoder=Zi.Encoder=Zi.PacketType=Zi.protocol=void 0;Zi.isPacketValid=uG;const eG=Rl,P$=hg,A$=_f,tG=Xs,aS=(0,tG.default)("socket.io-parser"),O$=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];Zi.protocol=5;var jr;(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"})(jr||(Zi.PacketType=jr={}));class rG{constructor(e){this.replacer=e}encode(e){return aS("encoding packet %j",e),(e.type===jr.EVENT||e.type===jr.ACK)&&(0,A$.hasBinary)(e)?this.encodeAsBinary({type:e.type===jr.EVENT?jr.BINARY_EVENT:jr.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===jr.BINARY_EVENT||e.type===jr.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)),aS("encoded %j as %s",e,t),t}encodeAsBinary(e){const t=(0,P$.deconstructPacket)(e),n=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(n),i}}Zi.Encoder=rG;class Qw extends eG.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===jr.BINARY_EVENT;n||t.type===jr.BINARY_ACK?(t.type=n?jr.EVENT:jr.ACK,this.reconstructor=new nG(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,A$.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(jr[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===jr.BINARY_EVENT||n.type===jr.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(Qw.isPayloadValid(n.type,s))n.data=s;else throw new Error("invalid payload")}return aS("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 jr.CONNECT:return Tv(t);case jr.DISCONNECT:return t===void 0;case jr.CONNECT_ERROR:return typeof t=="string"||Tv(t);case jr.EVENT:case jr.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&O$.indexOf(t[0])===-1);case jr.ACK:case jr.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}Zi.Decoder=Qw;class nG{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,P$.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function iG(r){return typeof r=="string"}const sG=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function aG(r){return r===void 0||sG(r)}function Tv(r){return Object.prototype.toString.call(r)==="[object Object]"}function oG(r,e){switch(r){case jr.CONNECT:return e===void 0||Tv(e);case jr.DISCONNECT:return e===void 0;case jr.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&O$.indexOf(e[0])===-1);case jr.ACK:return Array.isArray(e);case jr.CONNECT_ERROR:return typeof e=="string"||Tv(e);default:return!1}}function uG(r){return iG(r.nsp)&&aG(r.id)&&oG(r.type,r.data)}var pg={};Object.defineProperty(pg,"__esModule",{value:!0});pg.on=cG;function cG(r,e,t){return r.on(e,t),function(){r.off(e,t)}}var lG=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(yf,"__esModule",{value:!0});yf.Socket=void 0;const Ls=Zi,Bh=pg,dG=Rl,fG=lG(Xs),bn=(0,fG.default)("socket.io-client:socket"),hG=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class pG extends dG.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,Bh.on)(e,"open",this.onopen.bind(this)),(0,Bh.on)(e,"packet",this.onpacket.bind(this)),(0,Bh.on)(e,"error",this.onerror.bind(this)),(0,Bh.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(hG.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)}}}yf.Socket=pG;var Zw={};Object.defineProperty(Zw,"__esModule",{value:!0});Zw.Backoff=Il;function Il(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}Il.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};Il.prototype.reset=function(){this.attempts=0};Il.prototype.setMin=function(r){this.ms=r};Il.prototype.setMax=function(r){this.max=r};Il.prototype.setJitter=function(r){this.jitter=r};var vG=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]}),gG=Ye&&Ye.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),mG=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)&&vG(e,r,t);return gG(e,r),e},yG=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(fg,"__esModule",{value:!0});fg.Manager=void 0;const Ky=og,_G=yf,bG=mG(Zi),Tu=pg,SG=Zw,wG=Rl,TG=yG(Xs),Vn=(0,TG.default)("socket.io-client:manager");class EG extends wG.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,Ky.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 SG.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||bG;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(Vn("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Vn("opening %s",this.uri),this.engine=new Ky.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=>{Vn("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;Vn("connect attempt will timeout after %d",c);const o=this.setTimeoutFn(()=>{Vn("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(){Vn("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,Ky.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){Vn("error",e),this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new _G.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){Vn("socket %s is still active, skipping close",n);return}this._close()}_packet(e){Vn("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(){Vn("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){Vn("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;Vn("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)Vn("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();Vn("will wait %dms before reconnect attempt",t),this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(Vn("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(Vn("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):(Vn("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)}}fg.Manager=EG;(function(r,e){var t=Ye&&Ye.__importDefault||function(p){return p&&p.__esModule?p:{default:p}};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=Xw,i=fg;Object.defineProperty(e,"Manager",{enumerable:!0,get:function(){return i.Manager}});const s=yf;Object.defineProperty(e,"Socket",{enumerable:!0,get:function(){return s.Socket}});const c=(0,t(Xs).default)("socket.io-client"),o={};function l(p,y){typeof p=="object"&&(y=p,p=void 0),y=y||{};const w=(0,n.url)(p,y.path||"/socket.io"),k=w.source,P=w.id,A=w.path,B=o[P]&&A in o[P].nsps,L=y.forceNew||y["force new connection"]||y.multiplex===!1||B;let $;return L?(c("ignoring socket cache for %s",k),$=new i.Manager(k,y)):(o[P]||(c("new io instance for %s",k),o[P]=new i.Manager(k,y)),$=o[P]),w.query&&!y.query&&(y.query=w.queryKey),$.socket(w.path,y)}Object.assign(l,{Manager:i.Manager,Socket:s.Socket,io:l,connect:l});var d=Zi;Object.defineProperty(e,"protocol",{enumerable:!0,get:function(){return d.protocol}});var h=og;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})(Zb,Zb.exports);var $$=Zb.exports,x$={exports:{}};(function(r,e){(function(t){r.exports=t()})(function(){var t=function(v,g,b){for(var _=b,S=0,T=v.length;S<T;S++)_=g(_,v[S],S,v);return _},n=function(v,g){return t(v,function(b,_,S,T){return g(_,S,T)?b.concat(_):b},[])},i=function(v,g){return t(v,function(b,_,S,T){return b.concat(g(_,S,T))},[])},s=function(v,g){return t(v,function(b,_,S,T){return b===!0||_===g},!1)},a=!{toString:null}.propertyIsEnumerable("toString"),c=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],o=function(v){var g=[],b;for(b in v)Object.prototype.hasOwnProperty.call(v,b)&&g.push(b);if(!a)return g;for(var _=0,S=c.length;_<S;_++)Object.prototype.hasOwnProperty.call(v,c[_])&&g.push(c[_]);return g},l=function(v){return Object.prototype.toString.call(v)==="[object Array]"},d=function(v){return v<10?"0"+v:v},h=function(){var v=new Date;return v.getUTCFullYear()+"-"+d(v.getUTCMonth()+1)+"-"+d(v.getUTCDate())+"T"+d(v.getUTCHours())+":"+d(v.getUTCMinutes())+":"+d(v.getUTCSeconds())+"."+(v.getUTCMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z"},p={map:i,reduce:t,filter:n,includes:s,keys:o,isArray:l,isoDate:h},y={};y.intRange=function(v,g){return v===void 0&&(v=1),g===void 0&&(g=1/0),function(b){return typeof b=="number"&&parseInt(""+b,10)===b&&b>=v&&b<=g}},y.stringWithLength=function(v){return typeof v=="string"&&!!v.length};var w={},k=p.filter,P=p.reduce,A=p.keys,B=p.isArray,L=p.includes,$=y.intRange,F=y.stringWithLength;w.schema={apiKey:{defaultValue:function(){return null},message:"is required",validate:F},appVersion:{defaultValue:function(){return null},message:"should be a string",validate:function(v){return v===null||F(v)}},appType:{defaultValue:function(){return null},message:"should be a string",validate:function(v){return v===null||F(v)}},autoNotify:{defaultValue:function(){return!0},message:"should be true|false",validate:function(v){return v===!0||v===!1}},beforeSend:{defaultValue:function(){return[]},message:"should be a function or array of functions",validate:function(v){return typeof v=="function"||B(v)&&k(v,function(g){return typeof g=="function"}).length===v.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(v,g){return v&&typeof v=="object"&&F(v.notify)&&(g.autoCaptureSessions===!1||F(v.sessions))&&k(A(v),function(b){return!L(["notify","sessions"],b)}).length===0}},autoCaptureSessions:{defaultValue:function(v,g){return g.endpoints===void 0||!!g.endpoints&&!!g.endpoints.sessions},message:"should be true|false",validate:function(v){return v===!0||v===!1}},notifyReleaseStages:{defaultValue:function(){return null},message:"should be an array of strings",validate:function(v){return v===null||B(v)&&k(v,function(g){return typeof g=="string"}).length===v.length}},releaseStage:{defaultValue:function(){return"production"},message:"should be a string",validate:function(v){return typeof v=="string"&&v.length}},maxBreadcrumbs:{defaultValue:function(){return 20},message:"should be a number ≤40",validate:function(v){return $(0,40)(v)}},autoBreadcrumbs:{defaultValue:function(){return!0},message:"should be true|false",validate:function(v){return typeof v=="boolean"}},user:{defaultValue:function(){return null},message:"(object) user should be an object",validate:function(v){return typeof v=="object"}},metaData:{defaultValue:function(){return null},message:"should be an object",validate:function(v){return typeof v=="object"}},logger:{defaultValue:function(){},message:"should be null or an object with methods { debug, info, warn, error }",validate:function(v){return!v||v&&P(["debug","info","warn","error"],function(g,b){return g&&typeof v[b]=="function"},!0)}},filters:{defaultValue:function(){return["password"]},message:"should be an array of strings|regexes",validate:function(v){return B(v)&&v.length===k(v,function(g){return typeof g=="string"||g&&typeof g.test=="function"}).length}}},w.mergeDefaults=function(v,g){if(!v||!g)throw new Error("opts and schema objects are required");return P(A(g),function(b,_){return b[_]=v[_]!==void 0?v[_]:g[_].defaultValue(v[_],v),b},{})},w.validate=function(v,g){if(!v||!g)throw new Error("opts and schema objects are required");var b=P(A(g),function(_,S){return g[S].validate(v[S],v)?_:_.concat({key:S,message:g[S].message,value:v[S]})},[]);return{valid:!b.length,errors:b}};function G(){return G=Object.assign||function(v){for(var g=1;g<arguments.length;g++){var b=arguments[g];for(var _ in b)Object.prototype.hasOwnProperty.call(b,_)&&(v[_]=b[_])}return v},G.apply(this,arguments)}var K=w.schema,D=p.map,he=y.stringWithLength,X={releaseStage:{defaultValue:function(){return/^localhost(:\d+)?$/.test(window.location.host)?"development":"production"},message:"should be set",validate:he},logger:G({},K.logger,{defaultValue:function(){return typeof console<"u"&&typeof console.debug=="function"?ve():void 0}})},ve=function(){var v={},g=console.log;return D(["debug","info","warn","error"],function(b){var _=console[b];v[b]=typeof _=="function"?_.bind(console,"[bugsnag]"):g.bind(console,"[bugsnag]")}),v},Q=p.isoDate,Oe=function(){function v(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=v.prototype;return g.toJSON=function(){return{type:this.type,name:this.name,timestamp:this.timestamp,metaData:this.metaData}},v}(),He=Oe,Ze=function(v,g,b){var _=v.length,S=0,T=function(){if(S>=_)return b(null,!1);g(v[S],function(E,I){if(E)return b(E,!1);if(I===!0)return b(null,!0);S++,T()})};T()},Xe=function(v){return v.app&&typeof v.app.releaseStage=="string"?v.app.releaseStage:v.config.releaseStage},Re=Je;function Je(v){switch(Object.prototype.toString.call(v)){case"[object Error]":return!0;case"[object Exception]":return!0;case"[object DOMException]":return!0;default:return v instanceof Error}}var Ke=Re,Y=function(v,g){return function(b,_){if(typeof b!="function")return _(null,!1);try{if(b.length!==2){var S=b(v);return S&&typeof S.then=="function"?S.then(function(T){return setTimeout(function(){return _(null,Ee(v,T))},0)},function(T){setTimeout(function(){return g(T),_(null,!1)})}):_(null,Ee(v,S))}b(v,function(T,E){if(T)return g(T),_(null,!1);_(null,Ee(v,E))})}catch(T){g(T),_(null,!1)}}},Ee=function(v,g){return v.isIgnored()||g===!1},Ct={};(function(v,g){typeof Ct=="object"?Ct=g():v.StackFrame=g()})(this,function(){function v(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=v(this.getLineNumber())?":"+this.getLineNumber():"",ct=v(this.getColumnNumber())?":"+this.getColumnNumber():"";return Se+Ge+gt+et+ct}};for(var V=0;V<_.length;V++)q.prototype["get"+g(_[V])]=b(_[V]),q.prototype["set"+g(_[V])]=function(Se){return function(Ge){this[Se]=!!Ge}}(_[V]);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(!v(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(v,g){typeof Nt=="object"?Nt=g(Ct):v.ErrorStackParser=g(v.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
+ `+sn),Ot&&Mh([Q,Oe,He],_n=>{sn=sd(sn,_n," ")}),$&&Lr?$.createHTML(sn):sn},e.setConfig=function(){let vt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Me(vt),zt=!0},e.clearConfig=function(){ge=null,zt=!1},e.isValidAttribute=function(vt,ce,je){ge||Me({});const st=se(vt),Jt=se(ce);return qt(st,Jt,je)},e.addHook=function(vt,ce){typeof ce=="function"&&id(ve[vt],ce)},e.removeHook=function(vt,ce){if(ce!==void 0){const je=S6(ve[vt],ce);return je===-1?void 0:w6(ve[vt],je,1)[0]}return GC(ve[vt])},e.removeHooks=function(vt){ve[vt]=[]},e.removeAllHooks=function(){ve=QC()},e}var FO=LO();const Gb={ALLOWED_TAGS:["b","i","em","strong","p","br","ul","ol","li","a"],ALLOWED_ATTR:["href","alt","title","target","class","id"],ALLOW_DATA_ATTR:!1,FORBID_TAGS:["img","iframe","object","input","style","script","embed","svg","video","audio","body","form","link"],FORBID_ATTR:["onerror","onclick","onload","onmouseover","onfocus","onblur","onchange","onsubmit","src","href","style","action","value"],IN_PLACE:!0},U6={...Gb,FORBID_ATTR:Gb.FORBID_ATTR.filter(r=>r!=="href"),ALLOWED_URI_REGEXP:/^(?:https|mailto|tel):/i},UO="javascript:";var Lu;let Fu=(Lu=class extends Error{constructor(t,n,i){super(t);oe(this,"code",Lu.CODE);oe(this,"refusedBy");this.name="UnauthorizedError",this.refusedBy=n,i&&"cause"in i&&(this.cause=i.cause)}},oe(Lu,"CODE","UNAUTHORIZED"),Lu);function j6(r){return(r==null?void 0:r.constructor)===Object}async function ZC(r,e=3){let t=0,n;for(;t<=e;){t+=1;try{return await r()}catch(i){if(i instanceof Fu)throw i;n=i,console.error(i),await tf(1e3*Math.pow(2,t))}}throw n}function tf(r){return new Promise(e=>{setTimeout(()=>{e(0)},r)})}function Vw(){return Math.random().toString(36).slice(2)}const B6=new TextDecoder,jO=r=>{const e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return B6.decode(t)},q6=r=>jO(r.replace(/-/g,"+").replace(/_/g,"/")),W6=r=>r.length===0,H6=(...r)=>r.every(W6),Gw=r=>{const e=FO.sanitize(r,Gb);return e.includes(UO)?(console.warn("Suspicious content detected and removed."),""):e};let Nh;function V6(){return Nh||(Nh=FO(window),Nh.addHook("afterSanitizeAttributes",r=>{r.tagName==="A"&&r.hasAttribute("href")&&(r.setAttribute("target","_blank"),r.setAttribute("rel","noopener noreferrer"))})),Nh}const G6=r=>{const e=V6().sanitize(r,U6);return e.includes(UO)?(console.warn("Suspicious content detected and removed."),""):e},z6=[8,4,4,4,12],xy=()=>{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 z6.map(i=>{const s=t.slice(n,n+i);return n+=i,s}).join("-")},K6="prod",zw="6.40.0",ek="https://main.api.ujet.co",zn={companyId:"",tenant:"",trackerId:"",deviceId:"",application:"websdk",version:zw};class J6{constructor(e){oe(this,"buffer");oe(this,"writeIndex",0);oe(this,"size",0);oe(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){oe(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(Kw);Lo.logHandlers.forEach(i=>i(this.channel,e,...n)),Lo.logHistory.push({date:new Date().toISOString(),channel:this.channel,level:e,args:n})}};oe(Lo,"logHandlers",[]),oe(Lo,"logHistory",new J6(1e3));let Jr=Lo;const Y6=(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:Q6(n),message:Kw(t.join(" "))}},tk=["user","phone","phone_number","phoneNumber","email","token","access_token","accessToken","authorization","Authorization"],X6=[/(?: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 Kw(r){return Uc(r,new WeakSet)}function Uc(r,e){if(!r)return r;if(typeof r=="string")return X6.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"||(tk.indexOf(n)!==-1?t[n]="__MASKED__":t[n]=Uc(r[n],e));return t}return j6(r)&&(r={...r},Object.keys(r).forEach(t=>{tk.indexOf(t)!==-1?r[t]="__MASKED__":r[t]=Uc(r[t],e)})),r}function Q6(r){if(r.error){const e=r.error;return{error:{name:e.name,message:e.message,stack:e.stack}}}return Kw(r.data)}const Z6=new Jr("chat-provider"),qd="$superseded",BO="_sendReady",zb="_taskStateSignal";class ng{constructor(e,t,n,i){oe(this,"audio");oe(this,"issueChatToken");oe(this,"identity");oe(this,"channelId");oe(this,"region");oe(this,"inTask",!1);oe(this,"muted",!1);oe(this,"providerContext");oe(this,"events");this.events=e,this.region=t.region,this.audio=new m6,this.issueChatToken=n,this.providerContext=i}async reconnect(){}ping(){if(!this.muted)try{this.audio.playPing()}catch(e){Z6.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)}get tracksSends(){return!1}get canPublish(){return!1}publishTracked(e){return Promise.reject(new Error("this provider does not track sends"))}attachmentKeyOf(e){return""}trackInTask(e){if(e.type===xr.NOTI&&e.event===mr.TASK_VA_STARTED)this.inTask=!0;else if(e.type===xr.NOTI&&(e.event===mr.TASK_VA_FINISHED||e.event===mr.TASK_VA_FAILED))this.inTask=!1;else return;this.events.triggerEvent(zb)}}oe(ng,"type","base");const qO={};function ig(r){qO[r.type]=r}function eW(r){return qO[r]}const zv=class zv extends Error{constructor(t){super("Cannot send a message: the chat has already ended");oe(this,"code",zv.CODE);oe(this,"status");this.name="ChatEndedError",this.status=t}};oe(zv,"CODE","CHAT_ENDED");let dl=zv;const rk=new Jr("MediaStore"),tW=window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB||window.OIndexedDB||window.msIndexedDB,rW="chat-media",nk=1,_v="file";class WO{constructor(){oe(this,"db")}store(){return new Promise((e,t)=>{if(this.db)return e(ik(this.db));const n=tW.open(rW,nk);n.onerror=()=>{t(new Error("indexedDB open failed"))},n.onsuccess=()=>{const i=n.result;this.db=i,e(ik(i))},n.onupgradeneeded=i=>{const s=n.result;i.oldVersion>0&&i.oldVersion<nk&&(rk.info("deprecating media store"),s.deleteObjectStore(_v)),rk.info("creating media store"),s.createObjectStore(_v)}})}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 ik(r){return r.transaction(_v,"readwrite").objectStore(_v)}const nW=new Jr("EventManager");class sg{constructor(){oe(this,"handlers",{})}addEventListener(e,t){this.handlers[e]||(this.handlers[e]=[]),this.handlers[e].push(t)}triggerEvent(e,t){nW.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 iW(r,e){const t={};return e.forEach(n=>{t[n.id]=n}),r.map(n=>{if(n.type===xr.SERVER_MESSAGE){const i=n.server_message_id??n.message_id,s=t[i];HO(n,s.content)}return n})}function sW(r,e){return HO(r,e.content)}function HO(r,e){return Object.keys(e).forEach(t=>{r[t]=e[t]}),r}const sk={photo:2,video:2,audio:1,document:1};function aW(r){return r.toSorted((e,t)=>!e.groupMessageId||!t.groupMessageId||e.groupMessageId!==t.groupMessageId?0:(sk[t.type]||0)-(sk[e.type]||0))}function oW(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 uW(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=oW(n.url)))}})}const VO="chat-5565-surface-subscription-end",cW="chat-5580-nonblocking-history-hint",lW="chat-5566-history-recovery-job",dW="chat-5862-emulated-authorization-header",ak=new Jr("Outbox"),fW=45e3,hW=1e3,pW=1,vW=2,gW=3,mW=4,yW=7,_W=10,bW=11,SW=409;function wW(r){return(r==null?void 0:r.code)===SW}function GO(r,e=new WeakSet){if(r!==null&&typeof r=="object"&&!e.has(r)){e.add(r),Object.freeze(r);for(const t of Object.values(r))GO(t,e)}return r}function TW(r){if(r instanceof dl)return{reason:"chat_ended",retryable:!1};const{code:e,temporary:t}=r??{};switch(e){case pW:return{reason:"timeout",retryable:!0};case vW:case _W:case bW:return{reason:"disconnected",retryable:!0};case gW:case mW:case yW:return{reason:"disconnected",retryable:!1};default:return{reason:"rejected",retryable:t===!0}}}const Lh=Symbol("skipped");class EW{constructor(e){oe(this,"slots",new Map);oe(this,"inFlight",null);oe(this,"handedOff",new Set);oe(this,"resumeTimer");oe(this,"windowMs");this.options=e,this.windowMs=e.windowMs??fW}enqueue(e,t){this.slots.has(e)||this.start({client_message_id:e,payload:GO(t),status:"sending",attempt:1,$timestamp:new Date})}confirm(e){const t=this.slots.get(e);return t?(this.finish(t,{...t.entry,status:"sent",error:void 0}),!0):!1}wasHandedOff(e){return this.handedOff.has(e)}retry(e){var n;const t=this.slots.get(e);return(t==null?void 0:t.entry.status)!=="failed"||((n=t.entry.error)==null?void 0:n.reason)==="chat_ended"?!1:(this.slots.delete(e),this.start({...t.entry,status:"sending",attempt:t.entry.attempt+1,$timestamp:new Date,error:void 0}),!0)}discard(e){const t=this.slots.get(e);return(t==null?void 0:t.entry.status)!=="failed"?!1:(this.finish(t,{...t.entry,status:"discarded"}),!0)}resume(){clearTimeout(this.resumeTimer),this.resumeTimer=void 0;let e=!1;for(const t of this.slots.values())t.waiting&&Date.now()>=t.deadline?(this.failExpired(t),e=!0):t.waiting&&(t.waiting=!1,t.entry={...t.entry,attempt:t.entry.attempt+1,error:void 0},this.notify(t.entry),e=!0);e&&this.pump()}failAll(e){for(const t of this.slots.values())t.entry.status==="sending"&&this.fail(t,{reason:e,retryable:!1})}release(){var t;clearTimeout(this.resumeTimer),this.resumeTimer=void 0;const e=(t=this.inFlight)!=null&&t.onWire?this.inFlight:null;for(const n of[...this.slots.values()])n.entry.status==="sending"&&(clearTimeout(n.timer),this.slots.delete(n.entry.client_message_id),this.handedOff.delete(n.entry.client_message_id),n!==e&&this.options.send(n.entry).catch(()=>{}),this.notify({...n.entry,status:"sent",error:void 0}))}snapshot(){return Object.freeze([...this.slots.values()].map(({entry:e})=>Object.freeze({...e,$timestamp:new Date(e.$timestamp),error:e.error&&Object.freeze({...e.error})})))}destroy(){for(const e of this.slots.values())clearTimeout(e.timer);clearTimeout(this.resumeTimer),this.resumeTimer=void 0,this.slots.clear(),this.handedOff.clear(),this.inFlight=null}start(e){const t={entry:e,deadline:Date.now()+this.windowMs,timer:void 0,waiting:!1,onWire:!1};t.timer=setTimeout(()=>this.expire(t),this.windowMs),this.slots.set(e.client_message_id,t),this.notify(e),this.pump()}isCurrent(e){return this.slots.get(e.entry.client_message_id)===e&&e.entry.status==="sending"}pump(){const e=this.nextToSend();e&&(this.inFlight=e,Promise.resolve().then(()=>this.isCurrent(e)?(e.onWire=!0,this.handedOff.add(e.entry.client_message_id),this.options.send(e.entry)):Lh).then(t=>this.settle(e,t===Lh?Lh:null),t=>this.settle(e,t)))}nextToSend(){for(;;){if(this.inFlight)return;const e=[...this.slots.values()].find(t=>t.entry.status==="sending");if(!e||e.waiting)return;if(Date.now()<e.deadline)return e;this.failExpired(e)}}settle(e,t){if(e.onWire=!1,this.inFlight===e&&(this.inFlight=null),t===Lh||!this.isCurrent(e)){this.pump();return}if(t===null||wW(t))this.finish(e,{...e.entry,status:"sent",error:void 0});else{const n=TW(t);!n.retryable||Date.now()>=e.deadline?this.fail(e,n):(e.entry={...e.entry,error:n},e.waiting=!0,this.notify(e.entry),this.options.isReady()&&this.scheduleResume())}this.pump()}scheduleResume(){this.resumeTimer===void 0&&(this.resumeTimer=setTimeout(()=>{this.resumeTimer=void 0,this.resume()},hW))}expire(e){e.timer=void 0,!(e.entry.status!=="sending"||this.inFlight===e)&&(this.failExpired(e),this.pump())}failExpired(e){this.fail(e,e.entry.error??{reason:"timeout",retryable:!0})}fail(e,t){clearTimeout(e.timer),e.timer=void 0,e.waiting=!1,e.entry={...e.entry,status:"failed",error:{...t,retryable:!1}},ak.warn("send failed",{data:{client_message_id:e.entry.client_message_id,reason:t.reason,attempt:e.entry.attempt}}),this.notify(e.entry)}notify(e){try{this.options.onChange(e)}catch(t){ak.warn("status listener threw",{data:{client_message_id:e.client_message_id,error:t}})}}finish(e,t){clearTimeout(e.timer),this.slots.delete(t.client_message_id),this.handedOff.delete(t.client_message_id),this.notify(t),this.pump()}}const Fh=new Jr("chat-originals"),CW="web-4258-local-original-cache",kW=1e3,RW=4,ok=1e4,IW=100;function uk(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}class PW{constructor(){oe(this,"byClientMessageId",new Map);oe(this,"byRedactionRef",new Map);oe(this,"inFlight",new Map);oe(this,"queue",[]);oe(this,"active",0);oe(this,"generation",0)}get currentGeneration(){return this.generation}remember(e,t){!e||!t||My(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?My(this.byRedactionRef,e,null):Fh.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"?(Fh.warn("original lookup returned an unusable payload",{redactionRef:t}),null):(My(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<RW?n():this.queue.length>=IW?(Fh.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),Fh.info("original lookup gave up waiting for a slot"),i(null)},ok);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"}))},ok);e.then(s=>{clearTimeout(i),t(s)},s=>{clearTimeout(i),n(s)})})}}function My(r,e,t){r.delete(e),r.set(e,t),r.size>kW&&r.delete(r.keys().next().value)}const zO=["assigned","va_assigned"],KO=["dismissed","va_dismissed"],AW=["va_assigned","va_dismissed"],OW=["queued","check_in_timeout",...zO,...KO],$W=["timeout","canceled","failed","finished"],xW=new Jr("task-state-resync"),MW=6e4;function DW(r){return r instanceof Error?{error:r}:{data:{status:r==null?void 0:r.status}}}class NW{constructor(e,t,n,i,s,a=MW){oe(this,"seq",0);oe(this,"inFlight",!1);oe(this,"dirty",!1);oe(this,"owed",!1);oe(this,"timer",null);oe(this,"stopped",!1);this.fetchActive=e,this.apply=t,this.isInTask=n,this.isEnabled=i,this.isLive=s,this.pollMs=a}signal(){this.stopped||(this.seq+=1,this.isEnabled()&&(this.owed=!0),this.inFlight?this.dirty=!0:this.canApply()&&this.run(),this.syncPoll())}stop(){this.stopped=!0,this.clearTimer()}canApply(){return this.isEnabled()&&this.isLive()}async run(){this.inFlight=!0;try{do{this.dirty=!1;const e=this.seq;let t,n=!1;try{t=await this.fetchActive()}catch(i){n=!0,xW.warn("task state read failed",DW(i))}if(this.stopped)return;e!==this.seq?this.dirty=!0:!n&&this.canApply()&&(typeof t=="boolean"&&this.apply(t),this.owed=!1)}while(this.dirty&&this.canApply())}finally{this.inFlight=!1,this.syncPoll()}}shouldPoll(){return!this.stopped&&this.isLive()&&(this.isInTask()||this.owed)}syncPoll(){if(!this.shouldPoll()){this.clearTimer();return}this.timer||(this.timer=setInterval(()=>this.tick(),this.pollMs))}tick(){if(!this.shouldPoll()){this.clearTimer();return}!this.isEnabled()||this.inFlight||this.run()}clearTimer(){this.timer&&(clearInterval(this.timer),this.timer=null)}}const Yi=new Jr("Chat"),LW=Symbol("owner-conflict"),Dy=1e3;function FW(r){return typeof WeakRef=="function"?new WeakRef(r):{deref:()=>r}}const UW="web-4206-media-pairing-guard",jW="chat-5362-send-retry",BW=1e4,qW="chat-5821-late-echo-pairing",WW="chat-5808-task-va-resync",HW=[mr.TASK_VA_STARTED,mr.TASK_VA_FINISHED,mr.TASK_VA_FAILED];function VW(r){return r.type===xr.NOTI&&!!r.event&&HW.includes(r.event)}const GW=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function ck(r){return typeof r=="string"&&GW.test(r)?r.toLowerCase():void 0}function Ny(r){return r==="photo"||r==="video"||r==="document"}function zW(r,e){const t={client_message_id:r.client_message_id,status:r.status,$timestamp:new Date(r.$timestamp),attempt:r.attempt,error:r.error&&Object.freeze({...r.error})};return Object.freeze(e?{...t,type:r.payload.type,file:e.file,media_id:typeof e.mediaId=="number"?e.mediaId:void 0}:{...t,type:"text",content:r.payload.content??""})}function lk(r,e){return r.type!==e.type?!1:e.type===xr.TEXT?r.content===e.content:e.media_id!=null&&r.media_id===e.media_id}const JO="web-4512-inbound-sanitize-paths",KW="web-4534-inbound-https-links";function YO(r){return r(KW)??!0?G6:Gw}function XO(r,e){typeof r.title=="string"&&(r.title=e(r.title))}function Kb(r,e){typeof r.content=="string"&&(r.content=e(r.content)),XO(r,e)}class JW{constructor(e,t,n={},i){oe(this,"provider");oe(this,"store");oe(this,"globalEvents");oe(this,"state");oe(this,"connected",!1);oe(this,"allowSkipVirtualAgent",!1);oe(this,"inEscalation",!1);oe(this,"events");oe(this,"cachedFiles");oe(this,"hooks");oe(this,"originals",new PW);oe(this,"cacheOwner",null);oe(this,"restoredMessages",new Map);oe(this,"nextTrackedSweepAt",Dy);oe(this,"destroying",!1);oe(this,"leaveSent",!1);oe(this,"beaconAttempted",!1);oe(this,"connecting",!1);oe(this,"connectEnd","none");oe(this,"outbox",null);oe(this,"sendTrackingReleased",!1);oe(this,"newestSid");oe(this,"sendFloors",new Map);oe(this,"sentAwaitingEcho",new Map);oe(this,"pairedEchoIds",new Map);oe(this,"sentFiles",new Map);oe(this,"taskStateResync",null);oe(this,"onTaskStateSignal",()=>{var e;(e=this.taskStateResync)==null||e.signal()});this.state=e,this.store=new WO,this.cachedFiles={},this.events=new sg,this.hooks=n;const s=eW(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;const i=this.inboundSanitizer();n.content=i(n.content),this.sanitizesInboundPaths()&&XO(n,i),this.noteSid(n);const s=n[qd]===!0;if(delete n[qd],this.syncCacheOwner(),n.type===xr.SERVER_MESSAGE){const a=n.server_message_id??n.message_id;t(this.id,a).then(c=>{this.destroying||(n=sW(n,c),this.sanitizesInboundPaths()&&Kb(n,i),e.triggerEvent("chat.message",n))})}else if(Ny(n.type))this.settleOwnEcho(n),this.pairSentFile(n),setTimeout(()=>{if(this.destroying)return;const a=n.$index.toString();n.file=this.cachedFiles[a],e.triggerEvent("chat.message",n)},100);else{this.settleOwnEcho(n);const a=this.restoreOwnOriginal(n);e.triggerEvent("chat.message",n),s||this.registerMessageEvents(n),a&&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=>{Yi.warn("Chat connection ended",{error:n}),this.handleConnectionEnded()}),this.on(BO,()=>{var n;(n=this.outbox)==null||n.resume()})}handleConnectionEnded(){this.connecting&&this.connectEnd==="none"&&this.surfacesSubscriptionEnd()&&(this.connectEnd=this.connected?"done":"pending"),this.connected&&this.endConnection()}endConnection(){var e;this.connected=!1,this._stopTaskStateResync(),(e=this.outbox)==null||e.failAll("disconnected"),this.triggerEvent("connectionEnded",this),this.triggerEvent("disconnected",this),this.provider&&this.provider.destroy().catch(t=>Yi.warn("provider destroy failed",{error:t}))}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 AW.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===Jn.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 OW.indexOf(this.status)!=-1}get assigned(){return zO.indexOf(this.status)!=-1}get dismissed(){return KO.indexOf(this.status)!=-1}get ended(){return $W.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===ll.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){var i;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(),this.ended&&((i=this.outbox)==null||i.failAll("chat_ended")),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(){var e;if(!this.provider)return Yi.info("connecting interrupted"),!1;this.connecting=!0,this.connectEnd="none",this.startTaskStateResync();try{if(await ZC(()=>this.provider.create(),3),await ZC(()=>this.connectEnd!=="none"?Promise.resolve():this.provider.join(this.state.provider_channel_id),3),this.settleEndedConnect())return Yi.info("connect abandoned: connection ended before it was announced"),!1;this.syncCacheOwner(),this.connected=!0;const t=await this.fetchMessages();if(this.destroying)return Yi.info("connect abandoned: chat destroyed while loading history"),!1;if(this.settleEndedConnect())return Yi.info("connect abandoned: connection ended while loading history"),!1;this.inTask&&((e=this.taskStateResync)==null||e.signal());const n={chat:this,messages:t};return this.triggerEvent("connectedMessages",n),this.triggerEvent("connected",this),this.registerProviderEvents(),Yi.info("connected with provider",this.state.provider_type),!0}catch(t){return this.settleEndedConnect(),Yi.error("Failed to connect with provider",t),!1}finally{this.connecting=!1}}async disconnect(){var e;this.connected=!1,this._stopTaskStateResync(),(e=this.outbox)==null||e.failAll("disconnected"),this.triggerEvent("disconnected",this),await this.sendLeave(),this.events.destroy(),this.provider&&(await this.provider.destroy(),Yi.info("disconnect with provider",this.state.provider_type))}async sendLeave(){var e;if(!this.leaveSent&&((e=this.state)==null?void 0:e.provider_type)===Hu.UJET&&this.hooks.leaveChat)try{await this.hooks.leaveChat(),this.leaveSent=!0}catch(t){Yi.warn("leaveChat failed",{error:t})}}leaveBeacon(){var e;this.leaveSent||this.beaconAttempted||((e=this.state)==null?void 0:e.provider_type)===Hu.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 dl(this.status);const n=await this.provider.sendMessage(e),i=((a=(s=this.hooks).isRiskFlagEnabled)==null?void 0:a.call(s,UW))??!0;return t&&(!i||n!=null&&n!=="")&&this.saveMedia(n,t),typeof n=="number"?n:-1}get tracksSends(){var e,t,n;return!this.destroying&&!this.sendTrackingReleased&&(((e=this.provider)==null?void 0:e.tracksSends)??!1)&&(((n=(t=this.hooks).isRiskFlagEnabled)==null?void 0:n.call(t,jW))??!0)}get outgoingMessages(){var e;return Object.freeze((((e=this.outbox)==null?void 0:e.snapshot())??[]).map(t=>this.statusOf(t)))}enqueueMessage(e,t,n){if(this.ended)throw new dl(this.status);this.outbox??(this.outbox=new EW({send:i=>this.provider?this.provider.publishTracked(i.payload):Promise.reject(new Error("chat destroyed")),onChange:i=>{const s=this.statusOf(i);i.status==="sent"?(this.awaitEcho(i.client_message_id,i.payload),this.saveSentFile(i)):i.status==="discarded"&&this.sendFloors.delete(i.client_message_id),i.status==="discarded"&&this.sentFiles.delete(i.client_message_id),this.triggerEvent("messageSendStatusChanged",s)},isReady:()=>{var i;return((i=this.provider)==null?void 0:i.canPublish)??!1}})),this.sendFloors.has(e)||this.sendFloors.set(e,this.newestSid),n&&!this.sentFiles.has(e)&&this.sentFiles.set(e,{file:n,type:t.type,mediaId:t.media_id}),this.outbox.enqueue(e,{...t,client_message_id:e})}saveSentFile(e){var i;const t=this.sentFiles.get(e.client_message_id),n=t&&((i=this.provider)==null?void 0:i.attachmentKeyOf(e.payload));t&&n!=null&&n!==""&&this.cachedFiles[n.toString()]!==t.file&&this.saveMedia(n,t.file)}statusOf(e){return zW(e,this.sentFiles.get(e.client_message_id))}pairSentFile(e){const t=e.client_message_id?this.sentFiles.get(e.client_message_id):this.sentFileByMediaId(e);if(!t)return;const n=e.$index;return n!=null&&n!==""&&this.cachedFiles[n.toString()]!==t.file&&this.saveMedia(n,t.file),t.file}sentFileByMediaId(e){if(!(e.media_id==null||e.$userType!==Jn.END_USER||e.$userId!==this.ownUserId)){for(const t of this.sentFiles.values())if(t.type===e.type&&t.mediaId===e.media_id)return t}}retryMessage(e){return this.ended||!this.outbox?!1:this.outbox.retry(e)}discardMessage(e){var t;return((t=this.outbox)==null?void 0:t.discard(e))??!1}settleOwnEcho(e){const t=this.outbox;if(!t)return;if(e.client_message_id){t.confirm(e.client_message_id),this.forgetSent(e.client_message_id);return}if(e.type!==xr.TEXT&&!Ny(e.type)||e.$userType!==Jn.END_USER||e.$userId!==this.ownUserId)return;const n=e.$sid!=null?this.pairedEchoIds.get(String(e.$sid)):void 0;if(n){e.client_message_id=n;return}if(this.pairLateEcho(e))return;const i=t.snapshot().find(s=>lk(s.payload,e)&&t.wasHandedOff(s.client_message_id)&&this.isAfterSend(s.client_message_id,e));i&&(Yi.warn("outbox released: own echo without client_message_id",{data:{sid:e.$sid}}),this.givePairedId(e,i.client_message_id),t.confirm(i.client_message_id),this.forgetSent(i.client_message_id),this.sendTrackingReleased=!0,t.release())}pairLateEcho(e){var n;const t=(n=[...this.sentAwaitingEcho].find(([i,s])=>lk(s.payload,e)&&this.isAfterSend(i,e)))==null?void 0:n[0];return t?(this.givePairedId(e,t),this.forgetSent(t),!0):!1}givePairedId(e,t){e.client_message_id=t,e.$sid!=null&&e.$sid!==""&&this.pairedEchoIds.set(String(e.$sid),t)}awaitEcho(e,t){var n,i,s;if(!(((i=(n=this.hooks).isRiskFlagEnabled)==null?void 0:i.call(n,qW))??!0)){this.forgetSent(e);return}clearTimeout((s=this.sentAwaitingEcho.get(e))==null?void 0:s.timer),this.sentAwaitingEcho.set(e,{payload:t,timer:setTimeout(()=>this.forgetSent(e),BW)})}forgetSent(e){var t;clearTimeout((t=this.sentAwaitingEcho.get(e))==null?void 0:t.timer),this.sentAwaitingEcho.delete(e),this.sendFloors.delete(e)}isAfterSend(e,t){const n=this.sendFloors.get(e);if(n===void 0)return!0;const i=ck(t.$sid);return i!==void 0&&i>n}noteSid(e){const t=ck(e.$sid);t!==void 0&&(this.newestSid===void 0||t>this.newestSid)&&(this.newestSid=t)}preview(e){if(!this.inTask)return this.provider.preview(e)}async fetchMessages(){var e;if(this.connected){const t=await this.store.getAllFiles(),n=await this.provider.fetchMessages(t);if(this.destroying||!this.state||!this.provider)return[];const i=this.sanitizesInboundPaths(),s=this.inboundSanitizer();for(const c of n)delete c[qd],i&&Kb(c,s);return this.syncCacheOwner(),n.forEach(c=>{if(this.noteSid(c),this.settleOwnEcho(c),!c.file&&Ny(c.type)){const o=this.pairSentFile(c);o&&(c.file=o)}}),n.filter(c=>this.restoreOwnOriginal(c)).forEach(c=>this.lookupOwnOriginal(c)),n.some(VW)&&((e=this.taskStateResync)==null||e.signal()),n}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(LW),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=Dy,e.forEach(t=>{const n=t.deref();!n||n.unredacted===void 0||(delete n.unredacted,this.triggerEvent("messageUpdated",n))})}trackRestored(e){const t=FW(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(Dy,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,VO))??!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,CW))??!0}sanitizesInboundPaths(){var e,t;return((t=(e=this.hooks).isRiskFlagEnabled)==null?void 0:t.call(e,JO))??!0}inboundSanitizer(){return YO(e=>{var t,n;return(n=(t=this.hooks).isRiskFlagEnabled)==null?void 0:n.call(t,e)})}restoreOwnOriginal(e){if(this.destroying||e.$userType!==Jn.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(!uk(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?Gw(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||!uk(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=>{Yi.warn("original lookup failed",{error:c})})}startTyping(){return this.provider.startTyping()}stopTyping(){return this.provider.stopTyping()}saveMedia(e,t){this.cachedFiles[e.toString()]=t;const n=i=>Yi.warn(`media not saved: ${e}`,{error:i});try{Promise.resolve(this.store.save(e,t)).catch(n)}catch(i){n(i)}}async destroy(){var e;this.destroying=!0,this._stopTaskStateResync(),(e=this.outbox)==null||e.destroy(),this.outbox=null,this.sendFloors.clear(),this.sentAwaitingEcho.forEach(({timer:t})=>clearTimeout(t)),this.sentAwaitingEcho.clear(),this.pairedEchoIds.clear(),this.sentFiles.clear(),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()}startTaskStateResync(){var t;(t=this.taskStateResync)==null||t.stop(),this.taskStateResync=null;const e=this.hooks.fetchTaskVaActive;e&&(this.taskStateResync=new NW(e,n=>{this.provider&&(this.provider.inTask=n)},()=>this.inTask,()=>{var n,i;return((i=(n=this.hooks).isRiskFlagEnabled)==null?void 0:i.call(n,WW))??!0},()=>!this.destroying&&!!this.provider&&this.connected&&this.ongoing),this.off(zb,this.onTaskStateSignal),this.on(zb,this.onTaskStateSignal))}_stopTaskStateResync(){var e;(e=this.taskStateResync)==null||e.stop(),this.taskStateResync=null}async clearMediaStore(){await this.store.clear()}_handleChatEndedEvent(e){var t;this.state&&((t=this.outbox)==null||t.failAll("chat_ended"),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 mr.COBROWSE_REQUESTED_FROM_AGENT:this.events.triggerEvent("_requestCobrowse","agent");break;case mr.COBROWSE_REQUESTED_FROM_END_USER:this.events.triggerEvent("_requestCobrowse","end_user");break;case mr.CHAT_DISMISSED:this.state&&(this.state.status="dismissed",this.triggerEvent("dismissed",this));break;case mr.CHAT_ENDED:this.events.triggerEvent("_chatEnded",e);break;case mr.ESCALATION_STARTED:this.inEscalation=!0;break;case mr.ESCALATION_FAILED:case mr.ESCALATION_ACCEPTED:this.inEscalation=!1;break;case mr.CHECK_IN_REQUIRED:this.events.triggerEvent("checkInRequired");break;case mr.CHECK_IN_TIMED_OUT:this.events.triggerEvent("checkInTimedOut");break}}}const ev={LOADED:"cobrowse.loaded",UPDATED:"cobrowse.updated",ENDED:"cobrowse.ended"},dk=1e4,YW=3e4,XW=9e5,QO={UPDATED:"riskFlagsUpdated"},wu=new Jr("Communicator"),QW="web-4503-base64url-jwt-decode";var Uo,ff;class ZW{constructor(e,t){oe(this,"user");oe(this,"clientEventManager");oe(this,"clientAuthenticate");oe(this,"config");oe(this,"channel");oe(this,"channelReady",!1);oe(this,"hasAuthenticated",!1);oe(this,"hasInitializedLogProxy",!1);oe(this,"queuedMessagesToBridge",[]);oe(this,"pendingBridgeRequests",{});oe(this,"bridgeIframe");oe(this,"bridgeMessageHandlers");oe(this,"tokenRefreshTimeout");oe(this,"logProxyQueue",[]);Cy(this,Uo,"");Cy(this,ff,0);oe(this,"authRefreshInFlight",null);oe(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 Ic(this,Uo);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(!Ic(this,Uo)||!((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 ${Ic(this,Uo)}`,"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 Fu))throw e;if(e.refusedBy==="client")throw e.cause;wu.error(e.message)}}isAuthTokenFresh(){return!!Ic(this,Uo)&&Ic(this,ff)-Date.now()>YW}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 Fu("Client authenticate callback rejected","client",{cause:i})}const t=await this.serverAuthenticate(e.token);if(t.error)throw new Fu("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){ky(this,Uo,e),ky(this,ff,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(QO.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=Vw()+"_"+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=ek.replace("main.api",e.tenant):t=ek);const n=e.lang||"en",i=!!((l=e.cobrowse)!=null&&l.enabled),a=(e.bridge||"https://websdk.ujet.co/v3/bridge.html")+"?6.40.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.40.0",bridge:a,bridgeOrigin:c,modules:o}}initLogProxyHandler(e){!this.hasInitializedLogProxy&&e.log_proxy_url&&(this.hasInitializedLogProxy=!0,Jr.addHandler((t,n,...i)=>{if(n==="debug")return;const s=Y6(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()-dk,dk);this.tokenRefreshTimeout=setTimeout(()=>{this.onRefreshToken()},n)}decodeJwt(e){const t=e.split(".")[1],n=this.isRiskFlagEnabled(QW)?q6:jO;return JSON.parse(n(t))}normalizeJwtExp(e){return e.toString().length===13?e:e.toString().length===10?e*1e3:Date.now()+XW}}Uo=new WeakMap,ff=new WeakMap;const eH={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"},tH={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"},rH={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"},nH={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"},iH={confirmSessionTitle:"共同ブラウジングセッションリクエスト",confirmSessionContent:"現在の画面を担当者と共有したいですか。",endSessionText:"共同ブラウジングセッションを終了",confirmRemoteControlTitle:"リモートアクセスリクエスト",confirmRemoteControlContent:"担当者は、お客様をさらにお手伝いするために、現在共有中の画面へのアクセスを希望しています。許可しますか。",confirmFullDeviceTitle:"画面共有リクエスト",confirmFullDeviceContent:"画面全体を担当者と共有したいですか。担当者は画面上で一切の操作ができません。",allowText:"許可",denyText:"拒否"},sH={confirmSessionTitle:"코브라우징 세션 요청",confirmSessionContent:"현재 화면을 상담원과 공유하시겠습니까?",endSessionText:"코브라우징 세션 종료",confirmRemoteControlTitle:"원격 액세스 요청",confirmRemoteControlContent:"상담원이 추가 지원을 위해 현재 공유된 화면에 액세스할 수 있기를 원합니다. 허용하시겠습니까?",confirmFullDeviceTitle:"화면 공유 요청",confirmFullDeviceContent:"상담원과 전체 화면을 공유하시겠습니까? 상담원은 화면의 어떤 부분도 제어할 수 없습니다.",allowText:"허용",denyText:"거절"},aH={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"},oH={confirmSessionTitle:"同步浏览会话请求",confirmSessionContent:"您是否要向该客服代表共享当前的屏幕?",endSessionText:"结束同步浏览会话",confirmRemoteControlTitle:"远程访问请求",confirmRemoteControlContent:"为了进一步协助您,客服代表想访问您当前的共享屏幕。您是否允许这样做?",confirmFullDeviceTitle:"屏幕共享请求",confirmFullDeviceContent:"您是否要向该客服代表共享全屏?客服代表将不能控制屏幕上的任何东西。",allowText:"允许",denyText:"拒绝"},uH={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"},cH={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"},lH={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ä"},dH={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"},fH={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"},hH={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"},pH={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"},vH={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"},gH={confirmSessionTitle:"ขอเซสชันเรียกดูร่วม",confirmSessionContent:"คุณต้องการแชร์หน้าจอปัจจุบันกับตัวแทนหรือไม่",endSessionText:"สิ้นสุดเซสชันเรียกดูร่วม",confirmRemoteControlTitle:"ขอการเข้าถึงระยะไกล",confirmRemoteControlContent:"ตัวแทนต้องการเข้าถึงหน้าจอของคุณที่แชร์อยู่ในปัจจุบันเพื่อให้ความช่วยเหลือคุณต่อไป คุณจะอนุญาตหรือไม่",confirmFullDeviceTitle:"ขอแชร์หน้าจอ",confirmFullDeviceContent:"คุณต้องการแชร์ทั้งหน้าของคุณกับตัวแทนหรือไม่ ตัวแทนจะไม่สามารถควบคุมอะไรบนหน้าจอ",allowText:"ยินยอม",denyText:"ปฏิเสธ"},mH={confirmSessionTitle:"طلب جلسة تصفح مشترك",confirmSessionContent:"هل تريد مشاركة شاشتك الحالية مع الموظف؟",endSessionText:"إنهاء جلسة التصفح المشترك",confirmRemoteControlTitle:"طلب التحكم عن بعد",confirmRemoteControlContent:"يرغب مسئول الدعم في رؤية شاشتك المشاركة حالياً لمساعدتك بشكلٍ أكبر. هل تسمح بذلك؟",confirmFullDeviceTitle:"طلب مشاركة الشاشة",confirmFullDeviceContent:"هل تريد مشاركة شاشتك الكاملة مع مسئول الدعم؟ لن يتمكن المسئول من التحكم في أي شيء على الشاشة.",allowText:"السماح",denyText:"الرفض"},yH={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"},_H={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"},bH={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"},SH={confirmSessionTitle:"Запрос сеанса совместного просмотра веб-страниц",confirmSessionContent:"Хотите поделиться вашим текущим экраном с представителем?",endSessionText:"Завершить сеанс совместного просмотра веб-страниц",confirmRemoteControlTitle:"Запрос на удаленный доступ",confirmRemoteControlContent:"Представитель хочет получить доступ к вашему текущему экрану, которым вы делитесь, чтобы помочь вам. Хотите разрешить это?",confirmFullDeviceTitle:"Запрос на совместный просмотр экрана",confirmFullDeviceContent:"Хотите поделиться вашим полный экраном с представителем? Агент не сможет выполнять никаких действий на экране.",allowText:"Разрешить",denyText:"Отказать"},wH={confirmSessionTitle:"सह-ब्राउज़ सत्र अनुरोध किया गया",confirmSessionContent:"क्या आप अपनी वर्तमान स्क्रीन को एजेंट के साथ साझा करना चाहते हैं?",endSessionText:"सह-ब्राउज़ सत्र समाप्त करें",confirmRemoteControlTitle:"रिमोट पहुँच का अनुरोध किया गया",confirmRemoteControlContent:"एजेंट आपकी वर्तमान साझा स्क्रीन तक पहुँच प्राप्त करना चाहेगा ताकि वह आपकी और सहायता कर सके। क्या आप इसकी अनुमति देना चाहते हैं?",confirmFullDeviceTitle:"स्क्रीन साझाकरण अनुरोध",confirmFullDeviceContent:"क्या आप अपनी पूरी स्क्रीन एजेंट के साथ साझा करना चाहते हैं? एजेंट स्क्रीन पर कुछ भी नियंत्रित नहीं कर पाएगा।",allowText:"अनुमति दें",denyText:"अस्वीकार करें"},TH={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"},EH={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"},CH={confirmSessionTitle:"Запит на сесію спільного перегляду",confirmSessionContent:"Чи Ви хочете поділитись з агентом своїм поточним екраном?",endSessionText:"Завершити сесію спільного перегляду",confirmRemoteControlTitle:"Запит на віддалений доступ",confirmRemoteControlContent:"Агент хоче отримати доступ до Вашого поточного екрану, який переглядається спільно, щоб допомогти Вам. Ви дозволяєте?",confirmFullDeviceTitle:"Запит на спільний перегляд екрану",confirmFullDeviceContent:"Чи Ви хочете поділитись з агентом своїм екраном повністю? Агент не зможе нічого на ньому контролювати.",allowText:"Дозволити",denyText:"Відмовити"},kH={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"},cd={en:eH,es:tH,"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:rH,"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:nH,ja:iH,ko:sH,it:aH,zh:oH,"zh-Hant":{confirmSessionTitle:"共同瀏覽工作階段要求",confirmSessionContent:"要與專員分享您目前的畫面嗎?",endSessionText:"結束共同瀏覽工作階段",confirmRemoteControlTitle:"遠端存取要求",confirmRemoteControlContent:"專員想要存取您目前分享的螢幕畫面以進一步協助您。要允許嗎?",confirmFullDeviceTitle:"螢幕畫面分享要求",confirmFullDeviceContent:"要與專員分享全螢幕嗎?專員將無法控制畫面上的任何項目。",allowText:"允許",denyText:"拒絕"},sv:uH,pt:cH,"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:lH,nb:dH,da:fH,nl:hH,tr:pH,vi:vH,th:gH,ar:mH,cs:yH,pl:_H,hu:bH,ru:SH,hi:wH,ro:TH,hr:EH,uk:CH,tl:kH};function RH(r){const e=r.split("-")[0];return cd[r]?r===e?cd[r]:{...cd[e],...cd[r]}:cd[e]}async function IH(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 PH(a)}function PH(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 AH=()=>typeof navigator<"u"&&/Android/.test(navigator.userAgent),OH=()=>typeof navigator<"u"&&/Chrome/.test(navigator.userAgent),ZO=()=>typeof navigator>"u"?!1:/Android|iPhone|iPad|iPod/.test(navigator.userAgent)?!0:navigator.platform==="MacIntel"&&(navigator.maxTouchPoints??0)>1,Ly=()=>OH()&&!AH();function fk(r){return r.chats=r.chats.map(e=>{const t=e.entries.map((n,i)=>$H(n,`${e.comm_id}-${i}`));return e.entries=aW(t),e}),r}function $H(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 xH={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 MH(r){var t,n;return{languages:r.languages.filter(i=>i.enabled).map(i=>({lang:i.lang,name:i.name,localeName:xH[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 e$(r){return r.map(DH).filter(e=>e.enabled)}function DH(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=NH(r);if(t&&(e.redirection=r.redirection),r.children&&r.children.length){const n=e$(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}=LH(r.channels);e.deflection=i,t||(e.channels=n),e.enabled=n.length>0||t}return e}function NH(r){let e=!1;const t=r.redirection;return t&&(t.option==="message"||t.option==="url")&&(e=!!t.data),e}function LH(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:yv.INBOUND_CALL}),r.voice_call&&r.voice_call.deflected&&r.voice_call.voicemail_reason&&i({...r.voice_call,type:yv.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 FH="ujet_voice_call",t$="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"},Jw=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)},UH=(r,e)=>!!r&&typeof r=="object"&&"code"in r&&r.code===e,r$=r=>{if(r&&typeof r=="object"&&"status"in r){const e=r.status;if(typeof e=="number")return e}};class Ts extends Error{constructor(t,n,i){super(t,i!==void 0?{cause:i}:void 0);oe(this,"code");this.name="VoiceCallError",this.code=n,i!==void 0&&(this.cause=i)}}const Kv=class Kv extends Ts{constructor(e="End user has a call in progress"){super(e,Kv.CODE),this.name="CallInProgressError"}};oe(Kv,"CODE","CALL_IN_PROGRESS");let Vu=Kv;const Jv=class Jv extends Ts{constructor(e="Inbound voice is disabled for this menu"){super(e,Jv.CODE),this.name="InboundDisabledError"}};oe(Jv,"CODE","INBOUND_DISABLED");let fl=Jv;const Yv=class Yv extends Ts{constructor(e="Outside operation hours"){super(e,Yv.CODE),this.name="OperationHoursError"}};oe(Yv,"CODE","OPERATION_HOURS");let Gu=Yv;const Xv=class Xv extends Ts{constructor(e="Inbound voice feature is not enabled for this tenant"){super(e,Xv.CODE),this.name="FeatureNotEnabledError"}};oe(Xv,"CODE","FEATURE_NOT_ENABLED");let hl=Xv;const Qv=class Qv extends Ts{constructor(e="Microphone permission denied",t){super(e,Qv.CODE,t),this.name="MicPermissionDeniedError"}};oe(Qv,"CODE","MIC_PERMISSION_DENIED");let pl=Qv;const Zv=class Zv extends Ts{constructor(e="No active voice call"){super(e,Zv.CODE),this.name="NoActiveVoiceCallError"}};oe(Zv,"CODE","NO_ACTIVE_VOICE_CALL");let Fo=Zv;const eg=class eg extends Ts{constructor(e="A voice call is active in another tab"){super(e,eg.CODE),this.name="AnotherTabVoiceCallError"}};oe(eg,"CODE","ANOTHER_TAB_VOICE_CALL");let vl=eg;const tg=class tg extends Ts{constructor(e,t){super(e,tg.CODE,t),this.name="ProviderError"}};oe(tg,"CODE","PROVIDER_ERROR");let fa=tg;const Qc=class Qc extends Ts{constructor(e,t){super(e,Qc.CODE,t),this.name="SmartActionError"}get isAlreadyEnded(){return this.message===Qc.ENDED_MESSAGE}};oe(Qc,"CODE","SMART_ACTION_ERROR"),oe(Qc,"ENDED_MESSAGE","smart action is already ended");let ii=Qc;const rg=class rg extends Ts{constructor(e,t){super(`Unrecognized voice error: ${e}`,rg.CODE,t),this.name="UnknownVoiceError"}};oe(rg,"CODE","UNKNOWN_VOICE_ERROR");let bv=rg;const jH=r=>r instanceof Gu||r instanceof fl||r instanceof hl||r instanceof Vu,qa=new Jr("BackgroundKeepAlive");class BH{constructor(e={}){oe(this,"active",!1);oe(this,"currentAgentName",null);oe(this,"wakeLock",null);oe(this,"audioCtx",null);oe(this,"silentSource",null);oe(this,"visibilityListener",null);oe(this,"pagehideListener",null);oe(this,"pageshowListener",null);oe(this,"resumeListener",null);oe(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){qa.debug("onCleanup threw during unload",n)}this.stop().catch(n=>qa.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=>qa.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){qa.debug("wakeLock.request failed",t)}}async releaseWakeLock(){if(this.wakeLock){try{await this.wakeLock.release()}catch(e){qa.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){qa.debug("mediaSession.metadata set failed",n)}}clearMediaSession(){if(typeof navigator>"u")return;const e=navigator.mediaSession;if(e)try{e.metadata=null}catch(t){qa.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){qa.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=>qa.debug("audioCtx.close failed",s)),this.audioCtx=null}}const vs={CONNECTED:"voice:internal:connected",DISCONNECTED:"voice:internal:disconnected",ERROR:"voice:internal:error"},n$="_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"},Hc=new Set(["finished","failed","canceled","timeout","recovered","voicemail"]),Fy=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 qH{constructor(e){oe(this,"_status");this._status=e}get status(){return this._status}get isTerminal(){return Hc.has(this._status)}transitionTo(e){if(this.isTerminal)return null;const t=this._status;return this._status=e,t}}const Uy="ujet:",Sr={set(r,e){try{localStorage.setItem(Uy+r,e)}catch{}},get(r){try{return localStorage.getItem(Uy+r)}catch{return null}},del(r){try{localStorage.removeItem(Uy+r)}catch{}}},Sv="voice",WH=r=>{Sr.set(Sv,String(r))},hk=()=>{const r=Sr.get(Sv);if(!r)return null;const e=Number(r);return Number.isFinite(e)&&e>0?e:(Sr.del(Sv),null)},Vc=()=>{Sr.del(Sv)},HH=new Set(["connected","va_connected"]),jy=r=>HH.has(r),VH=new Set(["finished","canceled","expired"]),GH=[Kn.RECONNECTING,Kn.RECONNECTED,Kn.CONNECTION_QUALITY];class zH{constructor(e,t,n,i,s){oe(this,"_state");oe(this,"_publicState",null);oe(this,"events");oe(this,"provider");oe(this,"methods");oe(this,"globalEvents");oe(this,"logger");oe(this,"destroyed",!1);oe(this,"isProviderConnected",!1);oe(this,"isUnloading",!1);oe(this,"startedAt",null);oe(this,"fetchEpoch",0);oe(this,"keepAlive",null);oe(this,"stateMachine");oe(this,"handledSmartActionIds",new Set);oe(this,"smartActionQueue",[]);oe(this,"currentCobrowseSmartActionId",null);oe(this,"recordingPermissionAsked",!1);oe(this,"speakerOn",!1);oe(this,"cobrowseStarter");this._state=e,this.methods=t,this.events=new sg,this.logger=new Jr(`VoiceCall:${e.id}`),this.provider=new n(this.events,e,t.issueToken),this.globalEvents=i,this.cobrowseStarter=s,this.stateMachine=new qH(e.status),jy(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:Fy(e),prevStatus:Fy(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 Fy(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=>!VH.has(n.status));for(const n of e)this.handleSmartActionRequested(n);this.keepAlive=new BH({onCleanup:()=>{this.isUnloading=!0;const n=this._state.status;jy(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=jy(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 fa("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 ii("uploadVideos not configured");await this.methods.uploadVideos(this.id,t,e)}else{if(!this.methods.uploadPhotos)throw new ii("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 ii("call destroyed");if(t==="video"){if(!this.methods.uploadOneVideo)throw new ii("uploadOneVideo not configured");return{ref:await this.methods.uploadOneVideo(this.id,e,n),kind:t}}if(!this.methods.uploadOnePhoto)throw new ii("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 ii("call destroyed");if(n.length===0)throw new ii("submitMediaRefsForSmartAction called with empty refs");const i=n.find(a=>a.kind!==t);if(i)throw new ii(`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 ii("registerVideos not configured");await this.methods.registerVideos(this.id,s,e)}else{if(!this.methods.registerPhotos)throw new ii("registerPhotos not configured");await this.methods.registerPhotos(this.id,t,s,e)}this.markSmartActionHandled(e)}registerProviderEvents(){this.events.addEventListener(vs.CONNECTED,async()=>{this.destroyed||(await this.fetchAndUpdateState(),!(this.destroyed||this._state.status==="finished")&&(this.startedAt=this.resolveStartedAtFromState()))}),this.events.addEventListener(vs.DISCONNECTED,()=>{this.destroyed||this.stateMachine.isTerminal||(this.isProviderConnected=!1,this.setStatus("finished"),this.fetchAndUpdateState())}),this.events.addEventListener(vs.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 GH)this.events.addEventListener(e,t=>{this.globalEvents.triggerEvent(e,t)});this.events.addEventListener(n$,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}}),!Hc.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 ii("updateSmartAction not configured");try{await this.methods.updateSmartAction(this.id,e,t),this.markSmartActionHandled(e)}catch(n){const i=Jw(n);if(i===ii.ENDED_MESSAGE){this.markSmartActionHandled(e);return}throw new ii(i,n)}}}class Yw{constructor(e,t,n){oe(this,"events");oe(this,"state");oe(this,"issueVoiceToken");this.events=e,this.state=t,this.issueVoiceToken=n}getRemoteStream(){return null}sendMessage(e){return null}}oe(Yw,"type","base");const i$={},s$=r=>{i$[r.type]=r},a$=r=>i$[r],Uh=new Jr("methods"),pk=!0,KH="web-4191-refresh-unknown-chat-agent";class JH{constructor(e,t,n,i){oe(this,"request");oe(this,"lastDapRequestId",null);oe(this,"lastDirectAccessKeyId",null);oe(this,"dapPollGeneration",0);oe(this,"beaconLeaveChat");oe(this,"authContext");oe(this,"isRiskFlagEnabled");oe(this,"getCustomFormData",async e=>{const t=`forms/${e}/details`;try{return await this.get(t)}catch(n){Uh.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 MH(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:Uh.warn("unexpected /menus response shape; rendering an empty menu list"),{menus:e$(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 Uh.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 tf(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:pk})).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===ll.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 fk(t)}else{const{data:t}=await this.get(`/chats/histories?page=${e}&per_page=1`);return fk(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};Ly()&&(a.file=await Jb(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=h=>this.getChatMessageOriginal(e.id,h),c=async()=>(await this.getChat(e.id)).task_virtual_agent_active,o=new JW(e,n,{leaveChat:i,leaveChatBeacon:s,isRiskFlagEnabled:this.isRiskFlagEnabled,fetchMessageOriginal:a,fetchTaskVaActive:c},this.buildProviderContext(e.id)),l=async h=>{if(o.status==="va_assigned"){const p=await this.getSkipVirtualAgentSettings(o.menuId,o.lang);o.allowSkipVirtualAgent=p,o.update(h)}};o.on("initialized",async()=>{if(o.status==="queued"){const h=await this.getChat(o.id);o.update(h)}}),o.on("memberJoined",async()=>{const h=await this.getChat(o.id);o.update(h)}),o.on("memberLeft",async()=>{const h=await this.getChat(o.id);o.update(h)});let d=!1;if(o.on("message",h=>{var p;!o.connected||!o.ongoing||d||h.$userType!==Jn.USER||!Number.isSafeInteger(h.$userId)||h.$userId<=0||o.allAgents.human.some(y=>y.id===h.$userId)||((p=this.isRiskFlagEnabled)==null?void 0:p.call(this,KH))===!1||(d=!0,this.getChat(o.id).then(y=>{o.connected&&o.ongoing&&o.update(y)}).catch(()=>{Uh.warn("Unable to refresh chat agents after an unknown human message")}).finally(()=>{d=!1}))}),o.on("_chatEnded",async h=>{const p=await this.getChat(o.id);o.update(p),(!o.state||o.ended)&&o._handleChatEndedEvent(h)}),o.on("_menuChanged",async h=>{const p=await this.getChat(h.id);l(p)}),o.on("checkInRequired",async()=>{const h=await this.getChat(o.id);o.update(h)}),o.on("checkInTimedOut",async()=>{const h=await this.getChat(o.id);o.update(h)}),o.channelId)o.connect(),l(e);else{let h;for(;!h;)await this.getChat(o.id).then(p=>{p.provider_channel_id&&o.state?(h=!0,o.update(p),o.connect(),l(p)):(p.status==="canceled"||p.status==="finished")&&(h=!0)}),h||await tf(1500)}return o}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(ZO())return await IH(s.data.url,t,s.data.fields,n);const a={file:t,fields:s.data.fields};return Ly()&&(a.file=await Jb(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,$,F)=>await this.failVoiceCall(L,$,F),l=async L=>await this.escalateVoiceCall(L),d=async(L,$)=>await this.updateVoiceCallRecordingPermission(L,$),h=async(L,$,F)=>await this.updateVoiceSmartAction(L,$,F),p=async(L,$,F,G)=>{await this.uploadVoiceCallPhotos(L,$,F,G)},y=async(L,$,F)=>{await this.uploadVoiceCallVideos(L,$,F)},w=async(L,$,F)=>await this.uploadVoiceCallPhotoSingle(L,$,F),k=async(L,$,F)=>await this.uploadVoiceCallVideoSingle(L,$,F),P=async(L,$,F,G)=>{await this.registerVoiceCallPhotos(L,$,F,G)},A=async(L,$,F)=>{await this.registerVoiceCallVideos(L,$,F)},B=a$(this.resolveVoiceProviderType(e));if(!B)throw new fa(`No voice provider registered for ${e.voip_provider}`);return new zH(e,{issueToken:s,fetchCall:a,finishCall:c,failCall:o,escalateCall:l,updateRecordingPermission:d,updateSmartAction:h,uploadPhotos:p,uploadVideos:y,uploadOnePhoto:w,uploadOneVideo:k,registerPhotos:P,registerVideos:A},B,n,i)}resolveVoiceProviderType(e){return e.voip_provider==="voip_provider_twilio"?t$: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:pk,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&&Ly()?i["email_attachments[]"]=await YH(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 YH(r){return Promise.all(r.map(Jb))}function Jb(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 o$=new Jr("CobrowseService");async function XH(r){return window.CobrowseIO?window.CobrowseIO:await QH(r)}async function QH(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(){o$.error("Failed to load cobrowse script",r),e(null)}})}const vk="https://js.cobrowse.io/CobrowseIO.js";function ZH(r){return!r||r.toLowerCase()==="https://cobrowse.io"?vk:r.toLowerCase().startsWith("https://")?`${r}/sdk-js/CobrowseIO.js`:(o$.warn("customCobrowseDomain must use HTTPS; falling back to default",{cobrowseDomain:r}),vk)}async function eV(r,e){let t=r.instance;if(!t){const n=ZH(e);t=await XH(n)}return new tV(t,r)}class tV{constructor(e,t){oe(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 rV=Date.now(),u$={href:window.location.href,interval:24*60*60};function nV(r){if(!Array.isArray(r)||!r.length)return null;const e=uV(),t=e===0,n=e+1;return cV(n),r.filter(s=>{const a=sV(s,u$.href),c=aV(s.visitor_type,t),o=n>=s.page_visit_count,l=!oV(s.id);return a&&c&&o&&l}).sort((s,a)=>s.stay_time-a.stay_time)[0]||null}function iV(r,e){const t=r.stay_time*1e3,n=Math.max(t-(Date.now()-rV),0);setTimeout(()=>{e(r),Sr.set(`trigger:${r.id}`,(Date.now()/1e3).toString())},n)}const sV=(r,e)=>{const{keywords_included_or:t=[],keywords_excluded_or:n=[],keywords_included:i=[],keywords_excluded:s=[]}=r;if(H6(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 aV(r,e){return r==="visitor_type_new"?e:r==="visitor_type_returning"?!e:!0}function oV(r){try{const e=parseInt(Sr.get(`trigger:${r}`),10);return Date.now()/1e3-e<u$.interval}catch(e){return console.error("Couldn't parse trigger time",e),!1}}function uV(){try{const r=Sr.get("visits");return r?parseInt(r,10):0}catch(r){return console.error("Couldn't get visit count",r),0}}function cV(r){try{Sr.set("visits",r.toString())}catch(e){console.error(e)}}function lV(r){return r.replace(/\/+$/,"")}const By=new Jr("VoiceMultiTab"),Yb="voice:tab-lock",dV=5e3,fV=2e3,hV=250,qy=()=>{const r=Sr.get(Yb);if(!r)return null;try{return JSON.parse(r)}catch{return null}},Wy=()=>{var i;const r=qy();if(r&&typeof r.ts=="number"&&Date.now()-r.ts<dV)throw new vl;const e=Vw(),t=()=>{Sr.set(Yb,JSON.stringify({id:e,ts:Date.now()}))};if(t(),((i=qy())==null?void 0:i.id)!==e)throw new vl;const n=setInterval(t,fV);return{release(){clearInterval(n);const s=qy();(!s||s.id===e)&&Sr.del(Yb)}}},gk=async()=>{if(typeof BroadcastChannel>"u")return Wy();let r;try{r=new BroadcastChannel(FH)}catch{return Wy()}const e=Vw();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){By.debug("BC postMessage(claim) failed; falling back to localStorage path",n);try{r.close()}catch{}return Wy()}if(await new Promise(n=>setTimeout(n,hV)),t)throw r.close(),new vl;return r.onmessage=n=>{const i=n.data;if(i.kind==="claim"&&i.id!==e)try{r.postMessage({kind:"present",id:e})}catch(s){By.debug("BC postMessage(present) failed",s)}},{release(){try{r.postMessage({kind:"release",id:e})}catch(n){By.debug("BC postMessage(release) failed",n)}r.close()}}},pV=["photo","video","audio","document"],oa=new Jr("client");function vV(r){const e=r==null?void 0:r.status;return typeof e=="number"&&e>=400&&e<500}let gV=class{constructor(e){oe(this,"VERSION",zw);oe(this,"options");oe(this,"communicator");oe(this,"methods");oe(this,"events",new sg);oe(this,"request");oe(this,"chat");oe(this,"_cobrowse");oe(this,"_voiceCall",null);oe(this,"_voiceTabLock",null);oe(this,"redactionSendQueue",Promise.resolve());oe(this,"fileSendQueue",Promise.resolve());oe(this,"noCryptoLogged",!1);oe(this,"_rehydratePromise",null);oe(this,"onPageHide");oe(this,"onPageShow");this.options=e.host?{...e,host:lV(e.host)}:e,this.communicator=new ZW(this.options,this.events);const t=this.communicator.request.bind(this.communicator),n=this.communicator.leaveChatBeacon.bind(this.communicator);this.methods=new JH(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&&$O.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:Sr.get("lang")||"en"}set lang(e){this.options.lang||Sr.set("lang",e)}get cobrowse(){return this._cobrowse.cobrowseIO}get cobrowseEnabled(){var e;return!!((e=this.options.cobrowse)!=null&&e.enabled)}destroy(){var e;(e=this.chat)==null||e._stopTaskStateResync(),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=nV(t);n&&iV(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&&Sr.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):(Sr.del("chat"),Sr.del("cobrowse")),t}catch(t){throw Sr.del("chat"),Sr.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=Sr.get("chat");if(!e)return Sr.del("chat"),null;try{const t=await this.loadChat(e);return t&&t.ongoing?t:(Sr.del("chat"),null)}catch(t){throw Sr.del("chat"),t}}async restoreCobrowseSession(){var t;const e=Sr.get("cobrowse");if(!(!e||!((t=this.options.cobrowse)!=null&&t.enabled)))try{await this.initializeCobrowse(this.lang),oa.debug("cobrowse session restored with nonce:",e)}catch(n){oa.error("Failed to restore cobrowse session",n),Sr.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===ll.FINISHED||e===ll.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){oa.warn("finishChat during destroy failed",{error:e})}await this.chat.destroy(),this.chat=null,zn.trackerId=""}}get voiceCall(){return this._voiceCall}hasStoredVoiceCall(){return hk()!==null}async startVoiceCall(e,t={}){var i;if(this._voiceCall&&!Hc.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 mV()}catch(s){const a=s instanceof pl?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 gk();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(),mk(s)}this._voiceCall=n;try{await n._connect()}catch(s){throw await n._destroy().catch(()=>{}),this._voiceCall=null,this.releaseVoiceTabLock(),s}return WH(n.id),n}async loadVoiceCall(e){if(this._voiceCall&&!Hc.has(this._voiceCall.serverStatus()))return this._voiceCall;let t=null;if(e!==void 0?t=Number(e):t=hk(),t===null)return null;this.releaseVoiceTabLock(),this._voiceTabLock=await gk();let n;try{n=await this.methods.fetchVoiceCall(t)}catch(s){if(r$(s)===404)return Vc(),this.releaseVoiceTabLock(),null;throw this.releaseVoiceTabLock(),mk(s)}if(Hc.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=>{oa.warn("cobrowse restore failed during voice restore",s)}),i}async endVoiceCall(){this._voiceCall&&(Hc.has(this._voiceCall.serverStatus())||await this._voiceCall._abandonOrFinish())}async escalateVoiceCall(){if(!this._voiceCall)throw new Fo;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 Fo;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 Fo;return await this.methods.getVoiceCallSurvey(this._voiceCall.id)}async submitVoiceCallSurvey(e){if(!this._voiceCall)throw new Fo;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);uW(e,t)}catch(t){oa.warn("[fetchMessages] Failed to fetch chat documents",t)}if(e.filter(t=>t.type===xr.SERVER_MESSAGE).length>0){const t=await this.methods.listChatTaskMessages(this.chat.id);return this.sanitizeFetchedMessages(iW(e,t))}return this.sanitizeFetchedMessages(e)}catch{return[]}}sanitizeFetchedMessages(e){if(this.communicator.isRiskFlagEnabled(JO)){const t=YO(n=>this.communicator.isRiskFlagEnabled(n));e.forEach(n=>Kb(n,t))}return e}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 oa.warn("[sendFileMessage] upload failed",s),-1}if(this.chat.tracksSends&&!this.chat.inTask&&!this.chat.state.redaction_enabled){const s=xy();if(s)return this.chat.enqueueMessage(s,i,e),-1;this.warnNoCrypto()}return this.chat.sendMessage(i,e)});return this.fileSendQueue=n.catch(()=>{}),await n}async sendTextMessage(e){const t=Gw(e);if(t){if(this.chat.inTask){const n=await this.methods.sendChatTaskMessage(this.chat.id,t);this.chat.sendMessage({type:xr.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=xy();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&&vV(c)&&n.forgetOwnOriginal(s),c}return}if(this.chat.tracksSends){const n=xy();if(n)return this.chat.enqueueMessage(n,{type:xr.TEXT,content:t}),n;this.warnNoCrypto()}this.chat.sendMessage({type:xr.TEXT,content:t})}}warnNoCrypto(){this.noCryptoLogged||(this.noCryptoLogged=!0,oa.warn("outbox disabled: no crypto"))}retryMessage(e){var t;return((t=this.chat)==null?void 0:t.retryMessage(e))??!1}discardMessage(e){var t;return((t=this.chat)==null?void 0:t.discardMessage(e))??!1}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=Sr.get("cobrowse");i||(i=Date.now().toString(),Sr.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=Sr.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 Fo;const n=this._voiceCall.id,i={callId:`call_${n}`},s=await this.createCobrowseCode(e||this.lang,i);if(!s)return"";const a=Sr.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!==Jn.END_USER&&pV.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=Jr.logHistory.toArray();return{bridgeLogs:e,rootLogs:t}}async printLogs(){const e=await this.getLogs();console.log("Printing bridge logs:"),e.bridgeLogs.forEach(t=>{Jr.printLogHistoryData(t)}),console.log("Printing root logs:"),e.rootLogs.forEach(t=>{Jr.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||RH(e),i={...this.options.cobrowse,messages:n,lang:e};this._cobrowse=await eV(i,t.cobrowse_domain),await this._cobrowse.start(),[["session.loaded",ev.LOADED],["session.updated",ev.UPDATED],["session.ended",ev.ENDED]].forEach(([a,c])=>{this.cobrowse.on(a,o=>{this.events.triggerEvent(c,o)})}),oa.debug("cobrowse has been initialized"),this.events.triggerEvent("cobrowse.initialized",this._cobrowse)}}registerOngoingChat(e){this.chat&&this.chat!==e&&this.chat._stopTaskStateResync(),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=>{oa.error("Failed to initialize cobrowse on request",n)}),this.events.triggerEvent("cobrowse.request",{from:t})}),e.on("disconnected",()=>{Sr.del("chat"),Sr.del("cobrowse")}),this.chat=e,zn.trackerId=`chat_${e.id}`,Sr.set("chat",e.id.toString()),e.cobrowsable&&Sr.get("cobrowse")&&this.initializeCobrowse(e.lang).catch(t=>{oa.error("Failed to initialize cobrowse for ongoing chat",t)})}_triggerEvent(e,t){this.events.triggerEvent(e,t)}};const mV=async()=>{var r;if(typeof navigator>"u"||!((r=navigator.mediaDevices)!=null&&r.getUserMedia))throw new pl("Browser does not support microphone access");try{(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(t=>t.stop())}catch(e){throw new pl(Jw(e),e)}},yV=new Map([["call_in_progress",Vu],["inbound_disabled",fl],["outside_operation_hours",Gu],["operation_hours",Gu],["feature_not_enabled",hl],["invalid_call_type",hl]]),_V=new Map([[409,Gu],[403,fl],[400,Vu]]),mk=r=>{var a,c;if(r instanceof Ts)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?yV.get(t):void 0;if(i)return new i(n);const s=e.status!==void 0?_V.get(e.status):void 0;return s?new s(n):new bv(n,r)};var Ye=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ag(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}function c$(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 Xb={exports:{}},Zo=wv;function wv(){}wv.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}};wv.mixin(wv);var l$={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,p=arguments.length,y;h<p;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 p=d.methodFactory,y=d.name||"",w=s[y]||s[""]||n;function k(P,A,B){var L=p(P,A,B),$=s[B]||s[""],F=$.template.indexOf("%t")!==-1,G=$.template.indexOf("%l")!==-1,K=$.template.indexOf("%n")!==-1;return function(){for(var D="",he=arguments.length,X=Array(he),ve=0;ve<he;ve++)X[ve]=arguments[ve];if(y||!s[B]){var Q=$.timestampFormatter(new Date),Oe=$.levelFormatter(P),He=$.nameFormatter(B);$.format?D+=$.format(Oe,He,Q):(D+=$.template,F&&(D=D.replace(/%t/,Q)),G&&(D=D.replace(/%l/,Oe)),K&&(D=D.replace(/%n/,He))),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})})(l$);var bV=l$.exports,d$={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 p(k,P,A){return l(k)||h.apply(this,arguments)}function y(k,P){var A=this,B,L,$,F="loglevel";typeof k=="string"?F+=":"+k:typeof k=="symbol"&&(F=void 0);function G(ve){var Q=(i[ve]||"silent").toUpperCase();if(!(typeof window===t||!F)){try{window.localStorage[F]=Q;return}catch{}try{window.document.cookie=encodeURIComponent(F)+"="+Q+";"}catch{}}}function K(){var ve;if(!(typeof window===t||!F)){try{ve=window.localStorage[F]}catch{}if(typeof ve===t)try{var Q=window.document.cookie,Oe=encodeURIComponent(F),He=Q.indexOf(Oe+"=");He!==-1&&(ve=/^([^;]+)/.exec(Q.slice(He+Oe.length+1))[1])}catch{}return A.levels[ve]===void 0&&(ve=void 0),ve}}function D(){if(!(typeof window===t||!F)){try{window.localStorage.removeItem(F)}catch{}try{window.document.cookie=encodeURIComponent(F)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function he(ve){var Q=ve;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: "+ve)}A.name=k,A.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},A.methodFactory=P||p,A.getLevel=function(){return $??L??B},A.setLevel=function(ve,Q){return $=he(ve),Q!==!1&&G($),d.call(A)},A.setDefaultLevel=function(ve){L=he(ve),K()||A.setLevel(ve,!1)},A.resetLevel=function(){$=null,D(),d.call(A)},A.enableAll=function(ve){A.setLevel(A.levels.TRACE,ve)},A.disableAll=function(ve){A.setLevel(A.levels.SILENT,ve)},A.rebuild=function(){if(a!==A&&(B=he(a.getLevel())),d.call(A),a===A)for(var ve in s)s[ve].rebuild()},B=he(a?a.getLevel():"WARN");var X=K();X!=null&&($=he(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})})(d$);var Yr=d$.exports;const SV=ag(Yr),wV=v6({__proto__:null,default:SV},[Yr]);var Qb={exports:{}},TV={"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=TV,n=Yr;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}})(Qb,Qb.exports);var Es=Qb.exports,Zb={exports:{}},Xw={},og={},eo={},hf={},va={},pf={},ro={},kl={},vf={},ga={};Object.defineProperty(ga,"__esModule",{value:!0});ga.ERROR_PACKET=ga.PACKET_TYPES_REVERSE=ga.PACKET_TYPES=void 0;const _a=Object.create(null);ga.PACKET_TYPES=_a;_a.open="0";_a.close="1";_a.ping="2";_a.pong="3";_a.message="4";_a.upgrade="5";_a.noop="6";const f$=Object.create(null);ga.PACKET_TYPES_REVERSE=f$;Object.keys(_a).forEach(r=>{f$[_a[r]]=r});const EV={type:"error",data:"parser error"};ga.ERROR_PACKET=EV;Object.defineProperty(vf,"__esModule",{value:!0});vf.encodePacket=void 0;vf.encodePacketToBinary=kV;const CV=ga,h$=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",p$=typeof ArrayBuffer=="function",v$=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r&&r.buffer instanceof ArrayBuffer,g$=({type:r,data:e},t,n)=>h$&&e instanceof Blob?t?n(e):yk(e,n):p$&&(e instanceof ArrayBuffer||v$(e))?t?n(e):yk(new Blob([e]),n):n(CV.PACKET_TYPES[r]+(e||""));vf.encodePacket=g$;const yk=(r,e)=>{const t=new FileReader;return t.onload=function(){const n=t.result.split(",")[1];e("b"+(n||""))},t.readAsDataURL(r)};function _k(r){return r instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let Hy;function kV(r,e){if(h$&&r.data instanceof Blob)return r.data.arrayBuffer().then(_k).then(e);if(p$&&(r.data instanceof ArrayBuffer||v$(r.data)))return e(_k(r.data));g$(r,!1,t=>{Hy||(Hy=new TextEncoder),e(Hy.encode(t))})}var ug={},gl={};Object.defineProperty(gl,"__esModule",{value:!0});gl.decode=gl.encode=void 0;const Gc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Od=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let r=0;r<Gc.length;r++)Od[Gc.charCodeAt(r)]=r;const RV=r=>{let e=new Uint8Array(r),t,n=e.length,i="";for(t=0;t<n;t+=3)i+=Gc[e[t]>>2],i+=Gc[(e[t]&3)<<4|e[t+1]>>4],i+=Gc[(e[t+1]&15)<<2|e[t+2]>>6],i+=Gc[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};gl.encode=RV;const IV=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=Od[r.charCodeAt(n)],a=Od[r.charCodeAt(n+1)],c=Od[r.charCodeAt(n+2)],o=Od[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};gl.decode=IV;Object.defineProperty(ug,"__esModule",{value:!0});ug.decodePacket=void 0;const jh=ga,PV=gl,AV=typeof ArrayBuffer=="function",OV=(r,e)=>{if(typeof r!="string")return{type:"message",data:m$(r,e)};const t=r.charAt(0);return t==="b"?{type:"message",data:$V(r.substring(1),e)}:jh.PACKET_TYPES_REVERSE[t]?r.length>1?{type:jh.PACKET_TYPES_REVERSE[t],data:r.substring(1)}:{type:jh.PACKET_TYPES_REVERSE[t]}:jh.ERROR_PACKET};ug.decodePacket=OV;const $V=(r,e)=>{if(AV){const t=(0,PV.decode)(r);return m$(t,e)}else return{base64:!0,data:r}},m$=(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=vf;Object.defineProperty(r,"encodePacket",{enumerable:!0,get:function(){return e.encodePacket}});const t=ug;Object.defineProperty(r,"decodePacket",{enumerable:!0,get:function(){return t.decodePacket}});const n=ga,i="",s=(p,y)=>{const w=p.length,k=new Array(w);let P=0;p.forEach((A,B)=>{(0,e.encodePacket)(A,!1,L=>{k[B]=L,++P===w&&y(k.join(i))})})};r.encodePayload=s;const a=(p,y)=>{const w=p.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(p,y){(0,e.encodePacketToBinary)(p,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))}p.data&&typeof p.data!="string"&&(P[0]|=128),y.enqueue(P),y.enqueue(w)})}})}let o;function l(p){return p.reduce((y,w)=>y+w.length,0)}function d(p,y){if(p[0].length===y)return p.shift();const w=new Uint8Array(y);let k=0;for(let P=0;P<y;P++)w[P]=p[0][k++],k===p[0].length&&(p.shift(),k=0);return p.length&&k<p[0].length&&(p[0]=p[0].slice(k)),w}function h(p,y){o||(o=new TextDecoder);const w=[];let k=0,P=-1,A=!1;return new TransformStream({transform(B,L){for(w.push(B);;){if(k===0){if(l(w)<1)break;const $=d(w,1);A=($[0]&128)===128,P=$[0]&127,P<126?k=3:P===126?k=1:k=2}else if(k===1){if(l(w)<2)break;const $=d(w,2);P=new DataView($.buffer,$.byteOffset,$.length).getUint16(0),k=3}else if(k===2){if(l(w)<8)break;const $=d(w,8),F=new DataView($.buffer,$.byteOffset,$.length),G=F.getUint32(0);if(G>Math.pow(2,21)-1){L.enqueue(n.ERROR_PACKET);break}P=G*Math.pow(2,32)+F.getUint32(4),k=3}else{if(l(w)<P)break;const $=d(w,P);L.enqueue((0,t.decodePacket)(A?$:o.decode($),y)),k=0}if(P===0||P>p){L.enqueue(n.ERROR_PACKET);break}}}})}r.protocol=4})(kl);function bi(r){if(r)return xV(r)}function xV(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 MV=Object.freeze(Object.defineProperty({__proto__:null,Emitter:bi},Symbol.toStringTag,{value:"Module"})),Rl=c$(MV);var Ys={},Li={};Object.defineProperty(Li,"__esModule",{value:!0});Li.defaultBinaryType=Li.globalThisShim=Li.nextTick=void 0;Li.createCookieJar=DV;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 DV(){}Object.defineProperty(Ys,"__esModule",{value:!0});Ys.pick=NV;Ys.installTimerFunctions=UV;Ys.byteLength=BV;Ys.randomString=WV;const No=Li;function NV(r,...e){return e.reduce((t,n)=>(r.hasOwnProperty(n)&&(t[n]=r[n]),t),{})}const LV=No.globalThisShim.setTimeout,FV=No.globalThisShim.clearTimeout;function UV(r,e){e.useNativeTimers?(r.setTimeoutFn=LV.bind(No.globalThisShim),r.clearTimeoutFn=FV.bind(No.globalThisShim)):(r.setTimeoutFn=No.globalThisShim.setTimeout.bind(No.globalThisShim),r.clearTimeoutFn=No.globalThisShim.clearTimeout.bind(No.globalThisShim))}const jV=1.33;function BV(r){return typeof r=="string"?qV(r):Math.ceil((r.byteLength||r.size)*jV)}function qV(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 WV(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}var gf={};Object.defineProperty(gf,"__esModule",{value:!0});gf.encode=HV;gf.decode=VV;function HV(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function VV(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 eS={exports:{}},Vy,bk;function GV(){if(bk)return Vy;bk=1;var r=1e3,e=r*60,t=e*60,n=t*24,i=n*7,s=n*365.25;Vy=function(d,h){h=h||{};var p=typeof d;if(p==="string"&&d.length>0)return a(d);if(p==="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 p=parseFloat(h[1]),y=(h[2]||"ms").toLowerCase();switch(y){case"years":case"year":case"yrs":case"yr":case"y":return p*s;case"weeks":case"week":case"w":return p*i;case"days":case"day":case"d":return p*n;case"hours":case"hour":case"hrs":case"hr":case"h":return p*t;case"minutes":case"minute":case"mins":case"min":case"m":return p*e;case"seconds":case"second":case"secs":case"sec":case"s":return p*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return p;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,p,y){var w=h>=p*1.5;return Math.round(d/p)+" "+y+(w?"s":"")}return Vy}function zV(r){t.debug=t,t.default=t,t.coerce=o,t.disable=a,t.enable=i,t.enabled=c,t.humanize=GV(),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 p=0;p<d.length;p++)h=(h<<5)-h+d.charCodeAt(p),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(d){let h,p=null,y,w;function k(...P){if(!k.enabled)return;const A=k,B=Number(new Date),L=B-(h||B);A.diff=L,A.prev=h,A.curr=B,h=B,P[0]=t.coerce(P[0]),typeof P[0]!="string"&&P.unshift("%O");let $=0;P[0]=P[0].replace(/%([a-zA-Z%])/g,(G,K)=>{if(G==="%%")return"%";$++;const D=t.formatters[K];if(typeof D=="function"){const he=P[$];G=D.call(A,he),P.splice($,1),$--}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:()=>p!==null?p:(y!==t.namespaces&&(y=t.namespaces,w=t.enabled(d)),w),set:P=>{p=P}}),typeof t.init=="function"&&t.init(k),k}function n(d,h){const p=t(this.namespace+(typeof h>"u"?":":h)+d);return p.log=this.log,p}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 p of h)p[0]==="-"?t.skips.push(p.slice(1)):t.names.push(p)}function s(d,h){let p=0,y=0,w=-1,k=0;for(;p<d.length;)if(y<h.length&&(h[y]===d[p]||h[y]==="*"))h[y]==="*"?(w=y,k=p,y++):(p++,y++);else if(w!==-1)y=w+1,k++,p=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 KV=zV;(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,p=>{p!=="%%"&&(d++,p==="%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=KV(e);const{formatters:c}=r.exports;c.j=function(o){try{return JSON.stringify(o)}catch(l){return"[UnexpectedJSONParseError]: "+l.message}}})(eS,eS.exports);var Xs=eS.exports,JV=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 YV=kl,XV=Rl,QV=Ys,ZV=gf,e5=JV(Xs),t5=(0,e5.default)("engine.io-client:transport");class y$ extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}ro.TransportError=y$;class r5 extends XV.Emitter{constructor(e){super(),this.writable=!1,(0,QV.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 y$(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):t5("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=(0,YV.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,ZV.encode)(e);return t.length?"?"+t:""}}ro.Transport=r5;var n5=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(pf,"__esModule",{value:!0});pf.Polling=void 0;const i5=ro,s5=Ys,Sk=kl,a5=n5(Xs),Ns=(0,a5.default)("engine.io-client:polling");class o5 extends i5.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,s5.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}pf.Polling=o5;var cg={};Object.defineProperty(cg,"__esModule",{value:!0});cg.hasCORS=void 0;let _$=!1;try{_$=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}cg.hasCORS=_$;var u5=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(va,"__esModule",{value:!0});va.XHR=va.Request=va.BaseXHR=void 0;const c5=pf,l5=Rl,wk=Ys,b$=Li,d5=cg,f5=u5(Xs),tS=(0,f5.default)("engine.io-client:polling");function h5(){}class S$ extends c5.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(){tS("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}}va.BaseXHR=S$;let Uu=class tv extends l5.Emitter{constructor(e,t,n){super(),this.createRequest=e,(0,wk.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,wk.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{tS("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))},tS("xhr data %s",this._data),n.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=tv.requestsCount++,tv.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=h5,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete tv.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()}};va.Request=Uu;Uu.requestsCount=0;Uu.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Tk);else if(typeof addEventListener=="function"){const r="onpagehide"in b$.globalThisShim?"pagehide":"unload";addEventListener(r,Tk,!1)}}function Tk(){for(let r in Uu.requests)Uu.requests.hasOwnProperty(r)&&Uu.requests[r].abort()}const p5=function(){const r=w$({xdomain:!1});return r&&r.responseType!==null}();class v5 extends S${constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=p5&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Uu(w$,this.uri(),e)}}va.XHR=v5;function w$(r){const e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||d5.hasCORS))return new XMLHttpRequest}catch{}if(!e)try{return new b$.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Jo={},g5=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 m5=ro,Ek=Ys,y5=kl,rS=Li,_5=g5(Xs),b5=(0,_5.default)("engine.io-client:websocket"),T$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class E$ extends m5.Transport{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=T$?{}:(0,Ek.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,y5.encodePacket)(n,this.supportsBinary,s=>{try{this.doWrite(n,s)}catch{b5("websocket closed before onclose event")}i&&(0,rS.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,Ek.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}Jo.BaseWS=E$;const Gy=rS.globalThisShim.WebSocket||rS.globalThisShim.MozWebSocket;class S5 extends E${createSocket(e,t,n){return T$?new Gy(e,t,n):t?new Gy(e,t):new Gy(e)}doWrite(e,t){this.ws.send(t)}}Jo.WS=S5;var mf={},w5=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(mf,"__esModule",{value:!0});mf.WT=void 0;const T5=ro,E5=Li,Ck=kl,C5=w5(Xs),ld=(0,C5.default)("engine.io-client:webtransport");class k5 extends T5.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(()=>{ld("transport closed gracefully"),this.onClose()}).catch(e=>{ld("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){ld("session is closed");return}ld("received chunk: %o",o),this.onPacket(o),s()}).catch(c=>{ld("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,E5.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}mf.WT=k5;Object.defineProperty(hf,"__esModule",{value:!0});hf.transports=void 0;const R5=va,I5=Jo,P5=mf;hf.transports={websocket:I5.WS,webtransport:P5.WT,polling:R5.XHR};var lg={};Object.defineProperty(lg,"__esModule",{value:!0});lg.parse=$5;const A5=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,O5=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function $5(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=A5.exec(r||""),s={},a=14;for(;a--;)s[O5[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=x5(s,s.path),s.queryKey=M5(s,s.query),s}function x5(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 M5(r,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,s){i&&(t[i]=s)}),t}var D5=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 N5=hf,kk=Ys,L5=gf,Rk=lg,F5=Rl,C$=kl,zy=Li,U5=D5(Xs),Kr=(0,U5.default)("engine.io-client:socket"),nS=typeof addEventListener=="function"&&typeof removeEventListener=="function",Wd=[];nS&&addEventListener("offline",()=>{Kr("closing %d connection(s) because the network was lost",Wd.length),Wd.forEach(r=>r())},!1);class to extends F5.Emitter{constructor(e,t){if(super(),this.binaryType=zy.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,Rk.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,Rk.parse)(t.host).host);(0,kk.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,L5.decode)(this.opts.query)),nS&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(Kr("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Wd.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,zy.createCookieJar)()),this._open()}createTransport(e){Kr('creating transport "%s"',e);const t=Object.assign({},this.opts.query);t.EIO=C$.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 Kr("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){Kr("setting transport %s",e.name),this.transport&&(Kr("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(){Kr("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(Kr('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 Kr('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();Kr("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,kk.byteLength)(i)),n>0&&t>this._maxPayload)return Kr("only send %d out of %d packets",n,this.writeBuffer.length),this.writeBuffer.slice(0,n);t+=2}return Kr("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&&(Kr("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,zy.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"),Kr("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(Kr("socket error %j",e),to.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return Kr("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(Kr('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),nS&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=Wd.indexOf(this._offlineEventListener);n!==-1&&(Kr("removing listener for the 'offline' event"),Wd.splice(n,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}eo.SocketWithoutUpgrade=to;to.protocol=C$.protocol;class k$ extends to{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){Kr("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){Kr('probing transport "%s"',e);let t=this.createTransport(e),n=!1;to.priorWebsocketSuccess=!1;const i=()=>{n||(Kr('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(Kr('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;to.priorWebsocketSuccess=t.name==="websocket",Kr('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{n||this.readyState!=="closed"&&(Kr("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{Kr('probe transport "%s" failed',e);const p=new Error("probe error");p.transport=t.name,this.emitReserved("upgradeError",p)}}))};function s(){n||(n=!0,d(),t.close(),t=null)}const a=h=>{const p=new Error("probe error: "+h);p.transport=t.name,s(),Kr('probe transport "%s" failed because of error: %s',e,h),this.emitReserved("upgradeError",p)};function c(){a("transport closed")}function o(){a("socket closed")}function l(h){t&&h.name!==t.name&&(Kr('"%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=k$;let j5=class extends k${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=>N5.transports[i]).filter(i=>!!i)),super(e,n)}};eo.Socket=j5;var dg={};Object.defineProperty(dg,"__esModule",{value:!0});dg.Fetch=void 0;const B5=pf;class q5 extends B5.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})}}dg.Fetch=q5;(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=hf;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=lg;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=dg;Object.defineProperty(r,"Fetch",{enumerable:!0,get:function(){return o.Fetch}});var l=va;Object.defineProperty(r,"NodeXHR",{enumerable:!0,get:function(){return l.XHR}});var d=va;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 p=Jo;Object.defineProperty(r,"WebSocket",{enumerable:!0,get:function(){return p.WS}});var y=mf;Object.defineProperty(r,"WebTransport",{enumerable:!0,get:function(){return y.WT}})})(og);var W5=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Xw,"__esModule",{value:!0});Xw.url=G5;const H5=og,V5=W5(Xs),Ik=(0,V5.default)("socket.io-client:url");function G5(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)||(Ik("protocol-less url %s",r),typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),Ik("parse %s",r),n=(0,H5.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 fg={},yf={},Zi={},hg={},_f={};Object.defineProperty(_f,"__esModule",{value:!0});_f.isBinary=I$;_f.hasBinary=rv;const z5=typeof ArrayBuffer=="function",K5=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,R$=Object.prototype.toString,J5=typeof Blob=="function"||typeof Blob<"u"&&R$.call(Blob)==="[object BlobConstructor]",Y5=typeof File=="function"||typeof File<"u"&&R$.call(File)==="[object FileConstructor]";function I$(r){return z5&&(r instanceof ArrayBuffer||K5(r))||J5&&r instanceof Blob||Y5&&r instanceof File}function rv(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,n=r.length;t<n;t++)if(rv(r[t]))return!0;return!1}if(I$(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return rv(r.toJSON(),!0);for(const t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&rv(r[t]))return!0;return!1}Object.defineProperty(hg,"__esModule",{value:!0});hg.deconstructPacket=Q5;hg.reconstructPacket=Z5;const X5=_f;function Q5(r){const e=[],t=r.data,n=r;return n.data=iS(t,e),n.attachments=e.length,{packet:n,buffers:e}}function iS(r,e){if(!r)return r;if((0,X5.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]=iS(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]=iS(r[n],e));return t}return r}function Z5(r,e){return r.data=sS(r.data,e),delete r.attachments,r}function sS(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]=sS(r[t],e);else if(typeof r=="object")for(const t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=sS(r[t],e));return r}Object.defineProperty(Zi,"__esModule",{value:!0});Zi.Decoder=Zi.Encoder=Zi.PacketType=Zi.protocol=void 0;Zi.isPacketValid=uG;const eG=Rl,P$=hg,A$=_f,tG=Xs,aS=(0,tG.default)("socket.io-parser"),O$=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];Zi.protocol=5;var jr;(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"})(jr||(Zi.PacketType=jr={}));class rG{constructor(e){this.replacer=e}encode(e){return aS("encoding packet %j",e),(e.type===jr.EVENT||e.type===jr.ACK)&&(0,A$.hasBinary)(e)?this.encodeAsBinary({type:e.type===jr.EVENT?jr.BINARY_EVENT:jr.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===jr.BINARY_EVENT||e.type===jr.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)),aS("encoded %j as %s",e,t),t}encodeAsBinary(e){const t=(0,P$.deconstructPacket)(e),n=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(n),i}}Zi.Encoder=rG;class Qw extends eG.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===jr.BINARY_EVENT;n||t.type===jr.BINARY_ACK?(t.type=n?jr.EVENT:jr.ACK,this.reconstructor=new nG(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if((0,A$.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(jr[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===jr.BINARY_EVENT||n.type===jr.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(Qw.isPayloadValid(n.type,s))n.data=s;else throw new Error("invalid payload")}return aS("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 jr.CONNECT:return Tv(t);case jr.DISCONNECT:return t===void 0;case jr.CONNECT_ERROR:return typeof t=="string"||Tv(t);case jr.EVENT:case jr.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&O$.indexOf(t[0])===-1);case jr.ACK:case jr.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}Zi.Decoder=Qw;class nG{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,P$.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function iG(r){return typeof r=="string"}const sG=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function aG(r){return r===void 0||sG(r)}function Tv(r){return Object.prototype.toString.call(r)==="[object Object]"}function oG(r,e){switch(r){case jr.CONNECT:return e===void 0||Tv(e);case jr.DISCONNECT:return e===void 0;case jr.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&O$.indexOf(e[0])===-1);case jr.ACK:return Array.isArray(e);case jr.CONNECT_ERROR:return typeof e=="string"||Tv(e);default:return!1}}function uG(r){return iG(r.nsp)&&aG(r.id)&&oG(r.type,r.data)}var pg={};Object.defineProperty(pg,"__esModule",{value:!0});pg.on=cG;function cG(r,e,t){return r.on(e,t),function(){r.off(e,t)}}var lG=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(yf,"__esModule",{value:!0});yf.Socket=void 0;const Ls=Zi,Bh=pg,dG=Rl,fG=lG(Xs),bn=(0,fG.default)("socket.io-client:socket"),hG=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class pG extends dG.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,Bh.on)(e,"open",this.onopen.bind(this)),(0,Bh.on)(e,"packet",this.onpacket.bind(this)),(0,Bh.on)(e,"error",this.onerror.bind(this)),(0,Bh.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(hG.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)}}}yf.Socket=pG;var Zw={};Object.defineProperty(Zw,"__esModule",{value:!0});Zw.Backoff=Il;function Il(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}Il.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};Il.prototype.reset=function(){this.attempts=0};Il.prototype.setMin=function(r){this.ms=r};Il.prototype.setMax=function(r){this.max=r};Il.prototype.setJitter=function(r){this.jitter=r};var vG=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]}),gG=Ye&&Ye.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),mG=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)&&vG(e,r,t);return gG(e,r),e},yG=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(fg,"__esModule",{value:!0});fg.Manager=void 0;const Ky=og,_G=yf,bG=mG(Zi),Tu=pg,SG=Zw,wG=Rl,TG=yG(Xs),Vn=(0,TG.default)("socket.io-client:manager");class EG extends wG.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,Ky.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 SG.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||bG;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(Vn("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Vn("opening %s",this.uri),this.engine=new Ky.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=>{Vn("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;Vn("connect attempt will timeout after %d",c);const o=this.setTimeoutFn(()=>{Vn("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(){Vn("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,Ky.nextTick)(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){Vn("error",e),this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new _G.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){Vn("socket %s is still active, skipping close",n);return}this._close()}_packet(e){Vn("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(){Vn("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){Vn("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;Vn("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)Vn("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();Vn("will wait %dms before reconnect attempt",t),this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(Vn("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(Vn("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):(Vn("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)}}fg.Manager=EG;(function(r,e){var t=Ye&&Ye.__importDefault||function(p){return p&&p.__esModule?p:{default:p}};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=Xw,i=fg;Object.defineProperty(e,"Manager",{enumerable:!0,get:function(){return i.Manager}});const s=yf;Object.defineProperty(e,"Socket",{enumerable:!0,get:function(){return s.Socket}});const c=(0,t(Xs).default)("socket.io-client"),o={};function l(p,y){typeof p=="object"&&(y=p,p=void 0),y=y||{};const w=(0,n.url)(p,y.path||"/socket.io"),k=w.source,P=w.id,A=w.path,B=o[P]&&A in o[P].nsps,L=y.forceNew||y["force new connection"]||y.multiplex===!1||B;let $;return L?(c("ignoring socket cache for %s",k),$=new i.Manager(k,y)):(o[P]||(c("new io instance for %s",k),o[P]=new i.Manager(k,y)),$=o[P]),w.query&&!y.query&&(y.query=w.queryKey),$.socket(w.path,y)}Object.assign(l,{Manager:i.Manager,Socket:s.Socket,io:l,connect:l});var d=Zi;Object.defineProperty(e,"protocol",{enumerable:!0,get:function(){return d.protocol}});var h=og;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})(Zb,Zb.exports);var $$=Zb.exports,x$={exports:{}};(function(r,e){(function(t){r.exports=t()})(function(){var t=function(v,g,b){for(var _=b,S=0,T=v.length;S<T;S++)_=g(_,v[S],S,v);return _},n=function(v,g){return t(v,function(b,_,S,T){return g(_,S,T)?b.concat(_):b},[])},i=function(v,g){return t(v,function(b,_,S,T){return b.concat(g(_,S,T))},[])},s=function(v,g){return t(v,function(b,_,S,T){return b===!0||_===g},!1)},a=!{toString:null}.propertyIsEnumerable("toString"),c=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],o=function(v){var g=[],b;for(b in v)Object.prototype.hasOwnProperty.call(v,b)&&g.push(b);if(!a)return g;for(var _=0,S=c.length;_<S;_++)Object.prototype.hasOwnProperty.call(v,c[_])&&g.push(c[_]);return g},l=function(v){return Object.prototype.toString.call(v)==="[object Array]"},d=function(v){return v<10?"0"+v:v},h=function(){var v=new Date;return v.getUTCFullYear()+"-"+d(v.getUTCMonth()+1)+"-"+d(v.getUTCDate())+"T"+d(v.getUTCHours())+":"+d(v.getUTCMinutes())+":"+d(v.getUTCSeconds())+"."+(v.getUTCMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z"},p={map:i,reduce:t,filter:n,includes:s,keys:o,isArray:l,isoDate:h},y={};y.intRange=function(v,g){return v===void 0&&(v=1),g===void 0&&(g=1/0),function(b){return typeof b=="number"&&parseInt(""+b,10)===b&&b>=v&&b<=g}},y.stringWithLength=function(v){return typeof v=="string"&&!!v.length};var w={},k=p.filter,P=p.reduce,A=p.keys,B=p.isArray,L=p.includes,$=y.intRange,F=y.stringWithLength;w.schema={apiKey:{defaultValue:function(){return null},message:"is required",validate:F},appVersion:{defaultValue:function(){return null},message:"should be a string",validate:function(v){return v===null||F(v)}},appType:{defaultValue:function(){return null},message:"should be a string",validate:function(v){return v===null||F(v)}},autoNotify:{defaultValue:function(){return!0},message:"should be true|false",validate:function(v){return v===!0||v===!1}},beforeSend:{defaultValue:function(){return[]},message:"should be a function or array of functions",validate:function(v){return typeof v=="function"||B(v)&&k(v,function(g){return typeof g=="function"}).length===v.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(v,g){return v&&typeof v=="object"&&F(v.notify)&&(g.autoCaptureSessions===!1||F(v.sessions))&&k(A(v),function(b){return!L(["notify","sessions"],b)}).length===0}},autoCaptureSessions:{defaultValue:function(v,g){return g.endpoints===void 0||!!g.endpoints&&!!g.endpoints.sessions},message:"should be true|false",validate:function(v){return v===!0||v===!1}},notifyReleaseStages:{defaultValue:function(){return null},message:"should be an array of strings",validate:function(v){return v===null||B(v)&&k(v,function(g){return typeof g=="string"}).length===v.length}},releaseStage:{defaultValue:function(){return"production"},message:"should be a string",validate:function(v){return typeof v=="string"&&v.length}},maxBreadcrumbs:{defaultValue:function(){return 20},message:"should be a number ≤40",validate:function(v){return $(0,40)(v)}},autoBreadcrumbs:{defaultValue:function(){return!0},message:"should be true|false",validate:function(v){return typeof v=="boolean"}},user:{defaultValue:function(){return null},message:"(object) user should be an object",validate:function(v){return typeof v=="object"}},metaData:{defaultValue:function(){return null},message:"should be an object",validate:function(v){return typeof v=="object"}},logger:{defaultValue:function(){},message:"should be null or an object with methods { debug, info, warn, error }",validate:function(v){return!v||v&&P(["debug","info","warn","error"],function(g,b){return g&&typeof v[b]=="function"},!0)}},filters:{defaultValue:function(){return["password"]},message:"should be an array of strings|regexes",validate:function(v){return B(v)&&v.length===k(v,function(g){return typeof g=="string"||g&&typeof g.test=="function"}).length}}},w.mergeDefaults=function(v,g){if(!v||!g)throw new Error("opts and schema objects are required");return P(A(g),function(b,_){return b[_]=v[_]!==void 0?v[_]:g[_].defaultValue(v[_],v),b},{})},w.validate=function(v,g){if(!v||!g)throw new Error("opts and schema objects are required");var b=P(A(g),function(_,S){return g[S].validate(v[S],v)?_:_.concat({key:S,message:g[S].message,value:v[S]})},[]);return{valid:!b.length,errors:b}};function G(){return G=Object.assign||function(v){for(var g=1;g<arguments.length;g++){var b=arguments[g];for(var _ in b)Object.prototype.hasOwnProperty.call(b,_)&&(v[_]=b[_])}return v},G.apply(this,arguments)}var K=w.schema,D=p.map,he=y.stringWithLength,X={releaseStage:{defaultValue:function(){return/^localhost(:\d+)?$/.test(window.location.host)?"development":"production"},message:"should be set",validate:he},logger:G({},K.logger,{defaultValue:function(){return typeof console<"u"&&typeof console.debug=="function"?ve():void 0}})},ve=function(){var v={},g=console.log;return D(["debug","info","warn","error"],function(b){var _=console[b];v[b]=typeof _=="function"?_.bind(console,"[bugsnag]"):g.bind(console,"[bugsnag]")}),v},Q=p.isoDate,Oe=function(){function v(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=v.prototype;return g.toJSON=function(){return{type:this.type,name:this.name,timestamp:this.timestamp,metaData:this.metaData}},v}(),He=Oe,Ze=function(v,g,b){var _=v.length,S=0,T=function(){if(S>=_)return b(null,!1);g(v[S],function(E,I){if(E)return b(E,!1);if(I===!0)return b(null,!0);S++,T()})};T()},Xe=function(v){return v.app&&typeof v.app.releaseStage=="string"?v.app.releaseStage:v.config.releaseStage},Re=Je;function Je(v){switch(Object.prototype.toString.call(v)){case"[object Error]":return!0;case"[object Exception]":return!0;case"[object DOMException]":return!0;default:return v instanceof Error}}var Ke=Re,Y=function(v,g){return function(b,_){if(typeof b!="function")return _(null,!1);try{if(b.length!==2){var S=b(v);return S&&typeof S.then=="function"?S.then(function(T){return setTimeout(function(){return _(null,Ee(v,T))},0)},function(T){setTimeout(function(){return g(T),_(null,!1)})}):_(null,Ee(v,S))}b(v,function(T,E){if(T)return g(T),_(null,!1);_(null,Ee(v,E))})}catch(T){g(T),_(null,!1)}}},Ee=function(v,g){return v.isIgnored()||g===!1},Ct={};(function(v,g){typeof Ct=="object"?Ct=g():v.StackFrame=g()})(this,function(){function v(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=v(this.getLineNumber())?":"+this.getLineNumber():"",ct=v(this.getColumnNumber())?":"+this.getColumnNumber():"";return Se+Ge+gt+et+ct}};for(var V=0;V<_.length;V++)q.prototype["get"+g(_[V])]=b(_[V]),q.prototype["set"+g(_[V])]=function(Se){return function(Ge){this[Se]=!!Ge}}(_[V]);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(!v(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(v,g){typeof Nt=="object"?Nt=g(Ct):v.ErrorStackParser=g(v.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 V=q.replace(/^\s+/,"").replace(/\(eval code/g,"("),J=V.match(/ (\((.+):(\d+):(\d+)\)$)/);V=J?V.replace(J[0],""):V;var ae=V.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 V=/((.*".+"[^@]*)?[^@]*)(?:@)/,J=q.match(V),ae=J&&J[1]?J[1]:void 0,Se=this.extractLocation(q.replace(V,""));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(`
@@ -364,7 +364,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
364
364
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,a=!1,c;return{s:function(){t=t.call(r)},n:function(){var l=t.next();return s=l.done,l},e:function(l){a=!0,c=l},f:function(){try{!s&&t.return!=null&&t.return()}finally{if(a)throw c}}}}function mve(r,e){if(r){if(typeof r=="string")return eA(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return eA(r,e)}}function eA(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}var yve=function(){function r(e,t){hr.default(this,r),this.balanceFactor=0,this.key=e,this.value=t,this.parent=null,this.left=null,this.right=null}return pr.default(r,[{key:"isRoot",get:function(){return this.parent===null}},{key:"isLeaf",get:function(){return this.left===null&&this.right===null}},{key:"isLeftChild",get:function(){return this.parent.left===this}},{key:"update",value:function(t){this.value=t}},{key:"replace",value:function(t,n){t&&(this.left===n?this.left=n:this.right===n&&(this.right=n))}}]),r}(),_ve=function(r){function e(t,n){hr.default(this,e),this.isLessThan=t||function(i,s){return i<s},this.isEqual=n||function(i,s){return i===s},this.root=null,this.count=null}return pr.default(e,[{key:"size",get:function(){return this.count}},{key:"clear",value:function(){this.root=null,this.count=0}},{key:"set",value:function(n,i){var s=this.getNode(n);s?s.update(i):this.insert(n,i)}},{key:"insert",value:function(n,i){var s=new yve(n,i);if(this.count++,!this.root){this.root=s;return}for(var a=this.root;;)if(this.isLessThan(n,a.key))if(a.left)a=a.left;else{a.left=s;break}else if(a.right)a=a.right;else{a.right=s;break}for(s.parent=a,a=s;a.parent;){var c=a.parent,o=c.balanceFactor;if(a.isLeftChild?c.balanceFactor++:c.balanceFactor--,Math.abs(c.balanceFactor)<Math.abs(o))break;if(c.balanceFactor<-1||c.balanceFactor>1){this.rebalance(c);break}a=c}}},{key:"get",value:function(n){for(var i=this.root;i;){if(this.isEqual(n,i.key))return i.value;this.isLessThan(n,i.key)?i=i.left:i=i.right}return null}},{key:"delete",value:function(n){var i=this.getNode(n);if(!i||i.key!==n)return null;var s=i.parent,a=i.left,c=i.right;if(!!a!=!!c){var o=a||c;!s&&!o?this.root=null:s&&!o?this.root=o:(s.replace(i,null),this.rebalance(s))}else{for(var l=i.left;l.right;)l=l.right;if(i.left===l)i.isRoot?(this.root=l,l.parent=null):(i.isLeftChild?i.parent.left=l:i.parent.right=l,l.parent=i.parent),l.right=i.right,l.right.parent=l,l.balanceFactor=i.balanceFactor,i={parent:l,isLeftChild:!0};else{var d=l.parent,h=l.left;d.right=h,h&&(h.parent=d),i.isRoot?(this.root=l,l.parent=null):(i.isLeftChild?i.parent.left=l:i.parent.right=l,l.parent=i.parent),l.right=i.right,l.right.parent=l,l.left=i.left,l.left.parent=l,l.balanceFactor=i.balanceFactor,i={parent:d,isLeftChild:!1}}}for(this.count--;i.parent;){var p=i.parent,y=p.balanceFactor;if(i.isLeftChild?p.balanceFactor-=1:p.balanceFactor+=1,Math.abs(p.balanceFactor)>Math.abs(y))if(p.balanceFactor<-1||p.balanceFactor>1)if(this.rebalance(p),p.parent.balanceFactor===0)i=p.parent;else break;else break;else i=p}return null}},{key:"getNode",value:function(n){for(var i=this.root;i;){if(this.isEqual(n,i.key))return i;this.isLessThan(n,i.key)?i=i.left:i=i.right}return null}},{key:"rebalance",value:function(n){n.balanceFactor<0?n.right.balanceFactor>0?(this.rotateRight(n.right),this.rotateLeft(n)):this.rotateLeft(n):n.balanceFactor>0&&(n.left.balanceFactor<0?(this.rotateLeft(n.left),this.rotateRight(n)):this.rotateRight(n))}},{key:"rotateLeft",value:function(n){var i=n.right;n.right=i.left,i.left!==null&&(i.left.parent=n),i.parent=n.parent,i.parent===null?this.root=i:n.isLeftChild?i.parent.left=i:i.parent.right=i,i.left=n,n.parent=i,n.balanceFactor=n.balanceFactor+1-Math.min(i.balanceFactor,0),i.balanceFactor=i.balanceFactor+1-Math.max(n.balanceFactor,0)}},{key:"rotateRight",value:function(n){var i=n.left;n.left=i.right,i.right!==null&&(i.right.parent=n),i.parent=n.parent,i.parent===null?this.root=i:n.isLeftChild?i.parent.left=i:i.parent.right=i,i.right=n,n.parent=i,n.balanceFactor=n.balanceFactor-1-Math.min(i.balanceFactor,0),i.balanceFactor=i.balanceFactor-1-Math.max(n.balanceFactor,0)}},{key:r,value:fe.default.mark(function t(){var n,i,s;return fe.default.wrap(function(c){for(;;)switch(c.prev=c.next){case 0:n=gve(this.getIterator()),c.prev=1,n.s();case 3:if((i=n.n()).done){c.next=9;break}return s=i.value,c.next=7,s;case 7:c.next=3;break;case 9:c.next=14;break;case 11:c.prev=11,c.t0=c.catch(1),n.e(c.t0);case 14:return c.prev=14,n.f(),c.finish(14);case 17:case"end":return c.stop()}},t,this,[[1,11,14,17]])})},{key:"getIterator",value:fe.default.mark(function t(){var n,i,s,a=arguments;return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:n=a.length>0&&a[0]!==void 0?a[0]:null,i=this.root;case 2:if(!i){o.next=8;break}if(!(this.isEqual(n,i.key)||n===null&&!i.left)){o.next=5;break}return o.abrupt("break",8);case 5:this.isLessThan(n,i.key)||n===null?i=i.left:i=i.right,o.next=2;break;case 8:if(i){o.next=10;break}return o.abrupt("return",null);case 10:s=!0;case 11:if(!s){o.next=29;break}return o.next=14,[i.key,i.value];case 14:if(s=!1,!i.right){o.next=21;break}for(i=i.right;i.left;)i=i.left;s=!0,o.next=27;break;case 21:if(!i.parent){o.next=26;break}s=i.parent.left===i,i=i.parent,o.next=27;break;case 26:return o.abrupt("break",37);case 27:o.next=35;break;case 29:if(!i.parent){o.next=34;break}s=i.parent.left===i,i=i.parent,o.next=35;break;case 34:return o.abrupt("break",37);case 35:o.next=11;break;case 37:return o.abrupt("return",null);case 38:case"end":return o.stop()}},t,this)})},{key:"getReverseIterator",value:fe.default.mark(function t(){var n,i,s,a=arguments;return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:n=a.length>0&&a[0]!==void 0?a[0]:null,i=this.root;case 2:if(!i){o.next=8;break}if(!(this.isEqual(n,i.key)||n===null&&!i.right)){o.next=5;break}return o.abrupt("break",8);case 5:!this.isLessThan(n,i.key)||n===null?i=i.right:i=i.left,o.next=2;break;case 8:if(i){o.next=10;break}return o.abrupt("return",null);case 10:s=!0;case 11:if(!s){o.next=29;break}return o.next=14,[i.key,i.value];case 14:if(s=!1,!i.left){o.next=21;break}for(i=i.left;i.right;)i=i.right;s=!0,o.next=27;break;case 21:if(!i.parent){o.next=26;break}s=i.parent.right===i,i=i.parent,o.next=27;break;case 26:return o.abrupt("break",37);case 27:o.next=35;break;case 29:if(!i.parent){o.next=34;break}s=i.parent.right===i,i=i.parent,o.next=35;break;case 34:return o.abrupt("break",37);case 35:o.next=11;break;case 37:return o.abrupt("return",null);case 38:case"end":return o.stop()}},t,this)})}]),e}(Symbol.iterator);function Fp(r,e){var t=typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=bve(r))||e){t&&(r=t);var n=0,i=function(){};return{s:i,n:function(){return n>=r.length?{done:!0}:{done:!1,value:r[n++]}},e:function(l){throw l},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
365
365
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,a=!1,c;return{s:function(){t=t.call(r)},n:function(){var l=t.next();return s=l.done,l},e:function(l){a=!0,c=l},f:function(){try{!s&&t.return!=null&&t.return()}finally{if(a)throw c}}}}function bve(r,e){if(r){if(typeof r=="string")return tA(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return tA(r,e)}}function tA(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}var Sve=function(){function r(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;hr.default(this,r),this._data=e,this.lastEventId=t||0,this.isLeftBound=n,this.isRightBound=i}return pr.default(r,[{key:"isValid",get:function(){return!0}},{key:"value",get:function(){return this._data}}]),r}(),wve=function(){function r(e){hr.default(this,r),this.lastEventId=e,this.isLeftBound=!1,this.isRightBound=!1}return pr.default(r,[{key:"isValid",get:function(){return!1}},{key:"value",get:function(){return null}}]),r}(),$T=function(){function r(){hr.default(this,r),fr.default(this,"items",new _ve),fr.default(this,"beginKey",null),fr.default(this,"endKey",null),this.items.clear()}return pr.default(r,[{key:"size",get:function(){return this.items.size}},{key:"collectionBegin",get:function(){return this.beginKey}},{key:"collectionEnd",get:function(){return this.endKey}},{key:"has",value:function(t){var n,i=this.items.get(t);return(n=i==null?void 0:i.isValid)!==null&&n!==void 0?n:!1}},{key:"exists",value:function(t){var n=this.items.get(t);return!!n}},{key:"getValue",value:function(t){var n,i=this.items.get(t);return(n=i==null?void 0:i.value)!==null&&n!==void 0?n:null}},{key:"get",value:function(t){return this.items.get(t)}},{key:"getNextItem",value:function(t,n,i){return t===null?this.getFirstItem(n):i?this.getValue(t):this.getAdjacentItem(t,n)}},{key:"getFirstItem",value:function(t){var n=t==="asc"?this.beginKey:this.endKey;if(this.exists(n)){var i=this.items.get(n);return i.isValid?i.value:this.getAdjacentItem(n,t)}return null}},{key:"getAdjacentItem",value:function(t,n){var i=n==="asc"?this.items.getIterator(t):this.items.getReverseIterator(t),s=Fp(i),a;try{for(s.s();!(a=s.n()).done;){var c=Ld.default(a.value,2),o=c[0],l=c[1];if(n==="asc"?l.isRightBound:l.isLeftBound)break;if(l.isValid)return l.value}}catch(d){s.e(d)}finally{s.f()}return null}},{key:"store",value:function(t,n,i){var s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!0,a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,c=this.items.get(t);if(c&&c.lastEventId>i)return c.value;if(this.items.set(t,new Sve(n,i,c?c.isLeftBound&&s:s,c?c.isRightBound&&a:a)),this.beginKey!==null&&t<this.beginKey){var o=this.items.get(this.beginKey);o&&(o.isLeftBound=!1),this.beginKey=t}if(this.endKey!==null&&this.endKey<t){var l=this.items.get(this.endKey);l&&(l.isRightBound=!1),this.endKey=t}return n}},{key:"populate",value:function(t,n,i){var s=this;if(t.length){var a=Hpe.default(t);if(a.sort(function(l,d){return l.cacheKey===d.cacheKey?0:l.cacheKey>d.cacheKey?1:-1}),a.forEach(function(l,d){s.store(l.cacheKey,l,l.lastEventId,d===0,d===a.length-1)}),n){var c=a[0].cacheKey;(!this.beginKey||c<this.beginKey)&&(this.beginKey=c)}if(i){var o=a[a.length-1].cacheKey;(!this.endKey||this.endKey<o)&&(this.endKey=o)}}}},{key:"delete",value:function(t,n){var i=this.items.get(t);(i===null||n===null||i.lastEventId<n)&&this.items.set(t,new wve(n))}},{key:"isKnown",value:function(t,n){var i=this.items.get(t);return i&&i.lastEventId>=n}},{key:"getIterator",value:fe.default.mark(function e(t){var n,i,s,a;return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:if(t===null&&this.beginKey!==null&&(t=this.beginKey),t!==null){o.next=3;break}return o.abrupt("return");case 3:n=Fp(this.items.getIterator(t)),o.prev=4,n.s();case 6:if((i=n.n()).done){o.next=16;break}if(s=Ld.default(i.value,2),a=s[1],a.isValid){o.next=10;break}return o.abrupt("continue",14);case 10:return o.next=12,a;case 12:if(!a.isRightBound){o.next=14;break}return o.abrupt("break",16);case 14:o.next=6;break;case 16:o.next=21;break;case 18:o.prev=18,o.t0=o.catch(4),n.e(o.t0);case 21:return o.prev=21,n.f(),o.finish(21);case 24:case"end":return o.stop()}},e,this,[[4,18,21,24]])})},{key:"getReverseIterator",value:fe.default.mark(function e(t){var n,i,s,a;return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:if(t===null&&this.endKey!==null&&(t=this.endKey),t!==null){o.next=3;break}return o.abrupt("return");case 3:n=Fp(this.items.getReverseIterator(t)),o.prev=4,n.s();case 6:if((i=n.n()).done){o.next=16;break}if(s=Ld.default(i.value,2),a=s[1],a.isValid){o.next=10;break}return o.abrupt("continue",14);case 10:return o.next=12,a;case 12:if(!a.isLeftBound){o.next=14;break}return o.abrupt("break",16);case 14:o.next=6;break;case 16:o.next=21;break;case 18:o.prev=18,o.t0=o.catch(4),n.e(o.t0);case 21:return o.prev=21,n.f(),o.finish(21);case 24:case"end":return o.stop()}},e,this,[[4,18,21,24]])})},{key:"forEach",value:function(t){if(this.items){var n=Fp(this.items),i;try{for(n.s();!(i=n.n()).done;){var s=Ld.default(i.value,2),a=s[0],c=s[1];c.isValid&&t(a,c.value)}}catch(o){n.e(o)}finally{n.f()}}}}]),r}(),Ed=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof Ye<"u"?Ye:typeof self<"u"?self:{},ai={exports:{}};(function(r,e){(function(){var t,n="4.17.21",i=200,s="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",a="Expected a function",c="Invalid `variable` option passed into `_.template`",o="__lodash_hash_undefined__",l=500,d="__lodash_placeholder__",h=1,p=2,y=4,w=1,k=2,P=1,A=2,B=4,L=8,$=16,F=32,G=64,K=128,D=256,he=512,X=30,ve="...",Q=800,Oe=16,He=1,Ze=2,Xe=3,Re=1/0,Je=9007199254740991,Ke=17976931348623157e292,Y=NaN,Ee=4294967295,Ct=Ee-1,Nt=Ee>>>1,Et=[["ary",K],["bind",P],["bindKey",A],["curry",L],["curryRight",$],["flip",he],["partial",F],["partialRight",G],["rearg",D]],wt="[object Arguments]",te="[object Array]",ne="[object AsyncFunction]",ut="[object Boolean]",It="[object Date]",Zt="[object DOMException]",rt="[object Error]",cn="[object Function]",Ot="[object GeneratorFunction]",$e="[object Map]",_t="[object Number]",zt="[object Null]",Ue="[object Object]",vr="[object Promise]",er="[object Proxy]",Lr="[object RegExp]",dr="[object Set]",tn="[object String]",yn="[object Symbol]",hn="[object Undefined]",Kt="[object WeakMap]",Ht="[object WeakSet]",kt="[object ArrayBuffer]",yt="[object DataView]",Xt="[object Float32Array]",nn="[object Float64Array]",Qr="[object Int8Array]",Mn="[object Int16Array]",kn="[object Int32Array]",Rn="[object Uint8Array]",sr="[object Uint8ClampedArray]",Fr="[object Uint16Array]",ke="[object Uint32Array]",Pe=/\b__p \+= '';/g,_e=/\b(__p \+=) '' \+/g,we=/(__e\(.*?\)|\b__t\)) \+\n'';/g,de=/&(?:amp|lt|gt|quot|#39);/g,xe=/[&<>"']/g,Le=RegExp(de.source),pe=RegExp(xe.source),be=/<%-([\s\S]+?)%>/g,se=/<%([\s\S]+?)%>/g,ge=/<%=([\s\S]+?)%>/g,ue=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Qe=/^\w*$/,Me=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ot=/[\\^$.*+?()[\]{}|]/g,tt=RegExp(ot.source),it=/^\s+/,at=/\s/,ht=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,jt=/\{\n\/\* \[wrapped with (.+)\] \*/,pt=/,? & /,bt=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,Pt=/[()=,{}\[\]\/\s]/,Ur=/\\(\\)?/g,ln=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,qt=/\w*$/,Dn=/^[-+]0x[0-9a-f]+$/i,Ri=/^0b[01]+$/i,Bn=/^\[object .+?Constructor\]$/,vt=/^0o[0-7]+$/i,ce=/^(?:0|[1-9]\d*)$/,je=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,st=/($^)/,Jt=/['\n\r\u2028\u2029\\]/g,ur="\\ud800-\\udfff",Ar="\\u0300-\\u036f",sn="\\ufe20-\\ufe2f",_n="\\u20d0-\\u20ff",li=Ar+sn+_n,Ii="\\u2700-\\u27bf",Gr="a-z\\xdf-\\xf6\\xf8-\\xff",Zs="\\xac\\xb1\\xd7\\xf7",ea="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",qn="\\u2000-\\u206f",Is=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",ta="A-Z\\xc0-\\xd6\\xd8-\\xde",br="\\ufe0e\\ufe0f",Pa=Zs+ea+qn+Is,Aa="['’]",_o="["+ur+"]",Pi="["+Pa+"]",Ps="["+li+"]",ie="\\d+",re="["+Ii+"]",H="["+Gr+"]",j="[^"+ur+Pa+ie+Ii+Gr+ta+"]",N="\\ud83c[\\udffb-\\udfff]",Z="(?:"+Ps+"|"+N+")",z="[^"+ur+"]",Ie="(?:\\ud83c[\\udde6-\\uddff]){2}",Te="[\\ud800-\\udbff][\\udc00-\\udfff]",Be="["+ta+"]",Ve="\\u200d",Rt="(?:"+H+"|"+j+")",pn="(?:"+Be+"|"+j+")",ra="(?:"+Aa+"(?:d|ll|m|re|s|t|ve))?",Nn="(?:"+Aa+"(?:D|LL|M|RE|S|T|VE))?",Ln=Z+"?",Oa="["+br+"]?",Wi="(?:"+Ve+"(?:"+[z,Ie,Te].join("|")+")"+Oa+Ln+")*",bo="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",na="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",So=Oa+Ln+Wi,uc="(?:"+[re,Ie,Te].join("|")+")"+So,Hi="(?:"+[z+Ps+"?",Ps,Ie,Te,_o].join("|")+")",Vi=RegExp(Aa,"g"),lu=RegExp(Ps,"g"),wo=RegExp(N+"(?="+N+")|"+Hi+So,"g"),jl=RegExp([Be+"?"+H+"+"+ra+"(?="+[Pi,Be,"$"].join("|")+")",pn+"+"+Nn+"(?="+[Pi,Be+Rt,"$"].join("|")+")",Be+"?"+Rt+"+"+ra,Be+"+"+Nn,na,bo,ie,uc].join("|"),"g"),cc=RegExp("["+Ve+ur+li+br+"]"),As=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Bl=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],lc=-1,Or={};Or[Xt]=Or[nn]=Or[Qr]=Or[Mn]=Or[kn]=Or[Rn]=Or[sr]=Or[Fr]=Or[ke]=!0,Or[wt]=Or[te]=Or[kt]=Or[ut]=Or[yt]=Or[It]=Or[rt]=Or[cn]=Or[$e]=Or[_t]=Or[Ue]=Or[Lr]=Or[dr]=Or[tn]=Or[Kt]=!1;var Tr={};Tr[wt]=Tr[te]=Tr[kt]=Tr[yt]=Tr[ut]=Tr[It]=Tr[Xt]=Tr[nn]=Tr[Qr]=Tr[Mn]=Tr[kn]=Tr[$e]=Tr[_t]=Tr[Ue]=Tr[Lr]=Tr[dr]=Tr[tn]=Tr[yn]=Tr[Rn]=Tr[sr]=Tr[Fr]=Tr[ke]=!0,Tr[rt]=Tr[cn]=Tr[Kt]=!1;var dc={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},du={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},fu={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"},ql={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},fc=parseFloat,hc=parseInt,$a=ps.default(Ed)=="object"&&Ed&&Ed.Object===Object&&Ed,hu=(typeof self>"u"?"undefined":ps.default(self))=="object"&&self&&self.Object===Object&&self,$t=$a||hu||Function("return this")(),To=e&&!e.nodeType&&e,Ai=To&&!0&&r&&!r.nodeType&&r,pc=Ai&&Ai.exports===To,Os=pc&&$a.process,xt=function(){try{var me=Ai&&Ai.require&&Ai.require("util").types;return me||Os&&Os.binding&&Os.binding("util")}catch{}}(),vc=xt&&xt.isArrayBuffer,x=xt&&xt.isDate,M=xt&&xt.isMap,R=xt&&xt.isRegExp,v=xt&&xt.isSet,g=xt&&xt.isTypedArray;function b(me,Ae,Ce){switch(Ce.length){case 0:return me.call(Ae);case 1:return me.call(Ae,Ce[0]);case 2:return me.call(Ae,Ce[0],Ce[1]);case 3:return me.call(Ae,Ce[0],Ce[1],Ce[2])}return me.apply(Ae,Ce)}function _(me,Ae,Ce,mt){for(var Vt=-1,Er=me==null?0:me.length;++Vt<Er;){var In=me[Vt];Ae(mt,In,Ce(In),me)}return mt}function S(me,Ae){for(var Ce=-1,mt=me==null?0:me.length;++Ce<mt&&Ae(me[Ce],Ce,me)!==!1;);return me}function T(me,Ae){for(var Ce=me==null?0:me.length;Ce--&&Ae(me[Ce],Ce,me)!==!1;);return me}function E(me,Ae){for(var Ce=-1,mt=me==null?0:me.length;++Ce<mt;)if(!Ae(me[Ce],Ce,me))return!1;return!0}function I(me,Ae){for(var Ce=-1,mt=me==null?0:me.length,Vt=0,Er=[];++Ce<mt;){var In=me[Ce];Ae(In,Ce,me)&&(Er[Vt++]=In)}return Er}function q(me,Ae){var Ce=me==null?0:me.length;return!!Ce&&an(me,Ae,0)>-1}function V(me,Ae,Ce){for(var mt=-1,Vt=me==null?0:me.length;++mt<Vt;)if(Ce(Ae,me[mt]))return!0;return!1}function J(me,Ae){for(var Ce=-1,mt=me==null?0:me.length,Vt=Array(mt);++Ce<mt;)Vt[Ce]=Ae(me[Ce],Ce,me);return Vt}function ae(me,Ae){for(var Ce=-1,mt=Ae.length,Vt=me.length;++Ce<mt;)me[Vt+Ce]=Ae[Ce];return me}function Se(me,Ae,Ce,mt){var Vt=-1,Er=me==null?0:me.length;for(mt&&Er&&(Ce=me[++Vt]);++Vt<Er;)Ce=Ae(Ce,me[Vt],Vt,me);return Ce}function Ge(me,Ae,Ce,mt){var Vt=me==null?0:me.length;for(mt&&Vt&&(Ce=me[--Vt]);Vt--;)Ce=Ae(Ce,me[Vt],Vt,me);return Ce}function gt(me,Ae){for(var Ce=-1,mt=me==null?0:me.length;++Ce<mt;)if(Ae(me[Ce],Ce,me))return!0;return!1}var et=Cm("length");function ct(me){return me.split("")}function At(me){return me.match(bt)||[]}function lt(me,Ae,Ce){var mt;return Ce(me,function(Vt,Er,In){if(Ae(Vt,Er,In))return mt=Er,!1}),mt}function Zr(me,Ae,Ce,mt){for(var Vt=me.length,Er=Ce+(mt?1:-1);mt?Er--:++Er<Vt;)if(Ae(me[Er],Er,me))return Er;return-1}function an(me,Ae,Ce){return Ae===Ae?ZF(me,Ae,Ce):Zr(me,di,Ce)}function St(me,Ae,Ce,mt){for(var Vt=Ce-1,Er=me.length;++Vt<Er;)if(mt(me[Vt],Ae))return Vt;return-1}function di(me){return me!==me}function Wn(me,Ae){var Ce=me==null?0:me.length;return Ce?Rm(me,Ae)/Ce:Y}function Cm(me){return function(Ae){return Ae==null?t:Ae[me]}}function km(me){return function(Ae){return me==null?t:me[Ae]}}function KT(me,Ae,Ce,mt,Vt){return Vt(me,function(Er,In,zr){Ce=mt?(mt=!1,Er):Ae(Ce,Er,In,zr)}),Ce}function WF(me,Ae){var Ce=me.length;for(me.sort(Ae);Ce--;)me[Ce]=me[Ce].value;return me}function Rm(me,Ae){for(var Ce,mt=-1,Vt=me.length;++mt<Vt;){var Er=Ae(me[mt]);Er!==t&&(Ce=Ce===t?Er:Ce+Er)}return Ce}function Im(me,Ae){for(var Ce=-1,mt=Array(me);++Ce<me;)mt[Ce]=Ae(Ce);return mt}function HF(me,Ae){return J(Ae,function(Ce){return[Ce,me[Ce]]})}function JT(me){return me&&me.slice(0,ZT(me)+1).replace(it,"")}function Gi(me){return function(Ae){return me(Ae)}}function Pm(me,Ae){return J(Ae,function(Ce){return me[Ce]})}function Wl(me,Ae){return me.has(Ae)}function YT(me,Ae){for(var Ce=-1,mt=me.length;++Ce<mt&&an(Ae,me[Ce],0)>-1;);return Ce}function XT(me,Ae){for(var Ce=me.length;Ce--&&an(Ae,me[Ce],0)>-1;);return Ce}function VF(me,Ae){for(var Ce=me.length,mt=0;Ce--;)me[Ce]===Ae&&++mt;return mt}var GF=km(dc),zF=km(du);function KF(me){return"\\"+ql[me]}function JF(me,Ae){return me==null?t:me[Ae]}function gc(me){return cc.test(me)}function YF(me){return As.test(me)}function XF(me){for(var Ae,Ce=[];!(Ae=me.next()).done;)Ce.push(Ae.value);return Ce}function Am(me){var Ae=-1,Ce=Array(me.size);return me.forEach(function(mt,Vt){Ce[++Ae]=[Vt,mt]}),Ce}function QT(me,Ae){return function(Ce){return me(Ae(Ce))}}function Eo(me,Ae){for(var Ce=-1,mt=me.length,Vt=0,Er=[];++Ce<mt;){var In=me[Ce];(In===Ae||In===d)&&(me[Ce]=d,Er[Vt++]=Ce)}return Er}function Xf(me){var Ae=-1,Ce=Array(me.size);return me.forEach(function(mt){Ce[++Ae]=mt}),Ce}function QF(me){var Ae=-1,Ce=Array(me.size);return me.forEach(function(mt){Ce[++Ae]=[mt,mt]}),Ce}function ZF(me,Ae,Ce){for(var mt=Ce-1,Vt=me.length;++mt<Vt;)if(me[mt]===Ae)return mt;return-1}function eU(me,Ae,Ce){for(var mt=Ce+1;mt--;)if(me[mt]===Ae)return mt;return mt}function mc(me){return gc(me)?rU(me):et(me)}function $s(me){return gc(me)?nU(me):ct(me)}function ZT(me){for(var Ae=me.length;Ae--&&at.test(me.charAt(Ae)););return Ae}var tU=km(fu);function rU(me){for(var Ae=wo.lastIndex=0;wo.test(me);)++Ae;return Ae}function nU(me){return me.match(wo)||[]}function iU(me){return me.match(jl)||[]}var sU=function me(Ae){Ae=Ae==null?$t:yc.defaults($t.Object(),Ae,yc.pick($t,Bl));var Ce=Ae.Array,mt=Ae.Date,Vt=Ae.Error,Er=Ae.Function,In=Ae.Math,zr=Ae.Object,Om=Ae.RegExp,aU=Ae.String,ss=Ae.TypeError,Qf=Ce.prototype,oU=Er.prototype,_c=zr.prototype,Zf=Ae["__core-js_shared__"],eh=oU.toString,$r=_c.hasOwnProperty,uU=0,eE=function(){var u=/[^.]+$/.exec(Zf&&Zf.keys&&Zf.keys.IE_PROTO||"");return u?"Symbol(src)_1."+u:""}(),th=_c.toString,cU=eh.call(zr),lU=$t._,dU=Om("^"+eh.call($r).replace(ot,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),rh=pc?Ae.Buffer:t,Co=Ae.Symbol,nh=Ae.Uint8Array,tE=rh?rh.allocUnsafe:t,ih=QT(zr.getPrototypeOf,zr),rE=zr.create,nE=_c.propertyIsEnumerable,sh=Qf.splice,iE=Co?Co.isConcatSpreadable:t,Hl=Co?Co.iterator:t,pu=Co?Co.toStringTag:t,ah=function(){try{var u=_u(zr,"defineProperty");return u({},"",{}),u}catch{}}(),fU=Ae.clearTimeout!==$t.clearTimeout&&Ae.clearTimeout,hU=mt&&mt.now!==$t.Date.now&&mt.now,pU=Ae.setTimeout!==$t.setTimeout&&Ae.setTimeout,oh=In.ceil,uh=In.floor,$m=zr.getOwnPropertySymbols,vU=rh?rh.isBuffer:t,sE=Ae.isFinite,gU=Qf.join,mU=QT(zr.keys,zr),Pn=In.max,Yn=In.min,yU=mt.now,_U=Ae.parseInt,aE=In.random,bU=Qf.reverse,xm=_u(Ae,"DataView"),Vl=_u(Ae,"Map"),Mm=_u(Ae,"Promise"),bc=_u(Ae,"Set"),Gl=_u(Ae,"WeakMap"),zl=_u(zr,"create"),ch=Gl&&new Gl,Sc={},SU=bu(xm),wU=bu(Vl),TU=bu(Mm),EU=bu(bc),CU=bu(Gl),lh=Co?Co.prototype:t,Kl=lh?lh.valueOf:t,oE=lh?lh.toString:t;function U(u){if(dn(u)&&!Yt(u)&&!(u instanceof cr)){if(u instanceof as)return u;if($r.call(u,"__wrapped__"))return uC(u)}return new as(u)}var wc=function(){function u(){}return function(f){if(!on(f))return{};if(rE)return rE(f);u.prototype=f;var m=new u;return u.prototype=t,m}}();function dh(){}function as(u,f){this.__wrapped__=u,this.__actions__=[],this.__chain__=!!f,this.__index__=0,this.__values__=t}U.templateSettings={escape:be,evaluate:se,interpolate:ge,variable:"",imports:{_:U}},U.prototype=dh.prototype,U.prototype.constructor=U,as.prototype=wc(dh.prototype),as.prototype.constructor=as;function cr(u){this.__wrapped__=u,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=Ee,this.__views__=[]}function kU(){var u=new cr(this.__wrapped__);return u.__actions__=Oi(this.__actions__),u.__dir__=this.__dir__,u.__filtered__=this.__filtered__,u.__iteratees__=Oi(this.__iteratees__),u.__takeCount__=this.__takeCount__,u.__views__=Oi(this.__views__),u}function RU(){if(this.__filtered__){var u=new cr(this);u.__dir__=-1,u.__filtered__=!0}else u=this.clone(),u.__dir__*=-1;return u}function IU(){var u=this.__wrapped__.value(),f=this.__dir__,m=Yt(u),C=f<0,O=m?u.length:0,W=jj(0,O,this.__views__),ee=W.start,le=W.end,ye=le-ee,De=C?le:ee-1,Ne=this.__iteratees__,qe=Ne.length,nt=0,Tt=Yn(ye,this.__takeCount__);if(!m||!C&&O==ye&&Tt==ye)return OE(u,this.__actions__);var Lt=[];e:for(;ye--&&nt<Tt;){De+=f;for(var nr=-1,Ft=u[De];++nr<qe;){var lr=Ne[nr],gr=lr.iteratee,Qn=lr.type,pi=gr(Ft);if(Qn==Ze)Ft=pi;else if(!pi){if(Qn==He)continue e;break e}}Lt[nt++]=Ft}return Lt}cr.prototype=wc(dh.prototype),cr.prototype.constructor=cr;function vu(u){var f=-1,m=u==null?0:u.length;for(this.clear();++f<m;){var C=u[f];this.set(C[0],C[1])}}function PU(){this.__data__=zl?zl(null):{},this.size=0}function AU(u){var f=this.has(u)&&delete this.__data__[u];return this.size-=f?1:0,f}function OU(u){var f=this.__data__;if(zl){var m=f[u];return m===o?t:m}return $r.call(f,u)?f[u]:t}function $U(u){var f=this.__data__;return zl?f[u]!==t:$r.call(f,u)}function xU(u,f){var m=this.__data__;return this.size+=this.has(u)?0:1,m[u]=zl&&f===t?o:f,this}vu.prototype.clear=PU,vu.prototype.delete=AU,vu.prototype.get=OU,vu.prototype.has=$U,vu.prototype.set=xU;function xa(u){var f=-1,m=u==null?0:u.length;for(this.clear();++f<m;){var C=u[f];this.set(C[0],C[1])}}function MU(){this.__data__=[],this.size=0}function DU(u){var f=this.__data__,m=fh(f,u);if(m<0)return!1;var C=f.length-1;return m==C?f.pop():sh.call(f,m,1),--this.size,!0}function NU(u){var f=this.__data__,m=fh(f,u);return m<0?t:f[m][1]}function LU(u){return fh(this.__data__,u)>-1}function FU(u,f){var m=this.__data__,C=fh(m,u);return C<0?(++this.size,m.push([u,f])):m[C][1]=f,this}xa.prototype.clear=MU,xa.prototype.delete=DU,xa.prototype.get=NU,xa.prototype.has=LU,xa.prototype.set=FU;function Ma(u){var f=-1,m=u==null?0:u.length;for(this.clear();++f<m;){var C=u[f];this.set(C[0],C[1])}}function UU(){this.size=0,this.__data__={hash:new vu,map:new(Vl||xa),string:new vu}}function jU(u){var f=Eh(this,u).delete(u);return this.size-=f?1:0,f}function BU(u){return Eh(this,u).get(u)}function qU(u){return Eh(this,u).has(u)}function WU(u,f){var m=Eh(this,u),C=m.size;return m.set(u,f),this.size+=m.size==C?0:1,this}Ma.prototype.clear=UU,Ma.prototype.delete=jU,Ma.prototype.get=BU,Ma.prototype.has=qU,Ma.prototype.set=WU;function gu(u){var f=-1,m=u==null?0:u.length;for(this.__data__=new Ma;++f<m;)this.add(u[f])}function HU(u){return this.__data__.set(u,o),this}function VU(u){return this.__data__.has(u)}gu.prototype.add=gu.prototype.push=HU,gu.prototype.has=VU;function xs(u){var f=this.__data__=new xa(u);this.size=f.size}function GU(){this.__data__=new xa,this.size=0}function zU(u){var f=this.__data__,m=f.delete(u);return this.size=f.size,m}function KU(u){return this.__data__.get(u)}function JU(u){return this.__data__.has(u)}function YU(u,f){var m=this.__data__;if(m instanceof xa){var C=m.__data__;if(!Vl||C.length<i-1)return C.push([u,f]),this.size=++m.size,this;m=this.__data__=new Ma(C)}return m.set(u,f),this.size=m.size,this}xs.prototype.clear=GU,xs.prototype.delete=zU,xs.prototype.get=KU,xs.prototype.has=JU,xs.prototype.set=YU;function uE(u,f){var m=Yt(u),C=!m&&Su(u),O=!m&&!C&&Ao(u),W=!m&&!C&&!O&&kc(u),ee=m||C||O||W,le=ee?Im(u.length,aU):[],ye=le.length;for(var De in u)(f||$r.call(u,De))&&!(ee&&(De=="length"||O&&(De=="offset"||De=="parent")||W&&(De=="buffer"||De=="byteLength"||De=="byteOffset")||Fa(De,ye)))&&le.push(De);return le}function cE(u){var f=u.length;return f?u[Vm(0,f-1)]:t}function XU(u,f){return Ch(Oi(u),mu(f,0,u.length))}function QU(u){return Ch(Oi(u))}function Dm(u,f,m){(m!==t&&!Ms(u[f],m)||m===t&&!(f in u))&&Da(u,f,m)}function Jl(u,f,m){var C=u[f];(!($r.call(u,f)&&Ms(C,m))||m===t&&!(f in u))&&Da(u,f,m)}function fh(u,f){for(var m=u.length;m--;)if(Ms(u[m][0],f))return m;return-1}function ZU(u,f,m,C){return ko(u,function(O,W,ee){f(C,O,m(O),ee)}),C}function lE(u,f){return u&&sa(f,Fn(f),u)}function ej(u,f){return u&&sa(f,xi(f),u)}function Da(u,f,m){f=="__proto__"&&ah?ah(u,f,{configurable:!0,enumerable:!0,value:m,writable:!0}):u[f]=m}function Nm(u,f){for(var m=-1,C=f.length,O=Ce(C),W=u==null;++m<C;)O[m]=W?t:gy(u,f[m]);return O}function mu(u,f,m){return u===u&&(m!==t&&(u=u<=m?u:m),f!==t&&(u=u>=f?u:f)),u}function os(u,f,m,C,O,W){var ee,le=f&h,ye=f&p,De=f&y;if(m&&(ee=O?m(u,C,O,W):m(u)),ee!==t)return ee;if(!on(u))return u;var Ne=Yt(u);if(Ne){if(ee=qj(u),!le)return Oi(u,ee)}else{var qe=Xn(u),nt=qe==cn||qe==Ot;if(Ao(u))return ME(u,le);if(qe==Ue||qe==wt||nt&&!O){if(ee=ye||nt?{}:ZE(u),!le)return ye?Oj(u,ej(ee,u)):Aj(u,lE(ee,u))}else{if(!Tr[qe])return O?u:{};ee=Wj(u,qe,le)}}W||(W=new xs);var Tt=W.get(u);if(Tt)return Tt;W.set(u,ee),IC(u)?u.forEach(function(Ft){ee.add(os(Ft,f,m,Ft,u,W))}):kC(u)&&u.forEach(function(Ft,lr){ee.set(lr,os(Ft,f,m,lr,u,W))});var Lt=De?ye?ry:ty:ye?xi:Fn,nr=Ne?t:Lt(u);return S(nr||u,function(Ft,lr){nr&&(lr=Ft,Ft=u[lr]),Jl(ee,lr,os(Ft,f,m,lr,u,W))}),ee}function tj(u){var f=Fn(u);return function(m){return dE(m,u,f)}}function dE(u,f,m){var C=m.length;if(u==null)return!C;for(u=zr(u);C--;){var O=m[C],W=f[O],ee=u[O];if(ee===t&&!(O in u)||!W(ee))return!1}return!0}function fE(u,f,m){if(typeof u!="function")throw new ss(a);return rd(function(){u.apply(t,m)},f)}function Yl(u,f,m,C){var O=-1,W=q,ee=!0,le=u.length,ye=[],De=f.length;if(!le)return ye;m&&(f=J(f,Gi(m))),C?(W=V,ee=!1):f.length>=i&&(W=Wl,ee=!1,f=new gu(f));e:for(;++O<le;){var Ne=u[O],qe=m==null?Ne:m(Ne);if(Ne=C||Ne!==0?Ne:0,ee&&qe===qe){for(var nt=De;nt--;)if(f[nt]===qe)continue e;ye.push(Ne)}else W(f,qe,C)||ye.push(Ne)}return ye}var ko=UE(ia),hE=UE(Fm,!0);function rj(u,f){var m=!0;return ko(u,function(C,O,W){return m=!!f(C,O,W),m}),m}function hh(u,f,m){for(var C=-1,O=u.length;++C<O;){var W=u[C],ee=f(W);if(ee!=null&&(le===t?ee===ee&&!Ki(ee):m(ee,le)))var le=ee,ye=W}return ye}function nj(u,f,m,C){var O=u.length;for(m=tr(m),m<0&&(m=-m>O?0:O+m),C=C===t||C>O?O:tr(C),C<0&&(C+=O),C=m>C?0:AC(C);m<C;)u[m++]=f;return u}function pE(u,f){var m=[];return ko(u,function(C,O,W){f(C,O,W)&&m.push(C)}),m}function Hn(u,f,m,C,O){var W=-1,ee=u.length;for(m||(m=Vj),O||(O=[]);++W<ee;){var le=u[W];f>0&&m(le)?f>1?Hn(le,f-1,m,C,O):ae(O,le):C||(O[O.length]=le)}return O}var Lm=jE(),vE=jE(!0);function ia(u,f){return u&&Lm(u,f,Fn)}function Fm(u,f){return u&&vE(u,f,Fn)}function ph(u,f){return I(f,function(m){return Ua(u[m])})}function yu(u,f){f=Io(f,u);for(var m=0,C=f.length;u!=null&&m<C;)u=u[aa(f[m++])];return m&&m==C?u:t}function gE(u,f,m){var C=f(u);return Yt(u)?C:ae(C,m(u))}function fi(u){return u==null?u===t?hn:zt:pu&&pu in zr(u)?Uj(u):Qj(u)}function Um(u,f){return u>f}function ij(u,f){return u!=null&&$r.call(u,f)}function sj(u,f){return u!=null&&f in zr(u)}function aj(u,f,m){return u>=Yn(f,m)&&u<Pn(f,m)}function jm(u,f,m){for(var C=m?V:q,O=u[0].length,W=u.length,ee=W,le=Ce(W),ye=1/0,De=[];ee--;){var Ne=u[ee];ee&&f&&(Ne=J(Ne,Gi(f))),ye=Yn(Ne.length,ye),le[ee]=!m&&(f||O>=120&&Ne.length>=120)?new gu(ee&&Ne):t}Ne=u[0];var qe=-1,nt=le[0];e:for(;++qe<O&&De.length<ye;){var Tt=Ne[qe],Lt=f?f(Tt):Tt;if(Tt=m||Tt!==0?Tt:0,!(nt?Wl(nt,Lt):C(De,Lt,m))){for(ee=W;--ee;){var nr=le[ee];if(!(nr?Wl(nr,Lt):C(u[ee],Lt,m)))continue e}nt&&nt.push(Lt),De.push(Tt)}}return De}function oj(u,f,m,C){return ia(u,function(O,W,ee){f(C,m(O),W,ee)}),C}function Xl(u,f,m){f=Io(f,u),u=nC(u,f);var C=u==null?u:u[aa(cs(f))];return C==null?t:b(C,u,m)}function mE(u){return dn(u)&&fi(u)==wt}function uj(u){return dn(u)&&fi(u)==kt}function cj(u){return dn(u)&&fi(u)==It}function Ql(u,f,m,C,O){return u===f?!0:u==null||f==null||!dn(u)&&!dn(f)?u!==u&&f!==f:lj(u,f,m,C,Ql,O)}function lj(u,f,m,C,O,W){var ee=Yt(u),le=Yt(f),ye=ee?te:Xn(u),De=le?te:Xn(f);ye=ye==wt?Ue:ye,De=De==wt?Ue:De;var Ne=ye==Ue,qe=De==Ue,nt=ye==De;if(nt&&Ao(u)){if(!Ao(f))return!1;ee=!0,Ne=!1}if(nt&&!Ne)return W||(W=new xs),ee||kc(u)?YE(u,f,m,C,O,W):Lj(u,f,ye,m,C,O,W);if(!(m&w)){var Tt=Ne&&$r.call(u,"__wrapped__"),Lt=qe&&$r.call(f,"__wrapped__");if(Tt||Lt){var nr=Tt?u.value():u,Ft=Lt?f.value():f;return W||(W=new xs),O(nr,Ft,m,C,W)}}return nt?(W||(W=new xs),Fj(u,f,m,C,O,W)):!1}function dj(u){return dn(u)&&Xn(u)==$e}function Bm(u,f,m,C){var O=m.length,W=O,ee=!C;if(u==null)return!W;for(u=zr(u);O--;){var le=m[O];if(ee&&le[2]?le[1]!==u[le[0]]:!(le[0]in u))return!1}for(;++O<W;){le=m[O];var ye=le[0],De=u[ye],Ne=le[1];if(ee&&le[2]){if(De===t&&!(ye in u))return!1}else{var qe=new xs;if(C)var nt=C(De,Ne,ye,u,f,qe);if(!(nt===t?Ql(Ne,De,w|k,C,qe):nt))return!1}}return!0}function yE(u){if(!on(u)||zj(u))return!1;var f=Ua(u)?dU:Bn;return f.test(bu(u))}function fj(u){return dn(u)&&fi(u)==Lr}function hj(u){return dn(u)&&Xn(u)==dr}function pj(u){return dn(u)&&Oh(u.length)&&!!Or[fi(u)]}function _E(u){return typeof u=="function"?u:u==null?Mi:ps.default(u)=="object"?Yt(u)?wE(u[0],u[1]):SE(u):BC(u)}function qm(u){if(!td(u))return mU(u);var f=[];for(var m in zr(u))$r.call(u,m)&&m!="constructor"&&f.push(m);return f}function vj(u){if(!on(u))return Xj(u);var f=td(u),m=[];for(var C in u)C=="constructor"&&(f||!$r.call(u,C))||m.push(C);return m}function Wm(u,f){return u<f}function bE(u,f){var m=-1,C=$i(u)?Ce(u.length):[];return ko(u,function(O,W,ee){C[++m]=f(O,W,ee)}),C}function SE(u){var f=iy(u);return f.length==1&&f[0][2]?tC(f[0][0],f[0][1]):function(m){return m===u||Bm(m,u,f)}}function wE(u,f){return ay(u)&&eC(f)?tC(aa(u),f):function(m){var C=gy(m,u);return C===t&&C===f?my(m,u):Ql(f,C,w|k)}}function vh(u,f,m,C,O){u!==f&&Lm(f,function(W,ee){if(O||(O=new xs),on(W))gj(u,f,ee,m,vh,C,O);else{var le=C?C(uy(u,ee),W,ee+"",u,f,O):t;le===t&&(le=W),Dm(u,ee,le)}},xi)}function gj(u,f,m,C,O,W,ee){var le=uy(u,m),ye=uy(f,m),De=ee.get(ye);if(De){Dm(u,m,De);return}var Ne=W?W(le,ye,m+"",u,f,ee):t,qe=Ne===t;if(qe){var nt=Yt(ye),Tt=!nt&&Ao(ye),Lt=!nt&&!Tt&&kc(ye);Ne=ye,nt||Tt||Lt?Yt(le)?Ne=le:vn(le)?Ne=Oi(le):Tt?(qe=!1,Ne=ME(ye,!0)):Lt?(qe=!1,Ne=DE(ye,!0)):Ne=[]:nd(ye)||Su(ye)?(Ne=le,Su(le)?Ne=OC(le):(!on(le)||Ua(le))&&(Ne=ZE(ye))):qe=!1}qe&&(ee.set(ye,Ne),O(Ne,ye,C,W,ee),ee.delete(ye)),Dm(u,m,Ne)}function TE(u,f){var m=u.length;if(m)return f+=f<0?m:0,Fa(f,m)?u[f]:t}function EE(u,f,m){f.length?f=J(f,function(W){return Yt(W)?function(ee){return yu(ee,W.length===1?W[0]:W)}:W}):f=[Mi];var C=-1;f=J(f,Gi(Mt()));var O=bE(u,function(W,ee,le){var ye=J(f,function(De){return De(W)});return{criteria:ye,index:++C,value:W}});return WF(O,function(W,ee){return Pj(W,ee,m)})}function mj(u,f){return CE(u,f,function(m,C){return my(u,C)})}function CE(u,f,m){for(var C=-1,O=f.length,W={};++C<O;){var ee=f[C],le=yu(u,ee);m(le,ee)&&Zl(W,Io(ee,u),le)}return W}function yj(u){return function(f){return yu(f,u)}}function Hm(u,f,m,C){var O=C?St:an,W=-1,ee=f.length,le=u;for(u===f&&(f=Oi(f)),m&&(le=J(u,Gi(m)));++W<ee;)for(var ye=0,De=f[W],Ne=m?m(De):De;(ye=O(le,Ne,ye,C))>-1;)le!==u&&sh.call(le,ye,1),sh.call(u,ye,1);return u}function kE(u,f){for(var m=u?f.length:0,C=m-1;m--;){var O=f[m];if(m==C||O!==W){var W=O;Fa(O)?sh.call(u,O,1):Km(u,O)}}return u}function Vm(u,f){return u+uh(aE()*(f-u+1))}function _j(u,f,m,C){for(var O=-1,W=Pn(oh((f-u)/(m||1)),0),ee=Ce(W);W--;)ee[C?W:++O]=u,u+=m;return ee}function Gm(u,f){var m="";if(!u||f<1||f>Je)return m;do f%2&&(m+=u),f=uh(f/2),f&&(u+=u);while(f);return m}function ar(u,f){return cy(rC(u,f,Mi),u+"")}function bj(u){return cE(Rc(u))}function Sj(u,f){var m=Rc(u);return Ch(m,mu(f,0,m.length))}function Zl(u,f,m,C){if(!on(u))return u;f=Io(f,u);for(var O=-1,W=f.length,ee=W-1,le=u;le!=null&&++O<W;){var ye=aa(f[O]),De=m;if(ye==="__proto__"||ye==="constructor"||ye==="prototype")return u;if(O!=ee){var Ne=le[ye];De=C?C(Ne,ye,le):t,De===t&&(De=on(Ne)?Ne:Fa(f[O+1])?[]:{})}Jl(le,ye,De),le=le[ye]}return u}var RE=ch?function(u,f){return ch.set(u,f),u}:Mi,wj=ah?function(u,f){return ah(u,"toString",{configurable:!0,enumerable:!1,value:_y(f),writable:!0})}:Mi;function Tj(u){return Ch(Rc(u))}function us(u,f,m){var C=-1,O=u.length;f<0&&(f=-f>O?0:O+f),m=m>O?O:m,m<0&&(m+=O),O=f>m?0:m-f>>>0,f>>>=0;for(var W=Ce(O);++C<O;)W[C]=u[C+f];return W}function Ej(u,f){var m;return ko(u,function(C,O,W){return m=f(C,O,W),!m}),!!m}function gh(u,f,m){var C=0,O=u==null?C:u.length;if(typeof f=="number"&&f===f&&O<=Nt){for(;C<O;){var W=C+O>>>1,ee=u[W];ee!==null&&!Ki(ee)&&(m?ee<=f:ee<f)?C=W+1:O=W}return O}return zm(u,f,Mi,m)}function zm(u,f,m,C){var O=0,W=u==null?0:u.length;if(W===0)return 0;f=m(f);for(var ee=f!==f,le=f===null,ye=Ki(f),De=f===t;O<W;){var Ne=uh((O+W)/2),qe=m(u[Ne]),nt=qe!==t,Tt=qe===null,Lt=qe===qe,nr=Ki(qe);if(ee)var Ft=C||Lt;else De?Ft=Lt&&(C||nt):le?Ft=Lt&&nt&&(C||!Tt):ye?Ft=Lt&&nt&&!Tt&&(C||!nr):Tt||nr?Ft=!1:Ft=C?qe<=f:qe<f;Ft?O=Ne+1:W=Ne}return Yn(W,Ct)}function IE(u,f){for(var m=-1,C=u.length,O=0,W=[];++m<C;){var ee=u[m],le=f?f(ee):ee;if(!m||!Ms(le,ye)){var ye=le;W[O++]=ee===0?0:ee}}return W}function PE(u){return typeof u=="number"?u:Ki(u)?Y:+u}function zi(u){if(typeof u=="string")return u;if(Yt(u))return J(u,zi)+"";if(Ki(u))return oE?oE.call(u):"";var f=u+"";return f=="0"&&1/u==-Re?"-0":f}function Ro(u,f,m){var C=-1,O=q,W=u.length,ee=!0,le=[],ye=le;if(m)ee=!1,O=V;else if(W>=i){var De=f?null:Dj(u);if(De)return Xf(De);ee=!1,O=Wl,ye=new gu}else ye=f?[]:le;e:for(;++C<W;){var Ne=u[C],qe=f?f(Ne):Ne;if(Ne=m||Ne!==0?Ne:0,ee&&qe===qe){for(var nt=ye.length;nt--;)if(ye[nt]===qe)continue e;f&&ye.push(qe),le.push(Ne)}else O(ye,qe,m)||(ye!==le&&ye.push(qe),le.push(Ne))}return le}function Km(u,f){return f=Io(f,u),u=nC(u,f),u==null||delete u[aa(cs(f))]}function AE(u,f,m,C){return Zl(u,f,m(yu(u,f)),C)}function mh(u,f,m,C){for(var O=u.length,W=C?O:-1;(C?W--:++W<O)&&f(u[W],W,u););return m?us(u,C?0:W,C?W+1:O):us(u,C?W+1:0,C?O:W)}function OE(u,f){var m=u;return m instanceof cr&&(m=m.value()),Se(f,function(C,O){return O.func.apply(O.thisArg,ae([C],O.args))},m)}function Jm(u,f,m){var C=u.length;if(C<2)return C?Ro(u[0]):[];for(var O=-1,W=Ce(C);++O<C;)for(var ee=u[O],le=-1;++le<C;)le!=O&&(W[O]=Yl(W[O]||ee,u[le],f,m));return Ro(Hn(W,1),f,m)}function $E(u,f,m){for(var C=-1,O=u.length,W=f.length,ee={};++C<O;){var le=C<W?f[C]:t;m(ee,u[C],le)}return ee}function Ym(u){return vn(u)?u:[]}function Xm(u){return typeof u=="function"?u:Mi}function Io(u,f){return Yt(u)?u:ay(u,f)?[u]:oC(kr(u))}var Cj=ar;function Po(u,f,m){var C=u.length;return m=m===t?C:m,!f&&m>=C?u:us(u,f,m)}var xE=fU||function(u){return $t.clearTimeout(u)};function ME(u,f){if(f)return u.slice();var m=u.length,C=tE?tE(m):new u.constructor(m);return u.copy(C),C}function Qm(u){var f=new u.constructor(u.byteLength);return new nh(f).set(new nh(u)),f}function kj(u,f){var m=f?Qm(u.buffer):u.buffer;return new u.constructor(m,u.byteOffset,u.byteLength)}function Rj(u){var f=new u.constructor(u.source,qt.exec(u));return f.lastIndex=u.lastIndex,f}function Ij(u){return Kl?zr(Kl.call(u)):{}}function DE(u,f){var m=f?Qm(u.buffer):u.buffer;return new u.constructor(m,u.byteOffset,u.length)}function NE(u,f){if(u!==f){var m=u!==t,C=u===null,O=u===u,W=Ki(u),ee=f!==t,le=f===null,ye=f===f,De=Ki(f);if(!le&&!De&&!W&&u>f||W&&ee&&ye&&!le&&!De||C&&ee&&ye||!m&&ye||!O)return 1;if(!C&&!W&&!De&&u<f||De&&m&&O&&!C&&!W||le&&m&&O||!ee&&O||!ye)return-1}return 0}function Pj(u,f,m){for(var C=-1,O=u.criteria,W=f.criteria,ee=O.length,le=m.length;++C<ee;){var ye=NE(O[C],W[C]);if(ye){if(C>=le)return ye;var De=m[C];return ye*(De=="desc"?-1:1)}}return u.index-f.index}function LE(u,f,m,C){for(var O=-1,W=u.length,ee=m.length,le=-1,ye=f.length,De=Pn(W-ee,0),Ne=Ce(ye+De),qe=!C;++le<ye;)Ne[le]=f[le];for(;++O<ee;)(qe||O<W)&&(Ne[m[O]]=u[O]);for(;De--;)Ne[le++]=u[O++];return Ne}function FE(u,f,m,C){for(var O=-1,W=u.length,ee=-1,le=m.length,ye=-1,De=f.length,Ne=Pn(W-le,0),qe=Ce(Ne+De),nt=!C;++O<Ne;)qe[O]=u[O];for(var Tt=O;++ye<De;)qe[Tt+ye]=f[ye];for(;++ee<le;)(nt||O<W)&&(qe[Tt+m[ee]]=u[O++]);return qe}function Oi(u,f){var m=-1,C=u.length;for(f||(f=Ce(C));++m<C;)f[m]=u[m];return f}function sa(u,f,m,C){var O=!m;m||(m={});for(var W=-1,ee=f.length;++W<ee;){var le=f[W],ye=C?C(m[le],u[le],le,m,u):t;ye===t&&(ye=u[le]),O?Da(m,le,ye):Jl(m,le,ye)}return m}function Aj(u,f){return sa(u,sy(u),f)}function Oj(u,f){return sa(u,XE(u),f)}function yh(u,f){return function(m,C){var O=Yt(m)?_:ZU,W=f?f():{};return O(m,u,Mt(C,2),W)}}function Tc(u){return ar(function(f,m){var C=-1,O=m.length,W=O>1?m[O-1]:t,ee=O>2?m[2]:t;for(W=u.length>3&&typeof W=="function"?(O--,W):t,ee&&hi(m[0],m[1],ee)&&(W=O<3?t:W,O=1),f=zr(f);++C<O;){var le=m[C];le&&u(f,le,C,W)}return f})}function UE(u,f){return function(m,C){if(m==null)return m;if(!$i(m))return u(m,C);for(var O=m.length,W=f?O:-1,ee=zr(m);(f?W--:++W<O)&&C(ee[W],W,ee)!==!1;);return m}}function jE(u){return function(f,m,C){for(var O=-1,W=zr(f),ee=C(f),le=ee.length;le--;){var ye=ee[u?le:++O];if(m(W[ye],ye,W)===!1)break}return f}}function $j(u,f,m){var C=f&P,O=ed(u);function W(){var ee=this&&this!==$t&&this instanceof W?O:u;return ee.apply(C?m:this,arguments)}return W}function BE(u){return function(f){f=kr(f);var m=gc(f)?$s(f):t,C=m?m[0]:f.charAt(0),O=m?Po(m,1).join(""):f.slice(1);return C[u]()+O}}function Ec(u){return function(f){return Se(UC(FC(f).replace(Vi,"")),u,"")}}function ed(u){return function(){var f=arguments;switch(f.length){case 0:return new u;case 1:return new u(f[0]);case 2:return new u(f[0],f[1]);case 3:return new u(f[0],f[1],f[2]);case 4:return new u(f[0],f[1],f[2],f[3]);case 5:return new u(f[0],f[1],f[2],f[3],f[4]);case 6:return new u(f[0],f[1],f[2],f[3],f[4],f[5]);case 7:return new u(f[0],f[1],f[2],f[3],f[4],f[5],f[6])}var m=wc(u.prototype),C=u.apply(m,f);return on(C)?C:m}}function xj(u,f,m){var C=ed(u);function O(){for(var W=arguments.length,ee=Ce(W),le=W,ye=Cc(O);le--;)ee[le]=arguments[le];var De=W<3&&ee[0]!==ye&&ee[W-1]!==ye?[]:Eo(ee,ye);if(W-=De.length,W<m)return GE(u,f,_h,O.placeholder,t,ee,De,t,t,m-W);var Ne=this&&this!==$t&&this instanceof O?C:u;return b(Ne,this,ee)}return O}function qE(u){return function(f,m,C){var O=zr(f);if(!$i(f)){var W=Mt(m,3);f=Fn(f),m=function(ye){return W(O[ye],ye,O)}}var ee=u(f,m,C);return ee>-1?O[W?f[ee]:ee]:t}}function WE(u){return La(function(f){var m=f.length,C=m,O=as.prototype.thru;for(u&&f.reverse();C--;){var W=f[C];if(typeof W!="function")throw new ss(a);if(O&&!ee&&Th(W)=="wrapper")var ee=new as([],!0)}for(C=ee?C:m;++C<m;){W=f[C];var le=Th(W),ye=le=="wrapper"?ny(W):t;ye&&oy(ye[0])&&ye[1]==(K|L|F|D)&&!ye[4].length&&ye[9]==1?ee=ee[Th(ye[0])].apply(ee,ye[3]):ee=W.length==1&&oy(W)?ee[le]():ee.thru(W)}return function(){var De=arguments,Ne=De[0];if(ee&&De.length==1&&Yt(Ne))return ee.plant(Ne).value();for(var qe=0,nt=m?f[qe].apply(this,De):Ne;++qe<m;)nt=f[qe].call(this,nt);return nt}})}function _h(u,f,m,C,O,W,ee,le,ye,De){var Ne=f&K,qe=f&P,nt=f&A,Tt=f&(L|$),Lt=f&he,nr=nt?t:ed(u);function Ft(){for(var lr=arguments.length,gr=Ce(lr),Qn=lr;Qn--;)gr[Qn]=arguments[Qn];if(Tt)var pi=Cc(Ft),Ji=VF(gr,pi);if(C&&(gr=LE(gr,C,O,Tt)),W&&(gr=FE(gr,W,ee,Tt)),lr-=Ji,Tt&&lr<De){var gn=Eo(gr,pi);return GE(u,f,_h,Ft.placeholder,m,gr,gn,le,ye,De-lr)}var Ds=qe?m:this,Ba=nt?Ds[u]:u;return lr=gr.length,le?gr=Zj(gr,le):Lt&&lr>1&&gr.reverse(),Ne&&ye<lr&&(gr.length=ye),this&&this!==$t&&this instanceof Ft&&(Ba=nr||ed(Ba)),Ba.apply(Ds,gr)}return Ft}function HE(u,f){return function(m,C){return oj(m,u,f(C),{})}}function bh(u,f){return function(m,C){var O;if(m===t&&C===t)return f;if(m!==t&&(O=m),C!==t){if(O===t)return C;typeof m=="string"||typeof C=="string"?(m=zi(m),C=zi(C)):(m=PE(m),C=PE(C)),O=u(m,C)}return O}}function Zm(u){return La(function(f){return f=J(f,Gi(Mt())),ar(function(m){var C=this;return u(f,function(O){return b(O,C,m)})})})}function Sh(u,f){f=f===t?" ":zi(f);var m=f.length;if(m<2)return m?Gm(f,u):f;var C=Gm(f,oh(u/mc(f)));return gc(f)?Po($s(C),0,u).join(""):C.slice(0,u)}function Mj(u,f,m,C){var O=f&P,W=ed(u);function ee(){for(var le=-1,ye=arguments.length,De=-1,Ne=C.length,qe=Ce(Ne+ye),nt=this&&this!==$t&&this instanceof ee?W:u;++De<Ne;)qe[De]=C[De];for(;ye--;)qe[De++]=arguments[++le];return b(nt,O?m:this,qe)}return ee}function VE(u){return function(f,m,C){return C&&typeof C!="number"&&hi(f,m,C)&&(m=C=t),f=ja(f),m===t?(m=f,f=0):m=ja(m),C=C===t?f<m?1:-1:ja(C),_j(f,m,C,u)}}function wh(u){return function(f,m){return typeof f=="string"&&typeof m=="string"||(f=ls(f),m=ls(m)),u(f,m)}}function GE(u,f,m,C,O,W,ee,le,ye,De){var Ne=f&L,qe=Ne?ee:t,nt=Ne?t:ee,Tt=Ne?W:t,Lt=Ne?t:W;f|=Ne?F:G,f&=~(Ne?G:F),f&B||(f&=-4);var nr=[u,f,O,Tt,qe,Lt,nt,le,ye,De],Ft=m.apply(t,nr);return oy(u)&&iC(Ft,nr),Ft.placeholder=C,sC(Ft,u,f)}function ey(u){var f=In[u];return function(m,C){if(m=ls(m),C=C==null?0:Yn(tr(C),292),C&&sE(m)){var O=(kr(m)+"e").split("e"),W=f(O[0]+"e"+(+O[1]+C));return O=(kr(W)+"e").split("e"),+(O[0]+"e"+(+O[1]-C))}return f(m)}}var Dj=bc&&1/Xf(new bc([,-0]))[1]==Re?function(u){return new bc(u)}:wy;function zE(u){return function(f){var m=Xn(f);return m==$e?Am(f):m==dr?QF(f):HF(f,u(f))}}function Na(u,f,m,C,O,W,ee,le){var ye=f&A;if(!ye&&typeof u!="function")throw new ss(a);var De=C?C.length:0;if(De||(f&=-97,C=O=t),ee=ee===t?ee:Pn(tr(ee),0),le=le===t?le:tr(le),De-=O?O.length:0,f&G){var Ne=C,qe=O;C=O=t}var nt=ye?t:ny(u),Tt=[u,f,m,C,O,Ne,qe,W,ee,le];if(nt&&Yj(Tt,nt),u=Tt[0],f=Tt[1],m=Tt[2],C=Tt[3],O=Tt[4],le=Tt[9]=Tt[9]===t?ye?0:u.length:Pn(Tt[9]-De,0),!le&&f&(L|$)&&(f&=-25),!f||f==P)var Lt=$j(u,f,m);else f==L||f==$?Lt=xj(u,f,le):(f==F||f==(P|F))&&!O.length?Lt=Mj(u,f,m,C):Lt=_h.apply(t,Tt);var nr=nt?RE:iC;return sC(nr(Lt,Tt),u,f)}function KE(u,f,m,C){return u===t||Ms(u,_c[m])&&!$r.call(C,m)?f:u}function JE(u,f,m,C,O,W){return on(u)&&on(f)&&(W.set(f,u),vh(u,f,t,JE,W),W.delete(f)),u}function Nj(u){return nd(u)?t:u}function YE(u,f,m,C,O,W){var ee=m&w,le=u.length,ye=f.length;if(le!=ye&&!(ee&&ye>le))return!1;var De=W.get(u),Ne=W.get(f);if(De&&Ne)return De==f&&Ne==u;var qe=-1,nt=!0,Tt=m&k?new gu:t;for(W.set(u,f),W.set(f,u);++qe<le;){var Lt=u[qe],nr=f[qe];if(C)var Ft=ee?C(nr,Lt,qe,f,u,W):C(Lt,nr,qe,u,f,W);if(Ft!==t){if(Ft)continue;nt=!1;break}if(Tt){if(!gt(f,function(lr,gr){if(!Wl(Tt,gr)&&(Lt===lr||O(Lt,lr,m,C,W)))return Tt.push(gr)})){nt=!1;break}}else if(!(Lt===nr||O(Lt,nr,m,C,W))){nt=!1;break}}return W.delete(u),W.delete(f),nt}function Lj(u,f,m,C,O,W,ee){switch(m){case yt:if(u.byteLength!=f.byteLength||u.byteOffset!=f.byteOffset)return!1;u=u.buffer,f=f.buffer;case kt:return!(u.byteLength!=f.byteLength||!W(new nh(u),new nh(f)));case ut:case It:case _t:return Ms(+u,+f);case rt:return u.name==f.name&&u.message==f.message;case Lr:case tn:return u==f+"";case $e:var le=Am;case dr:var ye=C&w;if(le||(le=Xf),u.size!=f.size&&!ye)return!1;var De=ee.get(u);if(De)return De==f;C|=k,ee.set(u,f);var Ne=YE(le(u),le(f),C,O,W,ee);return ee.delete(u),Ne;case yn:if(Kl)return Kl.call(u)==Kl.call(f)}return!1}function Fj(u,f,m,C,O,W){var ee=m&w,le=ty(u),ye=le.length,De=ty(f),Ne=De.length;if(ye!=Ne&&!ee)return!1;for(var qe=ye;qe--;){var nt=le[qe];if(!(ee?nt in f:$r.call(f,nt)))return!1}var Tt=W.get(u),Lt=W.get(f);if(Tt&&Lt)return Tt==f&&Lt==u;var nr=!0;W.set(u,f),W.set(f,u);for(var Ft=ee;++qe<ye;){nt=le[qe];var lr=u[nt],gr=f[nt];if(C)var Qn=ee?C(gr,lr,nt,f,u,W):C(lr,gr,nt,u,f,W);if(!(Qn===t?lr===gr||O(lr,gr,m,C,W):Qn)){nr=!1;break}Ft||(Ft=nt=="constructor")}if(nr&&!Ft){var pi=u.constructor,Ji=f.constructor;pi!=Ji&&"constructor"in u&&"constructor"in f&&!(typeof pi=="function"&&pi instanceof pi&&typeof Ji=="function"&&Ji instanceof Ji)&&(nr=!1)}return W.delete(u),W.delete(f),nr}function La(u){return cy(rC(u,t,dC),u+"")}function ty(u){return gE(u,Fn,sy)}function ry(u){return gE(u,xi,XE)}var ny=ch?function(u){return ch.get(u)}:wy;function Th(u){for(var f=u.name+"",m=Sc[f],C=$r.call(Sc,f)?m.length:0;C--;){var O=m[C],W=O.func;if(W==null||W==u)return O.name}return f}function Cc(u){var f=$r.call(U,"placeholder")?U:u;return f.placeholder}function Mt(){var u=U.iteratee||by;return u=u===by?_E:u,arguments.length?u(arguments[0],arguments[1]):u}function Eh(u,f){var m=u.__data__;return Gj(f)?m[typeof f=="string"?"string":"hash"]:m.map}function iy(u){for(var f=Fn(u),m=f.length;m--;){var C=f[m],O=u[C];f[m]=[C,O,eC(O)]}return f}function _u(u,f){var m=JF(u,f);return yE(m)?m:t}function Uj(u){var f=$r.call(u,pu),m=u[pu];try{u[pu]=t;var C=!0}catch{}var O=th.call(u);return C&&(f?u[pu]=m:delete u[pu]),O}var sy=$m?function(u){return u==null?[]:(u=zr(u),I($m(u),function(f){return nE.call(u,f)}))}:Ty,XE=$m?function(u){for(var f=[];u;)ae(f,sy(u)),u=ih(u);return f}:Ty,Xn=fi;(xm&&Xn(new xm(new ArrayBuffer(1)))!=yt||Vl&&Xn(new Vl)!=$e||Mm&&Xn(Mm.resolve())!=vr||bc&&Xn(new bc)!=dr||Gl&&Xn(new Gl)!=Kt)&&(Xn=function(f){var m=fi(f),C=m==Ue?f.constructor:t,O=C?bu(C):"";if(O)switch(O){case SU:return yt;case wU:return $e;case TU:return vr;case EU:return dr;case CU:return Kt}return m});function jj(u,f,m){for(var C=-1,O=m.length;++C<O;){var W=m[C],ee=W.size;switch(W.type){case"drop":u+=ee;break;case"dropRight":f-=ee;break;case"take":f=Yn(f,u+ee);break;case"takeRight":u=Pn(u,f-ee);break}}return{start:u,end:f}}function Bj(u){var f=u.match(jt);return f?f[1].split(pt):[]}function QE(u,f,m){f=Io(f,u);for(var C=-1,O=f.length,W=!1;++C<O;){var ee=aa(f[C]);if(!(W=u!=null&&m(u,ee)))break;u=u[ee]}return W||++C!=O?W:(O=u==null?0:u.length,!!O&&Oh(O)&&Fa(ee,O)&&(Yt(u)||Su(u)))}function qj(u){var f=u.length,m=new u.constructor(f);return f&&typeof u[0]=="string"&&$r.call(u,"index")&&(m.index=u.index,m.input=u.input),m}function ZE(u){return typeof u.constructor=="function"&&!td(u)?wc(ih(u)):{}}function Wj(u,f,m){var C=u.constructor;switch(f){case kt:return Qm(u);case ut:case It:return new C(+u);case yt:return kj(u,m);case Xt:case nn:case Qr:case Mn:case kn:case Rn:case sr:case Fr:case ke:return DE(u,m);case $e:return new C;case _t:case tn:return new C(u);case Lr:return Rj(u);case dr:return new C;case yn:return Ij(u)}}function Hj(u,f){var m=f.length;if(!m)return u;var C=m-1;return f[C]=(m>1?"& ":"")+f[C],f=f.join(m>2?", ":" "),u.replace(ht,`{
366
366
  /* [wrapped with `+f+`] */
367
- `)}function Vj(u){return Yt(u)||Su(u)||!!(iE&&u&&u[iE])}function Fa(u,f){var m=ps.default(u);return f=f??Je,!!f&&(m=="number"||m!="symbol"&&ce.test(u))&&u>-1&&u%1==0&&u<f}function hi(u,f,m){if(!on(m))return!1;var C=ps.default(f);return(C=="number"?$i(m)&&Fa(f,m.length):C=="string"&&f in m)?Ms(m[f],u):!1}function ay(u,f){if(Yt(u))return!1;var m=ps.default(u);return m=="number"||m=="symbol"||m=="boolean"||u==null||Ki(u)?!0:Qe.test(u)||!ue.test(u)||f!=null&&u in zr(f)}function Gj(u){var f=ps.default(u);return f=="string"||f=="number"||f=="symbol"||f=="boolean"?u!=="__proto__":u===null}function oy(u){var f=Th(u),m=U[f];if(typeof m!="function"||!(f in cr.prototype))return!1;if(u===m)return!0;var C=ny(m);return!!C&&u===C[0]}function zj(u){return!!eE&&eE in u}var Kj=Zf?Ua:Ey;function td(u){var f=u&&u.constructor,m=typeof f=="function"&&f.prototype||_c;return u===m}function eC(u){return u===u&&!on(u)}function tC(u,f){return function(m){return m==null?!1:m[u]===f&&(f!==t||u in zr(m))}}function Jj(u){var f=Ph(u,function(C){return m.size===l&&m.clear(),C}),m=f.cache;return f}function Yj(u,f){var m=u[1],C=f[1],O=m|C,W=O<(P|A|K),ee=C==K&&m==L||C==K&&m==D&&u[7].length<=f[8]||C==(K|D)&&f[7].length<=f[8]&&m==L;if(!(W||ee))return u;C&P&&(u[2]=f[2],O|=m&P?0:B);var le=f[3];if(le){var ye=u[3];u[3]=ye?LE(ye,le,f[4]):le,u[4]=ye?Eo(u[3],d):f[4]}return le=f[5],le&&(ye=u[5],u[5]=ye?FE(ye,le,f[6]):le,u[6]=ye?Eo(u[5],d):f[6]),le=f[7],le&&(u[7]=le),C&K&&(u[8]=u[8]==null?f[8]:Yn(u[8],f[8])),u[9]==null&&(u[9]=f[9]),u[0]=f[0],u[1]=O,u}function Xj(u){var f=[];if(u!=null)for(var m in zr(u))f.push(m);return f}function Qj(u){return th.call(u)}function rC(u,f,m){return f=Pn(f===t?u.length-1:f,0),function(){for(var C=arguments,O=-1,W=Pn(C.length-f,0),ee=Ce(W);++O<W;)ee[O]=C[f+O];O=-1;for(var le=Ce(f+1);++O<f;)le[O]=C[O];return le[f]=m(ee),b(u,this,le)}}function nC(u,f){return f.length<2?u:yu(u,us(f,0,-1))}function Zj(u,f){for(var m=u.length,C=Yn(f.length,m),O=Oi(u);C--;){var W=f[C];u[C]=Fa(W,m)?O[W]:t}return u}function uy(u,f){if(!(f==="constructor"&&typeof u[f]=="function")&&f!="__proto__")return u[f]}var iC=aC(RE),rd=pU||function(u,f){return $t.setTimeout(u,f)},cy=aC(wj);function sC(u,f,m){var C=f+"";return cy(u,Hj(C,e3(Bj(C),m)))}function aC(u){var f=0,m=0;return function(){var C=yU(),O=Oe-(C-m);if(m=C,O>0){if(++f>=Q)return arguments[0]}else f=0;return u.apply(t,arguments)}}function Ch(u,f){var m=-1,C=u.length,O=C-1;for(f=f===t?C:f;++m<f;){var W=Vm(m,O),ee=u[W];u[W]=u[m],u[m]=ee}return u.length=f,u}var oC=Jj(function(u){var f=[];return u.charCodeAt(0)===46&&f.push(""),u.replace(Me,function(m,C,O,W){f.push(O?W.replace(Ur,"$1"):C||m)}),f});function aa(u){if(typeof u=="string"||Ki(u))return u;var f=u+"";return f=="0"&&1/u==-Re?"-0":f}function bu(u){if(u!=null){try{return eh.call(u)}catch{}try{return u+""}catch{}}return""}function e3(u,f){return S(Et,function(m){var C="_."+m[0];f&m[1]&&!q(u,C)&&u.push(C)}),u.sort()}function uC(u){if(u instanceof cr)return u.clone();var f=new as(u.__wrapped__,u.__chain__);return f.__actions__=Oi(u.__actions__),f.__index__=u.__index__,f.__values__=u.__values__,f}function t3(u,f,m){(m?hi(u,f,m):f===t)?f=1:f=Pn(tr(f),0);var C=u==null?0:u.length;if(!C||f<1)return[];for(var O=0,W=0,ee=Ce(oh(C/f));O<C;)ee[W++]=us(u,O,O+=f);return ee}function r3(u){for(var f=-1,m=u==null?0:u.length,C=0,O=[];++f<m;){var W=u[f];W&&(O[C++]=W)}return O}function n3(){var u=arguments.length;if(!u)return[];for(var f=Ce(u-1),m=arguments[0],C=u;C--;)f[C-1]=arguments[C];return ae(Yt(m)?Oi(m):[m],Hn(f,1))}var i3=ar(function(u,f){return vn(u)?Yl(u,Hn(f,1,vn,!0)):[]}),s3=ar(function(u,f){var m=cs(f);return vn(m)&&(m=t),vn(u)?Yl(u,Hn(f,1,vn,!0),Mt(m,2)):[]}),a3=ar(function(u,f){var m=cs(f);return vn(m)&&(m=t),vn(u)?Yl(u,Hn(f,1,vn,!0),t,m):[]});function o3(u,f,m){var C=u==null?0:u.length;return C?(f=m||f===t?1:tr(f),us(u,f<0?0:f,C)):[]}function u3(u,f,m){var C=u==null?0:u.length;return C?(f=m||f===t?1:tr(f),f=C-f,us(u,0,f<0?0:f)):[]}function c3(u,f){return u&&u.length?mh(u,Mt(f,3),!0,!0):[]}function l3(u,f){return u&&u.length?mh(u,Mt(f,3),!0):[]}function d3(u,f,m,C){var O=u==null?0:u.length;return O?(m&&typeof m!="number"&&hi(u,f,m)&&(m=0,C=O),nj(u,f,m,C)):[]}function cC(u,f,m){var C=u==null?0:u.length;if(!C)return-1;var O=m==null?0:tr(m);return O<0&&(O=Pn(C+O,0)),Zr(u,Mt(f,3),O)}function lC(u,f,m){var C=u==null?0:u.length;if(!C)return-1;var O=C-1;return m!==t&&(O=tr(m),O=m<0?Pn(C+O,0):Yn(O,C-1)),Zr(u,Mt(f,3),O,!0)}function dC(u){var f=u==null?0:u.length;return f?Hn(u,1):[]}function f3(u){var f=u==null?0:u.length;return f?Hn(u,Re):[]}function h3(u,f){var m=u==null?0:u.length;return m?(f=f===t?1:tr(f),Hn(u,f)):[]}function p3(u){for(var f=-1,m=u==null?0:u.length,C={};++f<m;){var O=u[f];C[O[0]]=O[1]}return C}function fC(u){return u&&u.length?u[0]:t}function v3(u,f,m){var C=u==null?0:u.length;if(!C)return-1;var O=m==null?0:tr(m);return O<0&&(O=Pn(C+O,0)),an(u,f,O)}function g3(u){var f=u==null?0:u.length;return f?us(u,0,-1):[]}var m3=ar(function(u){var f=J(u,Ym);return f.length&&f[0]===u[0]?jm(f):[]}),y3=ar(function(u){var f=cs(u),m=J(u,Ym);return f===cs(m)?f=t:m.pop(),m.length&&m[0]===u[0]?jm(m,Mt(f,2)):[]}),_3=ar(function(u){var f=cs(u),m=J(u,Ym);return f=typeof f=="function"?f:t,f&&m.pop(),m.length&&m[0]===u[0]?jm(m,t,f):[]});function b3(u,f){return u==null?"":gU.call(u,f)}function cs(u){var f=u==null?0:u.length;return f?u[f-1]:t}function S3(u,f,m){var C=u==null?0:u.length;if(!C)return-1;var O=C;return m!==t&&(O=tr(m),O=O<0?Pn(C+O,0):Yn(O,C-1)),f===f?eU(u,f,O):Zr(u,di,O,!0)}function w3(u,f){return u&&u.length?TE(u,tr(f)):t}var T3=ar(hC);function hC(u,f){return u&&u.length&&f&&f.length?Hm(u,f):u}function E3(u,f,m){return u&&u.length&&f&&f.length?Hm(u,f,Mt(m,2)):u}function C3(u,f,m){return u&&u.length&&f&&f.length?Hm(u,f,t,m):u}var k3=La(function(u,f){var m=u==null?0:u.length,C=Nm(u,f);return kE(u,J(f,function(O){return Fa(O,m)?+O:O}).sort(NE)),C});function R3(u,f){var m=[];if(!(u&&u.length))return m;var C=-1,O=[],W=u.length;for(f=Mt(f,3);++C<W;){var ee=u[C];f(ee,C,u)&&(m.push(ee),O.push(C))}return kE(u,O),m}function ly(u){return u==null?u:bU.call(u)}function I3(u,f,m){var C=u==null?0:u.length;return C?(m&&typeof m!="number"&&hi(u,f,m)?(f=0,m=C):(f=f==null?0:tr(f),m=m===t?C:tr(m)),us(u,f,m)):[]}function P3(u,f){return gh(u,f)}function A3(u,f,m){return zm(u,f,Mt(m,2))}function O3(u,f){var m=u==null?0:u.length;if(m){var C=gh(u,f);if(C<m&&Ms(u[C],f))return C}return-1}function $3(u,f){return gh(u,f,!0)}function x3(u,f,m){return zm(u,f,Mt(m,2),!0)}function M3(u,f){var m=u==null?0:u.length;if(m){var C=gh(u,f,!0)-1;if(Ms(u[C],f))return C}return-1}function D3(u){return u&&u.length?IE(u):[]}function N3(u,f){return u&&u.length?IE(u,Mt(f,2)):[]}function L3(u){var f=u==null?0:u.length;return f?us(u,1,f):[]}function F3(u,f,m){return u&&u.length?(f=m||f===t?1:tr(f),us(u,0,f<0?0:f)):[]}function U3(u,f,m){var C=u==null?0:u.length;return C?(f=m||f===t?1:tr(f),f=C-f,us(u,f<0?0:f,C)):[]}function j3(u,f){return u&&u.length?mh(u,Mt(f,3),!1,!0):[]}function B3(u,f){return u&&u.length?mh(u,Mt(f,3)):[]}var q3=ar(function(u){return Ro(Hn(u,1,vn,!0))}),W3=ar(function(u){var f=cs(u);return vn(f)&&(f=t),Ro(Hn(u,1,vn,!0),Mt(f,2))}),H3=ar(function(u){var f=cs(u);return f=typeof f=="function"?f:t,Ro(Hn(u,1,vn,!0),t,f)});function V3(u){return u&&u.length?Ro(u):[]}function G3(u,f){return u&&u.length?Ro(u,Mt(f,2)):[]}function z3(u,f){return f=typeof f=="function"?f:t,u&&u.length?Ro(u,t,f):[]}function dy(u){if(!(u&&u.length))return[];var f=0;return u=I(u,function(m){if(vn(m))return f=Pn(m.length,f),!0}),Im(f,function(m){return J(u,Cm(m))})}function pC(u,f){if(!(u&&u.length))return[];var m=dy(u);return f==null?m:J(m,function(C){return b(f,t,C)})}var K3=ar(function(u,f){return vn(u)?Yl(u,f):[]}),J3=ar(function(u){return Jm(I(u,vn))}),Y3=ar(function(u){var f=cs(u);return vn(f)&&(f=t),Jm(I(u,vn),Mt(f,2))}),X3=ar(function(u){var f=cs(u);return f=typeof f=="function"?f:t,Jm(I(u,vn),t,f)}),Q3=ar(dy);function Z3(u,f){return $E(u||[],f||[],Jl)}function eB(u,f){return $E(u||[],f||[],Zl)}var tB=ar(function(u){var f=u.length,m=f>1?u[f-1]:t;return m=typeof m=="function"?(u.pop(),m):t,pC(u,m)});function vC(u){var f=U(u);return f.__chain__=!0,f}function rB(u,f){return f(u),u}function kh(u,f){return f(u)}var nB=La(function(u){var f=u.length,m=f?u[0]:0,C=this.__wrapped__,O=function(ee){return Nm(ee,u)};return f>1||this.__actions__.length||!(C instanceof cr)||!Fa(m)?this.thru(O):(C=C.slice(m,+m+(f?1:0)),C.__actions__.push({func:kh,args:[O],thisArg:t}),new as(C,this.__chain__).thru(function(W){return f&&!W.length&&W.push(t),W}))});function iB(){return vC(this)}function sB(){return new as(this.value(),this.__chain__)}function aB(){this.__values__===t&&(this.__values__=PC(this.value()));var u=this.__index__>=this.__values__.length,f=u?t:this.__values__[this.__index__++];return{done:u,value:f}}function oB(){return this}function uB(u){for(var f,m=this;m instanceof dh;){var C=uC(m);C.__index__=0,C.__values__=t,f?O.__wrapped__=C:f=C;var O=C;m=m.__wrapped__}return O.__wrapped__=u,f}function cB(){var u=this.__wrapped__;if(u instanceof cr){var f=u;return this.__actions__.length&&(f=new cr(this)),f=f.reverse(),f.__actions__.push({func:kh,args:[ly],thisArg:t}),new as(f,this.__chain__)}return this.thru(ly)}function lB(){return OE(this.__wrapped__,this.__actions__)}var dB=yh(function(u,f,m){$r.call(u,m)?++u[m]:Da(u,m,1)});function fB(u,f,m){var C=Yt(u)?E:rj;return m&&hi(u,f,m)&&(f=t),C(u,Mt(f,3))}function hB(u,f){var m=Yt(u)?I:pE;return m(u,Mt(f,3))}var pB=qE(cC),vB=qE(lC);function gB(u,f){return Hn(Rh(u,f),1)}function mB(u,f){return Hn(Rh(u,f),Re)}function yB(u,f,m){return m=m===t?1:tr(m),Hn(Rh(u,f),m)}function gC(u,f){var m=Yt(u)?S:ko;return m(u,Mt(f,3))}function mC(u,f){var m=Yt(u)?T:hE;return m(u,Mt(f,3))}var _B=yh(function(u,f,m){$r.call(u,m)?u[m].push(f):Da(u,m,[f])});function bB(u,f,m,C){u=$i(u)?u:Rc(u),m=m&&!C?tr(m):0;var O=u.length;return m<0&&(m=Pn(O+m,0)),$h(u)?m<=O&&u.indexOf(f,m)>-1:!!O&&an(u,f,m)>-1}var SB=ar(function(u,f,m){var C=-1,O=typeof f=="function",W=$i(u)?Ce(u.length):[];return ko(u,function(ee){W[++C]=O?b(f,ee,m):Xl(ee,f,m)}),W}),wB=yh(function(u,f,m){Da(u,m,f)});function Rh(u,f){var m=Yt(u)?J:bE;return m(u,Mt(f,3))}function TB(u,f,m,C){return u==null?[]:(Yt(f)||(f=f==null?[]:[f]),m=C?t:m,Yt(m)||(m=m==null?[]:[m]),EE(u,f,m))}var EB=yh(function(u,f,m){u[m?0:1].push(f)},function(){return[[],[]]});function CB(u,f,m){var C=Yt(u)?Se:KT,O=arguments.length<3;return C(u,Mt(f,4),m,O,ko)}function kB(u,f,m){var C=Yt(u)?Ge:KT,O=arguments.length<3;return C(u,Mt(f,4),m,O,hE)}function RB(u,f){var m=Yt(u)?I:pE;return m(u,Ah(Mt(f,3)))}function IB(u){var f=Yt(u)?cE:bj;return f(u)}function PB(u,f,m){(m?hi(u,f,m):f===t)?f=1:f=tr(f);var C=Yt(u)?XU:Sj;return C(u,f)}function AB(u){var f=Yt(u)?QU:Tj;return f(u)}function OB(u){if(u==null)return 0;if($i(u))return $h(u)?mc(u):u.length;var f=Xn(u);return f==$e||f==dr?u.size:qm(u).length}function $B(u,f,m){var C=Yt(u)?gt:Ej;return m&&hi(u,f,m)&&(f=t),C(u,Mt(f,3))}var xB=ar(function(u,f){if(u==null)return[];var m=f.length;return m>1&&hi(u,f[0],f[1])?f=[]:m>2&&hi(f[0],f[1],f[2])&&(f=[f[0]]),EE(u,Hn(f,1),[])}),Ih=hU||function(){return $t.Date.now()};function MB(u,f){if(typeof f!="function")throw new ss(a);return u=tr(u),function(){if(--u<1)return f.apply(this,arguments)}}function yC(u,f,m){return f=m?t:f,f=u&&f==null?u.length:f,Na(u,K,t,t,t,t,f)}function _C(u,f){var m;if(typeof f!="function")throw new ss(a);return u=tr(u),function(){return--u>0&&(m=f.apply(this,arguments)),u<=1&&(f=t),m}}var fy=ar(function(u,f,m){var C=P;if(m.length){var O=Eo(m,Cc(fy));C|=F}return Na(u,C,f,m,O)}),bC=ar(function(u,f,m){var C=P|A;if(m.length){var O=Eo(m,Cc(bC));C|=F}return Na(f,C,u,m,O)});function SC(u,f,m){f=m?t:f;var C=Na(u,L,t,t,t,t,t,f);return C.placeholder=SC.placeholder,C}function wC(u,f,m){f=m?t:f;var C=Na(u,$,t,t,t,t,t,f);return C.placeholder=wC.placeholder,C}function TC(u,f,m){var C,O,W,ee,le,ye,De=0,Ne=!1,qe=!1,nt=!0;if(typeof u!="function")throw new ss(a);f=ls(f)||0,on(m)&&(Ne=!!m.leading,qe="maxWait"in m,W=qe?Pn(ls(m.maxWait)||0,f):W,nt="trailing"in m?!!m.trailing:nt);function Tt(gn){var Ds=C,Ba=O;return C=O=t,De=gn,ee=u.apply(Ba,Ds),ee}function Lt(gn){return De=gn,le=rd(lr,f),Ne?Tt(gn):ee}function nr(gn){var Ds=gn-ye,Ba=gn-De,qC=f-Ds;return qe?Yn(qC,W-Ba):qC}function Ft(gn){var Ds=gn-ye,Ba=gn-De;return ye===t||Ds>=f||Ds<0||qe&&Ba>=W}function lr(){var gn=Ih();if(Ft(gn))return gr(gn);le=rd(lr,nr(gn))}function gr(gn){return le=t,nt&&C?Tt(gn):(C=O=t,ee)}function Qn(){le!==t&&xE(le),De=0,C=ye=O=le=t}function pi(){return le===t?ee:gr(Ih())}function Ji(){var gn=Ih(),Ds=Ft(gn);if(C=arguments,O=this,ye=gn,Ds){if(le===t)return Lt(ye);if(qe)return xE(le),le=rd(lr,f),Tt(ye)}return le===t&&(le=rd(lr,f)),ee}return Ji.cancel=Qn,Ji.flush=pi,Ji}var DB=ar(function(u,f){return fE(u,1,f)}),NB=ar(function(u,f,m){return fE(u,ls(f)||0,m)});function LB(u){return Na(u,he)}function Ph(u,f){if(typeof u!="function"||f!=null&&typeof f!="function")throw new ss(a);var m=function C(){var O=arguments,W=f?f.apply(this,O):O[0],ee=C.cache;if(ee.has(W))return ee.get(W);var le=u.apply(this,O);return C.cache=ee.set(W,le)||ee,le};return m.cache=new(Ph.Cache||Ma),m}Ph.Cache=Ma;function Ah(u){if(typeof u!="function")throw new ss(a);return function(){var f=arguments;switch(f.length){case 0:return!u.call(this);case 1:return!u.call(this,f[0]);case 2:return!u.call(this,f[0],f[1]);case 3:return!u.call(this,f[0],f[1],f[2])}return!u.apply(this,f)}}function FB(u){return _C(2,u)}var UB=Cj(function(u,f){f=f.length==1&&Yt(f[0])?J(f[0],Gi(Mt())):J(Hn(f,1),Gi(Mt()));var m=f.length;return ar(function(C){for(var O=-1,W=Yn(C.length,m);++O<W;)C[O]=f[O].call(this,C[O]);return b(u,this,C)})}),hy=ar(function(u,f){var m=Eo(f,Cc(hy));return Na(u,F,t,f,m)}),EC=ar(function(u,f){var m=Eo(f,Cc(EC));return Na(u,G,t,f,m)}),jB=La(function(u,f){return Na(u,D,t,t,t,f)});function BB(u,f){if(typeof u!="function")throw new ss(a);return f=f===t?f:tr(f),ar(u,f)}function qB(u,f){if(typeof u!="function")throw new ss(a);return f=f==null?0:Pn(tr(f),0),ar(function(m){var C=m[f],O=Po(m,0,f);return C&&ae(O,C),b(u,this,O)})}function WB(u,f,m){var C=!0,O=!0;if(typeof u!="function")throw new ss(a);return on(m)&&(C="leading"in m?!!m.leading:C,O="trailing"in m?!!m.trailing:O),TC(u,f,{leading:C,maxWait:f,trailing:O})}function HB(u){return yC(u,1)}function VB(u,f){return hy(Xm(f),u)}function GB(){if(!arguments.length)return[];var u=arguments[0];return Yt(u)?u:[u]}function zB(u){return os(u,y)}function KB(u,f){return f=typeof f=="function"?f:t,os(u,y,f)}function JB(u){return os(u,h|y)}function YB(u,f){return f=typeof f=="function"?f:t,os(u,h|y,f)}function XB(u,f){return f==null||dE(u,f,Fn(f))}function Ms(u,f){return u===f||u!==u&&f!==f}var QB=wh(Um),ZB=wh(function(u,f){return u>=f}),Su=mE(function(){return arguments}())?mE:function(u){return dn(u)&&$r.call(u,"callee")&&!nE.call(u,"callee")},Yt=Ce.isArray,e4=vc?Gi(vc):uj;function $i(u){return u!=null&&Oh(u.length)&&!Ua(u)}function vn(u){return dn(u)&&$i(u)}function t4(u){return u===!0||u===!1||dn(u)&&fi(u)==ut}var Ao=vU||Ey,r4=x?Gi(x):cj;function n4(u){return dn(u)&&u.nodeType===1&&!nd(u)}function i4(u){if(u==null)return!0;if($i(u)&&(Yt(u)||typeof u=="string"||typeof u.splice=="function"||Ao(u)||kc(u)||Su(u)))return!u.length;var f=Xn(u);if(f==$e||f==dr)return!u.size;if(td(u))return!qm(u).length;for(var m in u)if($r.call(u,m))return!1;return!0}function s4(u,f){return Ql(u,f)}function a4(u,f,m){m=typeof m=="function"?m:t;var C=m?m(u,f):t;return C===t?Ql(u,f,t,m):!!C}function py(u){if(!dn(u))return!1;var f=fi(u);return f==rt||f==Zt||typeof u.message=="string"&&typeof u.name=="string"&&!nd(u)}function o4(u){return typeof u=="number"&&sE(u)}function Ua(u){if(!on(u))return!1;var f=fi(u);return f==cn||f==Ot||f==ne||f==er}function CC(u){return typeof u=="number"&&u==tr(u)}function Oh(u){return typeof u=="number"&&u>-1&&u%1==0&&u<=Je}function on(u){var f=ps.default(u);return u!=null&&(f=="object"||f=="function")}function dn(u){return u!=null&&ps.default(u)=="object"}var kC=M?Gi(M):dj;function u4(u,f){return u===f||Bm(u,f,iy(f))}function c4(u,f,m){return m=typeof m=="function"?m:t,Bm(u,f,iy(f),m)}function l4(u){return RC(u)&&u!=+u}function d4(u){if(Kj(u))throw new Vt(s);return yE(u)}function f4(u){return u===null}function h4(u){return u==null}function RC(u){return typeof u=="number"||dn(u)&&fi(u)==_t}function nd(u){if(!dn(u)||fi(u)!=Ue)return!1;var f=ih(u);if(f===null)return!0;var m=$r.call(f,"constructor")&&f.constructor;return typeof m=="function"&&m instanceof m&&eh.call(m)==cU}var vy=R?Gi(R):fj;function p4(u){return CC(u)&&u>=-Je&&u<=Je}var IC=v?Gi(v):hj;function $h(u){return typeof u=="string"||!Yt(u)&&dn(u)&&fi(u)==tn}function Ki(u){return ps.default(u)=="symbol"||dn(u)&&fi(u)==yn}var kc=g?Gi(g):pj;function v4(u){return u===t}function g4(u){return dn(u)&&Xn(u)==Kt}function m4(u){return dn(u)&&fi(u)==Ht}var y4=wh(Wm),_4=wh(function(u,f){return u<=f});function PC(u){if(!u)return[];if($i(u))return $h(u)?$s(u):Oi(u);if(Hl&&u[Hl])return XF(u[Hl]());var f=Xn(u),m=f==$e?Am:f==dr?Xf:Rc;return m(u)}function ja(u){if(!u)return u===0?u:0;if(u=ls(u),u===Re||u===-Re){var f=u<0?-1:1;return f*Ke}return u===u?u:0}function tr(u){var f=ja(u),m=f%1;return f===f?m?f-m:f:0}function AC(u){return u?mu(tr(u),0,Ee):0}function ls(u){if(typeof u=="number")return u;if(Ki(u))return Y;if(on(u)){var f=typeof u.valueOf=="function"?u.valueOf():u;u=on(f)?f+"":f}if(typeof u!="string")return u===0?u:+u;u=JT(u);var m=Ri.test(u);return m||vt.test(u)?hc(u.slice(2),m?2:8):Dn.test(u)?Y:+u}function OC(u){return sa(u,xi(u))}function b4(u){return u?mu(tr(u),-Je,Je):u===0?u:0}function kr(u){return u==null?"":zi(u)}var S4=Tc(function(u,f){if(td(f)||$i(f)){sa(f,Fn(f),u);return}for(var m in f)$r.call(f,m)&&Jl(u,m,f[m])}),$C=Tc(function(u,f){sa(f,xi(f),u)}),xh=Tc(function(u,f,m,C){sa(f,xi(f),u,C)}),w4=Tc(function(u,f,m,C){sa(f,Fn(f),u,C)}),T4=La(Nm);function E4(u,f){var m=wc(u);return f==null?m:lE(m,f)}var C4=ar(function(u,f){u=zr(u);var m=-1,C=f.length,O=C>2?f[2]:t;for(O&&hi(f[0],f[1],O)&&(C=1);++m<C;)for(var W=f[m],ee=xi(W),le=-1,ye=ee.length;++le<ye;){var De=ee[le],Ne=u[De];(Ne===t||Ms(Ne,_c[De])&&!$r.call(u,De))&&(u[De]=W[De])}return u}),k4=ar(function(u){return u.push(t,JE),b(xC,t,u)});function R4(u,f){return lt(u,Mt(f,3),ia)}function I4(u,f){return lt(u,Mt(f,3),Fm)}function P4(u,f){return u==null?u:Lm(u,Mt(f,3),xi)}function A4(u,f){return u==null?u:vE(u,Mt(f,3),xi)}function O4(u,f){return u&&ia(u,Mt(f,3))}function $4(u,f){return u&&Fm(u,Mt(f,3))}function x4(u){return u==null?[]:ph(u,Fn(u))}function M4(u){return u==null?[]:ph(u,xi(u))}function gy(u,f,m){var C=u==null?t:yu(u,f);return C===t?m:C}function D4(u,f){return u!=null&&QE(u,f,ij)}function my(u,f){return u!=null&&QE(u,f,sj)}var N4=HE(function(u,f,m){f!=null&&typeof f.toString!="function"&&(f=th.call(f)),u[f]=m},_y(Mi)),L4=HE(function(u,f,m){f!=null&&typeof f.toString!="function"&&(f=th.call(f)),$r.call(u,f)?u[f].push(m):u[f]=[m]},Mt),F4=ar(Xl);function Fn(u){return $i(u)?uE(u):qm(u)}function xi(u){return $i(u)?uE(u,!0):vj(u)}function U4(u,f){var m={};return f=Mt(f,3),ia(u,function(C,O,W){Da(m,f(C,O,W),C)}),m}function j4(u,f){var m={};return f=Mt(f,3),ia(u,function(C,O,W){Da(m,O,f(C,O,W))}),m}var B4=Tc(function(u,f,m){vh(u,f,m)}),xC=Tc(function(u,f,m,C){vh(u,f,m,C)}),q4=La(function(u,f){var m={};if(u==null)return m;var C=!1;f=J(f,function(W){return W=Io(W,u),C||(C=W.length>1),W}),sa(u,ry(u),m),C&&(m=os(m,h|p|y,Nj));for(var O=f.length;O--;)Km(m,f[O]);return m});function W4(u,f){return MC(u,Ah(Mt(f)))}var H4=La(function(u,f){return u==null?{}:mj(u,f)});function MC(u,f){if(u==null)return{};var m=J(ry(u),function(C){return[C]});return f=Mt(f),CE(u,m,function(C,O){return f(C,O[0])})}function V4(u,f,m){f=Io(f,u);var C=-1,O=f.length;for(O||(O=1,u=t);++C<O;){var W=u==null?t:u[aa(f[C])];W===t&&(C=O,W=m),u=Ua(W)?W.call(u):W}return u}function G4(u,f,m){return u==null?u:Zl(u,f,m)}function z4(u,f,m,C){return C=typeof C=="function"?C:t,u==null?u:Zl(u,f,m,C)}var DC=zE(Fn),NC=zE(xi);function K4(u,f,m){var C=Yt(u),O=C||Ao(u)||kc(u);if(f=Mt(f,4),m==null){var W=u&&u.constructor;O?m=C?new W:[]:on(u)?m=Ua(W)?wc(ih(u)):{}:m={}}return(O?S:ia)(u,function(ee,le,ye){return f(m,ee,le,ye)}),m}function J4(u,f){return u==null?!0:Km(u,f)}function Y4(u,f,m){return u==null?u:AE(u,f,Xm(m))}function X4(u,f,m,C){return C=typeof C=="function"?C:t,u==null?u:AE(u,f,Xm(m),C)}function Rc(u){return u==null?[]:Pm(u,Fn(u))}function Q4(u){return u==null?[]:Pm(u,xi(u))}function Z4(u,f,m){return m===t&&(m=f,f=t),m!==t&&(m=ls(m),m=m===m?m:0),f!==t&&(f=ls(f),f=f===f?f:0),mu(ls(u),f,m)}function eq(u,f,m){return f=ja(f),m===t?(m=f,f=0):m=ja(m),u=ls(u),aj(u,f,m)}function tq(u,f,m){if(m&&typeof m!="boolean"&&hi(u,f,m)&&(f=m=t),m===t&&(typeof f=="boolean"?(m=f,f=t):typeof u=="boolean"&&(m=u,u=t)),u===t&&f===t?(u=0,f=1):(u=ja(u),f===t?(f=u,u=0):f=ja(f)),u>f){var C=u;u=f,f=C}if(m||u%1||f%1){var O=aE();return Yn(u+O*(f-u+fc("1e-"+((O+"").length-1))),f)}return Vm(u,f)}var rq=Ec(function(u,f,m){return f=f.toLowerCase(),u+(m?LC(f):f)});function LC(u){return yy(kr(u).toLowerCase())}function FC(u){return u=kr(u),u&&u.replace(je,GF).replace(lu,"")}function nq(u,f,m){u=kr(u),f=zi(f);var C=u.length;m=m===t?C:mu(tr(m),0,C);var O=m;return m-=f.length,m>=0&&u.slice(m,O)==f}function iq(u){return u=kr(u),u&&pe.test(u)?u.replace(xe,zF):u}function sq(u){return u=kr(u),u&&tt.test(u)?u.replace(ot,"\\$&"):u}var aq=Ec(function(u,f,m){return u+(m?"-":"")+f.toLowerCase()}),oq=Ec(function(u,f,m){return u+(m?" ":"")+f.toLowerCase()}),uq=BE("toLowerCase");function cq(u,f,m){u=kr(u),f=tr(f);var C=f?mc(u):0;if(!f||C>=f)return u;var O=(f-C)/2;return Sh(uh(O),m)+u+Sh(oh(O),m)}function lq(u,f,m){u=kr(u),f=tr(f);var C=f?mc(u):0;return f&&C<f?u+Sh(f-C,m):u}function dq(u,f,m){u=kr(u),f=tr(f);var C=f?mc(u):0;return f&&C<f?Sh(f-C,m)+u:u}function fq(u,f,m){return m||f==null?f=0:f&&(f=+f),_U(kr(u).replace(it,""),f||0)}function hq(u,f,m){return(m?hi(u,f,m):f===t)?f=1:f=tr(f),Gm(kr(u),f)}function pq(){var u=arguments,f=kr(u[0]);return u.length<3?f:f.replace(u[1],u[2])}var vq=Ec(function(u,f,m){return u+(m?"_":"")+f.toLowerCase()});function gq(u,f,m){return m&&typeof m!="number"&&hi(u,f,m)&&(f=m=t),m=m===t?Ee:m>>>0,m?(u=kr(u),u&&(typeof f=="string"||f!=null&&!vy(f))&&(f=zi(f),!f&&gc(u))?Po($s(u),0,m):u.split(f,m)):[]}var mq=Ec(function(u,f,m){return u+(m?" ":"")+yy(f)});function yq(u,f,m){return u=kr(u),m=m==null?0:mu(tr(m),0,u.length),f=zi(f),u.slice(m,m+f.length)==f}function _q(u,f,m){var C=U.templateSettings;m&&hi(u,f,m)&&(f=t),u=kr(u),f=xh({},f,C,KE);var O=xh({},f.imports,C.imports,KE),W=Fn(O),ee=Pm(O,W),le,ye,De=0,Ne=f.interpolate||st,qe="__p += '",nt=Om((f.escape||st).source+"|"+Ne.source+"|"+(Ne===ge?ln:st).source+"|"+(f.evaluate||st).source+"|$","g"),Tt="//# sourceURL="+($r.call(f,"sourceURL")?(f.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++lc+"]")+`
367
+ `)}function Vj(u){return Yt(u)||Su(u)||!!(iE&&u&&u[iE])}function Fa(u,f){var m=ps.default(u);return f=f??Je,!!f&&(m=="number"||m!="symbol"&&ce.test(u))&&u>-1&&u%1==0&&u<f}function hi(u,f,m){if(!on(m))return!1;var C=ps.default(f);return(C=="number"?$i(m)&&Fa(f,m.length):C=="string"&&f in m)?Ms(m[f],u):!1}function ay(u,f){if(Yt(u))return!1;var m=ps.default(u);return m=="number"||m=="symbol"||m=="boolean"||u==null||Ki(u)?!0:Qe.test(u)||!ue.test(u)||f!=null&&u in zr(f)}function Gj(u){var f=ps.default(u);return f=="string"||f=="number"||f=="symbol"||f=="boolean"?u!=="__proto__":u===null}function oy(u){var f=Th(u),m=U[f];if(typeof m!="function"||!(f in cr.prototype))return!1;if(u===m)return!0;var C=ny(m);return!!C&&u===C[0]}function zj(u){return!!eE&&eE in u}var Kj=Zf?Ua:Ey;function td(u){var f=u&&u.constructor,m=typeof f=="function"&&f.prototype||_c;return u===m}function eC(u){return u===u&&!on(u)}function tC(u,f){return function(m){return m==null?!1:m[u]===f&&(f!==t||u in zr(m))}}function Jj(u){var f=Ph(u,function(C){return m.size===l&&m.clear(),C}),m=f.cache;return f}function Yj(u,f){var m=u[1],C=f[1],O=m|C,W=O<(P|A|K),ee=C==K&&m==L||C==K&&m==D&&u[7].length<=f[8]||C==(K|D)&&f[7].length<=f[8]&&m==L;if(!(W||ee))return u;C&P&&(u[2]=f[2],O|=m&P?0:B);var le=f[3];if(le){var ye=u[3];u[3]=ye?LE(ye,le,f[4]):le,u[4]=ye?Eo(u[3],d):f[4]}return le=f[5],le&&(ye=u[5],u[5]=ye?FE(ye,le,f[6]):le,u[6]=ye?Eo(u[5],d):f[6]),le=f[7],le&&(u[7]=le),C&K&&(u[8]=u[8]==null?f[8]:Yn(u[8],f[8])),u[9]==null&&(u[9]=f[9]),u[0]=f[0],u[1]=O,u}function Xj(u){var f=[];if(u!=null)for(var m in zr(u))f.push(m);return f}function Qj(u){return th.call(u)}function rC(u,f,m){return f=Pn(f===t?u.length-1:f,0),function(){for(var C=arguments,O=-1,W=Pn(C.length-f,0),ee=Ce(W);++O<W;)ee[O]=C[f+O];O=-1;for(var le=Ce(f+1);++O<f;)le[O]=C[O];return le[f]=m(ee),b(u,this,le)}}function nC(u,f){return f.length<2?u:yu(u,us(f,0,-1))}function Zj(u,f){for(var m=u.length,C=Yn(f.length,m),O=Oi(u);C--;){var W=f[C];u[C]=Fa(W,m)?O[W]:t}return u}function uy(u,f){if(!(f==="constructor"&&typeof u[f]=="function")&&f!="__proto__")return u[f]}var iC=aC(RE),rd=pU||function(u,f){return $t.setTimeout(u,f)},cy=aC(wj);function sC(u,f,m){var C=f+"";return cy(u,Hj(C,eB(Bj(C),m)))}function aC(u){var f=0,m=0;return function(){var C=yU(),O=Oe-(C-m);if(m=C,O>0){if(++f>=Q)return arguments[0]}else f=0;return u.apply(t,arguments)}}function Ch(u,f){var m=-1,C=u.length,O=C-1;for(f=f===t?C:f;++m<f;){var W=Vm(m,O),ee=u[W];u[W]=u[m],u[m]=ee}return u.length=f,u}var oC=Jj(function(u){var f=[];return u.charCodeAt(0)===46&&f.push(""),u.replace(Me,function(m,C,O,W){f.push(O?W.replace(Ur,"$1"):C||m)}),f});function aa(u){if(typeof u=="string"||Ki(u))return u;var f=u+"";return f=="0"&&1/u==-Re?"-0":f}function bu(u){if(u!=null){try{return eh.call(u)}catch{}try{return u+""}catch{}}return""}function eB(u,f){return S(Et,function(m){var C="_."+m[0];f&m[1]&&!q(u,C)&&u.push(C)}),u.sort()}function uC(u){if(u instanceof cr)return u.clone();var f=new as(u.__wrapped__,u.__chain__);return f.__actions__=Oi(u.__actions__),f.__index__=u.__index__,f.__values__=u.__values__,f}function tB(u,f,m){(m?hi(u,f,m):f===t)?f=1:f=Pn(tr(f),0);var C=u==null?0:u.length;if(!C||f<1)return[];for(var O=0,W=0,ee=Ce(oh(C/f));O<C;)ee[W++]=us(u,O,O+=f);return ee}function rB(u){for(var f=-1,m=u==null?0:u.length,C=0,O=[];++f<m;){var W=u[f];W&&(O[C++]=W)}return O}function nB(){var u=arguments.length;if(!u)return[];for(var f=Ce(u-1),m=arguments[0],C=u;C--;)f[C-1]=arguments[C];return ae(Yt(m)?Oi(m):[m],Hn(f,1))}var iB=ar(function(u,f){return vn(u)?Yl(u,Hn(f,1,vn,!0)):[]}),sB=ar(function(u,f){var m=cs(f);return vn(m)&&(m=t),vn(u)?Yl(u,Hn(f,1,vn,!0),Mt(m,2)):[]}),aB=ar(function(u,f){var m=cs(f);return vn(m)&&(m=t),vn(u)?Yl(u,Hn(f,1,vn,!0),t,m):[]});function oB(u,f,m){var C=u==null?0:u.length;return C?(f=m||f===t?1:tr(f),us(u,f<0?0:f,C)):[]}function uB(u,f,m){var C=u==null?0:u.length;return C?(f=m||f===t?1:tr(f),f=C-f,us(u,0,f<0?0:f)):[]}function cB(u,f){return u&&u.length?mh(u,Mt(f,3),!0,!0):[]}function lB(u,f){return u&&u.length?mh(u,Mt(f,3),!0):[]}function dB(u,f,m,C){var O=u==null?0:u.length;return O?(m&&typeof m!="number"&&hi(u,f,m)&&(m=0,C=O),nj(u,f,m,C)):[]}function cC(u,f,m){var C=u==null?0:u.length;if(!C)return-1;var O=m==null?0:tr(m);return O<0&&(O=Pn(C+O,0)),Zr(u,Mt(f,3),O)}function lC(u,f,m){var C=u==null?0:u.length;if(!C)return-1;var O=C-1;return m!==t&&(O=tr(m),O=m<0?Pn(C+O,0):Yn(O,C-1)),Zr(u,Mt(f,3),O,!0)}function dC(u){var f=u==null?0:u.length;return f?Hn(u,1):[]}function fB(u){var f=u==null?0:u.length;return f?Hn(u,Re):[]}function hB(u,f){var m=u==null?0:u.length;return m?(f=f===t?1:tr(f),Hn(u,f)):[]}function pB(u){for(var f=-1,m=u==null?0:u.length,C={};++f<m;){var O=u[f];C[O[0]]=O[1]}return C}function fC(u){return u&&u.length?u[0]:t}function vB(u,f,m){var C=u==null?0:u.length;if(!C)return-1;var O=m==null?0:tr(m);return O<0&&(O=Pn(C+O,0)),an(u,f,O)}function gB(u){var f=u==null?0:u.length;return f?us(u,0,-1):[]}var mB=ar(function(u){var f=J(u,Ym);return f.length&&f[0]===u[0]?jm(f):[]}),yB=ar(function(u){var f=cs(u),m=J(u,Ym);return f===cs(m)?f=t:m.pop(),m.length&&m[0]===u[0]?jm(m,Mt(f,2)):[]}),_B=ar(function(u){var f=cs(u),m=J(u,Ym);return f=typeof f=="function"?f:t,f&&m.pop(),m.length&&m[0]===u[0]?jm(m,t,f):[]});function bB(u,f){return u==null?"":gU.call(u,f)}function cs(u){var f=u==null?0:u.length;return f?u[f-1]:t}function SB(u,f,m){var C=u==null?0:u.length;if(!C)return-1;var O=C;return m!==t&&(O=tr(m),O=O<0?Pn(C+O,0):Yn(O,C-1)),f===f?eU(u,f,O):Zr(u,di,O,!0)}function wB(u,f){return u&&u.length?TE(u,tr(f)):t}var TB=ar(hC);function hC(u,f){return u&&u.length&&f&&f.length?Hm(u,f):u}function EB(u,f,m){return u&&u.length&&f&&f.length?Hm(u,f,Mt(m,2)):u}function CB(u,f,m){return u&&u.length&&f&&f.length?Hm(u,f,t,m):u}var kB=La(function(u,f){var m=u==null?0:u.length,C=Nm(u,f);return kE(u,J(f,function(O){return Fa(O,m)?+O:O}).sort(NE)),C});function RB(u,f){var m=[];if(!(u&&u.length))return m;var C=-1,O=[],W=u.length;for(f=Mt(f,3);++C<W;){var ee=u[C];f(ee,C,u)&&(m.push(ee),O.push(C))}return kE(u,O),m}function ly(u){return u==null?u:bU.call(u)}function IB(u,f,m){var C=u==null?0:u.length;return C?(m&&typeof m!="number"&&hi(u,f,m)?(f=0,m=C):(f=f==null?0:tr(f),m=m===t?C:tr(m)),us(u,f,m)):[]}function PB(u,f){return gh(u,f)}function AB(u,f,m){return zm(u,f,Mt(m,2))}function OB(u,f){var m=u==null?0:u.length;if(m){var C=gh(u,f);if(C<m&&Ms(u[C],f))return C}return-1}function $B(u,f){return gh(u,f,!0)}function xB(u,f,m){return zm(u,f,Mt(m,2),!0)}function MB(u,f){var m=u==null?0:u.length;if(m){var C=gh(u,f,!0)-1;if(Ms(u[C],f))return C}return-1}function DB(u){return u&&u.length?IE(u):[]}function NB(u,f){return u&&u.length?IE(u,Mt(f,2)):[]}function LB(u){var f=u==null?0:u.length;return f?us(u,1,f):[]}function FB(u,f,m){return u&&u.length?(f=m||f===t?1:tr(f),us(u,0,f<0?0:f)):[]}function UB(u,f,m){var C=u==null?0:u.length;return C?(f=m||f===t?1:tr(f),f=C-f,us(u,f<0?0:f,C)):[]}function jB(u,f){return u&&u.length?mh(u,Mt(f,3),!1,!0):[]}function BB(u,f){return u&&u.length?mh(u,Mt(f,3)):[]}var qB=ar(function(u){return Ro(Hn(u,1,vn,!0))}),WB=ar(function(u){var f=cs(u);return vn(f)&&(f=t),Ro(Hn(u,1,vn,!0),Mt(f,2))}),HB=ar(function(u){var f=cs(u);return f=typeof f=="function"?f:t,Ro(Hn(u,1,vn,!0),t,f)});function VB(u){return u&&u.length?Ro(u):[]}function GB(u,f){return u&&u.length?Ro(u,Mt(f,2)):[]}function zB(u,f){return f=typeof f=="function"?f:t,u&&u.length?Ro(u,t,f):[]}function dy(u){if(!(u&&u.length))return[];var f=0;return u=I(u,function(m){if(vn(m))return f=Pn(m.length,f),!0}),Im(f,function(m){return J(u,Cm(m))})}function pC(u,f){if(!(u&&u.length))return[];var m=dy(u);return f==null?m:J(m,function(C){return b(f,t,C)})}var KB=ar(function(u,f){return vn(u)?Yl(u,f):[]}),JB=ar(function(u){return Jm(I(u,vn))}),YB=ar(function(u){var f=cs(u);return vn(f)&&(f=t),Jm(I(u,vn),Mt(f,2))}),XB=ar(function(u){var f=cs(u);return f=typeof f=="function"?f:t,Jm(I(u,vn),t,f)}),QB=ar(dy);function ZB(u,f){return $E(u||[],f||[],Jl)}function e3(u,f){return $E(u||[],f||[],Zl)}var t3=ar(function(u){var f=u.length,m=f>1?u[f-1]:t;return m=typeof m=="function"?(u.pop(),m):t,pC(u,m)});function vC(u){var f=U(u);return f.__chain__=!0,f}function r3(u,f){return f(u),u}function kh(u,f){return f(u)}var n3=La(function(u){var f=u.length,m=f?u[0]:0,C=this.__wrapped__,O=function(ee){return Nm(ee,u)};return f>1||this.__actions__.length||!(C instanceof cr)||!Fa(m)?this.thru(O):(C=C.slice(m,+m+(f?1:0)),C.__actions__.push({func:kh,args:[O],thisArg:t}),new as(C,this.__chain__).thru(function(W){return f&&!W.length&&W.push(t),W}))});function i3(){return vC(this)}function s3(){return new as(this.value(),this.__chain__)}function a3(){this.__values__===t&&(this.__values__=PC(this.value()));var u=this.__index__>=this.__values__.length,f=u?t:this.__values__[this.__index__++];return{done:u,value:f}}function o3(){return this}function u3(u){for(var f,m=this;m instanceof dh;){var C=uC(m);C.__index__=0,C.__values__=t,f?O.__wrapped__=C:f=C;var O=C;m=m.__wrapped__}return O.__wrapped__=u,f}function c3(){var u=this.__wrapped__;if(u instanceof cr){var f=u;return this.__actions__.length&&(f=new cr(this)),f=f.reverse(),f.__actions__.push({func:kh,args:[ly],thisArg:t}),new as(f,this.__chain__)}return this.thru(ly)}function l3(){return OE(this.__wrapped__,this.__actions__)}var d3=yh(function(u,f,m){$r.call(u,m)?++u[m]:Da(u,m,1)});function f3(u,f,m){var C=Yt(u)?E:rj;return m&&hi(u,f,m)&&(f=t),C(u,Mt(f,3))}function h3(u,f){var m=Yt(u)?I:pE;return m(u,Mt(f,3))}var p3=qE(cC),v3=qE(lC);function g3(u,f){return Hn(Rh(u,f),1)}function m3(u,f){return Hn(Rh(u,f),Re)}function y3(u,f,m){return m=m===t?1:tr(m),Hn(Rh(u,f),m)}function gC(u,f){var m=Yt(u)?S:ko;return m(u,Mt(f,3))}function mC(u,f){var m=Yt(u)?T:hE;return m(u,Mt(f,3))}var _3=yh(function(u,f,m){$r.call(u,m)?u[m].push(f):Da(u,m,[f])});function b3(u,f,m,C){u=$i(u)?u:Rc(u),m=m&&!C?tr(m):0;var O=u.length;return m<0&&(m=Pn(O+m,0)),$h(u)?m<=O&&u.indexOf(f,m)>-1:!!O&&an(u,f,m)>-1}var S3=ar(function(u,f,m){var C=-1,O=typeof f=="function",W=$i(u)?Ce(u.length):[];return ko(u,function(ee){W[++C]=O?b(f,ee,m):Xl(ee,f,m)}),W}),w3=yh(function(u,f,m){Da(u,m,f)});function Rh(u,f){var m=Yt(u)?J:bE;return m(u,Mt(f,3))}function T3(u,f,m,C){return u==null?[]:(Yt(f)||(f=f==null?[]:[f]),m=C?t:m,Yt(m)||(m=m==null?[]:[m]),EE(u,f,m))}var E3=yh(function(u,f,m){u[m?0:1].push(f)},function(){return[[],[]]});function C3(u,f,m){var C=Yt(u)?Se:KT,O=arguments.length<3;return C(u,Mt(f,4),m,O,ko)}function k3(u,f,m){var C=Yt(u)?Ge:KT,O=arguments.length<3;return C(u,Mt(f,4),m,O,hE)}function R3(u,f){var m=Yt(u)?I:pE;return m(u,Ah(Mt(f,3)))}function I3(u){var f=Yt(u)?cE:bj;return f(u)}function P3(u,f,m){(m?hi(u,f,m):f===t)?f=1:f=tr(f);var C=Yt(u)?XU:Sj;return C(u,f)}function A3(u){var f=Yt(u)?QU:Tj;return f(u)}function O3(u){if(u==null)return 0;if($i(u))return $h(u)?mc(u):u.length;var f=Xn(u);return f==$e||f==dr?u.size:qm(u).length}function $3(u,f,m){var C=Yt(u)?gt:Ej;return m&&hi(u,f,m)&&(f=t),C(u,Mt(f,3))}var x3=ar(function(u,f){if(u==null)return[];var m=f.length;return m>1&&hi(u,f[0],f[1])?f=[]:m>2&&hi(f[0],f[1],f[2])&&(f=[f[0]]),EE(u,Hn(f,1),[])}),Ih=hU||function(){return $t.Date.now()};function M3(u,f){if(typeof f!="function")throw new ss(a);return u=tr(u),function(){if(--u<1)return f.apply(this,arguments)}}function yC(u,f,m){return f=m?t:f,f=u&&f==null?u.length:f,Na(u,K,t,t,t,t,f)}function _C(u,f){var m;if(typeof f!="function")throw new ss(a);return u=tr(u),function(){return--u>0&&(m=f.apply(this,arguments)),u<=1&&(f=t),m}}var fy=ar(function(u,f,m){var C=P;if(m.length){var O=Eo(m,Cc(fy));C|=F}return Na(u,C,f,m,O)}),bC=ar(function(u,f,m){var C=P|A;if(m.length){var O=Eo(m,Cc(bC));C|=F}return Na(f,C,u,m,O)});function SC(u,f,m){f=m?t:f;var C=Na(u,L,t,t,t,t,t,f);return C.placeholder=SC.placeholder,C}function wC(u,f,m){f=m?t:f;var C=Na(u,$,t,t,t,t,t,f);return C.placeholder=wC.placeholder,C}function TC(u,f,m){var C,O,W,ee,le,ye,De=0,Ne=!1,qe=!1,nt=!0;if(typeof u!="function")throw new ss(a);f=ls(f)||0,on(m)&&(Ne=!!m.leading,qe="maxWait"in m,W=qe?Pn(ls(m.maxWait)||0,f):W,nt="trailing"in m?!!m.trailing:nt);function Tt(gn){var Ds=C,Ba=O;return C=O=t,De=gn,ee=u.apply(Ba,Ds),ee}function Lt(gn){return De=gn,le=rd(lr,f),Ne?Tt(gn):ee}function nr(gn){var Ds=gn-ye,Ba=gn-De,qC=f-Ds;return qe?Yn(qC,W-Ba):qC}function Ft(gn){var Ds=gn-ye,Ba=gn-De;return ye===t||Ds>=f||Ds<0||qe&&Ba>=W}function lr(){var gn=Ih();if(Ft(gn))return gr(gn);le=rd(lr,nr(gn))}function gr(gn){return le=t,nt&&C?Tt(gn):(C=O=t,ee)}function Qn(){le!==t&&xE(le),De=0,C=ye=O=le=t}function pi(){return le===t?ee:gr(Ih())}function Ji(){var gn=Ih(),Ds=Ft(gn);if(C=arguments,O=this,ye=gn,Ds){if(le===t)return Lt(ye);if(qe)return xE(le),le=rd(lr,f),Tt(ye)}return le===t&&(le=rd(lr,f)),ee}return Ji.cancel=Qn,Ji.flush=pi,Ji}var D3=ar(function(u,f){return fE(u,1,f)}),N3=ar(function(u,f,m){return fE(u,ls(f)||0,m)});function L3(u){return Na(u,he)}function Ph(u,f){if(typeof u!="function"||f!=null&&typeof f!="function")throw new ss(a);var m=function C(){var O=arguments,W=f?f.apply(this,O):O[0],ee=C.cache;if(ee.has(W))return ee.get(W);var le=u.apply(this,O);return C.cache=ee.set(W,le)||ee,le};return m.cache=new(Ph.Cache||Ma),m}Ph.Cache=Ma;function Ah(u){if(typeof u!="function")throw new ss(a);return function(){var f=arguments;switch(f.length){case 0:return!u.call(this);case 1:return!u.call(this,f[0]);case 2:return!u.call(this,f[0],f[1]);case 3:return!u.call(this,f[0],f[1],f[2])}return!u.apply(this,f)}}function F3(u){return _C(2,u)}var U3=Cj(function(u,f){f=f.length==1&&Yt(f[0])?J(f[0],Gi(Mt())):J(Hn(f,1),Gi(Mt()));var m=f.length;return ar(function(C){for(var O=-1,W=Yn(C.length,m);++O<W;)C[O]=f[O].call(this,C[O]);return b(u,this,C)})}),hy=ar(function(u,f){var m=Eo(f,Cc(hy));return Na(u,F,t,f,m)}),EC=ar(function(u,f){var m=Eo(f,Cc(EC));return Na(u,G,t,f,m)}),j3=La(function(u,f){return Na(u,D,t,t,t,f)});function B3(u,f){if(typeof u!="function")throw new ss(a);return f=f===t?f:tr(f),ar(u,f)}function q3(u,f){if(typeof u!="function")throw new ss(a);return f=f==null?0:Pn(tr(f),0),ar(function(m){var C=m[f],O=Po(m,0,f);return C&&ae(O,C),b(u,this,O)})}function W3(u,f,m){var C=!0,O=!0;if(typeof u!="function")throw new ss(a);return on(m)&&(C="leading"in m?!!m.leading:C,O="trailing"in m?!!m.trailing:O),TC(u,f,{leading:C,maxWait:f,trailing:O})}function H3(u){return yC(u,1)}function V3(u,f){return hy(Xm(f),u)}function G3(){if(!arguments.length)return[];var u=arguments[0];return Yt(u)?u:[u]}function z3(u){return os(u,y)}function K3(u,f){return f=typeof f=="function"?f:t,os(u,y,f)}function J3(u){return os(u,h|y)}function Y3(u,f){return f=typeof f=="function"?f:t,os(u,h|y,f)}function X3(u,f){return f==null||dE(u,f,Fn(f))}function Ms(u,f){return u===f||u!==u&&f!==f}var Q3=wh(Um),Z3=wh(function(u,f){return u>=f}),Su=mE(function(){return arguments}())?mE:function(u){return dn(u)&&$r.call(u,"callee")&&!nE.call(u,"callee")},Yt=Ce.isArray,e4=vc?Gi(vc):uj;function $i(u){return u!=null&&Oh(u.length)&&!Ua(u)}function vn(u){return dn(u)&&$i(u)}function t4(u){return u===!0||u===!1||dn(u)&&fi(u)==ut}var Ao=vU||Ey,r4=x?Gi(x):cj;function n4(u){return dn(u)&&u.nodeType===1&&!nd(u)}function i4(u){if(u==null)return!0;if($i(u)&&(Yt(u)||typeof u=="string"||typeof u.splice=="function"||Ao(u)||kc(u)||Su(u)))return!u.length;var f=Xn(u);if(f==$e||f==dr)return!u.size;if(td(u))return!qm(u).length;for(var m in u)if($r.call(u,m))return!1;return!0}function s4(u,f){return Ql(u,f)}function a4(u,f,m){m=typeof m=="function"?m:t;var C=m?m(u,f):t;return C===t?Ql(u,f,t,m):!!C}function py(u){if(!dn(u))return!1;var f=fi(u);return f==rt||f==Zt||typeof u.message=="string"&&typeof u.name=="string"&&!nd(u)}function o4(u){return typeof u=="number"&&sE(u)}function Ua(u){if(!on(u))return!1;var f=fi(u);return f==cn||f==Ot||f==ne||f==er}function CC(u){return typeof u=="number"&&u==tr(u)}function Oh(u){return typeof u=="number"&&u>-1&&u%1==0&&u<=Je}function on(u){var f=ps.default(u);return u!=null&&(f=="object"||f=="function")}function dn(u){return u!=null&&ps.default(u)=="object"}var kC=M?Gi(M):dj;function u4(u,f){return u===f||Bm(u,f,iy(f))}function c4(u,f,m){return m=typeof m=="function"?m:t,Bm(u,f,iy(f),m)}function l4(u){return RC(u)&&u!=+u}function d4(u){if(Kj(u))throw new Vt(s);return yE(u)}function f4(u){return u===null}function h4(u){return u==null}function RC(u){return typeof u=="number"||dn(u)&&fi(u)==_t}function nd(u){if(!dn(u)||fi(u)!=Ue)return!1;var f=ih(u);if(f===null)return!0;var m=$r.call(f,"constructor")&&f.constructor;return typeof m=="function"&&m instanceof m&&eh.call(m)==cU}var vy=R?Gi(R):fj;function p4(u){return CC(u)&&u>=-Je&&u<=Je}var IC=v?Gi(v):hj;function $h(u){return typeof u=="string"||!Yt(u)&&dn(u)&&fi(u)==tn}function Ki(u){return ps.default(u)=="symbol"||dn(u)&&fi(u)==yn}var kc=g?Gi(g):pj;function v4(u){return u===t}function g4(u){return dn(u)&&Xn(u)==Kt}function m4(u){return dn(u)&&fi(u)==Ht}var y4=wh(Wm),_4=wh(function(u,f){return u<=f});function PC(u){if(!u)return[];if($i(u))return $h(u)?$s(u):Oi(u);if(Hl&&u[Hl])return XF(u[Hl]());var f=Xn(u),m=f==$e?Am:f==dr?Xf:Rc;return m(u)}function ja(u){if(!u)return u===0?u:0;if(u=ls(u),u===Re||u===-Re){var f=u<0?-1:1;return f*Ke}return u===u?u:0}function tr(u){var f=ja(u),m=f%1;return f===f?m?f-m:f:0}function AC(u){return u?mu(tr(u),0,Ee):0}function ls(u){if(typeof u=="number")return u;if(Ki(u))return Y;if(on(u)){var f=typeof u.valueOf=="function"?u.valueOf():u;u=on(f)?f+"":f}if(typeof u!="string")return u===0?u:+u;u=JT(u);var m=Ri.test(u);return m||vt.test(u)?hc(u.slice(2),m?2:8):Dn.test(u)?Y:+u}function OC(u){return sa(u,xi(u))}function b4(u){return u?mu(tr(u),-Je,Je):u===0?u:0}function kr(u){return u==null?"":zi(u)}var S4=Tc(function(u,f){if(td(f)||$i(f)){sa(f,Fn(f),u);return}for(var m in f)$r.call(f,m)&&Jl(u,m,f[m])}),$C=Tc(function(u,f){sa(f,xi(f),u)}),xh=Tc(function(u,f,m,C){sa(f,xi(f),u,C)}),w4=Tc(function(u,f,m,C){sa(f,Fn(f),u,C)}),T4=La(Nm);function E4(u,f){var m=wc(u);return f==null?m:lE(m,f)}var C4=ar(function(u,f){u=zr(u);var m=-1,C=f.length,O=C>2?f[2]:t;for(O&&hi(f[0],f[1],O)&&(C=1);++m<C;)for(var W=f[m],ee=xi(W),le=-1,ye=ee.length;++le<ye;){var De=ee[le],Ne=u[De];(Ne===t||Ms(Ne,_c[De])&&!$r.call(u,De))&&(u[De]=W[De])}return u}),k4=ar(function(u){return u.push(t,JE),b(xC,t,u)});function R4(u,f){return lt(u,Mt(f,3),ia)}function I4(u,f){return lt(u,Mt(f,3),Fm)}function P4(u,f){return u==null?u:Lm(u,Mt(f,3),xi)}function A4(u,f){return u==null?u:vE(u,Mt(f,3),xi)}function O4(u,f){return u&&ia(u,Mt(f,3))}function $4(u,f){return u&&Fm(u,Mt(f,3))}function x4(u){return u==null?[]:ph(u,Fn(u))}function M4(u){return u==null?[]:ph(u,xi(u))}function gy(u,f,m){var C=u==null?t:yu(u,f);return C===t?m:C}function D4(u,f){return u!=null&&QE(u,f,ij)}function my(u,f){return u!=null&&QE(u,f,sj)}var N4=HE(function(u,f,m){f!=null&&typeof f.toString!="function"&&(f=th.call(f)),u[f]=m},_y(Mi)),L4=HE(function(u,f,m){f!=null&&typeof f.toString!="function"&&(f=th.call(f)),$r.call(u,f)?u[f].push(m):u[f]=[m]},Mt),F4=ar(Xl);function Fn(u){return $i(u)?uE(u):qm(u)}function xi(u){return $i(u)?uE(u,!0):vj(u)}function U4(u,f){var m={};return f=Mt(f,3),ia(u,function(C,O,W){Da(m,f(C,O,W),C)}),m}function j4(u,f){var m={};return f=Mt(f,3),ia(u,function(C,O,W){Da(m,O,f(C,O,W))}),m}var B4=Tc(function(u,f,m){vh(u,f,m)}),xC=Tc(function(u,f,m,C){vh(u,f,m,C)}),q4=La(function(u,f){var m={};if(u==null)return m;var C=!1;f=J(f,function(W){return W=Io(W,u),C||(C=W.length>1),W}),sa(u,ry(u),m),C&&(m=os(m,h|p|y,Nj));for(var O=f.length;O--;)Km(m,f[O]);return m});function W4(u,f){return MC(u,Ah(Mt(f)))}var H4=La(function(u,f){return u==null?{}:mj(u,f)});function MC(u,f){if(u==null)return{};var m=J(ry(u),function(C){return[C]});return f=Mt(f),CE(u,m,function(C,O){return f(C,O[0])})}function V4(u,f,m){f=Io(f,u);var C=-1,O=f.length;for(O||(O=1,u=t);++C<O;){var W=u==null?t:u[aa(f[C])];W===t&&(C=O,W=m),u=Ua(W)?W.call(u):W}return u}function G4(u,f,m){return u==null?u:Zl(u,f,m)}function z4(u,f,m,C){return C=typeof C=="function"?C:t,u==null?u:Zl(u,f,m,C)}var DC=zE(Fn),NC=zE(xi);function K4(u,f,m){var C=Yt(u),O=C||Ao(u)||kc(u);if(f=Mt(f,4),m==null){var W=u&&u.constructor;O?m=C?new W:[]:on(u)?m=Ua(W)?wc(ih(u)):{}:m={}}return(O?S:ia)(u,function(ee,le,ye){return f(m,ee,le,ye)}),m}function J4(u,f){return u==null?!0:Km(u,f)}function Y4(u,f,m){return u==null?u:AE(u,f,Xm(m))}function X4(u,f,m,C){return C=typeof C=="function"?C:t,u==null?u:AE(u,f,Xm(m),C)}function Rc(u){return u==null?[]:Pm(u,Fn(u))}function Q4(u){return u==null?[]:Pm(u,xi(u))}function Z4(u,f,m){return m===t&&(m=f,f=t),m!==t&&(m=ls(m),m=m===m?m:0),f!==t&&(f=ls(f),f=f===f?f:0),mu(ls(u),f,m)}function eq(u,f,m){return f=ja(f),m===t?(m=f,f=0):m=ja(m),u=ls(u),aj(u,f,m)}function tq(u,f,m){if(m&&typeof m!="boolean"&&hi(u,f,m)&&(f=m=t),m===t&&(typeof f=="boolean"?(m=f,f=t):typeof u=="boolean"&&(m=u,u=t)),u===t&&f===t?(u=0,f=1):(u=ja(u),f===t?(f=u,u=0):f=ja(f)),u>f){var C=u;u=f,f=C}if(m||u%1||f%1){var O=aE();return Yn(u+O*(f-u+fc("1e-"+((O+"").length-1))),f)}return Vm(u,f)}var rq=Ec(function(u,f,m){return f=f.toLowerCase(),u+(m?LC(f):f)});function LC(u){return yy(kr(u).toLowerCase())}function FC(u){return u=kr(u),u&&u.replace(je,GF).replace(lu,"")}function nq(u,f,m){u=kr(u),f=zi(f);var C=u.length;m=m===t?C:mu(tr(m),0,C);var O=m;return m-=f.length,m>=0&&u.slice(m,O)==f}function iq(u){return u=kr(u),u&&pe.test(u)?u.replace(xe,zF):u}function sq(u){return u=kr(u),u&&tt.test(u)?u.replace(ot,"\\$&"):u}var aq=Ec(function(u,f,m){return u+(m?"-":"")+f.toLowerCase()}),oq=Ec(function(u,f,m){return u+(m?" ":"")+f.toLowerCase()}),uq=BE("toLowerCase");function cq(u,f,m){u=kr(u),f=tr(f);var C=f?mc(u):0;if(!f||C>=f)return u;var O=(f-C)/2;return Sh(uh(O),m)+u+Sh(oh(O),m)}function lq(u,f,m){u=kr(u),f=tr(f);var C=f?mc(u):0;return f&&C<f?u+Sh(f-C,m):u}function dq(u,f,m){u=kr(u),f=tr(f);var C=f?mc(u):0;return f&&C<f?Sh(f-C,m)+u:u}function fq(u,f,m){return m||f==null?f=0:f&&(f=+f),_U(kr(u).replace(it,""),f||0)}function hq(u,f,m){return(m?hi(u,f,m):f===t)?f=1:f=tr(f),Gm(kr(u),f)}function pq(){var u=arguments,f=kr(u[0]);return u.length<3?f:f.replace(u[1],u[2])}var vq=Ec(function(u,f,m){return u+(m?"_":"")+f.toLowerCase()});function gq(u,f,m){return m&&typeof m!="number"&&hi(u,f,m)&&(f=m=t),m=m===t?Ee:m>>>0,m?(u=kr(u),u&&(typeof f=="string"||f!=null&&!vy(f))&&(f=zi(f),!f&&gc(u))?Po($s(u),0,m):u.split(f,m)):[]}var mq=Ec(function(u,f,m){return u+(m?" ":"")+yy(f)});function yq(u,f,m){return u=kr(u),m=m==null?0:mu(tr(m),0,u.length),f=zi(f),u.slice(m,m+f.length)==f}function _q(u,f,m){var C=U.templateSettings;m&&hi(u,f,m)&&(f=t),u=kr(u),f=xh({},f,C,KE);var O=xh({},f.imports,C.imports,KE),W=Fn(O),ee=Pm(O,W),le,ye,De=0,Ne=f.interpolate||st,qe="__p += '",nt=Om((f.escape||st).source+"|"+Ne.source+"|"+(Ne===ge?ln:st).source+"|"+(f.evaluate||st).source+"|$","g"),Tt="//# sourceURL="+($r.call(f,"sourceURL")?(f.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++lc+"]")+`
368
368
  `;u.replace(nt,function(Ft,lr,gr,Qn,pi,Ji){return gr||(gr=Qn),qe+=u.slice(De,Ji).replace(Jt,KF),lr&&(le=!0,qe+=`' +
369
369
  __e(`+lr+`) +
370
370
  '`),pi&&(ye=!0,qe+=`';
@@ -381,7 +381,7 @@ __p += '`),gr&&(qe+=`' +
381
381
  function print() { __p += __j.call(arguments, '') }
382
382
  `:`;
383
383
  `)+qe+`return __p
384
- }`;var nr=jC(function(){return Er(W,Tt+"return "+qe).apply(t,ee)});if(nr.source=qe,py(nr))throw nr;return nr}function bq(u){return kr(u).toLowerCase()}function Sq(u){return kr(u).toUpperCase()}function wq(u,f,m){if(u=kr(u),u&&(m||f===t))return JT(u);if(!u||!(f=zi(f)))return u;var C=$s(u),O=$s(f),W=YT(C,O),ee=XT(C,O)+1;return Po(C,W,ee).join("")}function Tq(u,f,m){if(u=kr(u),u&&(m||f===t))return u.slice(0,ZT(u)+1);if(!u||!(f=zi(f)))return u;var C=$s(u),O=XT(C,$s(f))+1;return Po(C,0,O).join("")}function Eq(u,f,m){if(u=kr(u),u&&(m||f===t))return u.replace(it,"");if(!u||!(f=zi(f)))return u;var C=$s(u),O=YT(C,$s(f));return Po(C,O).join("")}function Cq(u,f){var m=X,C=ve;if(on(f)){var O="separator"in f?f.separator:O;m="length"in f?tr(f.length):m,C="omission"in f?zi(f.omission):C}u=kr(u);var W=u.length;if(gc(u)){var ee=$s(u);W=ee.length}if(m>=W)return u;var le=m-mc(C);if(le<1)return C;var ye=ee?Po(ee,0,le).join(""):u.slice(0,le);if(O===t)return ye+C;if(ee&&(le+=ye.length-le),vy(O)){if(u.slice(le).search(O)){var De,Ne=ye;for(O.global||(O=Om(O.source,kr(qt.exec(O))+"g")),O.lastIndex=0;De=O.exec(Ne);)var qe=De.index;ye=ye.slice(0,qe===t?le:qe)}}else if(u.indexOf(zi(O),le)!=le){var nt=ye.lastIndexOf(O);nt>-1&&(ye=ye.slice(0,nt))}return ye+C}function kq(u){return u=kr(u),u&&Le.test(u)?u.replace(de,tU):u}var Rq=Ec(function(u,f,m){return u+(m?" ":"")+f.toUpperCase()}),yy=BE("toUpperCase");function UC(u,f,m){return u=kr(u),f=m?t:f,f===t?YF(u)?iU(u):At(u):u.match(f)||[]}var jC=ar(function(u,f){try{return b(u,t,f)}catch(m){return py(m)?m:new Vt(m)}}),Iq=La(function(u,f){return S(f,function(m){m=aa(m),Da(u,m,fy(u[m],u))}),u});function Pq(u){var f=u==null?0:u.length,m=Mt();return u=f?J(u,function(C){if(typeof C[1]!="function")throw new ss(a);return[m(C[0]),C[1]]}):[],ar(function(C){for(var O=-1;++O<f;){var W=u[O];if(b(W[0],this,C))return b(W[1],this,C)}})}function Aq(u){return tj(os(u,h))}function _y(u){return function(){return u}}function Oq(u,f){return u==null||u!==u?f:u}var $q=WE(),xq=WE(!0);function Mi(u){return u}function by(u){return _E(typeof u=="function"?u:os(u,h))}function Mq(u){return SE(os(u,h))}function Dq(u,f){return wE(u,os(f,h))}var Nq=ar(function(u,f){return function(m){return Xl(m,u,f)}}),Lq=ar(function(u,f){return function(m){return Xl(u,m,f)}});function Sy(u,f,m){var C=Fn(f),O=ph(f,C);m==null&&!(on(f)&&(O.length||!C.length))&&(m=f,f=u,u=this,O=ph(f,Fn(f)));var W=!(on(m)&&"chain"in m)||!!m.chain,ee=Ua(u);return S(O,function(le){var ye=f[le];u[le]=ye,ee&&(u.prototype[le]=function(){var De=this.__chain__;if(W||De){var Ne=u(this.__wrapped__),qe=Ne.__actions__=Oi(this.__actions__);return qe.push({func:ye,args:arguments,thisArg:u}),Ne.__chain__=De,Ne}return ye.apply(u,ae([this.value()],arguments))})}),u}function Fq(){return $t._===this&&($t._=lU),this}function wy(){}function Uq(u){return u=tr(u),ar(function(f){return TE(f,u)})}var jq=Zm(J),Bq=Zm(E),qq=Zm(gt);function BC(u){return ay(u)?Cm(aa(u)):yj(u)}function Wq(u){return function(f){return u==null?t:yu(u,f)}}var Hq=VE(),Vq=VE(!0);function Ty(){return[]}function Ey(){return!1}function Gq(){return{}}function zq(){return""}function Kq(){return!0}function Jq(u,f){if(u=tr(u),u<1||u>Je)return[];var m=Ee,C=Yn(u,Ee);f=Mt(f),u-=Ee;for(var O=Im(C,f);++m<u;)f(m);return O}function Yq(u){return Yt(u)?J(u,aa):Ki(u)?[u]:Oi(oC(kr(u)))}function Xq(u){var f=++uU;return kr(u)+f}var Qq=bh(function(u,f){return u+f},0),Zq=ey("ceil"),e6=bh(function(u,f){return u/f},1),t6=ey("floor");function r6(u){return u&&u.length?hh(u,Mi,Um):t}function n6(u,f){return u&&u.length?hh(u,Mt(f,2),Um):t}function i6(u){return Wn(u,Mi)}function s6(u,f){return Wn(u,Mt(f,2))}function a6(u){return u&&u.length?hh(u,Mi,Wm):t}function o6(u,f){return u&&u.length?hh(u,Mt(f,2),Wm):t}var u6=bh(function(u,f){return u*f},1),c6=ey("round"),l6=bh(function(u,f){return u-f},0);function d6(u){return u&&u.length?Rm(u,Mi):0}function f6(u,f){return u&&u.length?Rm(u,Mt(f,2)):0}return U.after=MB,U.ary=yC,U.assign=S4,U.assignIn=$C,U.assignInWith=xh,U.assignWith=w4,U.at=T4,U.before=_C,U.bind=fy,U.bindAll=Iq,U.bindKey=bC,U.castArray=GB,U.chain=vC,U.chunk=t3,U.compact=r3,U.concat=n3,U.cond=Pq,U.conforms=Aq,U.constant=_y,U.countBy=dB,U.create=E4,U.curry=SC,U.curryRight=wC,U.debounce=TC,U.defaults=C4,U.defaultsDeep=k4,U.defer=DB,U.delay=NB,U.difference=i3,U.differenceBy=s3,U.differenceWith=a3,U.drop=o3,U.dropRight=u3,U.dropRightWhile=c3,U.dropWhile=l3,U.fill=d3,U.filter=hB,U.flatMap=gB,U.flatMapDeep=mB,U.flatMapDepth=yB,U.flatten=dC,U.flattenDeep=f3,U.flattenDepth=h3,U.flip=LB,U.flow=$q,U.flowRight=xq,U.fromPairs=p3,U.functions=x4,U.functionsIn=M4,U.groupBy=_B,U.initial=g3,U.intersection=m3,U.intersectionBy=y3,U.intersectionWith=_3,U.invert=N4,U.invertBy=L4,U.invokeMap=SB,U.iteratee=by,U.keyBy=wB,U.keys=Fn,U.keysIn=xi,U.map=Rh,U.mapKeys=U4,U.mapValues=j4,U.matches=Mq,U.matchesProperty=Dq,U.memoize=Ph,U.merge=B4,U.mergeWith=xC,U.method=Nq,U.methodOf=Lq,U.mixin=Sy,U.negate=Ah,U.nthArg=Uq,U.omit=q4,U.omitBy=W4,U.once=FB,U.orderBy=TB,U.over=jq,U.overArgs=UB,U.overEvery=Bq,U.overSome=qq,U.partial=hy,U.partialRight=EC,U.partition=EB,U.pick=H4,U.pickBy=MC,U.property=BC,U.propertyOf=Wq,U.pull=T3,U.pullAll=hC,U.pullAllBy=E3,U.pullAllWith=C3,U.pullAt=k3,U.range=Hq,U.rangeRight=Vq,U.rearg=jB,U.reject=RB,U.remove=R3,U.rest=BB,U.reverse=ly,U.sampleSize=PB,U.set=G4,U.setWith=z4,U.shuffle=AB,U.slice=I3,U.sortBy=xB,U.sortedUniq=D3,U.sortedUniqBy=N3,U.split=gq,U.spread=qB,U.tail=L3,U.take=F3,U.takeRight=U3,U.takeRightWhile=j3,U.takeWhile=B3,U.tap=rB,U.throttle=WB,U.thru=kh,U.toArray=PC,U.toPairs=DC,U.toPairsIn=NC,U.toPath=Yq,U.toPlainObject=OC,U.transform=K4,U.unary=HB,U.union=q3,U.unionBy=W3,U.unionWith=H3,U.uniq=V3,U.uniqBy=G3,U.uniqWith=z3,U.unset=J4,U.unzip=dy,U.unzipWith=pC,U.update=Y4,U.updateWith=X4,U.values=Rc,U.valuesIn=Q4,U.without=K3,U.words=UC,U.wrap=VB,U.xor=J3,U.xorBy=Y3,U.xorWith=X3,U.zip=Q3,U.zipObject=Z3,U.zipObjectDeep=eB,U.zipWith=tB,U.entries=DC,U.entriesIn=NC,U.extend=$C,U.extendWith=xh,Sy(U,U),U.add=Qq,U.attempt=jC,U.camelCase=rq,U.capitalize=LC,U.ceil=Zq,U.clamp=Z4,U.clone=zB,U.cloneDeep=JB,U.cloneDeepWith=YB,U.cloneWith=KB,U.conformsTo=XB,U.deburr=FC,U.defaultTo=Oq,U.divide=e6,U.endsWith=nq,U.eq=Ms,U.escape=iq,U.escapeRegExp=sq,U.every=fB,U.find=pB,U.findIndex=cC,U.findKey=R4,U.findLast=vB,U.findLastIndex=lC,U.findLastKey=I4,U.floor=t6,U.forEach=gC,U.forEachRight=mC,U.forIn=P4,U.forInRight=A4,U.forOwn=O4,U.forOwnRight=$4,U.get=gy,U.gt=QB,U.gte=ZB,U.has=D4,U.hasIn=my,U.head=fC,U.identity=Mi,U.includes=bB,U.indexOf=v3,U.inRange=eq,U.invoke=F4,U.isArguments=Su,U.isArray=Yt,U.isArrayBuffer=e4,U.isArrayLike=$i,U.isArrayLikeObject=vn,U.isBoolean=t4,U.isBuffer=Ao,U.isDate=r4,U.isElement=n4,U.isEmpty=i4,U.isEqual=s4,U.isEqualWith=a4,U.isError=py,U.isFinite=o4,U.isFunction=Ua,U.isInteger=CC,U.isLength=Oh,U.isMap=kC,U.isMatch=u4,U.isMatchWith=c4,U.isNaN=l4,U.isNative=d4,U.isNil=h4,U.isNull=f4,U.isNumber=RC,U.isObject=on,U.isObjectLike=dn,U.isPlainObject=nd,U.isRegExp=vy,U.isSafeInteger=p4,U.isSet=IC,U.isString=$h,U.isSymbol=Ki,U.isTypedArray=kc,U.isUndefined=v4,U.isWeakMap=g4,U.isWeakSet=m4,U.join=b3,U.kebabCase=aq,U.last=cs,U.lastIndexOf=S3,U.lowerCase=oq,U.lowerFirst=uq,U.lt=y4,U.lte=_4,U.max=r6,U.maxBy=n6,U.mean=i6,U.meanBy=s6,U.min=a6,U.minBy=o6,U.stubArray=Ty,U.stubFalse=Ey,U.stubObject=Gq,U.stubString=zq,U.stubTrue=Kq,U.multiply=u6,U.nth=w3,U.noConflict=Fq,U.noop=wy,U.now=Ih,U.pad=cq,U.padEnd=lq,U.padStart=dq,U.parseInt=fq,U.random=tq,U.reduce=CB,U.reduceRight=kB,U.repeat=hq,U.replace=pq,U.result=V4,U.round=c6,U.runInContext=me,U.sample=IB,U.size=OB,U.snakeCase=vq,U.some=$B,U.sortedIndex=P3,U.sortedIndexBy=A3,U.sortedIndexOf=O3,U.sortedLastIndex=$3,U.sortedLastIndexBy=x3,U.sortedLastIndexOf=M3,U.startCase=mq,U.startsWith=yq,U.subtract=l6,U.sum=d6,U.sumBy=f6,U.template=_q,U.times=Jq,U.toFinite=ja,U.toInteger=tr,U.toLength=AC,U.toLower=bq,U.toNumber=ls,U.toSafeInteger=b4,U.toString=kr,U.toUpper=Sq,U.trim=wq,U.trimEnd=Tq,U.trimStart=Eq,U.truncate=Cq,U.unescape=kq,U.uniqueId=Xq,U.upperCase=Rq,U.upperFirst=yy,U.each=gC,U.eachRight=mC,U.first=fC,Sy(U,function(){var u={};return ia(U,function(f,m){$r.call(U.prototype,m)||(u[m]=f)}),u}(),{chain:!1}),U.VERSION=n,S(["bind","bindKey","curry","curryRight","partial","partialRight"],function(u){U[u].placeholder=U}),S(["drop","take"],function(u,f){cr.prototype[u]=function(m){m=m===t?1:Pn(tr(m),0);var C=this.__filtered__&&!f?new cr(this):this.clone();return C.__filtered__?C.__takeCount__=Yn(m,C.__takeCount__):C.__views__.push({size:Yn(m,Ee),type:u+(C.__dir__<0?"Right":"")}),C},cr.prototype[u+"Right"]=function(m){return this.reverse()[u](m).reverse()}}),S(["filter","map","takeWhile"],function(u,f){var m=f+1,C=m==He||m==Xe;cr.prototype[u]=function(O){var W=this.clone();return W.__iteratees__.push({iteratee:Mt(O,3),type:m}),W.__filtered__=W.__filtered__||C,W}}),S(["head","last"],function(u,f){var m="take"+(f?"Right":"");cr.prototype[u]=function(){return this[m](1).value()[0]}}),S(["initial","tail"],function(u,f){var m="drop"+(f?"":"Right");cr.prototype[u]=function(){return this.__filtered__?new cr(this):this[m](1)}}),cr.prototype.compact=function(){return this.filter(Mi)},cr.prototype.find=function(u){return this.filter(u).head()},cr.prototype.findLast=function(u){return this.reverse().find(u)},cr.prototype.invokeMap=ar(function(u,f){return typeof u=="function"?new cr(this):this.map(function(m){return Xl(m,u,f)})}),cr.prototype.reject=function(u){return this.filter(Ah(Mt(u)))},cr.prototype.slice=function(u,f){u=tr(u);var m=this;return m.__filtered__&&(u>0||f<0)?new cr(m):(u<0?m=m.takeRight(-u):u&&(m=m.drop(u)),f!==t&&(f=tr(f),m=f<0?m.dropRight(-f):m.take(f-u)),m)},cr.prototype.takeRightWhile=function(u){return this.reverse().takeWhile(u).reverse()},cr.prototype.toArray=function(){return this.take(Ee)},ia(cr.prototype,function(u,f){var m=/^(?:filter|find|map|reject)|While$/.test(f),C=/^(?:head|last)$/.test(f),O=U[C?"take"+(f=="last"?"Right":""):f],W=C||/^find/.test(f);O&&(U.prototype[f]=function(){var ee=this.__wrapped__,le=C?[1]:arguments,ye=ee instanceof cr,De=le[0],Ne=ye||Yt(ee),qe=function(gr){var Qn=O.apply(U,ae([gr],le));return C&&nt?Qn[0]:Qn};Ne&&m&&typeof De=="function"&&De.length!=1&&(ye=Ne=!1);var nt=this.__chain__,Tt=!!this.__actions__.length,Lt=W&&!nt,nr=ye&&!Tt;if(!W&&Ne){ee=nr?ee:new cr(this);var Ft=u.apply(ee,le);return Ft.__actions__.push({func:kh,args:[qe],thisArg:t}),new as(Ft,nt)}return Lt&&nr?u.apply(this,le):(Ft=this.thru(qe),Lt?C?Ft.value()[0]:Ft.value():Ft)})}),S(["pop","push","shift","sort","splice","unshift"],function(u){var f=Qf[u],m=/^(?:push|sort|unshift)$/.test(u)?"tap":"thru",C=/^(?:pop|shift)$/.test(u);U.prototype[u]=function(){var O=arguments;if(C&&!this.__chain__){var W=this.value();return f.apply(Yt(W)?W:[],O)}return this[m](function(ee){return f.apply(Yt(ee)?ee:[],O)})}}),ia(cr.prototype,function(u,f){var m=U[f];if(m){var C=m.name+"";$r.call(Sc,C)||(Sc[C]=[]),Sc[C].push({name:f,func:m})}}),Sc[_h(t,A).name]=[{name:"wrapper",func:t}],cr.prototype.clone=kU,cr.prototype.reverse=RU,cr.prototype.value=IU,U.prototype.at=nB,U.prototype.chain=iB,U.prototype.commit=sB,U.prototype.next=aB,U.prototype.plant=uB,U.prototype.reverse=cB,U.prototype.toJSON=U.prototype.valueOf=U.prototype.value=lB,U.prototype.first=U.prototype.head,Hl&&(U.prototype[Hl]=oB),U},yc=sU();Ai?((Ai.exports=yc)._=yc,To._=yc):$t._=yc}).call(Ed)})(ai,ai.exports);function rA(r,e){var t=typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=Tve(r))||e){t&&(r=t);var n=0,i=function(){};return{s:i,n:function(){return n>=r.length?{done:!0}:{done:!1,value:r[n++]}},e:function(l){throw l},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
384
+ }`;var nr=jC(function(){return Er(W,Tt+"return "+qe).apply(t,ee)});if(nr.source=qe,py(nr))throw nr;return nr}function bq(u){return kr(u).toLowerCase()}function Sq(u){return kr(u).toUpperCase()}function wq(u,f,m){if(u=kr(u),u&&(m||f===t))return JT(u);if(!u||!(f=zi(f)))return u;var C=$s(u),O=$s(f),W=YT(C,O),ee=XT(C,O)+1;return Po(C,W,ee).join("")}function Tq(u,f,m){if(u=kr(u),u&&(m||f===t))return u.slice(0,ZT(u)+1);if(!u||!(f=zi(f)))return u;var C=$s(u),O=XT(C,$s(f))+1;return Po(C,0,O).join("")}function Eq(u,f,m){if(u=kr(u),u&&(m||f===t))return u.replace(it,"");if(!u||!(f=zi(f)))return u;var C=$s(u),O=YT(C,$s(f));return Po(C,O).join("")}function Cq(u,f){var m=X,C=ve;if(on(f)){var O="separator"in f?f.separator:O;m="length"in f?tr(f.length):m,C="omission"in f?zi(f.omission):C}u=kr(u);var W=u.length;if(gc(u)){var ee=$s(u);W=ee.length}if(m>=W)return u;var le=m-mc(C);if(le<1)return C;var ye=ee?Po(ee,0,le).join(""):u.slice(0,le);if(O===t)return ye+C;if(ee&&(le+=ye.length-le),vy(O)){if(u.slice(le).search(O)){var De,Ne=ye;for(O.global||(O=Om(O.source,kr(qt.exec(O))+"g")),O.lastIndex=0;De=O.exec(Ne);)var qe=De.index;ye=ye.slice(0,qe===t?le:qe)}}else if(u.indexOf(zi(O),le)!=le){var nt=ye.lastIndexOf(O);nt>-1&&(ye=ye.slice(0,nt))}return ye+C}function kq(u){return u=kr(u),u&&Le.test(u)?u.replace(de,tU):u}var Rq=Ec(function(u,f,m){return u+(m?" ":"")+f.toUpperCase()}),yy=BE("toUpperCase");function UC(u,f,m){return u=kr(u),f=m?t:f,f===t?YF(u)?iU(u):At(u):u.match(f)||[]}var jC=ar(function(u,f){try{return b(u,t,f)}catch(m){return py(m)?m:new Vt(m)}}),Iq=La(function(u,f){return S(f,function(m){m=aa(m),Da(u,m,fy(u[m],u))}),u});function Pq(u){var f=u==null?0:u.length,m=Mt();return u=f?J(u,function(C){if(typeof C[1]!="function")throw new ss(a);return[m(C[0]),C[1]]}):[],ar(function(C){for(var O=-1;++O<f;){var W=u[O];if(b(W[0],this,C))return b(W[1],this,C)}})}function Aq(u){return tj(os(u,h))}function _y(u){return function(){return u}}function Oq(u,f){return u==null||u!==u?f:u}var $q=WE(),xq=WE(!0);function Mi(u){return u}function by(u){return _E(typeof u=="function"?u:os(u,h))}function Mq(u){return SE(os(u,h))}function Dq(u,f){return wE(u,os(f,h))}var Nq=ar(function(u,f){return function(m){return Xl(m,u,f)}}),Lq=ar(function(u,f){return function(m){return Xl(u,m,f)}});function Sy(u,f,m){var C=Fn(f),O=ph(f,C);m==null&&!(on(f)&&(O.length||!C.length))&&(m=f,f=u,u=this,O=ph(f,Fn(f)));var W=!(on(m)&&"chain"in m)||!!m.chain,ee=Ua(u);return S(O,function(le){var ye=f[le];u[le]=ye,ee&&(u.prototype[le]=function(){var De=this.__chain__;if(W||De){var Ne=u(this.__wrapped__),qe=Ne.__actions__=Oi(this.__actions__);return qe.push({func:ye,args:arguments,thisArg:u}),Ne.__chain__=De,Ne}return ye.apply(u,ae([this.value()],arguments))})}),u}function Fq(){return $t._===this&&($t._=lU),this}function wy(){}function Uq(u){return u=tr(u),ar(function(f){return TE(f,u)})}var jq=Zm(J),Bq=Zm(E),qq=Zm(gt);function BC(u){return ay(u)?Cm(aa(u)):yj(u)}function Wq(u){return function(f){return u==null?t:yu(u,f)}}var Hq=VE(),Vq=VE(!0);function Ty(){return[]}function Ey(){return!1}function Gq(){return{}}function zq(){return""}function Kq(){return!0}function Jq(u,f){if(u=tr(u),u<1||u>Je)return[];var m=Ee,C=Yn(u,Ee);f=Mt(f),u-=Ee;for(var O=Im(C,f);++m<u;)f(m);return O}function Yq(u){return Yt(u)?J(u,aa):Ki(u)?[u]:Oi(oC(kr(u)))}function Xq(u){var f=++uU;return kr(u)+f}var Qq=bh(function(u,f){return u+f},0),Zq=ey("ceil"),e6=bh(function(u,f){return u/f},1),t6=ey("floor");function r6(u){return u&&u.length?hh(u,Mi,Um):t}function n6(u,f){return u&&u.length?hh(u,Mt(f,2),Um):t}function i6(u){return Wn(u,Mi)}function s6(u,f){return Wn(u,Mt(f,2))}function a6(u){return u&&u.length?hh(u,Mi,Wm):t}function o6(u,f){return u&&u.length?hh(u,Mt(f,2),Wm):t}var u6=bh(function(u,f){return u*f},1),c6=ey("round"),l6=bh(function(u,f){return u-f},0);function d6(u){return u&&u.length?Rm(u,Mi):0}function f6(u,f){return u&&u.length?Rm(u,Mt(f,2)):0}return U.after=M3,U.ary=yC,U.assign=S4,U.assignIn=$C,U.assignInWith=xh,U.assignWith=w4,U.at=T4,U.before=_C,U.bind=fy,U.bindAll=Iq,U.bindKey=bC,U.castArray=G3,U.chain=vC,U.chunk=tB,U.compact=rB,U.concat=nB,U.cond=Pq,U.conforms=Aq,U.constant=_y,U.countBy=d3,U.create=E4,U.curry=SC,U.curryRight=wC,U.debounce=TC,U.defaults=C4,U.defaultsDeep=k4,U.defer=D3,U.delay=N3,U.difference=iB,U.differenceBy=sB,U.differenceWith=aB,U.drop=oB,U.dropRight=uB,U.dropRightWhile=cB,U.dropWhile=lB,U.fill=dB,U.filter=h3,U.flatMap=g3,U.flatMapDeep=m3,U.flatMapDepth=y3,U.flatten=dC,U.flattenDeep=fB,U.flattenDepth=hB,U.flip=L3,U.flow=$q,U.flowRight=xq,U.fromPairs=pB,U.functions=x4,U.functionsIn=M4,U.groupBy=_3,U.initial=gB,U.intersection=mB,U.intersectionBy=yB,U.intersectionWith=_B,U.invert=N4,U.invertBy=L4,U.invokeMap=S3,U.iteratee=by,U.keyBy=w3,U.keys=Fn,U.keysIn=xi,U.map=Rh,U.mapKeys=U4,U.mapValues=j4,U.matches=Mq,U.matchesProperty=Dq,U.memoize=Ph,U.merge=B4,U.mergeWith=xC,U.method=Nq,U.methodOf=Lq,U.mixin=Sy,U.negate=Ah,U.nthArg=Uq,U.omit=q4,U.omitBy=W4,U.once=F3,U.orderBy=T3,U.over=jq,U.overArgs=U3,U.overEvery=Bq,U.overSome=qq,U.partial=hy,U.partialRight=EC,U.partition=E3,U.pick=H4,U.pickBy=MC,U.property=BC,U.propertyOf=Wq,U.pull=TB,U.pullAll=hC,U.pullAllBy=EB,U.pullAllWith=CB,U.pullAt=kB,U.range=Hq,U.rangeRight=Vq,U.rearg=j3,U.reject=R3,U.remove=RB,U.rest=B3,U.reverse=ly,U.sampleSize=P3,U.set=G4,U.setWith=z4,U.shuffle=A3,U.slice=IB,U.sortBy=x3,U.sortedUniq=DB,U.sortedUniqBy=NB,U.split=gq,U.spread=q3,U.tail=LB,U.take=FB,U.takeRight=UB,U.takeRightWhile=jB,U.takeWhile=BB,U.tap=r3,U.throttle=W3,U.thru=kh,U.toArray=PC,U.toPairs=DC,U.toPairsIn=NC,U.toPath=Yq,U.toPlainObject=OC,U.transform=K4,U.unary=H3,U.union=qB,U.unionBy=WB,U.unionWith=HB,U.uniq=VB,U.uniqBy=GB,U.uniqWith=zB,U.unset=J4,U.unzip=dy,U.unzipWith=pC,U.update=Y4,U.updateWith=X4,U.values=Rc,U.valuesIn=Q4,U.without=KB,U.words=UC,U.wrap=V3,U.xor=JB,U.xorBy=YB,U.xorWith=XB,U.zip=QB,U.zipObject=ZB,U.zipObjectDeep=e3,U.zipWith=t3,U.entries=DC,U.entriesIn=NC,U.extend=$C,U.extendWith=xh,Sy(U,U),U.add=Qq,U.attempt=jC,U.camelCase=rq,U.capitalize=LC,U.ceil=Zq,U.clamp=Z4,U.clone=z3,U.cloneDeep=J3,U.cloneDeepWith=Y3,U.cloneWith=K3,U.conformsTo=X3,U.deburr=FC,U.defaultTo=Oq,U.divide=e6,U.endsWith=nq,U.eq=Ms,U.escape=iq,U.escapeRegExp=sq,U.every=f3,U.find=p3,U.findIndex=cC,U.findKey=R4,U.findLast=v3,U.findLastIndex=lC,U.findLastKey=I4,U.floor=t6,U.forEach=gC,U.forEachRight=mC,U.forIn=P4,U.forInRight=A4,U.forOwn=O4,U.forOwnRight=$4,U.get=gy,U.gt=Q3,U.gte=Z3,U.has=D4,U.hasIn=my,U.head=fC,U.identity=Mi,U.includes=b3,U.indexOf=vB,U.inRange=eq,U.invoke=F4,U.isArguments=Su,U.isArray=Yt,U.isArrayBuffer=e4,U.isArrayLike=$i,U.isArrayLikeObject=vn,U.isBoolean=t4,U.isBuffer=Ao,U.isDate=r4,U.isElement=n4,U.isEmpty=i4,U.isEqual=s4,U.isEqualWith=a4,U.isError=py,U.isFinite=o4,U.isFunction=Ua,U.isInteger=CC,U.isLength=Oh,U.isMap=kC,U.isMatch=u4,U.isMatchWith=c4,U.isNaN=l4,U.isNative=d4,U.isNil=h4,U.isNull=f4,U.isNumber=RC,U.isObject=on,U.isObjectLike=dn,U.isPlainObject=nd,U.isRegExp=vy,U.isSafeInteger=p4,U.isSet=IC,U.isString=$h,U.isSymbol=Ki,U.isTypedArray=kc,U.isUndefined=v4,U.isWeakMap=g4,U.isWeakSet=m4,U.join=bB,U.kebabCase=aq,U.last=cs,U.lastIndexOf=SB,U.lowerCase=oq,U.lowerFirst=uq,U.lt=y4,U.lte=_4,U.max=r6,U.maxBy=n6,U.mean=i6,U.meanBy=s6,U.min=a6,U.minBy=o6,U.stubArray=Ty,U.stubFalse=Ey,U.stubObject=Gq,U.stubString=zq,U.stubTrue=Kq,U.multiply=u6,U.nth=wB,U.noConflict=Fq,U.noop=wy,U.now=Ih,U.pad=cq,U.padEnd=lq,U.padStart=dq,U.parseInt=fq,U.random=tq,U.reduce=C3,U.reduceRight=k3,U.repeat=hq,U.replace=pq,U.result=V4,U.round=c6,U.runInContext=me,U.sample=I3,U.size=O3,U.snakeCase=vq,U.some=$3,U.sortedIndex=PB,U.sortedIndexBy=AB,U.sortedIndexOf=OB,U.sortedLastIndex=$B,U.sortedLastIndexBy=xB,U.sortedLastIndexOf=MB,U.startCase=mq,U.startsWith=yq,U.subtract=l6,U.sum=d6,U.sumBy=f6,U.template=_q,U.times=Jq,U.toFinite=ja,U.toInteger=tr,U.toLength=AC,U.toLower=bq,U.toNumber=ls,U.toSafeInteger=b4,U.toString=kr,U.toUpper=Sq,U.trim=wq,U.trimEnd=Tq,U.trimStart=Eq,U.truncate=Cq,U.unescape=kq,U.uniqueId=Xq,U.upperCase=Rq,U.upperFirst=yy,U.each=gC,U.eachRight=mC,U.first=fC,Sy(U,function(){var u={};return ia(U,function(f,m){$r.call(U.prototype,m)||(u[m]=f)}),u}(),{chain:!1}),U.VERSION=n,S(["bind","bindKey","curry","curryRight","partial","partialRight"],function(u){U[u].placeholder=U}),S(["drop","take"],function(u,f){cr.prototype[u]=function(m){m=m===t?1:Pn(tr(m),0);var C=this.__filtered__&&!f?new cr(this):this.clone();return C.__filtered__?C.__takeCount__=Yn(m,C.__takeCount__):C.__views__.push({size:Yn(m,Ee),type:u+(C.__dir__<0?"Right":"")}),C},cr.prototype[u+"Right"]=function(m){return this.reverse()[u](m).reverse()}}),S(["filter","map","takeWhile"],function(u,f){var m=f+1,C=m==He||m==Xe;cr.prototype[u]=function(O){var W=this.clone();return W.__iteratees__.push({iteratee:Mt(O,3),type:m}),W.__filtered__=W.__filtered__||C,W}}),S(["head","last"],function(u,f){var m="take"+(f?"Right":"");cr.prototype[u]=function(){return this[m](1).value()[0]}}),S(["initial","tail"],function(u,f){var m="drop"+(f?"":"Right");cr.prototype[u]=function(){return this.__filtered__?new cr(this):this[m](1)}}),cr.prototype.compact=function(){return this.filter(Mi)},cr.prototype.find=function(u){return this.filter(u).head()},cr.prototype.findLast=function(u){return this.reverse().find(u)},cr.prototype.invokeMap=ar(function(u,f){return typeof u=="function"?new cr(this):this.map(function(m){return Xl(m,u,f)})}),cr.prototype.reject=function(u){return this.filter(Ah(Mt(u)))},cr.prototype.slice=function(u,f){u=tr(u);var m=this;return m.__filtered__&&(u>0||f<0)?new cr(m):(u<0?m=m.takeRight(-u):u&&(m=m.drop(u)),f!==t&&(f=tr(f),m=f<0?m.dropRight(-f):m.take(f-u)),m)},cr.prototype.takeRightWhile=function(u){return this.reverse().takeWhile(u).reverse()},cr.prototype.toArray=function(){return this.take(Ee)},ia(cr.prototype,function(u,f){var m=/^(?:filter|find|map|reject)|While$/.test(f),C=/^(?:head|last)$/.test(f),O=U[C?"take"+(f=="last"?"Right":""):f],W=C||/^find/.test(f);O&&(U.prototype[f]=function(){var ee=this.__wrapped__,le=C?[1]:arguments,ye=ee instanceof cr,De=le[0],Ne=ye||Yt(ee),qe=function(gr){var Qn=O.apply(U,ae([gr],le));return C&&nt?Qn[0]:Qn};Ne&&m&&typeof De=="function"&&De.length!=1&&(ye=Ne=!1);var nt=this.__chain__,Tt=!!this.__actions__.length,Lt=W&&!nt,nr=ye&&!Tt;if(!W&&Ne){ee=nr?ee:new cr(this);var Ft=u.apply(ee,le);return Ft.__actions__.push({func:kh,args:[qe],thisArg:t}),new as(Ft,nt)}return Lt&&nr?u.apply(this,le):(Ft=this.thru(qe),Lt?C?Ft.value()[0]:Ft.value():Ft)})}),S(["pop","push","shift","sort","splice","unshift"],function(u){var f=Qf[u],m=/^(?:push|sort|unshift)$/.test(u)?"tap":"thru",C=/^(?:pop|shift)$/.test(u);U.prototype[u]=function(){var O=arguments;if(C&&!this.__chain__){var W=this.value();return f.apply(Yt(W)?W:[],O)}return this[m](function(ee){return f.apply(Yt(ee)?ee:[],O)})}}),ia(cr.prototype,function(u,f){var m=U[f];if(m){var C=m.name+"";$r.call(Sc,C)||(Sc[C]=[]),Sc[C].push({name:f,func:m})}}),Sc[_h(t,A).name]=[{name:"wrapper",func:t}],cr.prototype.clone=kU,cr.prototype.reverse=RU,cr.prototype.value=IU,U.prototype.at=n3,U.prototype.chain=i3,U.prototype.commit=s3,U.prototype.next=a3,U.prototype.plant=u3,U.prototype.reverse=c3,U.prototype.toJSON=U.prototype.valueOf=U.prototype.value=l3,U.prototype.first=U.prototype.head,Hl&&(U.prototype[Hl]=o3),U},yc=sU();Ai?((Ai.exports=yc)._=yc,To._=yc):$t._=yc}).call(Ed)})(ai,ai.exports);function rA(r,e){var t=typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=Tve(r))||e){t&&(r=t);var n=0,i=function(){};return{s:i,n:function(){return n>=r.length?{done:!0}:{done:!1,value:r[n++]}},e:function(l){throw l},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
385
385
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,a=!1,c;return{s:function(){t=t.call(r)},n:function(){var l=t.next();return s=l.done,l},e:function(l){a=!0,c=l},f:function(){try{!s&&t.return!=null&&t.return()}finally{if(a)throw c}}}}function Tve(r,e){if(r){if(typeof r=="string")return nA(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return nA(r,e)}}function nA(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}function iA(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function Cd(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?iA(Object(t),!0).forEach(function(n){fr.default(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):iA(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function F2(r){var e=Eve();return function(){var n=mn.default(r),i;if(e){var s=mn.default(this).constructor;i=Reflect.construct(n,arguments,s)}else i=n.apply(this,arguments);return cu.default(this,i)}}function Eve(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var _w=function(r){ki.default(t,r);var e=F2(t);function t(n,i,s){var a;hr.default(this,t),a=e.call(this,n,s);var c=function(l,d){return typeof d.ttl=="number"?{ttl:d.ttl}:l};return a.updateMergingQueue=new N2(c),a.cache=new $T,a.descriptor=i,a.descriptor.date_updated=new Date(a.descriptor.date_updated),a}return pr.default(t,[{key:"uri",get:function(){return this.descriptor.url}},{key:"revision",get:function(){return this.descriptor.revision}},{key:"lastEventId",get:function(){return this.descriptor.last_event_id}},{key:"links",get:function(){return this.descriptor.links}},{key:"dateExpires",get:function(){return this.descriptor.date_expires}},{key:"type",get:function(){return"list"}},{key:"indexName",get:function(){}},{key:"queryString",get:function(){}},{key:"sid",get:function(){return this.descriptor.sid}},{key:"uniqueName",get:function(){return this.descriptor.unique_name||null}},{key:"dateUpdated",get:function(){return this.descriptor.date_updated}},{key:"_addOrUpdateItemOnServer",value:function(){var n=ze.default(fe.default.mark(function s(a,c,o,l){var d,h;return fe.default.wrap(function(y){for(;;)switch(y.prev=y.next){case 0:return d={data:c},l!==void 0&&(d.ttl=l),y.next=4,this.services.network.post(a,d,o);case 4:return h=y.sent,h.body.data=c,h.body.date_updated=new Date(h.body.date_updated),y.abrupt("return",h.body);case 8:case"end":return y.stop()}},s,this)}));function i(s,a,c,o){return n.apply(this,arguments)}return i}()},{key:"push",value:function(){var n=ze.default(fe.default.mark(function s(a,c){var o,l,d;return fe.default.wrap(function(p){for(;;)switch(p.prev=p.next){case 0:return o=(c||{}).ttl,p.next=3,this._addOrUpdateItemOnServer(this.links.items,a,void 0,o);case 3:return l=p.sent,d=Number(l.index),this._handleItemMutated(d,l.url,l.last_event_id,l.revision,a,l.date_updated,l.date_expires,!0,!1),p.abrupt("return",this.cache.getValue(d));case 7:case"end":return p.stop()}},s,this)}));function i(s,a){return n.apply(this,arguments)}return i}()},{key:"set",value:function(){var n=ze.default(fe.default.mark(function s(a,c,o){var l=this,d;return fe.default.wrap(function(p){for(;;)switch(p.prev=p.next){case 0:return d=o||{},p.abrupt("return",this.updateMergingQueue.squashAndAdd(a,d,function(y){return l._updateItemUnconditionally(a,c,y.ttl)}));case 2:case"end":return p.stop()}},s,this)}));function i(s,a,c){return n.apply(this,arguments)}return i}()},{key:"_updateItemUnconditionally",value:function(){var n=ze.default(fe.default.mark(function s(a,c,o){var l,d;return fe.default.wrap(function(p){for(;;)switch(p.prev=p.next){case 0:return p.next=2,this.get(a);case 2:return l=p.sent,p.next=5,this._addOrUpdateItemOnServer(l.url,c,void 0,o);case 5:return d=p.sent,this._handleItemMutated(a,d.url,d.last_event_id,d.revision,d.data,d.date_updated,d.date_expires,!1,!1),p.abrupt("return",this.cache.getValue(a));case 8:case"end":return p.stop()}},s,this)}));function i(s,a,c){return n.apply(this,arguments)}return i}()},{key:"_updateItemWithIfMatch",value:function(){var n=ze.default(fe.default.mark(function s(a,c,o){var l,d,h,p;return fe.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this.get(a);case 2:if(l=w.sent,d=c(zs(l.data)),!d){w.next=25;break}return h=l.revision,w.prev=6,w.next=9,this._addOrUpdateItemOnServer(l.url,d,h,o);case 9:return p=w.sent,this._handleItemMutated(a,p.url,p.last_event_id,p.revision,p.data,p.date_updated,p.date_expires,!1,!1),w.abrupt("return",this.cache.getValue(a));case 14:if(w.prev=14,w.t0=w.catch(6),w.t0.status!==412){w.next=22;break}return w.next=19,this._getItemFromServer(a);case 19:return w.abrupt("return",this._updateItemWithIfMatch(a,c,o));case 22:throw w.t0;case 23:w.next=26;break;case 25:return w.abrupt("return",l);case 26:case"end":return w.stop()}},s,this,[[6,14]])}));function i(s,a,c){return n.apply(this,arguments)}return i}()},{key:"mutate",value:function(){var n=ze.default(fe.default.mark(function s(a,c,o){var l=this,d;return fe.default.wrap(function(p){for(;;)switch(p.prev=p.next){case 0:return d=o||{},p.abrupt("return",this.updateMergingQueue.add(a,d,function(y){return l._updateItemWithIfMatch(a,c,y.ttl)}));case 2:case"end":return p.stop()}},s,this)}));function i(s,a,c){return n.apply(this,arguments)}return i}()},{key:"update",value:function(){var n=ze.default(fe.default.mark(function s(a,c,o){return fe.default.wrap(function(d){for(;;)switch(d.prev=d.next){case 0:return d.abrupt("return",this.mutate(a,function(h){return Object.assign(h,c)},o));case 1:case"end":return d.stop()}},s,this)}));function i(s,a,c){return n.apply(this,arguments)}return i}()},{key:"remove",value:function(){var n=ze.default(fe.default.mark(function s(a){var c,o,l;return fe.default.wrap(function(h){for(;;)switch(h.prev=h.next){case 0:return h.next=2,this.get(a);case 2:return c=h.sent,o=zs(c.data),h.next=6,this.services.network.delete(c.url);case 6:l=h.sent,this._handleItemRemoved(a,l.body.last_event_id,o,new Date(l.body.date_updated),!1);case 8:case"end":return h.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"get",value:function(){var n=ze.default(fe.default.mark(function s(a){var c;return fe.default.wrap(function(l){for(;;)switch(l.prev=l.next){case 0:if(c=this.cache.get(a),!c){l.next=3;break}return l.abrupt("return",c.value);case 3:return l.abrupt("return",this._getItemFromServer(a));case 4:case"end":return l.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"_getItemFromServer",value:function(){var n=ze.default(fe.default.mark(function s(a){var c;return fe.default.wrap(function(l){for(;;)switch(l.prev=l.next){case 0:return l.next=2,this._queryItemsFromServer({index:a});case 2:if(c=l.sent,!(c.items.length<1)){l.next=7;break}throw new Fi("No item with index ".concat(a," found"),404,54151);case 7:return l.abrupt("return",c.items[0]);case 8:case"end":return l.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"queryItems",value:function(){var n=ze.default(fe.default.mark(function s(a){var c,o,l,d,h,p,y,w,k,P,A,B,L,$,F,G,K,D,he,X,ve,Q,Oe,He,Ze,Xe,Re,Je,Ke;return fe.default.wrap(function(Ee){for(;;)switch(Ee.prev=Ee.next){case 0:if(!a.index){Ee.next=5;break}if(k=this.cache.get(a.index),!k){Ee.next=4;break}return Ee.abrupt("return",this.makePaginator(k.isValid?[k.value]:[],a,!1,!1));case 4:return Ee.abrupt("return",this._querySingleItemFromServer(a.index));case 5:P=!!a.nextPageItemId||!!a.prevPageItemId,A=Cd({},a),P&&(a.from=(B=(L=a.nextPageItemId)!==null&&L!==void 0?L:a.prevPageItemId)!==null&&B!==void 0?B:a.from),$=!!a.prevPageItemId,F=a.order==="desc"?$?this.cache.getIterator((c=(o=a.prevPageItemId)!==null&&o!==void 0?o:a.from)!==null&&c!==void 0?c:null):this.cache.getReverseIterator((l=(d=a.nextPageItemId)!==null&&d!==void 0?d:a.from)!==null&&l!==void 0?l:null):$?this.cache.getReverseIterator((h=(p=a.prevPageItemId)!==null&&p!==void 0?p:a.from)!==null&&h!==void 0?h:null):this.cache.getIterator((y=(w=a.nextPageItemId)!==null&&w!==void 0?w:a.from)!==null&&y!==void 0?y:null),G=[],K=P?a.limit+1:a.limit,D=rA(F),Ee.prev=13,D.s();case 15:if((he=D.n()).done){Ee.next=25;break}if(X=he.value,!(P&&X.value.index==a.from)){Ee.next=19;break}return Ee.abrupt("continue",23);case 19:if(G.push(X.value),!(G.length>=a.limit)){Ee.next=23;break}return $&&ai.exports.reverse(G),Ee.abrupt("return",this.makePaginator(G,a,this._prevPageAllowed(G,a.order),this._nextPageAllowed(G,a.order)));case 23:Ee.next=15;break;case 25:Ee.next=30;break;case 27:Ee.prev=27,Ee.t0=Ee.catch(13),D.e(Ee.t0);case 30:return Ee.prev=30,D.f(),Ee.finish(30);case 33:if(G.length>0&&(a.from=ai.exports.last(G).index),ve=Math.max(K-G.length,10),$&&(a.order=a.order==="desc"?"asc":"desc"),Q=a.from!==(A.order==="desc"?$?this.cache.collectionEnd:this.cache.collectionBegin:$?this.cache.collectionBegin:this.cache.collectionEnd),!Q){Ee.next=66;break}return Ee.next=40,this._queryItemsFromServer(Cd(Cd({},a),{},{limit:ve}));case 40:Oe=Ee.sent,He=Oe.items,A.order==="desc"?(Ze=!Oe.hasNextPage,Xe=!Oe.hasPrevPage):(Ze=!Oe.hasPrevPage,Xe=!Oe.hasNextPage),this.cache.populate(He,Ze,Xe),Re=rA(He),Ee.prev=45,Re.s();case 47:if((Je=Re.n()).done){Ee.next=56;break}if(Ke=Je.value,!((G.length>0||P)&&Ke.index==a.from)){Ee.next=51;break}return Ee.abrupt("continue",54);case 51:if($?G.unshift(Ke):G.push(Ke),!(G.length>=a.limit)){Ee.next=54;break}return Ee.abrupt("break",56);case 54:Ee.next=47;break;case 56:Ee.next=61;break;case 58:Ee.prev=58,Ee.t1=Ee.catch(45),Re.e(Ee.t1);case 61:return Ee.prev=61,Re.f(),Ee.finish(61);case 64:Ee.next=67;break;case 66:$&&ai.exports.reverse(G);case 67:return Ee.abrupt("return",this.makePaginator(G,A,this._prevPageAllowed(G,A.order),this._nextPageAllowed(G,A.order)));case 68:case"end":return Ee.stop()}},s,this,[[13,27,30,33],[45,58,61,64]])}));function i(s){return n.apply(this,arguments)}return i}()},{key:"_prevPageAllowed",value:function(i,s){return i.length>0&&ai.exports.head(i).index!==(s==="desc"?this.cache.collectionEnd:this.cache.collectionBegin)}},{key:"_nextPageAllowed",value:function(i,s){return i.length>0&&ai.exports.last(i).index!==(s==="desc"?this.cache.collectionBegin:this.cache.collectionEnd)}},{key:"makePaginator",value:function(i,s,a,c){var o=this;s.nextPageItemId=s.prevPageItemId=null;var l=a&&this._prevPageAllowed(i,s.order),d=c&&this._nextPageAllowed(i,s.order);return new OT(i,function(h){return o.queryItems(Cd(Cd({},s),h))},l?ai.exports.head(i).index:null,d?ai.exports.last(i).index:null)}},{key:"_querySingleItemFromServer",value:function(){var n=ze.default(fe.default.mark(function s(a){var c;return fe.default.wrap(function(l){for(;;)switch(l.prev=l.next){case 0:return l.next=2,this._queryItemsFromServer({index:a});case 2:return c=l.sent,c.items.length===0&&this.cache.exists(a)&&this.cache.delete(a,null),l.abrupt("return",c);case 5:case"end":return l.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"_queryItemsFromServer",value:function(){var n=ze.default(fe.default.mark(function s(a){var c,o,l=this,d,h,p,y;return fe.default.wrap(function(k){for(;;)switch(k.prev=k.next){case 0:return d=new wl(this.links.items).queryParam("HideExpired",!0).queryParam("Index",a.index).queryParam("PageToken",a.pageToken).queryParam("From",a.from).queryParam("PageSize",a.limit).queryParam("Order",a.order).build(),k.next=3,this.services.network.get(d);case 3:return h=k.sent,p=((c=(o=h.body)===null||o===void 0?void 0:o.items)!==null&&c!==void 0?c:[]).map(function(P){P.date_updated=new Date(P.date_updated);var A=l.cache.get(P.index),B=A&&A.value;if(B)l._handleItemMutated(P.index,P.url,P.last_event_id,P.revision,P.data,P.date_updated,P.date_expires,!1,!0);else{var L=new yw({index:P.index,url:P.url,lastEventId:P.last_event_id,revision:P.revision,data:P.data,dateUpdated:P.date_updated,dateExpires:P.date_expires});l.cache.store(P.index,L,P.last_event_id)}return l.cache.getValue(P.index)}),y=h.body.meta,k.abrupt("return",this.makePaginator(p,a,!!y.previous_token,!!y.next_token));case 7:case"end":return k.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"getItems",value:function(){var n=ze.default(fe.default.mark(function s(a){return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:return a=a||{},M2(a.pageSize),a.limit=a.pageSize||a.limit||50,a.order=a.order||"asc",o.abrupt("return",this.queryItems(a));case 5:case"end":return o.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"getContext",value:function(){var n=ze.default(fe.default.mark(function s(){var a;return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:if(this.context){o.next=5;break}return o.next=3,this.services.network.get(this.links.context);case 3:a=o.sent,this._updateContextIfRequired(a.body.data,a.body.last_event_id);case 5:return o.abrupt("return",this.context);case 6:case"end":return o.stop()}},s,this)}));function i(){return n.apply(this,arguments)}return i}()},{key:"setTtl",value:function(){var n=ze.default(fe.default.mark(function s(a){var c,o;return fe.default.wrap(function(d){for(;;)switch(d.prev=d.next){case 0:return d.prev=0,c={ttl:a},d.next=4,this.services.network.post(this.uri,c);case 4:o=d.sent,this.descriptor.date_expires=o.body.date_expires,d.next=12;break;case 8:throw d.prev=8,d.t0=d.catch(0),d.t0.status===404&&this.onRemoved(!1),d.t0;case 12:case"end":return d.stop()}},s,this,[[0,8]])}));function i(s){return n.apply(this,arguments)}return i}()},{key:"setItemTtl",value:function(){var n=ze.default(fe.default.mark(function s(a,c){var o,l,d;return fe.default.wrap(function(p){for(;;)switch(p.prev=p.next){case 0:return p.next=2,this.get(a);case 2:return o=p.sent,l={ttl:c},p.next=6,this.services.network.post(o.url,l);case 6:d=p.sent,o.updateDateExpires(d.body.date_expires);case 8:case"end":return p.stop()}},s,this)}));function i(s,a){return n.apply(this,arguments)}return i}()},{key:"removeList",value:function(){var n=ze.default(fe.default.mark(function s(){return fe.default.wrap(function(c){for(;;)switch(c.prev=c.next){case 0:return c.next=2,this.services.network.delete(this.uri);case 2:this.onRemoved(!0);case 3:case"end":return c.stop()}},s,this)}));function i(){return n.apply(this,arguments)}return i}()},{key:"onRemoved",value:function(i){this._unsubscribe(),this.removalHandler(this.type,this.sid,this.uniqueName),this.broadcastEventToListeners("removed",{isLocal:i})}},{key:"shouldIgnoreEvent",value:function(i,s){return this.cache.isKnown(i,s)}},{key:"_update",value:function(i,s){var a=Number(i.item_index);switch(i.date_created=new Date(i.date_created),i.type){case"list_item_added":case"list_item_updated":this._handleItemMutated(a,i.item_url,i.id,i.item_revision,i.item_data,i.date_created,i.date_expires,i.type==="list_item_added",!0);break;case"list_item_removed":this._handleItemRemoved(a,i.id,i.item_data,i.date_created,!0);break;case"list_context_updated":this._handleContextUpdate(i.context_data,i.id,i.date_created);break;case"list_removed":this.onRemoved(!1);break}s&&this._advanceLastEventId(i.id,i.list_revision)}},{key:"_advanceLastEventId",value:function(i,s){this.lastEventId<i&&(this.descriptor.last_event_id=i,s&&(this.descriptor.revision=s))}},{key:"_updateRootDateUpdated",value:function(i){(!this.descriptor.date_updated||i.getTime()>this.descriptor.date_updated.getTime())&&(this.descriptor.date_updated=i,this.services.storage.update(this.type,this.sid,this.uniqueName,{date_updated:i}))}},{key:"_handleItemMutated",value:function(i,s,a,c,o,l,d,h,p){if(this.shouldIgnoreEvent(i,a)){_r.trace("Item ".concat(i," update skipped, current: ").concat(this.lastEventId,", remote: ").concat(a));return}this._updateRootDateUpdated(l);var y=this.cache.getValue(i);if(!y){var w=new yw({index:i,url:s,lastEventId:a,revision:c,data:o,dateUpdated:l,dateExpires:d});this.cache.store(i,w,a),this.emitItemMutationEvent(w,p,h);return}var k=zs(y.data);y.update(a,c,o,l),this.cache.store(i,y,a),d!==void 0&&y.updateDateExpires(d),this.emitItemMutationEvent(y,p,!1,k)}},{key:"emitItemMutationEvent",value:function(i,s,a){var c=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null,o=a?"itemAdded":"itemUpdated",l={item:i,isLocal:!s};a||(l.previousItemData=c),this.broadcastEventToListeners(o,l)}},{key:"_handleItemRemoved",value:function(i,s,a,c,o){this._updateRootDateUpdated(c),this.cache.delete(i,s),this.broadcastEventToListeners("itemRemoved",{index:i,isLocal:!o,previousItemData:a})}},{key:"_handleContextUpdate",value:function(i,s,a){this._updateRootDateUpdated(a),this._updateContextIfRequired(i,s)&&this.broadcastEventToListeners("contextUpdated",{context:i,isLocal:!1})}},{key:"_updateContextIfRequired",value:function(i,s){return!this.contextEventId||s>this.contextEventId?(this.context=i,this.contextEventId=s,!0):(_r.trace("Context update skipped, current:",this.lastEventId,", remote:",s),!1)}}],[{key:"type",get:function(){return"list"}}]),t}(Kf),En=function(r){ki.default(t,r);var e=F2(t);function t(n){var i;return hr.default(this,t),i=e.call(this),i.syncListImpl=n,i.syncListImpl.attach(ma.default(i)),i}return pr.default(t,[{key:"uri",get:function(){return this.syncListImpl.uri}},{key:"revision",get:function(){return this.syncListImpl.revision}},{key:"lastEventId",get:function(){return this.syncListImpl.lastEventId}},{key:"links",get:function(){return this.syncListImpl.links}},{key:"dateExpires",get:function(){return this.syncListImpl.dateExpires}},{key:"type",get:function(){return _w.type}},{key:"sid",get:function(){return this.syncListImpl.sid}},{key:"uniqueName",get:function(){return this.syncListImpl.uniqueName}},{key:"dateUpdated",get:function(){return this.syncListImpl.dateUpdated}},{key:"push",value:function(){var n=ze.default(fe.default.mark(function s(a,c){return fe.default.wrap(function(l){for(;;)switch(l.prev=l.next){case 0:return this.ensureNotClosed(),l.abrupt("return",this.syncListImpl.push(a,c));case 2:case"end":return l.stop()}},s,this)}));function i(s,a){return n.apply(this,arguments)}return i}()},{key:"set",value:function(){var n=ze.default(fe.default.mark(function s(a,c,o){return fe.default.wrap(function(d){for(;;)switch(d.prev=d.next){case 0:return this.ensureNotClosed(),d.abrupt("return",this.syncListImpl.set(a,c,o));case 2:case"end":return d.stop()}},s,this)}));function i(s,a,c){return n.apply(this,arguments)}return i}()},{key:"mutate",value:function(){var n=ze.default(fe.default.mark(function s(a,c,o){return fe.default.wrap(function(d){for(;;)switch(d.prev=d.next){case 0:return this.ensureNotClosed(),d.abrupt("return",this.syncListImpl.mutate(a,c,o));case 2:case"end":return d.stop()}},s,this)}));function i(s,a,c){return n.apply(this,arguments)}return i}()},{key:"update",value:function(){var n=ze.default(fe.default.mark(function s(a,c,o){return fe.default.wrap(function(d){for(;;)switch(d.prev=d.next){case 0:return this.ensureNotClosed(),d.abrupt("return",this.syncListImpl.update(a,c,o));case 2:case"end":return d.stop()}},s,this)}));function i(s,a,c){return n.apply(this,arguments)}return i}()},{key:"remove",value:function(){var n=ze.default(fe.default.mark(function s(a){return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:return this.ensureNotClosed(),o.abrupt("return",this.syncListImpl.remove(a));case 2:case"end":return o.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"get",value:function(){var n=ze.default(fe.default.mark(function s(a){return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:return this.ensureNotClosed(),o.abrupt("return",this.syncListImpl.get(a));case 2:case"end":return o.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"getContext",value:function(){var n=ze.default(fe.default.mark(function s(){return fe.default.wrap(function(c){for(;;)switch(c.prev=c.next){case 0:return this.ensureNotClosed(),c.abrupt("return",this.syncListImpl.getContext());case 2:case"end":return c.stop()}},s,this)}));function i(){return n.apply(this,arguments)}return i}()},{key:"getItems",value:function(){var n=ze.default(fe.default.mark(function s(a){return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:return this.ensureNotClosed(),o.abrupt("return",this.syncListImpl.getItems(a));case 2:case"end":return o.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"setTtl",value:function(){var n=ze.default(fe.default.mark(function s(a){return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:return this.ensureNotClosed(),o.abrupt("return",this.syncListImpl.setTtl(a));case 2:case"end":return o.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"setItemTtl",value:function(){var n=ze.default(fe.default.mark(function s(a,c){return fe.default.wrap(function(l){for(;;)switch(l.prev=l.next){case 0:return this.ensureNotClosed(),l.abrupt("return",this.syncListImpl.setItemTtl(a,c));case 2:case"end":return l.stop()}},s,this)}));function i(s,a){return n.apply(this,arguments)}return i}()},{key:"removeList",value:function(){var n=ze.default(fe.default.mark(function s(){return fe.default.wrap(function(c){for(;;)switch(c.prev=c.next){case 0:return this.ensureNotClosed(),c.abrupt("return",this.syncListImpl.removeList());case 2:case"end":return c.stop()}},s,this)}));function i(){return n.apply(this,arguments)}return i}()},{key:"close",value:function(){zf.default(mn.default(t.prototype),"close",this).call(this),this.syncListImpl.detach(this.listenerUuid)}}],[{key:"type",get:function(){return _w.type}}]),t}(Jf);fr.default(En,"itemAdded","itemAdded");fr.default(En,"itemUpdated","itemUpdated");fr.default(En,"itemRemoved","itemRemoved");fr.default(En,"removed","removed");yr([Fe.validateTypesAsync(Fe.pureObject,["undefined",Fe.objectSchema("item metadata",{ttl:[Fe.nonNegativeInteger,"undefined"]})]),We("design:type",Function),We("design:paramtypes",[Object,Object]),We("design:returntype",Promise)],En.prototype,"push",null);yr([Fe.validateTypesAsync(Fe.nonNegativeInteger,Fe.pureObject,["undefined",Fe.objectSchema("item metadata",{ttl:[Fe.nonNegativeInteger,"undefined"]})]),We("design:type",Function),We("design:paramtypes",[Number,Object,Object]),We("design:returntype",Promise)],En.prototype,"set",null);yr([Fe.validateTypesAsync(Fe.nonNegativeInteger,"function",["undefined",Fe.objectSchema("item metadata",{ttl:[Fe.nonNegativeInteger,"undefined"]})]),We("design:type",Function),We("design:paramtypes",[Number,Function,Object]),We("design:returntype",Promise)],En.prototype,"mutate",null);yr([Fe.validateTypesAsync(Fe.nonNegativeInteger,Fe.pureObject,["undefined",Fe.objectSchema("item metadata",{ttl:[Fe.nonNegativeInteger,"undefined"]})]),We("design:type",Function),We("design:paramtypes",[Number,Object,Object]),We("design:returntype",Promise)],En.prototype,"update",null);yr([Fe.validateTypesAsync(Fe.nonNegativeInteger),We("design:type",Function),We("design:paramtypes",[Number]),We("design:returntype",Promise)],En.prototype,"remove",null);yr([Fe.validateTypesAsync(Fe.nonNegativeInteger),We("design:type",Function),We("design:paramtypes",[Number]),We("design:returntype",Promise)],En.prototype,"get",null);yr([Fe.validateTypesAsync(["undefined",Fe.objectSchema("query options",{from:[Fe.nonNegativeInteger,"undefined"],pageSize:[Fe.custom(function(r){return[AT(r),"a positive integer"]}),"undefined"],order:[Fe.custom(function(r){return[r==="asc"||r==="desc","either 'asc' or 'desc'"]}),"undefined"]})]),We("design:type",Function),We("design:paramtypes",[Object]),We("design:returntype",Promise)],En.prototype,"getItems",null);yr([Fe.validateTypesAsync(Fe.nonNegativeInteger),We("design:type",Function),We("design:paramtypes",[Number]),We("design:returntype",Promise)],En.prototype,"setTtl",null);yr([Fe.validateTypesAsync(Fe.nonNegativeInteger,Fe.nonNegativeInteger),We("design:type",Function),We("design:paramtypes",[Number,Number]),We("design:returntype",Promise)],En.prototype,"setItemTtl",null);var Fd=function(){function r(e){hr.default(this,r),this.descriptor=e}return pr.default(r,[{key:"uri",get:function(){return this.descriptor.url}},{key:"revision",get:function(){return this.descriptor.revision}},{key:"lastEventId",get:function(){return this.descriptor.last_event_id}},{key:"dateExpires",get:function(){return this.descriptor.date_expires}},{key:"key",get:function(){return this.descriptor.key}},{key:"data",get:function(){return this.descriptor.data}},{key:"dateUpdated",get:function(){return this.descriptor.date_updated}},{key:"cacheKey",get:function(){return this.key}},{key:"update",value:function(t,n,i,s){return this.descriptor.last_event_id=t,this.descriptor.revision=n,this.descriptor.data=i,this.descriptor.date_updated=s,this}},{key:"updateDateExpires",value:function(t){this.descriptor.date_expires=t}}]),r}();function sA(r,e){var t=typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=Cve(r))||e){t&&(r=t);var n=0,i=function(){};return{s:i,n:function(){return n>=r.length?{done:!0}:{done:!1,value:r[n++]}},e:function(l){throw l},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
386
386
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,a=!1,c;return{s:function(){t=t.call(r)},n:function(){var l=t.next();return s=l.done,l},e:function(l){a=!0,c=l},f:function(){try{!s&&t.return!=null&&t.return()}finally{if(a)throw c}}}}function Cve(r,e){if(r){if(typeof r=="string")return aA(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return aA(r,e)}}function aA(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}function oA(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function kd(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?oA(Object(t),!0).forEach(function(n){fr.default(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):oA(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function U2(r){var e=kve();return function(){var n=mn.default(r),i;if(e){var s=mn.default(this).constructor;i=Reflect.construct(n,arguments,s)}else i=n.apply(this,arguments);return cu.default(this,i)}}function kve(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var bw=function(r){ki.default(t,r);var e=U2(t);function t(n,i,s){var a;hr.default(this,t),a=e.call(this,n,s);var c=function(l,d){return typeof d.ttl=="number"?{ttl:d.ttl}:l};return a.updateMergingQueue=new N2(c),a.cache=new $T,a.descriptor=i,a.descriptor.date_updated=new Date(a.descriptor.date_updated),i.items&&i.items.forEach(function(o){o.date_updated=new Date(o.date_updated),a.cache.store(o.key,new Fd(o),o.last_event_id)}),a}return pr.default(t,[{key:"uri",get:function(){return this.descriptor.url}},{key:"links",get:function(){return this.descriptor.links}},{key:"revision",get:function(){return this.descriptor.revision}},{key:"lastEventId",get:function(){return this.descriptor.last_event_id}},{key:"dateExpires",get:function(){return this.descriptor.date_expires}},{key:"type",get:function(){return"map"}},{key:"indexName",get:function(){}},{key:"queryString",get:function(){}},{key:"sid",get:function(){return this.descriptor.sid}},{key:"uniqueName",get:function(){return this.descriptor.unique_name||null}},{key:"dateUpdated",get:function(){return this.descriptor.date_updated}},{key:"set",value:function(){var n=ze.default(fe.default.mark(function s(a,c,o){var l=this,d;return fe.default.wrap(function(p){for(;;)switch(p.prev=p.next){case 0:return d=o||{},p.abrupt("return",this.updateMergingQueue.squashAndAdd(a,d,function(y){return l._putItemUnconditionally(a,c,y.ttl)}));case 2:case"end":return p.stop()}},s,this)}));function i(s,a,c){return n.apply(this,arguments)}return i}()},{key:"get",value:function(){var n=ze.default(fe.default.mark(function s(a){return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:if(a!=null){o.next=2;break}throw new Fi("SyncMapItem key may not be empty",400,54209);case 2:if(!this.cache.has(a)){o.next=6;break}return o.abrupt("return",this.cache.getValue(a));case 6:return o.abrupt("return",this._getItemFromServer(a));case 7:case"end":return o.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"_getItemFromServer",value:function(){var n=ze.default(fe.default.mark(function s(a){var c;return fe.default.wrap(function(l){for(;;)switch(l.prev=l.next){case 0:return l.next=2,this._queryItemsFromServer({key:a});case 2:if(c=l.sent,!(c.items.length<1)){l.next=7;break}throw new Fi("The specified Map Item does not exist",404,54201);case 7:return l.abrupt("return",c.items[0]);case 8:case"end":return l.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"mutate",value:function(){var n=ze.default(fe.default.mark(function s(a,c,o){var l=this,d;return fe.default.wrap(function(p){for(;;)switch(p.prev=p.next){case 0:return d=o||{},p.abrupt("return",this.updateMergingQueue.add(a,d,function(y){return l._putItemWithIfMatch(a,c,y.ttl)}));case 2:case"end":return p.stop()}},s,this)}));function i(s,a,c){return n.apply(this,arguments)}return i}()},{key:"update",value:function(){var n=ze.default(fe.default.mark(function s(a,c,o){return fe.default.wrap(function(d){for(;;)switch(d.prev=d.next){case 0:return d.abrupt("return",this.mutate(a,function(h){return Object.assign(h,c)},o));case 1:case"end":return d.stop()}},s,this)}));function i(s,a,c){return n.apply(this,arguments)}return i}()},{key:"_putItemUnconditionally",value:function(){var n=ze.default(fe.default.mark(function s(a,c,o){var l,d;return fe.default.wrap(function(p){for(;;)switch(p.prev=p.next){case 0:return p.next=2,this._putItemToServer(a,c,void 0,o);case 2:return l=p.sent,d=l.item,this._handleItemMutated(d.key,d.url,d.last_event_id,d.revision,d.data,d.date_updated,d.date_expires,l.added,!1),p.abrupt("return",this.cache.getValue(d.key));case 6:case"end":return p.stop()}},s,this)}));function i(s,a,c){return n.apply(this,arguments)}return i}()},{key:"_putItemWithIfMatch",value:function(){var n=ze.default(fe.default.mark(function s(a,c,o){var l,d,h,p,y;return fe.default.wrap(function(k){for(;;)switch(k.prev=k.next){case 0:return k.next=2,this.get(a).catch(function(P){if(P.status===404)return new Fd({key:a,data:{},last_event_id:-1,revision:"-1",url:null,date_updated:null,date_expires:null});throw P});case 2:if(l=k.sent,d=c(zs(l.data)),!d){k.next=26;break}return h=l.revision,k.prev=6,k.next=9,this._putItemToServer(a,d,h,o);case 9:return p=k.sent,y=p.item,this._handleItemMutated(y.key,y.url,y.last_event_id,y.revision,y.data,y.date_updated,y.date_expires,p.added,!1),k.abrupt("return",this.cache.getValue(y.key));case 15:if(k.prev=15,k.t0=k.catch(6),k.t0.status!==412){k.next=23;break}return k.next=20,this._getItemFromServer(a);case 20:return k.abrupt("return",this._putItemWithIfMatch(a,c,o));case 23:throw k.t0;case 24:k.next=27;break;case 26:return k.abrupt("return",l);case 27:case"end":return k.stop()}},s,this,[[6,15]])}));function i(s,a,c){return n.apply(this,arguments)}return i}()},{key:"_putItemToServer",value:function(){var n=ze.default(fe.default.mark(function s(a,c,o,l){var d,h,p,y,w;return fe.default.wrap(function(P){for(;;)switch(P.prev=P.next){case 0:return d=new wl(this.links.items).pathSegment(a).build(),h={data:c},l!==void 0&&(h.ttl=l),P.prev=3,P.next=6,this.services.network.put(d,h,o);case 6:return p=P.sent,y=p.body,y.data=c,y.date_updated=new Date(y.date_updated),w=p.status.code===201,P.abrupt("return",{added:w,item:y});case 14:throw P.prev=14,P.t0=P.catch(3),P.t0.status===404&&this.onRemoved(!1),P.t0;case 18:case"end":return P.stop()}},s,this,[[3,14]])}));function i(s,a,c,o){return n.apply(this,arguments)}return i}()},{key:"remove",value:function(){var n=ze.default(fe.default.mark(function s(a){var c,o,l;return fe.default.wrap(function(h){for(;;)switch(h.prev=h.next){case 0:return h.next=2,this.get(a);case 2:return c=h.sent,o=zs(c.data),h.next=6,this.services.network.delete(c.uri);case 6:l=h.sent,this._handleItemRemoved(a,l.body.last_event_id,o,new Date(l.body.date_updated),!1);case 8:case"end":return h.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"queryItems",value:function(){var n=ze.default(fe.default.mark(function s(a){var c,o,l,d,h,p,y,w,k,P,A,B,L,$,F,G,K,D,he,X,ve,Q,Oe,He,Ze,Xe,Re,Je,Ke;return fe.default.wrap(function(Ee){for(;;)switch(Ee.prev=Ee.next){case 0:if(!a.key){Ee.next=5;break}if(k=this.cache.get(a.key),!k){Ee.next=4;break}return Ee.abrupt("return",this.makePaginator(k.isValid?[k.value]:[],a,!1,!1));case 4:return Ee.abrupt("return",this._querySingleItemFromServer(a.key));case 5:P=!!a.nextPageItemId||!!a.prevPageItemId,A=kd({},a),P&&(a.from=(B=(L=a.nextPageItemId)!==null&&L!==void 0?L:a.prevPageItemId)!==null&&B!==void 0?B:a.from),$=!!a.prevPageItemId,F=a.order==="desc"?$?this.cache.getIterator((c=(o=a.prevPageItemId)!==null&&o!==void 0?o:a.from)!==null&&c!==void 0?c:null):this.cache.getReverseIterator((l=(d=a.nextPageItemId)!==null&&d!==void 0?d:a.from)!==null&&l!==void 0?l:null):$?this.cache.getReverseIterator((h=(p=a.prevPageItemId)!==null&&p!==void 0?p:a.from)!==null&&h!==void 0?h:null):this.cache.getIterator((y=(w=a.nextPageItemId)!==null&&w!==void 0?w:a.from)!==null&&y!==void 0?y:null),G=[],K=P?a.limit+1:a.limit,D=sA(F),Ee.prev=13,D.s();case 15:if((he=D.n()).done){Ee.next=25;break}if(X=he.value,!(P&&X.value.key==a.from)){Ee.next=19;break}return Ee.abrupt("continue",23);case 19:if(G.push(X.value),!(G.length>=a.limit)){Ee.next=23;break}return $&&ai.exports.reverse(G),Ee.abrupt("return",this.makePaginator(G,a,this._prevPageAllowed(G,a.order),this._nextPageAllowed(G,a.order)));case 23:Ee.next=15;break;case 25:Ee.next=30;break;case 27:Ee.prev=27,Ee.t0=Ee.catch(13),D.e(Ee.t0);case 30:return Ee.prev=30,D.f(),Ee.finish(30);case 33:if(G.length>0&&(a.from=ai.exports.last(G).key),ve=Math.max(K-G.length,10),$&&(a.order=a.order==="desc"?"asc":"desc"),Q=a.from!==(A.order==="desc"?$?this.cache.collectionEnd:this.cache.collectionBegin:$?this.cache.collectionBegin:this.cache.collectionEnd),!Q){Ee.next=66;break}return Ee.next=40,this._queryItemsFromServer(kd(kd({},a),{},{limit:ve}));case 40:Oe=Ee.sent,He=Oe.items,A.order==="desc"?(Ze=!Oe.hasNextPage,Xe=!Oe.hasPrevPage):(Ze=!Oe.hasPrevPage,Xe=!Oe.hasNextPage),this.cache.populate(He,Ze,Xe),Re=sA(He),Ee.prev=45,Re.s();case 47:if((Je=Re.n()).done){Ee.next=56;break}if(Ke=Je.value,!((G.length>0||P)&&Ke.key==a.from)){Ee.next=51;break}return Ee.abrupt("continue",54);case 51:if($?G.unshift(Ke):G.push(Ke),!(G.length>=a.limit)){Ee.next=54;break}return Ee.abrupt("break",56);case 54:Ee.next=47;break;case 56:Ee.next=61;break;case 58:Ee.prev=58,Ee.t1=Ee.catch(45),Re.e(Ee.t1);case 61:return Ee.prev=61,Re.f(),Ee.finish(61);case 64:Ee.next=67;break;case 66:$&&ai.exports.reverse(G);case 67:return Ee.abrupt("return",this.makePaginator(G,A,this._prevPageAllowed(G,A.order),this._nextPageAllowed(G,A.order)));case 68:case"end":return Ee.stop()}},s,this,[[13,27,30,33],[45,58,61,64]])}));function i(s){return n.apply(this,arguments)}return i}()},{key:"_prevPageAllowed",value:function(i,s){return i.length>0&&ai.exports.head(i).key!==(s==="desc"?this.cache.collectionEnd:this.cache.collectionBegin)}},{key:"_nextPageAllowed",value:function(i,s){return i.length>0&&ai.exports.last(i).key!==(s==="desc"?this.cache.collectionBegin:this.cache.collectionEnd)}},{key:"makePaginator",value:function(i,s,a,c){var o=this;s.nextPageItemId=s.prevPageItemId=null;var l=a&&this._prevPageAllowed(i,s.order),d=c&&this._nextPageAllowed(i,s.order);return new OT(i,function(h){return o.queryItems(kd(kd({},s),h))},l?ai.exports.head(i).key:null,d?ai.exports.last(i).key:null)}},{key:"_querySingleItemFromServer",value:function(){var n=ze.default(fe.default.mark(function s(a){var c;return fe.default.wrap(function(l){for(;;)switch(l.prev=l.next){case 0:return l.next=2,this._queryItemsFromServer({key:a});case 2:return c=l.sent,c.items.length===0&&this.cache.exists(a)&&this.cache.delete(a,null),l.abrupt("return",c);case 5:case"end":return l.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"_queryItemsFromServer",value:function(){var n=ze.default(fe.default.mark(function s(a){var c,o,l=this,d,h,p,y;return fe.default.wrap(function(k){for(;;)switch(k.prev=k.next){case 0:return d=new wl(this.links.items).queryParam("HideExpired",!0).queryParam("Key",a.key).queryParam("PageToken",a.pageToken).queryParam("From",a.from).queryParam("PageSize",a.limit).queryParam("Order",a.order).build(),k.next=3,this.services.network.get(d);case 3:return h=k.sent,p=((c=(o=h.body)===null||o===void 0?void 0:o.items)!==null&&c!==void 0?c:[]).map(function(P){P.date_updated=new Date(P.date_updated);var A=l.cache.get(P.key),B=A&&A.value;if(B)l._handleItemMutated(P.key,P.url,P.last_event_id,P.revision,P.data,P.date_updated,P.date_expires,!1,!0);else{var L=new Fd({key:P.key,url:P.url,last_event_id:P.last_event_id,revision:P.revision,data:P.data,date_updated:P.date_updated,date_expires:P.date_expires});l.cache.store(P.key,L,P.last_event_id)}return l.cache.getValue(P.key)}),y=h.body.meta,k.abrupt("return",this.makePaginator(p,a,!!y.previous_token,!!y.next_token));case 7:case"end":return k.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"getItems",value:function(){var n=ze.default(fe.default.mark(function s(a){return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:return a=a||{},M2(a.pageSize),a.limit=a.pageSize||a.limit||50,a.order=a.order||"asc",o.abrupt("return",this.queryItems(a));case 5:case"end":return o.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"shouldIgnoreEvent",value:function(i,s){return this.cache.isKnown(i,s)}},{key:"_update",value:function(i,s){switch(i.date_created=new Date(i.date_created),i.type){case"map_item_added":case"map_item_updated":this._handleItemMutated(i.item_key,i.item_url,i.id,i.item_revision,i.item_data,i.date_created,i.date_expires,i.type==="map_item_added",!0);break;case"map_item_removed":this._handleItemRemoved(i.item_key,i.id,i.item_data,i.date_created,!0);break;case"map_removed":this.onRemoved(!1);break}s&&this._advanceLastEventId(i.id,i.map_revision)}},{key:"_advanceLastEventId",value:function(i,s){this.lastEventId<i&&(this.descriptor.last_event_id=i,s&&(this.descriptor.revision=s))}},{key:"_updateRootDateUpdated",value:function(i){(!this.descriptor.date_updated||i.getTime()>this.descriptor.date_updated.getTime())&&(this.descriptor.date_updated=i,this.services.storage.update(this.type,this.sid,this.uniqueName,{date_updated:i}))}},{key:"_handleItemMutated",value:function(i,s,a,c,o,l,d,h,p){if(this.shouldIgnoreEvent(i,a)){_r.trace("SyncMapItem ",i," update skipped, current:",this.lastEventId,", remote:",a);return}this._updateRootDateUpdated(l);var y=this.cache.getValue(i);if(!y){var w=new Fd({key:i,url:s,last_event_id:a,revision:c,data:o,date_updated:l,date_expires:d});this.cache.store(i,w,a),this.emitItemMutationEvent(w,p,h);return}var k=zs(y.data);y.update(a,c,o,l),this.cache.store(i,y,a),d!==void 0&&y.updateDateExpires(d),this.emitItemMutationEvent(y,p,!1,k)}},{key:"emitItemMutationEvent",value:function(i,s,a){var c=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null,o=a?"itemAdded":"itemUpdated",l={item:i,isLocal:!s};a||(l.previousItemData=c),this.broadcastEventToListeners(o,l)}},{key:"_handleItemRemoved",value:function(i,s,a,c,o){this._updateRootDateUpdated(c),this.cache.delete(i,s),this.broadcastEventToListeners("itemRemoved",{key:i,isLocal:!o,previousItemData:a})}},{key:"onRemoved",value:function(i){this._unsubscribe(),this.removalHandler(this.type,this.sid,this.uniqueName),this.broadcastEventToListeners("removed",{isLocal:i})}},{key:"setTtl",value:function(){var n=ze.default(fe.default.mark(function s(a){var c,o;return fe.default.wrap(function(d){for(;;)switch(d.prev=d.next){case 0:return d.prev=0,c={ttl:a},d.next=4,this.services.network.post(this.uri,c);case 4:o=d.sent,this.descriptor.date_expires=o.body.date_expires,d.next=12;break;case 8:throw d.prev=8,d.t0=d.catch(0),d.t0.status===404&&this.onRemoved(!1),d.t0;case 12:case"end":return d.stop()}},s,this,[[0,8]])}));function i(s){return n.apply(this,arguments)}return i}()},{key:"setItemTtl",value:function(){var n=ze.default(fe.default.mark(function s(a,c){var o,l,d;return fe.default.wrap(function(p){for(;;)switch(p.prev=p.next){case 0:return p.next=2,this.get(a);case 2:return o=p.sent,l={ttl:c},p.next=6,this.services.network.post(o.uri,l);case 6:d=p.sent,o.updateDateExpires(d.body.date_expires);case 8:case"end":return p.stop()}},s,this)}));function i(s,a){return n.apply(this,arguments)}return i}()},{key:"removeMap",value:function(){var n=ze.default(fe.default.mark(function s(){return fe.default.wrap(function(c){for(;;)switch(c.prev=c.next){case 0:return c.next=2,this.services.network.delete(this.uri);case 2:this.onRemoved(!0);case 3:case"end":return c.stop()}},s,this)}));function i(){return n.apply(this,arguments)}return i}()}],[{key:"type",get:function(){return"map"}}]),t}(Kf),On=function(r){ki.default(t,r);var e=U2(t);function t(n){var i;return hr.default(this,t),i=e.call(this),i.syncMapImpl=n,i.syncMapImpl.attach(ma.default(i)),i}return pr.default(t,[{key:"uri",get:function(){return this.syncMapImpl.uri}},{key:"links",get:function(){return this.syncMapImpl.links}},{key:"revision",get:function(){return this.syncMapImpl.revision}},{key:"lastEventId",get:function(){return this.syncMapImpl.lastEventId}},{key:"dateExpires",get:function(){return this.syncMapImpl.dateExpires}},{key:"type",get:function(){return bw.type}},{key:"sid",get:function(){return this.syncMapImpl.sid}},{key:"uniqueName",get:function(){return this.syncMapImpl.uniqueName}},{key:"dateUpdated",get:function(){return this.syncMapImpl.dateUpdated}},{key:"set",value:function(){var n=ze.default(fe.default.mark(function s(a,c,o){return fe.default.wrap(function(d){for(;;)switch(d.prev=d.next){case 0:return this.ensureNotClosed(),d.abrupt("return",this.syncMapImpl.set(a,c,o));case 2:case"end":return d.stop()}},s,this)}));function i(s,a,c){return n.apply(this,arguments)}return i}()},{key:"get",value:function(){var n=ze.default(fe.default.mark(function s(a){return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:return this.ensureNotClosed(),o.abrupt("return",this.syncMapImpl.get(a));case 2:case"end":return o.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"mutate",value:function(){var n=ze.default(fe.default.mark(function s(a,c,o){return fe.default.wrap(function(d){for(;;)switch(d.prev=d.next){case 0:return this.ensureNotClosed(),d.abrupt("return",this.syncMapImpl.mutate(a,c,o));case 2:case"end":return d.stop()}},s,this)}));function i(s,a,c){return n.apply(this,arguments)}return i}()},{key:"update",value:function(){var n=ze.default(fe.default.mark(function s(a,c,o){return fe.default.wrap(function(d){for(;;)switch(d.prev=d.next){case 0:return this.ensureNotClosed(),d.abrupt("return",this.syncMapImpl.update(a,c,o));case 2:case"end":return d.stop()}},s,this)}));function i(s,a,c){return n.apply(this,arguments)}return i}()},{key:"remove",value:function(){var n=ze.default(fe.default.mark(function s(a){return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:return this.ensureNotClosed(),o.abrupt("return",this.syncMapImpl.remove(a));case 2:case"end":return o.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"getItems",value:function(){var n=ze.default(fe.default.mark(function s(a){return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:return this.ensureNotClosed(),o.abrupt("return",this.syncMapImpl.getItems(a));case 2:case"end":return o.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"setTtl",value:function(){var n=ze.default(fe.default.mark(function s(a){return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:return this.ensureNotClosed(),o.abrupt("return",this.syncMapImpl.setTtl(a));case 2:case"end":return o.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"setItemTtl",value:function(){var n=ze.default(fe.default.mark(function s(a,c){return fe.default.wrap(function(l){for(;;)switch(l.prev=l.next){case 0:return this.ensureNotClosed(),l.abrupt("return",this.syncMapImpl.setItemTtl(a,c));case 2:case"end":return l.stop()}},s,this)}));function i(s,a){return n.apply(this,arguments)}return i}()},{key:"removeMap",value:function(){var n=ze.default(fe.default.mark(function s(){return fe.default.wrap(function(c){for(;;)switch(c.prev=c.next){case 0:return this.ensureNotClosed(),c.next=3,this.syncMapImpl.removeMap();case 3:case"end":return c.stop()}},s,this)}));function i(){return n.apply(this,arguments)}return i}()},{key:"close",value:function(){zf.default(mn.default(t.prototype),"close",this).call(this),this.syncMapImpl.detach(this.listenerUuid)}}],[{key:"type",get:function(){return bw.type}}]),t}(Jf);fr.default(On,"itemAdded","itemAdded");fr.default(On,"itemUpdated","itemUpdated");fr.default(On,"itemRemoved","itemRemoved");fr.default(On,"removed","removed");yr([Fe.validateTypesAsync("string",Fe.pureObject,["undefined",Fe.objectSchema("item metadata",{ttl:[Fe.nonNegativeInteger,"undefined"]})]),We("design:type",Function),We("design:paramtypes",[String,Object,Object]),We("design:returntype",Promise)],On.prototype,"set",null);yr([Fe.validateTypesAsync("string"),We("design:type",Function),We("design:paramtypes",[String]),We("design:returntype",Promise)],On.prototype,"get",null);yr([Fe.validateTypesAsync("string","function",["undefined",Fe.objectSchema("item metadata",{ttl:[Fe.nonNegativeInteger,"undefined"]})]),We("design:type",Function),We("design:paramtypes",[String,Function,Object]),We("design:returntype",Promise)],On.prototype,"mutate",null);yr([Fe.validateTypesAsync("string",Fe.pureObject,["undefined",Fe.objectSchema("item metadata",{ttl:[Fe.nonNegativeInteger,"undefined"]})]),We("design:type",Function),We("design:paramtypes",[String,Object,Object]),We("design:returntype",Promise)],On.prototype,"update",null);yr([Fe.validateTypesAsync("string"),We("design:type",Function),We("design:paramtypes",[String]),We("design:returntype",Promise)],On.prototype,"remove",null);yr([Fe.validateTypesAsync(["undefined",Fe.objectSchema("query options",{from:["string","undefined"],pageSize:[Fe.custom(function(r){return[AT(r),"a positive integer"]}),"undefined"],order:[Fe.custom(function(r){return[r==="asc"||r==="desc","either 'asc' or 'desc'"]}),"undefined"]})]),We("design:type",Function),We("design:paramtypes",[Object]),We("design:returntype",Promise)],On.prototype,"getItems",null);yr([Fe.validateTypesAsync(Fe.nonNegativeInteger),We("design:type",Function),We("design:paramtypes",[Number]),We("design:returntype",Promise)],On.prototype,"setTtl",null);yr([Fe.validateTypesAsync("string",Fe.nonNegativeInteger),We("design:type",Function),We("design:paramtypes",[String,Number]),We("design:returntype",Promise)],On.prototype,"setItemTtl",null);function j2(r){var e=Rve();return function(){var n=mn.default(r),i;if(e){var s=mn.default(this).constructor;i=Reflect.construct(n,arguments,s)}else i=n.apply(this,arguments);return cu.default(this,i)}}function Rve(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var cf=function(r){ki.default(t,r);var e=j2(t);function t(n,i,s){var a;return hr.default(this,t),a=e.call(this,n,s),a.descriptor=i,a}return pr.default(t,[{key:"uri",get:function(){return this.descriptor.url}},{key:"links",get:function(){return this.descriptor.links}},{key:"dateExpires",get:function(){return this.descriptor.date_expires}},{key:"type",get:function(){return"stream"}},{key:"lastEventId",get:function(){return null}},{key:"indexName",get:function(){}},{key:"queryString",get:function(){}},{key:"sid",get:function(){return this.descriptor.sid}},{key:"uniqueName",get:function(){return this.descriptor.unique_name||null}},{key:"publishMessage",value:function(){var n=ze.default(fe.default.mark(function s(a){var c,o,l,d;return fe.default.wrap(function(p){for(;;)switch(p.prev=p.next){case 0:return c={data:a},p.next=3,this.services.network.post(this.links.messages,c);case 3:return o=p.sent,l=o.body,d=this._handleMessagePublished(l.sid,a,!1),p.abrupt("return",d);case 7:case"end":return p.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"setTtl",value:function(){var n=ze.default(fe.default.mark(function s(a){var c,o;return fe.default.wrap(function(d){for(;;)switch(d.prev=d.next){case 0:return d.prev=0,c={ttl:a},d.next=4,this.services.network.post(this.uri,c);case 4:o=d.sent,this.descriptor.date_expires=o.body.date_expires,d.next=12;break;case 8:throw d.prev=8,d.t0=d.catch(0),d.t0.status===404&&this.onRemoved(!1),d.t0;case 12:case"end":return d.stop()}},s,this,[[0,8]])}));function i(s){return n.apply(this,arguments)}return i}()},{key:"removeStream",value:function(){var n=ze.default(fe.default.mark(function s(){return fe.default.wrap(function(c){for(;;)switch(c.prev=c.next){case 0:return c.next=2,this.services.network.delete(this.uri);case 2:this.onRemoved(!0);case 3:case"end":return c.stop()}},s,this)}));function i(){return n.apply(this,arguments)}return i}()},{key:"_update",value:function(i){switch(i.type){case"stream_message_published":{this._handleMessagePublished(i.message_sid,i.message_data,!0);break}case"stream_removed":{this.onRemoved(!1);break}}}},{key:"_handleMessagePublished",value:function(i,s,a){var c={sid:i,data:s};return this.broadcastEventToListeners("messagePublished",{message:c,isLocal:!a}),c}},{key:"onRemoved",value:function(i){this._unsubscribe(),this.removalHandler(this.type,this.sid,this.uniqueName),this.broadcastEventToListeners("removed",{isLocal:i})}}],[{key:"type",get:function(){return"stream"}}]),t}(Kf);yr([Fe.validateTypesAsync(Fe.pureObject),We("design:type",Function),We("design:paramtypes",[Object]),We("design:returntype",Promise)],cf.prototype,"publishMessage",null);yr([Fe.validateTypesAsync(Fe.nonNegativeInteger),We("design:type",Function),We("design:paramtypes",[Number]),We("design:returntype",Promise)],cf.prototype,"setTtl",null);var ha=function(r){ki.default(t,r);var e=j2(t);function t(n){var i;return hr.default(this,t),i=e.call(this),i.syncStreamImpl=n,i.syncStreamImpl.attach(ma.default(i)),i}return pr.default(t,[{key:"uri",get:function(){return this.syncStreamImpl.uri}},{key:"links",get:function(){return this.syncStreamImpl.links}},{key:"dateExpires",get:function(){return this.syncStreamImpl.dateExpires}},{key:"type",get:function(){return cf.type}},{key:"lastEventId",get:function(){return null}},{key:"sid",get:function(){return this.syncStreamImpl.sid}},{key:"uniqueName",get:function(){return this.syncStreamImpl.uniqueName}},{key:"publishMessage",value:function(){var n=ze.default(fe.default.mark(function s(a){return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:return this.ensureNotClosed(),o.abrupt("return",this.syncStreamImpl.publishMessage(a));case 2:case"end":return o.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"setTtl",value:function(){var n=ze.default(fe.default.mark(function s(a){return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:return this.ensureNotClosed(),o.abrupt("return",this.syncStreamImpl.setTtl(a));case 2:case"end":return o.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"removeStream",value:function(){var n=ze.default(fe.default.mark(function s(){return fe.default.wrap(function(c){for(;;)switch(c.prev=c.next){case 0:return this.ensureNotClosed(),c.abrupt("return",this.syncStreamImpl.removeStream());case 2:case"end":return c.stop()}},s,this)}));function i(){return n.apply(this,arguments)}return i}()},{key:"close",value:function(){zf.default(mn.default(t.prototype),"close",this).call(this),this.syncStreamImpl.detach(this.listenerUuid)}}],[{key:"type",get:function(){return cf.type}}]),t}(Jf);fr.default(ha,"messagePublished","messagePublished");fr.default(ha,"removed","removed");yr([Fe.validateTypesAsync(Fe.pureObject),We("design:type",Function),We("design:paramtypes",[Object]),We("design:returntype",Promise)],ha.prototype,"publishMessage",null);yr([Fe.validateTypesAsync(Fe.nonNegativeInteger),We("design:type",Function),We("design:paramtypes",[Number]),We("design:returntype",Promise)],ha.prototype,"setTtl",null);var Ive=pr.default(function r(e){hr.default(this,r),this.sdk="js",this.sdkVer=e,this.os=Lp.os.family,this.osVer=Lp.os.version,this.pl=Lp.name,this.plVer=Lp.version}),Pve=function(){function r(){hr.default(this,r),this.names=new Map,this.entities=new Map}return pr.default(r,[{key:"store",value:function(t){var n=this.entities.get(t.sid);return n||(this.entities.set(t.sid,t),t.uniqueName&&this.names.set(t.type+"::"+t.uniqueName,t.sid),t)}},{key:"getResolved",value:function(t,n){var i=this.names.get(n+"::"+t);return i?this.entities.get(i):null}},{key:"get",value:function(t,n){return this.entities.get(t)||this.getResolved(t,n)||null}},{key:"remove",value:function(t){var n=this.entities.get(t);n&&(this.entities.delete(t),n.uniqueName&&this.names.delete(n.type+"::"+n.uniqueName))}}]),r}();function xT(r){var e=Ave();return function(){var n=mn.default(r),i;if(e){var s=mn.default(this).constructor;i=Reflect.construct(n,arguments,s)}else i=n.apply(this,arguments);return cu.default(this,i)}}function Ave(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}var Sw=function(){function r(e,t,n){hr.default(this,r),this.key=e,this.value=t,this.lastEventId=n}return pr.default(r,[{key:"cacheKey",get:function(){return this.key}}]),r}(),ww=function(r){ki.default(t,r);var e=xT(t);function t(n,i,s,a){var c;return hr.default(this,t),c=e.call(this,i,s),c.descriptor=n,c.cache=new $T,a&&a.forEach(function(o){var l=new Sw(o.key,o.data,o.revision);c.cache.store(o.key,l,o.revision)}),c}return pr.default(t,[{key:"sid",get:function(){return this.descriptor.sid}},{key:"uniqueName",get:function(){return null}},{key:"type",get:function(){return t.type}},{key:"lastEventId",get:function(){return this.descriptor.last_event_id}},{key:"indexName",get:function(){return this.descriptor.indexName}},{key:"queryString",get:function(){return this.descriptor.queryExpression}},{key:"queryUri",get:function(){return this.descriptor.queryUri}},{key:"liveQueryDescriptor",get:function(){return this.descriptor}},{key:"onRemoved",value:function(){}},{key:"getItems",value:function(){var i={};return this.cache.forEach(function(s,a){i[s]=a.value}),i}},{key:"_update",value:function(i,s){switch(i.type){case"live_query_item_updated":this.handleItemMutated(i.item_key,i.item_data,i.item_revision);break;case"live_query_item_removed":this.handleItemRemoved(i.item_key,i.item_revision);break;case"live_query_updated":this.handleBatchUpdate(i.items);break}s&&this._advanceLastEventId(i.last_event_id)}},{key:"handleItemMutated",value:function(i,s,a){if(this.shouldIgnoreEvent(i,a)){_r.trace("Item ".concat(i," update skipped, revision: ").concat(a));return}var c=new Sw(i,s,a);this.cache.store(i,c,a),this.broadcastEventToListeners("itemUpdated",c)}},{key:"handleItemRemoved",value:function(i,s){if(this.shouldIgnoreEvent(i,s)){_r.trace("Item ".concat(i," delete skipped, revision: ").concat(s));return}this.cache.delete(i,s),this.broadcastEventToListeners("itemRemoved",{key:i})}},{key:"handleBatchUpdate",value:function(i){var s=this,a={};i!=null&&i.forEach(function(o){a[o.key]={data:o.data,revision:o.revision}}),this.cache.forEach(function(o,l){var d=a[o];d!=null?s.handleItemMutated(o,d.data,d.revision):s.handleItemRemoved(o,null),delete a[o]});for(var c in a)this.handleItemMutated(c,a[c].data,a[c].revision)}},{key:"shouldIgnoreEvent",value:function(i,s){return i!=null&&s!=null&&this.cache.isKnown(i,s)}},{key:"_advanceLastEventId",value:function(i,s){this.lastEventId<i&&(this.descriptor.last_event_id=i)}}],[{key:"type",get:function(){return"live_query"}}]),t}(Kf);function B2(r){return Tw.apply(this,arguments)}function Tw(){return Tw=ze.default(fe.default.mark(function r(e){var t,n,i,s,a,c;return fe.default.wrap(function(l){for(;;)switch(l.prev=l.next){case 0:if(t=e.network,n=e.queryString,i=e.uri,s=e.type,n!=null){l.next=3;break}throw new Fi("Invalid query",400,54507);case 3:return a={query_string:n},s===Qa.type&&(a.type=s),l.next=7,t.post(i,a,void 0,!0);case 7:return c=l.sent,l.abrupt("return",c.body);case 9:case"end":return l.stop()}},r)})),Tw.apply(this,arguments)}var Qa=function(r){ki.default(t,r);var e=xT(t);function t(n){var i;return hr.default(this,t),i=e.call(this),i.liveQueryImpl=n,i.liveQueryImpl.attach(ma.default(i)),i}return pr.default(t,[{key:"type",get:function(){return ww.type}},{key:"lastEventId",get:function(){return this.liveQueryImpl.lastEventId}},{key:"sid",get:function(){return this.liveQueryImpl.sid}},{key:"close",value:function(){zf.default(mn.default(t.prototype),"close",this).call(this),this.liveQueryImpl.detach(this.listenerUuid)}},{key:"getItems",value:function(){return this.ensureNotClosed(),this.liveQueryImpl.getItems()}}],[{key:"type",get:function(){return ww.type}}]),t}(Jf);fr.default(Qa,"itemUpdated","itemUpdated");fr.default(Qa,"itemRemoved","itemRemoved");var Yf=function(r){ki.default(t,r);var e=xT(t);function t(n){var i;return hr.default(this,t),i=e.call(this),fr.default(ma.default(i),"queryExpression",null),fr.default(ma.default(i),"items",{}),Object.assign(ma.default(i),n),i.updateIndexName(n.indexName),i}return pr.default(t,[{key:"type",get:function(){return t.type}},{key:"search",value:function(){var n=ze.default(fe.default.mark(function s(a){var c=this,o;return fe.default.wrap(function(d){for(;;)switch(d.prev=d.next){case 0:return this.items={},d.prev=1,d.next=4,B2({network:this.network,uri:this.queryUri,queryString:a});case 4:o=d.sent,this.queryExpression=a,o.items&&o.items.forEach(function(h){c.items[h.key]=h.data}),this.emit("searchResult",this.getItems()),d.next=15;break;case 10:throw d.prev=10,d.t0=d.catch(1),_r.error("Error '".concat(d.t0.message,"' while executing query '").concat(a,"'")),this.queryExpression=null,d.t0;case 15:case"end":return d.stop()}},s,this,[[1,10]])}));function i(s){return n.apply(this,arguments)}return i}()},{key:"subscribe",value:function(){var n=ze.default(fe.default.mark(function s(){return fe.default.wrap(function(c){for(;;)switch(c.prev=c.next){case 0:if(this.queryExpression!=null){c.next=2;break}return c.abrupt("return",Promise.reject(new Fi("Invalid query",400,54507)));case 2:return c.abrupt("return",this.liveQueryCreator(this.indexName,this.queryExpression));case 3:case"end":return c.stop()}},s,this)}));function i(){return n.apply(this,arguments)}return i}()},{key:"getItems",value:function(){return this.items}},{key:"updateIndexName",value:function(i){this.indexName=i,this.queryUri=this.generateQueryUri(this.indexName)}},{key:"generateQueryUri",value:function(i){return new wl(this.insightsUri).pathSegment(i).pathSegment("Items").build()}}],[{key:"type",get:function(){return"instant_query"}}]),t}(IT.ReplayEventEmitter);fr.default(Yf,"searchResult","searchResult");yr([Fe.validateTypesAsync("string"),We("design:type",Function),We("design:paramtypes",[String]),We("design:returntype",Promise)],Yf.prototype,"search",null);yr([Fe.validateTypes(Fe.nonEmptyString),We("design:type",Function),We("design:paramtypes",[String]),We("design:returntype",void 0)],Yf.prototype,"updateIndexName",null);var Ove="3.4.0";function $ve(r){var e=xve();return function(){var n=mn.default(r),i;if(e){var s=mn.default(this).constructor;i=Reflect.construct(n,arguments,s)}else i=n.apply(this,arguments);return cu.default(this,i)}}function xve(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function uA(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function cA(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?uA(Object(t),!0).forEach(function(n){fr.default(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):uA(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var Mve="data_sync",mb=Ove;function Up(r){if(r){if(typeof r=="string")return{id:r,mode:"open_or_create"};var e=r.mode||(r.id?"open_or_create":"create_new");return cA(cA({},r),{},{mode:e})}else return{mode:"create_new"}}var lA="com.twilio.rtd.cds.document",dA="com.twilio.rtd.cds.list",fA="com.twilio.rtd.cds.map",hA="twilio.sync.event",is=function(r){ki.default(t,r);var e=$ve(t);function t(n){var i,s,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(hr.default(this,t),s=e.call(this),!n)throw new Error("Sync library needs a valid Twilio token to be passed");a.hasOwnProperty("logLevel")?_r.setLevel(a.logLevel):_r.setLevel("silent");var c=a.productId=a.productId||Mve;a.clientMetadata=a.clientMetadata||{},a.clientMetadata.hasOwnProperty("type")||(a.clientMetadata.type="sync"),a.clientMetadata.hasOwnProperty("sdk")||(a.clientMetadata.sdk="JS",a.clientMetadata.sdkv=mb);var o=!a.twilsockClient;if(!a.initRegistrations){var l=new Uv.InitRegistration(c);t.populateInitRegistrations(l),a.initRegistrations=[l]}var d=a.twilsockClient=(i=a.twilsockClient)!==null&&i!==void 0?i:new Uv.Twilsock(n,c,a);d.on("tokenAboutToExpire",function(){return s.emit("tokenAboutToExpire")}),d.on("tokenExpired",function(){return s.emit("tokenExpired")}),d.on("connectionError",function(w){return s.emit("connectionError",w)}),d.on("stateChanged",function(w){s.emit("connectionStateChanged",w),s.services.subscriptions.onConnectionStateChanged(w==="connected")}),d.on("message",function(w,k){return s._routeMessage(w,k)});var h=new tve(a),p=new cve(new Ive(mb),h,d),y=new lve(h);return s.services={config:h,twilsock:d,network:p,storage:y,router:ma.default(s),subscriptions:null},s.services.subscriptions=new ive(s.services),s.entities=new Pve,o&&d.connect(),s}return pr.default(t,[{key:"_routeMessage",value:function(i,s){switch(_r.trace("Notification type:",i,"content:",s),i){case lA:case dA:case fA:this.services.subscriptions.acceptMessage(s,!1);break;case hA:this.services.subscriptions.acceptMessage(s,!0);break}}},{key:"_subscribe",value:function(i,s){this.services.subscriptions.add(i,s)}},{key:"_unsubscribe",value:function(i){this.services.subscriptions.remove(i)}},{key:"connectionState",get:function(){return this.services.twilsock.state}},{key:"ensureReady",value:function(){var n=ze.default(fe.default.mark(function s(){var a;return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:if(this.services.config.sessionStorageEnabled){o.next=2;break}return o.abrupt("return");case 2:return o.prev=2,o.next=5,this.services.twilsock.storageId();case 5:a=o.sent,this.services.storage.updateStorageId(a.id),o.next=12;break;case 9:o.prev=9,o.t0=o.catch(2),_r.warn("Failed to initialize storage",o.t0);case 12:case"end":return o.stop()}},s,this,[[2,9]])}));function i(){return n.apply(this,arguments)}return i}()},{key:"storeRootInSessionCache",value:function(i,s,a){if(!(!this.services.config.sessionStorageEnabled||!s)){var c=zs(a);(i===En.type||i===On.type)&&(c.last_event_id=null,delete c.items),this.services.storage.store(i,s,c)}}},{key:"readRootFromSessionCache",value:function(i,s){return!this.services.config.sessionStorageEnabled||!s?null:this.services.storage.read(i,s)}},{key:"_get",value:function(){var n=ze.default(fe.default.mark(function s(a,c){var o,l,d,h=arguments;return fe.default.wrap(function(y){for(;;)switch(y.prev=y.next){case 0:if(o=h.length>2&&h[2]!==void 0?h[2]:!1,c){y.next=3;break}throw new Fi("Cannot get entity without id",404);case 3:return l=new wl(a).pathSegment(c).queryParam("Include",o?"items":void 0).build(),y.next=6,this.services.network.get(l);case 6:return d=y.sent,y.abrupt("return",d.body);case 8:case"end":return y.stop()}},s,this)}));function i(s,a){return n.apply(this,arguments)}return i}()},{key:"_createDocument",value:function(i,s,a){var c={unique_name:i,data:s||{}};return a!==void 0&&(c.ttl=a),this.services.network.post(this.services.config.documentsUri,c).then(function(o){return o.body.data=c.data,o.body})}},{key:"_getDocument",value:function(){var n=ze.default(fe.default.mark(function s(a){return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:return o.abrupt("return",this.readRootFromSessionCache(ys.type,a)||this._get(this.services.config.documentsUri,a));case 1:case"end":return o.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"_createList",value:function(i,s,a,c){var o={unique_name:i,purpose:s,context:a};return c!==void 0&&(o.ttl=c),this.services.network.post(this.services.config.listsUri,o).then(function(l){return l.body})}},{key:"_getList",value:function(){var n=ze.default(fe.default.mark(function s(a){return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:return o.abrupt("return",this.readRootFromSessionCache(En.type,a)||this._get(this.services.config.listsUri,a));case 1:case"end":return o.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"_createMap",value:function(i,s){var a={unique_name:i};return s!==void 0&&(a.ttl=s),this.services.network.post(this.services.config.mapsUri,a).then(function(c){return c.body})}},{key:"_getMap",value:function(){var n=ze.default(fe.default.mark(function s(a){var c,o=arguments;return fe.default.wrap(function(d){for(;;)switch(d.prev=d.next){case 0:return c=o.length>1&&o[1]!==void 0?o[1]:!1,d.abrupt("return",this.readRootFromSessionCache(On.type,a)||this._get(this.services.config.mapsUri,a,c));case 2:case"end":return d.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"_getStream",value:function(){var n=ze.default(fe.default.mark(function s(a){return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:return o.abrupt("return",this.readRootFromSessionCache(ha.type,a)||this._get(this.services.config.streamsUri,a,!1));case 1:case"end":return o.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"_createStream",value:function(){var n=ze.default(fe.default.mark(function s(a,c){var o,l;return fe.default.wrap(function(h){for(;;)switch(h.prev=h.next){case 0:return o={unique_name:a},c!==void 0&&(o.ttl=c),h.next=4,this.services.network.post(this.services.config.streamsUri,o);case 4:return l=h.sent,h.abrupt("return",l.body);case 6:case"end":return h.stop()}},s,this)}));function i(s,a){return n.apply(this,arguments)}return i}()},{key:"_getLiveQuery",value:function(i){return this.readRootFromSessionCache(Qa.type,i)}},{key:"getCached",value:function(i,s){return i&&this.entities.get(i,s)||null}},{key:"removeFromCacheAndSession",value:function(i,s,a){this.entities.remove(s),this.services.config.sessionStorageEnabled&&this.services.storage.remove(i,s,a)}},{key:"document",value:function(){var n=ze.default(fe.default.mark(function s(a){var c=this,o,l,d,h;return fe.default.wrap(function(y){for(;;)switch(y.prev=y.next){case 0:return y.next=2,this.ensureReady();case 2:if(o=Up(a),o.mode!=="create_new"){y.next=9;break}return y.next=6,this._createDocument(o.id,o.data,o.ttl);case 6:l=y.sent,y.next=39;break;case 9:if(d=this.getCached(o.id,ys.type),!d){y.next=14;break}return y.abrupt("return",new ys(d));case 14:return y.prev=14,y.next=17,this._getDocument(o.id);case 17:l=y.sent,y.next=39;break;case 20:if(y.prev=20,y.t0=y.catch(14),!(y.t0.status!==404||o.mode==="open_existing")){y.next=26;break}throw y.t0;case 26:return y.prev=26,y.next=29,this._createDocument(o.id,o.data,o.ttl);case 29:l=y.sent,y.next=39;break;case 32:if(y.prev=32,y.t1=y.catch(26),y.t1.status!==409){y.next=38;break}return y.abrupt("return",this.document(a));case 38:throw y.t1;case 39:return this.storeRootInSessionCache(ys.type,o.id,l),h=new mw(this.services,l,function(w,k,P){return c.removeFromCacheAndSession(w,k,P)}),h=this.entities.store(h),y.abrupt("return",new ys(h));case 43:case"end":return y.stop()}},s,this,[[14,20],[26,32]])}));function i(s){return n.apply(this,arguments)}return i}()},{key:"map",value:function(){var n=ze.default(fe.default.mark(function s(a){var c=this,o,l,d,h;return fe.default.wrap(function(y){for(;;)switch(y.prev=y.next){case 0:return y.next=2,this.ensureReady();case 2:if(o=Up(a),o.mode!=="create_new"){y.next=9;break}return y.next=6,this._createMap(o.id,o.ttl);case 6:l=y.sent,y.next=39;break;case 9:if(d=this.getCached(o.id,On.type),!d){y.next=14;break}return y.abrupt("return",new On(d));case 14:return y.prev=14,y.next=17,this._getMap(o.id,o.includeItems);case 17:l=y.sent,y.next=39;break;case 20:if(y.prev=20,y.t0=y.catch(14),!(y.t0.status!==404||o.mode==="open_existing")){y.next=26;break}throw y.t0;case 26:return y.prev=26,y.next=29,this._createMap(o.id,o.ttl);case 29:l=y.sent,y.next=39;break;case 32:if(y.prev=32,y.t1=y.catch(26),y.t1.status!==409){y.next=38;break}return y.abrupt("return",this.map(a));case 38:throw y.t1;case 39:return this.storeRootInSessionCache(On.type,o.id,l),h=new bw(this.services,l,function(w,k,P){return c.removeFromCacheAndSession(w,k,P)}),h=this.entities.store(h),y.abrupt("return",new On(h));case 43:case"end":return y.stop()}},s,this,[[14,20],[26,32]])}));function i(s){return n.apply(this,arguments)}return i}()},{key:"list",value:function(){var n=ze.default(fe.default.mark(function s(a){var c=this,o,l,d,h;return fe.default.wrap(function(y){for(;;)switch(y.prev=y.next){case 0:return y.next=2,this.ensureReady();case 2:if(o=Up(a),o.mode!=="create_new"){y.next=9;break}return y.next=6,this._createList(o.id,o.purpose,o.context,o.ttl);case 6:l=y.sent,y.next=39;break;case 9:if(d=this.getCached(o.id,En.type),!d){y.next=14;break}return y.abrupt("return",new En(d));case 14:return y.prev=14,y.next=17,this._getList(o.id);case 17:l=y.sent,y.next=39;break;case 20:if(y.prev=20,y.t0=y.catch(14),!(y.t0.status!==404||o.mode==="open_existing")){y.next=26;break}throw y.t0;case 26:return y.prev=26,y.next=29,this._createList(o.id,o.purpose,o.context,o.ttl);case 29:l=y.sent,y.next=39;break;case 32:if(y.prev=32,y.t1=y.catch(26),y.t1.status!==409){y.next=38;break}return y.abrupt("return",this.list(a));case 38:throw y.t1;case 39:return this.storeRootInSessionCache(En.type,o.id,l),h=new _w(this.services,l,function(w,k,P){return c.removeFromCacheAndSession(w,k,P)}),h=this.entities.store(h),y.abrupt("return",new En(h));case 43:case"end":return y.stop()}},s,this,[[14,20],[26,32]])}));function i(s){return n.apply(this,arguments)}return i}()},{key:"stream",value:function(){var n=ze.default(fe.default.mark(function s(a){var c=this,o,l,d,h,p;return fe.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this.ensureReady();case 2:if(o=Up(a),o.mode!=="create_new"){w.next=9;break}return w.next=6,this._createStream(o.id,o.ttl);case 6:l=w.sent,w.next=39;break;case 9:if(d=this.getCached(o.id,ha.type),!d){w.next=14;break}return w.abrupt("return",new ha(d));case 14:return w.prev=14,w.next=17,this._getStream(o.id);case 17:l=w.sent,w.next=39;break;case 20:if(w.prev=20,w.t0=w.catch(14),!(w.t0.status!==404||o.mode==="open_existing")){w.next=26;break}throw w.t0;case 26:return w.prev=26,w.next=29,this._createStream(o.id,o.ttl);case 29:l=w.sent,w.next=39;break;case 32:if(w.prev=32,w.t1=w.catch(26),w.t1.status!==409){w.next=38;break}return w.abrupt("return",this.stream(a));case 38:throw w.t1;case 39:return this.storeRootInSessionCache(ha.type,o.id,l),h=function(P,A,B){return c.removeFromCacheAndSession(P,A,B)},p=new cf(this.services,l,h),p=this.entities.store(p),w.abrupt("return",new ha(p));case 44:case"end":return w.stop()}},s,this,[[14,20],[26,32]])}));function i(s){return n.apply(this,arguments)}return i}()},{key:"shutdown",value:function(){var n=ze.default(fe.default.mark(function s(){return fe.default.wrap(function(c){for(;;)switch(c.prev=c.next){case 0:return c.next=2,this.services.subscriptions.shutdown();case 2:return c.next=4,this.services.twilsock.disconnect();case 4:case"end":return c.stop()}},s,this)}));function i(){return n.apply(this,arguments)}return i}()},{key:"updateToken",value:function(){var n=ze.default(fe.default.mark(function s(a){return fe.default.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:return o.abrupt("return",this.services.twilsock.updateToken(a).catch(function(l){var d,h=l==null||(d=l.reply)===null||d===void 0?void 0:d.status;throw(h==null?void 0:h.code)===401&&(h==null?void 0:h.status)==="UNAUTHORIZED"?new Fi("Updated token was rejected by server",400,51130):l}));case 1:case"end":return o.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()},{key:"liveQuery",value:function(){var n=ze.default(fe.default.mark(function s(a,c){var o=this,l,d,h,p,y;return fe.default.wrap(function(k){for(;;)switch(k.prev=k.next){case 0:return k.next=2,this.ensureReady();case 2:return l=new wl(this.services.config.insightsUri).pathSegment(a).pathSegment("Items").build(),k.next=5,B2({network:this.services.network,uri:l,queryString:c,type:Qa.type});case 5:return d=k.sent,h=this.getCached(d.query_id,Qa.type),h||(p=this._getLiveQuery(d.query_id),p||(p={indexName:a,queryExpression:c,sid:d.query_id,queryUri:l,last_event_id:d.last_event_id}),y=function(A,B,L){return o.removeFromCacheAndSession(A,B,L)},h=new ww(p,this.services,y,d.items)),this.storeRootInSessionCache(Qa.type,d.query_id,h.liveQueryDescriptor),h=this.entities.store(h),k.abrupt("return",new Qa(h));case 11:case"end":return k.stop()}},s,this)}));function i(s,a){return n.apply(this,arguments)}return i}()},{key:"instantQuery",value:function(){var n=ze.default(fe.default.mark(function s(a){var c=this,o;return fe.default.wrap(function(d){for(;;)switch(d.prev=d.next){case 0:return d.next=2,this.ensureReady();case 2:return o=function(p,y){return c.liveQuery(p,y)},d.abrupt("return",new Yf({indexName:a,network:this.services.network,insightsUri:this.services.config.insightsUri,liveQueryCreator:o}));case 4:case"end":return d.stop()}},s,this)}));function i(s){return n.apply(this,arguments)}return i}()}],[{key:"populateInitRegistrations",value:function(i){i.populateInitRegistrations([hA,lA,dA,fA])}},{key:"version",get:function(){return mb}}]),t}(IT.ReplayEventEmitter);fr.default(is,"connectionStateChanged","connectionStateChanged");fr.default(is,"connectionError","connectionError");fr.default(is,"tokenAboutToExpire","tokenAboutToExpire");fr.default(is,"tokenExpired","tokenExpired");yr([Fe.validateTypesAsync(["undefined","string",Fe.objectSchema("open document options",{id:["string","undefined"],mode:[Fe.literal("open_or_create","open_existing","create_new"),"undefined"],ttl:[Fe.nonNegativeInteger,"undefined"],data:[Fe.pureObject,"undefined",Fe.literal(null)]})]),We("design:type",Function),We("design:paramtypes",[Object]),We("design:returntype",Promise)],is.prototype,"document",null);yr([Fe.validateTypesAsync(["undefined","string",Fe.objectSchema("open map options",{id:["string","undefined"],mode:[Fe.literal("open_or_create","open_existing","create_new"),"undefined"],ttl:[Fe.nonNegativeInteger,"undefined"],data:[Fe.pureObject,"undefined",Fe.literal(null)],includeItems:["boolean","undefined"]})]),We("design:type",Function),We("design:paramtypes",[Object]),We("design:returntype",Promise)],is.prototype,"map",null);yr([Fe.validateTypesAsync(["undefined","string",Fe.objectSchema("open list options",{id:["string","undefined"],mode:[Fe.literal("open_or_create","open_existing","create_new"),"undefined"],ttl:[Fe.nonNegativeInteger,"undefined"],data:[Fe.pureObject,"undefined",Fe.literal(null)],purpose:["string","undefined"],context:[Fe.pureObject,"undefined"],includeItems:["boolean","undefined"]})]),We("design:type",Function),We("design:paramtypes",[Object]),We("design:returntype",Promise)],is.prototype,"list",null);yr([Fe.validateTypesAsync(["undefined","string",Fe.objectSchema("open stream options",{id:["string","undefined"],mode:[Fe.literal("open_or_create","open_existing","create_new"),"undefined"],ttl:[Fe.nonNegativeInteger,"undefined"],data:[Fe.pureObject,"undefined",Fe.literal(null)]})]),We("design:type",Function),We("design:paramtypes",[Object]),We("design:returntype",Promise)],is.prototype,"stream",null);yr([Fe.validateTypesAsync(Fe.nonEmptyString),We("design:type",Function),We("design:paramtypes",[String]),We("design:returntype",Promise)],is.prototype,"updateToken",null);yr([Fe.validateTypesAsync(Fe.nonEmptyString,"string"),We("design:type",Function),We("design:paramtypes",[String,String]),We("design:returntype",Promise)],is.prototype,"liveQuery",null);yr([Fe.validateTypesAsync(Fe.nonEmptyString),We("design:type",Function),We("design:paramtypes",[String]),We("design:returntype",Promise)],is.prototype,"instantQuery",null);Bi.Client=is;Bi.InsightsItem=Sw;Bi.InstantQuery=Yf;Bi.LiveQuery=Qa;Bi.Paginator=OT;Bi.SyncClient=is;Bi.SyncDocument=ys;Bi.SyncList=En;Bi.SyncListItem=yw;Bi.SyncMap=On;Bi.SyncMapItem=Fd;Bi.SyncStream=ha;var q2={},Dve=Cr,Nve=wa,Lve=Nr,Fve=Lve("match"),Uve=function(r){var e;return Dve(r)&&((e=r[Fve])!==void 0?!!e:Nve(r)==="RegExp")},jve=Uve,Bve=TypeError,W2=function(r){if(jve(r))throw new Bve("The method doesn't accept regular expressions");return r},qve=Nr,Wve=qve("match"),H2=function(r){var e=/./;try{"/./"[r](e)}catch{try{return e[Wve]=!1,"/./"[r](e)}catch{}}return!1},Hve=Gt,Vve=E0,Gve=co.f,zve=ho,pA=xn,Kve=W2,Jve=Qs,Yve=H2,Xve=Vve("".slice),Qve=Math.min,V2=Yve("startsWith"),Zve=!V2&&!!function(){var r=Gve(String.prototype,"startsWith");return r&&!r.writable}();Hve({target:"String",proto:!0,forced:!Zve&&!V2},{startsWith:function(e){var t=pA(Jve(this));Kve(e);var n=zve(Qve(arguments.length>1?arguments[1]:void 0,t.length)),i=pA(e);return Xve(t,n,n+i.length)===i}});var ege=Ut,tge=Nr,rge=Wr,vA=Hx,nge=tge("iterator"),G2=!ege(function(){var r=new URL("b?a=1&b=2&c=3","https://a"),e=r.searchParams,t=new URLSearchParams("a=1&a=2&b=3"),n="";return r.pathname="c%20d",e.forEach(function(i,s){e.delete("b"),n+=s+i}),t.delete("a",2),t.delete("b",void 0),vA&&(!r.toJSON||!t.has("a",1)||t.has("a",2)||!t.has("a",void 0)||t.has("b"))||!e.size&&(vA||!rge)||!e.sort||r.href!=="https://a/c%20d?a=1&c=3"||e.get("c")!=="3"||String(new URLSearchParams("?a=1"))!=="a=1"||!e[nge]||new URL("https://a@b").username!=="a"||new URLSearchParams(new URLSearchParams("a=b")).get("a")!=="b"||new URL("https://тест").host!=="xn--e1aybc"||new URL("https://a#б").hash!=="#%D0%B1"||n!=="a1c3"||new URL("https://x",void 0).host!=="x"}),oc=Wt,yb=2147483647,zd=36,z2=1,Ew=26,ige=38,sge=700,age=72,oge=128,uge="-",cge=/[^\0-\u007E]/,K2=/[.\u3002\uFF0E\uFF61]/g,gA="Overflow: input needs wider integers to process",_b=zd-z2,mA=RangeError,lge=oc(K2.exec),Yc=Math.floor,bb=String.fromCharCode,yA=oc("".charCodeAt),J2=oc([].join),Ho=oc([].push),dge=oc("".replace),fge=oc("".split),hge=oc("".toLowerCase),pge=function(r){for(var e=[],t=0,n=r.length;t<n;){var i=yA(r,t++);if(i>=55296&&i<=56319&&t<n){var s=yA(r,t++);(s&64512)===56320?Ho(e,((i&1023)<<10)+(s&1023)+65536):(Ho(e,i),t--)}else Ho(e,i)}return e},_A=function(r){return r+22+75*(r<26)},vge=function(r,e,t){var n=0;for(r=t?Yc(r/sge):r>>1,r+=Yc(r/e);r>_b*Ew>>1;)r=Yc(r/_b),n+=zd;return Yc(n+(_b+1)*r/(r+ige))},gge=function(r){var e=[];r=pge(r);var t=r.length,n=oge,i=0,s=age,a,c;for(a=0;a<r.length;a++)c=r[a],c<128&&Ho(e,bb(c));var o=e.length,l=o;for(o&&Ho(e,uge);l<t;){var d=yb;for(a=0;a<r.length;a++)c=r[a],c>=n&&c<d&&(d=c);var h=l+1;if(d-n>Yc((yb-i)/h))throw new mA(gA);for(i+=(d-n)*h,n=d,a=0;a<r.length;a++){if(c=r[a],c<n&&++i>yb)throw new mA(gA);if(c===n){for(var p=i,y=zd;;){var w=y<=s?z2:y>=s+Ew?Ew:y-s;if(p<w)break;var k=p-w,P=zd-w;Ho(e,bb(_A(w+k%P))),p=Yc(k/P),y+=zd}Ho(e,bb(_A(p))),s=vge(i,h,l===o),i=0,l++}}i++,n++}return J2(e,"")},mge=function(r){var e=[],t=fge(dge(hge(r),K2,"."),"."),n,i;for(n=0;n<t.length;n++)i=t[n],Ho(e,lge(cge,i)?"xn--"+gge(i):i);return J2(e,".")},yge=Gt,_ge=Wt,bge=ec,Sge=RangeError,bA=String.fromCharCode,SA=String.fromCodePoint,wge=_ge([].join),Tge=!!SA&&SA.length!==1;yge({target:"String",stat:!0,arity:1,forced:Tge},{fromCodePoint:function(e){for(var t=[],n=arguments.length,i=0,s;n>i;){if(s=+arguments[i++],bge(s,1114111)!==s)throw new Sge(s+" is not a valid code point");t[i]=s<65536?bA(s):bA(((s-=65536)>>10)+55296,s%1024+56320)}return wge(t,"")}});var Cw=Gt,Y2=Qt,MT=lD,Ege=Cs,jp=Dr,Js=Wt,Kd=Wr,X2=G2,Q2=Ci,Cge=ka,kge=Xg,Rge=Ea,Ige=YD,DT=Ui,Z2=au,Sb=Hr,Pge=en,Age=vo,Oge=po,$ge=fn,eF=Cr,yi=xn,xge=tu,wA=Ju,TA=Dg,Mge=Df,Bp=Fg,Mc=x0,Dge=Nr,Nge=CT,Lge=Dge("iterator"),Ul="URLSearchParams",tF=Ul+"Iterator",rF=DT.set,gs=DT.getterFor(Ul),Fge=DT.getterFor(tF),EA=MT("fetch"),jv=MT("Request"),Jd=MT("Headers"),wb=jv&&jv.prototype,CA=Jd&&Jd.prototype,Uge=Y2.TypeError,jge=Y2.encodeURIComponent,Bge=String.fromCharCode,qge=Ege("String","fromCodePoint"),Wge=parseInt,hv=Js("".charAt),kA=Js([].join),Vo=Js([].push),nF=Js("".replace),Hge=Js([].shift),RA=Js([].splice),IA=Js("".split),iF=Js("".slice),Vge=Js(/./.exec),Gge=/\+/g,Tb="�",zge=/^[0-9a-f]+$/i,PA=function(r,e){var t=iF(r,e,e+2);return Vge(zge,t)?Wge(t,16):NaN},Kge=function(r){for(var e=0,t=128;t>0&&r&t;t>>=1)e++;return e},Jge=function(r){var e=null;switch(r.length){case 1:e=r[0];break;case 2:e=(r[0]&31)<<6|r[1]&63;break;case 3:e=(r[0]&15)<<12|(r[1]&63)<<6|r[2]&63;break;case 4:e=(r[0]&7)<<18|(r[1]&63)<<12|(r[2]&63)<<6|r[3]&63;break}return e>1114111?null:e},AA=function(r){r=nF(r,Gge," ");for(var e=r.length,t="",n=0;n<e;){var i=hv(r,n);if(i==="%"){if(hv(r,n+1)==="%"||n+3>e){t+="%",n++;continue}var s=PA(r,n+1);if(s!==s){t+=i,n++;continue}n+=2;var a=Kge(s);if(a===0)i=Bge(s);else{if(a===1||a>4){t+=Tb,n++;continue}for(var c=[s],o=1;o<a&&(n++,!(n+3>e||hv(r,n)!=="%"));){var l=PA(r,n+1);if(l!==l){n+=3;break}if(l>191||l<128)break;Vo(c,l),n+=2,o++}if(c.length!==a){t+=Tb;continue}var d=Jge(c);d===null?t+=Tb:i=qge(d)}}t+=i,n++}return t},Yge=/[!'()~]|%20/g,Xge={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},Qge=function(r){return Xge[r]},OA=function(r){return nF(jge(r),Yge,Qge)},Eb=Ige(function(e,t){rF(this,{type:tF,target:gs(e).entries,index:0,kind:t})},Ul,function(){var e=Fge(this),t=e.target,n=e.index++;if(!t||n>=t.length)return e.target=null,Bp(void 0,!0);var i=t[n];switch(e.kind){case"keys":return Bp(i.key,!1);case"values":return Bp(i.value,!1)}return Bp([i.key,i.value],!1)},!0),sF=function(r){this.entries=[],this.url=null,r!==void 0&&(eF(r)?this.parseObject(r):this.parseQuery(typeof r=="string"?hv(r,0)==="?"?iF(r,1):r:yi(r)))};sF.prototype={type:Ul,bindURL:function(r){this.url=r,this.update()},parseObject:function(r){var e=this.entries,t=Mge(r),n,i,s,a,c,o,l;if(t)for(n=TA(r,t),i=n.next;!(s=jp(i,n)).done;){if(a=TA($ge(s.value)),c=a.next,(o=jp(c,a)).done||(l=jp(c,a)).done||!jp(c,a).done)throw new Uge("Expected sequence with length 2");Vo(e,{key:yi(o.value),value:yi(l.value)})}else for(var d in r)Pge(r,d)&&Vo(e,{key:d,value:yi(r[d])})},parseQuery:function(r){if(r)for(var e=this.entries,t=IA(r,"&"),n=0,i,s;n<t.length;)i=t[n++],i.length&&(s=IA(i,"="),Vo(e,{key:AA(Hge(s)),value:AA(kA(s,"="))}))},serialize:function(){for(var r=this.entries,e=[],t=0,n;t<r.length;)n=r[t++],Vo(e,OA(n.key)+"="+OA(n.value));return kA(e,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var mm=function(){Z2(this,Tl);var e=arguments.length>0?arguments[0]:void 0,t=rF(this,new sF(e));Kd||(this.size=t.entries.length)},Tl=mm.prototype;kge(Tl,{append:function(e,t){var n=gs(this);Mc(arguments.length,2),Vo(n.entries,{key:yi(e),value:yi(t)}),Kd||this.size++,n.updateURL()},delete:function(r){for(var e=gs(this),t=Mc(arguments.length,1),n=e.entries,i=yi(r),s=t<2?void 0:arguments[1],a=s===void 0?s:yi(s),c=0;c<n.length;){var o=n[c];if(o.key===i&&(a===void 0||o.value===a)){if(RA(n,c,1),a!==void 0)break}else c++}Kd||(this.size=n.length),e.updateURL()},get:function(e){var t=gs(this).entries;Mc(arguments.length,1);for(var n=yi(e),i=0;i<t.length;i++)if(t[i].key===n)return t[i].value;return null},getAll:function(e){var t=gs(this).entries;Mc(arguments.length,1);for(var n=yi(e),i=[],s=0;s<t.length;s++)t[s].key===n&&Vo(i,t[s].value);return i},has:function(e){for(var t=gs(this).entries,n=Mc(arguments.length,1),i=yi(e),s=n<2?void 0:arguments[1],a=s===void 0?s:yi(s),c=0;c<t.length;){var o=t[c++];if(o.key===i&&(a===void 0||o.value===a))return!0}return!1},set:function(e,t){var n=gs(this);Mc(arguments.length,1);for(var i=n.entries,s=!1,a=yi(e),c=yi(t),o=0,l;o<i.length;o++)l=i[o],l.key===a&&(s?RA(i,o--,1):(s=!0,l.value=c));s||Vo(i,{key:a,value:c}),Kd||(this.size=i.length),n.updateURL()},sort:function(){var e=gs(this);Nge(e.entries,function(t,n){return t.key>n.key?1:-1}),e.updateURL()},forEach:function(e){for(var t=gs(this).entries,n=Age(e,arguments.length>1?arguments[1]:void 0),i=0,s;i<t.length;)s=t[i++],n(s.value,s.key,this)},keys:function(){return new Eb(this,"keys")},values:function(){return new Eb(this,"values")},entries:function(){return new Eb(this,"entries")}},{enumerable:!0});Q2(Tl,Lge,Tl.entries,{name:"entries"});Q2(Tl,"toString",function(){return gs(this).serialize()},{enumerable:!0});Kd&&Cge(Tl,"size",{get:function(){return gs(this).entries.length},configurable:!0,enumerable:!0});Rge(mm,Ul);Cw({global:!0,constructor:!0,forced:!X2},{URLSearchParams:mm});if(!X2&&Sb(Jd)){var Zge=Js(CA.has),eme=Js(CA.set),$A=function(r){if(eF(r)){var e=r.body,t;if(Oge(e)===Ul)return t=r.headers?new Jd(r.headers):new Jd,Zge(t,"content-type")||eme(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),xge(r,{body:wA(0,yi(e)),headers:wA(0,t)})}return r};if(Sb(EA)&&Cw({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return EA(e,arguments.length>1?$A(arguments[1]):{})}}),Sb(jv)){var Cb=function(e){return Z2(this,wb),new jv(e,arguments.length>1?$A(arguments[1]):{})};wb.constructor=Cb,Cb.prototype=wb,Cw({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:Cb})}}var tme={URLSearchParams:mm,getState:gs},rme=Gt,NT=Wr,nme=G2,LT=Qt,xA=vo,Rs=Wt,Bv=Ci,ds=ka,ime=au,kw=en,FT=I2,Dc=zD,Fs=Ca,sme=q0.codeAt,ame=mge,Va=xn,ome=Ea,ume=x0,aF=tme,oF=Ui,cme=oF.set,qv=oF.getterFor("URL"),lme=aF.URLSearchParams,dme=aF.getState,Rd=LT.URL,Rw=LT.TypeError,Wv=LT.parseInt,fme=Math.floor,MA=Math.pow,ms=Rs("".charAt),Vs=Rs(/./.exec),Ud=Rs([].join),hme=Rs(1.1.toString),pme=Rs([].pop),qc=Rs([].push),kb=Rs("".replace),vme=Rs([].shift),gme=Rs("".split),Yd=Rs("".slice),Hv=Rs("".toLowerCase),mme=Rs([].unshift),yme="Invalid authority",Rb="Invalid scheme",Ou="Invalid host",DA="Invalid port",uF=/[a-z]/i,_me=/[\d+-.a-z]/i,Iw=/\d/,bme=/^0x/i,Sme=/^[0-7]+$/,wme=/^\d+$/,cF=/^[\da-f]+$/i,Tme=/[\0\t\n\r #%/:<>?@[\\\]^|]/,Eme=/[\0\t\n\r #/:<>?@[\\\]^|]/,Cme=/^[\u0000-\u0020]+/,kme=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,Rme=/[\t\n\r]/g,fs,Ime=function(r){var e=gme(r,"."),t,n,i,s,a,c,o;if(e.length&&e[e.length-1]===""&&e.length--,t=e.length,t>4)return r;for(n=[],i=0;i<t;i++){if(s=e[i],s==="")return r;if(a=10,s.length>1&&ms(s,0)==="0"&&(a=Vs(bme,s)?16:8,s=Yd(s,a===8?1:2)),s==="")c=0;else{if(!Vs(a===10?wme:a===8?Sme:cF,s))return r;c=Wv(s,a)}qc(n,c)}for(i=0;i<t;i++)if(c=n[i],i===t-1){if(c>=MA(256,5-t))return null}else if(c>255)return null;for(o=pme(n),i=0;i<n.length;i++)o+=n[i]*MA(256,3-i);return o},Pme=function(r){var e=[0,0,0,0,0,0,0,0],t=0,n=null,i=0,s,a,c,o,l,d,h,p=function(){return ms(r,i)};if(p()===":"){if(ms(r,1)!==":")return;i+=2,t++,n=t}for(;p();){if(t===8)return;if(p()===":"){if(n!==null)return;i++,t++,n=t;continue}for(s=a=0;a<4&&Vs(cF,p());)s=s*16+Wv(p(),16),i++,a++;if(p()==="."){if(a===0||(i-=a,t>6))return;for(c=0;p();){if(o=null,c>0)if(p()==="."&&c<4)i++;else return;if(!Vs(Iw,p()))return;for(;Vs(Iw,p());){if(l=Wv(p(),10),o===null)o=l;else{if(o===0)return;o=o*10+l}if(o>255)return;i++}e[t]=e[t]*256+o,c++,(c===2||c===4)&&t++}if(c!==4)return;break}else if(p()===":"){if(i++,!p())return}else if(p())return;e[t++]=s}if(n!==null)for(d=t-n,t=7;t!==0&&d>0;)h=e[t],e[t--]=e[n+d-1],e[n+--d]=h;else if(t!==8)return;return e},Ame=function(r){for(var e=null,t=1,n=null,i=0,s=0;s<8;s++)r[s]!==0?(i>t&&(e=n,t=i),n=null,i=0):(n===null&&(n=s),++i);return i>t?n:e},Id=function(r){var e,t,n,i;if(typeof r=="number"){for(e=[],t=0;t<4;t++)mme(e,r%256),r=fme(r/256);return Ud(e,".")}if(typeof r=="object"){for(e="",n=Ame(r),t=0;t<8;t++)i&&r[t]===0||(i&&(i=!1),n===t?(e+=t?":":"::",i=!0):(e+=hme(r[t],16),t<7&&(e+=":")));return"["+e+"]"}return r},pv={},lF=FT({},pv,{" ":1,'"':1,"<":1,">":1,"`":1}),dF=FT({},lF,{"#":1,"?":1,"{":1,"}":1}),Ib=FT({},dF,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),Do=function(r,e){var t=sme(r,0);return t>32&&t<127&&!kw(e,r)?r:encodeURIComponent(r)},qp={ftp:21,file:null,http:80,https:443,ws:80,wss:443},jd=function(r,e){var t;return r.length===2&&Vs(uF,ms(r,0))&&((t=ms(r,1))===":"||!e&&t==="|")},NA=function(r){var e;return r.length>1&&jd(Yd(r,0,2))&&(r.length===2||(e=ms(r,2))==="/"||e==="\\"||e==="?"||e==="#")},Ome=function(r){return r==="."||Hv(r)==="%2e"},$me=function(r){return r=Hv(r),r===".."||r==="%2e."||r===".%2e"||r==="%2e%2e"},Pb={},LA={},Ab={},FA={},UA={},Ob={},jA={},BA={},Wp={},Hp={},$b={},xb={},Mb={},Db={},qA={},Nb={},Nc={},ca={},WA={},$u={},Wa={},UT=function(r,e,t){var n=Va(r),i,s,a;if(e){if(s=this.parse(n),s)throw new Rw(s);this.searchParams=null}else{if(t!==void 0&&(i=new UT(t,!0)),s=this.parse(n,null,i),s)throw new Rw(s);a=dme(new lme),a.bindURL(this),this.searchParams=a}};UT.prototype={type:"URL",parse:function(r,e,t){var n=this,i=e||Pb,s=0,a="",c=!1,o=!1,l=!1,d,h,p,y;for(r=Va(r),e||(n.scheme="",n.username="",n.password="",n.host=null,n.port=null,n.path=[],n.query=null,n.fragment=null,n.cannotBeABaseURL=!1,r=kb(r,Cme,""),r=kb(r,kme,"$1")),r=kb(r,Rme,""),d=Dc(r);s<=d.length;){switch(h=d[s],i){case Pb:if(h&&Vs(uF,h))a+=Hv(h),i=LA;else{if(e)return Rb;i=Ab;continue}break;case LA:if(h&&(Vs(_me,h)||h==="+"||h==="-"||h==="."))a+=Hv(h);else if(h===":"){if(e&&(n.isSpecial()!==kw(qp,a)||a==="file"&&(n.includesCredentials()||n.port!==null)||n.scheme==="file"&&!n.host))return;if(n.scheme=a,e){n.isSpecial()&&qp[n.scheme]===n.port&&(n.port=null);return}a="",n.scheme==="file"?i=Db:n.isSpecial()&&t&&t.scheme===n.scheme?i=FA:n.isSpecial()?i=BA:d[s+1]==="/"?(i=UA,s++):(n.cannotBeABaseURL=!0,qc(n.path,""),i=WA)}else{if(e)return Rb;a="",i=Ab,s=0;continue}break;case Ab:if(!t||t.cannotBeABaseURL&&h!=="#")return Rb;if(t.cannotBeABaseURL&&h==="#"){n.scheme=t.scheme,n.path=Fs(t.path),n.query=t.query,n.fragment="",n.cannotBeABaseURL=!0,i=Wa;break}i=t.scheme==="file"?Db:Ob;continue;case FA:if(h==="/"&&d[s+1]==="/")i=Wp,s++;else{i=Ob;continue}break;case UA:if(h==="/"){i=Hp;break}else{i=ca;continue}case Ob:if(n.scheme=t.scheme,h===fs)n.username=t.username,n.password=t.password,n.host=t.host,n.port=t.port,n.path=Fs(t.path),n.query=t.query;else if(h==="/"||h==="\\"&&n.isSpecial())i=jA;else if(h==="?")n.username=t.username,n.password=t.password,n.host=t.host,n.port=t.port,n.path=Fs(t.path),n.query="",i=$u;else if(h==="#")n.username=t.username,n.password=t.password,n.host=t.host,n.port=t.port,n.path=Fs(t.path),n.query=t.query,n.fragment="",i=Wa;else{n.username=t.username,n.password=t.password,n.host=t.host,n.port=t.port,n.path=Fs(t.path),n.path.length--,i=ca;continue}break;case jA:if(n.isSpecial()&&(h==="/"||h==="\\"))i=Wp;else if(h==="/")i=Hp;else{n.username=t.username,n.password=t.password,n.host=t.host,n.port=t.port,i=ca;continue}break;case BA:if(i=Wp,h!=="/"||ms(a,s+1)!=="/")continue;s++;break;case Wp:if(h!=="/"&&h!=="\\"){i=Hp;continue}break;case Hp:if(h==="@"){c&&(a="%40"+a),c=!0,p=Dc(a);for(var w=0;w<p.length;w++){var k=p[w];if(k===":"&&!l){l=!0;continue}var P=Do(k,Ib);l?n.password+=P:n.username+=P}a=""}else if(h===fs||h==="/"||h==="?"||h==="#"||h==="\\"&&n.isSpecial()){if(c&&a==="")return yme;s-=Dc(a).length+1,a="",i=$b}else a+=h;break;case $b:case xb:if(e&&n.scheme==="file"){i=Nb;continue}else if(h===":"&&!o){if(a==="")return Ou;if(y=n.parseHost(a),y)return y;if(a="",i=Mb,e===xb)return}else if(h===fs||h==="/"||h==="?"||h==="#"||h==="\\"&&n.isSpecial()){if(n.isSpecial()&&a==="")return Ou;if(e&&a===""&&(n.includesCredentials()||n.port!==null))return;if(y=n.parseHost(a),y)return y;if(a="",i=Nc,e)return;continue}else h==="["?o=!0:h==="]"&&(o=!1),a+=h;break;case Mb:if(Vs(Iw,h))a+=h;else if(h===fs||h==="/"||h==="?"||h==="#"||h==="\\"&&n.isSpecial()||e){if(a!==""){var A=Wv(a,10);if(A>65535)return DA;n.port=n.isSpecial()&&A===qp[n.scheme]?null:A,a=""}if(e)return;i=Nc;continue}else return DA;break;case Db:if(n.scheme="file",h==="/"||h==="\\")i=qA;else if(t&&t.scheme==="file")switch(h){case fs:n.host=t.host,n.path=Fs(t.path),n.query=t.query;break;case"?":n.host=t.host,n.path=Fs(t.path),n.query="",i=$u;break;case"#":n.host=t.host,n.path=Fs(t.path),n.query=t.query,n.fragment="",i=Wa;break;default:NA(Ud(Fs(d,s),""))||(n.host=t.host,n.path=Fs(t.path),n.shortenPath()),i=ca;continue}else{i=ca;continue}break;case qA:if(h==="/"||h==="\\"){i=Nb;break}t&&t.scheme==="file"&&!NA(Ud(Fs(d,s),""))&&(jd(t.path[0],!0)?qc(n.path,t.path[0]):n.host=t.host),i=ca;continue;case Nb:if(h===fs||h==="/"||h==="\\"||h==="?"||h==="#"){if(!e&&jd(a))i=ca;else if(a===""){if(n.host="",e)return;i=Nc}else{if(y=n.parseHost(a),y)return y;if(n.host==="localhost"&&(n.host=""),e)return;a="",i=Nc}continue}else a+=h;break;case Nc:if(n.isSpecial()){if(i=ca,h!=="/"&&h!=="\\")continue}else if(!e&&h==="?")n.query="",i=$u;else if(!e&&h==="#")n.fragment="",i=Wa;else if(h!==fs&&(i=ca,h!=="/"))continue;break;case ca:if(h===fs||h==="/"||h==="\\"&&n.isSpecial()||!e&&(h==="?"||h==="#")){if($me(a)?(n.shortenPath(),h!=="/"&&!(h==="\\"&&n.isSpecial())&&qc(n.path,"")):Ome(a)?h!=="/"&&!(h==="\\"&&n.isSpecial())&&qc(n.path,""):(n.scheme==="file"&&!n.path.length&&jd(a)&&(n.host&&(n.host=""),a=ms(a,0)+":"),qc(n.path,a)),a="",n.scheme==="file"&&(h===fs||h==="?"||h==="#"))for(;n.path.length>1&&n.path[0]==="";)vme(n.path);h==="?"?(n.query="",i=$u):h==="#"&&(n.fragment="",i=Wa)}else a+=Do(h,dF);break;case WA:h==="?"?(n.query="",i=$u):h==="#"?(n.fragment="",i=Wa):h!==fs&&(n.path[0]+=Do(h,pv));break;case $u:!e&&h==="#"?(n.fragment="",i=Wa):h!==fs&&(h==="'"&&n.isSpecial()?n.query+="%27":h==="#"?n.query+="%23":n.query+=Do(h,pv));break;case Wa:h!==fs&&(n.fragment+=Do(h,lF));break}s++}},parseHost:function(r){var e,t,n;if(ms(r,0)==="["){if(ms(r,r.length-1)!=="]"||(e=Pme(Yd(r,1,-1)),!e))return Ou;this.host=e}else if(this.isSpecial()){if(r=ame(r),Vs(Tme,r)||(e=Ime(r),e===null))return Ou;this.host=e}else{if(Vs(Eme,r))return Ou;for(e="",t=Dc(r),n=0;n<t.length;n++)e+=Do(t[n],pv);this.host=e}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||this.scheme==="file"},includesCredentials:function(){return this.username!==""||this.password!==""},isSpecial:function(){return kw(qp,this.scheme)},shortenPath:function(){var r=this.path,e=r.length;e&&(this.scheme!=="file"||e!==1||!jd(r[0],!0))&&r.length--},serialize:function(){var r=this,e=r.scheme,t=r.username,n=r.password,i=r.host,s=r.port,a=r.path,c=r.query,o=r.fragment,l=e+":";return i!==null?(l+="//",r.includesCredentials()&&(l+=t+(n?":"+n:"")+"@"),l+=Id(i),s!==null&&(l+=":"+s)):e==="file"&&(l+="//"),l+=r.cannotBeABaseURL?a[0]:a.length?"/"+Ud(a,"/"):"",c!==null&&(l+="?"+c),o!==null&&(l+="#"+o),l},setHref:function(r){var e=this.parse(r);if(e)throw new Rw(e);this.searchParams.update()},getOrigin:function(){var r=this.scheme,e=this.port;if(r==="blob")try{return new El(r.path[0]).origin}catch{return"null"}return r==="file"||!this.isSpecial()?"null":r+"://"+Id(this.host)+(e!==null?":"+e:"")},getProtocol:function(){return this.scheme+":"},setProtocol:function(r){this.parse(Va(r)+":",Pb)},getUsername:function(){return this.username},setUsername:function(r){var e=Dc(Va(r));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var t=0;t<e.length;t++)this.username+=Do(e[t],Ib)}},getPassword:function(){return this.password},setPassword:function(r){var e=Dc(Va(r));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var t=0;t<e.length;t++)this.password+=Do(e[t],Ib)}},getHost:function(){var r=this.host,e=this.port;return r===null?"":e===null?Id(r):Id(r)+":"+e},setHost:function(r){this.cannotBeABaseURL||this.parse(r,$b)},getHostname:function(){var r=this.host;return r===null?"":Id(r)},setHostname:function(r){this.cannotBeABaseURL||this.parse(r,xb)},getPort:function(){var r=this.port;return r===null?"":Va(r)},setPort:function(r){this.cannotHaveUsernamePasswordPort()||(r=Va(r),r===""?this.port=null:this.parse(r,Mb))},getPathname:function(){var r=this.path;return this.cannotBeABaseURL?r[0]:r.length?"/"+Ud(r,"/"):""},setPathname:function(r){this.cannotBeABaseURL||(this.path=[],this.parse(r,Nc))},getSearch:function(){var r=this.query;return r?"?"+r:""},setSearch:function(r){r=Va(r),r===""?this.query=null:(ms(r,0)==="?"&&(r=Yd(r,1)),this.query="",this.parse(r,$u)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var r=this.fragment;return r?"#"+r:""},setHash:function(r){if(r=Va(r),r===""){this.fragment=null;return}ms(r,0)==="#"&&(r=Yd(r,1)),this.fragment="",this.parse(r,Wa)},update:function(){this.query=this.searchParams.serialize()||null}};var El=function(e){var t=ime(this,mi),n=ume(arguments.length,1)>1?arguments[1]:void 0,i=cme(t,new UT(e,!1,n));NT||(t.href=i.serialize(),t.origin=i.getOrigin(),t.protocol=i.getProtocol(),t.username=i.getUsername(),t.password=i.getPassword(),t.host=i.getHost(),t.hostname=i.getHostname(),t.port=i.getPort(),t.pathname=i.getPathname(),t.search=i.getSearch(),t.searchParams=i.getSearchParams(),t.hash=i.getHash())},mi=El.prototype,hs=function(r,e){return{get:function(){return qv(this)[r]()},set:e&&function(t){return qv(this)[e](t)},configurable:!0,enumerable:!0}};NT&&(ds(mi,"href",hs("serialize","setHref")),ds(mi,"origin",hs("getOrigin")),ds(mi,"protocol",hs("getProtocol","setProtocol")),ds(mi,"username",hs("getUsername","setUsername")),ds(mi,"password",hs("getPassword","setPassword")),ds(mi,"host",hs("getHost","setHost")),ds(mi,"hostname",hs("getHostname","setHostname")),ds(mi,"port",hs("getPort","setPort")),ds(mi,"pathname",hs("getPathname","setPathname")),ds(mi,"search",hs("getSearch","setSearch")),ds(mi,"searchParams",hs("getSearchParams")),ds(mi,"hash",hs("getHash","setHash")));Bv(mi,"toJSON",function(){return qv(this).serialize()},{enumerable:!0});Bv(mi,"toString",function(){return qv(this).serialize()},{enumerable:!0});if(Rd){var HA=Rd.createObjectURL,VA=Rd.revokeObjectURL;HA&&Bv(El,"createObjectURL",xA(HA,Rd)),VA&&Bv(El,"revokeObjectURL",xA(VA,Rd))}ome(El,"URL");rme({global:!0,constructor:!0,forced:!nme,sham:!NT},{URL:El});/*
387
387
  @license