@ujet/websdk-headless 3.6.3 → 3.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var wI=Object.defineProperty;var SI=(e,r,t)=>r in e?wI(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var pt=(e,r,t)=>SI(e,typeof r!="symbol"?r+"":r,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function TI(e,r){for(var t=0;t<r.length;t++){const n=r[t];if(typeof n!="string"&&!Array.isArray(n)){for(const i in n)if(i!=="default"&&!(i in e)){const a=Object.getOwnPropertyDescriptor(n,i);a&&Object.defineProperty(e,i,a.get?a:{enumerable:!0,get:()=>n[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}var Qs=(e=>(e.WAITING="waiting",e.READY="ready",e.IN_PROGRESS="in_progress",e.FINISHED="finished",e))(Qs||{});const CI="prod",Fv="3.6.3",Bg="https://main.api.ujet.co",Br={companyId:"",tenant:"",trackerId:"",deviceId:"",application:"websdk",version:Fv};/*! @license DOMPurify 3.2.4 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.4/LICENSE */const{entries:Q0,setPrototypeOf:qg,isFrozen:EI,getPrototypeOf:kI,getOwnPropertyDescriptor:RI}=Object;let{freeze:tn,seal:Fn,create:Z0}=Object,{apply:nh,construct:ih}=typeof Reflect<"u"&&Reflect;tn||(tn=function(r){return r});Fn||(Fn=function(r){return r});nh||(nh=function(r,t,n){return r.apply(t,n)});ih||(ih=function(r,t){return new r(...t)});const Qu=rn(Array.prototype.forEach),$I=rn(Array.prototype.lastIndexOf),zg=rn(Array.prototype.pop),Co=rn(Array.prototype.push),II=rn(Array.prototype.splice),ol=rn(String.prototype.toLowerCase),Vf=rn(String.prototype.toString),Wg=rn(String.prototype.match),Eo=rn(String.prototype.replace),OI=rn(String.prototype.indexOf),AI=rn(String.prototype.trim),Xn=rn(Object.prototype.hasOwnProperty),Xr=rn(RegExp.prototype.test),ko=PI(TypeError);function rn(e){return function(r){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return nh(e,r,n)}}function PI(e){return function(){for(var r=arguments.length,t=new Array(r),n=0;n<r;n++)t[n]=arguments[n];return ih(e,t)}}function Mt(e,r){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ol;qg&&qg(e,null);let n=r.length;for(;n--;){let i=r[n];if(typeof i=="string"){const a=t(i);a!==i&&(EI(r)||(r[n]=a),i=a)}e[i]=!0}return e}function MI(e){for(let r=0;r<e.length;r++)Xn(e,r)||(e[r]=null);return e}function Qa(e){const r=Z0(null);for(const[t,n]of Q0(e))Xn(e,t)&&(Array.isArray(n)?r[t]=MI(n):n&&typeof n=="object"&&n.constructor===Object?r[t]=Qa(n):r[t]=n);return r}function Ro(e,r){for(;e!==null;){const n=RI(e,r);if(n){if(n.get)return rn(n.get);if(typeof n.value=="function")return rn(n.value)}e=kI(e)}function t(){return null}return t}const Hg=tn(["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","section","select","shadow","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"]),Kf=tn(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Jf=tn(["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"]),xI=tn(["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"]),Yf=tn(["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"]),NI=tn(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Gg=tn(["#text"]),Vg=tn(["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","face","for","headers","height","hidden","high","href","hreflang","id","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","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Xf=tn(["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","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"]),Kg=tn(["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"]),Zu=tn(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),LI=Fn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),DI=Fn(/<%[\w\W]*|[\w\W]*%>/gm),jI=Fn(/\$\{[\w\W]*/gm),FI=Fn(/^data-[\-\w.\u00B7-\uFFFF]+$/),UI=Fn(/^aria-[\-\w]+$/),eT=Fn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),BI=Fn(/^(?:\w+script|data):/i),qI=Fn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),tT=Fn(/^html$/i),zI=Fn(/^[a-z][.\w]*(-[.\w]+)+$/i);var Jg=Object.freeze({__proto__:null,ARIA_ATTR:UI,ATTR_WHITESPACE:qI,CUSTOM_ELEMENT:zI,DATA_ATTR:FI,DOCTYPE_NAME:tT,ERB_EXPR:DI,IS_ALLOWED_URI:eT,IS_SCRIPT_OR_DATA:BI,MUSTACHE_EXPR:LI,TMPLIT_EXPR:jI});const $o={element:1,text:3,progressingInstruction:7,comment:8,document:9},WI=function(){return typeof window>"u"?null:window},HI=function(r,t){if(typeof r!="object"||typeof r.createPolicy!="function")return null;let n=null;const i="data-tt-policy-suffix";t&&t.hasAttribute(i)&&(n=t.getAttribute(i));const a="dompurify"+(n?"#"+n:"");try{return r.createPolicy(a,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},Yg=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function rT(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:WI();const r=rt=>rT(rt);if(r.version="3.2.4",r.removed=[],!e||!e.document||e.document.nodeType!==$o.document||!e.Element)return r.isSupported=!1,r;let{document:t}=e;const n=t,i=n.currentScript,{DocumentFragment:a,HTMLTemplateElement:s,Node:o,Element:u,NodeFilter:c,NamedNodeMap:l=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:p,DOMParser:v,trustedTypes:m}=e,_=u.prototype,T=Ro(_,"cloneNode"),I=Ro(_,"remove"),$=Ro(_,"nextSibling"),x=Ro(_,"childNodes"),N=Ro(_,"parentNode");if(typeof s=="function"){const rt=t.createElement("template");rt.content&&rt.content.ownerDocument&&(t=rt.content.ownerDocument)}let j,X="";const{implementation:J,createNodeIterator:G,createDocumentFragment:L,getElementsByTagName:re}=t,{importNode:ue}=n;let ee=Yg();r.isSupported=typeof Q0=="function"&&typeof N=="function"&&J&&J.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:ye,ERB_EXPR:Z,TMPLIT_EXPR:qe,DATA_ATTR:Qe,ARIA_ATTR:Nt,IS_SCRIPT_OR_DATA:vt,ATTR_WHITESPACE:Pe,CUSTOM_ELEMENT:me}=Jg;let{IS_ALLOWED_URI:he}=Jg,P=null;const Oe=Mt({},[...Hg,...Kf,...Jf,...Yf,...Gg]);let He=null;const Fe=Mt({},[...Vg,...Xf,...Kg,...Zu]);let be=Object.seal(Z0(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}})),Q=null,Ot=null,we=!0,fe=!0,Et=!1,De=!0,Dt=!1,ht=!0,Te=!1,ct=!1,wt=!1,ke=!1,Bt=!1,dt=!1,qt=!0,sr=!1;const Ue="user-content-";let Tr=!0,mr=!1,Ct={},Rt=null;const yt=Mt({},["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 ot=null;const Ft=Mt({},["audio","video","img","source","image","track"]);let At=null;const cr=Mt({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Cr="http://www.w3.org/1998/Math/MathML",Dr="http://www.w3.org/2000/svg",gr="http://www.w3.org/1999/xhtml";let zt=gr,lr=!1,ve=null;const _e=Mt({},[Cr,Dr,gr],Vf);let se=Mt({},["mi","mo","mn","ms","mtext"]),pe=Mt({},["annotation-xml"]);const ce=Mt({},["title","style","font","a","script"]);let ge=null;const Ee=["application/xhtml+xml","text/html"],te="text/html";let ae=null,V=null;const oe=t.createElement("form"),K=function(Y){return Y instanceof RegExp||Y instanceof Function},xe=function(){let Y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(V&&V===Y)){if((!Y||typeof Y!="object")&&(Y={}),Y=Qa(Y),ge=Ee.indexOf(Y.PARSER_MEDIA_TYPE)===-1?te:Y.PARSER_MEDIA_TYPE,ae=ge==="application/xhtml+xml"?Vf:ol,P=Xn(Y,"ALLOWED_TAGS")?Mt({},Y.ALLOWED_TAGS,ae):Oe,He=Xn(Y,"ALLOWED_ATTR")?Mt({},Y.ALLOWED_ATTR,ae):Fe,ve=Xn(Y,"ALLOWED_NAMESPACES")?Mt({},Y.ALLOWED_NAMESPACES,Vf):_e,At=Xn(Y,"ADD_URI_SAFE_ATTR")?Mt(Qa(cr),Y.ADD_URI_SAFE_ATTR,ae):cr,ot=Xn(Y,"ADD_DATA_URI_TAGS")?Mt(Qa(Ft),Y.ADD_DATA_URI_TAGS,ae):Ft,Rt=Xn(Y,"FORBID_CONTENTS")?Mt({},Y.FORBID_CONTENTS,ae):yt,Q=Xn(Y,"FORBID_TAGS")?Mt({},Y.FORBID_TAGS,ae):{},Ot=Xn(Y,"FORBID_ATTR")?Mt({},Y.FORBID_ATTR,ae):{},Ct=Xn(Y,"USE_PROFILES")?Y.USE_PROFILES:!1,we=Y.ALLOW_ARIA_ATTR!==!1,fe=Y.ALLOW_DATA_ATTR!==!1,Et=Y.ALLOW_UNKNOWN_PROTOCOLS||!1,De=Y.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Dt=Y.SAFE_FOR_TEMPLATES||!1,ht=Y.SAFE_FOR_XML!==!1,Te=Y.WHOLE_DOCUMENT||!1,ke=Y.RETURN_DOM||!1,Bt=Y.RETURN_DOM_FRAGMENT||!1,dt=Y.RETURN_TRUSTED_TYPE||!1,wt=Y.FORCE_BODY||!1,qt=Y.SANITIZE_DOM!==!1,sr=Y.SANITIZE_NAMED_PROPS||!1,Tr=Y.KEEP_CONTENT!==!1,mr=Y.IN_PLACE||!1,he=Y.ALLOWED_URI_REGEXP||eT,zt=Y.NAMESPACE||gr,se=Y.MATHML_TEXT_INTEGRATION_POINTS||se,pe=Y.HTML_INTEGRATION_POINTS||pe,be=Y.CUSTOM_ELEMENT_HANDLING||{},Y.CUSTOM_ELEMENT_HANDLING&&K(Y.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(be.tagNameCheck=Y.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Y.CUSTOM_ELEMENT_HANDLING&&K(Y.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(be.attributeNameCheck=Y.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Y.CUSTOM_ELEMENT_HANDLING&&typeof Y.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(be.allowCustomizedBuiltInElements=Y.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Dt&&(fe=!1),Bt&&(ke=!0),Ct&&(P=Mt({},Gg),He=[],Ct.html===!0&&(Mt(P,Hg),Mt(He,Vg)),Ct.svg===!0&&(Mt(P,Kf),Mt(He,Xf),Mt(He,Zu)),Ct.svgFilters===!0&&(Mt(P,Jf),Mt(He,Xf),Mt(He,Zu)),Ct.mathMl===!0&&(Mt(P,Yf),Mt(He,Kg),Mt(He,Zu))),Y.ADD_TAGS&&(P===Oe&&(P=Qa(P)),Mt(P,Y.ADD_TAGS,ae)),Y.ADD_ATTR&&(He===Fe&&(He=Qa(He)),Mt(He,Y.ADD_ATTR,ae)),Y.ADD_URI_SAFE_ATTR&&Mt(At,Y.ADD_URI_SAFE_ATTR,ae),Y.FORBID_CONTENTS&&(Rt===yt&&(Rt=Qa(Rt)),Mt(Rt,Y.FORBID_CONTENTS,ae)),Tr&&(P["#text"]=!0),Te&&Mt(P,["html","head","body"]),P.table&&(Mt(P,["tbody"]),delete Q.tbody),Y.TRUSTED_TYPES_POLICY){if(typeof Y.TRUSTED_TYPES_POLICY.createHTML!="function")throw ko('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Y.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw ko('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');j=Y.TRUSTED_TYPES_POLICY,X=j.createHTML("")}else j===void 0&&(j=HI(m,i)),j!==null&&typeof X=="string"&&(X=j.createHTML(""));tn&&tn(Y),V=Y}},Ce=Mt({},[...Kf,...Jf,...xI]),Ve=Mt({},[...Yf,...NI]),ze=function(Y){let Ae=N(Y);(!Ae||!Ae.tagName)&&(Ae={namespaceURI:zt,tagName:"template"});const Ke=ol(Y.tagName),Pt=ol(Ae.tagName);return ve[Y.namespaceURI]?Y.namespaceURI===Dr?Ae.namespaceURI===gr?Ke==="svg":Ae.namespaceURI===Cr?Ke==="svg"&&(Pt==="annotation-xml"||se[Pt]):!!Ce[Ke]:Y.namespaceURI===Cr?Ae.namespaceURI===gr?Ke==="math":Ae.namespaceURI===Dr?Ke==="math"&&pe[Pt]:!!Ve[Ke]:Y.namespaceURI===gr?Ae.namespaceURI===Dr&&!pe[Pt]||Ae.namespaceURI===Cr&&!se[Pt]?!1:!Ve[Ke]&&(ce[Ke]||!Ce[Ke]):!!(ge==="application/xhtml+xml"&&ve[Y.namespaceURI]):!1},We=function(Y){Co(r.removed,{element:Y});try{N(Y).removeChild(Y)}catch{I(Y)}},Ze=function(Y,Ae){try{Co(r.removed,{attribute:Ae.getAttributeNode(Y),from:Ae})}catch{Co(r.removed,{attribute:null,from:Ae})}if(Ae.removeAttribute(Y),Y==="is")if(ke||Bt)try{We(Ae)}catch{}else try{Ae.setAttribute(Y,"")}catch{}},tt=function(Y){let Ae=null,Ke=null;if(wt)Y="<remove></remove>"+Y;else{const $t=Wg(Y,/^[\r\n\t ]+/);Ke=$t&&$t[0]}ge==="application/xhtml+xml"&&zt===gr&&(Y='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+Y+"</body></html>");const Pt=j?j.createHTML(Y):Y;if(zt===gr)try{Ae=new v().parseFromString(Pt,ge)}catch{}if(!Ae||!Ae.documentElement){Ae=J.createDocument(zt,"template",null);try{Ae.documentElement.innerHTML=lr?X:Pt}catch{}}const nr=Ae.body||Ae.documentElement;return Y&&Ke&&nr.insertBefore(t.createTextNode(Ke),nr.childNodes[0]||null),zt===gr?re.call(Ae,Te?"html":"body")[0]:Te?Ae.documentElement:nr},Ye=function(Y){return G.call(Y.ownerDocument||Y,Y,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},et=function(Y){return Y instanceof p&&(typeof Y.nodeName!="string"||typeof Y.textContent!="string"||typeof Y.removeChild!="function"||!(Y.attributes instanceof l)||typeof Y.removeAttribute!="function"||typeof Y.setAttribute!="function"||typeof Y.namespaceURI!="string"||typeof Y.insertBefore!="function"||typeof Y.hasChildNodes!="function")},nt=function(Y){return typeof o=="function"&&Y instanceof o};function it(rt,Y,Ae){Qu(rt,Ke=>{Ke.call(r,Y,Ae,V)})}const yr=function(Y){let Ae=null;if(it(ee.beforeSanitizeElements,Y,null),et(Y))return We(Y),!0;const Ke=ae(Y.nodeName);if(it(ee.uponSanitizeElement,Y,{tagName:Ke,allowedTags:P}),Y.hasChildNodes()&&!nt(Y.firstElementChild)&&Xr(/<[/\w]/g,Y.innerHTML)&&Xr(/<[/\w]/g,Y.textContent)||Y.nodeType===$o.progressingInstruction||ht&&Y.nodeType===$o.comment&&Xr(/<[/\w]/g,Y.data))return We(Y),!0;if(!P[Ke]||Q[Ke]){if(!Q[Ke]&&lt(Ke)&&(be.tagNameCheck instanceof RegExp&&Xr(be.tagNameCheck,Ke)||be.tagNameCheck instanceof Function&&be.tagNameCheck(Ke)))return!1;if(Tr&&!Rt[Ke]){const Pt=N(Y)||Y.parentNode,nr=x(Y)||Y.childNodes;if(nr&&Pt){const $t=nr.length;for(let ir=$t-1;ir>=0;--ir){const Pr=T(nr[ir],!0);Pr.__removalCount=(Y.__removalCount||0)+1,Pt.insertBefore(Pr,$(Y))}}}return We(Y),!0}return Y instanceof u&&!ze(Y)||(Ke==="noscript"||Ke==="noembed"||Ke==="noframes")&&Xr(/<\/no(script|embed|frames)/i,Y.innerHTML)?(We(Y),!0):(Dt&&Y.nodeType===$o.text&&(Ae=Y.textContent,Qu([ye,Z,qe],Pt=>{Ae=Eo(Ae,Pt," ")}),Y.textContent!==Ae&&(Co(r.removed,{element:Y.cloneNode()}),Y.textContent=Ae)),it(ee.afterSanitizeElements,Y,null),!1)},fr=function(Y,Ae,Ke){if(qt&&(Ae==="id"||Ae==="name")&&(Ke in t||Ke in oe))return!1;if(!(fe&&!Ot[Ae]&&Xr(Qe,Ae))){if(!(we&&Xr(Nt,Ae))){if(!He[Ae]||Ot[Ae]){if(!(lt(Y)&&(be.tagNameCheck instanceof RegExp&&Xr(be.tagNameCheck,Y)||be.tagNameCheck instanceof Function&&be.tagNameCheck(Y))&&(be.attributeNameCheck instanceof RegExp&&Xr(be.attributeNameCheck,Ae)||be.attributeNameCheck instanceof Function&&be.attributeNameCheck(Ae))||Ae==="is"&&be.allowCustomizedBuiltInElements&&(be.tagNameCheck instanceof RegExp&&Xr(be.tagNameCheck,Ke)||be.tagNameCheck instanceof Function&&be.tagNameCheck(Ke))))return!1}else if(!At[Ae]){if(!Xr(he,Eo(Ke,Pe,""))){if(!((Ae==="src"||Ae==="xlink:href"||Ae==="href")&&Y!=="script"&&OI(Ke,"data:")===0&&ot[Y])){if(!(Et&&!Xr(vt,Eo(Ke,Pe,"")))){if(Ke)return!1}}}}}}return!0},lt=function(Y){return Y!=="annotation-xml"&&Wg(Y,me)},Wr=function(Y){it(ee.beforeSanitizeAttributes,Y,null);const{attributes:Ae}=Y;if(!Ae||et(Y))return;const Ke={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:He,forceKeepAttr:void 0};let Pt=Ae.length;for(;Pt--;){const nr=Ae[Pt],{name:$t,namespaceURI:ir,value:Pr}=nr,Mr=ae($t);let dr=$t==="value"?Pr:AI(Pr);if(Ke.attrName=Mr,Ke.attrValue=dr,Ke.keepAttr=!0,Ke.forceKeepAttr=void 0,it(ee.uponSanitizeAttribute,Y,Ke),dr=Ke.attrValue,sr&&(Mr==="id"||Mr==="name")&&(Ze($t,Y),dr=Ue+dr),ht&&Xr(/((--!?|])>)|<\/(style|title)/i,dr)){Ze($t,Y);continue}if(Ke.forceKeepAttr||(Ze($t,Y),!Ke.keepAttr))continue;if(!De&&Xr(/\/>/i,dr)){Ze($t,Y);continue}Dt&&Qu([ye,Z,qe],Hr=>{dr=Eo(dr,Hr," ")});const $n=ae(Y.nodeName);if(fr($n,Mr,dr)){if(j&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!ir)switch(m.getAttributeType($n,Mr)){case"TrustedHTML":{dr=j.createHTML(dr);break}case"TrustedScriptURL":{dr=j.createScriptURL(dr);break}}try{ir?Y.setAttributeNS(ir,$t,dr):Y.setAttribute($t,dr),et(Y)?We(Y):zg(r.removed)}catch{}}}it(ee.afterSanitizeAttributes,Y,null)},cn=function rt(Y){let Ae=null;const Ke=Ye(Y);for(it(ee.beforeSanitizeShadowDOM,Y,null);Ae=Ke.nextNode();)it(ee.uponSanitizeShadowNode,Ae,null),yr(Ae),Wr(Ae),Ae.content instanceof a&&rt(Ae.content);it(ee.afterSanitizeShadowDOM,Y,null)};return r.sanitize=function(rt){let Y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Ae=null,Ke=null,Pt=null,nr=null;if(lr=!rt,lr&&(rt="<!-->"),typeof rt!="string"&&!nt(rt))if(typeof rt.toString=="function"){if(rt=rt.toString(),typeof rt!="string")throw ko("dirty is not a string, aborting")}else throw ko("toString is not a function");if(!r.isSupported)return rt;if(ct||xe(Y),r.removed=[],typeof rt=="string"&&(mr=!1),mr){if(rt.nodeName){const Pr=ae(rt.nodeName);if(!P[Pr]||Q[Pr])throw ko("root node is forbidden and cannot be sanitized in-place")}}else if(rt instanceof o)Ae=tt("<!---->"),Ke=Ae.ownerDocument.importNode(rt,!0),Ke.nodeType===$o.element&&Ke.nodeName==="BODY"||Ke.nodeName==="HTML"?Ae=Ke:Ae.appendChild(Ke);else{if(!ke&&!Dt&&!Te&&rt.indexOf("<")===-1)return j&&dt?j.createHTML(rt):rt;if(Ae=tt(rt),!Ae)return ke?null:dt?X:""}Ae&&wt&&We(Ae.firstChild);const $t=Ye(mr?rt:Ae);for(;Pt=$t.nextNode();)yr(Pt),Wr(Pt),Pt.content instanceof a&&cn(Pt.content);if(mr)return rt;if(ke){if(Bt)for(nr=L.call(Ae.ownerDocument);Ae.firstChild;)nr.appendChild(Ae.firstChild);else nr=Ae;return(He.shadowroot||He.shadowrootmode)&&(nr=ue.call(n,nr,!0)),nr}let ir=Te?Ae.outerHTML:Ae.innerHTML;return Te&&P["!doctype"]&&Ae.ownerDocument&&Ae.ownerDocument.doctype&&Ae.ownerDocument.doctype.name&&Xr(tT,Ae.ownerDocument.doctype.name)&&(ir="<!DOCTYPE "+Ae.ownerDocument.doctype.name+`>
2
- `+ir),Dt&&Qu([ye,Z,qe],Pr=>{ir=Eo(ir,Pr," ")}),j&&dt?j.createHTML(ir):ir},r.setConfig=function(){let rt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};xe(rt),ct=!0},r.clearConfig=function(){V=null,ct=!1},r.isValidAttribute=function(rt,Y,Ae){V||xe({});const Ke=ae(rt),Pt=ae(Y);return fr(Ke,Pt,Ae)},r.addHook=function(rt,Y){typeof Y=="function"&&Co(ee[rt],Y)},r.removeHook=function(rt,Y){if(Y!==void 0){const Ae=$I(ee[rt],Y);return Ae===-1?void 0:II(ee[rt],Ae,1)[0]}return zg(ee[rt])},r.removeHooks=function(rt){ee[rt]=[]},r.removeAllHooks=function(){ee=Yg()},r}var GI=rT();const VI={ALLOWED_TAGS:["b","i","em","strong","p","br","ul","ol","li","a"],ALLOWED_ATTR:["href","src","alt","title","target","class","id","style"],ALLOW_DATA_ATTR:!1,FORBID_TAGS:["img","iframe","object","input","style","script","embed","svg","video","audio","body","input","form","link"],FORBID_ATTR:["onerror","onclick","onload","onmouseover","onfocus","onblur","onchange","onsubmit","scr","href","style","action","value"],IN_PLACE:!0},KI="javascript:";function JI(e){return(e==null?void 0:e.constructor)===Object}async function Xg(e,r=3){let t=0,n;for(;t<=r;){t+=1;try{return await e()}catch(i){n=i,console.error(i),await YI(1e3*Math.pow(2,t))}}throw n}function YI(e){return new Promise(r=>{setTimeout(()=>{r(0)},e)})}function XI(){return Math.random().toString(36).slice(2)}const QI=new TextDecoder,ZI=e=>{const r=atob(e),t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r.charCodeAt(n);return QI.decode(t)},eO=e=>e.length===0,tO=(...e)=>e.every(eO),nT=e=>{const r=GI.sanitize(e,VI);return r.includes(KI)?(console.warn("Suspicious content detected and removed."),""):r},Qg=[];class $a{constructor(r){pt(this,"channel");this.channel=r}static addHandler(r){Qg.push(r)}debug(...r){this._log("debug",...r)}info(...r){this._log("info",...r)}warn(...r){this._log("warn",...r)}error(...r){this._log("error",...r)}_log(r,...t){Qg.forEach(n=>{n(this.channel,r,...t)})}}const rO=(e,r,...t)=>{console[r](`[${r}][${e}]`,...t)},nO=e=>{let r=[],t;return(i,a,...s)=>{a==="debug"||i==="communicator"||(r.push(iO(i,a,...s)),clearTimeout(t),t=window.setTimeout(()=>{if(r.length){const o={num_of_logs:r.length,logs:r};e(o)}r=[]},2e3))}};function iO(e,r,...t){let n=t.pop();typeof n=="string"&&(t.push(n),n={});const i=t.join(" "),a={loglevel:r,channel:e,timestamp:new Date().toISOString(),application:Br.application,version:Br.version,device:Br.deviceId,tenant:Br.tenant,company_id:Br.companyId,location_url:location.href,data:oO(n),message:Uv(i)};return Br.trackerId&&(a.tracker_id=Br.trackerId),a}const aO=["user","phone","phone_number","phoneNumber","email"],sO=[/(?: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];function Uv(e){return typeof e=="string"?sO.forEach(r=>{e=e.replace(r,"__MASKED__")}):e&&JI(e)&&(e={...e},Object.keys(e).forEach(r=>{aO.indexOf(r)!==-1?e[r]="__MASKED__":Uv(e[r])})),e}function oO(e){if(e.error){const r=e.error;return{error:{name:r.name,message:r.message,stack:r.stack}}}return Uv(e.data)}const Qf=new $a("communicator");let Zg=!1;class uO{constructor(r,t){pt(this,"events");pt(this,"options");pt(this,"channel");pt(this,"authenticate");pt(this,"channelReady",!1);pt(this,"__authed",!1);pt(this,"pending",[]);pt(this,"promises",{});pt(this,"user");pt(this,"iframe");this.authenticate=r.authenticate,this.events=t,this.options=cO(r),this.channel=new MessageChannel,this.useConnect(this.options)}useConnect(r){const t=document.createElement("iframe");t.src=r.bridge,t.setAttribute("style","display:none");let n="*";/^https:/.test(r.bridge)&&(n=new URL(r.bridge).origin),t.addEventListener("load",()=>{if(Qf.debug("iframe bridge ready for",n),!this.channelReady){const i={type:"_init",data:r};t.contentWindow.postMessage(i,n,[this.channel.port2])}}),this.channel.port1.onmessage=i=>{this.receiveMessage(i)},document.body.appendChild(t),this.iframe=t}receiveMessage(r){const t=r.data;if(t){if(Qf.debug("receiveMessage",t),t.type==="ready")this.channelReady=!0,Br.deviceId=t.result.deviceId,Br.deviceId||console.error("Device Id has not been provided. SDK will not work properly."),this.runPending(),this.events.triggerEvent("ready");else if(t.type==="callback"&&t.callbackId){const[n,i]=this.promises[t.callbackId];t.error?i(t.error):n(t.result),delete this.promises[t.callbackId]}else if(t.type==="refreshToken")this.refreshToken();else if(t.request==="_auth"&&(this.events.triggerEvent("authenticated"),t.result&&t.result.log_proxy_url&&!Zg)){Zg=!0;const n=nO(i=>{this.postMessage({type:"_log",data:i})});$a.addHandler(n)}}}postMessage(r){this.channelReady?(Qf.debug("postMessage",r),this.channel.port1.postMessage(r)):this.pending.push(r)}runPending(){for(;this.pending.length;){const r=this.pending.shift();this.postMessage(r)}}postPromise(r,t){return new Promise((n,i)=>{const a=XI()+"_"+Date.now();this.promises[a]=[n,i];const s={type:r,callbackId:a,data:t};this.postMessage(s)})}async refreshToken(){this.__authed=!0;const r=await this.authenticate(),t=["twilio_chat","nexmo_chat"];this.options.cobrowse&&t.push("cobrowse");const i={type:"_auth",data:{modules:t,user:{token:r.token,company_id:this.options.companyId}}};this.postMessage(i);const a=JSON.parse(ZI(r.token.split(".")[1]));if(this.user={identifier:a.identifier,name:a.name,email:a.email},this.events.triggerEvent("authenticate"),a.exp){let s;a.exp.toString().length===13?s=a.exp:a.exp.toString().length===10&&(s=a.exp*1e3),s&&setTimeout(()=>{this.refreshToken()},s-Date.now()-12e4)}}request(r,t){!this.__authed&&r!=="proactive_chat_triggers"&&this.refreshToken();const n={url:r,options:t};return this.postPromise("request",n)}destroy(){delete this.channel,this.iframe&&(document.body.removeChild(this.iframe),this.iframe=void 0)}}function cO(e){var a;let r=e.host;r||(e.tenant?r=Bg.replace("main.api",e.tenant+".api"):r=Bg);const t=e.lang||"en",n=!!((a=e.cobrowse)!=null&&a.enabled),i=e.bridge||"https://websdk.ujet.co/v3/bridge.html";return{host:r,lang:t,cobrowse:n,companyId:e.companyId,location:location.href,version:e.version||"3.6.3",bridge:i}}class Bv{constructor(){pt(this,"handlers",{})}addEventListener(r,t){this.handlers[r]||(this.handlers[r]=[]),this.handlers[r].push(t)}triggerEvent(r,t){const n=this.handlers[r];n&&n.forEach(i=>{i(t)})}removeEventListener(r,t){if(this.handlers[r]){const n=this.handlers[r].indexOf(t);n!==-1&&this.handlers[r].splice(n,1)}}destroy(){this.handlers={}}}function lO(e,r){const t={};return r.forEach(n=>{t[n.id]=n}),e.map(n=>{if(n.type==="server_message"){const i=n.message_id,a=t[i];iT(n,a.content)}return n})}function fO(e,r){return iT(e,r.content)}function iT(e,r){return Object.keys(r).forEach(t=>{e[t]=r[t]}),e}const ey={photo:2,video:2,audio:1,document:1};function dO(e){const r=e.toSorted((t,n)=>!t.groupMessageId||!n.groupMessageId||t.groupMessageId!==n.groupMessageId?0:(ey[n.type]||0)-(ey[t.type]||0));return r.forEach((t,n,i)=>{const a=i[n+1];a&&a.groupMessageId===t.groupMessageId&&t.$time&&(a.$time=t.$time,t.$time=null)}),r}const ty=new $a("MediaStore"),pO=window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB||window.OIndexedDB||window.msIndexedDB,hO="chat-media",ry=1,Cl="file";class aT{constructor(){pt(this,"db")}store(){return new Promise((r,t)=>{if(this.db)return r(ny(this.db));const n=pO.open(hO,ry);n.onerror=()=>{t(new Error("indexedDB open failed"))},n.onsuccess=()=>{const i=n.result;this.db=i,r(ny(i))},n.onupgradeneeded=i=>{const a=n.result;i.oldVersion>0&&i.oldVersion<ry&&(ty.info("deprecating media store"),a.deleteObjectStore(Cl)),ty.info("creating media store"),a.createObjectStore(Cl)}})}async save(r,t){(await this.store()).put({index:r,file:t},r)}async getAll(){const r=await this.store();return await new Promise((t,n)=>{const i=r.getAll();i.onerror=()=>{n(new Error("indexedDB getAll failed"))},i.onsuccess=()=>{t(i.result)}})}async getAllFiles(){const r={};return(await this.getAll()).forEach(n=>{r[n.index]=n.file}),r}async clear(){(await this.store()).clear()}}function ny(e){return e.transaction(Cl,"readwrite").objectStore(Cl)}class vO{constructor(){pt(this,"_hostPath","")}setPath(r){this._hostPath=r}getPath(){return this._hostPath}}const sT=new vO,mO=new $a("chat-provider");class qv{constructor(r,t,n){pt(this,"audio");pt(this,"issueChatToken");pt(this,"identity");pt(this,"channelId");pt(this,"region");pt(this,"inTask",!1);pt(this,"muted",!1);pt(this,"events");this.events=r,this.region=t.region,this.issueChatToken=n}ping(){if(!this.muted){if(!this.audio){sT.getPath();const r="https://websdk.ujet.co/v3/ping.mp3";this.audio=new window.Audio(r)}try{this.audio.play()}catch(r){mO.warn("Chat audio play failed",{error:r})}}}on(r,t){this.events.addEventListener(r,t)}off(r,t){this.events.removeEventListener(r,t)}trackInTask(r){r.type==="noti"&&r.event==="taskVaStarted"?this.inTask=!0:r.type==="noti"&&r.event==="taskVaFinished"&&(this.inTask=!1)}}pt(qv,"type","base");const oT={};function zv(e){oT[e.type]=e}function gO(e){return oT[e]}const uT=["assigned","va_assigned"],cT=["dismissed","va_dismissed"],yO=["va_assigned","va_dismissed"],bO=["queued",...uT,...cT],_O=["timeout","canceled","failed","finished"],Zf=new $a("Chat");class wO{constructor(r,t){pt(this,"provider");pt(this,"store");pt(this,"globalEvents");pt(this,"state");pt(this,"connected",!1);pt(this,"allowSkipVirtualAgent",!1);pt(this,"inEscalation",!1);pt(this,"events");pt(this,"cachedFiles");this.state=r,this.store=new aT,this.cachedFiles={},this.events=new Bv;const n=gO(this.state.provider_type);this.provider=new n(this.events,r,t)}_setGlobalEvents(r,t){this.globalEvents=r,this.on("message",n=>{if(n.content=nT(n.content),n.type==="server_message"){const i=n.message_id;t(this.id,i).then(a=>{n=fO(n,a),r.triggerEvent("chat.message",n)})}else n.type==="photo"||n.type==="video"?setTimeout(()=>{const i=n.$index.toString();n.file=this.cachedFiles[i],r.triggerEvent("chat.message",n)},100):(r.triggerEvent("chat.message",n),this.registerMessageEvents(n))}),this.on("memberJoined",n=>{r.triggerEvent("chat.memberJoined",n)}),this.on("memberLeft",n=>{r.triggerEvent("chat.memberLeft",n)}),this.on("typingStarted",n=>{r.triggerEvent("chat.typingStarted",n)}),this.on("typingEnded",n=>{r.triggerEvent("chat.typingEnded",n)})}get id(){return this.state.id}get menuId(){return this.state.menus[this.state.menus.length-1].id}get channelId(){return this.state.provider_channel_id}get lang(){return this.state.lang}get virtual(){return yO.indexOf(this.state.status)!==-1}get muted(){return this.provider.muted}set muted(r){this.provider.muted=r}get agent(){return this.virtual?this.state.external_agent?this.state.external_agent:this.state.virtual_agent:this.state.agent||this.state.virtual_agent}get allAgents(){return{virtual:this.state.all_virtual_agents,human:this.state.all_agents}}get userIdentity(){return this.provider.identity}get status(){return this.state.status}get postSessionStatus(){return this.state.post_session_transfer_status}get statusText(){return this.state.status_text}get cobrowsable(){return this.state.features.indexOf("cobrowse")!==-1}get ongoing(){return bO.indexOf(this.state.status)!=-1}get assigned(){return uT.indexOf(this.state.status)!=-1}get dismissed(){return cT.indexOf(this.state.status)!=-1}get ended(){return _O.indexOf(this.state.status)!=-1}get transcriptCount(){return this.state.transcript_requested_count}get createdAt(){return this.state.created_at}get inTask(){return this.provider.inTask}get feedbackType(){var r;return this.state.survey_enabled?"survey":(r=this.state.csat_settings)!=null&&r.enabled?"rate":"none"}get optInRequired(){return this.state.post_session_opt_in_required}get postSessionRequired(){return this.state.post_session_required}get postSessionInProgress(){return this.state.post_session_transfer_status===Qs.IN_PROGRESS}update(r){r.id==this.state.id&&(this.state=r,r.status==="canceled"?this.triggerEvent("ended",this):this.triggerEvent("updated",this))}on(r,t){this.events.addEventListener(r,t)}off(r,t){this.events.removeEventListener(r,t)}async connect(){try{return await Xg(()=>{var r;return(r=this.provider)==null?void 0:r.create()},3),await Xg(()=>{var r;return(r=this.provider)==null?void 0:r.join(this.state.provider_channel_id)},3),this.provider?(this.connected=!0,this.triggerEvent("connected",this),Zf.info("connected with provider",this.state.provider_type),!0):(Zf.info("connecting interrupted"),!1)}catch{return!1}}async disconnect(){this.connected=!1,this.triggerEvent("disconnected",this),this.events.destroy(),this.provider&&(await this.provider.destroy(),Zf.info("disconnect with provider",this.state.provider_type))}async sendMessage(r,t){const n=await this.provider.sendMessage(r);return t&&this.saveMedia(n,t),n}preview(r){if(!this.inTask)return this.provider.preview(r)}async fetchMessages(){if(this.connected){const r=await this.store.getAllFiles();return this.provider.fetchMessages(r)}else throw new Error("Please fetchMessages after chat connected.")}startTyping(){return this.provider.startTyping()}stopTyping(){return this.provider.stopTyping()}saveMedia(r,t){this.cachedFiles[r.toString()]=t,this.store.save(r,t)}async destroy(){await this.clearMediaStore(),this.connected&&await this.disconnect(),this.provider&&(this.triggerEvent("destroyed"),this.provider=null),this.events.destroy(),this.state=null}async clearMediaStore(){await this.store.clear()}_handleChatEndedEvent(r){this.disconnect(),r.timeout?(this.state.status="timeout",this.triggerEvent("timeout",this)):(this.state.status="finished",this.triggerEvent("ended",this))}triggerEvent(r,t){this.events.triggerEvent(r,t),this.globalEvents&&this.globalEvents.triggerEvent("chat."+r,t)}registerMessageEvents(r){r.event==="cobrowseRequestedFromAgent"?this.events.triggerEvent("_requestCobrowse","agent"):r.event==="cobrowseRequestedFromEndUser"?this.events.triggerEvent("_requestCobrowse","end_user"):r.event==="chatDismissed"?(this.state.status="dismissed",this.triggerEvent("dismissed",this)):r.event==="chatEnded"?this.events.triggerEvent("_chatEnded",r):r.event==="escalationStarted"?this.inEscalation=!0:(r.event==="escalationFailed"||r.event==="escalationAccepted")&&(this.inEscalation=!1)}}function lT(e){return e.map(SO).filter(r=>r.enabled)}function SO(e){const r={id:e.id,enabled:!0,channels:[],hidden:!!e.hidden};if(!e.name||!e.name.trim())return r.enabled=!1,r;r.name=e.name.trim();const t=TO(e);if(t&&(r.redirection=e.redirection),e.children&&e.children.length){const n=lT(e.children);return r.enabled=n.length>0||t,r.children=n,r}if(!e.channels)r.enabled=t;else{const{channels:n,deflection:i}=CO(e.channels);r.deflection=i,t||(r.channels=n),r.enabled=n.length>0||t}return r}function TO(e){let r=!1;const t=e.redirection;return t&&(t.option==="message"||t.option==="url")&&(r=!!t.data),r}function CO(e){let r=null;const t=[],n=e.chat,i=a=>{!a.deflection_type&&a.deflected_reason&&(a.deflection_type=a.deflected_reason),a.deflected===void 0&&a.deflection_type&&(a.deflected=!0),t.push(a)};return n&&n.deflected&&(r={enabled:!0,type:n.deflected_reason}),n&&(n.enabled||n.virtual_agent_available)&&i({...e.chat,type:"chat"}),e.voice_call&&e.voice_call.instant_enabled&&i({...e.voice_call,type:"instant_call"}),e.voice_call&&e.voice_call.schedule_enabled&&i({...e.voice_call,type:"scheduled_call",deflection_type:e.voice_call.schedule_deflection_type}),e.email&&e.email.enabled&&i({...e.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}),e.external_deflection_link&&e.external_deflection_link.enabled&&e.external_deflection_link.links.forEach(s=>{s.enabled&&i({...s,type:"external_link"})}),{channels:t,deflection:r}}const EO={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 kO(e){var t,n;return{languages:e.languages.filter(i=>i.enabled).map(i=>({lang:i.lang,name:i.name,localeName:EO[i.lang]})),name:e.display_name,subdomain:e.subdomain,support_email:e.support_email,action_tracking:e.action_tracking_enabled,email_transcripts:e.chat_settings.email_transcripts,message_preview:e.chat_settings.message_preview,email_enhancement:e.email_enhancement_enabled,display_history:((t=e.chat_settings.display_history)==null?void 0:t.enabled)&&((n=e.chat_settings.display_history)==null?void 0:n.to_end_user),use_recording:e.use_recording,use_web:e.use_web,cobrowse_domain:e.cobrowse_domain}}function iy(e){return e.chats=e.chats.map(r=>{const t=r.entries.map((n,i)=>RO(n,`${r.comm_id}-${i}`));return r.entries=dO(t),r}),e}function RO(e,r){var t;return{$index:e.timestamp,$sid:r,$timestamp:new Date(e.timestamp),$userType:e.role,$userId:((t=e.user_data)==null?void 0:t.id)||0,user:e.user_data,type:e.type,...e.body}}const ay=/Chrome/.test(navigator.userAgent);class $O{constructor(r){pt(this,"request");this.request=r}get(r,t){if(t){const n=[];Object.keys(t).forEach(i=>{const a=t[i];a!==void 0&&n.push(`${encodeURIComponent(i)}=${encodeURIComponent(a)}`)}),r+="?"+n.join("&")}return this.request(r,{method:"GET"})}post(r,t){const n={method:"POST"};return n.body=JSON.stringify(t),this.request(r,n)}patch(r,t){const n={method:"PATCH"};return n.body=JSON.stringify(t),this.request(r,n)}put(r,t){const n={method:"PUT"};return n.body=JSON.stringify(t),this.request(r,n)}async getTriggers(r){const t={"UJET-Company-Id":r};return(await this.request("proactive_chat_triggers",{method:"GET",headers:t})).data}trackClientEvents(r){return this.post("/client_events",{events:r})}async getCompany(){const r=await this.get("company");return kO(r.data)}async getMenus(r,t){const n={type:"web_menu",lang:r,direct_access_key:t},i=await this.get("menus",n),a={key:!!t,user:!1},s=i.headers["ujet-direct-access"];return s&&s!="false"&&(a.user=!0),{menus:lT(i.data),direct:a}}async getAfterHourMessage(r){return(await this.get(`audible_messages/${r}`)).data["after_hours.message"].text}async getTimeSlots(r,t="en"){return(await this.get(`menus/${r}/time_slots`,{type:"web_menu",lang:t})).data}async getWaitTimes(r,t="en"){return(await this.get(`menus/${r}/wait_times`,{type:"web_menu",lang:t})).data}async verifyForm(r){try{return await this.post("forms/verify",r),!0}catch{return!1}}async finishChat(r){return(await this.patch(`chats/${r}`,{status:"finished"})).data}async updatePostSession(r,t){const n={post_session_transfer_status:t};try{return(await this.patch(`chats/${r}`,n)).data}catch(i){if(t===Qs.IN_PROGRESS&&i.status===400)return(await this.patch(`chats/${r}`,n)).data;throw i}}async getChatDeflection(r){const{data:t}=await this.get(`chats/${r}/deflections`);return t&&t.enabled?t:null}sendChatCustomData(r,t){let n;return typeof t=="string"?n={signed:!0,signed_data:t}:n={signed:!1,data:t},this.post(`chats/${r}/custom_data`,n)}async downloadChatTranscript(r){return(await this.post(`chats/${r}/generate_transcript_pdf`,{})).data}async getPdfStatus(r){return await this.get(`chat_transcript_pdfs/${r}/download_transcript`)}sendChatTranscripts(r,t){return this.post(`chats/${r}/transcripts`,{emails:t.join(",")})}async listChatTaskMessages(r){return(await this.get(`chats/${r}/task_va_messages`)).data}async getChatTaskMessage(r,t){return(await this.get(`chats/${r}/task_va_messages/${t}`)).data}async sendChatTaskMessage(r,t){const n={content:{content:t,type:"text"}};return(await this.post(`chats/${r}/task_va_messages`,n)).data}escalateChat(r,t){return this.post(`chats/${r}/escalations`,t)}trackEscalation(r,t,n){return this.put(`chats/${r}/escalations/${t}`,{escalation_id:t,deflection_channel:n})}requestChatCobrowse(r,t){return this.post(`chats/${r}/cobrowse`,t)}rateChat(r,t){return this.patch(`chats/${r}/rating`,t)}async getChatSurvey(r){return(await this.get(`chats/${r}/survey`)).data}sendChatSurvey(r,t){const n={chat_id:r,answers:t};return this.put(`chats/${r}/survey`,n)}trackChatEndUserEvent(r,t){return this.post(`chats/${r}/end_user_event`,t)}async createChat(r,t,n,i){const a={chat:{menu_id:r,lang:t,email:n.email,greeting:n.greeting,trigger_id:n.trigger_id,ticket_id:n.ticket_id,custom_data:n.custom_data},cobrowsable:n.cobrowsable},o=(await this.post("chats",a)).data;return this.wrapChat(o,i)}async loadChat(r,t){const n=await this.getChat(r);return this.wrapChat(n,t)}async resumeChat(r,t){const n=await this.patch(`chats/${r}`,{status:"queued"});return this.wrapChat(n.data,t)}async getChatHistory(r=1){if(r===1){const{data:t}=await this.get("/chats/histories?page=1&per_page=2");return iy(t)}else{const{data:t}=await this.get(`/chats/histories?page=${r}&per_page=1`);return iy(t)}}async uploadChatFile(r,t){let n="file";/^image/.test(t.type)?n="photo":/^video/.test(t.type)?n="video":n="file";const i=t.name.replace(/\.[^.]+$/i,""),a=await this.post(`chats/${r}/${n}s/upload`,{filename:i}),s={file:t,fields:a.data.fields};ay&&(s.file=await fT(t));const u=(await this.request(a.data.url,s)).data.key,l=(await this.post(`chats/${r}/${n}s`,{chat_id:r,[n]:{s3_path:u,photo_type:n}})).data;return l.type=n,l}async getChat(r){return(await this.get(`chats/${r}`)).data}wrapChat(r,t){const n=async()=>(await this.post(`chats/${r.id}/tokens`,{provider_type:r.provider_type,device_id:t})).data,i=new wO(r,n),a=async s=>{if(i.status==="va_assigned"){const u=(await this.get(`menus/${i.menuId}/virtual_agent_settings`,{lang:i.lang})).data.allow_skip_virtual_agent;i.allowSkipVirtualAgent=u,i.update(s)}};if(i.channelId)i.connect(),a(r);else{const s=setInterval(async()=>{const o=await this.getChat(i.id);o.provider_channel_id?(clearInterval(s),i.state&&(i.update(o),i.connect(),a(o))):(o.status==="canceled"||o.status==="finished")&&clearInterval(s)},1500)}return i.on("initialized",async()=>{if(i.status==="queued"){const s=await this.getChat(i.id);i.update(s)}}),i.on("memberJoined",async()=>{const s=await this.getChat(i.id);i.update(s)}),i.on("memberLeft",async()=>{const s=await this.getChat(i.id);i.update(s)}),i.on("_chatEnded",async s=>{const o=await this.getChat(i.id);i.update(o),i.ended&&i._handleChatEndedEvent(s)}),i}async createCall(r,t,n){const i={type:n.scheduled_at?"web_scheduled_call":"web_instant_call",menu_id:r,lang:t,email:n.email,ticket_id:n.ticket_id,recording_permission:n.recording_permission||"recording_permission_not_asked",scheduled_at:n.scheduled_at,custom_data:n.custom_data,end_user:{phone_number:n.phone_number}},s=(await this.post("calls",{call:i,cobrowsable:!1})).data;return s.menu_id=s.selected_menu.id,s}async fetchCall(r){const n=(await this.get(`calls/${r}`)).data;return n.menu_id=n.selected_menu.id,n}async cancelCall(r){const n=(await this.patch(`calls/${r}`,{status:"failed",fail_reason:"canceled"})).data;return n.menu_id=n.selected_menu.id,n}async listFileTypes(){return(await this.get("email_prohibited_file_types")).data}async createEmail(r,t,n){const i={end_user_email:n.email,email_body:n.content,menu_id:r.toString(),lang:t};return n.name&&(i.end_user_name=n.name),n.recaptcha&&(i.recaptcha_response=n.recaptcha),n.files&&ay?i["email_attachments[]"]=await IO(n.files):n.files&&(i["email_attachments[]"]=[...n.files]),this.request("emails",{form:i})}async getMedia(r,t){const n=await this.get(`media/${r}?type=${t}`);if(!n.data)return null;const i=n.headers["x-file-name"];return new File([n.data],i,{type:n.data.type})}}function IO(e){return Promise.all(e.map(fT))}function fT(e){return new Promise((r,t)=>{const n=new FileReader;n.onload=()=>{const i=[n.result],a={type:e.type,lastModified:e.lastModified};r({name:e.name,fileBits:i,options:a})},n.onerror=t,n.readAsArrayBuffer(e)})}const ed="ujet:",Kr={set(e,r){return localStorage.setItem(ed+e,r)},get(e){return localStorage.getItem(ed+e)},del(e){return localStorage.removeItem(ed+e)}},OO=Date.now(),dT={href:window.location.href,interval:24*60*60};function AO(e){if(!Array.isArray(e)||!e.length)return null;const r=LO(),t=r===0,n=r+1;return DO(n),e.filter(a=>{const s=MO(a,dT.href),o=xO(a.visitor_type,t),u=n>=a.page_visit_count,c=!NO(a.id);return s&&o&&u&&c}).sort((a,s)=>a.stay_time-s.stay_time)[0]||null}function PO(e,r){const t=e.stay_time*1e3,n=Math.max(t-(Date.now()-OO),0);setTimeout(()=>{r(e),Kr.set(`trigger:${e.id}`,(Date.now()/1e3).toString())},n)}const MO=(e,r)=>{const{keywords_included_or:t=[],keywords_excluded_or:n=[],keywords_included:i=[],keywords_excluded:a=[]}=e;if(tO(t,n,i,a))return!0;if(t.length||n.length){const u=t.some(l=>l.every(p=>r.includes(p))),c=n.length>0&&n.every(l=>l.every(p=>!r.includes(p)));return u||c}const s=i.filter(u=>r.indexOf(u)!==-1).length,o=a.filter(u=>r.indexOf(u)===-1).length;return!!s||!!o};function xO(e,r){return e==="visitor_type_new"?r:e==="visitor_type_returning"?!r:!0}function NO(e){try{const r=parseInt(Kr.get(`trigger:${e}`),10);return Date.now()/1e3-r<dT.interval}catch{return!1}}function LO(){try{const e=Kr.get("visits");return e?parseInt(e,10):0}catch{return 0}}function DO(e){try{Kr.set("visits",e.toString())}catch(r){console.error(r)}}const jO=`<dialog open class="cobrowse-dialog" data-test-id="cobrowse-dialog">
1
+ "use strict";var wI=Object.defineProperty;var SI=(e,r,t)=>r in e?wI(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var pt=(e,r,t)=>SI(e,typeof r!="symbol"?r+"":r,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function TI(e,r){for(var t=0;t<r.length;t++){const n=r[t];if(typeof n!="string"&&!Array.isArray(n)){for(const i in n)if(i!=="default"&&!(i in e)){const a=Object.getOwnPropertyDescriptor(n,i);a&&Object.defineProperty(e,i,a.get?a:{enumerable:!0,get:()=>n[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}var Qs=(e=>(e.WAITING="waiting",e.READY="ready",e.IN_PROGRESS="in_progress",e.FINISHED="finished",e))(Qs||{});const CI="prod",Fv="3.6.4",Bg="https://main.api.ujet.co",Br={companyId:"",tenant:"",trackerId:"",deviceId:"",application:"websdk",version:Fv};/*! @license DOMPurify 3.2.4 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.4/LICENSE */const{entries:Q0,setPrototypeOf:qg,isFrozen:EI,getPrototypeOf:kI,getOwnPropertyDescriptor:RI}=Object;let{freeze:tn,seal:Fn,create:Z0}=Object,{apply:nh,construct:ih}=typeof Reflect<"u"&&Reflect;tn||(tn=function(r){return r});Fn||(Fn=function(r){return r});nh||(nh=function(r,t,n){return r.apply(t,n)});ih||(ih=function(r,t){return new r(...t)});const Qu=rn(Array.prototype.forEach),$I=rn(Array.prototype.lastIndexOf),zg=rn(Array.prototype.pop),Co=rn(Array.prototype.push),II=rn(Array.prototype.splice),ol=rn(String.prototype.toLowerCase),Vf=rn(String.prototype.toString),Wg=rn(String.prototype.match),Eo=rn(String.prototype.replace),OI=rn(String.prototype.indexOf),AI=rn(String.prototype.trim),Xn=rn(Object.prototype.hasOwnProperty),Xr=rn(RegExp.prototype.test),ko=PI(TypeError);function rn(e){return function(r){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return nh(e,r,n)}}function PI(e){return function(){for(var r=arguments.length,t=new Array(r),n=0;n<r;n++)t[n]=arguments[n];return ih(e,t)}}function Mt(e,r){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ol;qg&&qg(e,null);let n=r.length;for(;n--;){let i=r[n];if(typeof i=="string"){const a=t(i);a!==i&&(EI(r)||(r[n]=a),i=a)}e[i]=!0}return e}function MI(e){for(let r=0;r<e.length;r++)Xn(e,r)||(e[r]=null);return e}function Qa(e){const r=Z0(null);for(const[t,n]of Q0(e))Xn(e,t)&&(Array.isArray(n)?r[t]=MI(n):n&&typeof n=="object"&&n.constructor===Object?r[t]=Qa(n):r[t]=n);return r}function Ro(e,r){for(;e!==null;){const n=RI(e,r);if(n){if(n.get)return rn(n.get);if(typeof n.value=="function")return rn(n.value)}e=kI(e)}function t(){return null}return t}const Hg=tn(["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","section","select","shadow","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"]),Kf=tn(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Jf=tn(["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"]),xI=tn(["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"]),Yf=tn(["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"]),NI=tn(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Gg=tn(["#text"]),Vg=tn(["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","face","for","headers","height","hidden","high","href","hreflang","id","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","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Xf=tn(["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","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"]),Kg=tn(["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"]),Zu=tn(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),LI=Fn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),DI=Fn(/<%[\w\W]*|[\w\W]*%>/gm),jI=Fn(/\$\{[\w\W]*/gm),FI=Fn(/^data-[\-\w.\u00B7-\uFFFF]+$/),UI=Fn(/^aria-[\-\w]+$/),eT=Fn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),BI=Fn(/^(?:\w+script|data):/i),qI=Fn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),tT=Fn(/^html$/i),zI=Fn(/^[a-z][.\w]*(-[.\w]+)+$/i);var Jg=Object.freeze({__proto__:null,ARIA_ATTR:UI,ATTR_WHITESPACE:qI,CUSTOM_ELEMENT:zI,DATA_ATTR:FI,DOCTYPE_NAME:tT,ERB_EXPR:DI,IS_ALLOWED_URI:eT,IS_SCRIPT_OR_DATA:BI,MUSTACHE_EXPR:LI,TMPLIT_EXPR:jI});const $o={element:1,text:3,progressingInstruction:7,comment:8,document:9},WI=function(){return typeof window>"u"?null:window},HI=function(r,t){if(typeof r!="object"||typeof r.createPolicy!="function")return null;let n=null;const i="data-tt-policy-suffix";t&&t.hasAttribute(i)&&(n=t.getAttribute(i));const a="dompurify"+(n?"#"+n:"");try{return r.createPolicy(a,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},Yg=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function rT(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:WI();const r=rt=>rT(rt);if(r.version="3.2.4",r.removed=[],!e||!e.document||e.document.nodeType!==$o.document||!e.Element)return r.isSupported=!1,r;let{document:t}=e;const n=t,i=n.currentScript,{DocumentFragment:a,HTMLTemplateElement:s,Node:o,Element:u,NodeFilter:c,NamedNodeMap:l=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:p,DOMParser:v,trustedTypes:m}=e,_=u.prototype,T=Ro(_,"cloneNode"),I=Ro(_,"remove"),$=Ro(_,"nextSibling"),x=Ro(_,"childNodes"),N=Ro(_,"parentNode");if(typeof s=="function"){const rt=t.createElement("template");rt.content&&rt.content.ownerDocument&&(t=rt.content.ownerDocument)}let j,X="";const{implementation:J,createNodeIterator:G,createDocumentFragment:L,getElementsByTagName:re}=t,{importNode:ue}=n;let ee=Yg();r.isSupported=typeof Q0=="function"&&typeof N=="function"&&J&&J.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:ye,ERB_EXPR:Z,TMPLIT_EXPR:qe,DATA_ATTR:Qe,ARIA_ATTR:Nt,IS_SCRIPT_OR_DATA:vt,ATTR_WHITESPACE:Pe,CUSTOM_ELEMENT:me}=Jg;let{IS_ALLOWED_URI:he}=Jg,P=null;const Oe=Mt({},[...Hg,...Kf,...Jf,...Yf,...Gg]);let He=null;const Fe=Mt({},[...Vg,...Xf,...Kg,...Zu]);let be=Object.seal(Z0(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}})),Q=null,Ot=null,we=!0,fe=!0,Et=!1,De=!0,Dt=!1,ht=!0,Te=!1,ct=!1,wt=!1,ke=!1,Bt=!1,dt=!1,qt=!0,sr=!1;const Ue="user-content-";let Tr=!0,mr=!1,Ct={},Rt=null;const yt=Mt({},["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 ot=null;const Ft=Mt({},["audio","video","img","source","image","track"]);let At=null;const cr=Mt({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Cr="http://www.w3.org/1998/Math/MathML",Dr="http://www.w3.org/2000/svg",gr="http://www.w3.org/1999/xhtml";let zt=gr,lr=!1,ve=null;const _e=Mt({},[Cr,Dr,gr],Vf);let se=Mt({},["mi","mo","mn","ms","mtext"]),pe=Mt({},["annotation-xml"]);const ce=Mt({},["title","style","font","a","script"]);let ge=null;const Ee=["application/xhtml+xml","text/html"],te="text/html";let ae=null,V=null;const oe=t.createElement("form"),K=function(Y){return Y instanceof RegExp||Y instanceof Function},xe=function(){let Y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(V&&V===Y)){if((!Y||typeof Y!="object")&&(Y={}),Y=Qa(Y),ge=Ee.indexOf(Y.PARSER_MEDIA_TYPE)===-1?te:Y.PARSER_MEDIA_TYPE,ae=ge==="application/xhtml+xml"?Vf:ol,P=Xn(Y,"ALLOWED_TAGS")?Mt({},Y.ALLOWED_TAGS,ae):Oe,He=Xn(Y,"ALLOWED_ATTR")?Mt({},Y.ALLOWED_ATTR,ae):Fe,ve=Xn(Y,"ALLOWED_NAMESPACES")?Mt({},Y.ALLOWED_NAMESPACES,Vf):_e,At=Xn(Y,"ADD_URI_SAFE_ATTR")?Mt(Qa(cr),Y.ADD_URI_SAFE_ATTR,ae):cr,ot=Xn(Y,"ADD_DATA_URI_TAGS")?Mt(Qa(Ft),Y.ADD_DATA_URI_TAGS,ae):Ft,Rt=Xn(Y,"FORBID_CONTENTS")?Mt({},Y.FORBID_CONTENTS,ae):yt,Q=Xn(Y,"FORBID_TAGS")?Mt({},Y.FORBID_TAGS,ae):{},Ot=Xn(Y,"FORBID_ATTR")?Mt({},Y.FORBID_ATTR,ae):{},Ct=Xn(Y,"USE_PROFILES")?Y.USE_PROFILES:!1,we=Y.ALLOW_ARIA_ATTR!==!1,fe=Y.ALLOW_DATA_ATTR!==!1,Et=Y.ALLOW_UNKNOWN_PROTOCOLS||!1,De=Y.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Dt=Y.SAFE_FOR_TEMPLATES||!1,ht=Y.SAFE_FOR_XML!==!1,Te=Y.WHOLE_DOCUMENT||!1,ke=Y.RETURN_DOM||!1,Bt=Y.RETURN_DOM_FRAGMENT||!1,dt=Y.RETURN_TRUSTED_TYPE||!1,wt=Y.FORCE_BODY||!1,qt=Y.SANITIZE_DOM!==!1,sr=Y.SANITIZE_NAMED_PROPS||!1,Tr=Y.KEEP_CONTENT!==!1,mr=Y.IN_PLACE||!1,he=Y.ALLOWED_URI_REGEXP||eT,zt=Y.NAMESPACE||gr,se=Y.MATHML_TEXT_INTEGRATION_POINTS||se,pe=Y.HTML_INTEGRATION_POINTS||pe,be=Y.CUSTOM_ELEMENT_HANDLING||{},Y.CUSTOM_ELEMENT_HANDLING&&K(Y.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(be.tagNameCheck=Y.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Y.CUSTOM_ELEMENT_HANDLING&&K(Y.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(be.attributeNameCheck=Y.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Y.CUSTOM_ELEMENT_HANDLING&&typeof Y.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(be.allowCustomizedBuiltInElements=Y.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Dt&&(fe=!1),Bt&&(ke=!0),Ct&&(P=Mt({},Gg),He=[],Ct.html===!0&&(Mt(P,Hg),Mt(He,Vg)),Ct.svg===!0&&(Mt(P,Kf),Mt(He,Xf),Mt(He,Zu)),Ct.svgFilters===!0&&(Mt(P,Jf),Mt(He,Xf),Mt(He,Zu)),Ct.mathMl===!0&&(Mt(P,Yf),Mt(He,Kg),Mt(He,Zu))),Y.ADD_TAGS&&(P===Oe&&(P=Qa(P)),Mt(P,Y.ADD_TAGS,ae)),Y.ADD_ATTR&&(He===Fe&&(He=Qa(He)),Mt(He,Y.ADD_ATTR,ae)),Y.ADD_URI_SAFE_ATTR&&Mt(At,Y.ADD_URI_SAFE_ATTR,ae),Y.FORBID_CONTENTS&&(Rt===yt&&(Rt=Qa(Rt)),Mt(Rt,Y.FORBID_CONTENTS,ae)),Tr&&(P["#text"]=!0),Te&&Mt(P,["html","head","body"]),P.table&&(Mt(P,["tbody"]),delete Q.tbody),Y.TRUSTED_TYPES_POLICY){if(typeof Y.TRUSTED_TYPES_POLICY.createHTML!="function")throw ko('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Y.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw ko('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');j=Y.TRUSTED_TYPES_POLICY,X=j.createHTML("")}else j===void 0&&(j=HI(m,i)),j!==null&&typeof X=="string"&&(X=j.createHTML(""));tn&&tn(Y),V=Y}},Ce=Mt({},[...Kf,...Jf,...xI]),Ve=Mt({},[...Yf,...NI]),ze=function(Y){let Ae=N(Y);(!Ae||!Ae.tagName)&&(Ae={namespaceURI:zt,tagName:"template"});const Ke=ol(Y.tagName),Pt=ol(Ae.tagName);return ve[Y.namespaceURI]?Y.namespaceURI===Dr?Ae.namespaceURI===gr?Ke==="svg":Ae.namespaceURI===Cr?Ke==="svg"&&(Pt==="annotation-xml"||se[Pt]):!!Ce[Ke]:Y.namespaceURI===Cr?Ae.namespaceURI===gr?Ke==="math":Ae.namespaceURI===Dr?Ke==="math"&&pe[Pt]:!!Ve[Ke]:Y.namespaceURI===gr?Ae.namespaceURI===Dr&&!pe[Pt]||Ae.namespaceURI===Cr&&!se[Pt]?!1:!Ve[Ke]&&(ce[Ke]||!Ce[Ke]):!!(ge==="application/xhtml+xml"&&ve[Y.namespaceURI]):!1},We=function(Y){Co(r.removed,{element:Y});try{N(Y).removeChild(Y)}catch{I(Y)}},Ze=function(Y,Ae){try{Co(r.removed,{attribute:Ae.getAttributeNode(Y),from:Ae})}catch{Co(r.removed,{attribute:null,from:Ae})}if(Ae.removeAttribute(Y),Y==="is")if(ke||Bt)try{We(Ae)}catch{}else try{Ae.setAttribute(Y,"")}catch{}},tt=function(Y){let Ae=null,Ke=null;if(wt)Y="<remove></remove>"+Y;else{const $t=Wg(Y,/^[\r\n\t ]+/);Ke=$t&&$t[0]}ge==="application/xhtml+xml"&&zt===gr&&(Y='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+Y+"</body></html>");const Pt=j?j.createHTML(Y):Y;if(zt===gr)try{Ae=new v().parseFromString(Pt,ge)}catch{}if(!Ae||!Ae.documentElement){Ae=J.createDocument(zt,"template",null);try{Ae.documentElement.innerHTML=lr?X:Pt}catch{}}const nr=Ae.body||Ae.documentElement;return Y&&Ke&&nr.insertBefore(t.createTextNode(Ke),nr.childNodes[0]||null),zt===gr?re.call(Ae,Te?"html":"body")[0]:Te?Ae.documentElement:nr},Ye=function(Y){return G.call(Y.ownerDocument||Y,Y,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},et=function(Y){return Y instanceof p&&(typeof Y.nodeName!="string"||typeof Y.textContent!="string"||typeof Y.removeChild!="function"||!(Y.attributes instanceof l)||typeof Y.removeAttribute!="function"||typeof Y.setAttribute!="function"||typeof Y.namespaceURI!="string"||typeof Y.insertBefore!="function"||typeof Y.hasChildNodes!="function")},nt=function(Y){return typeof o=="function"&&Y instanceof o};function it(rt,Y,Ae){Qu(rt,Ke=>{Ke.call(r,Y,Ae,V)})}const yr=function(Y){let Ae=null;if(it(ee.beforeSanitizeElements,Y,null),et(Y))return We(Y),!0;const Ke=ae(Y.nodeName);if(it(ee.uponSanitizeElement,Y,{tagName:Ke,allowedTags:P}),Y.hasChildNodes()&&!nt(Y.firstElementChild)&&Xr(/<[/\w]/g,Y.innerHTML)&&Xr(/<[/\w]/g,Y.textContent)||Y.nodeType===$o.progressingInstruction||ht&&Y.nodeType===$o.comment&&Xr(/<[/\w]/g,Y.data))return We(Y),!0;if(!P[Ke]||Q[Ke]){if(!Q[Ke]&&lt(Ke)&&(be.tagNameCheck instanceof RegExp&&Xr(be.tagNameCheck,Ke)||be.tagNameCheck instanceof Function&&be.tagNameCheck(Ke)))return!1;if(Tr&&!Rt[Ke]){const Pt=N(Y)||Y.parentNode,nr=x(Y)||Y.childNodes;if(nr&&Pt){const $t=nr.length;for(let ir=$t-1;ir>=0;--ir){const Pr=T(nr[ir],!0);Pr.__removalCount=(Y.__removalCount||0)+1,Pt.insertBefore(Pr,$(Y))}}}return We(Y),!0}return Y instanceof u&&!ze(Y)||(Ke==="noscript"||Ke==="noembed"||Ke==="noframes")&&Xr(/<\/no(script|embed|frames)/i,Y.innerHTML)?(We(Y),!0):(Dt&&Y.nodeType===$o.text&&(Ae=Y.textContent,Qu([ye,Z,qe],Pt=>{Ae=Eo(Ae,Pt," ")}),Y.textContent!==Ae&&(Co(r.removed,{element:Y.cloneNode()}),Y.textContent=Ae)),it(ee.afterSanitizeElements,Y,null),!1)},fr=function(Y,Ae,Ke){if(qt&&(Ae==="id"||Ae==="name")&&(Ke in t||Ke in oe))return!1;if(!(fe&&!Ot[Ae]&&Xr(Qe,Ae))){if(!(we&&Xr(Nt,Ae))){if(!He[Ae]||Ot[Ae]){if(!(lt(Y)&&(be.tagNameCheck instanceof RegExp&&Xr(be.tagNameCheck,Y)||be.tagNameCheck instanceof Function&&be.tagNameCheck(Y))&&(be.attributeNameCheck instanceof RegExp&&Xr(be.attributeNameCheck,Ae)||be.attributeNameCheck instanceof Function&&be.attributeNameCheck(Ae))||Ae==="is"&&be.allowCustomizedBuiltInElements&&(be.tagNameCheck instanceof RegExp&&Xr(be.tagNameCheck,Ke)||be.tagNameCheck instanceof Function&&be.tagNameCheck(Ke))))return!1}else if(!At[Ae]){if(!Xr(he,Eo(Ke,Pe,""))){if(!((Ae==="src"||Ae==="xlink:href"||Ae==="href")&&Y!=="script"&&OI(Ke,"data:")===0&&ot[Y])){if(!(Et&&!Xr(vt,Eo(Ke,Pe,"")))){if(Ke)return!1}}}}}}return!0},lt=function(Y){return Y!=="annotation-xml"&&Wg(Y,me)},Wr=function(Y){it(ee.beforeSanitizeAttributes,Y,null);const{attributes:Ae}=Y;if(!Ae||et(Y))return;const Ke={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:He,forceKeepAttr:void 0};let Pt=Ae.length;for(;Pt--;){const nr=Ae[Pt],{name:$t,namespaceURI:ir,value:Pr}=nr,Mr=ae($t);let dr=$t==="value"?Pr:AI(Pr);if(Ke.attrName=Mr,Ke.attrValue=dr,Ke.keepAttr=!0,Ke.forceKeepAttr=void 0,it(ee.uponSanitizeAttribute,Y,Ke),dr=Ke.attrValue,sr&&(Mr==="id"||Mr==="name")&&(Ze($t,Y),dr=Ue+dr),ht&&Xr(/((--!?|])>)|<\/(style|title)/i,dr)){Ze($t,Y);continue}if(Ke.forceKeepAttr||(Ze($t,Y),!Ke.keepAttr))continue;if(!De&&Xr(/\/>/i,dr)){Ze($t,Y);continue}Dt&&Qu([ye,Z,qe],Hr=>{dr=Eo(dr,Hr," ")});const $n=ae(Y.nodeName);if(fr($n,Mr,dr)){if(j&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!ir)switch(m.getAttributeType($n,Mr)){case"TrustedHTML":{dr=j.createHTML(dr);break}case"TrustedScriptURL":{dr=j.createScriptURL(dr);break}}try{ir?Y.setAttributeNS(ir,$t,dr):Y.setAttribute($t,dr),et(Y)?We(Y):zg(r.removed)}catch{}}}it(ee.afterSanitizeAttributes,Y,null)},cn=function rt(Y){let Ae=null;const Ke=Ye(Y);for(it(ee.beforeSanitizeShadowDOM,Y,null);Ae=Ke.nextNode();)it(ee.uponSanitizeShadowNode,Ae,null),yr(Ae),Wr(Ae),Ae.content instanceof a&&rt(Ae.content);it(ee.afterSanitizeShadowDOM,Y,null)};return r.sanitize=function(rt){let Y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Ae=null,Ke=null,Pt=null,nr=null;if(lr=!rt,lr&&(rt="<!-->"),typeof rt!="string"&&!nt(rt))if(typeof rt.toString=="function"){if(rt=rt.toString(),typeof rt!="string")throw ko("dirty is not a string, aborting")}else throw ko("toString is not a function");if(!r.isSupported)return rt;if(ct||xe(Y),r.removed=[],typeof rt=="string"&&(mr=!1),mr){if(rt.nodeName){const Pr=ae(rt.nodeName);if(!P[Pr]||Q[Pr])throw ko("root node is forbidden and cannot be sanitized in-place")}}else if(rt instanceof o)Ae=tt("<!---->"),Ke=Ae.ownerDocument.importNode(rt,!0),Ke.nodeType===$o.element&&Ke.nodeName==="BODY"||Ke.nodeName==="HTML"?Ae=Ke:Ae.appendChild(Ke);else{if(!ke&&!Dt&&!Te&&rt.indexOf("<")===-1)return j&&dt?j.createHTML(rt):rt;if(Ae=tt(rt),!Ae)return ke?null:dt?X:""}Ae&&wt&&We(Ae.firstChild);const $t=Ye(mr?rt:Ae);for(;Pt=$t.nextNode();)yr(Pt),Wr(Pt),Pt.content instanceof a&&cn(Pt.content);if(mr)return rt;if(ke){if(Bt)for(nr=L.call(Ae.ownerDocument);Ae.firstChild;)nr.appendChild(Ae.firstChild);else nr=Ae;return(He.shadowroot||He.shadowrootmode)&&(nr=ue.call(n,nr,!0)),nr}let ir=Te?Ae.outerHTML:Ae.innerHTML;return Te&&P["!doctype"]&&Ae.ownerDocument&&Ae.ownerDocument.doctype&&Ae.ownerDocument.doctype.name&&Xr(tT,Ae.ownerDocument.doctype.name)&&(ir="<!DOCTYPE "+Ae.ownerDocument.doctype.name+`>
2
+ `+ir),Dt&&Qu([ye,Z,qe],Pr=>{ir=Eo(ir,Pr," ")}),j&&dt?j.createHTML(ir):ir},r.setConfig=function(){let rt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};xe(rt),ct=!0},r.clearConfig=function(){V=null,ct=!1},r.isValidAttribute=function(rt,Y,Ae){V||xe({});const Ke=ae(rt),Pt=ae(Y);return fr(Ke,Pt,Ae)},r.addHook=function(rt,Y){typeof Y=="function"&&Co(ee[rt],Y)},r.removeHook=function(rt,Y){if(Y!==void 0){const Ae=$I(ee[rt],Y);return Ae===-1?void 0:II(ee[rt],Ae,1)[0]}return zg(ee[rt])},r.removeHooks=function(rt){ee[rt]=[]},r.removeAllHooks=function(){ee=Yg()},r}var GI=rT();const VI={ALLOWED_TAGS:["b","i","em","strong","p","br","ul","ol","li","a"],ALLOWED_ATTR:["href","src","alt","title","target","class","id","style"],ALLOW_DATA_ATTR:!1,FORBID_TAGS:["img","iframe","object","input","style","script","embed","svg","video","audio","body","input","form","link"],FORBID_ATTR:["onerror","onclick","onload","onmouseover","onfocus","onblur","onchange","onsubmit","scr","href","style","action","value"],IN_PLACE:!0},KI="javascript:";function JI(e){return(e==null?void 0:e.constructor)===Object}async function Xg(e,r=3){let t=0,n;for(;t<=r;){t+=1;try{return await e()}catch(i){n=i,console.error(i),await YI(1e3*Math.pow(2,t))}}throw n}function YI(e){return new Promise(r=>{setTimeout(()=>{r(0)},e)})}function XI(){return Math.random().toString(36).slice(2)}const QI=new TextDecoder,ZI=e=>{const r=atob(e),t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r.charCodeAt(n);return QI.decode(t)},eO=e=>e.length===0,tO=(...e)=>e.every(eO),nT=e=>{const r=GI.sanitize(e,VI);return r.includes(KI)?(console.warn("Suspicious content detected and removed."),""):r},Qg=[];class $a{constructor(r){pt(this,"channel");this.channel=r}static addHandler(r){Qg.push(r)}debug(...r){this._log("debug",...r)}info(...r){this._log("info",...r)}warn(...r){this._log("warn",...r)}error(...r){this._log("error",...r)}_log(r,...t){Qg.forEach(n=>{n(this.channel,r,...t)})}}const rO=(e,r,...t)=>{console[r](`[${r}][${e}]`,...t)},nO=e=>{let r=[],t;return(i,a,...s)=>{a==="debug"||i==="communicator"||(r.push(iO(i,a,...s)),clearTimeout(t),t=window.setTimeout(()=>{if(r.length){const o={num_of_logs:r.length,logs:r};e(o)}r=[]},2e3))}};function iO(e,r,...t){let n=t.pop();typeof n=="string"&&(t.push(n),n={});const i=t.join(" "),a={loglevel:r,channel:e,timestamp:new Date().toISOString(),application:Br.application,version:Br.version,device:Br.deviceId,tenant:Br.tenant,company_id:Br.companyId,location_url:location.href,data:oO(n),message:Uv(i)};return Br.trackerId&&(a.tracker_id=Br.trackerId),a}const aO=["user","phone","phone_number","phoneNumber","email"],sO=[/(?: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];function Uv(e){return typeof e=="string"?sO.forEach(r=>{e=e.replace(r,"__MASKED__")}):e&&JI(e)&&(e={...e},Object.keys(e).forEach(r=>{aO.indexOf(r)!==-1?e[r]="__MASKED__":Uv(e[r])})),e}function oO(e){if(e.error){const r=e.error;return{error:{name:r.name,message:r.message,stack:r.stack}}}return Uv(e.data)}const Qf=new $a("communicator");let Zg=!1;class uO{constructor(r,t){pt(this,"events");pt(this,"options");pt(this,"channel");pt(this,"authenticate");pt(this,"channelReady",!1);pt(this,"__authed",!1);pt(this,"pending",[]);pt(this,"promises",{});pt(this,"user");pt(this,"iframe");this.authenticate=r.authenticate,this.events=t,this.options=cO(r),this.channel=new MessageChannel,this.useConnect(this.options)}useConnect(r){const t=document.createElement("iframe");t.src=r.bridge,t.setAttribute("style","display:none");let n="*";/^https:/.test(r.bridge)&&(n=new URL(r.bridge).origin),t.addEventListener("load",()=>{if(Qf.debug("iframe bridge ready for",n),!this.channelReady){const i={type:"_init",data:r};t.contentWindow.postMessage(i,n,[this.channel.port2])}}),this.channel.port1.onmessage=i=>{this.receiveMessage(i)},document.body.appendChild(t),this.iframe=t}receiveMessage(r){const t=r.data;if(t){if(Qf.debug("receiveMessage",t),t.type==="ready")this.channelReady=!0,Br.deviceId=t.result.deviceId,Br.deviceId||console.error("Device Id has not been provided. SDK will not work properly."),this.runPending(),this.events.triggerEvent("ready");else if(t.type==="callback"&&t.callbackId){const[n,i]=this.promises[t.callbackId];t.error?i(t.error):n(t.result),delete this.promises[t.callbackId]}else if(t.type==="refreshToken")this.refreshToken();else if(t.request==="_auth"&&(this.events.triggerEvent("authenticated"),t.result&&t.result.log_proxy_url&&!Zg)){Zg=!0;const n=nO(i=>{this.postMessage({type:"_log",data:i})});$a.addHandler(n)}}}postMessage(r){this.channelReady?(Qf.debug("postMessage",r),this.channel.port1.postMessage(r)):this.pending.push(r)}runPending(){for(;this.pending.length;){const r=this.pending.shift();this.postMessage(r)}}postPromise(r,t){return new Promise((n,i)=>{const a=XI()+"_"+Date.now();this.promises[a]=[n,i];const s={type:r,callbackId:a,data:t};this.postMessage(s)})}async refreshToken(){this.__authed=!0;const r=await this.authenticate(),t=["twilio_chat","nexmo_chat"];this.options.cobrowse&&t.push("cobrowse");const i={type:"_auth",data:{modules:t,user:{token:r.token,company_id:this.options.companyId}}};this.postMessage(i);const a=JSON.parse(ZI(r.token.split(".")[1]));if(this.user={identifier:a.identifier,name:a.name,email:a.email},this.events.triggerEvent("authenticate"),a.exp){let s;a.exp.toString().length===13?s=a.exp:a.exp.toString().length===10&&(s=a.exp*1e3),s&&setTimeout(()=>{this.refreshToken()},s-Date.now()-12e4)}}request(r,t){!this.__authed&&r!=="proactive_chat_triggers"&&this.refreshToken();const n={url:r,options:t};return this.postPromise("request",n)}destroy(){delete this.channel,this.iframe&&(document.body.removeChild(this.iframe),this.iframe=void 0)}}function cO(e){var a;let r=e.host;r||(e.tenant?r=Bg.replace("main.api",e.tenant+".api"):r=Bg);const t=e.lang||"en",n=!!((a=e.cobrowse)!=null&&a.enabled),i=e.bridge||"https://websdk.ujet.co/v3/bridge.html";return{host:r,lang:t,cobrowse:n,companyId:e.companyId,location:location.href,version:e.version||"3.6.4",bridge:i}}class Bv{constructor(){pt(this,"handlers",{})}addEventListener(r,t){this.handlers[r]||(this.handlers[r]=[]),this.handlers[r].push(t)}triggerEvent(r,t){const n=this.handlers[r];n&&n.forEach(i=>{i(t)})}removeEventListener(r,t){if(this.handlers[r]){const n=this.handlers[r].indexOf(t);n!==-1&&this.handlers[r].splice(n,1)}}destroy(){this.handlers={}}}function lO(e,r){const t={};return r.forEach(n=>{t[n.id]=n}),e.map(n=>{if(n.type==="server_message"){const i=n.message_id,a=t[i];iT(n,a.content)}return n})}function fO(e,r){return iT(e,r.content)}function iT(e,r){return Object.keys(r).forEach(t=>{e[t]=r[t]}),e}const ey={photo:2,video:2,audio:1,document:1};function dO(e){const r=e.toSorted((t,n)=>!t.groupMessageId||!n.groupMessageId||t.groupMessageId!==n.groupMessageId?0:(ey[n.type]||0)-(ey[t.type]||0));return r.forEach((t,n,i)=>{const a=i[n+1];a&&a.groupMessageId===t.groupMessageId&&t.$time&&(a.$time=t.$time,t.$time=null)}),r}const ty=new $a("MediaStore"),pO=window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB||window.OIndexedDB||window.msIndexedDB,hO="chat-media",ry=1,Cl="file";class aT{constructor(){pt(this,"db")}store(){return new Promise((r,t)=>{if(this.db)return r(ny(this.db));const n=pO.open(hO,ry);n.onerror=()=>{t(new Error("indexedDB open failed"))},n.onsuccess=()=>{const i=n.result;this.db=i,r(ny(i))},n.onupgradeneeded=i=>{const a=n.result;i.oldVersion>0&&i.oldVersion<ry&&(ty.info("deprecating media store"),a.deleteObjectStore(Cl)),ty.info("creating media store"),a.createObjectStore(Cl)}})}async save(r,t){(await this.store()).put({index:r,file:t},r)}async getAll(){const r=await this.store();return await new Promise((t,n)=>{const i=r.getAll();i.onerror=()=>{n(new Error("indexedDB getAll failed"))},i.onsuccess=()=>{t(i.result)}})}async getAllFiles(){const r={};return(await this.getAll()).forEach(n=>{r[n.index]=n.file}),r}async clear(){(await this.store()).clear()}}function ny(e){return e.transaction(Cl,"readwrite").objectStore(Cl)}class vO{constructor(){pt(this,"_hostPath","")}setPath(r){this._hostPath=r}getPath(){return this._hostPath}}const sT=new vO,mO=new $a("chat-provider");class qv{constructor(r,t,n){pt(this,"audio");pt(this,"issueChatToken");pt(this,"identity");pt(this,"channelId");pt(this,"region");pt(this,"inTask",!1);pt(this,"muted",!1);pt(this,"events");this.events=r,this.region=t.region,this.issueChatToken=n}ping(){if(!this.muted){if(!this.audio){sT.getPath();const r="https://websdk.ujet.co/v3/ping.mp3";this.audio=new window.Audio(r)}try{this.audio.play()}catch(r){mO.warn("Chat audio play failed",{error:r})}}}on(r,t){this.events.addEventListener(r,t)}off(r,t){this.events.removeEventListener(r,t)}trackInTask(r){r.type==="noti"&&r.event==="taskVaStarted"?this.inTask=!0:r.type==="noti"&&r.event==="taskVaFinished"&&(this.inTask=!1)}}pt(qv,"type","base");const oT={};function zv(e){oT[e.type]=e}function gO(e){return oT[e]}const uT=["assigned","va_assigned"],cT=["dismissed","va_dismissed"],yO=["va_assigned","va_dismissed"],bO=["queued",...uT,...cT],_O=["timeout","canceled","failed","finished"],Zf=new $a("Chat");class wO{constructor(r,t){pt(this,"provider");pt(this,"store");pt(this,"globalEvents");pt(this,"state");pt(this,"connected",!1);pt(this,"allowSkipVirtualAgent",!1);pt(this,"inEscalation",!1);pt(this,"events");pt(this,"cachedFiles");this.state=r,this.store=new aT,this.cachedFiles={},this.events=new Bv;const n=gO(this.state.provider_type);this.provider=new n(this.events,r,t)}_setGlobalEvents(r,t){this.globalEvents=r,this.on("message",n=>{if(n.content=nT(n.content),n.type==="server_message"){const i=n.message_id;t(this.id,i).then(a=>{n=fO(n,a),r.triggerEvent("chat.message",n)})}else n.type==="photo"||n.type==="video"?setTimeout(()=>{const i=n.$index.toString();n.file=this.cachedFiles[i],r.triggerEvent("chat.message",n)},100):(r.triggerEvent("chat.message",n),this.registerMessageEvents(n))}),this.on("memberJoined",n=>{r.triggerEvent("chat.memberJoined",n)}),this.on("memberLeft",n=>{r.triggerEvent("chat.memberLeft",n)}),this.on("typingStarted",n=>{r.triggerEvent("chat.typingStarted",n)}),this.on("typingEnded",n=>{r.triggerEvent("chat.typingEnded",n)})}get id(){var r;return((r=this.state)==null?void 0:r.id)||-1}get menuId(){return this.state?this.state.menus[this.state.menus.length-1].id:-1}get channelId(){var r;return((r=this.state)==null?void 0:r.provider_channel_id)||""}get lang(){var r;return((r=this.state)==null?void 0:r.lang)||""}get virtual(){return yO.indexOf(this.status)!==-1}get muted(){var r;return((r=this.provider)==null?void 0:r.muted)||!1}set muted(r){this.provider&&(this.provider.muted=r)}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 r,t;return{virtual:((r=this.state)==null?void 0:r.all_virtual_agents)||[],human:((t=this.state)==null?void 0:t.all_agents)||[]}}get userIdentity(){var r;return((r=this.provider)==null?void 0:r.identity)||""}get status(){var r;return((r=this.state)==null?void 0:r.status)||""}get postSessionStatus(){var r;return((r=this.state)==null?void 0:r.post_session_transfer_status)||""}get statusText(){var r;return((r=this.state)==null?void 0:r.status_text)||""}get cobrowsable(){return this.state?this.state.features.indexOf("cobrowse")!==-1:!1}get ongoing(){return bO.indexOf(this.status)!=-1}get assigned(){return uT.indexOf(this.status)!=-1}get dismissed(){return cT.indexOf(this.status)!=-1}get ended(){return _O.indexOf(this.status)!=-1}get transcriptCount(){var r;return((r=this.state)==null?void 0:r.transcript_requested_count)||0}get createdAt(){var r;return((r=this.state)==null?void 0:r.created_at)||""}get inTask(){var r;return((r=this.provider)==null?void 0:r.inTask)||!1}get feedbackType(){var r;return this.state?this.state.survey_enabled?"survey":(r=this.state.csat_settings)!=null&&r.enabled?"rate":"none":"none"}get optInRequired(){var r;return((r=this.state)==null?void 0:r.post_session_opt_in_required)||!1}get postSessionRequired(){var r;return((r=this.state)==null?void 0:r.post_session_required)||!1}get postSessionInProgress(){return this.state?this.state.post_session_transfer_status===Qs.IN_PROGRESS:!1}update(r){!this.state||this.state.id!==r.id||(this.state=r,r.status==="canceled"?this.triggerEvent("ended",this):this.triggerEvent("updated",this))}on(r,t){this.events.addEventListener(r,t)}off(r,t){this.events.removeEventListener(r,t)}async connect(){try{if(await Xg(()=>{var n;return(n=this.provider)==null?void 0:n.create()},3),await Xg(()=>{var n;return(n=this.provider)==null?void 0:n.join(this.state.provider_channel_id)},3),!this.provider)return Zf.info("connecting interrupted"),!1;this.connected=!0;const r=await this.fetchMessages(),t={chat:this,messages:r};return this.triggerEvent("connectedMessages",t),this.triggerEvent("connected",this),this.registerProviderEvents(),Zf.info("connected with provider",this.state.provider_type),!0}catch{return!1}}async disconnect(){this.connected=!1,this.triggerEvent("disconnected",this),this.events.destroy(),this.provider&&(await this.provider.destroy(),Zf.info("disconnect with provider",this.state.provider_type))}async sendMessage(r,t){const n=await this.provider.sendMessage(r);return t&&this.saveMedia(n,t),n}preview(r){if(!this.inTask)return this.provider.preview(r)}async fetchMessages(){if(this.connected){const r=await this.store.getAllFiles();return this.provider.fetchMessages(r)}else throw new Error("Please fetchMessages after chat connected.")}startTyping(){return this.provider.startTyping()}stopTyping(){return this.provider.stopTyping()}saveMedia(r,t){this.cachedFiles[r.toString()]=t,this.store.save(r,t)}async destroy(){await this.clearMediaStore(),this.connected&&await this.disconnect(),this.provider&&(this.triggerEvent("destroyed"),this.provider=null),this.events.destroy(),this.state=null}async clearMediaStore(){await this.store.clear()}_handleChatEndedEvent(r){this.disconnect(),this.state&&(r.timeout?(this.state.status="timeout",this.triggerEvent("timeout",this)):(this.state.status="finished",this.triggerEvent("ended",this)))}triggerEvent(r,t){this.events.triggerEvent(r,t),this.globalEvents&&this.globalEvents.triggerEvent("chat."+r,t)}registerProviderEvents(){this.provider&&this.provider.registerConversationEvents()}registerMessageEvents(r){r.event==="cobrowseRequestedFromAgent"?this.events.triggerEvent("_requestCobrowse","agent"):r.event==="cobrowseRequestedFromEndUser"?this.events.triggerEvent("_requestCobrowse","end_user"):r.event==="chatDismissed"&&this.state?(this.state.status="dismissed",this.triggerEvent("dismissed",this)):r.event==="chatEnded"?this.events.triggerEvent("_chatEnded",r):r.event==="escalationStarted"?this.inEscalation=!0:(r.event==="escalationFailed"||r.event==="escalationAccepted")&&(this.inEscalation=!1)}}function lT(e){return e.map(SO).filter(r=>r.enabled)}function SO(e){const r={id:e.id,enabled:!0,channels:[],hidden:!!e.hidden};if(!e.name||!e.name.trim())return r.enabled=!1,r;r.name=e.name.trim();const t=TO(e);if(t&&(r.redirection=e.redirection),e.children&&e.children.length){const n=lT(e.children);return r.enabled=n.length>0||t,r.children=n,r}if(!e.channels)r.enabled=t;else{const{channels:n,deflection:i}=CO(e.channels);r.deflection=i,t||(r.channels=n),r.enabled=n.length>0||t}return r}function TO(e){let r=!1;const t=e.redirection;return t&&(t.option==="message"||t.option==="url")&&(r=!!t.data),r}function CO(e){let r=null;const t=[],n=e.chat,i=a=>{!a.deflection_type&&a.deflected_reason&&(a.deflection_type=a.deflected_reason),a.deflected===void 0&&a.deflection_type&&(a.deflected=!0),t.push(a)};return n&&n.deflected&&(r={enabled:!0,type:n.deflected_reason}),n&&(n.enabled||n.virtual_agent_available)&&i({...e.chat,type:"chat"}),e.voice_call&&e.voice_call.instant_enabled&&i({...e.voice_call,type:"instant_call"}),e.voice_call&&e.voice_call.schedule_enabled&&i({...e.voice_call,type:"scheduled_call",deflection_type:e.voice_call.schedule_deflection_type}),e.email&&e.email.enabled&&i({...e.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}),e.external_deflection_link&&e.external_deflection_link.enabled&&e.external_deflection_link.links.forEach(s=>{s.enabled&&i({...s,type:"external_link"})}),{channels:t,deflection:r}}const EO={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 kO(e){var t,n;return{languages:e.languages.filter(i=>i.enabled).map(i=>({lang:i.lang,name:i.name,localeName:EO[i.lang]})),name:e.display_name,subdomain:e.subdomain,support_email:e.support_email,action_tracking:e.action_tracking_enabled,email_transcripts:e.chat_settings.email_transcripts,message_preview:e.chat_settings.message_preview,email_enhancement:e.email_enhancement_enabled,display_history:((t=e.chat_settings.display_history)==null?void 0:t.enabled)&&((n=e.chat_settings.display_history)==null?void 0:n.to_end_user),use_recording:e.use_recording,use_web:e.use_web,cobrowse_domain:e.cobrowse_domain}}function iy(e){return e.chats=e.chats.map(r=>{const t=r.entries.map((n,i)=>RO(n,`${r.comm_id}-${i}`));return r.entries=dO(t),r}),e}function RO(e,r){var t;return{$index:e.timestamp,$sid:r,$timestamp:new Date(e.timestamp),$userType:e.role,$userId:((t=e.user_data)==null?void 0:t.id)||0,user:e.user_data,type:e.type,...e.body}}const ay=/Chrome/.test(navigator.userAgent);class $O{constructor(r){pt(this,"request");this.request=r}get(r,t){if(t){const n=[];Object.keys(t).forEach(i=>{const a=t[i];a!==void 0&&n.push(`${encodeURIComponent(i)}=${encodeURIComponent(a)}`)}),r+="?"+n.join("&")}return this.request(r,{method:"GET"})}post(r,t){const n={method:"POST"};return n.body=JSON.stringify(t),this.request(r,n)}patch(r,t){const n={method:"PATCH"};return n.body=JSON.stringify(t),this.request(r,n)}put(r,t){const n={method:"PUT"};return n.body=JSON.stringify(t),this.request(r,n)}async getTriggers(r){const t={"UJET-Company-Id":r};return(await this.request("proactive_chat_triggers",{method:"GET",headers:t})).data}trackClientEvents(r){return this.post("/client_events",{events:r})}async getCompany(){const r=await this.get("company");return kO(r.data)}async getMenus(r,t){const n={type:"web_menu",lang:r,direct_access_key:t},i=await this.get("menus",n),a={key:!!t,user:!1},s=i.headers["ujet-direct-access"];return s&&s!="false"&&(a.user=!0),{menus:lT(i.data),direct:a}}async getAfterHourMessage(r){return(await this.get(`audible_messages/${r}`)).data["after_hours.message"].text}async getTimeSlots(r,t="en"){return(await this.get(`menus/${r}/time_slots`,{type:"web_menu",lang:t})).data}async getWaitTimes(r,t="en"){return(await this.get(`menus/${r}/wait_times`,{type:"web_menu",lang:t})).data}async verifyForm(r){try{return await this.post("forms/verify",r),!0}catch{return!1}}async finishChat(r){return(await this.patch(`chats/${r}`,{status:"finished"})).data}async updatePostSession(r,t){const n={post_session_transfer_status:t};try{return(await this.patch(`chats/${r}`,n)).data}catch(i){if(t===Qs.IN_PROGRESS&&i.status===400)return(await this.patch(`chats/${r}`,n)).data;throw i}}async getChatDeflection(r){const{data:t}=await this.get(`chats/${r}/deflections`);return t&&t.enabled?t:null}sendChatCustomData(r,t){let n;return typeof t=="string"?n={signed:!0,signed_data:t}:n={signed:!1,data:t},this.post(`chats/${r}/custom_data`,n)}async downloadChatTranscript(r){return(await this.post(`chats/${r}/generate_transcript_pdf`,{})).data}async getPdfStatus(r){return await this.get(`chat_transcript_pdfs/${r}/download_transcript`)}sendChatTranscripts(r,t){return this.post(`chats/${r}/transcripts`,{emails:t.join(",")})}async listChatTaskMessages(r){return(await this.get(`chats/${r}/task_va_messages`)).data}async getChatTaskMessage(r,t){return(await this.get(`chats/${r}/task_va_messages/${t}`)).data}async sendChatTaskMessage(r,t){const n={content:{content:t,type:"text"}};return(await this.post(`chats/${r}/task_va_messages`,n)).data}escalateChat(r,t){return this.post(`chats/${r}/escalations`,t)}trackEscalation(r,t,n){return this.put(`chats/${r}/escalations/${t}`,{escalation_id:t,deflection_channel:n})}requestChatCobrowse(r,t){return this.post(`chats/${r}/cobrowse`,t)}rateChat(r,t){return this.patch(`chats/${r}/rating`,t)}async getChatSurvey(r){return(await this.get(`chats/${r}/survey`)).data}sendChatSurvey(r,t){const n={chat_id:r,answers:t};return this.put(`chats/${r}/survey`,n)}trackChatEndUserEvent(r,t){return this.post(`chats/${r}/end_user_event`,t)}async createChat(r,t,n,i){const a={chat:{menu_id:r,lang:t,email:n.email,greeting:n.greeting,trigger_id:n.trigger_id,ticket_id:n.ticket_id,custom_data:n.custom_data},cobrowsable:n.cobrowsable},o=(await this.post("chats",a)).data;return this.wrapChat(o,i)}async loadChat(r,t){const n=await this.getChat(r);return this.wrapChat(n,t)}async resumeChat(r,t){const n=await this.patch(`chats/${r}`,{status:"queued"});return this.wrapChat(n.data,t)}async getChatHistory(r=1){if(r===1){const{data:t}=await this.get("/chats/histories?page=1&per_page=2");return iy(t)}else{const{data:t}=await this.get(`/chats/histories?page=${r}&per_page=1`);return iy(t)}}async uploadChatFile(r,t){let n="file";/^image/.test(t.type)?n="photo":/^video/.test(t.type)?n="video":n="file";const i=t.name.replace(/\.[^.]+$/i,""),a=await this.post(`chats/${r}/${n}s/upload`,{filename:i}),s={file:t,fields:a.data.fields};ay&&(s.file=await fT(t));const u=(await this.request(a.data.url,s)).data.key,l=(await this.post(`chats/${r}/${n}s`,{chat_id:r,[n]:{s3_path:u,photo_type:n}})).data;return l.type=n,l}async getChat(r){return(await this.get(`chats/${r}`)).data}wrapChat(r,t){const n=async()=>(await this.post(`chats/${r.id}/tokens`,{provider_type:r.provider_type,device_id:t})).data,i=new wO(r,n),a=async s=>{if(i.status==="va_assigned"){const u=(await this.get(`menus/${i.menuId}/virtual_agent_settings`,{lang:i.lang})).data.allow_skip_virtual_agent;i.allowSkipVirtualAgent=u,i.update(s)}};if(i.channelId)i.connect(),a(r);else{const s=setInterval(async()=>{const o=await this.getChat(i.id);o.provider_channel_id?(clearInterval(s),i.state&&(i.update(o),i.connect(),a(o))):(o.status==="canceled"||o.status==="finished")&&clearInterval(s)},1500)}return i.on("initialized",async()=>{if(i.status==="queued"){const s=await this.getChat(i.id);i.update(s)}}),i.on("memberJoined",async()=>{const s=await this.getChat(i.id);i.update(s)}),i.on("memberLeft",async()=>{const s=await this.getChat(i.id);i.update(s)}),i.on("_chatEnded",async s=>{const o=await this.getChat(i.id);i.update(o),(!i.state||i.ended)&&i._handleChatEndedEvent(s)}),i}async createCall(r,t,n){const i={type:n.scheduled_at?"web_scheduled_call":"web_instant_call",menu_id:r,lang:t,email:n.email,ticket_id:n.ticket_id,recording_permission:n.recording_permission||"recording_permission_not_asked",scheduled_at:n.scheduled_at,custom_data:n.custom_data,end_user:{phone_number:n.phone_number}},s=(await this.post("calls",{call:i,cobrowsable:!1})).data;return s.menu_id=s.selected_menu.id,s}async fetchCall(r){const n=(await this.get(`calls/${r}`)).data;return n.menu_id=n.selected_menu.id,n}async cancelCall(r){const n=(await this.patch(`calls/${r}`,{status:"failed",fail_reason:"canceled"})).data;return n.menu_id=n.selected_menu.id,n}async listFileTypes(){return(await this.get("email_prohibited_file_types")).data}async createEmail(r,t,n){const i={end_user_email:n.email,email_body:n.content,menu_id:r.toString(),lang:t};return n.name&&(i.end_user_name=n.name),n.recaptcha&&(i.recaptcha_response=n.recaptcha),n.files&&ay?i["email_attachments[]"]=await IO(n.files):n.files&&(i["email_attachments[]"]=[...n.files]),this.request("emails",{form:i})}async getMedia(r,t){const n=await this.get(`media/${r}?type=${t}`);if(!n.data)return null;const i=n.headers["x-file-name"];return new File([n.data],i,{type:n.data.type})}}function IO(e){return Promise.all(e.map(fT))}function fT(e){return new Promise((r,t)=>{const n=new FileReader;n.onload=()=>{const i=[n.result],a={type:e.type,lastModified:e.lastModified};r({name:e.name,fileBits:i,options:a})},n.onerror=t,n.readAsArrayBuffer(e)})}const ed="ujet:",Kr={set(e,r){return localStorage.setItem(ed+e,r)},get(e){return localStorage.getItem(ed+e)},del(e){return localStorage.removeItem(ed+e)}},OO=Date.now(),dT={href:window.location.href,interval:24*60*60};function AO(e){if(!Array.isArray(e)||!e.length)return null;const r=LO(),t=r===0,n=r+1;return DO(n),e.filter(a=>{const s=MO(a,dT.href),o=xO(a.visitor_type,t),u=n>=a.page_visit_count,c=!NO(a.id);return s&&o&&u&&c}).sort((a,s)=>a.stay_time-s.stay_time)[0]||null}function PO(e,r){const t=e.stay_time*1e3,n=Math.max(t-(Date.now()-OO),0);setTimeout(()=>{r(e),Kr.set(`trigger:${e.id}`,(Date.now()/1e3).toString())},n)}const MO=(e,r)=>{const{keywords_included_or:t=[],keywords_excluded_or:n=[],keywords_included:i=[],keywords_excluded:a=[]}=e;if(tO(t,n,i,a))return!0;if(t.length||n.length){const u=t.some(l=>l.every(p=>r.includes(p))),c=n.length>0&&n.every(l=>l.every(p=>!r.includes(p)));return u||c}const s=i.filter(u=>r.indexOf(u)!==-1).length,o=a.filter(u=>r.indexOf(u)===-1).length;return!!s||!!o};function xO(e,r){return e==="visitor_type_new"?r:e==="visitor_type_returning"?!r:!0}function NO(e){try{const r=parseInt(Kr.get(`trigger:${e}`),10);return Date.now()/1e3-r<dT.interval}catch{return!1}}function LO(){try{const e=Kr.get("visits");return e?parseInt(e,10):0}catch{return 0}}function DO(e){try{Kr.set("visits",e.toString())}catch(r){console.error(r)}}const jO=`<dialog open class="cobrowse-dialog" data-test-id="cobrowse-dialog">
3
3
  <h1>$title</h1>
4
4
  <div class="cobrowse-dialog_content">$content</div>
5
5
  <div class="cobrowse-dialog_footer">
@@ -461,7 +461,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
461
461
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var y=!0,g=!1,b;return{s:function(){f=f.call(O)},n:function(){var S=f.next();return y=S.done,S},e:function(S){g=!0,b=S},f:function(){try{!y&&f.return!=null&&f.return()}finally{if(g)throw b}}}}function gn(O,A){if(O){if(typeof O=="string")return Oi(O,A);var f=Object.prototype.toString.call(O).slice(8,-1);if(f==="Object"&&O.constructor&&(f=O.constructor.name),f==="Map"||f==="Set")return Array.from(O);if(f==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(f))return Oi(O,A)}}function Oi(O,A){(A==null||A>O.length)&&(A=O.length);for(var f=0,d=new Array(A);f<A;f++)d[f]=O[f];return d}function Ai(O){var A=qa();return function(){var d=vt.default(O),h;if(A){var y=vt.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return Nt.default(this,h)}}function qa(){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 yn={lastMessage:"lastMessage",attributes:"attributes",createdBy:"createdBy",dateCreated:"dateCreated",dateUpdated:"dateUpdated",friendlyName:"friendlyName",lastConsumedMessageIndex:"lastConsumedMessageIndex",notificationLevel:"notificationLevel",sid:"sid",status:"status",uniqueName:"uniqueName",state:"state",bindings:"bindings"},It=function(O){Qe.default(f,O);var A=Ai(f);function f(d,h,y,g,b){var w,S,C;he.default(this,f),C=A.call(this),C.sid=h,C._links=y,C._configuration=g,C._services=b,C._entityName=d.channel,C._internalState={uniqueName:d.uniqueName||null,status:"notParticipating",attributes:(w=d.attributes)!==null&&w!==void 0?w:{},createdBy:d.createdBy,dateCreated:ot(d.dateCreated),dateUpdated:ot(d.dateUpdated),friendlyName:d.friendlyName||null,lastReadMessageIndex:Number.isInteger(d.lastConsumedMessageIndex)?d.lastConsumedMessageIndex:null,bindings:(S=d.bindings)!==null&&S!==void 0?S:{}},d.notificationLevel&&(C._internalState.notificationLevel=d.notificationLevel);var U={participants:C._links.participants};return C._participants=new Map,C._participantsEntity=new Ce(qe.default(C),C._participants,U,C._services),C._participantsEntity.on(f.participantJoined,function(F){return C.emit(f.participantJoined,F)}),C._participantsEntity.on(f.participantLeft,function(F){return C.emit(f.participantLeft,F)}),C._participantsEntity.on(f.participantUpdated,function(F){return C.emit(f.participantUpdated,F)}),C._messagesEntity=new Ua(qe.default(C),g,b),C._messagesEntity.on(f.messageAdded,function(F){return C._onMessageAdded(F)}),C._messagesEntity.on(f.messageUpdated,function(F){return C.emit(f.messageUpdated,F)}),C._messagesEntity.on(f.messageRemoved,function(F){return C.emit(f.messageRemoved,F)}),C}return me.default(f,[{key:"uniqueName",get:function(){return this._internalState.uniqueName}},{key:"status",get:function(){return this._internalState.status}},{key:"friendlyName",get:function(){return this._internalState.friendlyName}},{key:"dateUpdated",get:function(){return this._internalState.dateUpdated}},{key:"dateCreated",get:function(){return this._internalState.dateCreated}},{key:"createdBy",get:function(){var h;return(h=this._internalState.createdBy)!==null&&h!==void 0?h:""}},{key:"attributes",get:function(){return this._internalState.attributes}},{key:"lastReadMessageIndex",get:function(){return this._internalState.lastReadMessageIndex}},{key:"lastMessage",get:function(){var h;return(h=this._internalState.lastMessage)!==null&&h!==void 0?h:void 0}},{key:"notificationLevel",get:function(){var h;return(h=this._internalState.notificationLevel)!==null&&h!==void 0?h:"default"}},{key:"bindings",get:function(){return this._internalState.bindings}},{key:"limits",get:function(){return this._configuration.limits}},{key:"state",get:function(){return this._internalState.state}},{key:"_statusSource",get:function(){return this._dataSource}},{key:"add",value:function(){var d=Z.default(P.default.mark(function y(g,b){return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.abrupt("return",this._participantsEntity.add(g,b??{}));case 1:case"end":return S.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"addNonChatParticipant",value:function(){var d=Z.default(P.default.mark(function y(g,b){var w,S,C=arguments;return P.default.wrap(function(F){for(;;)switch(F.prev=F.next){case 0:return w=C.length>2&&C[2]!==void 0?C[2]:{},S=C.length>3&&C[3]!==void 0?C[3]:{},F.abrupt("return",this._participantsEntity.addNonChatParticipant(g,b,w??{},S??{}));case 3:case"end":return F.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"advanceLastReadMessageIndex",value:function(){var d=Z.default(P.default.mark(function y(g){var b;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._subscribeStreams();case 2:if(!(g<((b=this.lastReadMessageIndex)!==null&&b!==void 0?b:0))){S.next=6;break}return S.next=5,this._setLastReadMessageIndex(this.lastReadMessageIndex);case 5:return S.abrupt("return",S.sent);case 6:return S.next=8,this._setLastReadMessageIndex(g);case 8:return S.abrupt("return",S.sent);case 9:case"end":return S.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"delete",value:function(){var d=Z.default(P.default.mark(function y(){return P.default.wrap(function(b){for(;;)switch(b.prev=b.next){case 0:return b.next=2,this._services.commandExecutor.mutateResource("delete",this._links.self);case 2:return b.abrupt("return",this);case 3:case"end":return b.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getAttributes",value:function(){var d=Z.default(P.default.mark(function y(){return P.default.wrap(function(b){for(;;)switch(b.prev=b.next){case 0:return b.next=2,this._subscribe();case 2:return b.abrupt("return",this.attributes);case 3:case"end":return b.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getMessages",value:function(){var d=Z.default(P.default.mark(function y(g,b,w){return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:return C.next=2,this._subscribeStreams();case 2:return C.abrupt("return",this._messagesEntity.getMessages(g,b,w));case 3:case"end":return C.stop()}},y,this)}));function h(y,g,b){return d.apply(this,arguments)}return h}()},{key:"getParticipants",value:function(){var d=Z.default(P.default.mark(function y(){return P.default.wrap(function(b){for(;;)switch(b.prev=b.next){case 0:return b.next=2,this._subscribeStreams();case 2:return b.abrupt("return",this._participantsEntity.getParticipants());case 3:case"end":return b.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getParticipantsCount",value:function(){var d=Z.default(P.default.mark(function y(){var g,b,w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:return b=new At(this._configuration.links.conversations).path(this.sid).build(),C.next=3,this._services.network.get(b);case 3:return w=C.sent,C.abrupt("return",(g=w.body.participants_count)!==null&&g!==void 0?g:0);case 5:case"end":return C.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getParticipantBySid",value:function(){var d=Z.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.abrupt("return",this._participantsEntity.getParticipantBySid(g));case 1:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getParticipantByIdentity",value:function(){var d=Z.default(P.default.mark(function y(){var g,b=arguments;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return g=b.length>0&&b[0]!==void 0?b[0]:"",S.abrupt("return",this._participantsEntity.getParticipantByIdentity(g??""));case 2:case"end":return S.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getMessagesCount",value:function(){var d=Z.default(P.default.mark(function y(){var g,b,w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:return b=new At(this._configuration.links.conversations).path(this.sid).build(),C.next=3,this._services.network.get(b);case 3:return w=C.sent,C.abrupt("return",(g=w.body.messages_count)!==null&&g!==void 0?g:0);case 5:case"end":return C.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getUnreadMessagesCount",value:function(){var d=Z.default(P.default.mark(function y(){var g,b,w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:return g=new At(this._configuration.links.myConversations).path(this.sid).build(),C.next=3,this._services.network.get(g);case 3:if(b=C.sent,b.body.conversation_sid===this.sid){C.next=6;break}throw new Error("Conversation was not found in the user conversations list");case 6:if(w=b.body.unread_messages_count,typeof w!="number"){C.next=9;break}return C.abrupt("return",w);case 9:return C.abrupt("return",null);case 10:case"end":return C.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"join",value:function(){var d=Z.default(P.default.mark(function y(){return P.default.wrap(function(b){for(;;)switch(b.prev=b.next){case 0:return b.next=2,this._services.commandExecutor.mutateResource("post",this._links.participants,{identity:this._configuration.userIdentity});case 2:return b.abrupt("return",this);case 3:case"end":return b.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"leave",value:function(){var d=Z.default(P.default.mark(function y(){return P.default.wrap(function(b){for(;;)switch(b.prev=b.next){case 0:if(this._internalState.status!=="joined"){b.next=3;break}return b.next=3,this._services.commandExecutor.mutateResource("delete","".concat(this._links.participants,"/").concat(encodeURIComponent(this._configuration.userIdentity)));case 3:return b.abrupt("return",this);case 4:case"end":return b.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"removeParticipant",value:function(){var d=Z.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._participantsEntity.remove(typeof g=="string"?g:g.sid);case 2:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"sendMessage",value:function(){var d=Z.default(P.default.mark(function y(g,b,w){var S,C,U,F;return P.default.wrap(function(W){for(;;)switch(W.prev=W.next){case 0:if(!(typeof g=="string"||g===null)){W.next=5;break}return W.next=3,this._messagesEntity.send(g,b,w);case 3:return U=W.sent,W.abrupt("return",(C=yt(U.index))!==null&&C!==void 0?C:0);case 5:return W.next=7,this._messagesEntity.sendMedia(g,b,w);case 7:return F=W.sent,W.abrupt("return",(S=yt(F.index))!==null&&S!==void 0?S:0);case 9:case"end":return W.stop()}},y,this)}));function h(y,g,b){return d.apply(this,arguments)}return h}()},{key:"prepareMessage",value:function(){return new or(this.limits,this._messagesEntity)}},{key:"setAllMessagesRead",value:function(){var d=Z.default(P.default.mark(function y(){var g;return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._subscribeStreams();case 2:return w.next=4,this.getMessages(1);case 4:if(g=w.sent,!(g.items.length>0)){w.next=7;break}return w.abrupt("return",this.advanceLastReadMessageIndex(g.items[0].index));case 7:return w.abrupt("return",0);case 8:case"end":return w.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"setAllMessagesUnread",value:function(){var d=Z.default(P.default.mark(function y(){return P.default.wrap(function(b){for(;;)switch(b.prev=b.next){case 0:return b.next=2,this._subscribeStreams();case 2:return b.next=4,this._setLastReadMessageIndex(null);case 4:return b.abrupt("return",b.sent);case 5:case"end":return b.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"setUserNotificationLevel",value:function(){var d=Z.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._services.commandExecutor.mutateResource("post","".concat(this._configuration.links.myConversations,"/").concat(this.sid),{notification_level:g});case 2:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"typing",value:function(){return this._services.typingIndicator.send(this.sid)}},{key:"updateAttributes",value:function(){var d=Z.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._services.commandExecutor.mutateResource("post",this._links.self,{attributes:g!==void 0?JSON.stringify(g):void 0});case 2:return w.abrupt("return",this);case 3:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"updateFriendlyName",value:function(){var d=Z.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:if(this._internalState.friendlyName===g){w.next=3;break}return w.next=3,this._services.commandExecutor.mutateResource("post",this._links.self,{friendly_name:g});case 3:return w.abrupt("return",this);case 4:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"updateLastReadMessageIndex",value:function(){var d=Z.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._subscribeStreams();case 2:return w.abrupt("return",this._setLastReadMessageIndex(g));case 3:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"updateUniqueName",value:function(){var d=Z.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:if(this._internalState.uniqueName===g){w.next=4;break}return g||(g=""),w.next=4,this._services.commandExecutor.mutateResource("post",this._links.self,{unique_name:g});case 4:return w.abrupt("return",this);case 5:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getMessageRecipients",value:function(){var d=Z.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._services.messageRecipientsClient.getRecipientsFromConversation(this.sid,g);case 2:return w.abrupt("return",w.sent);case 3:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"_subscribe",value:function(){var d=Z.default(P.default.mark(function y(){var g=this;return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:if(!this._entityPromise){w.next=2;break}return w.abrupt("return",this._entityPromise);case 2:return this._entityPromise=this._services.syncClient.document({id:this._entityName,mode:"open_existing"}),w.prev=3,w.next=6,this._entityPromise;case 6:return this._entity=w.sent,this._entity.on(J.SyncDocument.updated,function(S){return g._update(S.data)}),this._entity.on(J.SyncDocument.removed,function(){return g.emit(f.removed,g)}),this._update(this._entity.data),w.abrupt("return",this._entity);case 13:throw w.prev=13,w.t0=w.catch(3),this._entity=null,this._entityPromise=null,this._services.syncClient.connectionState!="disconnected"&&f._logger.error("Failed to get conversation object",w.t0),f._logger.debug("ERROR: Failed to get conversation object",w.t0),w.t0;case 20:case"end":return w.stop()}},y,this,[[3,13]])}));function h(){return d.apply(this,arguments)}return h}()},{key:"_fetchStreams",value:function(){var d=Z.default(P.default.mark(function y(){var g,b,w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:return C.next=2,this._subscribe();case 2:return f._logger.trace("_streamsAvailable, this.entity.data=",(g=this._entity)===null||g===void 0?void 0:g.data),w=(b=this._entity)===null||b===void 0?void 0:b.data,C.next=6,this._services.syncClient.list({id:w.messages,mode:"open_existing"});case 6:return this._messagesList=C.sent,C.next=9,this._services.syncClient.map({id:w.roster,mode:"open_existing"});case 9:this._participantsMap=C.sent;case 10:case"end":return C.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_subscribeStreams",value:function(){var d=Z.default(P.default.mark(function y(){var g,b,w,S,C,U,F;return P.default.wrap(function(W){for(;;)switch(W.prev=W.next){case 0:return W.prev=0,W.next=3,this._subscribe();case 3:return f._logger.trace("_subscribeStreams, this.entity.data=",(g=this._entity)===null||g===void 0?void 0:g.data),C=(b=this._entity)===null||b===void 0?void 0:b.data,U=C.messages,F=C.roster,W.next=9,Promise.all([this._messagesEntity.subscribe((w=this._messagesList)!==null&&w!==void 0?w:U),this._participantsEntity.subscribe((S=this._participantsMap)!==null&&S!==void 0?S:F)]);case 9:W.next=16;break;case 11:throw W.prev=11,W.t0=W.catch(0),this._services.syncClient.connectionState!=="disconnected"&&f._logger.error("Failed to subscribe on conversation objects",this.sid,W.t0),f._logger.debug("ERROR: Failed to subscribe on conversation objects",this.sid,W.t0),W.t0;case 16:case"end":return W.stop()}},y,this,[[0,11]])}));function h(){return d.apply(this,arguments)}return h}()},{key:"_unsubscribe",value:function(){var d=Z.default(P.default.mark(function y(){return P.default.wrap(function(b){for(;;)switch(b.prev=b.next){case 0:return this._entity&&(this._entity.close(),this._entity=null,this._entityPromise=null),b.abrupt("return",Promise.all([this._participantsEntity.unsubscribe(),this._messagesEntity.unsubscribe()]));case 2:case"end":return b.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_setStatus",value:function(h,y){var g=this;if(this._dataSource=y,this._internalState.status!==h){if(this._internalState.status=h,h==="joined"){this._subscribeStreams().catch(function(b){if(f._logger.debug("ERROR while setting conversation status "+h,b),g._services.syncClient.connectionState!=="disconnected")throw b});return}this._entityPromise&&this._unsubscribe().catch(function(b){if(f._logger.debug("ERROR while setting conversation status "+h,b),g._services.syncClient.connectionState!=="disconnected")throw b})}}},{key:"_update",value:function(h){var y,g,b,w,S;f._logger.trace("_update",h),f.preprocessUpdate(h,this.sid);for(var C=new Set,U=0,F=Object.keys(h);U<F.length;U++){var H=F[U],W=yn[H];if(W)switch(W){case yn.status:if(!h.status||h.status==="unknown"||this._internalState.status===h.status)break;this._internalState.status=h.status,C.add(W);break;case yn.attributes:if(be.default(this._internalState.attributes,h.attributes))break;this._internalState.attributes=h.attributes,C.add(W);break;case yn.lastConsumedMessageIndex:if(h.lastConsumedMessageIndex===void 0||h.lastConsumedMessageIndex===this._internalState.lastReadMessageIndex)break;this._internalState.lastReadMessageIndex=h.lastConsumedMessageIndex,C.add("lastReadMessageIndex");break;case yn.lastMessage:if(this._internalState.lastMessage&&!h.lastMessage){delete this._internalState.lastMessage,C.add(W);break}this._internalState.lastMessage=this._internalState.lastMessage||{},((y=h.lastMessage)===null||y===void 0?void 0:y.index)!==void 0&&h.lastMessage.index!==this._internalState.lastMessage.index&&(this._internalState.lastMessage.index=h.lastMessage.index,C.add(W)),((g=h.lastMessage)===null||g===void 0?void 0:g.timestamp)!==void 0&&((b=this._internalState.lastMessage)===null||b===void 0||(w=b.dateCreated)===null||w===void 0?void 0:w.getTime())!==h.lastMessage.timestamp.getTime()&&(this._internalState.lastMessage.dateCreated=h.lastMessage.timestamp,C.add(W)),be.default(this._internalState.lastMessage,{})&&delete this._internalState.lastMessage;break;case yn.state:var Me=h.state||void 0;if(Me!==void 0&&(Me.dateUpdated=new Date(Me.dateUpdated)),be.default(this._internalState.state,Me))break;this._internalState.state=Me,C.add(W);break;case yn.bindings:if(be.default(this._internalState.bindings,h.bindings))break;this._internalState.bindings=h.bindings,C.add(W);break;default:var Je=h[H]instanceof Date,Be=Je&&((S=this._internalState[W])===null||S===void 0?void 0:S.getTime())===h[H].getTime(),Ge=!Je&&this[W]===h[H];if(Be||Ge)break;this._internalState[W]=h[H],C.add(W)}}C.size>0&&this.emit(f.updated,{conversation:this,updateReasons:Fe.default(C)})}},{key:"_onMessageAdded",value:function(h){var y=Ba(this._participants.values()),g;try{for(y.s();!(g=y.n()).done;){var b=g.value;if(b.identity===h.author){b._endTyping();break}}}catch(w){y.e(w)}finally{y.f()}this.emit(f.messageAdded,h)}},{key:"_setLastReadMessageIndex",value:function(){var d=Z.default(P.default.mark(function y(g){var b;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._services.commandExecutor.mutateResource("post","".concat(this._configuration.links.myConversations,"/").concat(this.sid),{last_read_message_index:g});case 2:return b=S.sent,S.abrupt("return",b.unread_messages_count);case 4:case"end":return S.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()}],[{key:"preprocessUpdate",value:function(h,y){try{typeof h.attributes=="string"?h.attributes=JSON.parse(h.attributes):h.attributes&&JSON.stringify(h.attributes)}catch{f._logger.warn("Retrieved malformed attributes from the server for conversation: "+y),h.attributes={}}try{h.dateCreated&&(h.dateCreated=new Date(h.dateCreated))}catch{f._logger.warn("Retrieved malformed dateCreated from the server for conversation: "+y),delete h.dateCreated}try{h.dateUpdated&&(h.dateUpdated=new Date(h.dateUpdated))}catch{f._logger.warn("Retrieved malformed dateUpdated from the server for conversation: "+y),delete h.dateUpdated}try{h.lastMessage&&h.lastMessage.timestamp&&(h.lastMessage.timestamp=new Date(h.lastMessage.timestamp))}catch{f._logger.warn("Retrieved malformed lastMessage.timestamp from the server for conversation: "+y),delete h.lastMessage.timestamp}}}]),f}(I.ReplayEventEmitter);Pe.default(It,"participantJoined","participantJoined"),Pe.default(It,"participantLeft","participantLeft"),Pe.default(It,"participantUpdated","participantUpdated"),Pe.default(It,"messageAdded","messageAdded"),Pe.default(It,"messageRemoved","messageRemoved"),Pe.default(It,"messageUpdated","messageUpdated"),Pe.default(It,"typingEnded","typingEnded"),Pe.default(It,"typingStarted","typingStarted"),Pe.default(It,"updated","updated"),Pe.default(It,"removed","removed"),Pe.default(It,"_logger",Dt.scope("Conversation")),we([_.validateTypesAsync(_.nonEmptyString,Cr),fe("design:type",Function),fe("design:paramtypes",[String,Object]),fe("design:returntype",Promise)],It.prototype,"add",null),we([_.validateTypesAsync(_.nonEmptyString,_.nonEmptyString,Cr,Cr),fe("design:type",Function),fe("design:paramtypes",[String,String,Object,Object]),fe("design:returntype",Promise)],It.prototype,"addNonChatParticipant",null),we([_.validateTypesAsync(_.nonNegativeInteger),fe("design:type",Function),fe("design:paramtypes",[Number]),fe("design:returntype",Promise)],It.prototype,"advanceLastReadMessageIndex",null),we([_.validateTypesAsync(["undefined",_.nonNegativeInteger],["undefined",_.nonNegativeInteger],["undefined",_.literal("backwards","forward")]),fe("design:type",Function),fe("design:paramtypes",[Number,Number,String]),fe("design:returntype",Promise)],It.prototype,"getMessages",null),we([_.validateTypesAsync(_.nonEmptyString),fe("design:type",Function),fe("design:paramtypes",[String]),fe("design:returntype",Promise)],It.prototype,"getParticipantBySid",null),we([_.validateTypesAsync(_.nonEmptyString),fe("design:type",Function),fe("design:paramtypes",[String]),fe("design:returntype",Promise)],It.prototype,"getParticipantByIdentity",null),we([_.validateTypesAsync([_.nonEmptyString,V]),fe("design:type",Function),fe("design:paramtypes",[Object]),fe("design:returntype",Promise)],It.prototype,"removeParticipant",null),we([_.validateTypesAsync(["string",FormData,_.literal(null),_.objectSchema("media options",{contentType:_.nonEmptyString,media:_.custom(function(O){var A=typeof O=="string"&&O.length>0||O instanceof Uint8Array||O instanceof ArrayBuffer;return typeof Blob=="function"&&(A=A||O instanceof Blob),[A,"a non-empty string, an instance of Buffer or an instance of Blob"]})})],Cr,["undefined",_.literal(null),_.objectSchema("email attributes",{subject:[_.nonEmptyString,"undefined"]})]),fe("design:type",Function),fe("design:paramtypes",[Object,Object,Object]),fe("design:returntype",Promise)],It.prototype,"sendMessage",null),we([_.validateTypesAsync(_.literal("default","muted")),fe("design:type",Function),fe("design:paramtypes",[String]),fe("design:returntype",Promise)],It.prototype,"setUserNotificationLevel",null),we([_.validateTypesAsync(cr),fe("design:type",Function),fe("design:paramtypes",[Object]),fe("design:returntype",Promise)],It.prototype,"updateAttributes",null),we([_.validateTypesAsync("string"),fe("design:type",Function),fe("design:paramtypes",[String]),fe("design:returntype",Promise)],It.prototype,"updateFriendlyName",null),we([_.validateTypesAsync([_.literal(null),_.nonNegativeInteger]),fe("design:type",Function),fe("design:paramtypes",[Number]),fe("design:returntype",Promise)],It.prototype,"updateLastReadMessageIndex",null),we([_.validateTypesAsync(["string",_.literal(null)]),fe("design:type",Function),fe("design:paramtypes",[String]),fe("design:returntype",Promise)],It.prototype,"updateUniqueName",null);var ua=function(){function O(){var A=this;he.default(this,O),this._promise=new Promise(function(f,d){A._resolve=f,A._reject=d})}return me.default(O,[{key:"promise",get:function(){return this._promise}},{key:"update",value:function(f){this._resolve(f)}},{key:"set",value:function(f){this.current=f,this._resolve(f)}},{key:"fail",value:function(f){this._reject(f)}}]),O}();function ca(O,A){var f=typeof Symbol<"u"&&O[Symbol.iterator]||O["@@iterator"];if(!f){if(Array.isArray(O)||(f=Pi(O))||A){f&&(O=f);var d=0,h=function(){};return{s:h,n:function(){return d>=O.length?{done:!0}:{done:!1,value:O[d++]}},e:function(S){throw S},f:h}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
462
462
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var y=!0,g=!1,b;return{s:function(){f=f.call(O)},n:function(){var S=f.next();return y=S.done,S},e:function(S){g=!0,b=S},f:function(){try{!y&&f.return!=null&&f.return()}finally{if(g)throw b}}}}function Pi(O,A){if(O){if(typeof O=="string")return Mi(O,A);var f=Object.prototype.toString.call(O).slice(8,-1);if(f==="Object"&&O.constructor&&(f=O.constructor.name),f==="Map"||f==="Set")return Array.from(O);if(f==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(f))return Mi(O,A)}}function Mi(O,A){(A==null||A>O.length)&&(A=O.length);for(var f=0,d=new Array(A);f<A;f++)d[f]=O[f];return d}function li(O,A){var f=Object.keys(O);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(O);A&&(d=d.filter(function(h){return Object.getOwnPropertyDescriptor(O,h).enumerable})),f.push.apply(f,d)}return f}function Gn(O){for(var A=1;A<arguments.length;A++){var f=arguments[A]!=null?arguments[A]:{};A%2?li(Object(f),!0).forEach(function(d){Pe.default(O,d,f[d])}):Object.getOwnPropertyDescriptors?Object.defineProperties(O,Object.getOwnPropertyDescriptors(f)):li(Object(f)).forEach(function(d){Object.defineProperty(O,d,Object.getOwnPropertyDescriptor(f,d))})}return O}function kr(O){var A=la();return function(){var d=vt.default(O),h;if(A){var y=vt.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return Nt.default(this,h)}}function la(){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 Rr=Dt.scope("Conversations"),Gr=function(O){Qe.default(f,O);var A=kr(f);function f(d,h){var y;return he.default(this,f),y=A.call(this),Pe.default(qe.default(y),"conversations",new Map),Pe.default(qe.default(y),"myConversationsRead",new ua),Pe.default(qe.default(y),"tombstones",new Set),Pe.default(qe.default(y),"myConversationsFetched",!1),y.configuration=d,y.services=h,y}return me.default(f,[{key:"addConversation",value:function(){var d=Z.default(P.default.mark(function y(g){var b,w,S,C,U,F,H,W,Me,Je;return P.default.wrap(function(Ge){for(;;)switch(Ge.prev=Ge.next){case 0:return C=typeof(g==null?void 0:g.attributes)<"u"?g.attributes:{},Ge.next=3,this.services.commandExecutor.mutateResource("post",this.configuration.links.conversations,{friendly_name:g.friendlyName,unique_name:g.uniqueName,attributes:typeof C<"u"?JSON.stringify(C):void 0});case 3:if(U=Ge.sent,F=(b=U.sid)!==null&&b!==void 0?b:null,H=(w=(S=U.sync_objects)===null||S===void 0?void 0:S.conversation)!==null&&w!==void 0?w:null,W=Gn({self:U.url},U.links),Me=this.conversations.get(F),!Me){Ge.next=12;break}return Ge.next=11,Me._subscribe();case 11:return Ge.abrupt("return",Me);case 12:return Je=new It({channel:H,entityName:"",uniqueName:"",attributes:null,createdBy:"",friendlyName:"",lastConsumedMessageIndex:0,dateCreated:null,dateUpdated:null},F,W,this.configuration,this.services),this.conversations.set(Je.sid,Je),this._registerForEvents(Je),Ge.next=17,Je._subscribe();case 17:return this.emit("conversationAdded",Je),Ge.abrupt("return",Je);case 19:case"end":return Ge.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"fetchConversations",value:function(){var d=Z.default(P.default.mark(function y(){var g=this,b,w,S,C,U,F,H;return P.default.wrap(function(Me){for(;;)switch(Me.prev=Me.next){case 0:return Me.prev=0,Me.next=3,this._getMap();case 3:return b=Me.sent,b.on(J.SyncMap.itemAdded,function(Je){Rr.debug("itemAdded: ".concat(Je.item.key)),g._upsertConversation("sync",Je.item.key,Je.item.data)}),b.on(J.SyncMap.itemRemoved,function(Je){Rr.debug("itemRemoved: ".concat(Je.key));var Be=Je.key;g.myConversationsFetched||g.tombstones.add(Be);var Ge=g.conversations.get(Be);Ge&&(Ge.status==="joined"&&(Ge._setStatus("notParticipating","sync"),g.emit("conversationLeft",Ge)),g.conversations.delete(Be),g.emit("conversationRemoved",Ge),Ge.emit("removed",Ge))}),b.on(J.SyncMap.itemUpdated,function(Je){Rr.debug("itemUpdated: ".concat(Je.item.key)),g._upsertConversation("sync",Je.item.key,Je.item.data)}),Me.next=9,this._fetchMyConversations();case 9:w=Me.sent,S=[],C=ca(w);try{for(C.s();!(U=C.n()).done;)F=U.value,S.push(this._upsertConversation("rest",F.channel_sid,F))}catch(Je){C.e(Je)}finally{C.f()}return this.myConversationsRead.set(!0),Me.next=16,Promise.all(S);case 16:return this.myConversationsFetched=!0,this.tombstones.clear(),Rr.debug("The conversations list has been successfully fetched"),Me.abrupt("return",this);case 22:throw Me.prev=22,Me.t0=Me.catch(0),H="Failed to fetch the conversations list",this.services.syncClient.connectionState!=="disconnected"&&Rr.error(H,Me.t0),Rr.debug("ERROR: ".concat(H),Me.t0),Me.t0;case 28:case"end":return Me.stop()}},y,this,[[0,22]])}));function h(){return d.apply(this,arguments)}return h}()},{key:"getConversations",value:function(){var d=Z.default(P.default.mark(function y(){var g=this,b,w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:return C.next=2,this._getMap();case 2:return b=C.sent,C.next=5,b.getItems();case 5:return w=C.sent,C.abrupt("return",this._wrapPaginator(w,function(U){return Promise.all(U.map(function(F){return g._upsertConversation("sync",F.key,F.data)}))}));case 7:case"end":return C.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getConversation",value:function(){var d=Z.default(P.default.mark(function y(g){var b=this,w,S,C;return P.default.wrap(function(F){for(;;)switch(F.prev=F.next){case 0:return F.next=2,this._getMap();case 2:return w=F.sent,F.next=5,w.getItems({key:g});case 5:return S=F.sent,C=S.items.map(function(H){return b._upsertConversation("sync",H.key,H.data)}),F.abrupt("return",C.length>0?C[0]:null);case 8:case"end":return F.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getConversationByUniqueName",value:function(){var d=Z.default(P.default.mark(function y(g){var b,w,S,C,U;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:return b=new At(this.configuration.links.myConversations).path(g).build(),H.next=3,this.services.network.get(b);case 3:return w=H.sent,S=w.body,C=S.conversation_sid,U={entityName:null,lastConsumedMessageIndex:S.last_read_message_index,status:(S==null?void 0:S.status)||"unknown",friendlyName:S.friendly_name,dateUpdated:S.date_updated,dateCreated:S.date_created,uniqueName:S.unique_name,createdBy:S.created_by,attributes:S.attributes,channel:S.sync_objects.conversation,notificationLevel:S==null?void 0:S.notification_level,sid:C},H.abrupt("return",C?this._upsertConversation("sync",C,U):null);case 8:case"end":return H.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"peekConversation",value:function(){var d=Z.default(P.default.mark(function y(g){var b,w,S,C;return P.default.wrap(function(F){for(;;)switch(F.prev=F.next){case 0:return b=new At(this.configuration.links.conversations).path(g).build(),F.next=3,this.services.network.get(b);case 3:return w=F.sent,S=w.body,C={entityName:null,status:(S==null?void 0:S.status)||"unknown",friendlyName:S.friendly_name,dateUpdated:S.date_updated,dateCreated:S.date_created,uniqueName:S.unique_name,createdBy:S.created_by,attributes:S.attributes,channel:"".concat(g,".channel"),sid:g},F.abrupt("return",this._upsertConversation("sync",g,C));case 7:case"end":return F.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"_getMap",value:function(){var d=Z.default(P.default.mark(function y(){return P.default.wrap(function(b){for(;;)switch(b.prev=b.next){case 0:return b.next=2,this.services.syncClient.map({id:this.configuration.myConversations,mode:"open_existing"});case 2:return b.abrupt("return",b.sent);case 3:case"end":return b.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_wrapPaginator",value:function(){var d=Z.default(P.default.mark(function y(g,b){var w=this,S;return P.default.wrap(function(U){for(;;)switch(U.prev=U.next){case 0:return U.next=2,b(g.items);case 2:return S=U.sent,U.abrupt("return",{items:S.filter(function(F){return F!==null}),hasNextPage:g.hasNextPage,hasPrevPage:g.hasPrevPage,nextPage:function(){return g.nextPage().then(function(H){return w._wrapPaginator(H,b)})},prevPage:function(){return g.prevPage().then(function(H){return w._wrapPaginator(H,b)})}});case 4:case"end":return U.stop()}},y)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"_updateConversation",value:function(){var d=Z.default(P.default.mark(function y(g,b,w){var S,C,U;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:if(S=b._statusSource!==void 0&&g!==b._statusSource,C=g!=="rest"||b._statusSource==="sync",!(S&&C&&g!=="sync")){H.next=5;break}return Rr.trace("upsertConversation: conversation is known from sync and came from REST, ignoring",{sid:b.sid,data:w.status,conversation:b.status}),H.abrupt("return");case 5:if(!(w.status==="joined"&&b.status!=="joined")){H.next=15;break}return b._setStatus("joined",g),U={},typeof w.notificationLevel<"u"&&(U.notificationLevel=w.notificationLevel),typeof w.lastConsumedMessageIndex<"u"&&(U.lastConsumedMessageIndex=w.lastConsumedMessageIndex),be.default(U,{})||b._update(U),H.next=13,b._subscribe();case 13:return this.emit("conversationJoined",b),H.abrupt("return");case 15:if(!(w.status==="notParticipating"&&b.status==="joined")){H.next=22;break}return b._setStatus("notParticipating",g),b._update(w),H.next=20,b._subscribe();case 20:return this.emit("conversationLeft",b),H.abrupt("return");case 22:if(w.status!=="notParticipating"){H.next=26;break}return H.next=25,b._subscribe();case 25:return H.abrupt("return");case 26:b._update(w);case 27:case"end":return H.stop()}},y,this)}));function h(y,g,b){return d.apply(this,arguments)}return h}()},{key:"_upsertConversation",value:function(){var d=Z.default(P.default.mark(function y(g,b,w){var S,C,U,F;return P.default.wrap(function(W){for(;;)switch(W.prev=W.next){case 0:if(Rr.trace("upsertConversation called for ".concat(b),w),S=this.conversations.get(b),!S){W.next=9;break}return Rr.trace("upsertConversation: the conversation ".concat(S.sid," is known;")+"its status is known from the source ".concat(S._statusSource," ")+"and the update came from the source ".concat(g),S),W.next=6,this._updateConversation(g,S,w);case 6:return W.next=8,S._subscribe();case 8:return W.abrupt("return",S);case 9:if(!(g==="rest"&&this.tombstones.has(b))){W.next=12;break}return Rr.trace("upsertChannel: the conversation is deleted but reappeared again from REST, ignoring",b),W.abrupt("return",null);case 12:return Rr.trace("upsertConversation: creating a local conversation object with sid "+b,w),C="".concat(this.configuration.links.conversations,"/").concat(b),U={self:C,messages:"".concat(C,"/Messages"),participants:"".concat(C,"/Participants")},F=new It(w,b,U,this.configuration,this.services),this.conversations.set(b,F),W.prev=17,W.next=20,F._subscribe();case 20:if(w.status!=="joined"){W.next=23;break}return W.next=23,F._fetchStreams();case 23:W.next=32;break;case 25:if(W.prev=25,W.t0=W.catch(17),W.t0.name==="SyncError"){W.next=29;break}throw W.t0;case 29:return Rr.trace("upsertChannel: the conversation is missing some Sync entity(ies), ignoring",b,W.t0),this.conversations.delete(b),W.abrupt("return",null);case 32:return this._registerForEvents(F),this.emit("conversationAdded",F),w.status==="joined"&&(F._setStatus("joined",g),this.emit("conversationJoined",F)),W.abrupt("return",F);case 36:case"end":return W.stop()}},y,this,[[17,25]])}));function h(y,g,b){return d.apply(this,arguments)}return h}()},{key:"_fetchMyConversations",value:function(){var d=Z.default(P.default.mark(function y(){var g,b,w,S,C,U;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:g=[],b=null;case 2:return S=new At(this.configuration.links.myConversations),b&&S.arg("PageToken",b),H.next=6,this.services.network.get(S.build());case 6:C=H.sent,U=(w=C.body)===null||w===void 0?void 0:w.conversations.map(function(W){return{descriptor:W,channel_sid:W.conversation_sid,status:W.status,channel:W.sync_objects.conversation,messages:W.sync_objects.messages,roster:"".concat(W.conversation_sid,".roster"),lastConsumedMessageIndex:W.last_read_message_index,notificationLevel:W.notification_level}}),b=C.body.meta.next_token,g=[].concat(Fe.default(g),Fe.default(U));case 10:if(b){H.next=2;break}case 11:return H.abrupt("return",g);case 12:case"end":return H.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_onConversationRemoved",value:function(h){var y=this.conversations.get(h);y&&(this.conversations.delete(h),this.emit("conversationRemoved",y))}},{key:"_registerForEvents",value:function(h){var y=this;h.on("removed",function(){return y._onConversationRemoved(h.sid)}),h.on("updated",function(g){return y.emit("conversationUpdated",g)}),h.on("participantJoined",function(g){return y.emit("participantJoined",g)}),h.on("participantLeft",function(g){return y.emit("participantLeft",g)}),h.on("participantUpdated",function(g){return y.emit("participantUpdated",g)}),h.on("messageAdded",function(g){return y.emit("messageAdded",g)}),h.on("messageUpdated",function(g){return y.emit("messageUpdated",g)}),h.on("messageRemoved",function(g){return y.emit("messageRemoved",g)}),h.on("typingStarted",function(g){return y.emit("typingStarted",g)}),h.on("typingEnded",function(g){return y.emit("typingEnded",g)})}}]),f}(I.ReplayEventEmitter);function bn(O){var A=fa();return function(){var d=vt.default(O),h;if(A){var y=vt.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return Nt.default(this,h)}}function fa(){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 D=function(O){Qe.default(f,O);var A=bn(f);function f(d,h,y){var g;return he.default(this,f),g=A.call(this),g.configuration=h,g.services=y,g.fifoStack=[],g.myself=d,g.myself.on("updated",function(b){return g.emit("userUpdated",b)}),g.myself.on("userSubscribed",function(){return g.emit("userSubscribed",g.myself)}),g.myself.on("userUnsubscribed",function(){g.emit("userUnsubscribed",g.myself),g.myself._ensureFetched()}),g.subscribedUsers=new Map,g}return me.default(f,[{key:"handleUnsubscribeUser",value:function(h){this.subscribedUsers.has(h.identity)&&this.subscribedUsers.delete(h.identity);var y=0,g=this.fifoStack.find(function(b,w){return b==h.identity?(y=w,!0):!1});g&&this.fifoStack.splice(y,1),this.emit("userUnsubscribed",h)}},{key:"handleSubscribeUser",value:function(h){if(!this.subscribedUsers.has(h.identity)){if(this.fifoStack.length>=this.configuration.userInfosToSubscribe){var y,g,b=this.fifoStack.shift();(y=this.subscribedUsers)===null||y===void 0||(g=y.get(b))===null||g===void 0||g.unsubscribe()}this.fifoStack.push(h.identity),this.subscribedUsers.set(h.identity,h),this.emit("userSubscribed",h)}}},{key:"getUser",value:function(){var d=Z.default(P.default.mark(function y(g,b){var w,S=this,C,U;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:return H.next=2,this.myself._ensureFetched();case 2:if(g!=this.myself.identity){H.next=4;break}return H.abrupt("return",this.myself);case 4:if(C=this.subscribedUsers.get(g),!C){H.next=7;break}return H.abrupt("return",C);case 7:if(!((w=b)!==null&&w!==void 0)){H.next=11;break}H.next=14;break;case 11:return H.next=13,this.getSyncUniqueName(g);case 13:b=H.sent;case 14:return U=new ve(g,b,this.configuration,this.services),U.on("updated",function(W){return S.emit("userUpdated",W)}),U.on("userSubscribed",function(){return S.handleSubscribeUser(U)}),U.on("userUnsubscribed",function(){return S.handleUnsubscribeUser(U)}),H.next=20,U._ensureFetched();case 20:return H.abrupt("return",U);case 21:case"end":return H.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"getSubscribedUsers",value:function(){var d=Z.default(P.default.mark(function y(){var g;return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this.myself._ensureFetched();case 2:return g=[this.myself],this.subscribedUsers.forEach(function(S){return g.push(S)}),w.abrupt("return",g);case 5:case"end":return w.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getSyncUniqueName",value:function(){var d=Z.default(P.default.mark(function y(g){var b,w,S,C;return P.default.wrap(function(F){for(;;)switch(F.prev=F.next){case 0:return S=new At(this.configuration.links.users).path(g).build(),F.next=3,this.services.network.get(S);case 3:return C=F.sent,F.abrupt("return",(b=(w=C.body)===null||w===void 0?void 0:w.sync_objects.user_info_map)!==null&&b!==void 0?b:"");case 5:case"end":return F.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()}]),f}(I.ReplayEventEmitter),q=Dt.scope("TypingIndicator"),R=function(){function O(A,f,d){he.default(this,O),this.configuration=f,this.services=d,this.getConversation=A,this.serviceTypingTimeout=null,this.sentUpdates=new Map}return me.default(O,[{key:"typingTimeout",get:function(){return this.configuration.typingIndicatorTimeoutOverride||this.serviceTypingTimeout||this.configuration.typingIndicatorTimeoutDefault}},{key:"initialize",value:function(){var f=this;this.services.notificationClient.on("message",function(){var d=Z.default(P.default.mark(function h(y,g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:if(y!==ge.TYPING_INDICATOR){w.next=3;break}return w.next=3,f._handleRemoteTyping(g);case 3:case"end":return w.stop()}},h)}));return function(h,y){return d.apply(this,arguments)}}())}},{key:"_handleRemoteTyping",value:function(){var A=Z.default(P.default.mark(function d(h){var y=this;return P.default.wrap(function(b){for(;;)switch(b.prev=b.next){case 0:q.trace("Got new typing indicator ",h),this.getConversation(h.channel_sid).then(function(w){w&&w._participants.forEach(function(S){if(S.identity===h.identity){var C=y.configuration.typingIndicatorTimeoutOverride?y.configuration.typingIndicatorTimeoutOverride+1e3:h.typing_timeout*1e3;S._startTyping(C)}})}).catch(function(w){throw q.error(w),w});case 2:case"end":return b.stop()}},d,this)}));function f(d){return A.apply(this,arguments)}return f}()},{key:"send",value:function(f){var d=this.sentUpdates.get(f);return d&&d>Date.now()-this.typingTimeout?Promise.resolve():(this.sentUpdates.set(f,Date.now()),this._send(f))}},{key:"_send",value:function(f){var d=this;q.trace("Sending typing indicator");var h=this.configuration.links.typing,y={"Content-Type":"application/x-www-form-urlencoded"},g="ChannelSid=".concat(f);return this.services.twilsockClient.post(h,y,g,this.configuration.productId).then(function(b){b.body.hasOwnProperty("typing_timeout")&&(d.serviceTypingTimeout=b.body.typing_timeout*1e3)}).catch(function(b){throw q.error("Failed to send typing indicator:",b),b})}}]),O}(),k=me.default(function O(A){he.default(this,O),this.title=A.title||null,this.body=A.body||null,this.sound=A.sound||null,this.badge=A.badge||null,this.action=A.action||null,this.type=A.type||null,this.data=A.data||{}}),E="2.6.0";function B(O,A){var f=Object.keys(O);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(O);A&&(d=d.filter(function(h){return Object.getOwnPropertyDescriptor(O,h).enumerable})),f.push.apply(f,d)}return f}function M(O){for(var A=1;A<arguments.length;A++){var f=arguments[A]!=null?arguments[A]:{};A%2?B(Object(f),!0).forEach(function(d){Pe.default(O,d,f[d])}):Object.getOwnPropertyDescriptors?Object.defineProperties(O,Object.getOwnPropertyDescriptors(f)):B(Object(f)).forEach(function(d){Object.defineProperty(O,d,Object.getOwnPropertyDescriptor(f,d))})}return O}function de(O){var A=le();return function(){var d=vt.default(O),h;if(A){var y=vt.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return Nt.default(this,h)}}function le(){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 Re=function(A){return A.replace(/(^\/+|\/+$)/g,"")},je=function(A){return A.status.code===202},at=function(O){Qe.default(f,O);var A=de(f);function f(d){return he.default(this,f),A.call(this,d)}return me.default(f)}(Ot.default(Error)),$r=function(){function O(A,f,d){he.default(this,O),this._serviceUrl=A,this._services=f,this._productId=d}return me.default(O,[{key:"_preProcessUrl",value:function(f){var d=Re(f);return/^https?:\/\//.test(f)?d:"".concat(Re(this._serviceUrl),"/").concat(d)}},{key:"_makeRequest",value:function(){var A=Z.default(P.default.mark(function d(h,y,g,b){var w,S,C,U;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:w=this._preProcessUrl(y),S=M({"Content-Type":"application/json; charset=utf-8"},b||{}),H.t0=h,H.next=H.t0==="get"?5:H.t0==="post"?11:H.t0==="delete"?15:19;break;case 5:return U=w,g&&(U+="?"+Object.entries(g).map(function(W){return W.map(encodeURIComponent).join("=")}).join("&")),H.next=9,this._services.transport.get(U,S,this._productId);case 9:return C=H.sent,H.abrupt("break",19);case 11:return H.next=13,this._services.transport.post(w,S,JSON.stringify(g),this._productId);case 13:return C=H.sent,H.abrupt("break",19);case 15:return H.next=17,this._services.transport.delete(w,S,{},this._productId);case 17:return C=H.sent,H.abrupt("break",19);case 19:if(!(C.status.code<200||C.status.code>=300)){H.next=21;break}throw new Error("Request responded with a non-success code ".concat(C.status.code));case 21:return H.abrupt("return",C);case 22:case"end":return H.stop()}},d,this)}));function f(d,h,y,g){return A.apply(this,arguments)}return f}()},{key:"fetchResource",value:function(){var A=Z.default(P.default.mark(function d(h,y){var g=this,b,w,S;return P.default.wrap(function(U){for(;;)switch(U.prev=U.next){case 0:return b=6,w=new N.AsyncRetrier({min:50,max:1600,maxAttemptsCount:b}),U.prev=2,U.next=5,w.run(Z.default(P.default.mark(function F(){var H,W,Me;return P.default.wrap(function(Be){for(;;)switch(Be.prev=Be.next){case 0:return Be.prev=0,Be.next=3,g._makeRequest("get",h,y);case 3:return H=Be.sent,Be.abrupt("return",{type:"success",data:H.body});case 7:if(Be.prev=7,Be.t0=Be.catch(0),!((Be.t0===null||Be.t0===void 0||(W=Be.t0.body)===null||W===void 0?void 0:W.status)===404&&(Be.t0===null||Be.t0===void 0||(Me=Be.t0.body)===null||Me===void 0?void 0:Me.code)===50530)){Be.next=11;break}return Be.abrupt("return",{type:"noMetadata"});case 11:throw Be.t0;case 12:case"end":return Be.stop()}},F,null,[[0,7]])})));case 5:S=U.sent,U.next=11;break;case 8:throw U.prev=8,U.t0=U.catch(2),new Error('Fetch resource from "'.concat(h,'" failed.'));case 11:if(S.type!=="noMetadata"){U.next=13;break}throw new at("No metadata found.");case 13:return U.abrupt("return",S.data);case 14:case"end":return U.stop()}},d,null,[[2,8]])}));function f(d,h){return A.apply(this,arguments)}return f}()},{key:"mutateResource",value:function(){var A=Z.default(P.default.mark(function d(h,y,g){var b;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._makeRequest(h,y,g,{"X-Twilio-Mutation-Id":ue.v4()});case 2:if(b=S.sent,!je(b)){S.next=7;break}return S.next=6,this.fetchResource(b.body.resource_url);case 6:return S.abrupt("return",S.sent);case 7:return S.abrupt("return",b.body);case 8:case"end":return S.stop()}},d,this)}));function f(d,h,y){return A.apply(this,arguments)}return f}()}]),O}(),ln=function(){function O(A){var f=arguments.length>1&&arguments[1]!==void 0?arguments[1]:100,d=arguments.length>2&&arguments[2]!==void 0?arguments[2]:5e3;he.default(this,O),Pe.default(this,"_cachedTemplates",null),this._services=A,this._pageSize=f,this._cacheTtlMs=d}return me.default(O,[{key:"getContentTemplates",value:function(){var A=Z.default(P.default.mark(function d(){var h=this,y,g,b,w,S,C,U;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:if(this._cachedTemplates===null){H.next=2;break}return H.abrupt("return",this._cachedTemplates);case 2:return H.next=4,this._fetchContentTemplates();case 4:y=H.sent,g=Q.default(y,2),b=g[0],w=g[1],S=b;case 9:if(w===null){H.next=19;break}return H.next=12,this._fetchContentTemplates(w);case 12:C=H.sent,U=Q.default(C,2),b=U[0],w=U[1],S=[].concat(Fe.default(S),Fe.default(b)),H.next=9;break;case 19:return this._cachedTemplates=Object.freeze(S),setTimeout(function(){h._cachedTemplates=null},this._cacheTtlMs),H.abrupt("return",S);case 22:case"end":return H.stop()}},d,this)}));function f(){return A.apply(this,arguments)}return f}()},{key:"_fetchContentTemplates",value:function(){var A=Z.default(P.default.mark(function d(h){var y,g,b;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return y="Client/v2/ContentTemplates",g=new At(y),g.arg("PageSize",this._pageSize),h!==void 0&&g.arg("PageToken",h),S.next=6,this._services.commandExecutor.fetchResource(g.build());case 6:return b=S.sent,S.abrupt("return",[b.templates.map(function(C){return new it(C)}),b.meta.next_token]);case 8:case"end":return S.stop()}},d,this)}));function f(d){return A.apply(this,arguments)}return f}()}]),O}();function br(O,A){var f=typeof Symbol<"u"&&O[Symbol.iterator]||O["@@iterator"];if(!f){if(Array.isArray(O)||(f=_n(O))||A){f&&(O=f);var d=0,h=function(){};return{s:h,n:function(){return d>=O.length?{done:!0}:{done:!1,value:O[d++]}},e:function(S){throw S},f:h}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
463
463
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var y=!0,g=!1,b;return{s:function(){f=f.call(O)},n:function(){var S=f.next();return y=S.done,S},e:function(S){g=!0,b=S},f:function(){try{!y&&f.return!=null&&f.return()}finally{if(g)throw b}}}}function _n(O,A){if(O){if(typeof O=="string")return Ss(O,A);var f=Object.prototype.toString.call(O).slice(8,-1);if(f==="Object"&&O.constructor&&(f=O.constructor.name),f==="Map"||f==="Set")return Array.from(O);if(f==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(f))return Ss(O,A)}}function Ss(O,A){(A==null||A>O.length)&&(A=O.length);for(var f=0,d=new Array(A);f<A;f++)d[f]=O[f];return d}var To=function(O){function A(){var f=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(he.default(this,A),!(f.maxSize&&f.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");this.maxSize=f.maxSize,this.onEviction=f.onEviction,this.cache=new Map,this.oldCache=new Map,this._size=0}return me.default(A,[{key:"_set",value:function(d,h){if(this.cache.set(d,h),this._size++,this._size>=this.maxSize){if(this._size=0,typeof this.onEviction=="function"){var y=br(this.oldCache.entries()),g;try{for(y.s();!(g=y.n()).done;){var b=Q.default(g.value,2),w=b[0],S=b[1];this.onEviction(w,S)}}catch(C){y.e(C)}finally{y.f()}}this.oldCache=this.cache,this.cache=new Map}}},{key:"get",value:function(d){if(this.cache.has(d))return this.cache.get(d);if(this.oldCache.has(d)){var h=this.oldCache.get(d);return this.oldCache.delete(d),this._set(d,h),h}}},{key:"set",value:function(d,h){return this.cache.has(d)?this.cache.set(d,h):this._set(d,h),this}},{key:"has",value:function(d){return this.cache.has(d)||this.oldCache.has(d)}},{key:"peek",value:function(d){if(this.cache.has(d))return this.cache.get(d);if(this.oldCache.has(d))return this.oldCache.get(d)}},{key:"delete",value:function(d){var h=this.cache.delete(d);return h&&this._size--,this.oldCache.delete(d)||h}},{key:"clear",value:function(){this.cache.clear(),this.oldCache.clear(),this._size=0}},{key:"keys",value:P.default.mark(function f(){var d,h,y,g;return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:d=br(this),w.prev=1,d.s();case 3:if((h=d.n()).done){w.next=9;break}return y=Q.default(h.value,1),g=y[0],w.next=7,g;case 7:w.next=3;break;case 9:w.next=14;break;case 11:w.prev=11,w.t0=w.catch(1),d.e(w.t0);case 14:return w.prev=14,d.f(),w.finish(14);case 17:case"end":return w.stop()}},f,this,[[1,11,14,17]])})},{key:"values",value:P.default.mark(function f(){var d,h,y,g;return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:d=br(this),w.prev=1,d.s();case 3:if((h=d.n()).done){w.next=9;break}return y=Q.default(h.value,2),g=y[1],w.next=7,g;case 7:w.next=3;break;case 9:w.next=14;break;case 11:w.prev=11,w.t0=w.catch(1),d.e(w.t0);case 14:return w.prev=14,d.f(),w.finish(14);case 17:case"end":return w.stop()}},f,this,[[1,11,14,17]])})},{key:O,value:P.default.mark(function f(){var d,h,y,g,b,w,S,C;return P.default.wrap(function(F){for(;;)switch(F.prev=F.next){case 0:d=br(this.cache),F.prev=1,d.s();case 3:if((h=d.n()).done){F.next=9;break}return y=h.value,F.next=7,y;case 7:F.next=3;break;case 9:F.next=14;break;case 11:F.prev=11,F.t0=F.catch(1),d.e(F.t0);case 14:return F.prev=14,d.f(),F.finish(14);case 17:g=br(this.oldCache),F.prev=18,g.s();case 20:if((b=g.n()).done){F.next=28;break}if(w=b.value,S=Q.default(w,1),C=S[0],this.cache.has(C)){F.next=26;break}return F.next=26,w;case 26:F.next=20;break;case 28:F.next=33;break;case 30:F.prev=30,F.t1=F.catch(18),g.e(F.t1);case 33:return F.prev=33,g.f(),F.finish(33);case 36:case"end":return F.stop()}},f,this,[[1,11,14,17],[18,30,33,36]])})},{key:"size",get:function(){var d=0,h=br(this.oldCache.keys()),y;try{for(h.s();!(y=h.n()).done;){var g=y.value;this.cache.has(g)||d++}}catch(b){h.e(b)}finally{h.f()}return Math.min(this._size+d,this.maxSize)}}]),A}(Symbol.iterator),z=To,ie=me.default(function O(A,f){he.default(this,O),this.type=A,this.data=f,Object.freeze(f)}),Se=function(){function O(A,f){he.default(this,O),this._services=A,this._configuration=f,this._cache=new z({maxSize:f.channelMetadataCacheCapacity})}return me.default(O,[{key:"getChannelMetadata",value:function(){var A=Z.default(P.default.mark(function d(h,y){var g,b,w,S,C;return P.default.wrap(function(F){for(;;)switch(F.prev=F.next){case 0:if(g="".concat(h,",").concat(y),b=this._cache.get(g),!b){F.next=4;break}return F.abrupt("return",b.item);case 4:return w="".concat(this._configuration.links.conversations,"/").concat(h,"/Messages/").concat(y,"/ChannelMetadata"),F.prev=5,F.next=8,this._services.commandExecutor.fetchResource(w);case 8:S=F.sent,F.next=17;break;case 11:if(F.prev=11,F.t0=F.catch(5),!(F.t0 instanceof at)){F.next=16;break}return this._cache.set(g,{item:null}),F.abrupt("return",null);case 16:throw new Error(F.t0);case 17:return C=new ie(S.type,S.data),this._cache.set(g,{item:C}),F.abrupt("return",C);case 20:case"end":return F.stop()}},d,this,[[5,11]])}));function f(d,h){return A.apply(this,arguments)}return f}()}]),O}();function Xe(O,A){var f=typeof Symbol<"u"&&O[Symbol.iterator]||O["@@iterator"];if(!f){if(Array.isArray(O)||(f=Kt(O))||A){f&&(O=f);var d=0,h=function(){};return{s:h,n:function(){return d>=O.length?{done:!0}:{done:!1,value:O[d++]}},e:function(S){throw S},f:h}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
464
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var y=!0,g=!1,b;return{s:function(){f=f.call(O)},n:function(){var S=f.next();return y=S.done,S},e:function(S){g=!0,b=S},f:function(){try{!y&&f.return!=null&&f.return()}finally{if(g)throw b}}}}function Kt(O,A){if(O){if(typeof O=="string")return bt(O,A);var f=Object.prototype.toString.call(O).slice(8,-1);if(f==="Object"&&O.constructor&&(f=O.constructor.name),f==="Map"||f==="Set")return Array.from(O);if(f==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(f))return bt(O,A)}}function bt(O,A){(A==null||A>O.length)&&(A=O.length);for(var f=0,d=new Array(A);f<A;f++)d[f]=O[f];return d}var Jt=me.default(function O(A){he.default(this,O),Pe.default(this,"type","email"),this.messageSid=A.message_sid,this.level=A.level,this.name=A.name,this.address=A.address}),ur=me.default(function O(A){he.default(this,O),this.type=A.type,this.messageSid=A.message_sid,this.rawData=JSON.stringify(A)}),_r=function(){function O(A,f){he.default(this,O),this._services=A,this._configuration=f,this._cache=new z({maxSize:f.messageRecipientsCacheCapacity})}return me.default(O,[{key:"getRecipientsFromMessage",value:function(){var A=Z.default(P.default.mark(function d(h,y){var g=this,b,w,S,C,U;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:if(b="".concat(h,",").concat(y),w=this._cache.get(b),!w){H.next=4;break}return H.abrupt("return",w.item);case 4:return S=new At(this._configuration.links.conversations).path(h).path("MessageRecipients").arg("MessageSid",y).build(),H.next=7,this._services.commandExecutor.fetchResource(S);case 7:return C=H.sent,U=C.message_recipients.map(function(W){return g._wrapResponse(W)}),U.length>0&&this._cache.set(b,{item:U}),H.abrupt("return",U);case 11:case"end":return H.stop()}},d,this)}));function f(d,h){return A.apply(this,arguments)}return f}()},{key:"getRecipientsFromConversation",value:function(){var A=Z.default(P.default.mark(function d(h,y){var g,b,w=this,S,C,U,F,H,W,Me,Je,Be,Ge;return P.default.wrap(function(St){for(;;)switch(St.prev=St.next){case 0:return S=new At(this._configuration.links.conversations).path(h).path("MessageRecipients").arg("PageToken",(g=y==null?void 0:y.pageToken)!==null&&g!==void 0?g:void 0).arg("PageSize",(b=y==null?void 0:y.pageSize)!==null&&b!==void 0?b:void 0).build(),St.next=3,this._services.commandExecutor.fetchResource(S);case 3:C=St.sent,U=C.message_recipients.map(function(ft){return w._wrapResponse(ft)}),F=Xe(U);try{for(F.s();!(H=F.n()).done;)Je=H.value,Be="".concat(h,",").concat(Je.messageSid),Ge=(W=(Me=this._cache.get(Be))===null||Me===void 0?void 0:Me.item)!==null&&W!==void 0?W:[],this._cache.set(Be,{item:[].concat(Fe.default(Ge),[Je])})}catch(ft){F.e(ft)}finally{F.f()}return St.abrupt("return",new We(U,function(ft,hr){return w.getRecipientsFromConversation(h,{pageToken:ft,pageSize:hr})},C.meta.previous_token,C.meta.next_token));case 8:case"end":return St.stop()}},d,this)}));function f(d,h){return A.apply(this,arguments)}return f}()},{key:"_wrapResponse",value:function(f){switch(f.type){case"email":return new Jt(f);default:return new ur(f)}}}]),O}(),ut;function jr(O,A){var f=Object.keys(O);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(O);A&&(d=d.filter(function(h){return Object.getOwnPropertyDescriptor(O,h).enumerable})),f.push.apply(f,d)}return f}function Fr(O){for(var A=1;A<arguments.length;A++){var f=arguments[A]!=null?arguments[A]:{};A%2?jr(Object(f),!0).forEach(function(d){Pe.default(O,d,f[d])}):Object.getOwnPropertyDescriptors?Object.defineProperties(O,Object.getOwnPropertyDescriptors(f)):jr(Object(f)).forEach(function(d){Object.defineProperty(O,d,Object.getOwnPropertyDescriptor(f,d))})}return O}function pr(O){var A=Ur();return function(){var d=vt.default(O),h;if(A){var y=vt.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return Nt.default(this,h)}}function Ur(){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 mt,In=me.default(function O(){he.default(this,O)});e.Client=mt=(ut=function(O){Qe.default(f,O);var A=pr(f);function f(d){var h,y,g,b,w,S,C=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(he.default(this,f),S=A.call(this),Pe.default(qe.default(S),"version",E),Pe.default(qe.default(S),"connectionState","unknown"),Pe.default(qe.default(S),"parsePushNotification",mt.parsePushNotification),S._fpaToken=d??"",S._options=C??{},!S._options.disableDeepClone){var U=Fr(Fr({},S._options),{},{transport:void 0,twilsockClient:void 0});U=Rt(U),U.transport=S._options.transport,U.twilsockClient=S._options.twilsockClient,S._options=U}S._options.logLevel=(h=S._options.logLevel)!==null&&h!==void 0?h:"silent",mt._logger.setLevel(S._options.logLevel);var F=S._options.productId="ip_messaging";if(S._options.clientMetadata=S._options.clientMetadata||{},S._options.clientMetadata.hasOwnProperty("type")||(S._options.clientMetadata.type="conversations"),S._options.clientMetadata.hasOwnProperty("sdk")||(S._options.clientMetadata.sdk="JS",S._options.clientMetadata.sdkv=E),S._options.Sync=S._options.Sync||{},typeof S._options.Sync.enableSessionStorage>"u"&&(S._options.Sync.enableSessionStorage=!0),S._options.region&&(S._options.Sync.region=S._options.region),!d)throw new Error("A valid Twilio token should be provided");S._services=new In,S._myself=new ve("","",null,S._services);var H=!S._options.twilsockClient;if(!S._options.initRegistrations){var W=new j.InitRegistration(F);mt.populateInitRegistrations(W),S._options.initRegistrations=[W]}S._services.twilsockClient=S._options.twilsockClient=(y=S._options.twilsockClient)!==null&&y!==void 0?y:new j.TwilsockClient(d,F,S._options),S._services.twilsockClient.on(mt.tokenAboutToExpire,function(){return S.emit(mt.tokenAboutToExpire)}),S._services.twilsockClient.on(mt.tokenExpired,function(){return S.emit(mt.tokenExpired)}),S._services.twilsockClient.on(mt.connectionError,function(St){return S.emit(mt.connectionError,St)}),S._services.twilsockClient.on("stateChanged",function(St){mt._logger.debug("Handling stateChanged for ConversationsClient: new state ".concat(St)),St!==S.connectionState&&(S.connectionState=St,S.emit(mt.connectionStateChanged,S.connectionState))}),S._services.transport=S._options.transport=(g=S._options.transport)!==null&&g!==void 0?g:S._options.twilsockClient,S._services.notificationClient=S._options.notificationsClient=(b=S._options.notificationsClient)!==null&&b!==void 0?b:new X.Notifications(d,S._options),S._services.syncClient=S._options.syncClient=(w=S._options.syncClient)!==null&&w!==void 0?w:new J.SyncClient(d,S._options);var Me=(C==null?void 0:C.Chat)||(C==null?void 0:C.IPMessaging)||C||{},Je=Me.region||(C==null?void 0:C.region),Be=Me.apiUri||Me.typingUri||"https://aim.".concat(Je||"us1",".twilio.com");S._services.commandExecutor=new $r(Be,{transport:S._options.transport},F),S._services.contentClient=new ln(S._services);var Ge=function(ft){S._rejectEnsureReady(ft),S.emit(mt.stateChanged,"failed"),S.emit(mt.initFailed,{error:ft})},xt=function(){Ge({terminal:!0,message:"Twilsock has disconnected."}),S._initializeEnsureReady((C==null?void 0:C.throwErrorsAlways)||!1)};return S._services.twilsockClient.once("connectionError",Ge),S._services.twilsockClient.once("disconnected",xt),S._services.twilsockClient.once("connected",Z.default(P.default.mark(function St(){var ft,hr;return P.default.wrap(function(st){for(;;)switch(st.prev=st.next){case 0:return mt._logger.debug("ConversationsClient started INITIALIZING"),S._services.twilsockClient.off("connectionError",Ge),S._services.twilsockClient.off("disconnected",xt),st.prev=3,ft="conversations.client.startup",S._services.twilsockClient.addPartialTelemetryEvent(new j.TelemetryEventDescription(ft,"Conversations client startup",new Date),ft,j.TelemetryPoint.Start),st.next=8,S._initialize();case 8:S._services.twilsockClient.addPartialTelemetryEvent(new j.TelemetryEventDescription("","",new Date),ft,j.TelemetryPoint.End),st.next=17;break;case 11:st.prev=11,st.t0=st.catch(3),hr={terminal:!0,message:st.t0.message},S._rejectEnsureReady(hr),S.emit(mt.stateChanged,"failed"),S.emit(mt.initFailed,{error:hr});case 17:case"end":return st.stop()}},St,null,[[3,11]])}))),S._initializeEnsureReady((C==null?void 0:C.throwErrorsAlways)||!1),H&&S._services.twilsockClient.connect(),S}return me.default(f,[{key:"user",get:function(){return this._myself}},{key:"reachabilityEnabled",get:function(){if(!this._configuration)throw new Error("Reachability information could not yet be accessed as the client has not yet been initialized. Subscribe to the 'stateChanged' event to properly react to the client initialization.");return this._configuration.reachabilityEnabled}},{key:"token",get:function(){return this._fpaToken}},{key:"shutdown",value:function(){var d=Z.default(P.default.mark(function y(){return P.default.wrap(function(b){for(;;)switch(b.prev=b.next){case 0:return b.next=2,this._ensureReady;case 2:return b.next=4,this._services.twilsockClient.disconnect();case 4:case"end":return b.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"updateToken",value:function(){var d=Z.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._ensureReady;case 2:if(mt._logger.info("updateToken"),this._fpaToken!==g){w.next=5;break}return w.abrupt("return",this);case 5:return w.next=7,this._services.twilsockClient.updateToken(g);case 7:return w.next=9,this._services.notificationClient.updateToken(g);case 9:return w.next=11,this._services.mcsClient.updateToken(g);case 11:return this._fpaToken=g,w.abrupt("return",this);case 13:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getConversationBySid",value:function(){var d=Z.default(P.default.mark(function y(g){var b;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._ensureReady;case 2:return S.next=4,this._conversationsEntity.myConversationsRead.promise;case 4:return S.next=6,this._conversationsEntity.getConversation(g);case 6:if(b=S.sent,b){S.next=12;break}return S.next=10,this.peekConversationBySid(g);case 10:b=S.sent,b&&L.deprecationWarning("The method getConversationBySid is deprecated to retrieve conversations you're not part of. Use peekConversationBySid instead.");case 12:if(b){S.next=14;break}throw new Error("Conversation with SID ".concat(g," was not found."));case 14:return S.abrupt("return",b);case 15:case"end":return S.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"peekConversationBySid",value:function(){var d=Z.default(P.default.mark(function y(g){var b;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._ensureReady;case 2:return S.next=4,this._conversationsEntity.peekConversation(g);case 4:if(b=S.sent,b){S.next=7;break}throw new Error("Conversation with SID ".concat(g," was not found."));case 7:return S.abrupt("return",b);case 8:case"end":return S.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getConversationByUniqueName",value:function(){var d=Z.default(P.default.mark(function y(g){var b;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._ensureReady;case 2:return S.next=4,this._conversationsEntity.myConversationsRead.promise;case 4:return S.next=6,this._conversationsEntity.getConversationByUniqueName(g);case 6:if(b=S.sent,b){S.next=9;break}throw new Error("Conversation with unique name ".concat(g," was not found."));case 9:return S.abrupt("return",b);case 10:case"end":return S.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getSubscribedConversations",value:function(){var d=Z.default(P.default.mark(function y(){return P.default.wrap(function(b){for(;;)switch(b.prev=b.next){case 0:return b.next=2,this._ensureReady;case 2:return b.abrupt("return",this._conversationsPromise.then(function(w){return w.getConversations()}));case 3:case"end":return b.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"createConversation",value:function(){var d=Z.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._ensureReady;case 2:return g=g||{},w.abrupt("return",this._conversationsPromise.then(function(S){return S.addConversation(g)}));case 4:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"setPushRegistrationId",value:function(){var d=Z.default(P.default.mark(function y(g,b){return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._ensureReady;case 2:return this._subscribeToPushNotifications(g),this._services.notificationClient.setPushRegistrationId(g,b),S.next=6,this._services.notificationClient.commitChanges();case 6:case"end":return S.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"unsetPushRegistrationId",value:function(){var d=Z.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._ensureReady;case 2:return this._unsubscribeFromPushNotifications(g),w.next=5,this._services.notificationClient.commitChanges();case 5:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"removePushRegistrations",value:function(){var d=Z.default(P.default.mark(function y(g,b){return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._services.notificationClient.removeRegistrations(g,b);case 2:case"end":return S.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"handlePushNotification",value:function(){var d=Z.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._ensureReady;case 2:mt._logger.debug("handlePushNotification, notificationPayload=",g),this.emit("pushNotification",mt.parsePushNotification(g));case 4:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getUser",value:function(){var d=Z.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._ensureReady;case 2:return w.abrupt("return",this._services.users.getUser(g));case 3:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getSubscribedUsers",value:function(){var d=Z.default(P.default.mark(function y(){return P.default.wrap(function(b){for(;;)switch(b.prev=b.next){case 0:return b.next=2,this._ensureReady;case 2:return b.abrupt("return",this._services.users.getSubscribedUsers());case 3:case"end":return b.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getTemporaryContentUrlsForMediaSids",value:function(h){var y=this;return new G.CancellablePromise(function(){var g=Z.default(P.default.mark(function b(w,S,C){var U,F;return P.default.wrap(function(W){for(;;)switch(W.prev=W.next){case 0:if(!(!y._services.mcsClient||!h)){W.next=3;break}return S(new Error("Media Content Service is unavailable")),W.abrupt("return");case 3:return U=y._services.mcsClient.mediaSetGetContentUrls(h),C(function(){U.cancel()}),W.prev=5,W.next=8,U;case 8:F=W.sent,w(F),W.next=15;break;case 12:W.prev=12,W.t0=W.catch(5),S(W.t0);case 15:case"end":return W.stop()}},b,null,[[5,12]])}));return function(b,w,S){return g.apply(this,arguments)}}())}},{key:"getTemporaryContentUrlsForMedia",value:function(h){var y=h.map(function(g){return g.sid});return this.getTemporaryContentUrlsForMediaSids(y)}},{key:"getContentTemplates",value:function(){var d=Z.default(P.default.mark(function y(){return P.default.wrap(function(b){for(;;)switch(b.prev=b.next){case 0:return b.next=2,this._ensureReady;case 2:return b.next=4,this._services.contentClient.getContentTemplates();case 4:return b.abrupt("return",b.sent);case 5:case"end":return b.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_initialize",value:function(){var d=Z.default(P.default.mark(function y(){var g=this,b;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._services.commandExecutor.fetchResource("Client/v2/Configuration");case 2:return b=S.sent,this._configuration=new Ct(this._options,b,mt._logger),this._services.channelMetadataClient=new Se(this._services,this._configuration),this._services.messageRecipientsClient=new _r(this._services,this._configuration),this._myself._resolveInitialization(this._configuration,this._configuration.userIdentity,this._configuration.userInfo,!0),this._services.typingIndicator=new R(this.getConversationBySid.bind(this),this._configuration,this._services),this._services.network=new ce(this._configuration,this._services),this._services.users=new D(this._myself,this._configuration,this._services),this._services.users.on("userSubscribed",function(C){g.emit("userSubscribed",C)}),this._services.users.on("userUpdated",function(C){return g.emit("userUpdated",C)}),this._services.users.on("userUnsubscribed",function(C){g.emit("userUnsubscribed",C)}),this._conversationsEntity=new Gr(this._configuration,this._services),this._conversationsEntity.on("conversationAdded",function(C){g.emit("conversationAdded",C)}),this._conversationsEntity.on("conversationRemoved",function(C){g.emit("conversationRemoved",C)}),this._conversationsEntity.on("conversationJoined",function(C){g.emit("conversationJoined",C)}),this._conversationsEntity.on("conversationLeft",function(C){g.emit("conversationLeft",C)}),this._conversationsEntity.on("conversationUpdated",function(C){return g.emit("conversationUpdated",C)}),this._conversationsEntity.on("participantJoined",function(C){g.emit("participantJoined",C)}),this._conversationsEntity.on("participantLeft",function(C){g.emit("participantLeft",C)}),this._conversationsEntity.on("participantUpdated",function(C){return g.emit("participantUpdated",C)}),this._conversationsEntity.on("messageAdded",function(C){return g.emit("messageAdded",C)}),this._conversationsEntity.on("messageUpdated",function(C){return g.emit("messageUpdated",C)}),this._conversationsEntity.on("messageRemoved",function(C){return g.emit("messageRemoved",C)}),this._conversationsEntity.on("typingStarted",function(C){return g.emit("typingStarted",C)}),this._conversationsEntity.on("typingEnded",function(C){return g.emit("typingEnded",C)}),this._conversationsPromise=this._conversationsEntity.fetchConversations().then(function(){return g._conversationsEntity}).catch(function(C){throw C}),S.next=30,this._services.users.myself._ensureFetched();case 30:mt._supportedPushChannels.forEach(function(C){return g._subscribeToPushNotifications(C)}),this._services.typingIndicator.initialize(),this._services.mcsClient=new G.McsClient(this._fpaToken,this._configuration.links.mediaService,this._configuration.links.mediaSetService,Fr(Fr({},this._options),{},{transport:void 0})),this._resolveEnsureReady(),this.emit(mt.stateChanged,"initialized"),this.emit(mt.initialized);case 36:case"end":return S.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_subscribeToPushNotifications",value:function(h){var y=this;[ge.NEW_MESSAGE,ge.ADDED_TO_CONVERSATION,ge.REMOVED_FROM_CONVERSATION,ge.TYPING_INDICATOR,ge.CONSUMPTION_UPDATE].forEach(function(g){y._services.notificationClient.subscribe(h,g)})}},{key:"_unsubscribeFromPushNotifications",value:function(h){var y=this;[ge.NEW_MESSAGE,ge.ADDED_TO_CONVERSATION,ge.REMOVED_FROM_CONVERSATION,ge.TYPING_INDICATOR,ge.CONSUMPTION_UPDATE].forEach(function(g){y._services.notificationClient.unsubscribe(h,g)})}},{key:"_initializeEnsureReady",value:function(h){var y=this;this._ensureReady=new Promise(function(g,b){y._resolveEnsureReady=g,y._rejectEnsureReady=b}).catch(function(g){if(h)throw g})}}],[{key:"create",value:function(){var d=Z.default(P.default.mark(function y(g,b){var w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:if(!(b!=null&&b.twilsockClient)){C.next=2;break}throw new Error("Obsolete usage of ConversationsClient.create() factory method: if you pass twilsock from the outside then you must use ConversationsClient constructor and be prepared to work with uninitialized client.");case 2:return w=new mt(g,b),C.next=5,w._ensureReady;case 5:return C.abrupt("return",w);case 6:case"end":return C.stop()}},y)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"parsePushNotification",value:function(h){if(mt._logger.debug("parsePushNotification, notificationPayload=",h),typeof h.aps<"u"){if(!h.twi_message_type)throw new Error("Provided push notification payload does not contain Programmable Chat push notification type");var y=mt._parsePushNotificationChatData(h),g=h.aps,b,w=null;if(typeof g.alert=="string")b=g.alert||null;else{var S,C;b=((S=g.alert)===null||S===void 0?void 0:S.body)||null,w=((C=g.alert)===null||C===void 0?void 0:C.title)||null}return new k({title:w,body:b,sound:g.sound||null,badge:g.badge||null,action:g.category||null,type:h.twi_message_type,data:y})}if(typeof h.data<"u"){var U=h.data;if(!U.twi_message_type)throw new Error("Provided push notification payload does not contain Programmable Chat push notification type");var F=mt._parsePushNotificationChatData(h.data);return new k({title:U.twi_title||null,body:U.twi_body||null,sound:U.twi_sound||null,badge:null,action:U.twi_action||null,type:U.twi_message_type,data:F})}throw new Error("Provided push notification payload is not Programmable Chat notification")}},{key:"_parsePushNotificationChatData",value:function(h){var y={};for(var g in mt._supportedPushDataFields){var b=h[g];if(!(typeof b>"u"||b===null)){if(g==="message_index"||g==="media_count"){var w=yt(b);w!==null&&(y[mt._supportedPushDataFields[g]]=w);continue}if(g==="media"){if(typeof b=="string")try{y[mt._supportedPushDataFields[g]]=JSON.parse(b)}catch{mt._logger.debug("Media message notification parsing error")}continue}y[mt._supportedPushDataFields[g]]=b}}return y}},{key:"populateInitRegistrations",value:function(h){h.populateInitRegistrations([ge.TYPING_INDICATOR]),J.SyncClient.populateInitRegistrations(h)}}]),f}(I.ReplayEventEmitter),Pe.default(ut,"conversationAdded","conversationAdded"),Pe.default(ut,"conversationJoined","conversationJoined"),Pe.default(ut,"conversationLeft","conversationLeft"),Pe.default(ut,"conversationRemoved","conversationRemoved"),Pe.default(ut,"conversationUpdated","conversationUpdated"),Pe.default(ut,"participantJoined","participantJoined"),Pe.default(ut,"participantLeft","participantLeft"),Pe.default(ut,"participantUpdated","participantUpdated"),Pe.default(ut,"messageAdded","messageAdded"),Pe.default(ut,"messageRemoved","messageRemoved"),Pe.default(ut,"messageUpdated","messageUpdated"),Pe.default(ut,"tokenAboutToExpire","tokenAboutToExpire"),Pe.default(ut,"tokenExpired","tokenExpired"),Pe.default(ut,"typingEnded","typingEnded"),Pe.default(ut,"typingStarted","typingStarted"),Pe.default(ut,"pushNotification","pushNotification"),Pe.default(ut,"userSubscribed","userSubscribed"),Pe.default(ut,"userUnsubscribed","userUnsubscribed"),Pe.default(ut,"userUpdated","userUpdated"),Pe.default(ut,"stateChanged","stateChanged"),Pe.default(ut,"initialized","initialized"),Pe.default(ut,"initFailed","initFailed"),Pe.default(ut,"connectionStateChanged","connectionStateChanged"),Pe.default(ut,"connectionError","connectionError"),Pe.default(ut,"version",E),Pe.default(ut,"_logger",Dt.scope("Client")),Pe.default(ut,"_supportedPushChannels",["fcm","apn"]),Pe.default(ut,"_supportedPushDataFields",{conversation_sid:"conversationSid",conversation_title:"conversationTitle",message_sid:"messageSid",message_index:"messageIndex",media_count:"mediaCount",media:"media"}),ut),we([L.deprecated("token"),fe("design:type",String),fe("design:paramtypes",[])],e.Client.prototype,"token",null),we([_.validateTypesAsync(_.nonEmptyString),fe("design:type",Function),fe("design:paramtypes",[String]),fe("design:returntype",Promise)],e.Client.prototype,"updateToken",null),we([_.validateTypesAsync(_.nonEmptyString),fe("design:type",Function),fe("design:paramtypes",[String]),fe("design:returntype",Promise)],e.Client.prototype,"getConversationBySid",null),we([_.validateTypesAsync(_.nonEmptyString),fe("design:type",Function),fe("design:paramtypes",[String]),fe("design:returntype",Promise)],e.Client.prototype,"peekConversationBySid",null),we([_.validateTypesAsync(_.nonEmptyString),fe("design:type",Function),fe("design:paramtypes",[String]),fe("design:returntype",Promise)],e.Client.prototype,"getConversationByUniqueName",null),we([_.validateTypesAsync(["undefined",_.objectSchema("conversation options",{friendlyName:["string","undefined"],isPrivate:["boolean","undefined"],uniqueName:["string","undefined"]})]),fe("design:type",Function),fe("design:paramtypes",[Object]),fe("design:returntype",Promise)],e.Client.prototype,"createConversation",null),we([_.validateTypesAsync(_.literal("fcm","apn"),"string"),fe("design:type",Function),fe("design:paramtypes",[String,String]),fe("design:returntype",Promise)],e.Client.prototype,"setPushRegistrationId",null),we([_.validateTypesAsync(_.literal("fcm","apn")),fe("design:type",Function),fe("design:paramtypes",[String]),fe("design:returntype",Promise)],e.Client.prototype,"unsetPushRegistrationId",null),we([_.validateTypesAsync(_.literal("fcm","apn"),_.nonEmptyString),fe("design:type",Function),fe("design:paramtypes",[String,String]),fe("design:returntype",Promise)],e.Client.prototype,"removePushRegistrations",null),we([_.validateTypesAsync(_.pureObject),fe("design:type",Function),fe("design:paramtypes",[Object]),fe("design:returntype",Promise)],e.Client.prototype,"handlePushNotification",null),we([_.validateTypesAsync(_.nonEmptyString),fe("design:type",Function),fe("design:paramtypes",[String]),fe("design:returntype",Promise)],e.Client.prototype,"getUser",null),we([_.validateTypesAsync(_.nonEmptyArray("strings","string")),fe("design:type",Function),fe("design:paramtypes",[Array]),fe("design:returntype",G.CancellablePromise)],e.Client.prototype,"getTemporaryContentUrlsForMediaSids",null),we([_.validateTypesAsync(_.nonEmptyArray("media",Ve)),fe("design:type",Function),fe("design:paramtypes",[Array]),fe("design:returntype",G.CancellablePromise)],e.Client.prototype,"getTemporaryContentUrlsForMedia",null),we([L.deprecated("Client.create()","new Client()"),_.validateTypesAsync("string",["undefined",_.pureObject]),fe("design:type",Function),fe("design:paramtypes",[String,Object]),fe("design:returntype",Promise)],e.Client,"create",null),we([_.validateTypes(_.pureObject),fe("design:type",Function),fe("design:paramtypes",[Object]),fe("design:returntype",k)],e.Client,"parsePushNotification",null),e.Client=mt=we([_.validateConstructorTypes(_.nonEmptyString,[_.pureObject,"undefined"]),fe("design:paramtypes",[String,Object])],e.Client),Object.defineProperty(e,"CancellablePromise",{enumerable:!0,get:function(){return G.CancellablePromise}}),e.AggregatedDeliveryReceipt=ze,e.ChannelMetadata=ie,e.ContentTemplate=it,e.ContentTemplateVariable=nt,e.Conversation=It,e.DetailedDeliveryReceipt=Ze,e.EmailRecipientDescriptor=Jt,e.Media=Ve,e.Message=$t,e.MessageBuilder=or,e.NotificationTypes=ge,e.Participant=V,e.PushNotification=k,e.RestPaginator=We,e.UnknownRecipientDescriptor=ur,e.UnsentMessage=ci,e.User=ve})(vT);const xn=new $a("twilio-chat");class t$ extends qv{constructor(){super(...arguments);pt(this,"client");pt(this,"conversation")}async create(){const{token:t,identity:n}=await this.issueChatToken();this.identity=n,xn.info(`Connecting chat, identity: ${n}, token: ${t}`);const i=new vT.Client(t);i.on("initialized",()=>{xn.info("client: initialized"),this.events.triggerEvent("initialized")}),i.on("tokenAboutToExpire",()=>{xn.info("client: tokenAboutToExpire"),this.refreshToken()}),i.on("tokenExpired",()=>{xn.info("client: tokenExpired"),this.refreshToken()}),this.client=i}async refreshToken(){const{token:t}=await this.issueChatToken();await this.client.updateToken(t)}async join(t){const n=await this.client.getConversationBySid(t);n.status==="joined"?xn.info("already joined conversation:",t):(await n.join(),xn.info("success joined conversation:",t)),this.registerEvents(n),this.conversation=n}async preview(t){await(await this.conversation.getParticipantByIdentity(this.identity)).updateAttributes({chat_preview:t,chat_preview_updated_at:new Date().toJSON()})}async destroy(){this.client&&(await this.client.shutdown(),this.client=null,this.conversation=null)}async fetchMessages(t){return(await this.conversation.getMessages()).items.map(i=>{const a=c0(i);return t[a.$index]&&(a.file=t[a.$index]),this.trackInTask(a),a})}async sendMessage(t){try{const n=await this.conversation.sendMessage(JSON.stringify(t));return xn.info(`Message sent from ${this.conversation.sid}, index: ${n}`),n}catch(n){xn.warn(`Failed to send a message from ${this.conversation.sid}`,{error:n})}}startTyping(){this.conversation&&this.conversation.typing()}stopTyping(){}registerEvents(t){t.on("messageAdded",n=>{const i=c0(n);xn.info(`Message added from ${this.conversation.sid}, index: ${i.$index}, sid: ${i.$sid}, timestamp: ${i.$timestamp}, user type: ${i.$userType}`),i.$userType!=="end_user"&&this.ping(),this.trackInTask(i),this.events.triggerEvent("message",i)}),t.on("participantJoined",n=>{xn.info("conversation: memberJoined",n),this.events.triggerEvent("memberJoined",n.identity)}),t.on("participantLeft",n=>{xn.info("conversation: memberLeft",n),this.events.triggerEvent("memberLeft",n.identity)}),t.on("typingStarted",n=>{this.events.triggerEvent("typingStarted",n.identity)}),t.on("typingEnded",n=>{this.events.triggerEvent("typingEnded",n.identity)})}}pt(t$,"type","twilio_conversations");zv(t$);function c0(e){const{index:r,sid:t,author:n,dateCreated:i,body:a}=e,[s,o]=n.split("-");let u=0;o&&(u=parseInt(o,10));const c={$index:r,$sid:t,$timestamp:i,$userType:s,$userId:u};try{const l=JSON.parse(a);return l.message&&!l.type?{...c,...l,type:"message"}:{...c,...l}}catch(l){return xn.warn("Format message failed",{error:l,data:a}),{...c,type:"text",content:a}}}var lv={exports:{}},Da=Gl;function Gl(){}Gl.mixin=function(e){var r=e.prototype||e;r.isWildEmitter=!0,r.on=function(t,n,i){this.callbacks=this.callbacks||{};var a=arguments.length===3,s=a?arguments[1]:void 0,o=a?arguments[2]:arguments[1];return o._groupName=s,(this.callbacks[t]=this.callbacks[t]||[]).push(o),this},r.once=function(t,n,i){var a=this,s=arguments.length===3,o=s?arguments[1]:void 0,u=s?arguments[2]:arguments[1];function c(){a.off(t,c),u.apply(this,arguments)}return this.on(t,o,c),this},r.releaseGroup=function(t){this.callbacks=this.callbacks||{};var n,i,a,s;for(n in this.callbacks)for(s=this.callbacks[n],i=0,a=s.length;i<a;i++)s[i]._groupName===t&&(s.splice(i,1),i--,a--);return this},r.off=function(t,n){this.callbacks=this.callbacks||{};var i=this.callbacks[t],a;return i?arguments.length===1?(delete this.callbacks[t],this):(a=i.indexOf(n),a!==-1&&(i.splice(a,1),i.length===0&&delete this.callbacks[t]),this):this},r.emit=function(t){this.callbacks=this.callbacks||{};var n=[].slice.call(arguments,1),i=this.callbacks[t],a=this.getWildcardCallbacks(t),s,o,u;if(i)for(u=i.slice(),s=0,o=u.length;s<o&&u[s];++s)u[s].apply(this,n);if(a)for(o=a.length,u=a.slice(),s=0,o=u.length;s<o&&u[s];++s)u[s].apply(this,[t].concat(n));return this},r.getWildcardCallbacks=function(t){this.callbacks=this.callbacks||{};var n,i,a=[];for(n in this.callbacks)i=n.split("*"),(n==="*"||i.length===2&&t.slice(0,i[0].length)===i[0])&&(a=a.concat(this.callbacks[n]));return a}};Gl.mixin(Gl);var r$={exports:{}};(function(e){(function(r,t){e.exports?e.exports=t():r.prefix=t(r)})(Ne,function(r){var t=function(l){for(var p=1,v=arguments.length,m;p<v;p++)for(m in arguments[p])Object.prototype.hasOwnProperty.call(arguments[p],m)&&(l[m]=arguments[p][m]);return l},n={template:"[%t] %l:",levelFormatter:function(l){return l.toUpperCase()},nameFormatter:function(l){return l||"root"},timestampFormatter:function(l){return l.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")},format:void 0},i,a={},s=function(l){if(!l||!l.getLogger)throw new TypeError("Argument is not a root logger");i=l},o=function(l,p){if(!l||!l.setLevel)throw new TypeError("Argument is not a logger");var v=l.methodFactory,m=l.name||"",_=a[m]||a[""]||n;function T(I,$,x){var N=v(I,$,x),j=a[x]||a[""],X=j.template.indexOf("%t")!==-1,J=j.template.indexOf("%l")!==-1,G=j.template.indexOf("%n")!==-1;return function(){for(var L="",re=arguments.length,ue=Array(re),ee=0;ee<re;ee++)ue[ee]=arguments[ee];if(m||!a[x]){var ye=j.timestampFormatter(new Date),Z=j.levelFormatter(I),qe=j.nameFormatter(x);j.format?L+=j.format(Z,qe,ye):(L+=j.template,X&&(L=L.replace(/%t/,ye)),J&&(L=L.replace(/%l/,Z)),G&&(L=L.replace(/%n/,qe))),ue.length&&typeof ue[0]=="string"?ue[0]=L+" "+ue[0]:ue.unshift(L)}N.apply(void 0,ue)}}return a[m]||(l.methodFactory=T),p=p||{},p.template&&(p.format=void 0),a[m]=t({},_,p),l.setLevel(l.getLevel()),i||l.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"),l},u={reg:s,apply:o},c;return r&&(c=r.prefix,u.noConflict=function(){return r.prefix===u&&(r.prefix=c),u}),u})})(r$);var EX=r$.exports,fv={exports:{}},kX={"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"},"error:input:unsanitized":{type:"error:input:unsanitized",description:"Input is not sanitized"}};(function(e,r){Object.defineProperty(r,"__esModule",{value:!0}),r.NexmoApiError=r.NexmoClientError=void 0;const t=kX,n=Ar;function i(o,u){var c,l;u!=null&&u.code&&(u.type=u.code,delete u.code),Object.assign(o,u),o.message="type: "+o.type+", description: "+((l=(c=o.description)!==null&&c!==void 0?c:o.detail)!==null&&l!==void 0?l:"")}class a{constructor(u){const c=t[u];c?i(this,c):(this.message=u&&u.message?u.message:u,this.stack=u.stack),this.log=n.getLogger(this.constructor.name),this.log.error(this),this.name="NexmoClientError",typeof Ne.NXMbugsnagClient<"u"&&Ne.NXMbugsnagClient.notify(this,{severity:"info"})}}r.NexmoClientError=a;class s{constructor(u){this.log=n.getLogger(this.constructor.name),u?i(this,u):(this.message=u&&u.message?u.message:u,this.stack=u&&u.stack?u.stack:new Error().stack),this.name="NexmoApiError",this.log=n.getLogger(this.constructor.name),this.log.error(this),typeof Ne.NXMbugsnagClient<"u"&&Ne.NXMbugsnagClient.notify(this,{severity:"info"})}}r.NexmoApiError=s,e.exports={NexmoClientError:a,NexmoApiError:s}})(fv,fv.exports);var Hn=fv.exports,dv={exports:{}},Pg={},Nf={},zi={},Gu={},yi={},Vu={},Ki={},_o={},Ku={},bi={};Object.defineProperty(bi,"__esModule",{value:!0});bi.ERROR_PACKET=bi.PACKET_TYPES_REVERSE=bi.PACKET_TYPES=void 0;const _i=Object.create(null);bi.PACKET_TYPES=_i;_i.open="0";_i.close="1";_i.ping="2";_i.pong="3";_i.message="4";_i.upgrade="5";_i.noop="6";const n$=Object.create(null);bi.PACKET_TYPES_REVERSE=n$;Object.keys(_i).forEach(e=>{n$[_i[e]]=e});const RX={type:"error",data:"parser error"};bi.ERROR_PACKET=RX;Object.defineProperty(Ku,"__esModule",{value:!0});Ku.encodePacket=void 0;Ku.encodePacketToBinary=IX;const $X=bi,i$=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",a$=typeof ArrayBuffer=="function",s$=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,o$=({type:e,data:r},t,n)=>i$&&r instanceof Blob?t?n(r):l0(r,n):a$&&(r instanceof ArrayBuffer||s$(r))?t?n(r):l0(new Blob([r]),n):n($X.PACKET_TYPES[e]+(r||""));Ku.encodePacket=o$;const l0=(e,r)=>{const t=new FileReader;return t.onload=function(){const n=t.result.split(",")[1];r("b"+(n||""))},t.readAsDataURL(e)};function f0(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Kp;function IX(e,r){if(i$&&e.data instanceof Blob)return e.data.arrayBuffer().then(f0).then(r);if(a$&&(e.data instanceof ArrayBuffer||s$(e.data)))return r(f0(e.data));o$(e,!1,t=>{Kp||(Kp=new TextEncoder),r(Kp.encode(t))})}var Lf={},oo={};Object.defineProperty(oo,"__esModule",{value:!0});oo.decode=oo.encode=void 0;const Us="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Xo=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<Us.length;e++)Xo[Us.charCodeAt(e)]=e;const OX=e=>{let r=new Uint8Array(e),t,n=r.length,i="";for(t=0;t<n;t+=3)i+=Us[r[t]>>2],i+=Us[(r[t]&3)<<4|r[t+1]>>4],i+=Us[(r[t+1]&15)<<2|r[t+2]>>6],i+=Us[r[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};oo.encode=OX;const AX=e=>{let r=e.length*.75,t=e.length,n,i=0,a,s,o,u;e[e.length-1]==="="&&(r--,e[e.length-2]==="="&&r--);const c=new ArrayBuffer(r),l=new Uint8Array(c);for(n=0;n<t;n+=4)a=Xo[e.charCodeAt(n)],s=Xo[e.charCodeAt(n+1)],o=Xo[e.charCodeAt(n+2)],u=Xo[e.charCodeAt(n+3)],l[i++]=a<<2|s>>4,l[i++]=(s&15)<<4|o>>2,l[i++]=(o&3)<<6|u&63;return c};oo.decode=AX;Object.defineProperty(Lf,"__esModule",{value:!0});Lf.decodePacket=void 0;const qc=bi,PX=oo,MX=typeof ArrayBuffer=="function",xX=(e,r)=>{if(typeof e!="string")return{type:"message",data:u$(e,r)};const t=e.charAt(0);return t==="b"?{type:"message",data:NX(e.substring(1),r)}:qc.PACKET_TYPES_REVERSE[t]?e.length>1?{type:qc.PACKET_TYPES_REVERSE[t],data:e.substring(1)}:{type:qc.PACKET_TYPES_REVERSE[t]}:qc.ERROR_PACKET};Lf.decodePacket=xX;const NX=(e,r)=>{if(MX){const t=(0,PX.decode)(e);return u$(t,r)}else return{base64:!0,data:e}},u$=(e,r)=>{switch(r){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.decodePayload=e.decodePacket=e.encodePayload=e.encodePacket=e.protocol=void 0,e.createPacketEncoderStream=o,e.createPacketDecoderStream=p;const r=Ku;Object.defineProperty(e,"encodePacket",{enumerable:!0,get:function(){return r.encodePacket}});const t=Lf;Object.defineProperty(e,"decodePacket",{enumerable:!0,get:function(){return t.decodePacket}});const n=bi,i="",a=(v,m)=>{const _=v.length,T=new Array(_);let I=0;v.forEach(($,x)=>{(0,r.encodePacket)($,!1,N=>{T[x]=N,++I===_&&m(T.join(i))})})};e.encodePayload=a;const s=(v,m)=>{const _=v.split(i),T=[];for(let I=0;I<_.length;I++){const $=(0,t.decodePacket)(_[I],m);if(T.push($),$.type==="error")break}return T};e.decodePayload=s;function o(){return new TransformStream({transform(v,m){(0,r.encodePacketToBinary)(v,_=>{const T=_.length;let I;if(T<126)I=new Uint8Array(1),new DataView(I.buffer).setUint8(0,T);else if(T<65536){I=new Uint8Array(3);const $=new DataView(I.buffer);$.setUint8(0,126),$.setUint16(1,T)}else{I=new Uint8Array(9);const $=new DataView(I.buffer);$.setUint8(0,127),$.setBigUint64(1,BigInt(T))}v.data&&typeof v.data!="string"&&(I[0]|=128),m.enqueue(I),m.enqueue(_)})}})}let u;function c(v){return v.reduce((m,_)=>m+_.length,0)}function l(v,m){if(v[0].length===m)return v.shift();const _=new Uint8Array(m);let T=0;for(let I=0;I<m;I++)_[I]=v[0][T++],T===v[0].length&&(v.shift(),T=0);return v.length&&T<v[0].length&&(v[0]=v[0].slice(T)),_}function p(v,m){u||(u=new TextDecoder);const _=[];let T=0,I=-1,$=!1;return new TransformStream({transform(x,N){for(_.push(x);;){if(T===0){if(c(_)<1)break;const j=l(_,1);$=(j[0]&128)===128,I=j[0]&127,I<126?T=3:I===126?T=1:T=2}else if(T===1){if(c(_)<2)break;const j=l(_,2);I=new DataView(j.buffer,j.byteOffset,j.length).getUint16(0),T=3}else if(T===2){if(c(_)<8)break;const j=l(_,8),X=new DataView(j.buffer,j.byteOffset,j.length),J=X.getUint32(0);if(J>Math.pow(2,21)-1){N.enqueue(n.ERROR_PACKET);break}I=J*Math.pow(2,32)+X.getUint32(4),T=3}else{if(c(_)<I)break;const j=l(_,I);N.enqueue((0,t.decodePacket)($?j:u.decode(j),m)),T=0}if(I===0||I>v){N.enqueue(n.ERROR_PACKET);break}}}})}e.protocol=4})(_o);function en(e){if(e)return LX(e)}function LX(e){for(var r in en.prototype)e[r]=en.prototype[r];return e}en.prototype.on=en.prototype.addEventListener=function(e,r){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(r),this};en.prototype.once=function(e,r){function t(){this.off(e,t),r.apply(this,arguments)}return t.fn=r,this.on(e,t),this};en.prototype.off=en.prototype.removeListener=en.prototype.removeAllListeners=en.prototype.removeEventListener=function(e,r){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+e];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var n,i=0;i<t.length;i++)if(n=t[i],n===r||n.fn===r){t.splice(i,1);break}return t.length===0&&delete this._callbacks["$"+e],this};en.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var r=new Array(arguments.length-1),t=this._callbacks["$"+e],n=1;n<arguments.length;n++)r[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,i=t.length;n<i;++n)t[n].apply(this,r)}return this};en.prototype.emitReserved=en.prototype.emit;en.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};en.prototype.hasListeners=function(e){return!!this.listeners(e).length};const DX=Object.freeze(Object.defineProperty({__proto__:null,Emitter:en},Symbol.toStringTag,{value:"Module"})),wo=hT(DX);var oi={},pn={};Object.defineProperty(pn,"__esModule",{value:!0});pn.defaultBinaryType=pn.globalThisShim=pn.nextTick=void 0;pn.createCookieJar=jX;pn.nextTick=typeof Promise=="function"&&typeof Promise.resolve=="function"?r=>Promise.resolve().then(r):(r,t)=>t(r,0);pn.globalThisShim=typeof self<"u"?self:typeof window<"u"?window:Function("return this")();pn.defaultBinaryType="arraybuffer";function jX(){}Object.defineProperty(oi,"__esModule",{value:!0});oi.pick=FX;oi.installTimerFunctions=qX;oi.byteLength=WX;oi.randomString=GX;const va=pn;function FX(e,...r){return r.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const UX=va.globalThisShim.setTimeout,BX=va.globalThisShim.clearTimeout;function qX(e,r){r.useNativeTimers?(e.setTimeoutFn=UX.bind(va.globalThisShim),e.clearTimeoutFn=BX.bind(va.globalThisShim)):(e.setTimeoutFn=va.globalThisShim.setTimeout.bind(va.globalThisShim),e.clearTimeoutFn=va.globalThisShim.clearTimeout.bind(va.globalThisShim))}const zX=1.33;function WX(e){return typeof e=="string"?HX(e):Math.ceil((e.byteLength||e.size)*zX)}function HX(e){let r=0,t=0;for(let n=0,i=e.length;n<i;n++)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:r<55296||r>=57344?t+=3:(n++,t+=4);return t}function GX(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}var Ju={};Object.defineProperty(Ju,"__esModule",{value:!0});Ju.encode=VX;Ju.decode=KX;function VX(e){let r="";for(let t in e)e.hasOwnProperty(t)&&(r.length&&(r+="&"),r+=encodeURIComponent(t)+"="+encodeURIComponent(e[t]));return r}function KX(e){let r={},t=e.split("&");for(let n=0,i=t.length;n<i;n++){let a=t[n].split("=");r[decodeURIComponent(a[0])]=decodeURIComponent(a[1])}return r}var pv={exports:{}},Jp,d0;function JX(){if(d0)return Jp;d0=1;var e=1e3,r=e*60,t=r*60,n=t*24,i=n*7,a=n*365.25;Jp=function(l,p){p=p||{};var v=typeof l;if(v==="string"&&l.length>0)return s(l);if(v==="number"&&isFinite(l))return p.long?u(l):o(l);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(l))};function s(l){if(l=String(l),!(l.length>100)){var p=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(l);if(p){var v=parseFloat(p[1]),m=(p[2]||"ms").toLowerCase();switch(m){case"years":case"year":case"yrs":case"yr":case"y":return v*a;case"weeks":case"week":case"w":return v*i;case"days":case"day":case"d":return v*n;case"hours":case"hour":case"hrs":case"hr":case"h":return v*t;case"minutes":case"minute":case"mins":case"min":case"m":return v*r;case"seconds":case"second":case"secs":case"sec":case"s":return v*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return v;default:return}}}}function o(l){var p=Math.abs(l);return p>=n?Math.round(l/n)+"d":p>=t?Math.round(l/t)+"h":p>=r?Math.round(l/r)+"m":p>=e?Math.round(l/e)+"s":l+"ms"}function u(l){var p=Math.abs(l);return p>=n?c(l,p,n,"day"):p>=t?c(l,p,t,"hour"):p>=r?c(l,p,r,"minute"):p>=e?c(l,p,e,"second"):l+" ms"}function c(l,p,v,m){var _=p>=v*1.5;return Math.round(l/v)+" "+m+(_?"s":"")}return Jp}function YX(e){t.debug=t,t.default=t,t.coerce=u,t.disable=a,t.enable=i,t.enabled=s,t.humanize=JX(),t.destroy=c,Object.keys(e).forEach(l=>{t[l]=e[l]}),t.names=[],t.skips=[],t.formatters={};function r(l){let p=0;for(let v=0;v<l.length;v++)p=(p<<5)-p+l.charCodeAt(v),p|=0;return t.colors[Math.abs(p)%t.colors.length]}t.selectColor=r;function t(l){let p,v=null,m,_;function T(...I){if(!T.enabled)return;const $=T,x=Number(new Date),N=x-(p||x);$.diff=N,$.prev=p,$.curr=x,p=x,I[0]=t.coerce(I[0]),typeof I[0]!="string"&&I.unshift("%O");let j=0;I[0]=I[0].replace(/%([a-zA-Z%])/g,(J,G)=>{if(J==="%%")return"%";j++;const L=t.formatters[G];if(typeof L=="function"){const re=I[j];J=L.call($,re),I.splice(j,1),j--}return J}),t.formatArgs.call($,I),($.log||t.log).apply($,I)}return T.namespace=l,T.useColors=t.useColors(),T.color=t.selectColor(l),T.extend=n,T.destroy=t.destroy,Object.defineProperty(T,"enabled",{enumerable:!0,configurable:!1,get:()=>v!==null?v:(m!==t.namespaces&&(m=t.namespaces,_=t.enabled(l)),_),set:I=>{v=I}}),typeof t.init=="function"&&t.init(T),T}function n(l,p){const v=t(this.namespace+(typeof p>"u"?":":p)+l);return v.log=this.log,v}function i(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let p;const v=(typeof l=="string"?l:"").split(/[\s,]+/),m=v.length;for(p=0;p<m;p++)v[p]&&(l=v[p].replace(/\*/g,".*?"),l[0]==="-"?t.skips.push(new RegExp("^"+l.slice(1)+"$")):t.names.push(new RegExp("^"+l+"$")))}function a(){const l=[...t.names.map(o),...t.skips.map(o).map(p=>"-"+p)].join(",");return t.enable(""),l}function s(l){if(l[l.length-1]==="*")return!0;let p,v;for(p=0,v=t.skips.length;p<v;p++)if(t.skips[p].test(l))return!1;for(p=0,v=t.names.length;p<v;p++)if(t.names[p].test(l))return!0;return!1}function o(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function u(l){return l instanceof Error?l.stack||l.message:l}function c(){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 XX=YX;(function(e,r){r.formatArgs=n,r.save=i,r.load=a,r.useColors=t,r.storage=s(),r.destroy=(()=>{let u=!1;return()=>{u||(u=!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`."))}})(),r.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 u;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&&(u=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(u[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function n(u){if(u[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+u[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const c="color: "+this.color;u.splice(1,0,c,"color: inherit");let l=0,p=0;u[0].replace(/%[a-zA-Z%]/g,v=>{v!=="%%"&&(l++,v==="%c"&&(p=l))}),u.splice(p,0,c)}r.log=console.debug||console.log||(()=>{});function i(u){try{u?r.storage.setItem("debug",u):r.storage.removeItem("debug")}catch{}}function a(){let u;try{u=r.storage.getItem("debug")}catch{}return!u&&typeof process<"u"&&"env"in process&&(u=process.env.DEBUG),u}function s(){try{return localStorage}catch{}}e.exports=XX(r);const{formatters:o}=e.exports;o.j=function(u){try{return JSON.stringify(u)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}})(pv,pv.exports);var ui=pv.exports,QX=Ne&&Ne.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ki,"__esModule",{value:!0});Ki.Transport=Ki.TransportError=void 0;const ZX=_o,eQ=wo,tQ=oi,rQ=Ju,nQ=QX(ui),iQ=(0,nQ.default)("engine.io-client:transport");class c$ extends Error{constructor(r,t,n){super(r),this.description=t,this.context=n,this.type="TransportError"}}Ki.TransportError=c$;class aQ extends eQ.Emitter{constructor(r){super(),this.writable=!1,(0,tQ.installTimerFunctions)(this,r),this.opts=r,this.query=r.query,this.socket=r.socket,this.supportsBinary=!r.forceBase64}onError(r,t,n){return super.emitReserved("error",new c$(r,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(r){this.readyState==="open"?this.write(r):iQ("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(r){const t=(0,ZX.decodePacket)(r,this.socket.binaryType);this.onPacket(t)}onPacket(r){super.emitReserved("packet",r)}onClose(r){this.readyState="closed",super.emitReserved("close",r)}pause(r){}createUri(r,t={}){return r+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const r=this.opts.hostname;return r.indexOf(":")===-1?r:"["+r+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(r){const t=(0,rQ.encode)(r);return t.length?"?"+t:""}}Ki.Transport=aQ;var sQ=Ne&&Ne.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Vu,"__esModule",{value:!0});Vu.Polling=void 0;const oQ=Ki,uQ=oi,p0=_o,cQ=sQ(ui),Kn=(0,cQ.default)("engine.io-client:polling");class lQ extends oQ.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(r){this.readyState="pausing";const t=()=>{Kn("paused"),this.readyState="paused",r()};if(this._polling||!this.writable){let n=0;this._polling&&(Kn("we are currently polling - waiting to pause"),n++,this.once("pollComplete",function(){Kn("pre-pause polling complete"),--n||t()})),this.writable||(Kn("we are currently writing - waiting to pause"),n++,this.once("drain",function(){Kn("pre-pause writing complete"),--n||t()}))}else t()}_poll(){Kn("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(r){Kn("polling got data %s",r);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,p0.decodePayload)(r,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Kn('ignoring poll - transport state "%s"',this.readyState))}doClose(){const r=()=>{Kn("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Kn("transport open - closing"),r()):(Kn("transport not open - deferring close"),this.once("open",r))}write(r){this.writable=!1,(0,p0.encodePayload)(r,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const r=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=(0,uQ.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(r,t)}}Vu.Polling=lQ;var Df={};Object.defineProperty(Df,"__esModule",{value:!0});Df.hasCORS=void 0;let l$=!1;try{l$=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}Df.hasCORS=l$;var fQ=Ne&&Ne.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(yi,"__esModule",{value:!0});yi.XHR=yi.Request=yi.BaseXHR=void 0;const dQ=Vu,pQ=wo,h0=oi,f$=pn,hQ=Df,vQ=fQ(ui),hv=(0,vQ.default)("engine.io-client:polling");function mQ(){}class d$ extends dQ.Polling{constructor(r){if(super(r),typeof location<"u"){const t=location.protocol==="https:";let n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&r.hostname!==location.hostname||n!==r.port}}doWrite(r,t){const n=this.request({method:"POST",data:r});n.on("success",t),n.on("error",(i,a)=>{this.onError("xhr post error",i,a)})}doPoll(){hv("xhr poll");const r=this.request();r.on("data",this.onData.bind(this)),r.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=r}}yi.BaseXHR=d$;class ni extends pQ.Emitter{constructor(r,t,n){super(),this.createRequest=r,(0,h0.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 r;const t=(0,h0.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{hv("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{}(r=this._opts.cookieJar)===null||r===void 0||r.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))},hv("xhr data %s",this._data),n.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=ni.requestsCount++,ni.requests[this._index]=this)}_onError(r){this.emitReserved("error",r,this._xhr),this._cleanup(!0)}_cleanup(r){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=mQ,r)try{this._xhr.abort()}catch{}typeof document<"u"&&delete ni.requests[this._index],this._xhr=null}}_onLoad(){const r=this._xhr.responseText;r!==null&&(this.emitReserved("data",r),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}yi.Request=ni;ni.requestsCount=0;ni.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",v0);else if(typeof addEventListener=="function"){const e="onpagehide"in f$.globalThisShim?"pagehide":"unload";addEventListener(e,v0,!1)}}function v0(){for(let e in ni.requests)ni.requests.hasOwnProperty(e)&&ni.requests[e].abort()}const gQ=function(){const e=p$({xdomain:!1});return e&&e.responseType!==null}();class yQ extends d${constructor(r){super(r);const t=r&&r.forceBase64;this.supportsBinary=gQ&&!t}request(r={}){return Object.assign(r,{xd:this.xd},this.opts),new ni(p$,this.uri(),r)}}yi.XHR=yQ;function p$(e){const r=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!r||hQ.hasCORS))return new XMLHttpRequest}catch{}if(!r)try{return new f$.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Ra={},bQ=Ne&&Ne.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ra,"__esModule",{value:!0});Ra.WS=Ra.BaseWS=void 0;const _Q=Ki,m0=oi,wQ=_o,vv=pn,SQ=bQ(ui),TQ=(0,SQ.default)("engine.io-client:websocket"),h$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class v$ extends _Q.Transport{get name(){return"websocket"}doOpen(){const r=this.uri(),t=this.opts.protocols,n=h$?{}:(0,m0.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(r,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=r=>this.onClose({description:"websocket connection closed",context:r}),this.ws.onmessage=r=>this.onData(r.data),this.ws.onerror=r=>this.onError("websocket error",r)}write(r){this.writable=!1;for(let t=0;t<r.length;t++){const n=r[t],i=t===r.length-1;(0,wQ.encodePacket)(n,this.supportsBinary,a=>{try{this.doWrite(n,a)}catch{TQ("websocket closed before onclose event")}i&&(0,vv.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 r=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=(0,m0.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(r,t)}}Ra.BaseWS=v$;const Yp=vv.globalThisShim.WebSocket||vv.globalThisShim.MozWebSocket;class CQ extends v${createSocket(r,t,n){return h$?new Yp(r,t,n):t?new Yp(r,t):new Yp(r)}doWrite(r,t){this.ws.send(t)}}Ra.WS=CQ;var Yu={},EQ=Ne&&Ne.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Yu,"__esModule",{value:!0});Yu.WT=void 0;const kQ=Ki,RQ=pn,g0=_o,$Q=EQ(ui),Wo=(0,$Q.default)("engine.io-client:webtransport");class IQ extends kQ.Transport{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(r){return this.emitReserved("error",r)}this._transport.closed.then(()=>{Wo("transport closed gracefully"),this.onClose()}).catch(r=>{Wo("transport closed due to %s",r),this.onError("webtransport error",r)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(r=>{const t=(0,g0.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=r.readable.pipeThrough(t).getReader(),i=(0,g0.createPacketEncoderStream)();i.readable.pipeTo(r.writable),this._writer=i.writable.getWriter();const a=()=>{n.read().then(({done:o,value:u})=>{if(o){Wo("session is closed");return}Wo("received chunk: %o",u),this.onPacket(u),a()}).catch(o=>{Wo("an error occurred while reading: %s",o)})};a();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this._writer.write(s).then(()=>this.onOpen())})})}write(r){this.writable=!1;for(let t=0;t<r.length;t++){const n=r[t],i=t===r.length-1;this._writer.write(n).then(()=>{i&&(0,RQ.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var r;(r=this._transport)===null||r===void 0||r.close()}}Yu.WT=IQ;Object.defineProperty(Gu,"__esModule",{value:!0});Gu.transports=void 0;const OQ=yi,AQ=Ra,PQ=Yu;Gu.transports={websocket:AQ.WS,webtransport:PQ.WT,polling:OQ.XHR};var jf={};Object.defineProperty(jf,"__esModule",{value:!0});jf.parse=NQ;const MQ=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,xQ=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function NQ(e){if(e.length>8e3)throw"URI too long";const r=e,t=e.indexOf("["),n=e.indexOf("]");t!=-1&&n!=-1&&(e=e.substring(0,t)+e.substring(t,n).replace(/:/g,";")+e.substring(n,e.length));let i=MQ.exec(e||""),a={},s=14;for(;s--;)a[xQ[s]]=i[s]||"";return t!=-1&&n!=-1&&(a.source=r,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a.pathNames=LQ(a,a.path),a.queryKey=DQ(a,a.query),a}function LQ(e,r){const t=/\/{2,9}/g,n=r.replace(t,"/").split("/");return(r.slice(0,1)=="/"||r.length===0)&&n.splice(0,1),r.slice(-1)=="/"&&n.splice(n.length-1,1),n}function DQ(e,r){const t={};return r.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,a){i&&(t[i]=a)}),t}var jQ=Ne&&Ne.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(zi,"__esModule",{value:!0});zi.Socket=zi.SocketWithUpgrade=zi.SocketWithoutUpgrade=void 0;const FQ=Gu,y0=oi,UQ=Ju,b0=jf,BQ=wo,m$=_o,Xp=pn,qQ=jQ(ui),rr=(0,qQ.default)("engine.io-client:socket"),mv=typeof addEventListener=="function"&&typeof removeEventListener=="function",au=[];mv&&addEventListener("offline",()=>{rr("closing %d connection(s) because the network was lost",au.length),au.forEach(e=>e())},!1);class Wi extends BQ.Emitter{constructor(r,t){if(super(),this.binaryType=Xp.defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,r&&typeof r=="object"&&(t=r,r=null),r){const n=(0,b0.parse)(r);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,b0.parse)(t.host).host);(0,y0.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,UQ.decode)(this.opts.query)),mv&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(rr("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},au.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,Xp.createCookieJar)()),this._open()}createTransport(r){rr('creating transport "%s"',r);const t=Object.assign({},this.opts.query);t.EIO=m$.protocol,t.transport=r,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[r]);return rr("options: %j",n),new this._transportsByName[r](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const r=this.opts.rememberUpgrade&&Wi.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(r);t.open(),this.setTransport(t)}setTransport(r){rr("setting transport %s",r.name),this.transport&&(rr("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=r,r.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(){rr("socket open"),this.readyState="open",Wi.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(rr('socket receive: type "%s", data "%s"',r.type,r.data),this.emitReserved("packet",r),this.emitReserved("heartbeat"),r.type){case"open":this.onHandshake(JSON.parse(r.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=r.data,this._onError(t);break;case"message":this.emitReserved("data",r.data),this.emitReserved("message",r.data);break}else rr('packet received with socket readyState "%s"',this.readyState)}onHandshake(r){this.emitReserved("handshake",r),this.id=r.sid,this.transport.query.sid=r.sid,this._pingInterval=r.pingInterval,this._pingTimeout=r.pingTimeout,this._maxPayload=r.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const r=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+r,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},r),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 r=this._getWritablePackets();rr("flushing %d packets in socket",r.length),this.transport.send(r),this._prevBufferLen=r.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,y0.byteLength)(i)),n>0&&t>this._maxPayload)return rr("only send %d out of %d packets",n,this.writeBuffer.length),this.writeBuffer.slice(0,n);t+=2}return rr("payload size is %d (max: %d)",t,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const r=Date.now()>this._pingTimeoutTime;return r&&(rr("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,Xp.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),r}write(r,t,n){return this._sendPacket("message",r,t,n),this}send(r,t,n){return this._sendPacket("message",r,t,n),this}_sendPacket(r,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 a={type:r,data:t,options:n};this.emitReserved("packetCreate",a),this.writeBuffer.push(a),i&&this.once("flush",i),this.flush()}close(){const r=()=>{this._onClose("forced close"),rr("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),r()},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():r()}):this.upgrading?n():r()),this}_onError(r){if(rr("socket error %j",r),Wi.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return rr("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",r),this._onClose("transport error",r)}_onClose(r,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(rr('socket close with reason: "%s"',r),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),mv&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=au.indexOf(this._offlineEventListener);n!==-1&&(rr("removing listener for the 'offline' event"),au.splice(n,1))}this.readyState="closed",this.id=null,this.emitReserved("close",r,t),this.writeBuffer=[],this._prevBufferLen=0}}}zi.SocketWithoutUpgrade=Wi;Wi.protocol=m$.protocol;class g$ extends Wi{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){rr("starting upgrade probes");for(let r=0;r<this._upgrades.length;r++)this._probe(this._upgrades[r])}}_probe(r){rr('probing transport "%s"',r);let t=this.createTransport(r),n=!1;Wi.priorWebsocketSuccess=!1;const i=()=>{n||(rr('probe transport "%s" opened',r),t.send([{type:"ping",data:"probe"}]),t.once("packet",p=>{if(!n)if(p.type==="pong"&&p.data==="probe"){if(rr('probe transport "%s" pong',r),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Wi.priorWebsocketSuccess=t.name==="websocket",rr('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{n||this.readyState!=="closed"&&(rr("changing transport and sending upgrade packet"),l(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{rr('probe transport "%s" failed',r);const v=new Error("probe error");v.transport=t.name,this.emitReserved("upgradeError",v)}}))};function a(){n||(n=!0,l(),t.close(),t=null)}const s=p=>{const v=new Error("probe error: "+p);v.transport=t.name,a(),rr('probe transport "%s" failed because of error: %s',r,p),this.emitReserved("upgradeError",v)};function o(){s("transport closed")}function u(){s("socket closed")}function c(p){t&&p.name!==t.name&&(rr('"%s" works - aborting "%s"',p.name,t.name),a())}const l=()=>{t.removeListener("open",i),t.removeListener("error",s),t.removeListener("close",o),this.off("close",u),this.off("upgrading",c)};t.once("open",i),t.once("error",s),t.once("close",o),this.once("close",u),this.once("upgrading",c),this._upgrades.indexOf("webtransport")!==-1&&r!=="webtransport"?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(r){this._upgrades=this._filterUpgrades(r.upgrades),super.onHandshake(r)}_filterUpgrades(r){const t=[];for(let n=0;n<r.length;n++)~this.transports.indexOf(r[n])&&t.push(r[n]);return t}}zi.SocketWithUpgrade=g$;let zQ=class extends g${constructor(r,t={}){const n=typeof r=="object"?r:t;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(i=>FQ.transports[i]).filter(i=>!!i)),super(r,n)}};zi.Socket=zQ;var Ff={};Object.defineProperty(Ff,"__esModule",{value:!0});Ff.Fetch=void 0;const WQ=Vu;class HQ extends WQ.Polling{doPoll(){this._fetch().then(r=>{if(!r.ok)return this.onError("fetch read error",r.status,r);r.text().then(t=>this.onData(t))}).catch(r=>{this.onError("fetch read error",r)})}doWrite(r,t){this._fetch(r).then(n=>{if(!n.ok)return this.onError("fetch write error",n.status,n);t()}).catch(n=>{this.onError("fetch write error",n)})}_fetch(r){var t;const n=r!==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?r:null,headers:i,credentials:this.opts.withCredentials?"include":"omit"}).then(a=>{var s;return(s=this.socket._cookieJar)===null||s===void 0||s.parseCookies(a.headers.getSetCookie()),a})}}Ff.Fetch=HQ;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.WebTransport=e.WebSocket=e.NodeWebSocket=e.XHR=e.NodeXHR=e.Fetch=e.nextTick=e.parse=e.installTimerFunctions=e.transports=e.TransportError=e.Transport=e.protocol=e.SocketWithUpgrade=e.SocketWithoutUpgrade=e.Socket=void 0;const r=zi;Object.defineProperty(e,"Socket",{enumerable:!0,get:function(){return r.Socket}});var t=zi;Object.defineProperty(e,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return t.SocketWithoutUpgrade}}),Object.defineProperty(e,"SocketWithUpgrade",{enumerable:!0,get:function(){return t.SocketWithUpgrade}}),e.protocol=r.Socket.protocol;var n=Ki;Object.defineProperty(e,"Transport",{enumerable:!0,get:function(){return n.Transport}}),Object.defineProperty(e,"TransportError",{enumerable:!0,get:function(){return n.TransportError}});var i=Gu;Object.defineProperty(e,"transports",{enumerable:!0,get:function(){return i.transports}});var a=oi;Object.defineProperty(e,"installTimerFunctions",{enumerable:!0,get:function(){return a.installTimerFunctions}});var s=jf;Object.defineProperty(e,"parse",{enumerable:!0,get:function(){return s.parse}});var o=pn;Object.defineProperty(e,"nextTick",{enumerable:!0,get:function(){return o.nextTick}});var u=Ff;Object.defineProperty(e,"Fetch",{enumerable:!0,get:function(){return u.Fetch}});var c=yi;Object.defineProperty(e,"NodeXHR",{enumerable:!0,get:function(){return c.XHR}});var l=yi;Object.defineProperty(e,"XHR",{enumerable:!0,get:function(){return l.XHR}});var p=Ra;Object.defineProperty(e,"NodeWebSocket",{enumerable:!0,get:function(){return p.WS}});var v=Ra;Object.defineProperty(e,"WebSocket",{enumerable:!0,get:function(){return v.WS}});var m=Yu;Object.defineProperty(e,"WebTransport",{enumerable:!0,get:function(){return m.WT}})})(Nf);var GQ=Ne&&Ne.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Pg,"__esModule",{value:!0});Pg.url=JQ;const VQ=Nf,KQ=GQ(ui),_0=(0,KQ.default)("socket.io-client:url");function JQ(e,r="",t){let n=e;t=t||typeof location<"u"&&location,e==null&&(e=t.protocol+"//"+t.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=t.protocol+e:e=t.host+e),/^(https?|wss?):\/\//.test(e)||(_0("protocol-less url %s",e),typeof t<"u"?e=t.protocol+"//"+e:e="https://"+e),_0("parse %s",e),n=(0,VQ.parse)(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const a=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+a+":"+n.port+r,n.href=n.protocol+"://"+a+(t&&t.port===n.port?"":":"+n.port),n}var Uf={},Xu={},Bf={},uo={},os={};Object.defineProperty(os,"__esModule",{value:!0});os.hasBinary=os.isBinary=void 0;const YQ=typeof ArrayBuffer=="function",XQ=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,y$=Object.prototype.toString,QQ=typeof Blob=="function"||typeof Blob<"u"&&y$.call(Blob)==="[object BlobConstructor]",ZQ=typeof File=="function"||typeof File<"u"&&y$.call(File)==="[object FileConstructor]";function b$(e){return YQ&&(e instanceof ArrayBuffer||XQ(e))||QQ&&e instanceof Blob||ZQ&&e instanceof File}os.isBinary=b$;function gl(e,r){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(gl(e[t]))return!0;return!1}if(b$(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return gl(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&gl(e[t]))return!0;return!1}os.hasBinary=gl;Object.defineProperty(uo,"__esModule",{value:!0});uo.reconstructPacket=uo.deconstructPacket=void 0;const eZ=os;function tZ(e){const r=[],t=e.data,n=e;return n.data=gv(t,r),n.attachments=r.length,{packet:n,buffers:r}}uo.deconstructPacket=tZ;function gv(e,r){if(!e)return e;if((0,eZ.isBinary)(e)){const t={_placeholder:!0,num:r.length};return r.push(e),t}else if(Array.isArray(e)){const t=new Array(e.length);for(let n=0;n<e.length;n++)t[n]=gv(e[n],r);return t}else if(typeof e=="object"&&!(e instanceof Date)){const t={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=gv(e[n],r));return t}return e}function rZ(e,r){return e.data=yv(e.data,r),delete e.attachments,e}uo.reconstructPacket=rZ;function yv(e,r){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num=="number"&&e.num>=0&&e.num<r.length)return r[e.num];throw new Error("illegal attachments")}else if(Array.isArray(e))for(let t=0;t<e.length;t++)e[t]=yv(e[t],r);else if(typeof e=="object")for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(e[t]=yv(e[t],r));return e}(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Decoder=e.Encoder=e.PacketType=e.protocol=void 0;const r=wo,t=uo,n=os,a=(0,ui.default)("socket.io-parser"),s=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];e.protocol=5;var o;(function(v){v[v.CONNECT=0]="CONNECT",v[v.DISCONNECT=1]="DISCONNECT",v[v.EVENT=2]="EVENT",v[v.ACK=3]="ACK",v[v.CONNECT_ERROR=4]="CONNECT_ERROR",v[v.BINARY_EVENT=5]="BINARY_EVENT",v[v.BINARY_ACK=6]="BINARY_ACK"})(o=e.PacketType||(e.PacketType={}));class u{constructor(m){this.replacer=m}encode(m){return a("encoding packet %j",m),(m.type===o.EVENT||m.type===o.ACK)&&(0,n.hasBinary)(m)?this.encodeAsBinary({type:m.type===o.EVENT?o.BINARY_EVENT:o.BINARY_ACK,nsp:m.nsp,data:m.data,id:m.id}):[this.encodeAsString(m)]}encodeAsString(m){let _=""+m.type;return(m.type===o.BINARY_EVENT||m.type===o.BINARY_ACK)&&(_+=m.attachments+"-"),m.nsp&&m.nsp!=="/"&&(_+=m.nsp+","),m.id!=null&&(_+=m.id),m.data!=null&&(_+=JSON.stringify(m.data,this.replacer)),a("encoded %j as %s",m,_),_}encodeAsBinary(m){const _=(0,t.deconstructPacket)(m),T=this.encodeAsString(_.packet),I=_.buffers;return I.unshift(T),I}}e.Encoder=u;function c(v){return Object.prototype.toString.call(v)==="[object Object]"}class l extends r.Emitter{constructor(m){super(),this.reviver=m}add(m){let _;if(typeof m=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");_=this.decodeString(m);const T=_.type===o.BINARY_EVENT;T||_.type===o.BINARY_ACK?(_.type=T?o.EVENT:o.ACK,this.reconstructor=new p(_),_.attachments===0&&super.emitReserved("decoded",_)):super.emitReserved("decoded",_)}else if((0,n.isBinary)(m)||m.base64)if(this.reconstructor)_=this.reconstructor.takeBinaryData(m),_&&(this.reconstructor=null,super.emitReserved("decoded",_));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+m)}decodeString(m){let _=0;const T={type:Number(m.charAt(0))};if(o[T.type]===void 0)throw new Error("unknown packet type "+T.type);if(T.type===o.BINARY_EVENT||T.type===o.BINARY_ACK){const $=_+1;for(;m.charAt(++_)!=="-"&&_!=m.length;);const x=m.substring($,_);if(x!=Number(x)||m.charAt(_)!=="-")throw new Error("Illegal attachments");T.attachments=Number(x)}if(m.charAt(_+1)==="/"){const $=_+1;for(;++_&&!(m.charAt(_)===","||_===m.length););T.nsp=m.substring($,_)}else T.nsp="/";const I=m.charAt(_+1);if(I!==""&&Number(I)==I){const $=_+1;for(;++_;){const x=m.charAt(_);if(x==null||Number(x)!=x){--_;break}if(_===m.length)break}T.id=Number(m.substring($,_+1))}if(m.charAt(++_)){const $=this.tryParse(m.substr(_));if(l.isPayloadValid(T.type,$))T.data=$;else throw new Error("invalid payload")}return a("decoded %s as %j",m,T),T}tryParse(m){try{return JSON.parse(m,this.reviver)}catch{return!1}}static isPayloadValid(m,_){switch(m){case o.CONNECT:return c(_);case o.DISCONNECT:return _===void 0;case o.CONNECT_ERROR:return typeof _=="string"||c(_);case o.EVENT:case o.BINARY_EVENT:return Array.isArray(_)&&(typeof _[0]=="number"||typeof _[0]=="string"&&s.indexOf(_[0])===-1);case o.ACK:case o.BINARY_ACK:return Array.isArray(_)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}e.Decoder=l;class p{constructor(m){this.packet=m,this.buffers=[],this.reconPack=m}takeBinaryData(m){if(this.buffers.push(m),this.buffers.length===this.reconPack.attachments){const _=(0,t.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),_}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}})(Bf);var qf={};Object.defineProperty(qf,"__esModule",{value:!0});qf.on=nZ;function nZ(e,r,t){return e.on(r,t),function(){e.off(r,t)}}var iZ=Ne&&Ne.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Xu,"__esModule",{value:!0});Xu.Socket=void 0;const Jn=Bf,zc=qf,aZ=wo,sZ=iZ(ui),xr=(0,sZ.default)("socket.io-client:socket"),oZ=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class uZ extends aZ.Emitter{constructor(r,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=r,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 r=this.io;this.subs=[(0,zc.on)(r,"open",this.onopen.bind(this)),(0,zc.on)(r,"packet",this.onpacket.bind(this)),(0,zc.on)(r,"error",this.onerror.bind(this)),(0,zc.on)(r,"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(...r){return r.unshift("message"),this.emit.apply(this,r),this}emit(r,...t){var n,i,a;if(oZ.hasOwnProperty(r))throw new Error('"'+r.toString()+'" is a reserved event name');if(t.unshift(r),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const s={type:Jn.PacketType.EVENT,data:t};if(s.options={},s.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const l=this.ids++;xr("emitting packet with ack id %d",l);const p=t.pop();this._registerAckCallback(l,p),s.id=l}const o=(i=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||i===void 0?void 0:i.writable,u=this.connected&&!(!((a=this.io.engine)===null||a===void 0)&&a._hasPingExpired());return this.flags.volatile&&!o?xr("discard packet as the transport is not currently writable"):u?(this.notifyOutgoingListeners(s),this.packet(s)):this.sendBuffer.push(s),this.flags={},this}_registerAckCallback(r,t){var n;const i=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(i===void 0){this.acks[r]=t;return}const a=this.io.setTimeoutFn(()=>{delete this.acks[r];for(let o=0;o<this.sendBuffer.length;o++)this.sendBuffer[o].id===r&&(xr("removing packet with ack id %d from the buffer",r),this.sendBuffer.splice(o,1));xr("event with ack id %d has timed out after %d ms",r,i),t.call(this,new Error("operation has timed out"))},i),s=(...o)=>{this.io.clearTimeoutFn(a),t.apply(this,o)};s.withError=!0,this.acks[r]=s}emitWithAck(r,...t){return new Promise((n,i)=>{const a=(s,o)=>s?i(s):n(o);a.withError=!0,t.push(a),this.emit(r,...t)})}_addToQueue(r){let t;typeof r[r.length-1]=="function"&&(t=r.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:r,flags:Object.assign({fromQueue:!0},this.flags)};r.push((i,...a)=>n!==this._queue[0]?void 0:(i!==null?n.tryCount>this._opts.retries&&(xr("packet [%d] is discarded after %d tries",n.id,n.tryCount),this._queue.shift(),t&&t(i)):(xr("packet [%d] was successfully sent",n.id),this._queue.shift(),t&&t(null,...a)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(r=!1){if(xr("draining queue"),!this.connected||this._queue.length===0)return;const t=this._queue[0];if(t.pending&&!r){xr("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,xr("sending packet [%d] (try n°%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)}packet(r){r.nsp=this.nsp,this.io._packet(r)}onopen(){xr("transport is open - connecting"),typeof this.auth=="function"?this.auth(r=>{this._sendConnectPacket(r)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(r){this.packet({type:Jn.PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},r):r})}onerror(r){this.connected||this.emitReserved("connect_error",r)}onclose(r,t){xr("close (%s)",r),this.connected=!1,delete this.id,this.emitReserved("disconnect",r,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(r=>{if(!this.sendBuffer.some(n=>String(n.id)===r)){const n=this.acks[r];delete this.acks[r],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(r){if(r.nsp===this.nsp)switch(r.type){case Jn.PacketType.CONNECT:r.data&&r.data.sid?this.onconnect(r.data.sid,r.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 Jn.PacketType.EVENT:case Jn.PacketType.BINARY_EVENT:this.onevent(r);break;case Jn.PacketType.ACK:case Jn.PacketType.BINARY_ACK:this.onack(r);break;case Jn.PacketType.DISCONNECT:this.ondisconnect();break;case Jn.PacketType.CONNECT_ERROR:this.destroy();const n=new Error(r.data.message);n.data=r.data.data,this.emitReserved("connect_error",n);break}}onevent(r){const t=r.data||[];xr("emitting event %j",t),r.id!=null&&(xr("attaching ack callback to event"),t.push(this.ack(r.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(r){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,r)}super.emit.apply(this,r),this._pid&&r.length&&typeof r[r.length-1]=="string"&&(this._lastOffset=r[r.length-1])}ack(r){const t=this;let n=!1;return function(...i){n||(n=!0,xr("sending ack %j",i),t.packet({type:Jn.PacketType.ACK,id:r,data:i}))}}onack(r){const t=this.acks[r.id];if(typeof t!="function"){xr("bad ack %s",r.id);return}delete this.acks[r.id],xr("calling ack %s with %j",r.id,r.data),t.withError&&r.data.unshift(null),t.apply(this,r.data)}onconnect(r,t){xr("socket connected with id %s",r),this.id=r,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(r=>this.emitEvent(r)),this.receiveBuffer=[],this.sendBuffer.forEach(r=>{this.notifyOutgoingListeners(r),this.packet(r)}),this.sendBuffer=[]}ondisconnect(){xr("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(r=>r()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(xr("performing disconnect (%s)",this.nsp),this.packet({type:Jn.PacketType.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(r){return this.flags.compress=r,this}get volatile(){return this.flags.volatile=!0,this}timeout(r){return this.flags.timeout=r,this}onAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(r),this}prependAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(r),this}offAny(r){if(!this._anyListeners)return this;if(r){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(r===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(r),this}prependAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(r),this}offAnyOutgoing(r){if(!this._anyOutgoingListeners)return this;if(r){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(r===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(r){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,r.data)}}}Xu.Socket=uZ;var Mg={};Object.defineProperty(Mg,"__esModule",{value:!0});Mg.Backoff=So;function So(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}So.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var r=Math.random(),t=Math.floor(r*this.jitter*e);e=Math.floor(r*10)&1?e+t:e-t}return Math.min(e,this.max)|0};So.prototype.reset=function(){this.attempts=0};So.prototype.setMin=function(e){this.ms=e};So.prototype.setMax=function(e){this.max=e};So.prototype.setJitter=function(e){this.jitter=e};var cZ=Ne&&Ne.__createBinding||(Object.create?function(e,r,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(r,t);(!i||("get"in i?!r.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return r[t]}}),Object.defineProperty(e,n,i)}:function(e,r,t,n){n===void 0&&(n=t),e[n]=r[t]}),lZ=Ne&&Ne.__setModuleDefault||(Object.create?function(e,r){Object.defineProperty(e,"default",{enumerable:!0,value:r})}:function(e,r){e.default=r}),fZ=Ne&&Ne.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var t in e)t!=="default"&&Object.prototype.hasOwnProperty.call(e,t)&&cZ(r,e,t);return lZ(r,e),r},dZ=Ne&&Ne.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Uf,"__esModule",{value:!0});Uf.Manager=void 0;const Qp=Nf,pZ=Xu,hZ=fZ(Bf),Xa=qf,vZ=Mg,mZ=wo,gZ=dZ(ui),Vr=(0,gZ.default)("socket.io-client:manager");class yZ extends mZ.Emitter{constructor(r,t){var n;super(),this.nsps={},this.subs=[],r&&typeof r=="object"&&(t=r,r=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,(0,Qp.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 vZ.Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=r;const i=t.parser||hZ;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(r){return arguments.length?(this._reconnection=!!r,r||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(r){return r===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=r,this)}reconnectionDelay(r){var t;return r===void 0?this._reconnectionDelay:(this._reconnectionDelay=r,(t=this.backoff)===null||t===void 0||t.setMin(r),this)}randomizationFactor(r){var t;return r===void 0?this._randomizationFactor:(this._randomizationFactor=r,(t=this.backoff)===null||t===void 0||t.setJitter(r),this)}reconnectionDelayMax(r){var t;return r===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=r,(t=this.backoff)===null||t===void 0||t.setMax(r),this)}timeout(r){return arguments.length?(this._timeout=r,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(r){if(Vr("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Vr("opening %s",this.uri),this.engine=new Qp.Socket(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=(0,Xa.on)(t,"open",function(){n.onopen(),r&&r()}),a=o=>{Vr("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",o),r?r(o):this.maybeReconnectOnOpen()},s=(0,Xa.on)(t,"error",a);if(this._timeout!==!1){const o=this._timeout;Vr("connect attempt will timeout after %d",o);const u=this.setTimeoutFn(()=>{Vr("connect attempt timed out after %d",o),i(),a(new Error("timeout")),t.close()},o);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(i),this.subs.push(s),this}connect(r){return this.open(r)}onopen(){Vr("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");const r=this.engine;this.subs.push((0,Xa.on)(r,"ping",this.onping.bind(this)),(0,Xa.on)(r,"data",this.ondata.bind(this)),(0,Xa.on)(r,"error",this.onerror.bind(this)),(0,Xa.on)(r,"close",this.onclose.bind(this)),(0,Xa.on)(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(r){try{this.decoder.add(r)}catch(t){this.onclose("parse error",t)}}ondecoded(r){(0,Qp.nextTick)(()=>{this.emitReserved("packet",r)},this.setTimeoutFn)}onerror(r){Vr("error",r),this.emitReserved("error",r)}socket(r,t){let n=this.nsps[r];return n?this._autoConnect&&!n.active&&n.connect():(n=new pZ.Socket(this,r,t),this.nsps[r]=n),n}_destroy(r){const t=Object.keys(this.nsps);for(const n of t)if(this.nsps[n].active){Vr("socket %s is still active, skipping close",n);return}this._close()}_packet(r){Vr("writing packet %j",r);const t=this.encoder.encode(r);for(let n=0;n<t.length;n++)this.engine.write(t[n],r.options)}cleanup(){Vr("cleanup"),this.subs.forEach(r=>r()),this.subs.length=0,this.decoder.destroy()}_close(){Vr("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(r,t){var n;Vr("closed due to %s",r),this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",r,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const r=this;if(this.backoff.attempts>=this._reconnectionAttempts)Vr("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();Vr("will wait %dms before reconnect attempt",t),this._reconnecting=!0;const n=this.setTimeoutFn(()=>{r.skipReconnect||(Vr("attempting reconnect"),this.emitReserved("reconnect_attempt",r.backoff.attempts),!r.skipReconnect&&r.open(i=>{i?(Vr("reconnect attempt error"),r._reconnecting=!1,r.reconnect(),this.emitReserved("reconnect_error",i)):(Vr("reconnect success"),r.onreconnect())}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const r=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",r)}}Uf.Manager=yZ;(function(e,r){var t=Ne&&Ne.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(r,"__esModule",{value:!0}),r.WebTransport=r.WebSocket=r.NodeWebSocket=r.XHR=r.NodeXHR=r.Fetch=r.Socket=r.Manager=r.protocol=void 0,r.io=c,r.connect=c,r.default=c;const n=Pg,i=Uf;Object.defineProperty(r,"Manager",{enumerable:!0,get:function(){return i.Manager}});const a=Xu;Object.defineProperty(r,"Socket",{enumerable:!0,get:function(){return a.Socket}});const o=(0,t(ui).default)("socket.io-client"),u={};function c(v,m){typeof v=="object"&&(m=v,v=void 0),m=m||{};const _=(0,n.url)(v,m.path||"/socket.io"),T=_.source,I=_.id,$=_.path,x=u[I]&&$ in u[I].nsps,N=m.forceNew||m["force new connection"]||m.multiplex===!1||x;let j;return N?(o("ignoring socket cache for %s",T),j=new i.Manager(T,m)):(u[I]||(o("new io instance for %s",T),u[I]=new i.Manager(T,m)),j=u[I]),_.query&&!m.query&&(m.query=_.queryKey),j.socket(_.path,m)}Object.assign(c,{Manager:i.Manager,Socket:a.Socket,io:c,connect:c});var l=Bf;Object.defineProperty(r,"protocol",{enumerable:!0,get:function(){return l.protocol}});var p=Nf;Object.defineProperty(r,"Fetch",{enumerable:!0,get:function(){return p.Fetch}}),Object.defineProperty(r,"NodeXHR",{enumerable:!0,get:function(){return p.NodeXHR}}),Object.defineProperty(r,"XHR",{enumerable:!0,get:function(){return p.XHR}}),Object.defineProperty(r,"NodeWebSocket",{enumerable:!0,get:function(){return p.NodeWebSocket}}),Object.defineProperty(r,"WebSocket",{enumerable:!0,get:function(){return p.WebSocket}}),Object.defineProperty(r,"WebTransport",{enumerable:!0,get:function(){return p.WebTransport}}),e.exports=c})(dv,dv.exports);var _$=dv.exports,w$={exports:{}};(function(e,r){(function(t){e.exports=t()})(function(){var t=function(f,d,h){for(var y=h,g=0,b=f.length;g<b;g++)y=d(y,f[g],g,f);return y},n=function(f,d){return t(f,function(h,y,g,b){return d(y,g,b)?h.concat(y):h},[])},i=function(f,d){return t(f,function(h,y,g,b){return h.concat(d(y,g,b))},[])},a=function(f,d){return t(f,function(h,y,g,b){return h===!0||y===d},!1)},s=!{toString:null}.propertyIsEnumerable("toString"),o=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],u=function(f){var d=[],h;for(h in f)Object.prototype.hasOwnProperty.call(f,h)&&d.push(h);if(!s)return d;for(var y=0,g=o.length;y<g;y++)Object.prototype.hasOwnProperty.call(f,o[y])&&d.push(o[y]);return d},c=function(f){return Object.prototype.toString.call(f)==="[object Array]"},l=function(f){return f<10?"0"+f:f},p=function(){var f=new Date;return f.getUTCFullYear()+"-"+l(f.getUTCMonth()+1)+"-"+l(f.getUTCDate())+"T"+l(f.getUTCHours())+":"+l(f.getUTCMinutes())+":"+l(f.getUTCSeconds())+"."+(f.getUTCMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z"},v={map:i,reduce:t,filter:n,includes:a,keys:u,isArray:c,isoDate:p},m={};m.intRange=function(f,d){return f===void 0&&(f=1),d===void 0&&(d=1/0),function(h){return typeof h=="number"&&parseInt(""+h,10)===h&&h>=f&&h<=d}},m.stringWithLength=function(f){return typeof f=="string"&&!!f.length};var _={},T=v.filter,I=v.reduce,$=v.keys,x=v.isArray,N=v.includes,j=m.intRange,X=m.stringWithLength;_.schema={apiKey:{defaultValue:function(){return null},message:"is required",validate:X},appVersion:{defaultValue:function(){return null},message:"should be a string",validate:function(f){return f===null||X(f)}},appType:{defaultValue:function(){return null},message:"should be a string",validate:function(f){return f===null||X(f)}},autoNotify:{defaultValue:function(){return!0},message:"should be true|false",validate:function(f){return f===!0||f===!1}},beforeSend:{defaultValue:function(){return[]},message:"should be a function or array of functions",validate:function(f){return typeof f=="function"||x(f)&&T(f,function(d){return typeof d=="function"}).length===f.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(f,d){return f&&typeof f=="object"&&X(f.notify)&&(d.autoCaptureSessions===!1||X(f.sessions))&&T($(f),function(h){return!N(["notify","sessions"],h)}).length===0}},autoCaptureSessions:{defaultValue:function(f,d){return d.endpoints===void 0||!!d.endpoints&&!!d.endpoints.sessions},message:"should be true|false",validate:function(f){return f===!0||f===!1}},notifyReleaseStages:{defaultValue:function(){return null},message:"should be an array of strings",validate:function(f){return f===null||x(f)&&T(f,function(d){return typeof d=="string"}).length===f.length}},releaseStage:{defaultValue:function(){return"production"},message:"should be a string",validate:function(f){return typeof f=="string"&&f.length}},maxBreadcrumbs:{defaultValue:function(){return 20},message:"should be a number ≤40",validate:function(f){return j(0,40)(f)}},autoBreadcrumbs:{defaultValue:function(){return!0},message:"should be true|false",validate:function(f){return typeof f=="boolean"}},user:{defaultValue:function(){return null},message:"(object) user should be an object",validate:function(f){return typeof f=="object"}},metaData:{defaultValue:function(){return null},message:"should be an object",validate:function(f){return typeof f=="object"}},logger:{defaultValue:function(){},message:"should be null or an object with methods { debug, info, warn, error }",validate:function(f){return!f||f&&I(["debug","info","warn","error"],function(d,h){return d&&typeof f[h]=="function"},!0)}},filters:{defaultValue:function(){return["password"]},message:"should be an array of strings|regexes",validate:function(f){return x(f)&&f.length===T(f,function(d){return typeof d=="string"||d&&typeof d.test=="function"}).length}}},_.mergeDefaults=function(f,d){if(!f||!d)throw new Error("opts and schema objects are required");return I($(d),function(h,y){return h[y]=f[y]!==void 0?f[y]:d[y].defaultValue(f[y],f),h},{})},_.validate=function(f,d){if(!f||!d)throw new Error("opts and schema objects are required");var h=I($(d),function(y,g){return d[g].validate(f[g],f)?y:y.concat({key:g,message:d[g].message,value:f[g]})},[]);return{valid:!h.length,errors:h}};function J(){return J=Object.assign||function(f){for(var d=1;d<arguments.length;d++){var h=arguments[d];for(var y in h)Object.prototype.hasOwnProperty.call(h,y)&&(f[y]=h[y])}return f},J.apply(this,arguments)}var G=_.schema,L=v.map,re=m.stringWithLength,ue={releaseStage:{defaultValue:function(){return/^localhost(:\d+)?$/.test(window.location.host)?"development":"production"},message:"should be set",validate:re},logger:J({},G.logger,{defaultValue:function(){return typeof console<"u"&&typeof console.debug=="function"?ee():void 0}})},ee=function(){var f={},d=console.log;return L(["debug","info","warn","error"],function(h){var y=console[h];f[h]=typeof y=="function"?y.bind(console,"[bugsnag]"):d.bind(console,"[bugsnag]")}),f},ye=v.isoDate,Z=function(){function f(h,y,g,b){h===void 0&&(h="[anonymous]"),y===void 0&&(y={}),g===void 0&&(g="manual"),b===void 0&&(b=ye()),this.type=g,this.name=h,this.metaData=y,this.timestamp=b}var d=f.prototype;return d.toJSON=function(){return{type:this.type,name:this.name,timestamp:this.timestamp,metaData:this.metaData}},f}(),qe=Z,Qe=function(f,d,h){var y=f.length,g=0,b=function(){if(g>=y)return h(null,!1);d(f[g],function(w,S){if(w)return h(w,!1);if(S===!0)return h(null,!0);g++,b()})};b()},Nt=function(f){return f.app&&typeof f.app.releaseStage=="string"?f.app.releaseStage:f.config.releaseStage},vt=Pe;function Pe(f){switch(Object.prototype.toString.call(f)){case"[object Error]":return!0;case"[object Exception]":return!0;case"[object DOMException]":return!0;default:return f instanceof Error}}var me=vt,he=function(f,d){return function(h,y){if(typeof h!="function")return y(null,!1);try{if(h.length!==2){var g=h(f);return g&&typeof g.then=="function"?g.then(function(b){return setTimeout(function(){return y(null,P(f,b))},0)},function(b){setTimeout(function(){return d(b),y(null,!1)})}):y(null,P(f,g))}h(f,function(b,w){if(b)return d(b),y(null,!1);y(null,P(f,w))})}catch(b){d(b),y(null,!1)}}},P=function(f,d){return f.isIgnored()||d===!1},Oe={};(function(f,d){typeof Oe=="object"?Oe=d():f.StackFrame=d()})(this,function(){function f(W){return!isNaN(parseFloat(W))&&isFinite(W)}function d(W){return W.charAt(0).toUpperCase()+W.substring(1)}function h(W){return function(){return this[W]}}var y=["isConstructor","isEval","isNative","isToplevel"],g=["columnNumber","lineNumber"],b=["fileName","functionName","source"],w=["args"],S=y.concat(g,b,w);function C(W){if(W instanceof Object)for(var Me=0;Me<S.length;Me++)W.hasOwnProperty(S[Me])&&W[S[Me]]!==void 0&&this["set"+d(S[Me])](W[S[Me]])}C.prototype={getArgs:function(){return this.args},setArgs:function(W){if(Object.prototype.toString.call(W)!=="[object Array]")throw new TypeError("Args must be an Array");this.args=W},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(W){if(W instanceof C)this.evalOrigin=W;else if(W instanceof Object)this.evalOrigin=new C(W);else throw new TypeError("Eval Origin must be an Object or StackFrame")},toString:function(){var W=this.getFunctionName()||"{anonymous}",Me="("+(this.getArgs()||[]).join(",")+")",Je=this.getFileName()?"@"+this.getFileName():"",Be=f(this.getLineNumber())?":"+this.getLineNumber():"",Ge=f(this.getColumnNumber())?":"+this.getColumnNumber():"";return W+Me+Je+Be+Ge}};for(var U=0;U<y.length;U++)C.prototype["get"+d(y[U])]=h(y[U]),C.prototype["set"+d(y[U])]=function(W){return function(Me){this[W]=!!Me}}(y[U]);for(var F=0;F<g.length;F++)C.prototype["get"+d(g[F])]=h(g[F]),C.prototype["set"+d(g[F])]=function(W){return function(Me){if(!f(Me))throw new TypeError(W+" must be a Number");this[W]=Number(Me)}}(g[F]);for(var H=0;H<b.length;H++)C.prototype["get"+d(b[H])]=h(b[H]),C.prototype["set"+d(b[H])]=function(W){return function(Me){this[W]=String(Me)}}(b[H]);return C});var He={};(function(f,d){typeof He=="object"?He=d(Oe):f.ErrorStackParser=d(f.StackFrame)})(this,function(d){var h=/(^|@)\S+\:\d+/,y=/^\s*at .*(\S+\:\d+|\(native\))/m,g=/^(eval@)?(\[native code\])?$/;return{parse:function(w){if(typeof w.stacktrace<"u"||typeof w["opera#sourceloc"]<"u")return this.parseOpera(w);if(w.stack&&w.stack.match(y))return this.parseV8OrIE(w);if(w.stack)return this.parseFFOrSafari(w);throw new Error("Cannot parse given Error object")},extractLocation:function(w){if(w.indexOf(":")===-1)return[w];var S=/(.+?)(?:\:(\d+))?(?:\:(\d+))?$/,C=S.exec(w.replace(/[\(\)]/g,""));return[C[1],C[2]||void 0,C[3]||void 0]},parseV8OrIE:function(w){var S=w.stack.split(`
464
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var y=!0,g=!1,b;return{s:function(){f=f.call(O)},n:function(){var S=f.next();return y=S.done,S},e:function(S){g=!0,b=S},f:function(){try{!y&&f.return!=null&&f.return()}finally{if(g)throw b}}}}function Kt(O,A){if(O){if(typeof O=="string")return bt(O,A);var f=Object.prototype.toString.call(O).slice(8,-1);if(f==="Object"&&O.constructor&&(f=O.constructor.name),f==="Map"||f==="Set")return Array.from(O);if(f==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(f))return bt(O,A)}}function bt(O,A){(A==null||A>O.length)&&(A=O.length);for(var f=0,d=new Array(A);f<A;f++)d[f]=O[f];return d}var Jt=me.default(function O(A){he.default(this,O),Pe.default(this,"type","email"),this.messageSid=A.message_sid,this.level=A.level,this.name=A.name,this.address=A.address}),ur=me.default(function O(A){he.default(this,O),this.type=A.type,this.messageSid=A.message_sid,this.rawData=JSON.stringify(A)}),_r=function(){function O(A,f){he.default(this,O),this._services=A,this._configuration=f,this._cache=new z({maxSize:f.messageRecipientsCacheCapacity})}return me.default(O,[{key:"getRecipientsFromMessage",value:function(){var A=Z.default(P.default.mark(function d(h,y){var g=this,b,w,S,C,U;return P.default.wrap(function(H){for(;;)switch(H.prev=H.next){case 0:if(b="".concat(h,",").concat(y),w=this._cache.get(b),!w){H.next=4;break}return H.abrupt("return",w.item);case 4:return S=new At(this._configuration.links.conversations).path(h).path("MessageRecipients").arg("MessageSid",y).build(),H.next=7,this._services.commandExecutor.fetchResource(S);case 7:return C=H.sent,U=C.message_recipients.map(function(W){return g._wrapResponse(W)}),U.length>0&&this._cache.set(b,{item:U}),H.abrupt("return",U);case 11:case"end":return H.stop()}},d,this)}));function f(d,h){return A.apply(this,arguments)}return f}()},{key:"getRecipientsFromConversation",value:function(){var A=Z.default(P.default.mark(function d(h,y){var g,b,w=this,S,C,U,F,H,W,Me,Je,Be,Ge;return P.default.wrap(function(St){for(;;)switch(St.prev=St.next){case 0:return S=new At(this._configuration.links.conversations).path(h).path("MessageRecipients").arg("PageToken",(g=y==null?void 0:y.pageToken)!==null&&g!==void 0?g:void 0).arg("PageSize",(b=y==null?void 0:y.pageSize)!==null&&b!==void 0?b:void 0).build(),St.next=3,this._services.commandExecutor.fetchResource(S);case 3:C=St.sent,U=C.message_recipients.map(function(ft){return w._wrapResponse(ft)}),F=Xe(U);try{for(F.s();!(H=F.n()).done;)Je=H.value,Be="".concat(h,",").concat(Je.messageSid),Ge=(W=(Me=this._cache.get(Be))===null||Me===void 0?void 0:Me.item)!==null&&W!==void 0?W:[],this._cache.set(Be,{item:[].concat(Fe.default(Ge),[Je])})}catch(ft){F.e(ft)}finally{F.f()}return St.abrupt("return",new We(U,function(ft,hr){return w.getRecipientsFromConversation(h,{pageToken:ft,pageSize:hr})},C.meta.previous_token,C.meta.next_token));case 8:case"end":return St.stop()}},d,this)}));function f(d,h){return A.apply(this,arguments)}return f}()},{key:"_wrapResponse",value:function(f){switch(f.type){case"email":return new Jt(f);default:return new ur(f)}}}]),O}(),ut;function jr(O,A){var f=Object.keys(O);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(O);A&&(d=d.filter(function(h){return Object.getOwnPropertyDescriptor(O,h).enumerable})),f.push.apply(f,d)}return f}function Fr(O){for(var A=1;A<arguments.length;A++){var f=arguments[A]!=null?arguments[A]:{};A%2?jr(Object(f),!0).forEach(function(d){Pe.default(O,d,f[d])}):Object.getOwnPropertyDescriptors?Object.defineProperties(O,Object.getOwnPropertyDescriptors(f)):jr(Object(f)).forEach(function(d){Object.defineProperty(O,d,Object.getOwnPropertyDescriptor(f,d))})}return O}function pr(O){var A=Ur();return function(){var d=vt.default(O),h;if(A){var y=vt.default(this).constructor;h=Reflect.construct(d,arguments,y)}else h=d.apply(this,arguments);return Nt.default(this,h)}}function Ur(){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 mt,In=me.default(function O(){he.default(this,O)});e.Client=mt=(ut=function(O){Qe.default(f,O);var A=pr(f);function f(d){var h,y,g,b,w,S,C=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(he.default(this,f),S=A.call(this),Pe.default(qe.default(S),"version",E),Pe.default(qe.default(S),"connectionState","unknown"),Pe.default(qe.default(S),"parsePushNotification",mt.parsePushNotification),S._fpaToken=d??"",S._options=C??{},!S._options.disableDeepClone){var U=Fr(Fr({},S._options),{},{transport:void 0,twilsockClient:void 0});U=Rt(U),U.transport=S._options.transport,U.twilsockClient=S._options.twilsockClient,S._options=U}S._options.logLevel=(h=S._options.logLevel)!==null&&h!==void 0?h:"silent",mt._logger.setLevel(S._options.logLevel);var F=S._options.productId="ip_messaging";if(S._options.clientMetadata=S._options.clientMetadata||{},S._options.clientMetadata.hasOwnProperty("type")||(S._options.clientMetadata.type="conversations"),S._options.clientMetadata.hasOwnProperty("sdk")||(S._options.clientMetadata.sdk="JS",S._options.clientMetadata.sdkv=E),S._options.Sync=S._options.Sync||{},typeof S._options.Sync.enableSessionStorage>"u"&&(S._options.Sync.enableSessionStorage=!0),S._options.region&&(S._options.Sync.region=S._options.region),!d)throw new Error("A valid Twilio token should be provided");S._services=new In,S._myself=new ve("","",null,S._services);var H=!S._options.twilsockClient;if(!S._options.initRegistrations){var W=new j.InitRegistration(F);mt.populateInitRegistrations(W),S._options.initRegistrations=[W]}S._services.twilsockClient=S._options.twilsockClient=(y=S._options.twilsockClient)!==null&&y!==void 0?y:new j.TwilsockClient(d,F,S._options),S._services.twilsockClient.on(mt.tokenAboutToExpire,function(){return S.emit(mt.tokenAboutToExpire)}),S._services.twilsockClient.on(mt.tokenExpired,function(){return S.emit(mt.tokenExpired)}),S._services.twilsockClient.on(mt.connectionError,function(St){return S.emit(mt.connectionError,St)}),S._services.twilsockClient.on("stateChanged",function(St){mt._logger.debug("Handling stateChanged for ConversationsClient: new state ".concat(St)),St!==S.connectionState&&(S.connectionState=St,S.emit(mt.connectionStateChanged,S.connectionState))}),S._services.transport=S._options.transport=(g=S._options.transport)!==null&&g!==void 0?g:S._options.twilsockClient,S._services.notificationClient=S._options.notificationsClient=(b=S._options.notificationsClient)!==null&&b!==void 0?b:new X.Notifications(d,S._options),S._services.syncClient=S._options.syncClient=(w=S._options.syncClient)!==null&&w!==void 0?w:new J.SyncClient(d,S._options);var Me=(C==null?void 0:C.Chat)||(C==null?void 0:C.IPMessaging)||C||{},Je=Me.region||(C==null?void 0:C.region),Be=Me.apiUri||Me.typingUri||"https://aim.".concat(Je||"us1",".twilio.com");S._services.commandExecutor=new $r(Be,{transport:S._options.transport},F),S._services.contentClient=new ln(S._services);var Ge=function(ft){S._rejectEnsureReady(ft),S.emit(mt.stateChanged,"failed"),S.emit(mt.initFailed,{error:ft})},xt=function(){Ge({terminal:!0,message:"Twilsock has disconnected."}),S._initializeEnsureReady((C==null?void 0:C.throwErrorsAlways)||!1)};return S._services.twilsockClient.once("connectionError",Ge),S._services.twilsockClient.once("disconnected",xt),S._services.twilsockClient.once("connected",Z.default(P.default.mark(function St(){var ft,hr;return P.default.wrap(function(st){for(;;)switch(st.prev=st.next){case 0:return mt._logger.debug("ConversationsClient started INITIALIZING"),S._services.twilsockClient.off("connectionError",Ge),S._services.twilsockClient.off("disconnected",xt),st.prev=3,ft="conversations.client.startup",S._services.twilsockClient.addPartialTelemetryEvent(new j.TelemetryEventDescription(ft,"Conversations client startup",new Date),ft,j.TelemetryPoint.Start),st.next=8,S._initialize();case 8:S._services.twilsockClient.addPartialTelemetryEvent(new j.TelemetryEventDescription("","",new Date),ft,j.TelemetryPoint.End),st.next=17;break;case 11:st.prev=11,st.t0=st.catch(3),hr={terminal:!0,message:st.t0.message},S._rejectEnsureReady(hr),S.emit(mt.stateChanged,"failed"),S.emit(mt.initFailed,{error:hr});case 17:case"end":return st.stop()}},St,null,[[3,11]])}))),S._initializeEnsureReady((C==null?void 0:C.throwErrorsAlways)||!1),H&&S._services.twilsockClient.connect(),S}return me.default(f,[{key:"user",get:function(){return this._myself}},{key:"reachabilityEnabled",get:function(){if(!this._configuration)throw new Error("Reachability information could not yet be accessed as the client has not yet been initialized. Subscribe to the 'stateChanged' event to properly react to the client initialization.");return this._configuration.reachabilityEnabled}},{key:"token",get:function(){return this._fpaToken}},{key:"shutdown",value:function(){var d=Z.default(P.default.mark(function y(){return P.default.wrap(function(b){for(;;)switch(b.prev=b.next){case 0:return b.next=2,this._ensureReady;case 2:return b.next=4,this._services.twilsockClient.disconnect();case 4:case"end":return b.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"updateToken",value:function(){var d=Z.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._ensureReady;case 2:if(mt._logger.info("updateToken"),this._fpaToken!==g){w.next=5;break}return w.abrupt("return",this);case 5:return w.next=7,this._services.twilsockClient.updateToken(g);case 7:return w.next=9,this._services.notificationClient.updateToken(g);case 9:return w.next=11,this._services.mcsClient.updateToken(g);case 11:return this._fpaToken=g,w.abrupt("return",this);case 13:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getConversationBySid",value:function(){var d=Z.default(P.default.mark(function y(g){var b;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._ensureReady;case 2:return S.next=4,this._conversationsEntity.myConversationsRead.promise;case 4:return S.next=6,this._conversationsEntity.getConversation(g);case 6:if(b=S.sent,b){S.next=12;break}return S.next=10,this.peekConversationBySid(g);case 10:b=S.sent,b&&L.deprecationWarning("The method getConversationBySid is deprecated to retrieve conversations you're not part of. Use peekConversationBySid instead.");case 12:if(b){S.next=14;break}throw new Error("Conversation with SID ".concat(g," was not found."));case 14:return S.abrupt("return",b);case 15:case"end":return S.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"peekConversationBySid",value:function(){var d=Z.default(P.default.mark(function y(g){var b;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._ensureReady;case 2:return S.next=4,this._conversationsEntity.peekConversation(g);case 4:if(b=S.sent,b){S.next=7;break}throw new Error("Conversation with SID ".concat(g," was not found."));case 7:return S.abrupt("return",b);case 8:case"end":return S.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getConversationByUniqueName",value:function(){var d=Z.default(P.default.mark(function y(g){var b;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._ensureReady;case 2:return S.next=4,this._conversationsEntity.myConversationsRead.promise;case 4:return S.next=6,this._conversationsEntity.getConversationByUniqueName(g);case 6:if(b=S.sent,b){S.next=9;break}throw new Error("Conversation with unique name ".concat(g," was not found."));case 9:return S.abrupt("return",b);case 10:case"end":return S.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getSubscribedConversations",value:function(){var d=Z.default(P.default.mark(function y(){return P.default.wrap(function(b){for(;;)switch(b.prev=b.next){case 0:return b.next=2,this._ensureReady;case 2:return b.abrupt("return",this._conversationsPromise.then(function(w){return w.getConversations()}));case 3:case"end":return b.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"createConversation",value:function(){var d=Z.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._ensureReady;case 2:return g=g||{},w.abrupt("return",this._conversationsPromise.then(function(S){return S.addConversation(g)}));case 4:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"setPushRegistrationId",value:function(){var d=Z.default(P.default.mark(function y(g,b){return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._ensureReady;case 2:return this._subscribeToPushNotifications(g),this._services.notificationClient.setPushRegistrationId(g,b),S.next=6,this._services.notificationClient.commitChanges();case 6:case"end":return S.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"unsetPushRegistrationId",value:function(){var d=Z.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._ensureReady;case 2:return this._unsubscribeFromPushNotifications(g),w.next=5,this._services.notificationClient.commitChanges();case 5:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"removePushRegistrations",value:function(){var d=Z.default(P.default.mark(function y(g,b){return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._services.notificationClient.removeRegistrations(g,b);case 2:case"end":return S.stop()}},y,this)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"handlePushNotification",value:function(){var d=Z.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._ensureReady;case 2:mt._logger.debug("handlePushNotification, notificationPayload=",g),this.emit("pushNotification",mt.parsePushNotification(g));case 4:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getUser",value:function(){var d=Z.default(P.default.mark(function y(g){return P.default.wrap(function(w){for(;;)switch(w.prev=w.next){case 0:return w.next=2,this._ensureReady;case 2:return w.abrupt("return",this._services.users.getUser(g));case 3:case"end":return w.stop()}},y,this)}));function h(y){return d.apply(this,arguments)}return h}()},{key:"getSubscribedUsers",value:function(){var d=Z.default(P.default.mark(function y(){return P.default.wrap(function(b){for(;;)switch(b.prev=b.next){case 0:return b.next=2,this._ensureReady;case 2:return b.abrupt("return",this._services.users.getSubscribedUsers());case 3:case"end":return b.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"getTemporaryContentUrlsForMediaSids",value:function(h){var y=this;return new G.CancellablePromise(function(){var g=Z.default(P.default.mark(function b(w,S,C){var U,F;return P.default.wrap(function(W){for(;;)switch(W.prev=W.next){case 0:if(!(!y._services.mcsClient||!h)){W.next=3;break}return S(new Error("Media Content Service is unavailable")),W.abrupt("return");case 3:return U=y._services.mcsClient.mediaSetGetContentUrls(h),C(function(){U.cancel()}),W.prev=5,W.next=8,U;case 8:F=W.sent,w(F),W.next=15;break;case 12:W.prev=12,W.t0=W.catch(5),S(W.t0);case 15:case"end":return W.stop()}},b,null,[[5,12]])}));return function(b,w,S){return g.apply(this,arguments)}}())}},{key:"getTemporaryContentUrlsForMedia",value:function(h){var y=h.map(function(g){return g.sid});return this.getTemporaryContentUrlsForMediaSids(y)}},{key:"getContentTemplates",value:function(){var d=Z.default(P.default.mark(function y(){return P.default.wrap(function(b){for(;;)switch(b.prev=b.next){case 0:return b.next=2,this._ensureReady;case 2:return b.next=4,this._services.contentClient.getContentTemplates();case 4:return b.abrupt("return",b.sent);case 5:case"end":return b.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_initialize",value:function(){var d=Z.default(P.default.mark(function y(){var g=this,b;return P.default.wrap(function(S){for(;;)switch(S.prev=S.next){case 0:return S.next=2,this._services.commandExecutor.fetchResource("Client/v2/Configuration");case 2:return b=S.sent,this._configuration=new Ct(this._options,b,mt._logger),this._services.channelMetadataClient=new Se(this._services,this._configuration),this._services.messageRecipientsClient=new _r(this._services,this._configuration),this._myself._resolveInitialization(this._configuration,this._configuration.userIdentity,this._configuration.userInfo,!0),this._services.typingIndicator=new R(this.getConversationBySid.bind(this),this._configuration,this._services),this._services.network=new ce(this._configuration,this._services),this._services.users=new D(this._myself,this._configuration,this._services),this._services.users.on("userSubscribed",function(C){g.emit("userSubscribed",C)}),this._services.users.on("userUpdated",function(C){return g.emit("userUpdated",C)}),this._services.users.on("userUnsubscribed",function(C){g.emit("userUnsubscribed",C)}),this._conversationsEntity=new Gr(this._configuration,this._services),this._conversationsEntity.on("conversationAdded",function(C){g.emit("conversationAdded",C)}),this._conversationsEntity.on("conversationRemoved",function(C){g.emit("conversationRemoved",C)}),this._conversationsEntity.on("conversationJoined",function(C){g.emit("conversationJoined",C)}),this._conversationsEntity.on("conversationLeft",function(C){g.emit("conversationLeft",C)}),this._conversationsEntity.on("conversationUpdated",function(C){return g.emit("conversationUpdated",C)}),this._conversationsEntity.on("participantJoined",function(C){g.emit("participantJoined",C)}),this._conversationsEntity.on("participantLeft",function(C){g.emit("participantLeft",C)}),this._conversationsEntity.on("participantUpdated",function(C){return g.emit("participantUpdated",C)}),this._conversationsEntity.on("messageAdded",function(C){return g.emit("messageAdded",C)}),this._conversationsEntity.on("messageUpdated",function(C){return g.emit("messageUpdated",C)}),this._conversationsEntity.on("messageRemoved",function(C){return g.emit("messageRemoved",C)}),this._conversationsEntity.on("typingStarted",function(C){return g.emit("typingStarted",C)}),this._conversationsEntity.on("typingEnded",function(C){return g.emit("typingEnded",C)}),this._conversationsPromise=this._conversationsEntity.fetchConversations().then(function(){return g._conversationsEntity}).catch(function(C){throw C}),S.next=30,this._services.users.myself._ensureFetched();case 30:mt._supportedPushChannels.forEach(function(C){return g._subscribeToPushNotifications(C)}),this._services.typingIndicator.initialize(),this._services.mcsClient=new G.McsClient(this._fpaToken,this._configuration.links.mediaService,this._configuration.links.mediaSetService,Fr(Fr({},this._options),{},{transport:void 0})),this._resolveEnsureReady(),this.emit(mt.stateChanged,"initialized"),this.emit(mt.initialized);case 36:case"end":return S.stop()}},y,this)}));function h(){return d.apply(this,arguments)}return h}()},{key:"_subscribeToPushNotifications",value:function(h){var y=this;[ge.NEW_MESSAGE,ge.ADDED_TO_CONVERSATION,ge.REMOVED_FROM_CONVERSATION,ge.TYPING_INDICATOR,ge.CONSUMPTION_UPDATE].forEach(function(g){y._services.notificationClient.subscribe(h,g)})}},{key:"_unsubscribeFromPushNotifications",value:function(h){var y=this;[ge.NEW_MESSAGE,ge.ADDED_TO_CONVERSATION,ge.REMOVED_FROM_CONVERSATION,ge.TYPING_INDICATOR,ge.CONSUMPTION_UPDATE].forEach(function(g){y._services.notificationClient.unsubscribe(h,g)})}},{key:"_initializeEnsureReady",value:function(h){var y=this;this._ensureReady=new Promise(function(g,b){y._resolveEnsureReady=g,y._rejectEnsureReady=b}).catch(function(g){if(h)throw g})}}],[{key:"create",value:function(){var d=Z.default(P.default.mark(function y(g,b){var w;return P.default.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:if(!(b!=null&&b.twilsockClient)){C.next=2;break}throw new Error("Obsolete usage of ConversationsClient.create() factory method: if you pass twilsock from the outside then you must use ConversationsClient constructor and be prepared to work with uninitialized client.");case 2:return w=new mt(g,b),C.next=5,w._ensureReady;case 5:return C.abrupt("return",w);case 6:case"end":return C.stop()}},y)}));function h(y,g){return d.apply(this,arguments)}return h}()},{key:"parsePushNotification",value:function(h){if(mt._logger.debug("parsePushNotification, notificationPayload=",h),typeof h.aps<"u"){if(!h.twi_message_type)throw new Error("Provided push notification payload does not contain Programmable Chat push notification type");var y=mt._parsePushNotificationChatData(h),g=h.aps,b,w=null;if(typeof g.alert=="string")b=g.alert||null;else{var S,C;b=((S=g.alert)===null||S===void 0?void 0:S.body)||null,w=((C=g.alert)===null||C===void 0?void 0:C.title)||null}return new k({title:w,body:b,sound:g.sound||null,badge:g.badge||null,action:g.category||null,type:h.twi_message_type,data:y})}if(typeof h.data<"u"){var U=h.data;if(!U.twi_message_type)throw new Error("Provided push notification payload does not contain Programmable Chat push notification type");var F=mt._parsePushNotificationChatData(h.data);return new k({title:U.twi_title||null,body:U.twi_body||null,sound:U.twi_sound||null,badge:null,action:U.twi_action||null,type:U.twi_message_type,data:F})}throw new Error("Provided push notification payload is not Programmable Chat notification")}},{key:"_parsePushNotificationChatData",value:function(h){var y={};for(var g in mt._supportedPushDataFields){var b=h[g];if(!(typeof b>"u"||b===null)){if(g==="message_index"||g==="media_count"){var w=yt(b);w!==null&&(y[mt._supportedPushDataFields[g]]=w);continue}if(g==="media"){if(typeof b=="string")try{y[mt._supportedPushDataFields[g]]=JSON.parse(b)}catch{mt._logger.debug("Media message notification parsing error")}continue}y[mt._supportedPushDataFields[g]]=b}}return y}},{key:"populateInitRegistrations",value:function(h){h.populateInitRegistrations([ge.TYPING_INDICATOR]),J.SyncClient.populateInitRegistrations(h)}}]),f}(I.ReplayEventEmitter),Pe.default(ut,"conversationAdded","conversationAdded"),Pe.default(ut,"conversationJoined","conversationJoined"),Pe.default(ut,"conversationLeft","conversationLeft"),Pe.default(ut,"conversationRemoved","conversationRemoved"),Pe.default(ut,"conversationUpdated","conversationUpdated"),Pe.default(ut,"participantJoined","participantJoined"),Pe.default(ut,"participantLeft","participantLeft"),Pe.default(ut,"participantUpdated","participantUpdated"),Pe.default(ut,"messageAdded","messageAdded"),Pe.default(ut,"messageRemoved","messageRemoved"),Pe.default(ut,"messageUpdated","messageUpdated"),Pe.default(ut,"tokenAboutToExpire","tokenAboutToExpire"),Pe.default(ut,"tokenExpired","tokenExpired"),Pe.default(ut,"typingEnded","typingEnded"),Pe.default(ut,"typingStarted","typingStarted"),Pe.default(ut,"pushNotification","pushNotification"),Pe.default(ut,"userSubscribed","userSubscribed"),Pe.default(ut,"userUnsubscribed","userUnsubscribed"),Pe.default(ut,"userUpdated","userUpdated"),Pe.default(ut,"stateChanged","stateChanged"),Pe.default(ut,"initialized","initialized"),Pe.default(ut,"initFailed","initFailed"),Pe.default(ut,"connectionStateChanged","connectionStateChanged"),Pe.default(ut,"connectionError","connectionError"),Pe.default(ut,"version",E),Pe.default(ut,"_logger",Dt.scope("Client")),Pe.default(ut,"_supportedPushChannels",["fcm","apn"]),Pe.default(ut,"_supportedPushDataFields",{conversation_sid:"conversationSid",conversation_title:"conversationTitle",message_sid:"messageSid",message_index:"messageIndex",media_count:"mediaCount",media:"media"}),ut),we([L.deprecated("token"),fe("design:type",String),fe("design:paramtypes",[])],e.Client.prototype,"token",null),we([_.validateTypesAsync(_.nonEmptyString),fe("design:type",Function),fe("design:paramtypes",[String]),fe("design:returntype",Promise)],e.Client.prototype,"updateToken",null),we([_.validateTypesAsync(_.nonEmptyString),fe("design:type",Function),fe("design:paramtypes",[String]),fe("design:returntype",Promise)],e.Client.prototype,"getConversationBySid",null),we([_.validateTypesAsync(_.nonEmptyString),fe("design:type",Function),fe("design:paramtypes",[String]),fe("design:returntype",Promise)],e.Client.prototype,"peekConversationBySid",null),we([_.validateTypesAsync(_.nonEmptyString),fe("design:type",Function),fe("design:paramtypes",[String]),fe("design:returntype",Promise)],e.Client.prototype,"getConversationByUniqueName",null),we([_.validateTypesAsync(["undefined",_.objectSchema("conversation options",{friendlyName:["string","undefined"],isPrivate:["boolean","undefined"],uniqueName:["string","undefined"]})]),fe("design:type",Function),fe("design:paramtypes",[Object]),fe("design:returntype",Promise)],e.Client.prototype,"createConversation",null),we([_.validateTypesAsync(_.literal("fcm","apn"),"string"),fe("design:type",Function),fe("design:paramtypes",[String,String]),fe("design:returntype",Promise)],e.Client.prototype,"setPushRegistrationId",null),we([_.validateTypesAsync(_.literal("fcm","apn")),fe("design:type",Function),fe("design:paramtypes",[String]),fe("design:returntype",Promise)],e.Client.prototype,"unsetPushRegistrationId",null),we([_.validateTypesAsync(_.literal("fcm","apn"),_.nonEmptyString),fe("design:type",Function),fe("design:paramtypes",[String,String]),fe("design:returntype",Promise)],e.Client.prototype,"removePushRegistrations",null),we([_.validateTypesAsync(_.pureObject),fe("design:type",Function),fe("design:paramtypes",[Object]),fe("design:returntype",Promise)],e.Client.prototype,"handlePushNotification",null),we([_.validateTypesAsync(_.nonEmptyString),fe("design:type",Function),fe("design:paramtypes",[String]),fe("design:returntype",Promise)],e.Client.prototype,"getUser",null),we([_.validateTypesAsync(_.nonEmptyArray("strings","string")),fe("design:type",Function),fe("design:paramtypes",[Array]),fe("design:returntype",G.CancellablePromise)],e.Client.prototype,"getTemporaryContentUrlsForMediaSids",null),we([_.validateTypesAsync(_.nonEmptyArray("media",Ve)),fe("design:type",Function),fe("design:paramtypes",[Array]),fe("design:returntype",G.CancellablePromise)],e.Client.prototype,"getTemporaryContentUrlsForMedia",null),we([L.deprecated("Client.create()","new Client()"),_.validateTypesAsync("string",["undefined",_.pureObject]),fe("design:type",Function),fe("design:paramtypes",[String,Object]),fe("design:returntype",Promise)],e.Client,"create",null),we([_.validateTypes(_.pureObject),fe("design:type",Function),fe("design:paramtypes",[Object]),fe("design:returntype",k)],e.Client,"parsePushNotification",null),e.Client=mt=we([_.validateConstructorTypes(_.nonEmptyString,[_.pureObject,"undefined"]),fe("design:paramtypes",[String,Object])],e.Client),Object.defineProperty(e,"CancellablePromise",{enumerable:!0,get:function(){return G.CancellablePromise}}),e.AggregatedDeliveryReceipt=ze,e.ChannelMetadata=ie,e.ContentTemplate=it,e.ContentTemplateVariable=nt,e.Conversation=It,e.DetailedDeliveryReceipt=Ze,e.EmailRecipientDescriptor=Jt,e.Media=Ve,e.Message=$t,e.MessageBuilder=or,e.NotificationTypes=ge,e.Participant=V,e.PushNotification=k,e.RestPaginator=We,e.UnknownRecipientDescriptor=ur,e.UnsentMessage=ci,e.User=ve})(vT);const xn=new $a("twilio-chat");class t$ extends qv{constructor(){super(...arguments);pt(this,"client");pt(this,"conversation")}async create(){const{token:t,identity:n}=await this.issueChatToken();this.identity=n,xn.info(`Connecting chat, identity: ${n}, token: ${t}`);const i=new vT.Client(t);i.on("initialized",()=>{xn.info("client: initialized"),this.events.triggerEvent("initialized")}),i.on("tokenAboutToExpire",()=>{xn.info("client: tokenAboutToExpire"),this.refreshToken()}),i.on("tokenExpired",()=>{xn.info("client: tokenExpired"),this.refreshToken()}),this.client=i}async refreshToken(){const{token:t}=await this.issueChatToken();await this.client.updateToken(t)}async join(t){const n=await this.client.getConversationBySid(t);n.status==="joined"?xn.info("already joined conversation:",t):(await n.join(),xn.info("success joined conversation:",t)),this.conversation=n}async preview(t){await(await this.conversation.getParticipantByIdentity(this.identity)).updateAttributes({chat_preview:t,chat_preview_updated_at:new Date().toJSON()})}async destroy(){this.client&&(await this.client.shutdown(),this.client=null,this.conversation=null)}async fetchMessages(t){return(await this.conversation.getMessages()).items.map(i=>{const a=c0(i);return t[a.$index]&&(a.file=t[a.$index]),this.trackInTask(a),a})}async sendMessage(t){try{const n=await this.conversation.sendMessage(JSON.stringify(t));return xn.info(`Message sent from ${this.conversation.sid}, index: ${n}`),n}catch(n){xn.warn(`Failed to send a message from ${this.conversation.sid}`,{error:n})}}startTyping(){this.conversation&&this.conversation.typing()}stopTyping(){}registerConversationEvents(){this.registerEvents(this.conversation)}registerEvents(t){t.on("messageAdded",n=>{const i=c0(n);xn.info(`Message added from ${this.conversation.sid}, index: ${i.$index}, sid: ${i.$sid}, timestamp: ${i.$timestamp}, user type: ${i.$userType}`),i.$userType!=="end_user"&&this.ping(),this.trackInTask(i),this.events.triggerEvent("message",i)}),t.on("participantJoined",n=>{xn.info("conversation: memberJoined",n),this.events.triggerEvent("memberJoined",n.identity)}),t.on("participantLeft",n=>{xn.info("conversation: memberLeft",n),this.events.triggerEvent("memberLeft",n.identity)}),t.on("typingStarted",n=>{this.events.triggerEvent("typingStarted",n.identity)}),t.on("typingEnded",n=>{this.events.triggerEvent("typingEnded",n.identity)})}}pt(t$,"type","twilio_conversations");zv(t$);function c0(e){const{index:r,sid:t,author:n,dateCreated:i,body:a}=e,[s,o]=n.split("-");let u=0;o&&(u=parseInt(o,10));const c={$index:r,$sid:t,$timestamp:i,$userType:s,$userId:u};try{const l=JSON.parse(a);return l.message&&!l.type?{...c,...l,type:"message"}:{...c,...l}}catch(l){return xn.warn("Format message failed",{error:l,data:a}),{...c,type:"text",content:a}}}var lv={exports:{}},Da=Gl;function Gl(){}Gl.mixin=function(e){var r=e.prototype||e;r.isWildEmitter=!0,r.on=function(t,n,i){this.callbacks=this.callbacks||{};var a=arguments.length===3,s=a?arguments[1]:void 0,o=a?arguments[2]:arguments[1];return o._groupName=s,(this.callbacks[t]=this.callbacks[t]||[]).push(o),this},r.once=function(t,n,i){var a=this,s=arguments.length===3,o=s?arguments[1]:void 0,u=s?arguments[2]:arguments[1];function c(){a.off(t,c),u.apply(this,arguments)}return this.on(t,o,c),this},r.releaseGroup=function(t){this.callbacks=this.callbacks||{};var n,i,a,s;for(n in this.callbacks)for(s=this.callbacks[n],i=0,a=s.length;i<a;i++)s[i]._groupName===t&&(s.splice(i,1),i--,a--);return this},r.off=function(t,n){this.callbacks=this.callbacks||{};var i=this.callbacks[t],a;return i?arguments.length===1?(delete this.callbacks[t],this):(a=i.indexOf(n),a!==-1&&(i.splice(a,1),i.length===0&&delete this.callbacks[t]),this):this},r.emit=function(t){this.callbacks=this.callbacks||{};var n=[].slice.call(arguments,1),i=this.callbacks[t],a=this.getWildcardCallbacks(t),s,o,u;if(i)for(u=i.slice(),s=0,o=u.length;s<o&&u[s];++s)u[s].apply(this,n);if(a)for(o=a.length,u=a.slice(),s=0,o=u.length;s<o&&u[s];++s)u[s].apply(this,[t].concat(n));return this},r.getWildcardCallbacks=function(t){this.callbacks=this.callbacks||{};var n,i,a=[];for(n in this.callbacks)i=n.split("*"),(n==="*"||i.length===2&&t.slice(0,i[0].length)===i[0])&&(a=a.concat(this.callbacks[n]));return a}};Gl.mixin(Gl);var r$={exports:{}};(function(e){(function(r,t){e.exports?e.exports=t():r.prefix=t(r)})(Ne,function(r){var t=function(l){for(var p=1,v=arguments.length,m;p<v;p++)for(m in arguments[p])Object.prototype.hasOwnProperty.call(arguments[p],m)&&(l[m]=arguments[p][m]);return l},n={template:"[%t] %l:",levelFormatter:function(l){return l.toUpperCase()},nameFormatter:function(l){return l||"root"},timestampFormatter:function(l){return l.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")},format:void 0},i,a={},s=function(l){if(!l||!l.getLogger)throw new TypeError("Argument is not a root logger");i=l},o=function(l,p){if(!l||!l.setLevel)throw new TypeError("Argument is not a logger");var v=l.methodFactory,m=l.name||"",_=a[m]||a[""]||n;function T(I,$,x){var N=v(I,$,x),j=a[x]||a[""],X=j.template.indexOf("%t")!==-1,J=j.template.indexOf("%l")!==-1,G=j.template.indexOf("%n")!==-1;return function(){for(var L="",re=arguments.length,ue=Array(re),ee=0;ee<re;ee++)ue[ee]=arguments[ee];if(m||!a[x]){var ye=j.timestampFormatter(new Date),Z=j.levelFormatter(I),qe=j.nameFormatter(x);j.format?L+=j.format(Z,qe,ye):(L+=j.template,X&&(L=L.replace(/%t/,ye)),J&&(L=L.replace(/%l/,Z)),G&&(L=L.replace(/%n/,qe))),ue.length&&typeof ue[0]=="string"?ue[0]=L+" "+ue[0]:ue.unshift(L)}N.apply(void 0,ue)}}return a[m]||(l.methodFactory=T),p=p||{},p.template&&(p.format=void 0),a[m]=t({},_,p),l.setLevel(l.getLevel()),i||l.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"),l},u={reg:s,apply:o},c;return r&&(c=r.prefix,u.noConflict=function(){return r.prefix===u&&(r.prefix=c),u}),u})})(r$);var EX=r$.exports,fv={exports:{}},kX={"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"},"error:input:unsanitized":{type:"error:input:unsanitized",description:"Input is not sanitized"}};(function(e,r){Object.defineProperty(r,"__esModule",{value:!0}),r.NexmoApiError=r.NexmoClientError=void 0;const t=kX,n=Ar;function i(o,u){var c,l;u!=null&&u.code&&(u.type=u.code,delete u.code),Object.assign(o,u),o.message="type: "+o.type+", description: "+((l=(c=o.description)!==null&&c!==void 0?c:o.detail)!==null&&l!==void 0?l:"")}class a{constructor(u){const c=t[u];c?i(this,c):(this.message=u&&u.message?u.message:u,this.stack=u.stack),this.log=n.getLogger(this.constructor.name),this.log.error(this),this.name="NexmoClientError",typeof Ne.NXMbugsnagClient<"u"&&Ne.NXMbugsnagClient.notify(this,{severity:"info"})}}r.NexmoClientError=a;class s{constructor(u){this.log=n.getLogger(this.constructor.name),u?i(this,u):(this.message=u&&u.message?u.message:u,this.stack=u&&u.stack?u.stack:new Error().stack),this.name="NexmoApiError",this.log=n.getLogger(this.constructor.name),this.log.error(this),typeof Ne.NXMbugsnagClient<"u"&&Ne.NXMbugsnagClient.notify(this,{severity:"info"})}}r.NexmoApiError=s,e.exports={NexmoClientError:a,NexmoApiError:s}})(fv,fv.exports);var Hn=fv.exports,dv={exports:{}},Pg={},Nf={},zi={},Gu={},yi={},Vu={},Ki={},_o={},Ku={},bi={};Object.defineProperty(bi,"__esModule",{value:!0});bi.ERROR_PACKET=bi.PACKET_TYPES_REVERSE=bi.PACKET_TYPES=void 0;const _i=Object.create(null);bi.PACKET_TYPES=_i;_i.open="0";_i.close="1";_i.ping="2";_i.pong="3";_i.message="4";_i.upgrade="5";_i.noop="6";const n$=Object.create(null);bi.PACKET_TYPES_REVERSE=n$;Object.keys(_i).forEach(e=>{n$[_i[e]]=e});const RX={type:"error",data:"parser error"};bi.ERROR_PACKET=RX;Object.defineProperty(Ku,"__esModule",{value:!0});Ku.encodePacket=void 0;Ku.encodePacketToBinary=IX;const $X=bi,i$=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",a$=typeof ArrayBuffer=="function",s$=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,o$=({type:e,data:r},t,n)=>i$&&r instanceof Blob?t?n(r):l0(r,n):a$&&(r instanceof ArrayBuffer||s$(r))?t?n(r):l0(new Blob([r]),n):n($X.PACKET_TYPES[e]+(r||""));Ku.encodePacket=o$;const l0=(e,r)=>{const t=new FileReader;return t.onload=function(){const n=t.result.split(",")[1];r("b"+(n||""))},t.readAsDataURL(e)};function f0(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Kp;function IX(e,r){if(i$&&e.data instanceof Blob)return e.data.arrayBuffer().then(f0).then(r);if(a$&&(e.data instanceof ArrayBuffer||s$(e.data)))return r(f0(e.data));o$(e,!1,t=>{Kp||(Kp=new TextEncoder),r(Kp.encode(t))})}var Lf={},oo={};Object.defineProperty(oo,"__esModule",{value:!0});oo.decode=oo.encode=void 0;const Us="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Xo=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<Us.length;e++)Xo[Us.charCodeAt(e)]=e;const OX=e=>{let r=new Uint8Array(e),t,n=r.length,i="";for(t=0;t<n;t+=3)i+=Us[r[t]>>2],i+=Us[(r[t]&3)<<4|r[t+1]>>4],i+=Us[(r[t+1]&15)<<2|r[t+2]>>6],i+=Us[r[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};oo.encode=OX;const AX=e=>{let r=e.length*.75,t=e.length,n,i=0,a,s,o,u;e[e.length-1]==="="&&(r--,e[e.length-2]==="="&&r--);const c=new ArrayBuffer(r),l=new Uint8Array(c);for(n=0;n<t;n+=4)a=Xo[e.charCodeAt(n)],s=Xo[e.charCodeAt(n+1)],o=Xo[e.charCodeAt(n+2)],u=Xo[e.charCodeAt(n+3)],l[i++]=a<<2|s>>4,l[i++]=(s&15)<<4|o>>2,l[i++]=(o&3)<<6|u&63;return c};oo.decode=AX;Object.defineProperty(Lf,"__esModule",{value:!0});Lf.decodePacket=void 0;const qc=bi,PX=oo,MX=typeof ArrayBuffer=="function",xX=(e,r)=>{if(typeof e!="string")return{type:"message",data:u$(e,r)};const t=e.charAt(0);return t==="b"?{type:"message",data:NX(e.substring(1),r)}:qc.PACKET_TYPES_REVERSE[t]?e.length>1?{type:qc.PACKET_TYPES_REVERSE[t],data:e.substring(1)}:{type:qc.PACKET_TYPES_REVERSE[t]}:qc.ERROR_PACKET};Lf.decodePacket=xX;const NX=(e,r)=>{if(MX){const t=(0,PX.decode)(e);return u$(t,r)}else return{base64:!0,data:e}},u$=(e,r)=>{switch(r){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.decodePayload=e.decodePacket=e.encodePayload=e.encodePacket=e.protocol=void 0,e.createPacketEncoderStream=o,e.createPacketDecoderStream=p;const r=Ku;Object.defineProperty(e,"encodePacket",{enumerable:!0,get:function(){return r.encodePacket}});const t=Lf;Object.defineProperty(e,"decodePacket",{enumerable:!0,get:function(){return t.decodePacket}});const n=bi,i="",a=(v,m)=>{const _=v.length,T=new Array(_);let I=0;v.forEach(($,x)=>{(0,r.encodePacket)($,!1,N=>{T[x]=N,++I===_&&m(T.join(i))})})};e.encodePayload=a;const s=(v,m)=>{const _=v.split(i),T=[];for(let I=0;I<_.length;I++){const $=(0,t.decodePacket)(_[I],m);if(T.push($),$.type==="error")break}return T};e.decodePayload=s;function o(){return new TransformStream({transform(v,m){(0,r.encodePacketToBinary)(v,_=>{const T=_.length;let I;if(T<126)I=new Uint8Array(1),new DataView(I.buffer).setUint8(0,T);else if(T<65536){I=new Uint8Array(3);const $=new DataView(I.buffer);$.setUint8(0,126),$.setUint16(1,T)}else{I=new Uint8Array(9);const $=new DataView(I.buffer);$.setUint8(0,127),$.setBigUint64(1,BigInt(T))}v.data&&typeof v.data!="string"&&(I[0]|=128),m.enqueue(I),m.enqueue(_)})}})}let u;function c(v){return v.reduce((m,_)=>m+_.length,0)}function l(v,m){if(v[0].length===m)return v.shift();const _=new Uint8Array(m);let T=0;for(let I=0;I<m;I++)_[I]=v[0][T++],T===v[0].length&&(v.shift(),T=0);return v.length&&T<v[0].length&&(v[0]=v[0].slice(T)),_}function p(v,m){u||(u=new TextDecoder);const _=[];let T=0,I=-1,$=!1;return new TransformStream({transform(x,N){for(_.push(x);;){if(T===0){if(c(_)<1)break;const j=l(_,1);$=(j[0]&128)===128,I=j[0]&127,I<126?T=3:I===126?T=1:T=2}else if(T===1){if(c(_)<2)break;const j=l(_,2);I=new DataView(j.buffer,j.byteOffset,j.length).getUint16(0),T=3}else if(T===2){if(c(_)<8)break;const j=l(_,8),X=new DataView(j.buffer,j.byteOffset,j.length),J=X.getUint32(0);if(J>Math.pow(2,21)-1){N.enqueue(n.ERROR_PACKET);break}I=J*Math.pow(2,32)+X.getUint32(4),T=3}else{if(c(_)<I)break;const j=l(_,I);N.enqueue((0,t.decodePacket)($?j:u.decode(j),m)),T=0}if(I===0||I>v){N.enqueue(n.ERROR_PACKET);break}}}})}e.protocol=4})(_o);function en(e){if(e)return LX(e)}function LX(e){for(var r in en.prototype)e[r]=en.prototype[r];return e}en.prototype.on=en.prototype.addEventListener=function(e,r){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(r),this};en.prototype.once=function(e,r){function t(){this.off(e,t),r.apply(this,arguments)}return t.fn=r,this.on(e,t),this};en.prototype.off=en.prototype.removeListener=en.prototype.removeAllListeners=en.prototype.removeEventListener=function(e,r){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+e];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var n,i=0;i<t.length;i++)if(n=t[i],n===r||n.fn===r){t.splice(i,1);break}return t.length===0&&delete this._callbacks["$"+e],this};en.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var r=new Array(arguments.length-1),t=this._callbacks["$"+e],n=1;n<arguments.length;n++)r[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,i=t.length;n<i;++n)t[n].apply(this,r)}return this};en.prototype.emitReserved=en.prototype.emit;en.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};en.prototype.hasListeners=function(e){return!!this.listeners(e).length};const DX=Object.freeze(Object.defineProperty({__proto__:null,Emitter:en},Symbol.toStringTag,{value:"Module"})),wo=hT(DX);var oi={},pn={};Object.defineProperty(pn,"__esModule",{value:!0});pn.defaultBinaryType=pn.globalThisShim=pn.nextTick=void 0;pn.createCookieJar=jX;pn.nextTick=typeof Promise=="function"&&typeof Promise.resolve=="function"?r=>Promise.resolve().then(r):(r,t)=>t(r,0);pn.globalThisShim=typeof self<"u"?self:typeof window<"u"?window:Function("return this")();pn.defaultBinaryType="arraybuffer";function jX(){}Object.defineProperty(oi,"__esModule",{value:!0});oi.pick=FX;oi.installTimerFunctions=qX;oi.byteLength=WX;oi.randomString=GX;const va=pn;function FX(e,...r){return r.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const UX=va.globalThisShim.setTimeout,BX=va.globalThisShim.clearTimeout;function qX(e,r){r.useNativeTimers?(e.setTimeoutFn=UX.bind(va.globalThisShim),e.clearTimeoutFn=BX.bind(va.globalThisShim)):(e.setTimeoutFn=va.globalThisShim.setTimeout.bind(va.globalThisShim),e.clearTimeoutFn=va.globalThisShim.clearTimeout.bind(va.globalThisShim))}const zX=1.33;function WX(e){return typeof e=="string"?HX(e):Math.ceil((e.byteLength||e.size)*zX)}function HX(e){let r=0,t=0;for(let n=0,i=e.length;n<i;n++)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:r<55296||r>=57344?t+=3:(n++,t+=4);return t}function GX(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}var Ju={};Object.defineProperty(Ju,"__esModule",{value:!0});Ju.encode=VX;Ju.decode=KX;function VX(e){let r="";for(let t in e)e.hasOwnProperty(t)&&(r.length&&(r+="&"),r+=encodeURIComponent(t)+"="+encodeURIComponent(e[t]));return r}function KX(e){let r={},t=e.split("&");for(let n=0,i=t.length;n<i;n++){let a=t[n].split("=");r[decodeURIComponent(a[0])]=decodeURIComponent(a[1])}return r}var pv={exports:{}},Jp,d0;function JX(){if(d0)return Jp;d0=1;var e=1e3,r=e*60,t=r*60,n=t*24,i=n*7,a=n*365.25;Jp=function(l,p){p=p||{};var v=typeof l;if(v==="string"&&l.length>0)return s(l);if(v==="number"&&isFinite(l))return p.long?u(l):o(l);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(l))};function s(l){if(l=String(l),!(l.length>100)){var p=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(l);if(p){var v=parseFloat(p[1]),m=(p[2]||"ms").toLowerCase();switch(m){case"years":case"year":case"yrs":case"yr":case"y":return v*a;case"weeks":case"week":case"w":return v*i;case"days":case"day":case"d":return v*n;case"hours":case"hour":case"hrs":case"hr":case"h":return v*t;case"minutes":case"minute":case"mins":case"min":case"m":return v*r;case"seconds":case"second":case"secs":case"sec":case"s":return v*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return v;default:return}}}}function o(l){var p=Math.abs(l);return p>=n?Math.round(l/n)+"d":p>=t?Math.round(l/t)+"h":p>=r?Math.round(l/r)+"m":p>=e?Math.round(l/e)+"s":l+"ms"}function u(l){var p=Math.abs(l);return p>=n?c(l,p,n,"day"):p>=t?c(l,p,t,"hour"):p>=r?c(l,p,r,"minute"):p>=e?c(l,p,e,"second"):l+" ms"}function c(l,p,v,m){var _=p>=v*1.5;return Math.round(l/v)+" "+m+(_?"s":"")}return Jp}function YX(e){t.debug=t,t.default=t,t.coerce=u,t.disable=a,t.enable=i,t.enabled=s,t.humanize=JX(),t.destroy=c,Object.keys(e).forEach(l=>{t[l]=e[l]}),t.names=[],t.skips=[],t.formatters={};function r(l){let p=0;for(let v=0;v<l.length;v++)p=(p<<5)-p+l.charCodeAt(v),p|=0;return t.colors[Math.abs(p)%t.colors.length]}t.selectColor=r;function t(l){let p,v=null,m,_;function T(...I){if(!T.enabled)return;const $=T,x=Number(new Date),N=x-(p||x);$.diff=N,$.prev=p,$.curr=x,p=x,I[0]=t.coerce(I[0]),typeof I[0]!="string"&&I.unshift("%O");let j=0;I[0]=I[0].replace(/%([a-zA-Z%])/g,(J,G)=>{if(J==="%%")return"%";j++;const L=t.formatters[G];if(typeof L=="function"){const re=I[j];J=L.call($,re),I.splice(j,1),j--}return J}),t.formatArgs.call($,I),($.log||t.log).apply($,I)}return T.namespace=l,T.useColors=t.useColors(),T.color=t.selectColor(l),T.extend=n,T.destroy=t.destroy,Object.defineProperty(T,"enabled",{enumerable:!0,configurable:!1,get:()=>v!==null?v:(m!==t.namespaces&&(m=t.namespaces,_=t.enabled(l)),_),set:I=>{v=I}}),typeof t.init=="function"&&t.init(T),T}function n(l,p){const v=t(this.namespace+(typeof p>"u"?":":p)+l);return v.log=this.log,v}function i(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let p;const v=(typeof l=="string"?l:"").split(/[\s,]+/),m=v.length;for(p=0;p<m;p++)v[p]&&(l=v[p].replace(/\*/g,".*?"),l[0]==="-"?t.skips.push(new RegExp("^"+l.slice(1)+"$")):t.names.push(new RegExp("^"+l+"$")))}function a(){const l=[...t.names.map(o),...t.skips.map(o).map(p=>"-"+p)].join(",");return t.enable(""),l}function s(l){if(l[l.length-1]==="*")return!0;let p,v;for(p=0,v=t.skips.length;p<v;p++)if(t.skips[p].test(l))return!1;for(p=0,v=t.names.length;p<v;p++)if(t.names[p].test(l))return!0;return!1}function o(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function u(l){return l instanceof Error?l.stack||l.message:l}function c(){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 XX=YX;(function(e,r){r.formatArgs=n,r.save=i,r.load=a,r.useColors=t,r.storage=s(),r.destroy=(()=>{let u=!1;return()=>{u||(u=!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`."))}})(),r.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 u;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&&(u=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(u[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function n(u){if(u[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+u[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const c="color: "+this.color;u.splice(1,0,c,"color: inherit");let l=0,p=0;u[0].replace(/%[a-zA-Z%]/g,v=>{v!=="%%"&&(l++,v==="%c"&&(p=l))}),u.splice(p,0,c)}r.log=console.debug||console.log||(()=>{});function i(u){try{u?r.storage.setItem("debug",u):r.storage.removeItem("debug")}catch{}}function a(){let u;try{u=r.storage.getItem("debug")}catch{}return!u&&typeof process<"u"&&"env"in process&&(u=process.env.DEBUG),u}function s(){try{return localStorage}catch{}}e.exports=XX(r);const{formatters:o}=e.exports;o.j=function(u){try{return JSON.stringify(u)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}})(pv,pv.exports);var ui=pv.exports,QX=Ne&&Ne.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ki,"__esModule",{value:!0});Ki.Transport=Ki.TransportError=void 0;const ZX=_o,eQ=wo,tQ=oi,rQ=Ju,nQ=QX(ui),iQ=(0,nQ.default)("engine.io-client:transport");class c$ extends Error{constructor(r,t,n){super(r),this.description=t,this.context=n,this.type="TransportError"}}Ki.TransportError=c$;class aQ extends eQ.Emitter{constructor(r){super(),this.writable=!1,(0,tQ.installTimerFunctions)(this,r),this.opts=r,this.query=r.query,this.socket=r.socket,this.supportsBinary=!r.forceBase64}onError(r,t,n){return super.emitReserved("error",new c$(r,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(r){this.readyState==="open"?this.write(r):iQ("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(r){const t=(0,ZX.decodePacket)(r,this.socket.binaryType);this.onPacket(t)}onPacket(r){super.emitReserved("packet",r)}onClose(r){this.readyState="closed",super.emitReserved("close",r)}pause(r){}createUri(r,t={}){return r+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const r=this.opts.hostname;return r.indexOf(":")===-1?r:"["+r+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(r){const t=(0,rQ.encode)(r);return t.length?"?"+t:""}}Ki.Transport=aQ;var sQ=Ne&&Ne.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Vu,"__esModule",{value:!0});Vu.Polling=void 0;const oQ=Ki,uQ=oi,p0=_o,cQ=sQ(ui),Kn=(0,cQ.default)("engine.io-client:polling");class lQ extends oQ.Transport{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(r){this.readyState="pausing";const t=()=>{Kn("paused"),this.readyState="paused",r()};if(this._polling||!this.writable){let n=0;this._polling&&(Kn("we are currently polling - waiting to pause"),n++,this.once("pollComplete",function(){Kn("pre-pause polling complete"),--n||t()})),this.writable||(Kn("we are currently writing - waiting to pause"),n++,this.once("drain",function(){Kn("pre-pause writing complete"),--n||t()}))}else t()}_poll(){Kn("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(r){Kn("polling got data %s",r);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,p0.decodePayload)(r,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Kn('ignoring poll - transport state "%s"',this.readyState))}doClose(){const r=()=>{Kn("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Kn("transport open - closing"),r()):(Kn("transport not open - deferring close"),this.once("open",r))}write(r){this.writable=!1,(0,p0.encodePayload)(r,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const r=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=(0,uQ.randomString)()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(r,t)}}Vu.Polling=lQ;var Df={};Object.defineProperty(Df,"__esModule",{value:!0});Df.hasCORS=void 0;let l$=!1;try{l$=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}Df.hasCORS=l$;var fQ=Ne&&Ne.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(yi,"__esModule",{value:!0});yi.XHR=yi.Request=yi.BaseXHR=void 0;const dQ=Vu,pQ=wo,h0=oi,f$=pn,hQ=Df,vQ=fQ(ui),hv=(0,vQ.default)("engine.io-client:polling");function mQ(){}class d$ extends dQ.Polling{constructor(r){if(super(r),typeof location<"u"){const t=location.protocol==="https:";let n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&r.hostname!==location.hostname||n!==r.port}}doWrite(r,t){const n=this.request({method:"POST",data:r});n.on("success",t),n.on("error",(i,a)=>{this.onError("xhr post error",i,a)})}doPoll(){hv("xhr poll");const r=this.request();r.on("data",this.onData.bind(this)),r.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=r}}yi.BaseXHR=d$;class ni extends pQ.Emitter{constructor(r,t,n){super(),this.createRequest=r,(0,h0.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 r;const t=(0,h0.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{hv("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{}(r=this._opts.cookieJar)===null||r===void 0||r.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))},hv("xhr data %s",this._data),n.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=ni.requestsCount++,ni.requests[this._index]=this)}_onError(r){this.emitReserved("error",r,this._xhr),this._cleanup(!0)}_cleanup(r){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=mQ,r)try{this._xhr.abort()}catch{}typeof document<"u"&&delete ni.requests[this._index],this._xhr=null}}_onLoad(){const r=this._xhr.responseText;r!==null&&(this.emitReserved("data",r),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}yi.Request=ni;ni.requestsCount=0;ni.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",v0);else if(typeof addEventListener=="function"){const e="onpagehide"in f$.globalThisShim?"pagehide":"unload";addEventListener(e,v0,!1)}}function v0(){for(let e in ni.requests)ni.requests.hasOwnProperty(e)&&ni.requests[e].abort()}const gQ=function(){const e=p$({xdomain:!1});return e&&e.responseType!==null}();class yQ extends d${constructor(r){super(r);const t=r&&r.forceBase64;this.supportsBinary=gQ&&!t}request(r={}){return Object.assign(r,{xd:this.xd},this.opts),new ni(p$,this.uri(),r)}}yi.XHR=yQ;function p$(e){const r=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!r||hQ.hasCORS))return new XMLHttpRequest}catch{}if(!r)try{return new f$.globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Ra={},bQ=Ne&&Ne.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ra,"__esModule",{value:!0});Ra.WS=Ra.BaseWS=void 0;const _Q=Ki,m0=oi,wQ=_o,vv=pn,SQ=bQ(ui),TQ=(0,SQ.default)("engine.io-client:websocket"),h$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class v$ extends _Q.Transport{get name(){return"websocket"}doOpen(){const r=this.uri(),t=this.opts.protocols,n=h$?{}:(0,m0.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(r,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=r=>this.onClose({description:"websocket connection closed",context:r}),this.ws.onmessage=r=>this.onData(r.data),this.ws.onerror=r=>this.onError("websocket error",r)}write(r){this.writable=!1;for(let t=0;t<r.length;t++){const n=r[t],i=t===r.length-1;(0,wQ.encodePacket)(n,this.supportsBinary,a=>{try{this.doWrite(n,a)}catch{TQ("websocket closed before onclose event")}i&&(0,vv.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 r=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=(0,m0.randomString)()),this.supportsBinary||(t.b64=1),this.createUri(r,t)}}Ra.BaseWS=v$;const Yp=vv.globalThisShim.WebSocket||vv.globalThisShim.MozWebSocket;class CQ extends v${createSocket(r,t,n){return h$?new Yp(r,t,n):t?new Yp(r,t):new Yp(r)}doWrite(r,t){this.ws.send(t)}}Ra.WS=CQ;var Yu={},EQ=Ne&&Ne.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Yu,"__esModule",{value:!0});Yu.WT=void 0;const kQ=Ki,RQ=pn,g0=_o,$Q=EQ(ui),Wo=(0,$Q.default)("engine.io-client:webtransport");class IQ extends kQ.Transport{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(r){return this.emitReserved("error",r)}this._transport.closed.then(()=>{Wo("transport closed gracefully"),this.onClose()}).catch(r=>{Wo("transport closed due to %s",r),this.onError("webtransport error",r)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(r=>{const t=(0,g0.createPacketDecoderStream)(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=r.readable.pipeThrough(t).getReader(),i=(0,g0.createPacketEncoderStream)();i.readable.pipeTo(r.writable),this._writer=i.writable.getWriter();const a=()=>{n.read().then(({done:o,value:u})=>{if(o){Wo("session is closed");return}Wo("received chunk: %o",u),this.onPacket(u),a()}).catch(o=>{Wo("an error occurred while reading: %s",o)})};a();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this._writer.write(s).then(()=>this.onOpen())})})}write(r){this.writable=!1;for(let t=0;t<r.length;t++){const n=r[t],i=t===r.length-1;this._writer.write(n).then(()=>{i&&(0,RQ.nextTick)(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var r;(r=this._transport)===null||r===void 0||r.close()}}Yu.WT=IQ;Object.defineProperty(Gu,"__esModule",{value:!0});Gu.transports=void 0;const OQ=yi,AQ=Ra,PQ=Yu;Gu.transports={websocket:AQ.WS,webtransport:PQ.WT,polling:OQ.XHR};var jf={};Object.defineProperty(jf,"__esModule",{value:!0});jf.parse=NQ;const MQ=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,xQ=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function NQ(e){if(e.length>8e3)throw"URI too long";const r=e,t=e.indexOf("["),n=e.indexOf("]");t!=-1&&n!=-1&&(e=e.substring(0,t)+e.substring(t,n).replace(/:/g,";")+e.substring(n,e.length));let i=MQ.exec(e||""),a={},s=14;for(;s--;)a[xQ[s]]=i[s]||"";return t!=-1&&n!=-1&&(a.source=r,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a.pathNames=LQ(a,a.path),a.queryKey=DQ(a,a.query),a}function LQ(e,r){const t=/\/{2,9}/g,n=r.replace(t,"/").split("/");return(r.slice(0,1)=="/"||r.length===0)&&n.splice(0,1),r.slice(-1)=="/"&&n.splice(n.length-1,1),n}function DQ(e,r){const t={};return r.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,a){i&&(t[i]=a)}),t}var jQ=Ne&&Ne.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(zi,"__esModule",{value:!0});zi.Socket=zi.SocketWithUpgrade=zi.SocketWithoutUpgrade=void 0;const FQ=Gu,y0=oi,UQ=Ju,b0=jf,BQ=wo,m$=_o,Xp=pn,qQ=jQ(ui),rr=(0,qQ.default)("engine.io-client:socket"),mv=typeof addEventListener=="function"&&typeof removeEventListener=="function",au=[];mv&&addEventListener("offline",()=>{rr("closing %d connection(s) because the network was lost",au.length),au.forEach(e=>e())},!1);class Wi extends BQ.Emitter{constructor(r,t){if(super(),this.binaryType=Xp.defaultBinaryType,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,r&&typeof r=="object"&&(t=r,r=null),r){const n=(0,b0.parse)(r);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,b0.parse)(t.host).host);(0,y0.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,UQ.decode)(this.opts.query)),mv&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(rr("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},au.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=(0,Xp.createCookieJar)()),this._open()}createTransport(r){rr('creating transport "%s"',r);const t=Object.assign({},this.opts.query);t.EIO=m$.protocol,t.transport=r,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[r]);return rr("options: %j",n),new this._transportsByName[r](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const r=this.opts.rememberUpgrade&&Wi.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(r);t.open(),this.setTransport(t)}setTransport(r){rr("setting transport %s",r.name),this.transport&&(rr("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=r,r.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(){rr("socket open"),this.readyState="open",Wi.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(rr('socket receive: type "%s", data "%s"',r.type,r.data),this.emitReserved("packet",r),this.emitReserved("heartbeat"),r.type){case"open":this.onHandshake(JSON.parse(r.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=r.data,this._onError(t);break;case"message":this.emitReserved("data",r.data),this.emitReserved("message",r.data);break}else rr('packet received with socket readyState "%s"',this.readyState)}onHandshake(r){this.emitReserved("handshake",r),this.id=r.sid,this.transport.query.sid=r.sid,this._pingInterval=r.pingInterval,this._pingTimeout=r.pingTimeout,this._maxPayload=r.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const r=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+r,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},r),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 r=this._getWritablePackets();rr("flushing %d packets in socket",r.length),this.transport.send(r),this._prevBufferLen=r.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,y0.byteLength)(i)),n>0&&t>this._maxPayload)return rr("only send %d out of %d packets",n,this.writeBuffer.length),this.writeBuffer.slice(0,n);t+=2}return rr("payload size is %d (max: %d)",t,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const r=Date.now()>this._pingTimeoutTime;return r&&(rr("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,(0,Xp.nextTick)(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),r}write(r,t,n){return this._sendPacket("message",r,t,n),this}send(r,t,n){return this._sendPacket("message",r,t,n),this}_sendPacket(r,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 a={type:r,data:t,options:n};this.emitReserved("packetCreate",a),this.writeBuffer.push(a),i&&this.once("flush",i),this.flush()}close(){const r=()=>{this._onClose("forced close"),rr("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),r()},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():r()}):this.upgrading?n():r()),this}_onError(r){if(rr("socket error %j",r),Wi.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return rr("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",r),this._onClose("transport error",r)}_onClose(r,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(rr('socket close with reason: "%s"',r),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),mv&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=au.indexOf(this._offlineEventListener);n!==-1&&(rr("removing listener for the 'offline' event"),au.splice(n,1))}this.readyState="closed",this.id=null,this.emitReserved("close",r,t),this.writeBuffer=[],this._prevBufferLen=0}}}zi.SocketWithoutUpgrade=Wi;Wi.protocol=m$.protocol;class g$ extends Wi{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){rr("starting upgrade probes");for(let r=0;r<this._upgrades.length;r++)this._probe(this._upgrades[r])}}_probe(r){rr('probing transport "%s"',r);let t=this.createTransport(r),n=!1;Wi.priorWebsocketSuccess=!1;const i=()=>{n||(rr('probe transport "%s" opened',r),t.send([{type:"ping",data:"probe"}]),t.once("packet",p=>{if(!n)if(p.type==="pong"&&p.data==="probe"){if(rr('probe transport "%s" pong',r),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Wi.priorWebsocketSuccess=t.name==="websocket",rr('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{n||this.readyState!=="closed"&&(rr("changing transport and sending upgrade packet"),l(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{rr('probe transport "%s" failed',r);const v=new Error("probe error");v.transport=t.name,this.emitReserved("upgradeError",v)}}))};function a(){n||(n=!0,l(),t.close(),t=null)}const s=p=>{const v=new Error("probe error: "+p);v.transport=t.name,a(),rr('probe transport "%s" failed because of error: %s',r,p),this.emitReserved("upgradeError",v)};function o(){s("transport closed")}function u(){s("socket closed")}function c(p){t&&p.name!==t.name&&(rr('"%s" works - aborting "%s"',p.name,t.name),a())}const l=()=>{t.removeListener("open",i),t.removeListener("error",s),t.removeListener("close",o),this.off("close",u),this.off("upgrading",c)};t.once("open",i),t.once("error",s),t.once("close",o),this.once("close",u),this.once("upgrading",c),this._upgrades.indexOf("webtransport")!==-1&&r!=="webtransport"?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(r){this._upgrades=this._filterUpgrades(r.upgrades),super.onHandshake(r)}_filterUpgrades(r){const t=[];for(let n=0;n<r.length;n++)~this.transports.indexOf(r[n])&&t.push(r[n]);return t}}zi.SocketWithUpgrade=g$;let zQ=class extends g${constructor(r,t={}){const n=typeof r=="object"?r:t;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(i=>FQ.transports[i]).filter(i=>!!i)),super(r,n)}};zi.Socket=zQ;var Ff={};Object.defineProperty(Ff,"__esModule",{value:!0});Ff.Fetch=void 0;const WQ=Vu;class HQ extends WQ.Polling{doPoll(){this._fetch().then(r=>{if(!r.ok)return this.onError("fetch read error",r.status,r);r.text().then(t=>this.onData(t))}).catch(r=>{this.onError("fetch read error",r)})}doWrite(r,t){this._fetch(r).then(n=>{if(!n.ok)return this.onError("fetch write error",n.status,n);t()}).catch(n=>{this.onError("fetch write error",n)})}_fetch(r){var t;const n=r!==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?r:null,headers:i,credentials:this.opts.withCredentials?"include":"omit"}).then(a=>{var s;return(s=this.socket._cookieJar)===null||s===void 0||s.parseCookies(a.headers.getSetCookie()),a})}}Ff.Fetch=HQ;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.WebTransport=e.WebSocket=e.NodeWebSocket=e.XHR=e.NodeXHR=e.Fetch=e.nextTick=e.parse=e.installTimerFunctions=e.transports=e.TransportError=e.Transport=e.protocol=e.SocketWithUpgrade=e.SocketWithoutUpgrade=e.Socket=void 0;const r=zi;Object.defineProperty(e,"Socket",{enumerable:!0,get:function(){return r.Socket}});var t=zi;Object.defineProperty(e,"SocketWithoutUpgrade",{enumerable:!0,get:function(){return t.SocketWithoutUpgrade}}),Object.defineProperty(e,"SocketWithUpgrade",{enumerable:!0,get:function(){return t.SocketWithUpgrade}}),e.protocol=r.Socket.protocol;var n=Ki;Object.defineProperty(e,"Transport",{enumerable:!0,get:function(){return n.Transport}}),Object.defineProperty(e,"TransportError",{enumerable:!0,get:function(){return n.TransportError}});var i=Gu;Object.defineProperty(e,"transports",{enumerable:!0,get:function(){return i.transports}});var a=oi;Object.defineProperty(e,"installTimerFunctions",{enumerable:!0,get:function(){return a.installTimerFunctions}});var s=jf;Object.defineProperty(e,"parse",{enumerable:!0,get:function(){return s.parse}});var o=pn;Object.defineProperty(e,"nextTick",{enumerable:!0,get:function(){return o.nextTick}});var u=Ff;Object.defineProperty(e,"Fetch",{enumerable:!0,get:function(){return u.Fetch}});var c=yi;Object.defineProperty(e,"NodeXHR",{enumerable:!0,get:function(){return c.XHR}});var l=yi;Object.defineProperty(e,"XHR",{enumerable:!0,get:function(){return l.XHR}});var p=Ra;Object.defineProperty(e,"NodeWebSocket",{enumerable:!0,get:function(){return p.WS}});var v=Ra;Object.defineProperty(e,"WebSocket",{enumerable:!0,get:function(){return v.WS}});var m=Yu;Object.defineProperty(e,"WebTransport",{enumerable:!0,get:function(){return m.WT}})})(Nf);var GQ=Ne&&Ne.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Pg,"__esModule",{value:!0});Pg.url=JQ;const VQ=Nf,KQ=GQ(ui),_0=(0,KQ.default)("socket.io-client:url");function JQ(e,r="",t){let n=e;t=t||typeof location<"u"&&location,e==null&&(e=t.protocol+"//"+t.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=t.protocol+e:e=t.host+e),/^(https?|wss?):\/\//.test(e)||(_0("protocol-less url %s",e),typeof t<"u"?e=t.protocol+"//"+e:e="https://"+e),_0("parse %s",e),n=(0,VQ.parse)(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const a=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+a+":"+n.port+r,n.href=n.protocol+"://"+a+(t&&t.port===n.port?"":":"+n.port),n}var Uf={},Xu={},Bf={},uo={},os={};Object.defineProperty(os,"__esModule",{value:!0});os.hasBinary=os.isBinary=void 0;const YQ=typeof ArrayBuffer=="function",XQ=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,y$=Object.prototype.toString,QQ=typeof Blob=="function"||typeof Blob<"u"&&y$.call(Blob)==="[object BlobConstructor]",ZQ=typeof File=="function"||typeof File<"u"&&y$.call(File)==="[object FileConstructor]";function b$(e){return YQ&&(e instanceof ArrayBuffer||XQ(e))||QQ&&e instanceof Blob||ZQ&&e instanceof File}os.isBinary=b$;function gl(e,r){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(gl(e[t]))return!0;return!1}if(b$(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return gl(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&gl(e[t]))return!0;return!1}os.hasBinary=gl;Object.defineProperty(uo,"__esModule",{value:!0});uo.reconstructPacket=uo.deconstructPacket=void 0;const eZ=os;function tZ(e){const r=[],t=e.data,n=e;return n.data=gv(t,r),n.attachments=r.length,{packet:n,buffers:r}}uo.deconstructPacket=tZ;function gv(e,r){if(!e)return e;if((0,eZ.isBinary)(e)){const t={_placeholder:!0,num:r.length};return r.push(e),t}else if(Array.isArray(e)){const t=new Array(e.length);for(let n=0;n<e.length;n++)t[n]=gv(e[n],r);return t}else if(typeof e=="object"&&!(e instanceof Date)){const t={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=gv(e[n],r));return t}return e}function rZ(e,r){return e.data=yv(e.data,r),delete e.attachments,e}uo.reconstructPacket=rZ;function yv(e,r){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num=="number"&&e.num>=0&&e.num<r.length)return r[e.num];throw new Error("illegal attachments")}else if(Array.isArray(e))for(let t=0;t<e.length;t++)e[t]=yv(e[t],r);else if(typeof e=="object")for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(e[t]=yv(e[t],r));return e}(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Decoder=e.Encoder=e.PacketType=e.protocol=void 0;const r=wo,t=uo,n=os,a=(0,ui.default)("socket.io-parser"),s=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];e.protocol=5;var o;(function(v){v[v.CONNECT=0]="CONNECT",v[v.DISCONNECT=1]="DISCONNECT",v[v.EVENT=2]="EVENT",v[v.ACK=3]="ACK",v[v.CONNECT_ERROR=4]="CONNECT_ERROR",v[v.BINARY_EVENT=5]="BINARY_EVENT",v[v.BINARY_ACK=6]="BINARY_ACK"})(o=e.PacketType||(e.PacketType={}));class u{constructor(m){this.replacer=m}encode(m){return a("encoding packet %j",m),(m.type===o.EVENT||m.type===o.ACK)&&(0,n.hasBinary)(m)?this.encodeAsBinary({type:m.type===o.EVENT?o.BINARY_EVENT:o.BINARY_ACK,nsp:m.nsp,data:m.data,id:m.id}):[this.encodeAsString(m)]}encodeAsString(m){let _=""+m.type;return(m.type===o.BINARY_EVENT||m.type===o.BINARY_ACK)&&(_+=m.attachments+"-"),m.nsp&&m.nsp!=="/"&&(_+=m.nsp+","),m.id!=null&&(_+=m.id),m.data!=null&&(_+=JSON.stringify(m.data,this.replacer)),a("encoded %j as %s",m,_),_}encodeAsBinary(m){const _=(0,t.deconstructPacket)(m),T=this.encodeAsString(_.packet),I=_.buffers;return I.unshift(T),I}}e.Encoder=u;function c(v){return Object.prototype.toString.call(v)==="[object Object]"}class l extends r.Emitter{constructor(m){super(),this.reviver=m}add(m){let _;if(typeof m=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");_=this.decodeString(m);const T=_.type===o.BINARY_EVENT;T||_.type===o.BINARY_ACK?(_.type=T?o.EVENT:o.ACK,this.reconstructor=new p(_),_.attachments===0&&super.emitReserved("decoded",_)):super.emitReserved("decoded",_)}else if((0,n.isBinary)(m)||m.base64)if(this.reconstructor)_=this.reconstructor.takeBinaryData(m),_&&(this.reconstructor=null,super.emitReserved("decoded",_));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+m)}decodeString(m){let _=0;const T={type:Number(m.charAt(0))};if(o[T.type]===void 0)throw new Error("unknown packet type "+T.type);if(T.type===o.BINARY_EVENT||T.type===o.BINARY_ACK){const $=_+1;for(;m.charAt(++_)!=="-"&&_!=m.length;);const x=m.substring($,_);if(x!=Number(x)||m.charAt(_)!=="-")throw new Error("Illegal attachments");T.attachments=Number(x)}if(m.charAt(_+1)==="/"){const $=_+1;for(;++_&&!(m.charAt(_)===","||_===m.length););T.nsp=m.substring($,_)}else T.nsp="/";const I=m.charAt(_+1);if(I!==""&&Number(I)==I){const $=_+1;for(;++_;){const x=m.charAt(_);if(x==null||Number(x)!=x){--_;break}if(_===m.length)break}T.id=Number(m.substring($,_+1))}if(m.charAt(++_)){const $=this.tryParse(m.substr(_));if(l.isPayloadValid(T.type,$))T.data=$;else throw new Error("invalid payload")}return a("decoded %s as %j",m,T),T}tryParse(m){try{return JSON.parse(m,this.reviver)}catch{return!1}}static isPayloadValid(m,_){switch(m){case o.CONNECT:return c(_);case o.DISCONNECT:return _===void 0;case o.CONNECT_ERROR:return typeof _=="string"||c(_);case o.EVENT:case o.BINARY_EVENT:return Array.isArray(_)&&(typeof _[0]=="number"||typeof _[0]=="string"&&s.indexOf(_[0])===-1);case o.ACK:case o.BINARY_ACK:return Array.isArray(_)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}e.Decoder=l;class p{constructor(m){this.packet=m,this.buffers=[],this.reconPack=m}takeBinaryData(m){if(this.buffers.push(m),this.buffers.length===this.reconPack.attachments){const _=(0,t.reconstructPacket)(this.reconPack,this.buffers);return this.finishedReconstruction(),_}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}})(Bf);var qf={};Object.defineProperty(qf,"__esModule",{value:!0});qf.on=nZ;function nZ(e,r,t){return e.on(r,t),function(){e.off(r,t)}}var iZ=Ne&&Ne.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Xu,"__esModule",{value:!0});Xu.Socket=void 0;const Jn=Bf,zc=qf,aZ=wo,sZ=iZ(ui),xr=(0,sZ.default)("socket.io-client:socket"),oZ=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class uZ extends aZ.Emitter{constructor(r,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=r,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 r=this.io;this.subs=[(0,zc.on)(r,"open",this.onopen.bind(this)),(0,zc.on)(r,"packet",this.onpacket.bind(this)),(0,zc.on)(r,"error",this.onerror.bind(this)),(0,zc.on)(r,"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(...r){return r.unshift("message"),this.emit.apply(this,r),this}emit(r,...t){var n,i,a;if(oZ.hasOwnProperty(r))throw new Error('"'+r.toString()+'" is a reserved event name');if(t.unshift(r),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const s={type:Jn.PacketType.EVENT,data:t};if(s.options={},s.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const l=this.ids++;xr("emitting packet with ack id %d",l);const p=t.pop();this._registerAckCallback(l,p),s.id=l}const o=(i=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||i===void 0?void 0:i.writable,u=this.connected&&!(!((a=this.io.engine)===null||a===void 0)&&a._hasPingExpired());return this.flags.volatile&&!o?xr("discard packet as the transport is not currently writable"):u?(this.notifyOutgoingListeners(s),this.packet(s)):this.sendBuffer.push(s),this.flags={},this}_registerAckCallback(r,t){var n;const i=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(i===void 0){this.acks[r]=t;return}const a=this.io.setTimeoutFn(()=>{delete this.acks[r];for(let o=0;o<this.sendBuffer.length;o++)this.sendBuffer[o].id===r&&(xr("removing packet with ack id %d from the buffer",r),this.sendBuffer.splice(o,1));xr("event with ack id %d has timed out after %d ms",r,i),t.call(this,new Error("operation has timed out"))},i),s=(...o)=>{this.io.clearTimeoutFn(a),t.apply(this,o)};s.withError=!0,this.acks[r]=s}emitWithAck(r,...t){return new Promise((n,i)=>{const a=(s,o)=>s?i(s):n(o);a.withError=!0,t.push(a),this.emit(r,...t)})}_addToQueue(r){let t;typeof r[r.length-1]=="function"&&(t=r.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:r,flags:Object.assign({fromQueue:!0},this.flags)};r.push((i,...a)=>n!==this._queue[0]?void 0:(i!==null?n.tryCount>this._opts.retries&&(xr("packet [%d] is discarded after %d tries",n.id,n.tryCount),this._queue.shift(),t&&t(i)):(xr("packet [%d] was successfully sent",n.id),this._queue.shift(),t&&t(null,...a)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(r=!1){if(xr("draining queue"),!this.connected||this._queue.length===0)return;const t=this._queue[0];if(t.pending&&!r){xr("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,xr("sending packet [%d] (try n°%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)}packet(r){r.nsp=this.nsp,this.io._packet(r)}onopen(){xr("transport is open - connecting"),typeof this.auth=="function"?this.auth(r=>{this._sendConnectPacket(r)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(r){this.packet({type:Jn.PacketType.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},r):r})}onerror(r){this.connected||this.emitReserved("connect_error",r)}onclose(r,t){xr("close (%s)",r),this.connected=!1,delete this.id,this.emitReserved("disconnect",r,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(r=>{if(!this.sendBuffer.some(n=>String(n.id)===r)){const n=this.acks[r];delete this.acks[r],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(r){if(r.nsp===this.nsp)switch(r.type){case Jn.PacketType.CONNECT:r.data&&r.data.sid?this.onconnect(r.data.sid,r.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 Jn.PacketType.EVENT:case Jn.PacketType.BINARY_EVENT:this.onevent(r);break;case Jn.PacketType.ACK:case Jn.PacketType.BINARY_ACK:this.onack(r);break;case Jn.PacketType.DISCONNECT:this.ondisconnect();break;case Jn.PacketType.CONNECT_ERROR:this.destroy();const n=new Error(r.data.message);n.data=r.data.data,this.emitReserved("connect_error",n);break}}onevent(r){const t=r.data||[];xr("emitting event %j",t),r.id!=null&&(xr("attaching ack callback to event"),t.push(this.ack(r.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(r){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,r)}super.emit.apply(this,r),this._pid&&r.length&&typeof r[r.length-1]=="string"&&(this._lastOffset=r[r.length-1])}ack(r){const t=this;let n=!1;return function(...i){n||(n=!0,xr("sending ack %j",i),t.packet({type:Jn.PacketType.ACK,id:r,data:i}))}}onack(r){const t=this.acks[r.id];if(typeof t!="function"){xr("bad ack %s",r.id);return}delete this.acks[r.id],xr("calling ack %s with %j",r.id,r.data),t.withError&&r.data.unshift(null),t.apply(this,r.data)}onconnect(r,t){xr("socket connected with id %s",r),this.id=r,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(r=>this.emitEvent(r)),this.receiveBuffer=[],this.sendBuffer.forEach(r=>{this.notifyOutgoingListeners(r),this.packet(r)}),this.sendBuffer=[]}ondisconnect(){xr("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(r=>r()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(xr("performing disconnect (%s)",this.nsp),this.packet({type:Jn.PacketType.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(r){return this.flags.compress=r,this}get volatile(){return this.flags.volatile=!0,this}timeout(r){return this.flags.timeout=r,this}onAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(r),this}prependAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(r),this}offAny(r){if(!this._anyListeners)return this;if(r){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(r===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(r),this}prependAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(r),this}offAnyOutgoing(r){if(!this._anyOutgoingListeners)return this;if(r){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(r===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(r){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,r.data)}}}Xu.Socket=uZ;var Mg={};Object.defineProperty(Mg,"__esModule",{value:!0});Mg.Backoff=So;function So(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}So.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var r=Math.random(),t=Math.floor(r*this.jitter*e);e=Math.floor(r*10)&1?e+t:e-t}return Math.min(e,this.max)|0};So.prototype.reset=function(){this.attempts=0};So.prototype.setMin=function(e){this.ms=e};So.prototype.setMax=function(e){this.max=e};So.prototype.setJitter=function(e){this.jitter=e};var cZ=Ne&&Ne.__createBinding||(Object.create?function(e,r,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(r,t);(!i||("get"in i?!r.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return r[t]}}),Object.defineProperty(e,n,i)}:function(e,r,t,n){n===void 0&&(n=t),e[n]=r[t]}),lZ=Ne&&Ne.__setModuleDefault||(Object.create?function(e,r){Object.defineProperty(e,"default",{enumerable:!0,value:r})}:function(e,r){e.default=r}),fZ=Ne&&Ne.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var t in e)t!=="default"&&Object.prototype.hasOwnProperty.call(e,t)&&cZ(r,e,t);return lZ(r,e),r},dZ=Ne&&Ne.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Uf,"__esModule",{value:!0});Uf.Manager=void 0;const Qp=Nf,pZ=Xu,hZ=fZ(Bf),Xa=qf,vZ=Mg,mZ=wo,gZ=dZ(ui),Vr=(0,gZ.default)("socket.io-client:manager");class yZ extends mZ.Emitter{constructor(r,t){var n;super(),this.nsps={},this.subs=[],r&&typeof r=="object"&&(t=r,r=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,(0,Qp.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 vZ.Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=r;const i=t.parser||hZ;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(r){return arguments.length?(this._reconnection=!!r,r||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(r){return r===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=r,this)}reconnectionDelay(r){var t;return r===void 0?this._reconnectionDelay:(this._reconnectionDelay=r,(t=this.backoff)===null||t===void 0||t.setMin(r),this)}randomizationFactor(r){var t;return r===void 0?this._randomizationFactor:(this._randomizationFactor=r,(t=this.backoff)===null||t===void 0||t.setJitter(r),this)}reconnectionDelayMax(r){var t;return r===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=r,(t=this.backoff)===null||t===void 0||t.setMax(r),this)}timeout(r){return arguments.length?(this._timeout=r,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(r){if(Vr("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Vr("opening %s",this.uri),this.engine=new Qp.Socket(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=(0,Xa.on)(t,"open",function(){n.onopen(),r&&r()}),a=o=>{Vr("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",o),r?r(o):this.maybeReconnectOnOpen()},s=(0,Xa.on)(t,"error",a);if(this._timeout!==!1){const o=this._timeout;Vr("connect attempt will timeout after %d",o);const u=this.setTimeoutFn(()=>{Vr("connect attempt timed out after %d",o),i(),a(new Error("timeout")),t.close()},o);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(i),this.subs.push(s),this}connect(r){return this.open(r)}onopen(){Vr("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");const r=this.engine;this.subs.push((0,Xa.on)(r,"ping",this.onping.bind(this)),(0,Xa.on)(r,"data",this.ondata.bind(this)),(0,Xa.on)(r,"error",this.onerror.bind(this)),(0,Xa.on)(r,"close",this.onclose.bind(this)),(0,Xa.on)(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(r){try{this.decoder.add(r)}catch(t){this.onclose("parse error",t)}}ondecoded(r){(0,Qp.nextTick)(()=>{this.emitReserved("packet",r)},this.setTimeoutFn)}onerror(r){Vr("error",r),this.emitReserved("error",r)}socket(r,t){let n=this.nsps[r];return n?this._autoConnect&&!n.active&&n.connect():(n=new pZ.Socket(this,r,t),this.nsps[r]=n),n}_destroy(r){const t=Object.keys(this.nsps);for(const n of t)if(this.nsps[n].active){Vr("socket %s is still active, skipping close",n);return}this._close()}_packet(r){Vr("writing packet %j",r);const t=this.encoder.encode(r);for(let n=0;n<t.length;n++)this.engine.write(t[n],r.options)}cleanup(){Vr("cleanup"),this.subs.forEach(r=>r()),this.subs.length=0,this.decoder.destroy()}_close(){Vr("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(r,t){var n;Vr("closed due to %s",r),this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",r,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const r=this;if(this.backoff.attempts>=this._reconnectionAttempts)Vr("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();Vr("will wait %dms before reconnect attempt",t),this._reconnecting=!0;const n=this.setTimeoutFn(()=>{r.skipReconnect||(Vr("attempting reconnect"),this.emitReserved("reconnect_attempt",r.backoff.attempts),!r.skipReconnect&&r.open(i=>{i?(Vr("reconnect attempt error"),r._reconnecting=!1,r.reconnect(),this.emitReserved("reconnect_error",i)):(Vr("reconnect success"),r.onreconnect())}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const r=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",r)}}Uf.Manager=yZ;(function(e,r){var t=Ne&&Ne.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(r,"__esModule",{value:!0}),r.WebTransport=r.WebSocket=r.NodeWebSocket=r.XHR=r.NodeXHR=r.Fetch=r.Socket=r.Manager=r.protocol=void 0,r.io=c,r.connect=c,r.default=c;const n=Pg,i=Uf;Object.defineProperty(r,"Manager",{enumerable:!0,get:function(){return i.Manager}});const a=Xu;Object.defineProperty(r,"Socket",{enumerable:!0,get:function(){return a.Socket}});const o=(0,t(ui).default)("socket.io-client"),u={};function c(v,m){typeof v=="object"&&(m=v,v=void 0),m=m||{};const _=(0,n.url)(v,m.path||"/socket.io"),T=_.source,I=_.id,$=_.path,x=u[I]&&$ in u[I].nsps,N=m.forceNew||m["force new connection"]||m.multiplex===!1||x;let j;return N?(o("ignoring socket cache for %s",T),j=new i.Manager(T,m)):(u[I]||(o("new io instance for %s",T),u[I]=new i.Manager(T,m)),j=u[I]),_.query&&!m.query&&(m.query=_.queryKey),j.socket(_.path,m)}Object.assign(c,{Manager:i.Manager,Socket:a.Socket,io:c,connect:c});var l=Bf;Object.defineProperty(r,"protocol",{enumerable:!0,get:function(){return l.protocol}});var p=Nf;Object.defineProperty(r,"Fetch",{enumerable:!0,get:function(){return p.Fetch}}),Object.defineProperty(r,"NodeXHR",{enumerable:!0,get:function(){return p.NodeXHR}}),Object.defineProperty(r,"XHR",{enumerable:!0,get:function(){return p.XHR}}),Object.defineProperty(r,"NodeWebSocket",{enumerable:!0,get:function(){return p.NodeWebSocket}}),Object.defineProperty(r,"WebSocket",{enumerable:!0,get:function(){return p.WebSocket}}),Object.defineProperty(r,"WebTransport",{enumerable:!0,get:function(){return p.WebTransport}}),e.exports=c})(dv,dv.exports);var _$=dv.exports,w$={exports:{}};(function(e,r){(function(t){e.exports=t()})(function(){var t=function(f,d,h){for(var y=h,g=0,b=f.length;g<b;g++)y=d(y,f[g],g,f);return y},n=function(f,d){return t(f,function(h,y,g,b){return d(y,g,b)?h.concat(y):h},[])},i=function(f,d){return t(f,function(h,y,g,b){return h.concat(d(y,g,b))},[])},a=function(f,d){return t(f,function(h,y,g,b){return h===!0||y===d},!1)},s=!{toString:null}.propertyIsEnumerable("toString"),o=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],u=function(f){var d=[],h;for(h in f)Object.prototype.hasOwnProperty.call(f,h)&&d.push(h);if(!s)return d;for(var y=0,g=o.length;y<g;y++)Object.prototype.hasOwnProperty.call(f,o[y])&&d.push(o[y]);return d},c=function(f){return Object.prototype.toString.call(f)==="[object Array]"},l=function(f){return f<10?"0"+f:f},p=function(){var f=new Date;return f.getUTCFullYear()+"-"+l(f.getUTCMonth()+1)+"-"+l(f.getUTCDate())+"T"+l(f.getUTCHours())+":"+l(f.getUTCMinutes())+":"+l(f.getUTCSeconds())+"."+(f.getUTCMilliseconds()/1e3).toFixed(3).slice(2,5)+"Z"},v={map:i,reduce:t,filter:n,includes:a,keys:u,isArray:c,isoDate:p},m={};m.intRange=function(f,d){return f===void 0&&(f=1),d===void 0&&(d=1/0),function(h){return typeof h=="number"&&parseInt(""+h,10)===h&&h>=f&&h<=d}},m.stringWithLength=function(f){return typeof f=="string"&&!!f.length};var _={},T=v.filter,I=v.reduce,$=v.keys,x=v.isArray,N=v.includes,j=m.intRange,X=m.stringWithLength;_.schema={apiKey:{defaultValue:function(){return null},message:"is required",validate:X},appVersion:{defaultValue:function(){return null},message:"should be a string",validate:function(f){return f===null||X(f)}},appType:{defaultValue:function(){return null},message:"should be a string",validate:function(f){return f===null||X(f)}},autoNotify:{defaultValue:function(){return!0},message:"should be true|false",validate:function(f){return f===!0||f===!1}},beforeSend:{defaultValue:function(){return[]},message:"should be a function or array of functions",validate:function(f){return typeof f=="function"||x(f)&&T(f,function(d){return typeof d=="function"}).length===f.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(f,d){return f&&typeof f=="object"&&X(f.notify)&&(d.autoCaptureSessions===!1||X(f.sessions))&&T($(f),function(h){return!N(["notify","sessions"],h)}).length===0}},autoCaptureSessions:{defaultValue:function(f,d){return d.endpoints===void 0||!!d.endpoints&&!!d.endpoints.sessions},message:"should be true|false",validate:function(f){return f===!0||f===!1}},notifyReleaseStages:{defaultValue:function(){return null},message:"should be an array of strings",validate:function(f){return f===null||x(f)&&T(f,function(d){return typeof d=="string"}).length===f.length}},releaseStage:{defaultValue:function(){return"production"},message:"should be a string",validate:function(f){return typeof f=="string"&&f.length}},maxBreadcrumbs:{defaultValue:function(){return 20},message:"should be a number ≤40",validate:function(f){return j(0,40)(f)}},autoBreadcrumbs:{defaultValue:function(){return!0},message:"should be true|false",validate:function(f){return typeof f=="boolean"}},user:{defaultValue:function(){return null},message:"(object) user should be an object",validate:function(f){return typeof f=="object"}},metaData:{defaultValue:function(){return null},message:"should be an object",validate:function(f){return typeof f=="object"}},logger:{defaultValue:function(){},message:"should be null or an object with methods { debug, info, warn, error }",validate:function(f){return!f||f&&I(["debug","info","warn","error"],function(d,h){return d&&typeof f[h]=="function"},!0)}},filters:{defaultValue:function(){return["password"]},message:"should be an array of strings|regexes",validate:function(f){return x(f)&&f.length===T(f,function(d){return typeof d=="string"||d&&typeof d.test=="function"}).length}}},_.mergeDefaults=function(f,d){if(!f||!d)throw new Error("opts and schema objects are required");return I($(d),function(h,y){return h[y]=f[y]!==void 0?f[y]:d[y].defaultValue(f[y],f),h},{})},_.validate=function(f,d){if(!f||!d)throw new Error("opts and schema objects are required");var h=I($(d),function(y,g){return d[g].validate(f[g],f)?y:y.concat({key:g,message:d[g].message,value:f[g]})},[]);return{valid:!h.length,errors:h}};function J(){return J=Object.assign||function(f){for(var d=1;d<arguments.length;d++){var h=arguments[d];for(var y in h)Object.prototype.hasOwnProperty.call(h,y)&&(f[y]=h[y])}return f},J.apply(this,arguments)}var G=_.schema,L=v.map,re=m.stringWithLength,ue={releaseStage:{defaultValue:function(){return/^localhost(:\d+)?$/.test(window.location.host)?"development":"production"},message:"should be set",validate:re},logger:J({},G.logger,{defaultValue:function(){return typeof console<"u"&&typeof console.debug=="function"?ee():void 0}})},ee=function(){var f={},d=console.log;return L(["debug","info","warn","error"],function(h){var y=console[h];f[h]=typeof y=="function"?y.bind(console,"[bugsnag]"):d.bind(console,"[bugsnag]")}),f},ye=v.isoDate,Z=function(){function f(h,y,g,b){h===void 0&&(h="[anonymous]"),y===void 0&&(y={}),g===void 0&&(g="manual"),b===void 0&&(b=ye()),this.type=g,this.name=h,this.metaData=y,this.timestamp=b}var d=f.prototype;return d.toJSON=function(){return{type:this.type,name:this.name,timestamp:this.timestamp,metaData:this.metaData}},f}(),qe=Z,Qe=function(f,d,h){var y=f.length,g=0,b=function(){if(g>=y)return h(null,!1);d(f[g],function(w,S){if(w)return h(w,!1);if(S===!0)return h(null,!0);g++,b()})};b()},Nt=function(f){return f.app&&typeof f.app.releaseStage=="string"?f.app.releaseStage:f.config.releaseStage},vt=Pe;function Pe(f){switch(Object.prototype.toString.call(f)){case"[object Error]":return!0;case"[object Exception]":return!0;case"[object DOMException]":return!0;default:return f instanceof Error}}var me=vt,he=function(f,d){return function(h,y){if(typeof h!="function")return y(null,!1);try{if(h.length!==2){var g=h(f);return g&&typeof g.then=="function"?g.then(function(b){return setTimeout(function(){return y(null,P(f,b))},0)},function(b){setTimeout(function(){return d(b),y(null,!1)})}):y(null,P(f,g))}h(f,function(b,w){if(b)return d(b),y(null,!1);y(null,P(f,w))})}catch(b){d(b),y(null,!1)}}},P=function(f,d){return f.isIgnored()||d===!1},Oe={};(function(f,d){typeof Oe=="object"?Oe=d():f.StackFrame=d()})(this,function(){function f(W){return!isNaN(parseFloat(W))&&isFinite(W)}function d(W){return W.charAt(0).toUpperCase()+W.substring(1)}function h(W){return function(){return this[W]}}var y=["isConstructor","isEval","isNative","isToplevel"],g=["columnNumber","lineNumber"],b=["fileName","functionName","source"],w=["args"],S=y.concat(g,b,w);function C(W){if(W instanceof Object)for(var Me=0;Me<S.length;Me++)W.hasOwnProperty(S[Me])&&W[S[Me]]!==void 0&&this["set"+d(S[Me])](W[S[Me]])}C.prototype={getArgs:function(){return this.args},setArgs:function(W){if(Object.prototype.toString.call(W)!=="[object Array]")throw new TypeError("Args must be an Array");this.args=W},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(W){if(W instanceof C)this.evalOrigin=W;else if(W instanceof Object)this.evalOrigin=new C(W);else throw new TypeError("Eval Origin must be an Object or StackFrame")},toString:function(){var W=this.getFunctionName()||"{anonymous}",Me="("+(this.getArgs()||[]).join(",")+")",Je=this.getFileName()?"@"+this.getFileName():"",Be=f(this.getLineNumber())?":"+this.getLineNumber():"",Ge=f(this.getColumnNumber())?":"+this.getColumnNumber():"";return W+Me+Je+Be+Ge}};for(var U=0;U<y.length;U++)C.prototype["get"+d(y[U])]=h(y[U]),C.prototype["set"+d(y[U])]=function(W){return function(Me){this[W]=!!Me}}(y[U]);for(var F=0;F<g.length;F++)C.prototype["get"+d(g[F])]=h(g[F]),C.prototype["set"+d(g[F])]=function(W){return function(Me){if(!f(Me))throw new TypeError(W+" must be a Number");this[W]=Number(Me)}}(g[F]);for(var H=0;H<b.length;H++)C.prototype["get"+d(b[H])]=h(b[H]),C.prototype["set"+d(b[H])]=function(W){return function(Me){this[W]=String(Me)}}(b[H]);return C});var He={};(function(f,d){typeof He=="object"?He=d(Oe):f.ErrorStackParser=d(f.StackFrame)})(this,function(d){var h=/(^|@)\S+\:\d+/,y=/^\s*at .*(\S+\:\d+|\(native\))/m,g=/^(eval@)?(\[native code\])?$/;return{parse:function(w){if(typeof w.stacktrace<"u"||typeof w["opera#sourceloc"]<"u")return this.parseOpera(w);if(w.stack&&w.stack.match(y))return this.parseV8OrIE(w);if(w.stack)return this.parseFFOrSafari(w);throw new Error("Cannot parse given Error object")},extractLocation:function(w){if(w.indexOf(":")===-1)return[w];var S=/(.+?)(?:\:(\d+))?(?:\:(\d+))?$/,C=S.exec(w.replace(/[\(\)]/g,""));return[C[1],C[2]||void 0,C[3]||void 0]},parseV8OrIE:function(w){var S=w.stack.split(`
465
465
  `).filter(function(C){return!!C.match(y)},this);return S.map(function(C){C.indexOf("(eval ")>-1&&(C=C.replace(/eval code/g,"eval").replace(/(\(eval at [^\()]*)|(\)\,.*$)/g,""));var U=C.replace(/^\s+/,"").replace(/\(eval code/g,"("),F=U.match(/ (\((.+):(\d+):(\d+)\)$)/);U=F?U.replace(F[0],""):U;var H=U.split(/\s+/).slice(1),W=this.extractLocation(F?F[1]:H.pop()),Me=H.join(" ")||void 0,Je=["eval","<anonymous>"].indexOf(W[0])>-1?void 0:W[0];return new d({functionName:Me,fileName:Je,lineNumber:W[1],columnNumber:W[2],source:C})},this)},parseFFOrSafari:function(w){var S=w.stack.split(`
466
466
  `).filter(function(C){return!C.match(g)},this);return S.map(function(C){if(C.indexOf(" > eval")>-1&&(C=C.replace(/ line (\d+)(?: > eval line \d+)* > eval\:\d+\:\d+/g,":$1")),C.indexOf("@")===-1&&C.indexOf(":")===-1)return new d({functionName:C});var U=/((.*".+"[^@]*)?[^@]*)(?:@)/,F=C.match(U),H=F&&F[1]?F[1]:void 0,W=this.extractLocation(C.replace(U,""));return new d({functionName:H,fileName:W[0],lineNumber:W[1],columnNumber:W[2],source:C})},this)},parseOpera:function(w){return!w.stacktrace||w.message.indexOf(`
467
467
  `)>-1&&w.message.split(`
@@ -523,4 +523,4 @@ a=extmap-allow-mixed`)!==-1){const a=i.sdp.split(`
523
523
  `).filter(s=>s.trim()!=="a=extmap-allow-mixed").join(`
524
524
  `);e.RTCSessionDescription&&i instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:i.type,sdp:a}):i.sdp=a}return t.apply(this,arguments)}}function Sl(e,r){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;const t=e.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(r.browser==="chrome"&&r.version<78||r.browser==="firefox"&&r.version<68||r.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Tl(e,r){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;const t=e.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(e.RTCPeerConnection.prototype.setLocalDescription=function(){let i=arguments[0]||{};if(typeof i!="object"||i.type&&i.sdp)return t.apply(this,arguments);if(i={type:i.type,sdp:i.sdp},!i.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":i.type="offer";break;default:i.type="answer";break}return i.sdp||i.type!=="offer"&&i.type!=="answer"?t.apply(this,[i]):(i.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(s=>t.apply(this,[s]))})}const zZ=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:Iv,shimAddIceCandidateNullOrEmpty:Sl,shimConnectionState:$v,shimMaxMessageSize:_l,shimParameterlessSetLocalDescription:Tl,shimRTCIceCandidate:bl,shimRTCIceCandidateRelayProtocol:Rv,shimSendThrowTypeError:wl},Symbol.toStringTag,{value:"Module"}));function WZ({window:e}={},r={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const t=I$,n=UZ(e),i={browserDetails:n,commonShim:zZ,extractVersion:yl,disableLog:jZ,disableWarnings:FZ,sdp:qZ};switch(n.browser){case"chrome":if(!A0||!Ev||!r.shimChrome)return t("Chrome shim is not included in this adapter release."),i;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),i;t("adapter.js shimming chrome."),i.browserShim=A0,Sl(e,n),Tl(e),A$(e,n),P$(e),Ev(e,n),M$(e),D$(e,n),x$(e),N$(e),j$(e,n),bl(e),Rv(e),$v(e),_l(e,n),wl(e),Iv(e,n);break;case"firefox":if(!P0||!kv||!r.shimFirefox)return t("Firefox shim is not included in this adapter release."),i;t("adapter.js shimming firefox."),i.browserShim=P0,Sl(e,n),Tl(e),F$(e,n),kv(e,n),U$(e),z$(e),B$(e),q$(e),W$(e),H$(e),G$(e),V$(e),K$(e),bl(e),$v(e),_l(e,n),wl(e);break;case"safari":if(!M0||!r.shimSafari)return t("Safari shim is not included in this adapter release."),i;t("adapter.js shimming safari."),i.browserShim=M0,Sl(e,n),Tl(e),eI(e),rI(e),X$(e),J$(e),Y$(e),tI(e),Q$(e),nI(e),bl(e),Rv(e),_l(e,n),wl(e),Iv(e,n);break;default:t("Unsupported browser!");break}return i}WZ({window:typeof window>"u"?void 0:window});var aa={},sI={},oI={exports:{}},x0=oI.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var r="candidate:%s %d %s %d %s %d typ %s";return r+=e.raddr!=null?" raddr %s rport %d":"%v%v",r+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(r+=" generation %d"),r+=e["network-id"]!=null?" network-id %d":"%v",r+=e["network-cost"]!=null?" network-cost %d":"%v",r}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var r="ssrc:%d";return e.attribute!=null&&(r+=" %s",e.value!=null&&(r+=":%s")),r}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var r="mediaclk:";return r+=e.id!=null?"id=%s %s":"%v%s",r+=e.mediaClockValue!=null?"=%s":"",r+=e.rateNumerator!=null?" rate=%s":"",r+=e.rateDenominator!=null?"/%s":"",r}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(x0).forEach(function(e){var r=x0[e];r.forEach(function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")})});var uI=oI.exports;(function(e){var r=function(o){return String(Number(o))===o?Number(o):o},t=function(o,u,c,l){if(l&&!c)u[l]=r(o[1]);else for(var p=0;p<c.length;p+=1)o[p+1]!=null&&(u[c[p]]=r(o[p+1]))},n=function(o,u,c){var l=o.name&&o.names;o.push&&!u[o.push]?u[o.push]=[]:l&&!u[o.name]&&(u[o.name]={});var p=o.push?{}:l?u[o.name]:u;t(c.match(o.reg),p,o.names,o.name),o.push&&u[o.push].push(p)},i=uI,a=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(o){var u={},c=[],l=u;return o.split(/(\r\n|\r|\n)/).filter(a).forEach(function(p){var v=p[0],m=p.slice(2);v==="m"&&(c.push({rtp:[],fmtp:[]}),l=c[c.length-1]);for(var _=0;_<(i[v]||[]).length;_+=1){var T=i[v][_];if(T.reg.test(m))return n(T,l,m)}}),u.media=c,u};var s=function(o,u){var c=u.split(/=(.+)/,2);return c.length===2?o[c[0]]=r(c[1]):c.length===1&&u.length>1&&(o[c[0]]=void 0),o};e.parseParams=function(o){return o.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(o){return o.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(o){for(var u=[],c=o.split(" ").map(r),l=0;l<c.length;l+=3)u.push({component:c[l],ip:c[l+1],port:c[l+2]});return u},e.parseImageAttributes=function(o){return o.split(" ").map(function(u){return u.substring(1,u.length-1).split(",").reduce(s,{})})},e.parseSimulcastStreamList=function(o){return o.split(";").map(function(u){return u.split(",").map(function(c){var l,p=!1;return c[0]!=="~"?l=r(c):(l=r(c.substring(1,c.length)),p=!0),{scid:l,paused:p}})})}})(sI);var rh=uI,HZ=/%[sdv%]/g,GZ=function(e){var r=1,t=arguments,n=t.length;return e.replace(HZ,function(i){if(r>=n)return i;var a=t[r];switch(r+=1,i){case"%%":return"%";case"%s":return String(a);case"%d":return Number(a);case"%v":return""}})},Ho=function(e,r,t){var n=r.format instanceof Function?r.format(r.push?t:t[r.name]):r.format,i=[e+"="+n];if(r.names)for(var a=0;a<r.names.length;a+=1){var s=r.names[a];r.name?i.push(t[r.name][s]):i.push(t[r.names[a]])}else i.push(t[r.name]);return GZ.apply(null,i)},VZ=["v","o","s","i","u","e","p","c","b","t","r","z","a"],KZ=["i","c","b","a"],JZ=function(e,r){r=r||{},e.version==null&&(e.version=0),e.name==null&&(e.name=" "),e.media.forEach(function(a){a.payloads==null&&(a.payloads="")});var t=r.outerOrder||VZ,n=r.innerOrder||KZ,i=[];return t.forEach(function(a){rh[a].forEach(function(s){s.name in e&&e[s.name]!=null?i.push(Ho(a,s,e)):s.push in e&&e[s.push]!=null&&e[s.push].forEach(function(o){i.push(Ho(a,s,o))})})}),e.media.forEach(function(a){i.push(Ho("m",rh.m[0],a)),n.forEach(function(s){rh[s].forEach(function(o){o.name in a&&a[o.name]!=null?i.push(Ho(s,o,a)):o.push in a&&a[o.push]!=null&&a[o.push].forEach(function(u){i.push(Ho(s,o,u))})})})}),i.join(`\r
525
525
  `)+`\r
526
- `},ws=sI,YZ=JZ;aa.write=YZ;aa.parse=ws.parse;aa.parseParams=ws.parseParams;aa.parseFmtpConfig=ws.parseFmtpConfig;aa.parsePayloads=ws.parsePayloads;aa.parseRemoteCandidates=ws.parseRemoteCandidates;aa.parseImageAttributes=ws.parseImageAttributes;aa.parseSimulcastStreamList=ws.parseSimulcastStreamList;var sa={},XZ=Ne&&Ne.__spreadArrays||function(){for(var e=0,r=0,t=arguments.length;r<t;r++)e+=arguments[r].length;for(var n=Array(e),i=0,r=0;r<t;r++)for(var a=arguments[r],s=0,o=a.length;s<o;s++,i++)n[i]=a[s];return n};Object.defineProperty(sa,"__esModule",{value:!0});var cI=function(){function e(r,t,n){this.name=r,this.version=t,this.os=n}return e}();sa.BrowserInfo=cI;var lI=function(){function e(r){this.version=r,this.name="node",this.os=process.platform}return e}();sa.NodeInfo=lI;var fI=function(){function e(){this.bot=!0,this.name="bot",this.version=null,this.os=null}return e}();sa.BotInfo=fI;var QZ=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,ZZ=/(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp)|(MSNBot)|(Ask Jeeves\/Teoma)|(ia_archiver)/,N0=3,eee=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["vivaldi",/Vivaldi\/([0-9\.]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/Edg\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FBAV\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["searchbot",QZ]],L0=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/],["Search Bot",ZZ]];function tee(e){return e?Ov(e):typeof navigator<"u"?Ov(navigator.userAgent):pI()}sa.detect=tee;function Ov(e){var r=e!==""&&eee.reduce(function(a,s){var o=s[0],u=s[1];if(a)return a;var c=u.exec(e);return!!c&&[o,c]},!1);if(!r)return null;var t=r[0],n=r[1];if(t==="searchbot")return new fI;var i=n[1]&&n[1].split(/[._]/).slice(0,3);return i?i.length<N0&&(i=XZ(i,ree(N0-i.length))):i=[],new cI(t,i.join("."),dI(e))}sa.parseUserAgent=Ov;function dI(e){for(var r=0,t=L0.length;r<t;r++){var n=L0[r],i=n[0],a=n[1],s=a.test(e);if(s)return i}return null}sa.detectOS=dI;function pI(){var e=typeof process<"u"&&process.version;return e?new lI(process.version.slice(1)):null}sa.getNodeVersion=pI;function ree(e){for(var r=[],t=0;t<e;t++)r.push("0");return r}var Qc={exports:{}};function nee(e,r){if(typeof e[Symbol.iterator]=="function")for(const t of e){const n=Array.isArray(t)?t[1]:t;r(n)}else for(const t in e)if(e.hasOwnProperty(t)){const n=e[t];r(n)}}var hI={iterateReports:nee};const iee={"outbound-rtp":{packetsSent:"audioSentPackets",bytesSent:"audioSentBytes"},"inbound-rtp":{packetsReceived:"audioRecvPackets",packetsLost:"audioRecvPacketsLost",bytesReceived:"audioRecvBytes",jitter:"audioRecvJitter"},"remote-inbound-rtp":{packetsLost:"audioSentPacketsLost",roundTripTime:"audioRtt",jitter:"audioSentJitter"}},aee={"remote-candidate":function(e){return Zc(e)},"inbound-rtp":function(e){return Zc(e)},"outbound-rtp":function(e){return Zc(e)},"remote-inbound-rtp":function(e){return Zc(e)}},Zc=e=>{const{type:r}=e,t=iee[r],n={};for(let i in t)if(i in e){let a;typeof t[i]=="function"?a=t[i](e):a=t[i],n[a]=e[i]}else n[t[i]]=null;return n};var see={parsers:aee};const{iterateReports:oee}=hI;function uee(e){let r=0,t=0,n=0,i=100,a=0,s,o,u;return oee(e,c=>{c.type==="inbound-rtp"&&(r=c.jitter,n=c.packetsLost,t=c.packetsReceived)}),t+n>0&&(a=100*(n/(t+n))),s=i+r*2+10,s<160?o=93.2-s/40:o=93.2-(s-120)/10,o=o-a*2.5,o<1&&(o=1),u=1+.035*o+7e-6*o*(o-60)*(100-o),parseFloat(u).toFixed(6)}var vI=uee;const{iterateReports:cee}=hI,{parsers:D0}=see,lee=vI;function fee(e){const r={};return cee(e,t=>{if(t.type in D0){const n=D0[t.type](t);Object.assign(r,n)}}),r.networkMos=parseFloat(lee(e)),r}var dee=fee,j0;function pee(){return j0||(j0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(r,"__esModule",{value:!0});const n=dee,i=vI,a=t(Ii());class s{constructor(u){this.mos_report={min:5,max:0},this._reportsCount=0,this._mosSum=0,this.intervals=[],this._deprecationWarningSent=!1,!(!u||!u.application||!u.rtc_id||!u.pc)&&(this.conversation=null,this.application_id=null,this.attachHandlers(u),this.startSendingStats(u),this.startEmittingStats(u))}attachHandlers(u){const{pc:c}=u;c.addEventListener("connectionstatechange",()=>{switch(c.connectionState){case"disconnected":case"failed":case"closed":this.removeIntervals(),this.emitLastReport(u)}}),u.conversation?u.conversation.on("member:media",(p,v)=>{!this.application_id&&(u==null?void 0:u.rtc_id)===v.body.channel.id&&(this.application_id=v.application_id)}):u.application.on("member:joined",(p,v)=>{(!this.conversation||!this.application_id)&&(u==null?void 0:u.rtc_id)===v.body.channel.id&&(this.conversation=p.conversation,this.application_id=v.application_id)})}emitLastReport(u){const{application:c,conversation:l=null,rtc_id:p,config:{emit_events:v,emit_rtc_analytics:m}}=u,_=this.getMOSReport(),T=_.last;T&&(m&&c.emit("rtcstats:analytics",{type:"mos_report",mos:T,rtc_id:p,mos_report:_,api_key:c.session.apiKey,...this.application_id&&{application_id:this.application_id},...l&&{conversation_id:l.id,conversation_name:l.name}}),v&&(this._deprecationWarningSent||(this._deprecationWarningSent=!0,console.warn('"rtcstats:report" event is deprecated. Use "rtcstats:analytics" instead')),c.emit("rtcstats:report",T,null,l,_)))}startSendingStats(u){const{application:c,conversation:l=null,pc:p,rtc_id:v,config:{remote_collection:m,remote_collection_url:_,remote_collection_interval:T}}=u;if(!m)return;const I=setInterval(()=>{p.getStats(null).then($=>{var x;const N=(x=l??this.conversation)!==null&&x!==void 0?x:null;a.default.networkRequest({url:_,type:"POST",data:{...n($),legId:v,apiKey:c.session.apiKey,...this.application_id&&{applicationId:this.application_id},...N&&{conversationId:N.id,conversationName:N.name}}}).catch(()=>{})}).catch(()=>{}),(p.connectionState==="closed"||p.signalingState==="closed")&&this.removeIntervals()},T);this.intervals.push(I)}startEmittingStats(u){const{application:c,conversation:l=null,pc:p,rtc_id:v,config:{emit_events:m,emit_rtc_analytics:_,emit_interval:T}}=u;if(!m&&!_)return;const I=setInterval(()=>{var $;p.getStats(null).then(x=>{var N;const j=this.getMos(x);if(!j)return;const X=(N=l??this.conversation)!==null&&N!==void 0?N:null;_&&c.emit("rtcstats:analytics",{type:"mos",mos:j,report:x,rtc_id:v,api_key:c.session.apiKey,...this.application_id&&{application_id:this.application_id},...X&&{conversation_id:X.id,conversation_name:X.name}}),m&&(this._deprecationWarningSent||(this._deprecationWarningSent=!0,console.warn('"rtcstats:report" event is deprecated. Use "rtcstats:analytics" instead')),c.emit("rtcstats:report",j,x,l))}).catch(()=>{}),(p.connectionState==="closed"||p.signalingState==="closed")&&(this.removeIntervals(),this.emitLastReport({...u,conversation:($=l??this.conversation)!==null&&$!==void 0?$:null}))},T);this.intervals.push(I)}removeIntervals(){this.intervals.forEach(u=>clearInterval(u)),this.intervals=[]}getMos(u){const c=i(u);return this.updateMOSReport(parseInt(c)),c}updateMOSReport(u){this._reportsCount++,this._mosSum+=u,this.mos_report.last=u,this.mos_report.min=u<this.mos_report.min?u:this.mos_report.min,this.mos_report.max=u>this.mos_report.max?u:this.mos_report.max,this.mos_report.average=this._mosSum/this._reportsCount}getMOSReport(){return this.mos_report.min=s.normaliseFloat(this.mos_report.min),this.mos_report.max=s.normaliseFloat(this.mos_report.max),this.mos_report.last=s.normaliseFloat(this.mos_report.last),this.mos_report.average=s.normaliseFloat(this.mos_report.average),this.mos_report}static normaliseFloat(u){return parseFloat(u).toFixed(6)}}r.default=s,e.exports=s}(Qc,Qc.exports)),Qc.exports}var F0;function Wf(){return F0||(F0=1,function(e,r){var t=Ne&&Ne.__createBinding||(Object.create?function(m,_,T,I){I===void 0&&(I=T),Object.defineProperty(m,I,{enumerable:!0,get:function(){return _[T]}})}:function(m,_,T,I){I===void 0&&(I=T),m[I]=_[T]}),n=Ne&&Ne.__setModuleDefault||(Object.create?function(m,_){Object.defineProperty(m,"default",{enumerable:!0,value:_})}:function(m,_){m.default=_}),i=Ne&&Ne.__importStar||function(m){if(m&&m.__esModule)return m;var _={};if(m!=null)for(var T in m)T!=="default"&&Object.hasOwnProperty.call(m,T)&&t(_,m,T);return n(_,m),_},a=Ne&&Ne.__importDefault||function(m){return m&&m.__esModule?m:{default:m}};Object.defineProperty(r,"__esModule",{value:!0});const s=aa,o=Ar,u=i(sa),c=Hn,l=a(pee()),p=2e4;class v{constructor(){this.log=o.getLogger(this.constructor.name)}static getUserAudio(_=!0){let T={video:!1,audio:_};return navigator.mediaDevices.getUserMedia(T)}createRTCPeerConnection(_){const T=new RTCPeerConnection(_);return T.trace=()=>{},T}_getWindowLocationProtocol(){return window.location.protocol}static _getBrowserName(){return u.detect().name}static isNode(){return this._getBrowserName()==="node"}checkValidKeys(_,T){let I=!0;return Object.keys(_).forEach($=>{T.hasOwnProperty($)||(I=!1)}),I}static cleanCallMediaIfFailed(_){setTimeout(()=>{_.conversation||(this.cleanMediaProperties(_),_.status=_.CALL_STATUS.FAILED,_.application.emit("call:status:changed",_))},5e3)}static callDisconnectHandler(_,T){const I=[_.CALL_STATUS.ANSWERED,_.CALL_STATUS.STARTED,_.CALL_STATUS.RINGING];if(!(T.connectionState!=="disconnected"||!_||!_.conversation))return setTimeout(()=>{T.connectionState==="connected"||I.indexOf(_.status)==-1||(this.cleanMediaProperties(_),_.status=_.CALL_STATUS.COMPLETED,_.application.emit("call:status:changed",_))},p)}static cleanMediaProperties(_){if(_.rtcObjects)for(const T in _.rtcObjects)_.rtcObjects[T].pc.close(),delete _.rtcObjects[T].pc,v.closeStream(_.rtcObjects[T].stream);_.application.activeStreams=[],_.rtcObjects={},_.conversation&&_.conversation.media&&(_.conversation.media.rtcStats=null)}static cleanConversationMediaProperties(_,T){T&&v.closeStream(T),_&&_.close()}static playAudioStream(_){const T=new Audio;return T.srcObject=_,T.autoplay=!0,T}static createDummyCandidateSDP(_){const T={foundation:1176891032,component:1,transport:"udp",priority:2122260223,ip:"0.0.0.0",port:9,type:"host",generation:0,"network-id":1,"network-cost":50},I=s.parse(_.localDescription.sdp);return I.media[0].candidates=[T],s.write(I)}static createRTCPeerConnectionConfig(_){return{iceTransportPolicy:"all",bundlePolicy:"balanced",rtcpMuxPolicy:"require",iceCandidatePoolSize:"0",..._.session.config&&_.session.config.iceServers&&{iceServers:_.session.config.iceServers}}}static setupPeerConnectionApplicationListeners(_,T){T.addEventListener("icecandidateerror",I=>_.emit("rtc:icecandidateerror",I)),T.addEventListener("icegatheringstatechange",()=>_.emit("rtc:icegatheringstatechange",T.iceGatheringState)),T.addEventListener("signalingstatechange",()=>_.emit("rtc:signalingstatechange",T.signalingState)),T.addEventListener("iceconnectionstatechange",()=>_.emit("rtc:iceconnectionstatechange",T.iceConnectionState)),T.addEventListener("connectionstatechange",()=>_.emit("rtc:peerconnectionstatechange",T.connectionState))}static createPeerConnection(_){const T=this.createRTCPeerConnectionConfig(_),I=new RTCPeerConnection(T);return this.setupPeerConnectionApplicationListeners(_,I),I}static sendOffer(_,T,I,$){const N={sdp:this.createDummyCandidateSDP(T)};let j={from:I.me.id,body:{offer:N}},X=`conversations/${I.id}/rtc`;return $&&(X+=`/${$}/offer`),_.session.sendNetworkRequest({type:"POST",path:X,data:j})}static sendAnswer(_,T,I,$){const x=this.createDummyCandidateSDP(T);let N={from:I.me.id,body:{answer:x}},j=`conversations/${I.id}/rtc/${$}/answer`;return _.session.sendNetworkRequest({type:"POST",path:j,data:N})}static createLeg(_,T){const $={sdp:this.createDummyCandidateSDP(T),type:"offer"};return _.session.sendNetworkRequest({type:"POST",path:"legs",version:"beta",data:{body:{offer:$}}})}static closeStream(_){_.getTracks().forEach(T=>{T.stop()})}static emitMediaStream(_,T,I){_.emit("media:stream:on",{pc:T,stream:I,type:"audio",streamIndex:0})}static _initStatsEvents(_){var T,I,$;if(!v.isNode()&&!(($=(I=(T=_==null?void 0:_.application)===null||T===void 0?void 0:T.session)===null||I===void 0?void 0:I.config)===null||$===void 0)&&$.rtcstats){const x=_.application.session.config.rtcstats,{emit_events:N,remote_collection:j,emit_rtc_analytics:X}=x;if(N||j||X){const J={..._,config:{...x}};return new l.default(J)}}}static attachConversationEventHandlers(_){const{conversation:T,pc:I,log:$}=_;T.once("rtc:answer",x=>{if(!I){$.warn("RTC: received an answer too late");return}I.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:x.body.answer}))})}static doAnswer(_,T,I){const{application:$,conversation:x,pc:N,reject:j,localStream:X}=_;this.addPeerConnectionListeners(_,()=>v.sendAnswer($,N,x,I).then(()=>({rtc_id:I}))),N.setRemoteDescription(new RTCSessionDescription({type:"offer",sdp:T})).then(()=>N.createAnswer()).then(J=>N.setLocalDescription(J)).catch(J=>{v.cleanConversationMediaProperties(N,X),j(J)})}static attachPeerConnectionEventHandlers(_){const{application:T,conversation:I,pc:$,reconnectRtcId:x}=_;this.addPeerConnectionListeners(_,()=>v.sendOffer(T,$,I,x))}static addPeerConnectionListeners(_,T){const{application:I,conversation:$,pc:x,streamIndex:N,localStream:j,log:X,rtcObjects:J,resolve:G,reject:L}=_;let re,ue=!1,ee;$.id&&(ee=I.calls.get($.id)),x.ontrack=ye=>{re=ye.streams[0],I.activeStreams.push(re),v.emitMediaStream($.me,x,re)},x.addEventListener("connectionstatechange",ye=>this.onconnectionstatechangeHandler(x,X,ee,()=>G(re),()=>{v.cleanConversationMediaProperties(x,j),L()})),x.addEventListener("negotiationneeded",()=>this.onnegotiationneededHandler(x,ye=>{v.cleanConversationMediaProperties(x,j),L(ye)})),x.addEventListener("iceconnectionstatechange",ye=>this.oniceconnectionstatechange(ye,x,X,Z=>{v.cleanConversationMediaProperties(x,j),L(Z)})),x.addEventListener("icecandidate",async ye=>{if(ye.candidate&&!ue&&x){ue=!0;try{const{rtc_id:Z}=await T();v._initStatsEvents({application:I,rtc_id:Z,pc:x,conversation:$}),x.trace&&x.trace("rtc_id",Z),J[Z]={rtc_id:Z,pc:x,stream:j,type:"audio",streamIndex:N}}catch(Z){v.cleanConversationMediaProperties(x,j),L(new c.NexmoClientError(Z))}}}),j.getTracks().forEach(ye=>x.addTrack(ye))}static prewarmLeg(_){const T=_.application;return new Promise(async(I,$)=>{let x=!1,N,j,X={},J,G;const L=o.getLogger(this.constructor.name);try{G=await this.getUserAudio(),J=this.createPeerConnection(T),J.ontrack=re=>{N=re.streams[0],T.activeStreams.push(N)},J.addEventListener("connectionstatechange",re=>this.onconnectionstatechangeHandler(J,L,_,()=>I({stream:N,legId:j,rtcObjects:X}),()=>{v.cleanConversationMediaProperties(J,G),$()})),J.addEventListener("negotiationneeded",()=>this.onnegotiationneededHandler(J,re=>{v.cleanConversationMediaProperties(J,G),$(re)})),J.addEventListener("iceconnectionstatechange",re=>this.oniceconnectionstatechange(re,J,L,ue=>{v.cleanConversationMediaProperties(J,G),$(ue)})),J.addEventListener("icecandidate",async re=>{if(re.candidate&&!x&&J){x=!0;const{rtc_id:ue,sdp:ee}=await this.createLeg(T,J);return v._initStatsEvents({application:T,rtc_id:ue,pc:J}),j=ue,X[j]={rtc_id:ue,pc:J,stream:G,type:"audio",streamIndex:1},J.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:ee}))}}),G.getTracks().forEach(re=>J.addTrack(re))}catch(re){v.cleanConversationMediaProperties(J,G),$(new c.NexmoClientError(re))}})}}r.default=v,v.onconnectionstatechangeHandler=(m,_,T,I,$)=>{switch(m.connectionState){case"connected":_.info("The connection has become fully connected"),I();break;case"disconnected":if(!T)break;T.call_disconnect_timeout&&clearTimeout(T.call_disconnect_timeout),T.call_disconnect_timeout=v.callDisconnectHandler(T,m);break;case"failed":$(),_.info("One or more transports has terminated unexpectedly or in an error");break;case"closed":_.info("The connection has been closed");break}},v.oniceconnectionstatechange=(m,_,T,I)=>{switch(_.iceConnectionState){case"disconnected":T.warn("One or more transports is disconnected",_.iceConnectionState);break;case"failed":I(new c.NexmoClientError(m)),T.warn("One or more transports has terminated unexpectedly or in an error",m);break;default:T.info("The ice connection status changed",_.iceConnectionState)}},v.onnegotiationneededHandler=async(m,_)=>{try{const T=await m.createOffer();return m.setLocalDescription(T)}catch(T){_(new c.NexmoClientError(T))}},e.exports=v}(Xc,Xc.exports)),Xc.exports}var U0;function hee(){return U0||(U0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(p){return p&&p.__esModule?p:{default:p}};Object.defineProperty(r,"__esModule",{value:!0});const n=Ar,i=Hn,a=t(Wf()),s=t(Ii()),o=t(ia),u=t(yI()),c=t(Gf());class l{constructor(v){var m,_,T;const I=v instanceof u.default?v:null,$=v instanceof c.default?v:null;this.log=n.getLogger(this.constructor.name),I?(this.rtcHelper=new a.default,this.application=I.application,this.application.activeStreams=this.application.activeStreams||[],this.parentConversation=I,this.rtcObjects={},this.streamIndex=0,this.rtcstats_conf=((T=(_=(m=this.application)===null||m===void 0?void 0:m.session)===null||_===void 0?void 0:_.config)===null||T===void 0?void 0:T.rtcStats)||{},this.rtcStats=null):$?(this.rtcHelper=new a.default,this.application=$):this.log.warn("No conversation object in Media")}_attachEndingEventHandlers(){this.parentConversation&&(this.log.debug("attaching leave listeners in media for "+this.parentConversation.id),this.parentConversation.on("rtc:hangup",async v=>{let m;if(this.parentConversation.members.has(v.from))m=this.parentConversation.members.get(v.from);else try{m=await this.parentConversation.getMember(v.from)}catch(_){this.log.warn(`There is an error getting the member ${_}`)}m.user.id===this.application.me.id&&this.application.activeStreams.length&&this._cleanMediaProperties(),m.user.id===this.application.me.id&&m.transferred_from&&m.transferred_from.media._cleanMediaProperties(),m.user.id===this.application.me.id&&this.parentConversation.off("rtc:hangup")}))}_enableStatsEvents(){this.rtcstats_conf.emit_rtc_analytics=!0,this.rtcstats_conf.remote_collection=!0;const v=this._findRtcObjectByType("audio");!this.rtcStats&&v&&(this.log.debug(`enabling stats events for ${v.rtc_id}`),this.rtcStats=a.default._initStatsEvents({application:this.application,rtc_id:v.rtc_id,pc:this.pc,conversation:this.parentConversation}))}_disableStatsEvents(){this.rtcstats_conf.emit_events=!1,this.rtcstats_conf.emit_rtc_analytics=!1,this.rtcstats_conf.remote_collection=!1,this.rtcStats.removeIntervals(),delete this.rtcStats}_audioInitHandler(v={},m){return new Promise(async(_,T)=>{const I=this.streamIndex;this.streamIndex++;const{audioConstraints:$}=v;try{const x=await a.default.getUserAudio($),N=a.default.createPeerConnection(this.application);this.pc=N;const{application:j,log:X,parentConversation:J,rtcObjects:G}=this,L={pc:N,streamIndex:I,localStream:x,application:j,conversation:J,log:X,rtcObjects:G};m({...L,resolve:_,reject:T}),a.default.attachConversationEventHandlers(L),this._attachEndingEventHandlers()}catch(x){T(new i.NexmoClientError(x))}})}_execAnswer(v={}){const{offer:{sdp:m,leg_id:_}}=v;return this._audioInitHandler(v,T=>a.default.doAnswer(T,m,_))}_handleAudio(v={}){const{reconnectRtcId:m}=v;return this._audioInitHandler(v,_=>a.default.attachPeerConnectionEventHandlers({..._,reconnectRtcId:m}))}_findRtcObjectByType(v){return Object.values(this.rtcObjects).find(m=>m.type===v)}async _cleanConversationProperties(){this.pc&&this.pc.close(),delete this.pc,this.rtcStats=null,this.application.activeStreams=[],this.listeningToRtcEvent=!1,await Promise.resolve()}_cleanMediaProperties(){if(this.pc&&this.pc.close(),this.rtcObjects)for(const v in this.rtcObjects)a.default.closeStream(this.rtcObjects[v].stream);delete this.pc,this.rtcStats=null,this.application.activeStreams=[],this.rtcObjects={},this.listeningToRtcEvent=!1}async _disableLeg(v){const m=new Promise(async(T,I)=>{try{await this.application.session.sendNetworkRequest({type:"DELETE",path:`conversations/${this.parentConversation.id}/rtc/${v}?from=${this.parentConversation.me.id}&originating_session=${this.application.session.session_id}`,version:"beta2"}),T("rtc:terminate:success")}catch($){I(new i.NexmoApiError($))}}),_=new Promise(T=>{this.rtcObjects[v].pc&&this.rtcObjects[v].pc.close(),this.rtcObjects[v].stream&&a.default.closeStream(this.rtcObjects[v].stream),T()});try{return await Promise.all([m,_]),this.parentConversation.me.emit("media:stream:off",this.rtcObjects[v].streamIndex),delete this.rtcObjects[v],"rtc:terminate:success"}catch(T){throw T}}_enableMediaTracks(v,m){v.forEach(_=>{_.enabled=m})}async _setMediaTracksAndMute(v,m,_,T){this._enableMediaTracks(m,!_);try{return await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:T,to:this.parentConversation.me.id,from:this.parentConversation.me.id,body:{rtc_id:v}}})}catch(I){throw this._enableMediaTracks(m,_),new i.NexmoApiError(I)}}async updateAudioConstraints(v={}){let m=this._findRtcObjectByType("audio");if(m&&m.pc)try{const _=await a.default.getUserAudio(v);return _.getTracks().forEach(T=>{const I=m.pc.getSenders().find($=>$.track.kind===T.kind);I&&(T.enabled=I.track.enabled,I.replaceTrack(T))}),a.default.closeStream(m.stream),m.stream=_,_}catch(_){return _}else throw new i.NexmoApiError("error:media:stream:not-found")}mute(v=!1,m=null){const T="audio:mute:"+(v?"on":"off");let I=[],$={};if(m!==null){if($[0]=Object.values(this.rtcObjects).find(x=>x.streamIndex===m),!$[0])throw new i.NexmoClientError("error:media:stream:not-found")}else $=this.rtcObjects;return Object.values($).forEach(x=>{const N=x.stream.getAudioTracks(),j=this._setMediaTracksAndMute(x.rtc_id,N,v,T);I.push(j)}),Promise.all(I)}async earmuff(v){try{if(this.me===null)throw new i.NexmoClientError("error:self");{let m="audio:earmuff:off";v&&(m="audio:earmuff:on");const{response:_}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:m,to:this.parentConversation.me.id}});return _}}catch(m){throw new i.NexmoApiError(m)}}async enable(v){try{if(this.parentConversation.me===null)throw new i.NexmoClientError("error:self");{const{offer:m}=v??{};let _=await(m!==void 0?this._execAnswer(v):this._handleAudio(v)),T=v&&(v.autoPlayAudio||v.autoPlayAudio===void 0);return(!v||T)&&a.default.playAudioStream(_),_}}catch(m){throw m}}disable(){let v=[];v.push(this._cleanConversationProperties());for(const m in this.rtcObjects)v.push(this._disableLeg(m));return Promise.all(v)}async sayText(v){try{const m=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:say",cid:this.parentConversation.id,from:this.parentConversation.me.id,body:{text:v.text,voice_name:v.voice_name||"Amy",level:v.level||1,queue:v.queue||!0,loop:v.loop||1,ssml:v.ssml||!1}}});return new o.default(this.parentConversation,m)}catch(m){throw new i.NexmoApiError(m)}}async sendDTMF(v){try{if(!s.default.validateDTMF(v))throw new i.NexmoClientError("error:audio:dtmf:invalid-digit");if(!(this._findRtcObjectByType("audio")||{}).rtc_id)throw new i.NexmoClientError("error:audio:dtmf:audio-disabled");const{id:_,timestamp:T}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:dtmf",from:this.parentConversation.me.id,body:{digit:v,channel:{type:"app",id:this._findRtcObjectByType("audio").rtc_id}}}}),I={body:{digit:v,dtmf_id:""},cid:this.parentConversation.id,from:this.parentConversation.me.id,id:_,timestamp:T,type:"audio:dtmf"},$=new o.default(this.parentConversation,I);return this.parentConversation.events.set(I.id,$),$}catch(m){throw new i.NexmoApiError(m)}}async playStream(v){try{const m=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:play",body:v}});return new o.default(this.parentConversation,m)}catch(m){throw new i.NexmoApiError(m)}}async startRinging(){try{const v=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:ringing:start",from:this.parentConversation.me.id,body:{}}});return new o.default(this.parentConversation,v)}catch(v){throw new i.NexmoApiError(v)}}async stopRinging(){try{const v=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:ringing:stop",from:this.parentConversation.me.id,body:{}}});return new o.default(this.parentConversation,v)}catch(v){throw new i.NexmoApiError(v)}}}r.default=l,e.exports=l}(Yc,Yc.exports)),Yc.exports}var el={exports:{}},tl={exports:{}},B0;function mI(){return B0||(B0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(r,"__esModule",{value:!0});const n=t(Ii()),i=Ar,a=t(ia);class s extends a.default{constructor(u,c){super(u,c),this.log=i.getLogger(this.constructor.name),this.type="image",this.conversation=u,this.state={seen_by:{},delivered_to:{}},c&&c.body&&c.body.timestamp&&(this.timestamp=c.body.timestamp),Object.assign(this,c)}seen(){return super.seen()}delivered(){return super.delivered()}async del(){return await n.default.networkRequest({type:"DELETE",url:this.body.representations.original.url,token:this.conversation.application.session.config.token}),super.del()}async fetchImage(u="thumbnail",c=this.body.representations){try{return n.default._fetchImage(c[u].url,this.conversation.application.session.config.token)}catch(l){throw this.log.error(l),l}}}r.default=s,e.exports=s}(tl,tl.exports)),tl.exports}var q0;function vee(){return q0||(q0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(r,"__esModule",{value:!0});const n=Ar,i=t(ia),a=t(jg),s=t(mI()),o=t(Fg());class u{constructor(l,p){this.log=n.getLogger(this.constructor.name),this.application=l,this.conversation=p,this.constructed_event=null,this._handleEventMap={"event:delete":this._processDelete,image:this._processImage,"image:delivered":this._processDelivered,"image:seen":this._processSeen,"member:invited":this._processMember,"member:joined":this._processMember,"member:left":this._processMember,"audio:ringing:start":this._processMember,"leg:status:update":this._processLegStatus,"member:media":this._processMedia,text:this._processText,"text:delivered":this._processDelivered,"text:seen":this._processSeen,"audio:mute:on":this._processMuteForMedia,"audio:mute:off":this._processMuteForMedia,message:this._processMessage,"message:delivered":this._processDelivered,"message:seen":this._processSeen,"message:submitted":this._processSubmitted,"message:rejected":this._processRejected,"message:undeliverable":this._processUndeliverable}}handleEvent(l){return this._handleEventMap.hasOwnProperty(l.type)?this._handleEventMap[l.type].call(this,l)||new i.default(this.conversation,l):new i.default(this.conversation,l)}_processDelivered(l){let p=this.conversation.events.get(l.body.event_id);return p?(p.state=p.state||{},p.state.delivered_to=p.state.delivered_to||{},p.state.delivered_to[l.from]=l.timestamp,p):(this.log.warn("NXMEvent not found"),null)}_processDelete(l){var p;let v=this.conversation.events.get((p=l==null?void 0:l.body)===null||p===void 0?void 0:p.event_id);return v?(v.body.text&&(v.body.text=""),v.body.representations&&(v.body.representations=""),v.body.timestamp={deleted:l.timestamp},v):(this.log.warn("NXMEvent not found"),null)}_processImage(l){var p;const v=new s.default(this.conversation,l);return((p=this.conversation.me)===null||p===void 0?void 0:p.id)!==v.from&&v.delivered(),v}_processMember(l){return this.application.calls.has(this.conversation.id)&&this.application.calls.get(this.conversation.id)._handleStatusChange(l),this.conversation.members.has(l.from)&&this.conversation.members.get(l.from)._handleEvent(l),new i.default(this.conversation,l)}_processLegStatus(l){return this.conversation.members.has(l.from)&&this.conversation.members.get(l.from)._handleEvent(l),new i.default(this.conversation,l)}_processMedia(l){return this.conversation.members.has(l.from)&&this.conversation.members.get(l.from)._handleEvent(l),null}_processMuteForMedia(l){return this.conversation.media.rtcObjects[l.body.rtc_id]?l.streamIndex=this.conversation.media.rtcObjects[l.body.rtc_id].streamIndex:this.log.warn("No audio stream was found"),null}_processSeen(l){let p=this.conversation.events.get(l.body.event_id);return p?(p.state=p.state||{},p.state.seen_by=p.state.seen_by||{},p.state.seen_by[l.from]=l.timestamp,p):(this.log.warn("NXMEvent not found"),null)}_processText(l){var p,v;const m=new a.default(this.conversation,l);return((v=(p=this.conversation)===null||p===void 0?void 0:p.me)===null||v===void 0?void 0:v.id)!==m.from&&m.delivered(),m}_processMessage(l){var p,v;const m=new o.default(this.conversation,l);return((v=(p=this.conversation)===null||p===void 0?void 0:p.me)===null||v===void 0?void 0:v.id)!==m.from&&m.delivered(),m}_processSubmitted(l){let p=this.conversation.events.get(l.body.event_id);return p?(p.state=p.state||{},p.state.submitted_to=p.state.submitted_to||{},p.state.submitted_to[l.from]=l.timestamp,p):(this.log.warn("NXMEvent not found"),null)}_processRejected(l){let p=this.conversation.events.get(l.body.event_id);return p?(p.state=p.state||{},p.state.rejected_by=p.state.rejected_by||{},p.state.rejected_by[l.from]=l.timestamp,p):(this.log.warn("NXMEvent not found"),null)}_processUndeliverable(l){let p=this.conversation.events.get(l.body.event_id);return p?(p.state=p.state||{},p.state.undeliverable_to=p.state.undeliverable_to||{},p.state.undeliverable_to[l.from]=l.timestamp,p):(this.log.warn("NXMEvent not found"),null)}}r.default=u,e.exports=u}(el,el.exports)),el.exports}var Av={exports:{}};(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});class t{constructor(i={}){this.page_size=i.page_size||10,this.order=i.order||"asc",this.cursor=i.cursor||"",this.state=i.state||"",i.event_type&&(this.event_type=i.event_type)}}r.default=t,e.exports=t})(Av,Av.exports);var gI=Av.exports,rl={exports:{}},Pv={exports:{}};(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});const t=Hn;class n{constructor(a={}){this.page_size=a.page_size,this.order=a.order,this.cursor=a.cursor,this.application=a.application,a.event_type&&a.event_type.length>0&&(this.event_type=a.event_type)}hasPrev(){return this.cursor.prev?this.cursor.prev.length>0:!1}hasNext(){return this.cursor.next?this.cursor.next.length>0:!1}_getConfig(a){return{page_size:this.page_size,order:this.order,cursor:a,...this.event_type&&{event_type:this.event_type}}}_getError(){return Promise.reject(new t.NexmoClientError("error:invalid-cursor"))}}r.default=n,e.exports=n})(Pv,Pv.exports);var Hf=Pv.exports,z0;function mee(){return z0||(z0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(r,"__esModule",{value:!0});const n=t(Hf),i=t(ia),a=t(jg),s=t(mI()),o=t(Fg());class u extends n.default{constructor(l){super(l),this.items=new Map,this.conversation=l.conversation,l.items.forEach(p=>{switch(p.type){case"text":this.items.set(p.id,new a.default(this.conversation,p));break;case"image":this.items.set(p.id,new s.default(this.conversation,p));break;case"message":this.items.set(p.id,new o.default(this.conversation,p));break;default:this.items.set(p.id,new i.default(this.conversation,p));break}}),this.conversation.events=new Map([...this.conversation.events,...this.items])}getPrev(){return this.hasPrev()?this.conversation.getEvents(this._getConfig(this.cursor.prev)):this._getError()}getNext(){return this.hasNext()?this.conversation.getEvents(this._getConfig(this.cursor.next)):this._getError()}}r.default=u,e.exports=u}(rl,rl.exports)),rl.exports}var nl={exports:{}},W0;function gee(){return W0||(W0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(r,"__esModule",{value:!0});const n=t(Hf),i=t(Dg());class a extends n.default{constructor(o){super(o),this.conversation=o.conversation,this.items=new Map,o.items.forEach(u=>{this.items.set(u.id,new i.default(this.conversation,u))})}getPrev(){return this.hasPrev()?this.conversation.getMembers(this._getConfig(this.cursor.prev)):this._getError()}getNext(){return this.hasNext()?this.conversation.getMembers(this._getConfig(this.cursor.next)):this._getError()}}r.default=a,e.exports=a}(nl,nl.exports)),nl.exports}var H0;function yI(){return H0||(H0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(x){return x&&x.__esModule?x:{default:x}};Object.defineProperty(r,"__esModule",{value:!0});const n=Da,i=Ar,a=Hn,s=t(Dg()),o=t(ia),u=t(jg),c=t(Fg()),l=t(hee()),p=t(vee()),v=t(Ii()),m=t(gI),_=t(mee()),T=t(gee()),I=t(Gf());class ${constructor(N,j){this.log=i.getLogger(this.constructor.name),this.application=N,this.id=null,this.name=null,this.display_name=null,this.timestamp=null,this.members=new Map,this.events=new Map,this.sequence_number=0,this.pageConfig=new m.default(((this.application.session||{}).config||{}).events_page_config),this.events_page_last=null,this.members_page_last=null,this.conversationEventHandler=new p.default(N,this),this.media=new l.default(this),this.me=null,this._updateObjectInstance(j),n.mixin($)}_updateObjectInstance(N){for(let j in N)switch(j){case"id":this.id=N.id;break;case"name":this.name=N.name;break;case"display_name":this.display_name=N.display_name;break;case"members":N.members.forEach(J=>{if(this.members.has(J.member_id))this.members.get(J.member_id)._normalise(J),J.user_id===this.application.me.id&&J.state!=="LEFT"&&(this.me=this.members.get(J.member_id),this.members.set(this.me.id,this.me));else{const G=new s.default(this,J);J.user_id===this.application.me.id&&J.state!=="LEFT"&&(this.me=G),this.members.set(G.id,G)}});break;case"timestamp":this.timestamp=N.timestamp;break;case"sequence_number":this.sequence_number=N.sequence_number;break;case"member_id":const X={id:N.member_id,state:N.state,user:this.application.me};if(this.members.has(N.member_id)){const J=this.members.get(N.member_id);Object.assign(J,X)}else{const J=new s.default(this,X);this.me=J,this.members.set(J.id,J)}break}}async join(N){var j,X;try{let J={state:"joined",channel:{type:"app"},user:{...!N&&{name:this.application.me.name,id:this.application.me.id},...N&&N.user_name&&{name:N.user_name},...N&&N.user_id&&{id:N.user_id}}};!((j=this===null||this===void 0?void 0:this.me)===null||j===void 0)&&j.id&&((X=this===null||this===void 0?void 0:this.me)===null||X===void 0?void 0:X.state)!=="LEFT"&&(J.from=this.me.id);const G=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/members`,version:"v0.3",data:J}),L=new s.default(this,G);return G._embedded.user.id===this.application.me.id&&(this.me=L,this.members.set(L.id,L)),this.application.getConversation(this.id,I.default.CONVERSATION_API_VERSION.v3),L}catch(J){throw new a.NexmoApiError(J)}}async del(){try{const N=await this.application.session.sendNetworkRequest({type:"DELETE",path:`conversations/${this.id}`});return this.application.conversations.delete(this.id),N}catch(N){throw new a.NexmoApiError(N)}}deleteEvent(N){return N.del()}async invite(N){var j,X;if(!N||!N.id&&!N.user_name)throw new a.NexmoClientError("error:invite:missing:params");const J={state:"invited",user:{...N.id&&{id:N.id},...N.user_name&&{name:N.user_name}},media:N.media,channel:{from:{type:"app"},to:{type:"app"},type:"app"}};!((j=this===null||this===void 0?void 0:this.me)===null||j===void 0)&&j.id&&((X=this===null||this===void 0?void 0:this.me)===null||X===void 0?void 0:X.state)!=="LEFT"&&(J.from=this.me.id);try{const G=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/members`,version:"v0.3",data:J});return new s.default(this,G)}catch(G){throw new a.NexmoApiError(G)}}inviteWithAudio(N){return!N||!N.id&&!N.user_name?Promise.reject(new a.NexmoClientError("error:invite:missing:params")):(N.media={audio_settings:{enabled:!0,muted:!1,earmuffed:!1}},this.invite(N))}leave(N){return this.me.kick(N)}async sendText(N){try{if(this.me===null)throw new a.NexmoClientError("error:self");const j={type:"text",cid:this.id,from:this.me.id,body:{text:N}},{id:X,timestamp:J}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:j});return j.id=X,j.body.timestamp=J,new u.default(this,j)}catch(j){throw new a.NexmoApiError(j)}}async sendCustomEvent({type:N,body:j}){try{if(this.me===null)throw new a.NexmoClientError("error:self");if(!N||typeof N!="string"||N.length<1)throw new a.NexmoClientError("error:custom-event:invalid");const X={type:`custom:${N}`,cid:this.id,from:this.me.id,body:j},{id:J,timestamp:G}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:X});return X.id=J,X.timestamp=G,new o.default(this,X)}catch(X){throw new a.NexmoApiError(X)}}async sendEphemeralEvent(N){try{if(this.me===null)throw new a.NexmoClientError("error:self");const j={type:"ephemeral",cid:this.id,from:this.me.id,body:N},{id:X,timestamp:J}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:j});return j.timestamp=J,new o.default(this,j)}catch(j){throw new a.NexmoApiError(j)}}async uploadImage(N,j={quality_ratio:"100",medium_size_ratio:"50",thumbnail_size_ratio:"30"}){const X=new FormData;X.append("file",N),X.append("quality_ratio",j.quality_ratio),X.append("medium_size_ratio",j.medium_size_ratio),X.append("thumbnail_size_ratio",j.thumbnail_size_ratio);const J=await v.default.networkRequest({type:"POST",url:this.application.session.config.ips_url,data:X,token:this.application.session.config.token});return J.upload.addEventListener("progress",G=>{G.lengthComputable&&this.log.debug("uploading image "+G.loaded+"/"+G.total)},!1),J.onreadystatechange=()=>{J.status!==200&&this.log.error(J)},J}async sendImage(N,j={quality_ratio:"100",medium_size_ratio:"50",thumbnail_size_ratio:"30"}){const X=await this.uploadImage(N,j);return X.onreadystatechange=()=>{if(X.readyState===4&&X.status===200)try{this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:{type:"image",from:this.me.id,body:{representations:JSON.parse(X.responseText)}}}),this.log.info(X)}catch(J){this.log.error(new a.NexmoApiError(J))}},X}abortSendImage(N){return N instanceof XMLHttpRequest?N.abort():new a.NexmoClientError("error:invalid:param:type")}async sendMessage(N){if(this.me===null)throw new a.NexmoClientError("error:self");if(!(N!=null&&N.message_type))throw new a.NexmoClientError("error:message-event:invalid");try{const j={type:"message",cid:this.id,from:this.me.id,body:{...N}},{id:X,timestamp:J}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:j});return j.id=X,j.body.timestamp=J,new c.default(this,j)}catch(j){throw new a.NexmoApiError(j)}}async _typing(N){const j={cid:this.id,from:this.me.id};try{return await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:j}),`text:typing:${N}:success`}catch(X){throw new a.NexmoApiError(X)}}startTyping(){return this._typing("on")}stopTyping(){return this._typing("off")}async getEvents(N={}){const j=`${this.application.session.config.nexmo_api_url}/beta2/conversations/${this.id}/events`;let X=Object.keys(N).length===0?this.pageConfig:new m.default(N);try{const J=await v.default.paginationRequest(j,X,this.application.session.config.token);J.application=this.application,J.conversation=this;const G=new _.default(J);return this.events_page_last=G,G}catch(J){throw new a.NexmoApiError(J)}}async getMembers(N={}){const j=`${this.application.session.config.nexmo_api_url}/beta2/conversations/${this.id}/members`;let X=Object.keys(N).length===0?this.pageConfig:new m.default(N);try{const J=await v.default.paginationRequest(j,X,this.application.session.config.token);J.application=this.application,J.conversation=this;const G=new T.default(J);return this.members_page_last=G,G}catch(J){throw new a.NexmoApiError(J)}}async getMyMember(){try{const N=await this.application.session.sendNetworkRequest({type:"GET",path:`conversations/${this.id}/members/me`,version:"v0.3"});return new s.default(this,N)}catch(N){throw new a.NexmoApiError(N)}}async getMember(N){try{const j=await this.application.session.sendNetworkRequest({type:"GET",path:`conversations/${this.id}/members/${N}`,version:"v0.3"});return new s.default(this,j)}catch(j){throw new a.NexmoApiError(j)}}_handleEvent(N){var j,X;if(N.type.startsWith("rtc"))return this.emit(N.type,N),Promise.resolve(N);this.sequence_number++,N.body&&N.body.event_id&&typeof N.body.event_id=="string"&&(N.body.event_id=parseInt(N.body.event_id));let J={memberId:N.from};if(!((j=N==null?void 0:N.body)===null||j===void 0)&&j.user){const{id:L,name:re,display_name:ue,image_url:ee,custom_data:ye}=N.body.user;J={...J,...L&&{userId:L},...re&&{userName:re},...ue&&{displayName:ue},...ee&&{imageUrl:ee},...ye&&{customData:ye}}}else if(!((X=N==null?void 0:N._embedded)===null||X===void 0)&&X.from_user){const{id:L,name:re,display_name:ue,image_url:ee,custom_data:ye}=N._embedded.from_user;J={...J,...L&&{userId:L},...re&&{userName:re},...ue&&{displayName:ue},...ee&&{imageUrl:ee},...ye&&{customData:ye}}}let G=this.conversationEventHandler.handleEvent(N);return["text:typing:on","text:typing:off","ephemeral"].includes(N.type)||this.events.set(G.id,G),N.type.startsWith("custom:")?(this.emit(G.type,J,G),Promise.resolve(N)):(this.emit(N.type,J,G),Promise.resolve(N))}}r.default=$,e.exports=$}(Vc,Vc.exports)),Vc.exports}var il={exports:{}},G0;function bI(){return G0||(G0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(r,"__esModule",{value:!0});const n=Da,i=Ar,a=Hn,s=t(Wf());class o{constructor(c,l,p){this.application=c,this.log=i.getLogger(this.constructor.name),this.from=p,this.conversation=null,this.rtcObjects={},this.CALL_STATUS={STARTED:"started",RINGING:"ringing",ANSWERED:"answered",COMPLETED:"completed",BUSY:"busy",TIMEOUT:"timeout",UNANSWERED:"unanswered",REJECTED:"rejected",FAILED:"failed"},this.CALL_DIRECTION={INBOUND:"inbound",OUTBOUND:"outbound"},Object.freeze(this.CALL_DIRECTION),this.STATUS_PERMITTED_FLOW=new Map([["STARTED",new Set([this.CALL_STATUS.RINGING,this.CALL_STATUS.ANSWERED,this.CALL_STATUS.FAILED,this.CALL_STATUS.TIMEOUT,this.CALL_STATUS.UNANSWERED,this.CALL_STATUS.REJECTED,this.CALL_STATUS.BUSY])],["RINGING",new Set([this.CALL_STATUS.ANSWERED,this.CALL_STATUS.FAILED,this.CALL_STATUS.TIMEOUT,this.CALL_STATUS.UNANSWERED,this.CALL_STATUS.REJECTED,this.CALL_STATUS.BUSY])],["ANSWERED",new Set([this.CALL_STATUS.COMPLETED,this.CALL_STATUS.FAILED])]]),Object.freeze(this.STATUS_PERMITTED_FLOW),this.status=null,this.call_disconnect_timeout=null,this.direction=this.CALL_DIRECTION.INBOUND,this._setupConversationObject(l),n.mixin(o)}_enableStatsEvents(){this.conversation.media._enableStatsEvents()}_attachCallListeners(){this.log.debug("_attachCallListeners : ",{nxmCall:this});try{this.conversation.releaseGroup("call_module"),this.conversation.on("member:media","call_module",(c,l)=>{this.application.calls&&this.application.calls.has(this.conversation.id)&&this.application.calls.get(this.conversation.id)._handleStatusChange(l)})}catch(c){this.log.error("_attachCallListeners_error: ",{e:c})}}_isValidStatusTransition(c){if(!c)throw new a.NexmoClientError(`Provide the status to validate the transition from '${this.status}'`);if(!this.status)return!0;const l=this.status.toUpperCase();return!this.STATUS_PERMITTED_FLOW.has(l)||this.status===c?!1:this.STATUS_PERMITTED_FLOW.get(l).has(c)}hangUpIfAllLeft(){if(this.log.debug("hangUpIfAllLeft: ",{nxmCall:this}),!this.conversation.me||this.conversation.me.state==="LEFT"||this.conversation.members.size<=1)return Promise.resolve();for(let c of this.conversation.members.values())if(c.state!=="LEFT"&&this.conversation.me.user.id!==c.user.id)return Promise.resolve();return this.hangUp()}_setupConversationObject(c,l){c&&(this.conversation=c,c.me?(this.to=new Map(c.members),this.from&&this.to.delete(this.from.id)):this.log.warn("missing own member object"),this._attachCallListeners())}_setFrom(c){this.from=c}_setOffer(c){this.offer=c}_handleStatusChange(c){var l;const p=this.conversation?((l=this.conversation.me)===null||l===void 0?void 0:l.id)===c.from:!0,v=this.direction===this.CALL_DIRECTION.OUTBOUND;this.log.debug("_handleStatusChange: ",{event:c},`_isEventFromMe: ${p} _isOutbound: ${v}`);let m=new Map;if(m.set("member:joined",async()=>{if(c.body.channel&&c.body.channel.id)try{this._setStatusAndEmit(this.CALL_STATUS.STARTED);return}catch(_){throw this._setStatusAndEmit(this.CALL_STATUS.FAILED),this.log.error(_),_}return Promise.resolve()}),m.set("member:invited",()=>(c.body.invited_by===null&&c.body.user.media&&c.body.user.media.audio_settings&&this._setStatusAndEmit(this.CALL_STATUS.STARTED),Promise.resolve())),m.set("rtc:hangup",()=>this.status===this.CALL_STATUS.ANSWERED?(this._setStatusAndEmit(this.CALL_STATUS.COMPLETED),Promise.resolve()):p&&v||!p&&!v?(this._setStatusAndEmit(this.CALL_STATUS.UNANSWERED),Promise.resolve()):(this._setStatusAndEmit(this.CALL_STATUS.REJECTED),Promise.resolve())),m.set("member:left",()=>{if(!c.body.timestamp.hasOwnProperty("joined")&&this.status!==this.CALL_STATUS.ANSWERED)return p&&v||!p&&!v?(this._setStatusAndEmit(this.CALL_STATUS.UNANSWERED),Promise.resolve()):(this._setStatusAndEmit(this.CALL_STATUS.REJECTED),Promise.resolve())}),m.set("member:media",()=>(this.status!==this.CALL_STATUS.ANSWERED&&c.body.audio&&(p&&c.body.channel&&(this.id=c.body.channel.id),(!p||!v)&&this.id&&this._setStatusAndEmit(this.CALL_STATUS.ANSWERED)),Promise.resolve())),m.set("sip:ringing",()=>(this.status!==this.CALL_STATUS.RINGING&&this._setStatusAndEmit(this.CALL_STATUS.RINGING),Promise.resolve())),m.set("sip:hangup",()=>{switch(c.body.reason.sip_code){case 486:this._setStatusAndEmit(this.CALL_STATUS.BUSY);break;case 487:this._setStatusAndEmit(this.CALL_STATUS.TIMEOUT);break;case 403:this._setStatusAndEmit(this.CALL_STATUS.FAILED);break}return Promise.resolve()}),m.set("knocking:delete:success",()=>(this._setStatusAndEmit(this.CALL_STATUS.UNANSWERED),Promise.resolve())),m.has(c.type))return m.get(c.type).call(this)}_setStatusAndEmit(c){this._isValidStatusTransition(c)&&(this.status=c,this.log.debug(`_setStatusAndEmit: ${c}`,{nxmCall:this}),this.application.emit("call:status:changed",this))}async answer(c=!0){if(this.log.debug(`answer: { autoPlayAudio: ${c}`),this.conversation)try{await this.conversation.join();const l=await this.conversation.media.enable({autoPlayAudio:c,offer:this.offer});return this.offer=void 0,l}catch(l){throw this._setStatusAndEmit(this.CALL_STATUS.FAILED),this.log.error(l),l}else throw new a.NexmoClientError("error:call:answer")}async createCall(c,l=!0){if(this.log.debug(`createCall: { usernames: ${c}, autoPlayAudio: ${l} }`),!c||!Array.isArray(c)||c.length===0)return Promise.reject(new a.NexmoClientError("error:application:call:params"));try{const p=await this.application.newConversationAndJoin({display_name:"CALL_"+this.application.me.name+"_"+c.join("_").replace(" ","")});p.members.set(p.me.id,p.me),this.from=p.me,this.successful_invited_members=new Map;const v=c.map(async _=>{try{const T=await p.inviteWithAudio({user_name:_});return p.members.set(T.id,T),this.successful_invited_members.set(T.id,T),T}catch(T){return this.log.error(T),T}}),m=async()=>{if(this.successful_invited_members.size>0)return await p.media.enable({audio:{muted:!1,earmuffed:!1},autoPlayAudio:l}),this.application.calls.set(p.id,this),v;throw v};return await Promise.all(v),this._setupConversationObject(p),await m()}catch(p){throw this.log.error(p),this._setStatusAndEmit(this.CALL_STATUS.FAILED),p}}async createServerCall(c,l,p){this.log.debug(`createServerCall: { user: ${c}, type: ${l}, custom_data: `,{custom_data:p});const v={type:l};l==="phone"?v.number=c:v.user=c;try{const{stream:m,legId:_,rtcObjects:T}=await s.default.prewarmLeg(this);this.log.debug("createServerCall: ",{stream:m},{legId:_},{rtcObjects:T}),this.rtcObjects=T,this.stream=m,this.id=_,this.application._call_draft_list.set(_,this),s.default.playAudioStream(m);const I={type:"POST",path:"knocking",data:{channel:{type:"app",from:{type:"app"},to:v,id:_||null},...p&&Object.keys(p).length&&{properties:{custom_data:p}}}};try{const $=await this.application.session.sendNetworkRequest(I);this.knocking_id=$.id}catch($){throw new a.NexmoApiError($)}return s.default.cleanCallMediaIfFailed(this),m}catch(m){throw s.default.cleanMediaProperties(this),m}}async hangUp(c){if(this.log.debug(`hangUp: { reason: ${c} }`),this.conversation&&await this.conversation.media.disable(),!this.knocking_id&&this.conversation)return this.conversation.leave(c).catch(l=>{if(l.type!=="conversation:error:invalid-member-state")return Promise.reject(l)});{let l=`knocking/${this.knocking_id}`;if(c){let p=new URLSearchParams;Object.keys(c).forEach(v=>{p.append(v,c[v])}),l+=`?${p.toString()}`}try{const p=await this.application.session.sendNetworkRequest({type:"DELETE",path:l});return this.application._call_draft_list.get(this.client_ref)._handleStatusChange(p),this.application._call_draft_list.delete(this.client_ref),p}catch(p){if(this.conversation)return this.log.error(new a.NexmoApiError(p)),this.conversation.leave(c).catch(v=>{if(v.type!=="conversation:error:invalid-member-state")return Promise.reject(v)});this.log.debug("hangup: Problem cancelling the call. Knocking cancel failed and Conversation. Leave not available",p);return}}}reject(c){return this.log.debug(`reject: { reason: ${c} }`),this.conversation?this.conversation.leave(c):Promise.reject(new a.NexmoClientError("error:call:reject"))}}r.default=o,e.exports=o}(il,il.exports)),il.exports}var Mv={exports:{}};(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});const t=Ar;class n{constructor(a){this.log=t.getLogger(this.constructor.name),this.application=a,this._handleSipCallEventMap={"sip:hangup":this._processSipHangup,"sip:ringing":this._processSipRinging}}_handleSipCallEvent(a){if(this.log.debug("_handleSipCallEvent: ",{event:a}),!this.application.calls.has(a.cid)){this.log.warn("There is no call object for this Conversation id.");return}const s=this.application.calls.get(a.cid);if(this._handleSipCallEventMap.hasOwnProperty(a.type))return this._handleSipCallEventMap[a.type].call(this,s,a)}_processSipHangup(a,s){this.log.debug("_processSipHangup: ",s),a._handleStatusChange(s)}_processSipRinging(a,s){this.log.debug("_processSipRinging: ",s),a._handleStatusChange(s)}}r.default=n,e.exports=n})(Mv,Mv.exports);var yee=Mv.exports,xv={exports:{}};(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});const t=Ar;class n{constructor(a){this.log=t.getLogger(this.constructor.name),this.application=a,this._handleRtcEventMap={"rtc:transfer":this._processRtcTransfer,"rtc:answer":this._processRtcAnswer,"rtc:hangup":this._processRtcHangup}}_handleRtcEvent(a){if(this._handleRtcEventMap.hasOwnProperty(a.type))return this._handleRtcEventMap[a.type].call(this,a)}_processRtcTransfer(a){this.log.debug("_processRtcTransfer: ",{event:a});const s=this.application.conversations.get(a.body.transferred_from),o=this.application.conversations.get(a.cid),u=this.application.calls.get(a.body.transferred_from);if(!u){this.log.warn("NXMCall transfer for unknown nxmCall");return}u.conversation.members.get(a.body.was_member).transferred_to=o,u._setupConversationObject(o),u.transferred=!0,this.application.calls.set(a.cid,u),this.application.calls.delete(a.body.transferred_from),s&&(o.members.get(a.from).transferred_from=s,o.media._attachEndingEventHandlers(),Object.entries(o.media.rtcObjects).length===0&&Object.entries(s.media.rtcObjects).length!==0&&Object.assign(o.media.rtcObjects,s.media.rtcObjects),!o.media.pc&&s.media.pc&&Object.assign(o.media.pc=s.media.pc),o.application.activeStreams.length===0&&s.application.activeStreams.length>0&&(o.application.activeStreams=s.application.activeStreams))}_processRtcAnswer(a){this.log.debug("_processRtcAnswer: ",{event:a}),this.application.calls.has(a.cid)&&(this.application.calls.get(a.cid).id=a.body.rtc_id)}_processRtcHangup(a){this.log.debug("_processRtcHangup: ",{event:a}),this.application.calls.has(a.cid)&&this.application.calls.get(a.cid)._handleStatusChange(a)}}r.default=n,e.exports=n})(xv,xv.exports);var bee=xv.exports,al={exports:{}},V0;function _ee(){return V0||(V0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(r,"__esModule",{value:!0});const n=Ar,i=t(ia),a=t(bI()),s=t(Ii()),o=t(Wf());class u{constructor(l){this.log=n.getLogger(this.constructor.name),this.application=l,this._handleApplicationEventMap={"member:joined":this._processMemberJoined,"member:invited":this._processMemberInvited}}handleEvent(l){const p=this.application.conversations.get(l.cid),v=Object.assign({},l);return this._handleApplicationEventMap.hasOwnProperty(l.type)?this._handleApplicationEventMap[l.type].call(this,p,new i.default(p,v),l):new i.default(p,v)}_processMemberJoined(l,p,v){try{if(p.body.channel&&this.application._call_draft_list.has(p.body.channel.id)){this.log.debug("_processMemberJoined: outbound serverCall from sdk",{event:p});const m=this.application._call_draft_list.get(p.body.channel.id);let _=((m.rtcObjects||{})[p.body.channel.id]||{}).pc;if(m._setFrom(l.me),m._setupConversationObject(l,p.body.channel.id),l.media._attachEndingEventHandlers(),Object.entries(l.media.rtcObjects).length===0&&Object.entries(m.rtcObjects).length!==0&&Object.assign(l.media.rtcObjects,m.rtcObjects),!l.media.pc&&_&&Object.assign(l.media.pc=_),l.application.activeStreams.length===0&&m.application.activeStreams.length>0&&(l.application.activeStreams=m.application.activeStreams),delete m.client_ref,delete m.knocking_id,m.rtcStats&&(l.media.rtcStats=m.rtcStats),this.application._call_draft_list.delete(p.body.channel.id),this.application.calls.set(l.id,m),m._handleStatusChange(p),this.log.debug("_processMemberJoined: processedCall ",{nxmCall:m}),l.members&&p.body.member_id){const T=l.members.get(p.body.member_id);T&&this.application.emit("member:call",T,m)}setTimeout(()=>{l!=null&&l.me&&o.default.emitMediaStream(l.me,_,m.stream)},200)}return this.log.debug("_processMemberJoined: default member joined: ",{event:p}),p}catch(m){this.log.error("_processMemberJoined: ",{e:m})}}_processMemberInvited(l,p){var v,m,_,T,I,$;try{if(!l)return this.log.warn(`no conversation object for ${p.type}`),p;if(((v=l.me)===null||v===void 0?void 0:v.user.id)===p.body.invited_by||!(!((_=(m=p.body.user.media)===null||m===void 0?void 0:m.audio_settings)===null||_===void 0)&&_.enabled))return p;const x=s.default.getMemberNumberFromEventOrNull(p.body.channel)||s.default.getMemberFromNameOrNull(l,p.body.invited_by)||"unknown",N=new a.default(this.application,l,x);return this.application.calls.set(l.id,N),!((T=p.body)===null||T===void 0)&&T.sdp&&this.application.session.config.enableInboundOffer&&N._setOffer({sdp:p.body.sdp,leg_id:p.body.channel.id}),!((I=l.display_name)===null||I===void 0)&&I.startsWith("CALL_")||N._handleStatusChange(p),this.application.emit("member:call",this.application.conversations.get(p.cid).members.get(($=p.body)===null||$===void 0?void 0:$.member_id),N),p}catch(x){this.log.error("_processMemberInvited: ",{e:x})}}}r.default=u,e.exports=u}(al,al.exports)),al.exports}var Nv={exports:{}};(function(e,r){var t=Ne&&Ne.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(r,"__esModule",{value:!0});const n=t(Hf);class i extends n.default{constructor(s){super(s),this.items=new Map,s.items.forEach(o=>{const u=this.application.updateOrCreateConversation(o);this.items.set(u.id,u)})}getPrev(){return this.hasPrev()?this.application.getConversations(this._getConfig(this.cursor.prev)):this._getError()}getNext(){return this.hasNext()?this.application.getConversations(this._getConfig(this.cursor.next)):this._getError()}}r.default=i,e.exports=i})(Nv,Nv.exports);var wee=Nv.exports,Lv={exports:{}},Dv={exports:{}};(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});const t=Da;class n{constructor(a,s){var o,u;this.application=a,this.id=(o=s==null?void 0:s.id)!==null&&o!==void 0?o:null,this._embedded=(u=s==null?void 0:s._embedded)!==null&&u!==void 0?u:null,t.mixin(n)}}r.default=n,e.exports=n})(Dv,Dv.exports);var See=Dv.exports;(function(e,r){var t=Ne&&Ne.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(r,"__esModule",{value:!0});const n=t(Hf),i=t(See);class a extends n.default{constructor(o){super(o),this.items=new Map,o.items.forEach(u=>{this.items.set(u.id,new i.default(this.application,u))})}getPrev(){return this.hasPrev()?this.application.getUserSessions(this._getConfig(this.cursor.prev)):this._getError()}getNext(){return this.hasNext()?this.application.getUserSessions(this._getConfig(this.cursor.next)):this._getError()}}r.default=a,e.exports=a})(Lv,Lv.exports);var Tee=Lv.exports,sl={exports:{}},K0;function Cee(){return K0||(K0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(r,"__esModule",{value:!0}),r.ConversationEventsProcessor=r.EventsQueue=void 0;const n=Hn,i=t(Ii()),a=Ar;class s{constructor(c){this.callback=c,this.cidMap=new Map,this.log=a.getLogger(this.constructor.name)}async enqueue(c,l){var p,v,m,_,T,I,$,x;const{cid:N,id:j}=c,X=Number(j);if(!N||isNaN(X))return this.callback(c);if(((v=(p=l.conversations.get(N))===null||p===void 0?void 0:p.me)===null||v===void 0?void 0:v.state)==="LEFT")return this.callback(c);if(!this.cidMap.get(N)){this.log.debug(`enqueue: create new ConversationEventsProcessor for ${N}`);const G=new o(N,X-1,l);if(this.cidMap.set(N,G),c.type=="member:media"&&(!((_=(m=c.body)===null||m===void 0?void 0:m.media)===null||_===void 0)&&_.audio)||c.type=="member:joined"&&(!((I=(T=c.body)===null||T===void 0?void 0:T.channel)===null||I===void 0)&&I.id)&&((x=($=c.body)===null||$===void 0?void 0:$.channel)===null||x===void 0?void 0:x.knocking_id)===void 0){G.processing=!0,G.lastEventIdProcessed=0;try{await new Promise(ee=>setTimeout(ee,G.eventRequestWaitTime));const L=ee=>{var ye;return(ye=ee.find(Z=>(Z==null?void 0:Z.type)==="rtc:transfer"&&(Z==null?void 0:Z.from)===c.from))===null||ye===void 0?void 0:ye.id};let re=[Array.from(Array(5).keys()).map(ee=>X+1+ee),Array.from(Array(5).keys()).map(ee=>X-1-ee)].flatMap(ee=>ee).map(ee=>G.eventsMap.get(ee)).filter(ee=>ee),ue;if((ue=L(re))===void 0){const ee=Math.max(X-20,1);re=await G.fetchConversationEvents(ee,20)}(ue=L(re))!==void 0&&(ue=Number(ue),G.lastEventIdProcessed=Math.max(ue-1,0),re.slice(ue).forEach(ee=>G.enqueue(Number(ee.id),ee)))}finally{G.processing=!1}}}const J=this.cidMap.get(N);J.enqueue(X,c),J.processing||(J.processing=!0,await J.processEvents())}}r.EventsQueue=s;class o{constructor(c,l,p){this.cid=c,this.eventsMap=new Map,this.callback=v=>p._handleEvent(v),this.lastEventIdProcessed=l,this.largestEventIdInQueue=l,this.processing=!1,this.application=p,this.eventsFetchRange=9,this.eventRequestWaitTime=p.session.config.eventQueueWaitTime,this.log=a.getLogger(this.constructor.name)}enqueue(c,l){return c>this.largestEventIdInQueue&&(this.largestEventIdInQueue=c),c>this.lastEventIdProcessed&&this.eventsMap.set(c,l),l}dequeue(c){const l=this.eventsMap.get(c);return this.eventsMap.delete(c),l}async processEvents(){const c=()=>(this.eventsMap.clear(),this.log.debug("processEvents: Done Processing"),this.processing=!1);if(this.eventsMap.size<1)return c();const l=this.lastEventIdProcessed+1,p=await this.processNextEvent(l,1);return p?(this.lastEventIdProcessed=Number(p.id),this.processEvents()):c()}async processNextEvent(c,l){this.log.debug(`processNextEvent: processing event number ${c}`);const p=this.dequeue(c);try{if(p)return await this.callback(p),p;if(l>0)return await new Promise(v=>setTimeout(v,this.eventRequestWaitTime)),this.processNextEvent(c,l-1);if(this.largestEventIdInQueue>c){this.log.debug(`processNextEvent: largestEventIdInQueue-${this.largestEventIdInQueue} > eventId-${c}`);const v=await this.fetchEventsAndProcess(c);return v?(this.log.debug("processNextEvent: foundEvent ",{foundEvent:v}),await this.callback(v),v):(this.log.debug(`processNextEvent: not found process next ${c+1}`),this.processNextEvent(c+1,l))}return}catch{return}}async fetchEventsAndProcess(c){try{const l=await this.fetchConversationEvents(c,this.eventsFetchRange);this.log.debug("fetchEventsAndProcess: fetched events list ",{eventsList:l});let p;return l.forEach(v=>{v.cid=this.cid;const m=Number(v.id);isNaN(m)||m<c||(m>c?(this.log.debug(`fetchEventsAndProcess: event > missingEvent ${m} `,{missingEvent:c}),this.enqueue(m,v)):(this.log.debug("fetchEventsAndProcess: foundEvent ",{event:v}),p=v))}),p}catch(l){this.log.debug("fetchEventsAndProcess: error ",{e:l});return}}async fetchConversationEvents(c,l){this.log.debug("fetchConversationEvents: ",this.cid,c);const p=this.largestEventIdInQueue>c?this.largestEventIdInQueue+l:c+l,v=`${this.application.session.config.nexmo_api_url}/beta2/conversations/${this.cid}/events`;try{return(await i.default.paginationRequest(v,{start_id:c,end_id:p},this.application.session.config.token)).items}catch(m){throw new n.NexmoApiError(m)}}}r.ConversationEventsProcessor=o,e.exports={EventsQueue:s,ConversationEventsProcessor:o}}(sl,sl.exports)),sl.exports}var J0;function Gf(){return J0||(J0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(J){return J&&J.__esModule?J:{default:J}};Object.defineProperty(r,"__esModule",{value:!0});const n=Da,i=Ar,a=Hn,s=t(k$),o=t(yI()),u=t(bI()),c=t(yee),l=t(bee),p=t(_ee()),v=t(Ii()),m=t(gI),_=t(wee),T=t(Tee),I=Cee(),$=t(Dg());let x=null,N=null,j=null;class X{constructor(G,L){this.log=i.getLogger(this.constructor.name),this.session=G,this.conversations=new Map,this.synced_conversations_count=0,this.start_sync_time=0,this.stop_sync_time=0,this.calls=new Map,this._call_draft_list=new Map,this.pageConfig=new m.default((G.config||{}).conversations_page_config),this.conversations_page_last=null,this.activeStreams=[],x=new c.default(this),N=new l.default(this),j=new p.default(this),this.me=null,Object.assign(this,L),n.mixin(X)}updateOrCreateConversation(G){const L=this.conversations.get(G.id);return L?(L._updateObjectInstance(G),this.conversations.set(G.id,L)):this.conversations.set(G.id,new o.default(this,G)),this.conversations.get(G.id)}async _enqueueEvent(G){this.session.config.enableEventsQueue?(this.eventsQueue||(this.eventsQueue=new I.EventsQueue(L=>this._handleEvent(L))),this.eventsQueue.enqueue(G,this)):this._handleEvent(G)}async _handleEvent(G){var L,re,ue,ee,ye,Z,qe;const Qe=!((L=G._embedded)===null||L===void 0)&&L.from_user?((ue=(re=G._embedded)===null||re===void 0?void 0:re.from_user)===null||ue===void 0?void 0:ue.id)===((ee=this.me)===null||ee===void 0?void 0:ee.id):((Z=(ye=G.body)===null||ye===void 0?void 0:ye.user)===null||Z===void 0?void 0:Z.user_id)===((qe=this.me)===null||qe===void 0?void 0:qe.id),Nt=v.default._checkIfUserIsReInvited(this.conversations,G);if(G.type.startsWith("sip"))return x._handleSipCallEvent(G),G;if(this.conversations.has(G.cid)&&G.type!=="rtc:transfer"&&!Nt)return G.type.startsWith("rtc")&&N._handleRtcEvent(G),this.conversations.get(G.cid)._handleEvent(G),(G.type==="member:joined"||G.type==="member:invited")&&Qe&&this._handleApplicationEvent(G),G;if(G.cid)try{Nt&&this.conversations.delete(G.cid);let vt;return v.default._isCallEvent(G)?vt=await this.getConversation(G.cid,X.CONVERSATION_API_VERSION.v1):vt=await this.getConversation(G.cid,X.CONVERSATION_API_VERSION.v3),this.conversations.set(G.cid,vt),await vt._handleEvent(G),await this._handleApplicationEvent(G),G.type.startsWith("rtc")&&N._handleRtcEvent(G),Promise.resolve(G)}catch(vt){return this.log.error(vt),Promise.reject(vt)}}async updateToken(G){if(this.session.connection&&this.session.connection.disconnected)return this.session.config.token=G,this.session.connection.io.opts.query.token=G,Promise.resolve();const L={url:`${this.session.config.nexmo_api_url}/v0.2/sessions/${this.session.session_id}`,type:"PUT",token:G};try{await v.default.networkRequest(L),this.me&&(this.session.config.token=G,this.session.connection.io.opts.query.token=G)}catch(re){throw new a.NexmoApiError(re)}}async _handleApplicationEvent(G){try{this.log.debug("_handleApplicationEvent: ",{event:G});const L=j.handleEvent(G),re=this.conversations.get(G.cid);let ue;if(re.members.has((L||{}).from))ue=re.members.get(L.from);else if(G.type==="member:joined"||G.type==="member:invited"){const ee={...G.body,...G.from&&{member_id:G.from}};ue=new $.default(re,ee)}else try{ue=await re.getMember(L.from)}catch(ee){this.log.warn(`There is an error getting the member ${ee}`)}return this.emit(L.type,ue,L),G}catch(L){throw this.log.error("_handleApplicationEvent: ",L),L}}async inAppCall(G){if(!G||!Array.isArray(G)||G.length===0)return Promise.reject(new a.NexmoClientError("error:application:call:params"));try{const L=new u.default(this);return await L.createCall(G),L.direction=L.CALL_DIRECTION.OUTBOUND,L}catch(L){throw L}}async callServer(G,L="phone",re={}){try{const ue=new u.default(this);return ue.direction=ue.CALL_DIRECTION.OUTBOUND,await ue.createServerCall(G,L,re),ue}catch(ue){throw ue}}async reconnectCall(G,L,re={}){try{if(!G||!L)throw new a.NexmoClientError("error:missing:params");const ue=await this.getConversation(G,X.CONVERSATION_API_VERSION.v1);await ue.media.enable({...re,reconnectRtcId:L});const ee=new u.default(this,ue),ye=Array.from(ue.events.values()).map(Z=>Z.type);return ye.includes("sip:answered")?ee.status=ee.CALL_STATUS.ANSWERED:ye.includes("sip:ringing")?ee.status=ee.CALL_STATUS.RINGING:ee.status=ee.CALL_STATUS.STARTED,ee.rtcObjects=ue.media.rtcObjects,this.calls.set(ue.id,ee),ee}catch(ue){throw ue}}async newConversation(G={}){try{const L=await this.session.sendNetworkRequest({type:"POST",path:"conversations",data:G}),re=new o.default(this,L);return this.conversations.set(re.id,re),this.getConversation(re.id,X.CONVERSATION_API_VERSION.v1)}catch(L){throw new a.NexmoApiError(L)}}async newConversationAndJoin(G){const L=await this.newConversation(G);return await L.join(),L}async getConversation(G,L=X.CONVERSATION_API_VERSION.v3){if(L!==X.CONVERSATION_API_VERSION.v1&&L!==X.CONVERSATION_API_VERSION.v3)throw new a.NexmoClientError("error:conversation-service:version");let re;if(L===X.CONVERSATION_API_VERSION.v1)try{re=await this.session.sendNetworkRequest({type:"GET",path:`conversations/${G}`}),re.id=re.uuid,delete re.uuid}catch(ee){throw new a.NexmoApiError(ee)}else try{re=await this.session.sendNetworkRequest({type:"GET",path:`conversations/${G}`,version:"v0.3"})}catch(ee){throw new a.NexmoApiError(ee)}const ue=this.updateOrCreateConversation(re);if(L===X.CONVERSATION_API_VERSION.v3&&!ue.me)try{const ee=await ue.getMyMember();ue.me=ee,ue.members.set(ee.id,ee)}catch{try{const ye=await ue.getMyMember();ue.me=ye,ue.members.set(ye.id,ye)}catch{this.log.warn(`You don't have any membership in ${ue.id}`)}}if(this.session.config.sync==="full"){const{items:ee}=await ue.getEvents();return ue.events=ee,ue}else return ue}async getConversations(G={}){const L=`${this.session.config.nexmo_api_url}/beta2/users/${this.me.id}/conversations`;let re=Object.keys(G).length===0?this.pageConfig:new m.default(G);try{const ue=await v.default.paginationRequest(L,re,this.session.config.token);ue.application=this;const ee=new _.default(ue);return this.conversations_page_last=ee,ee}catch(ue){throw new a.NexmoApiError(ue)}}syncConversations(G){const L=Array.from(G.values()),re=L.length,ue=new Date;this.start_sync_time=typeof window<"u"&&window.performance?window.performance.now():ue.getTime();const ee=async()=>{this.synced_conversations_percentage=Number((this.synced_conversations_count/re*100).toFixed(2));const ye={sync_progress:this.synced_conversations_percentage};if(this.emit("sync:progress",ye),this.log.info("Loading sync progress: "+this.synced_conversations_count+"/"+re+" - "+this.synced_conversations_percentage+"%"),this.synced_conversations_percentage>=100){const Z=new Date;this.stop_sync_time=typeof window<"u"&&window.performance?window.performance.now():Z.getTime(),this.log.info("Loaded conversations in "+(this.stop_sync_time-this.start_sync_time)+"ms")}this.synced_conversations_count<re&&(await this.getConversation(L[this.synced_conversations_count].id),ee(),this.synced_conversations_count++,this.sync_progress_buffer++)};ee()}async getUser(G=this.me.id){try{const L=await this.session.sendNetworkRequest({type:"GET",path:`users/${G}`});return new s.default(this,L)}catch(L){throw new a.NexmoApiError(L)}}async getUserSessions(G={}){var L;const re=((L=G)===null||L===void 0?void 0:L.user_id)||this.me.id,ue=`${this.session.config.nexmo_api_url}/v0.3/users/${re}/sessions`;let ee=Object.keys(G).length===0?this.pageConfig:new m.default(G);try{const ye=await v.default.paginationRequest(ue,ee,this.session.config.token,X.CONVERSATION_API_VERSION.v3);ye.application=this;const Z=new T.default(ye);return this.user_sessions_page_last=Z,Z}catch(ye){throw new a.NexmoApiError(ye)}}}r.default=X,X.CONVERSATION_API_VERSION={v1:"v0.1",v3:"v0.3"},e.exports=X}(Gc,Gc.exports)),Gc.exports}var Y0;function Ii(){return Y0||(Y0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(p){return p&&p.__esModule?p:{default:p}};Object.defineProperty(r,"__esModule",{value:!0});const n=t(DZ),i=t(_$),a=t(Gf()),s=4e4,o=2e4,u=new RegExp(`"|'|<|>|&|\\|/`),c=new RegExp(`"|'|<|>|\\|javascript:`);class l{static getMemberFromNameOrNull(v,m){if(!v||!m)return null;for(let _ of v.members.values())if(_.user.name===m)return _;return null}static getMemberNumberFromEventOrNull(v){const m=v&&v.from;return m&&(m.number||m.uri)?m.number||m.uri:null}static isSanitizedInput(v){return!u.test(v)}static isSanitizedUrlInput(v){return!c.test(v)}static checkIsSanitized([v,m]){if(m==null)return!0;switch(typeof m){case"string":return v.includes("url")||v.includes("uri")?l.isSanitizedUrlInput(m):l.isSanitizedInput(m);case"object":return Array.isArray(m)?m.every(_=>l.checkIsSanitized(["dummy",_])):Object.entries(m).every(l.checkIsSanitized);default:return!0}}static networkRequest(v){return new Promise((m,_)=>{!v.token&&!v.url.includes("logging")&&!v.url.includes("ping")&&_({response:{type:"error:user:token",description:"network error on request. Please create a new session."}});const T=new XMLHttpRequest;let I;T.open(v.type,v.url,!0),v.token&&T.setRequestHeader("Authorization","Bearer "+v.token),v&&v.url.includes("image")?(T.responseType="",I=v.data,T.onloadstart=()=>{m(T)}):(T.responseType=v.responseType||"json",I=v.data?JSON.stringify(v.data):null,T.setRequestHeader("Content-type","application/json; charset=utf-8")),T.onload=()=>{T.status===200||T.status===201||T.status===204?m(T):_(T)},T.onerror=$=>{_($)},T.send(I)})}static async paginationRequest(v,m,_,T=a.default.CONVERSATION_API_VERSION.v1){try{const I=await l.networkRequest({type:"GET",url:l.addUrlSearchParams(v,m),token:_}),{page_size:$,_embedded:x,_links:N}=I.response,j=v.split("/").pop().trim();return{items:T===a.default.CONVERSATION_API_VERSION.v1?x.data[j]:x[j],cursor:{prev:N.prev?new URLSearchParams(N.prev.href).get("cursor"):"",next:N.next?new URLSearchParams(N.next.href).get("cursor"):"",self:N.self?new URLSearchParams(N.self.href).get("cursor"):""},page_size:$,order:m.order||"asc",event_type:m.event_type||null}}catch({response:I}){const $=I||{type:"error:network:get-request",description:"network error on nexmo get request"};throw $.validation&&($.description=$.validation[Object.keys($.validation)[0]]),$}}static addUrlSearchParams(v,m={}){let _=new URL(v);return Object.keys(m).forEach(T=>{m[T]&&!(typeof m[T]=="string"&&m[T].length<1)&&m[T]!==null&&_.searchParams.set(T,m[T])}),_.href}static deepMergeObj(v,m){const _=JSON.parse(JSON.stringify(v));for(let T in m)Object.prototype.toString.call(m[T])==="[object Object]"?_[T]=l.deepMergeObj(_[T],m[T]):_[T]=m[T];return _}static injectScript(v,m){if(typeof document<"u"){let _=document.getElementsByTagName("head")[0],T=document.createElement("script");T.async=!0,T.src=v,T.onload=T.onreadystatechange=()=>{(!T.readyState||/loaded|complete/.test(T.readyState))&&(T.onload=T.onreadystatechange=null,T=null,m&&m())},_.insertBefore(T,_.firstChild)}}static allocateUUID(){return n.default.v4()}static validateDTMF(v){return typeof v=="string"?/^[\da-dA-D#*pP]{1,45}$$/.test(v):!1}static _getBugsnagKey(){return"76498fc1ca8d9b0a173a44e2b873d7ed"}static updateMemberLegs(v,m){if(v){const _=v.find(T=>T.leg_id===m.body.leg_id);if(!_)v.push({leg_id:m.body.leg_id,status:m.body.status});else if(_.status!==m.body.status){let T=v.indexOf(_);v.fill(_.status=m.body.status,T,T++)}}else v=[{leg_id:m.body.leg_id,status:m.body.status}];return v}static _isCallEvent(v){const{channel:m,media:_}=v.body;return!!(v.type==="rtc:transfer"||m&&(_&&_.audio_settings&&_.audio_settings.enabled||_&&_.audio&&_.audio.enabled||m.knocking_id))}static async _fetchImage(v,m){const{response:_}=await l.networkRequest({type:"GET",url:v,responseType:"arraybuffer",token:m}),T=new Uint8Array(_);let I="";const $=8*1024;let x;for(x=0;x<T.length/$;x++)I+=String.fromCharCode.apply(null,T.subarray(x*$,(x+1)*$));return I+=String.fromCharCode.apply(null,T.subarray(x*$)),"data:image/jpeg;base64,"+btoa(I)}static async _checkHttpConnectivity(v){const m=Date.now();try{await l.networkRequest({type:"GET",url:v});const _=Date.now()-m;return{url:v,canConnect:!0,connectionTime:_}}catch(_){return{url:v,canConnect:!1,error:_}}}static _checkWsConnectivity(v,m,_){return new Promise((T,I)=>{const $=Object.assign({path:m},_),x=Date.now(),N=i.default.connect(v,$),j=setTimeout(()=>T({url:v,canConnect:!1}),o);N.on("connect",()=>{const X=Date.now()-x;N.disconnect(),clearTimeout(j),T({url:v,canConnect:!0,connectionTime:X})}),N.on("error",X=>{N.disconnect(),clearTimeout(j),T({url:v,canConnect:!1,error:X})})})}static async _checkMediaServers(v,m,_){try{const{response:T}=await l.networkRequest({type:"GET",url:`${m}/v0.3/discovery/media/${_}`,token:v}),I=T.map($=>l._checkMediaConnectivity($.ip,$.port));return await Promise.all(I)}catch{return[]}}static async _checkMediaConnectivity(v,m){return new Promise(async(_,T)=>{const I={iceServers:[{urls:`stun:${v}:${m}`}]},$=new RTCPeerConnection(I),x=Date.now(),N=await $.createOffer({offerToReceiveAudio:!0});$.setLocalDescription(N);const j=setTimeout(()=>{$.close(),_({ip:v,canConnect:!1})},s);$.addEventListener("icecandidate",X=>{var J;if(((J=X==null?void 0:X.candidate)===null||J===void 0?void 0:J.type)==="srflx"){const G=Date.now()-x;clearTimeout(j),$.close(),_({ip:v,canConnect:!0,connectionTime:G})}}),$.addEventListener("icecandidateerror",X=>{X.errorCode&&($.close(),clearTimeout(j),_({ip:v,canConnect:!1,error:X}))})})}static _checkIfUserIsReInvited(v,m){var _;if(!v.has(m.cid)||!(m.type==="member:invited"||m.type==="member:joined"))return!1;const T=(_=v.get(m.cid))===null||_===void 0?void 0:_.me;return T?T.user.name===m.body.user.name&&T.state==="LEFT":!1}}r.default=l,e.exports=l}(Wc,Wc.exports)),Wc.exports}var jv={exports:{}};(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});const t=Ar,n=Hn;class i{constructor(s){if(this.log=t.getLogger(this.constructor.name),!s)throw new n.NexmoClientError("no emitter object passed for the Error Emitter");this.emitter=s,this.LISTENER_GROUP="NXM-errors"}emitResponseIfError(s){if(this._isTypeError(s.type))return this.emitter.emit(s.type,this.LISTENER_GROUP,s)}cleanup(){return this.emitter.releaseGroup(this.LISTENER_GROUP)}_isTypeError(s){return s.indexOf("error")!==-1}}r.default=i,e.exports=i})(jv,jv.exports);var Eee=jv.exports;(function(e,r){var t=Ne&&Ne.__importDefault||function(I){return I&&I.__esModule?I:{default:I}};Object.defineProperty(r,"__esModule",{value:!0});const n=Da,i=t(EX),a=t(Ar),s=Hn,o=t(_$),u=t(_Z),c=t(kZ),l=t(Ii()),p=t(Gf()),v=t(Eee),m=t(k$),_=t(Wf());i.default.reg(a.default),i.default.apply(a.default,{template:"[%t] %l (NXM-%n):",timestampFormatter:I=>I.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),levelFormatter:I=>I.toUpperCase(),nameFormatter:I=>I||"SDK"});class T{constructor($={}){const x=$;if(this.config={debug:"silent",log_reporter:{enabled:!1,bugsnag_key:null},environment:"production",ips_url:"https://api-us.vonage.com/v1/image",nexmo_api_url:"https://api-us.vonage.com",path:"/v2/rtc",repository:"https://github.com/Nexmo/conversation-js-sdk",SDK_version:"9.6.1",socket_io:{reconnection:!0,reconnectionAttempts:5,reconnectionDelay:2e3,randomizationFactor:.75,reconnectionDelayMax:15e3,forceNew:!0,autoConnect:!0,transports:["websocket"]},sync:"none",url:"https://ws-us.vonage.com",iceServers:[],rtcstats:{remote_collection:!0,remote_collection_url:"https://hlg.tokbox.com/prod/logging/nexmo_client_js_stats",remote_collection_interval:5e3,emit_events:!1,emit_rtc_analytics:!1,emit_interval:1e3},conversations_page_config:{page_size:10,order:"asc",cursor:""},events_page_config:{page_size:10,order:"asc",event_type:""},enableEventsQueue:!0,eventQueueWaitTime:50,enableInboundOffer:!1,acknowledgeEvents:!0,token:null},this.config.socket_io.query={token:"",SDK_version:this.config.SDK_version,session_version:$.enableInboundOffer?"0.0.3":"0.0.1",acknowledge_events:this.config.acknowledgeEvents,OS_family:"js",OS_revision:typeof navigator<"u"?navigator.userAgent:typeof window<"u"?window.navigator.userAgent:"Generic JS navigator"},this.sessionReady=!1,this.disconnectTimestamp=null,this.session_id=null,this.apiKey=null,this.requests={},this.application=null,["debug","info","warn","error"].includes(x.debug)?a.default.setLevel(x.debug):x.debug===!0?a.default.setLevel("debug"):a.default.setLevel("silent"),this.log=a.default.noConflict(),this.config=l.default.deepMergeObj(this.config,this._sanitizeConfig(x)),this.config.log_reporter.enabled){const N={apiKey:this.config.log_reporter.bugsnag_key||l.default._getBugsnagKey(),appVersion:this.config.socket_io.query.SDK_version,releaseStage:this.config.environment};Ne.NXMbugsnagClient=u.default(N)}n.mixin(T)}_createAndSetConnection(){let $,x=Object.assign({path:this.config.path},this.config.socket_io);return $=o.default.connect(this.config.url,x),this.connection=$,$.on("connect",()=>{this.emit("ready"),this.sessionReady=!0,this.log.info("websocket ready")}),$.on("disconnect",(N,j)=>{this.emit("disconnect",N==="io client disconnect"?T.DISCONNECT_REASON.ClientDisconnected:N==="io server disconnect"&&this.session_id?T.DISCONNECT_REASON.TokenExpired:T.DISCONNECT_REASON.ConnectionError),this.disconnectTimestamp=Date.now(),this.log.info("websocket disconnected",N,j)}),$.io.on("reconnect",N=>{this.emit("reconnect",N),this.log.info("websocket reconnect",N),l.default.networkRequest({url:`${this.config.url.replace("wss://","https://")}/v2/rtc/metrics`,type:"POST",token:this.config.token,data:{sessionId:this.session_id,metrics:[{name:"TIME_TO_RECONNECT_SUCCESS",time:this.disconnectTimestamp?Date.now()-this.disconnectTimestamp:void 0,attempt:N}]}}).catch(j=>{this.log.warn("Failed to publish socket reconnection metrics",j)})}),$.io.on("reconnect_attempt",N=>{this.emit("reconnecting",N),this.log.info("websocket reconnecting",N)}),$.on("connect_error",N=>{this.emit("error",new s.NexmoClientError(N)),this.log.error("Socket.io reported a generic error",N)}),$.io.on("reconnect_failed",()=>{this.emit("error",new s.NexmoClientError("error:client:reconnection_failed")),this.log.error("websocket reconnection error")}),$.io.on("packet",N=>{if(N.type!==2||N.data[0]==="echo")return;const j=N.data[2];j&&typeof j=="function"&&j();const X=N.data[1];if(X.type=N.data[0],this.log.debug("<--",X.type,X),this.requests["session:login"]){const J=this.requests["session:login"].callback;delete this.requests["session:login"],J(X)}else if(X.rid in this.requests){const J=this.requests[X.rid].callback;delete this.requests[X.rid],delete X.delay,this.errorsEmitter&&this.errorsEmitter.emitResponseIfError(X),J(X)}else this.errorsEmitter&&X.type.startsWith("system:error:")?this.errorsEmitter.emitResponseIfError(X):X.type.startsWith("session:")?this.updateSession(X):this.application&&this.application._enqueueEvent(X)}),$}_sanitizeConfig($){let x=$;return $.sync&&["none","lite","full"].indexOf($.sync)===-1&&(this.log.warn(`invalid param '${$.sync}' for sync, reverting to ${this.config.sync}`),x.sync=this.config.sync),x}sendRequest($,x){$.tid=l.default.allocateUUID();const N=$.type;delete $.type,this.log.debug("-->",N,$),this.log.info("-->",N,$.tid),this.connection.emit(N,$),this.requests[$.tid]={type:N,request:$,callback:x}}async sendNetworkRequest($){const x=$.version||"beta",N=`${this.config.nexmo_api_url}/${x}/${$.path}`;if(!($.type==="GET"||$.type==="DELETE")&&($.data={...$.data,originating_session:this.session_id},!l.default.checkIsSanitized(["data",$.data])))throw new s.NexmoClientError("error:input:unsanitized");try{const j={type:$.type,url:N,data:$.data?$.data:null,token:($.data||{}).token?$.data.token:this.config.token||null};this.log.debug("sendNetworkRequest: ",{request:j});const{response:X}=await l.default.networkRequest(j);return X}catch({response:j}){throw j}}createSession($){return this.config.socket_io.query.token=$,this._createAndSetConnection(),new Promise((x,N)=>{this.log.info(`Client-SDK Version: ${this.config.SDK_version}`),this.config.token=null,this.requests["session:login"]={type:"session:login",callback:async j=>{if(j.type==="session:success")if(this.session_id=j.body.id,this.apiKey=j.body.api_key,this.config.token=$,this.connection.io.opts.query={session_id:this.session_id,token:this.config.token},(!this.application||this.application.me&&this.application.me.id!==j.body.user_id)&&(this.application=new p.default(this,{})),this.application.me||(this.application.me=new m.default(this.application,{id:j.body.user_id,name:j.body.name})),this.errorsEmitter||(this.errorsEmitter=new v.default(this.application)),this.config.log_reporter.enabled&&(Ne.NXMbugsnagClient.user={id:this.application.me.id,name:this.application.me.name,session_id:j.body.id}),this.config.sync!=="none")try{await this.application.getConversations(),x(this.application)}catch(X){N(X)}else x(this.application);else N(new s.NexmoApiError(j))}}})}deleteSession(){return new Promise(async($,x)=>{const N=()=>this.sendRequest({type:"session:logout",body:{}},j=>{j.type==="session:logged-out"||j.type==="session:terminated"?(this.disconnect(),delete this.errorsEmitter,delete this.application,delete this.connection,this.requests={},this.sessionReady=!1,$(j)):x(j)});if(this.application){let j=[];if(this.application.conversations.size)for(let X of this.application.conversations.values())j.push(X.media.disable());try{await Promise.all(j)}catch(X){this.log.error("deleteSession: ",X)}return N()}else return N()})}updateSession($){$.type==="session:success"&&(this.session_id=$.body.id,this.connection.io.opts.query.session_id=$.body.id,this.application&&$.body.pending_events&&$.body.pending_events.forEach(x=>this.application._enqueueEvent(x)))}disconnect(){return this.connection.disconnect()}connect(){return this.connection.connect()}async connectivityReport($,x){const j={machineInfo:{ip:_.default.isNode()?void 0:await c.default.v4()},connectivityReport:[]};try{const{response:X}=await l.default.networkRequest({type:"GET",url:`${this.config.nexmo_api_url}/v0.3/discovery/api`,token:$});let J=X;x!=null&&x.dcListCallback&&(J=x.dcListCallback(J));for(const G in J){const L=J[G].endpoint,re=J[G].https,ue=J[G].ws;try{const ee=await l.default._checkHttpConnectivity(re),ye=await l.default._checkWsConnectivity(ue,this.config.path,this.config.socket_io),Z=await l.default._checkMediaServers($,L,G),qe={name:G,signalConnectionReport:{https:ee,ws:ye},mediaConnectionReport:Z};j.connectivityReport.push(qe)}catch(ee){this.log.error(`Error generating report for ${G}`,ee)}}}catch(X){this.log.error("Error fetching nexmo servers information",X)}return j}async checkMediaServers($,x,N){return await l.default._checkMediaServers($,x,N)}async checkMediaConnectivity($,x){return await l.default._checkMediaConnectivity($,x)}}r.default=T,T.DISCONNECT_REASON={ClientDisconnected:"ClientDisconnected",TokenExpired:"TokenExpired",ConnectionError:"ConnectionError"},e.exports=T})(lv,lv.exports);var kee=lv.exports;const Ree=pT(kee),Li=new $a("nexmo-chat"),$ee=["us-3","us-4","eu-3","eu-4","ap-3","ap-4"];class _I extends qv{constructor(){super(...arguments);pt(this,"rtc");pt(this,"application");pt(this,"conversation")}get _client(){if(this.rtc)return this.rtc;const t=Iee(this.region);return this.rtc=new Ree({nexmo_api_url:`https://api-${this.region}.${t}`,url:`wss://ws-${this.region}.${t}`}),this.rtc}async create(){const{identity:t,token:n}=await this.issueChatToken();Li.info(`Connecting chat, identity: ${t}, token: ${n}`),this.identity=t,this.application=await this._client.createSession(n)}async destroy(){this.rtc&&(await this.rtc.deleteSession(),this.rtc=null,this.application=null,this.conversation=null)}async join(t){const n=await this.application.getConversation(t);n.me.state==="JOINED"?Li.info("already joined conversation:",t):(await n.join(),Li.info("success joined conversation:",t)),this.registerEvents(n),this.conversation=n}async preview(t){await this.conversation.sendCustomEvent({type:"ujet_preview",body:{chat_preview:t,chat_preview_updated_at:new Date().toJSON()}})}async fetchMessages(t){const n=await this.conversation.getEvents({event_type:"message",order:"desc",page_size:100}),i=[];return n.items.forEach(a=>{const s=a._embedded.from_user.name,o=X0(a,s);t[o.$index]&&(o.file=t[o.$index]),this.trackInTask(o),i.push(o)}),i.reverse()}async sendMessage(t){try{const n=await this.conversation.sendMessage({message_type:"text",text:JSON.stringify(t)});return Li.info(`Message sent from ${this.conversation.id}, id: ${n.id}`),parseInt(n.id,10)}catch(n){Li.warn(`Failed to send a message from ${this.conversation.id}`,{error:n})}}startTyping(){this.conversation&&this.conversation.startTyping()}stopTyping(){this.conversation&&this.conversation.stopTyping()}registerEvents(t){t.on("message",(n,i)=>{const a=X0(i,n.userName);Li.info(`Message added from ${this.conversation.id}, index: ${a.$index}, sid: ${a.$sid}, timestamp: ${a.$timestamp}, user type: ${a.$userType}`),a.$userType!=="end_user"&&this.ping(),this.trackInTask(a),this.events.triggerEvent("message",a)}),t.on("member:joined",n=>{Li.info("conversation: memberJoined",n),this.events.triggerEvent("memberJoined",n.userName)}),t.on("member:left",n=>{Li.info("conversation: memberLeft",n),this.events.triggerEvent("memberLeft",n.userName)}),t.on("text:typing:on",n=>{/^end_user/.test(n.userName)||this.events.triggerEvent("typingStarted",n.userName)}),t.on("text:typing:off",n=>{/^end_user/.test(n.userName)||this.events.triggerEvent("typingEnded",n.userName)})}}pt(_I,"type","nexmo_conversations");zv(_I);function Iee(e){return $ee.indexOf(e)>-1?"vonage.com":"nexmo.com"}function X0(e,r){const{id:t,timestamp:n,body:i}=e,[a,s]=r.split("-");let o=0;s&&(o=parseInt(s,10));const u={$index:parseInt(t,10),$sid:t,$timestamp:new Date(Date.parse(n)),$userType:a,$userId:o};try{const c=JSON.parse(i.text);return c.message&&!c.type?{...u,...c,type:"message"}:{...u,...c}}catch(c){return Li.warn("Format message failed",{error:c,data:i.text}),{...u,type:"text",content:i.text}}}exports.Client=mA;exports.ENVIRONMENT=CI;exports.EventManager=Bv;exports.Logger=$a;exports.MediaStore=aT;exports.OPTIONS=Br;exports.PostSessionStatus=Qs;exports.VERSION=Fv;exports.addProviderType=zv;exports.consoleLoggerHandler=rO;
526
+ `},ws=sI,YZ=JZ;aa.write=YZ;aa.parse=ws.parse;aa.parseParams=ws.parseParams;aa.parseFmtpConfig=ws.parseFmtpConfig;aa.parsePayloads=ws.parsePayloads;aa.parseRemoteCandidates=ws.parseRemoteCandidates;aa.parseImageAttributes=ws.parseImageAttributes;aa.parseSimulcastStreamList=ws.parseSimulcastStreamList;var sa={},XZ=Ne&&Ne.__spreadArrays||function(){for(var e=0,r=0,t=arguments.length;r<t;r++)e+=arguments[r].length;for(var n=Array(e),i=0,r=0;r<t;r++)for(var a=arguments[r],s=0,o=a.length;s<o;s++,i++)n[i]=a[s];return n};Object.defineProperty(sa,"__esModule",{value:!0});var cI=function(){function e(r,t,n){this.name=r,this.version=t,this.os=n}return e}();sa.BrowserInfo=cI;var lI=function(){function e(r){this.version=r,this.name="node",this.os=process.platform}return e}();sa.NodeInfo=lI;var fI=function(){function e(){this.bot=!0,this.name="bot",this.version=null,this.os=null}return e}();sa.BotInfo=fI;var QZ=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,ZZ=/(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp)|(MSNBot)|(Ask Jeeves\/Teoma)|(ia_archiver)/,N0=3,eee=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["vivaldi",/Vivaldi\/([0-9\.]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/Edg\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FBAV\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["searchbot",QZ]],L0=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/],["Search Bot",ZZ]];function tee(e){return e?Ov(e):typeof navigator<"u"?Ov(navigator.userAgent):pI()}sa.detect=tee;function Ov(e){var r=e!==""&&eee.reduce(function(a,s){var o=s[0],u=s[1];if(a)return a;var c=u.exec(e);return!!c&&[o,c]},!1);if(!r)return null;var t=r[0],n=r[1];if(t==="searchbot")return new fI;var i=n[1]&&n[1].split(/[._]/).slice(0,3);return i?i.length<N0&&(i=XZ(i,ree(N0-i.length))):i=[],new cI(t,i.join("."),dI(e))}sa.parseUserAgent=Ov;function dI(e){for(var r=0,t=L0.length;r<t;r++){var n=L0[r],i=n[0],a=n[1],s=a.test(e);if(s)return i}return null}sa.detectOS=dI;function pI(){var e=typeof process<"u"&&process.version;return e?new lI(process.version.slice(1)):null}sa.getNodeVersion=pI;function ree(e){for(var r=[],t=0;t<e;t++)r.push("0");return r}var Qc={exports:{}};function nee(e,r){if(typeof e[Symbol.iterator]=="function")for(const t of e){const n=Array.isArray(t)?t[1]:t;r(n)}else for(const t in e)if(e.hasOwnProperty(t)){const n=e[t];r(n)}}var hI={iterateReports:nee};const iee={"outbound-rtp":{packetsSent:"audioSentPackets",bytesSent:"audioSentBytes"},"inbound-rtp":{packetsReceived:"audioRecvPackets",packetsLost:"audioRecvPacketsLost",bytesReceived:"audioRecvBytes",jitter:"audioRecvJitter"},"remote-inbound-rtp":{packetsLost:"audioSentPacketsLost",roundTripTime:"audioRtt",jitter:"audioSentJitter"}},aee={"remote-candidate":function(e){return Zc(e)},"inbound-rtp":function(e){return Zc(e)},"outbound-rtp":function(e){return Zc(e)},"remote-inbound-rtp":function(e){return Zc(e)}},Zc=e=>{const{type:r}=e,t=iee[r],n={};for(let i in t)if(i in e){let a;typeof t[i]=="function"?a=t[i](e):a=t[i],n[a]=e[i]}else n[t[i]]=null;return n};var see={parsers:aee};const{iterateReports:oee}=hI;function uee(e){let r=0,t=0,n=0,i=100,a=0,s,o,u;return oee(e,c=>{c.type==="inbound-rtp"&&(r=c.jitter,n=c.packetsLost,t=c.packetsReceived)}),t+n>0&&(a=100*(n/(t+n))),s=i+r*2+10,s<160?o=93.2-s/40:o=93.2-(s-120)/10,o=o-a*2.5,o<1&&(o=1),u=1+.035*o+7e-6*o*(o-60)*(100-o),parseFloat(u).toFixed(6)}var vI=uee;const{iterateReports:cee}=hI,{parsers:D0}=see,lee=vI;function fee(e){const r={};return cee(e,t=>{if(t.type in D0){const n=D0[t.type](t);Object.assign(r,n)}}),r.networkMos=parseFloat(lee(e)),r}var dee=fee,j0;function pee(){return j0||(j0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(r,"__esModule",{value:!0});const n=dee,i=vI,a=t(Ii());class s{constructor(u){this.mos_report={min:5,max:0},this._reportsCount=0,this._mosSum=0,this.intervals=[],this._deprecationWarningSent=!1,!(!u||!u.application||!u.rtc_id||!u.pc)&&(this.conversation=null,this.application_id=null,this.attachHandlers(u),this.startSendingStats(u),this.startEmittingStats(u))}attachHandlers(u){const{pc:c}=u;c.addEventListener("connectionstatechange",()=>{switch(c.connectionState){case"disconnected":case"failed":case"closed":this.removeIntervals(),this.emitLastReport(u)}}),u.conversation?u.conversation.on("member:media",(p,v)=>{!this.application_id&&(u==null?void 0:u.rtc_id)===v.body.channel.id&&(this.application_id=v.application_id)}):u.application.on("member:joined",(p,v)=>{(!this.conversation||!this.application_id)&&(u==null?void 0:u.rtc_id)===v.body.channel.id&&(this.conversation=p.conversation,this.application_id=v.application_id)})}emitLastReport(u){const{application:c,conversation:l=null,rtc_id:p,config:{emit_events:v,emit_rtc_analytics:m}}=u,_=this.getMOSReport(),T=_.last;T&&(m&&c.emit("rtcstats:analytics",{type:"mos_report",mos:T,rtc_id:p,mos_report:_,api_key:c.session.apiKey,...this.application_id&&{application_id:this.application_id},...l&&{conversation_id:l.id,conversation_name:l.name}}),v&&(this._deprecationWarningSent||(this._deprecationWarningSent=!0,console.warn('"rtcstats:report" event is deprecated. Use "rtcstats:analytics" instead')),c.emit("rtcstats:report",T,null,l,_)))}startSendingStats(u){const{application:c,conversation:l=null,pc:p,rtc_id:v,config:{remote_collection:m,remote_collection_url:_,remote_collection_interval:T}}=u;if(!m)return;const I=setInterval(()=>{p.getStats(null).then($=>{var x;const N=(x=l??this.conversation)!==null&&x!==void 0?x:null;a.default.networkRequest({url:_,type:"POST",data:{...n($),legId:v,apiKey:c.session.apiKey,...this.application_id&&{applicationId:this.application_id},...N&&{conversationId:N.id,conversationName:N.name}}}).catch(()=>{})}).catch(()=>{}),(p.connectionState==="closed"||p.signalingState==="closed")&&this.removeIntervals()},T);this.intervals.push(I)}startEmittingStats(u){const{application:c,conversation:l=null,pc:p,rtc_id:v,config:{emit_events:m,emit_rtc_analytics:_,emit_interval:T}}=u;if(!m&&!_)return;const I=setInterval(()=>{var $;p.getStats(null).then(x=>{var N;const j=this.getMos(x);if(!j)return;const X=(N=l??this.conversation)!==null&&N!==void 0?N:null;_&&c.emit("rtcstats:analytics",{type:"mos",mos:j,report:x,rtc_id:v,api_key:c.session.apiKey,...this.application_id&&{application_id:this.application_id},...X&&{conversation_id:X.id,conversation_name:X.name}}),m&&(this._deprecationWarningSent||(this._deprecationWarningSent=!0,console.warn('"rtcstats:report" event is deprecated. Use "rtcstats:analytics" instead')),c.emit("rtcstats:report",j,x,l))}).catch(()=>{}),(p.connectionState==="closed"||p.signalingState==="closed")&&(this.removeIntervals(),this.emitLastReport({...u,conversation:($=l??this.conversation)!==null&&$!==void 0?$:null}))},T);this.intervals.push(I)}removeIntervals(){this.intervals.forEach(u=>clearInterval(u)),this.intervals=[]}getMos(u){const c=i(u);return this.updateMOSReport(parseInt(c)),c}updateMOSReport(u){this._reportsCount++,this._mosSum+=u,this.mos_report.last=u,this.mos_report.min=u<this.mos_report.min?u:this.mos_report.min,this.mos_report.max=u>this.mos_report.max?u:this.mos_report.max,this.mos_report.average=this._mosSum/this._reportsCount}getMOSReport(){return this.mos_report.min=s.normaliseFloat(this.mos_report.min),this.mos_report.max=s.normaliseFloat(this.mos_report.max),this.mos_report.last=s.normaliseFloat(this.mos_report.last),this.mos_report.average=s.normaliseFloat(this.mos_report.average),this.mos_report}static normaliseFloat(u){return parseFloat(u).toFixed(6)}}r.default=s,e.exports=s}(Qc,Qc.exports)),Qc.exports}var F0;function Wf(){return F0||(F0=1,function(e,r){var t=Ne&&Ne.__createBinding||(Object.create?function(m,_,T,I){I===void 0&&(I=T),Object.defineProperty(m,I,{enumerable:!0,get:function(){return _[T]}})}:function(m,_,T,I){I===void 0&&(I=T),m[I]=_[T]}),n=Ne&&Ne.__setModuleDefault||(Object.create?function(m,_){Object.defineProperty(m,"default",{enumerable:!0,value:_})}:function(m,_){m.default=_}),i=Ne&&Ne.__importStar||function(m){if(m&&m.__esModule)return m;var _={};if(m!=null)for(var T in m)T!=="default"&&Object.hasOwnProperty.call(m,T)&&t(_,m,T);return n(_,m),_},a=Ne&&Ne.__importDefault||function(m){return m&&m.__esModule?m:{default:m}};Object.defineProperty(r,"__esModule",{value:!0});const s=aa,o=Ar,u=i(sa),c=Hn,l=a(pee()),p=2e4;class v{constructor(){this.log=o.getLogger(this.constructor.name)}static getUserAudio(_=!0){let T={video:!1,audio:_};return navigator.mediaDevices.getUserMedia(T)}createRTCPeerConnection(_){const T=new RTCPeerConnection(_);return T.trace=()=>{},T}_getWindowLocationProtocol(){return window.location.protocol}static _getBrowserName(){return u.detect().name}static isNode(){return this._getBrowserName()==="node"}checkValidKeys(_,T){let I=!0;return Object.keys(_).forEach($=>{T.hasOwnProperty($)||(I=!1)}),I}static cleanCallMediaIfFailed(_){setTimeout(()=>{_.conversation||(this.cleanMediaProperties(_),_.status=_.CALL_STATUS.FAILED,_.application.emit("call:status:changed",_))},5e3)}static callDisconnectHandler(_,T){const I=[_.CALL_STATUS.ANSWERED,_.CALL_STATUS.STARTED,_.CALL_STATUS.RINGING];if(!(T.connectionState!=="disconnected"||!_||!_.conversation))return setTimeout(()=>{T.connectionState==="connected"||I.indexOf(_.status)==-1||(this.cleanMediaProperties(_),_.status=_.CALL_STATUS.COMPLETED,_.application.emit("call:status:changed",_))},p)}static cleanMediaProperties(_){if(_.rtcObjects)for(const T in _.rtcObjects)_.rtcObjects[T].pc.close(),delete _.rtcObjects[T].pc,v.closeStream(_.rtcObjects[T].stream);_.application.activeStreams=[],_.rtcObjects={},_.conversation&&_.conversation.media&&(_.conversation.media.rtcStats=null)}static cleanConversationMediaProperties(_,T){T&&v.closeStream(T),_&&_.close()}static playAudioStream(_){const T=new Audio;return T.srcObject=_,T.autoplay=!0,T}static createDummyCandidateSDP(_){const T={foundation:1176891032,component:1,transport:"udp",priority:2122260223,ip:"0.0.0.0",port:9,type:"host",generation:0,"network-id":1,"network-cost":50},I=s.parse(_.localDescription.sdp);return I.media[0].candidates=[T],s.write(I)}static createRTCPeerConnectionConfig(_){return{iceTransportPolicy:"all",bundlePolicy:"balanced",rtcpMuxPolicy:"require",iceCandidatePoolSize:"0",..._.session.config&&_.session.config.iceServers&&{iceServers:_.session.config.iceServers}}}static setupPeerConnectionApplicationListeners(_,T){T.addEventListener("icecandidateerror",I=>_.emit("rtc:icecandidateerror",I)),T.addEventListener("icegatheringstatechange",()=>_.emit("rtc:icegatheringstatechange",T.iceGatheringState)),T.addEventListener("signalingstatechange",()=>_.emit("rtc:signalingstatechange",T.signalingState)),T.addEventListener("iceconnectionstatechange",()=>_.emit("rtc:iceconnectionstatechange",T.iceConnectionState)),T.addEventListener("connectionstatechange",()=>_.emit("rtc:peerconnectionstatechange",T.connectionState))}static createPeerConnection(_){const T=this.createRTCPeerConnectionConfig(_),I=new RTCPeerConnection(T);return this.setupPeerConnectionApplicationListeners(_,I),I}static sendOffer(_,T,I,$){const N={sdp:this.createDummyCandidateSDP(T)};let j={from:I.me.id,body:{offer:N}},X=`conversations/${I.id}/rtc`;return $&&(X+=`/${$}/offer`),_.session.sendNetworkRequest({type:"POST",path:X,data:j})}static sendAnswer(_,T,I,$){const x=this.createDummyCandidateSDP(T);let N={from:I.me.id,body:{answer:x}},j=`conversations/${I.id}/rtc/${$}/answer`;return _.session.sendNetworkRequest({type:"POST",path:j,data:N})}static createLeg(_,T){const $={sdp:this.createDummyCandidateSDP(T),type:"offer"};return _.session.sendNetworkRequest({type:"POST",path:"legs",version:"beta",data:{body:{offer:$}}})}static closeStream(_){_.getTracks().forEach(T=>{T.stop()})}static emitMediaStream(_,T,I){_.emit("media:stream:on",{pc:T,stream:I,type:"audio",streamIndex:0})}static _initStatsEvents(_){var T,I,$;if(!v.isNode()&&!(($=(I=(T=_==null?void 0:_.application)===null||T===void 0?void 0:T.session)===null||I===void 0?void 0:I.config)===null||$===void 0)&&$.rtcstats){const x=_.application.session.config.rtcstats,{emit_events:N,remote_collection:j,emit_rtc_analytics:X}=x;if(N||j||X){const J={..._,config:{...x}};return new l.default(J)}}}static attachConversationEventHandlers(_){const{conversation:T,pc:I,log:$}=_;T.once("rtc:answer",x=>{if(!I){$.warn("RTC: received an answer too late");return}I.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:x.body.answer}))})}static doAnswer(_,T,I){const{application:$,conversation:x,pc:N,reject:j,localStream:X}=_;this.addPeerConnectionListeners(_,()=>v.sendAnswer($,N,x,I).then(()=>({rtc_id:I}))),N.setRemoteDescription(new RTCSessionDescription({type:"offer",sdp:T})).then(()=>N.createAnswer()).then(J=>N.setLocalDescription(J)).catch(J=>{v.cleanConversationMediaProperties(N,X),j(J)})}static attachPeerConnectionEventHandlers(_){const{application:T,conversation:I,pc:$,reconnectRtcId:x}=_;this.addPeerConnectionListeners(_,()=>v.sendOffer(T,$,I,x))}static addPeerConnectionListeners(_,T){const{application:I,conversation:$,pc:x,streamIndex:N,localStream:j,log:X,rtcObjects:J,resolve:G,reject:L}=_;let re,ue=!1,ee;$.id&&(ee=I.calls.get($.id)),x.ontrack=ye=>{re=ye.streams[0],I.activeStreams.push(re),v.emitMediaStream($.me,x,re)},x.addEventListener("connectionstatechange",ye=>this.onconnectionstatechangeHandler(x,X,ee,()=>G(re),()=>{v.cleanConversationMediaProperties(x,j),L()})),x.addEventListener("negotiationneeded",()=>this.onnegotiationneededHandler(x,ye=>{v.cleanConversationMediaProperties(x,j),L(ye)})),x.addEventListener("iceconnectionstatechange",ye=>this.oniceconnectionstatechange(ye,x,X,Z=>{v.cleanConversationMediaProperties(x,j),L(Z)})),x.addEventListener("icecandidate",async ye=>{if(ye.candidate&&!ue&&x){ue=!0;try{const{rtc_id:Z}=await T();v._initStatsEvents({application:I,rtc_id:Z,pc:x,conversation:$}),x.trace&&x.trace("rtc_id",Z),J[Z]={rtc_id:Z,pc:x,stream:j,type:"audio",streamIndex:N}}catch(Z){v.cleanConversationMediaProperties(x,j),L(new c.NexmoClientError(Z))}}}),j.getTracks().forEach(ye=>x.addTrack(ye))}static prewarmLeg(_){const T=_.application;return new Promise(async(I,$)=>{let x=!1,N,j,X={},J,G;const L=o.getLogger(this.constructor.name);try{G=await this.getUserAudio(),J=this.createPeerConnection(T),J.ontrack=re=>{N=re.streams[0],T.activeStreams.push(N)},J.addEventListener("connectionstatechange",re=>this.onconnectionstatechangeHandler(J,L,_,()=>I({stream:N,legId:j,rtcObjects:X}),()=>{v.cleanConversationMediaProperties(J,G),$()})),J.addEventListener("negotiationneeded",()=>this.onnegotiationneededHandler(J,re=>{v.cleanConversationMediaProperties(J,G),$(re)})),J.addEventListener("iceconnectionstatechange",re=>this.oniceconnectionstatechange(re,J,L,ue=>{v.cleanConversationMediaProperties(J,G),$(ue)})),J.addEventListener("icecandidate",async re=>{if(re.candidate&&!x&&J){x=!0;const{rtc_id:ue,sdp:ee}=await this.createLeg(T,J);return v._initStatsEvents({application:T,rtc_id:ue,pc:J}),j=ue,X[j]={rtc_id:ue,pc:J,stream:G,type:"audio",streamIndex:1},J.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:ee}))}}),G.getTracks().forEach(re=>J.addTrack(re))}catch(re){v.cleanConversationMediaProperties(J,G),$(new c.NexmoClientError(re))}})}}r.default=v,v.onconnectionstatechangeHandler=(m,_,T,I,$)=>{switch(m.connectionState){case"connected":_.info("The connection has become fully connected"),I();break;case"disconnected":if(!T)break;T.call_disconnect_timeout&&clearTimeout(T.call_disconnect_timeout),T.call_disconnect_timeout=v.callDisconnectHandler(T,m);break;case"failed":$(),_.info("One or more transports has terminated unexpectedly or in an error");break;case"closed":_.info("The connection has been closed");break}},v.oniceconnectionstatechange=(m,_,T,I)=>{switch(_.iceConnectionState){case"disconnected":T.warn("One or more transports is disconnected",_.iceConnectionState);break;case"failed":I(new c.NexmoClientError(m)),T.warn("One or more transports has terminated unexpectedly or in an error",m);break;default:T.info("The ice connection status changed",_.iceConnectionState)}},v.onnegotiationneededHandler=async(m,_)=>{try{const T=await m.createOffer();return m.setLocalDescription(T)}catch(T){_(new c.NexmoClientError(T))}},e.exports=v}(Xc,Xc.exports)),Xc.exports}var U0;function hee(){return U0||(U0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(p){return p&&p.__esModule?p:{default:p}};Object.defineProperty(r,"__esModule",{value:!0});const n=Ar,i=Hn,a=t(Wf()),s=t(Ii()),o=t(ia),u=t(yI()),c=t(Gf());class l{constructor(v){var m,_,T;const I=v instanceof u.default?v:null,$=v instanceof c.default?v:null;this.log=n.getLogger(this.constructor.name),I?(this.rtcHelper=new a.default,this.application=I.application,this.application.activeStreams=this.application.activeStreams||[],this.parentConversation=I,this.rtcObjects={},this.streamIndex=0,this.rtcstats_conf=((T=(_=(m=this.application)===null||m===void 0?void 0:m.session)===null||_===void 0?void 0:_.config)===null||T===void 0?void 0:T.rtcStats)||{},this.rtcStats=null):$?(this.rtcHelper=new a.default,this.application=$):this.log.warn("No conversation object in Media")}_attachEndingEventHandlers(){this.parentConversation&&(this.log.debug("attaching leave listeners in media for "+this.parentConversation.id),this.parentConversation.on("rtc:hangup",async v=>{let m;if(this.parentConversation.members.has(v.from))m=this.parentConversation.members.get(v.from);else try{m=await this.parentConversation.getMember(v.from)}catch(_){this.log.warn(`There is an error getting the member ${_}`)}m.user.id===this.application.me.id&&this.application.activeStreams.length&&this._cleanMediaProperties(),m.user.id===this.application.me.id&&m.transferred_from&&m.transferred_from.media._cleanMediaProperties(),m.user.id===this.application.me.id&&this.parentConversation.off("rtc:hangup")}))}_enableStatsEvents(){this.rtcstats_conf.emit_rtc_analytics=!0,this.rtcstats_conf.remote_collection=!0;const v=this._findRtcObjectByType("audio");!this.rtcStats&&v&&(this.log.debug(`enabling stats events for ${v.rtc_id}`),this.rtcStats=a.default._initStatsEvents({application:this.application,rtc_id:v.rtc_id,pc:this.pc,conversation:this.parentConversation}))}_disableStatsEvents(){this.rtcstats_conf.emit_events=!1,this.rtcstats_conf.emit_rtc_analytics=!1,this.rtcstats_conf.remote_collection=!1,this.rtcStats.removeIntervals(),delete this.rtcStats}_audioInitHandler(v={},m){return new Promise(async(_,T)=>{const I=this.streamIndex;this.streamIndex++;const{audioConstraints:$}=v;try{const x=await a.default.getUserAudio($),N=a.default.createPeerConnection(this.application);this.pc=N;const{application:j,log:X,parentConversation:J,rtcObjects:G}=this,L={pc:N,streamIndex:I,localStream:x,application:j,conversation:J,log:X,rtcObjects:G};m({...L,resolve:_,reject:T}),a.default.attachConversationEventHandlers(L),this._attachEndingEventHandlers()}catch(x){T(new i.NexmoClientError(x))}})}_execAnswer(v={}){const{offer:{sdp:m,leg_id:_}}=v;return this._audioInitHandler(v,T=>a.default.doAnswer(T,m,_))}_handleAudio(v={}){const{reconnectRtcId:m}=v;return this._audioInitHandler(v,_=>a.default.attachPeerConnectionEventHandlers({..._,reconnectRtcId:m}))}_findRtcObjectByType(v){return Object.values(this.rtcObjects).find(m=>m.type===v)}async _cleanConversationProperties(){this.pc&&this.pc.close(),delete this.pc,this.rtcStats=null,this.application.activeStreams=[],this.listeningToRtcEvent=!1,await Promise.resolve()}_cleanMediaProperties(){if(this.pc&&this.pc.close(),this.rtcObjects)for(const v in this.rtcObjects)a.default.closeStream(this.rtcObjects[v].stream);delete this.pc,this.rtcStats=null,this.application.activeStreams=[],this.rtcObjects={},this.listeningToRtcEvent=!1}async _disableLeg(v){const m=new Promise(async(T,I)=>{try{await this.application.session.sendNetworkRequest({type:"DELETE",path:`conversations/${this.parentConversation.id}/rtc/${v}?from=${this.parentConversation.me.id}&originating_session=${this.application.session.session_id}`,version:"beta2"}),T("rtc:terminate:success")}catch($){I(new i.NexmoApiError($))}}),_=new Promise(T=>{this.rtcObjects[v].pc&&this.rtcObjects[v].pc.close(),this.rtcObjects[v].stream&&a.default.closeStream(this.rtcObjects[v].stream),T()});try{return await Promise.all([m,_]),this.parentConversation.me.emit("media:stream:off",this.rtcObjects[v].streamIndex),delete this.rtcObjects[v],"rtc:terminate:success"}catch(T){throw T}}_enableMediaTracks(v,m){v.forEach(_=>{_.enabled=m})}async _setMediaTracksAndMute(v,m,_,T){this._enableMediaTracks(m,!_);try{return await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:T,to:this.parentConversation.me.id,from:this.parentConversation.me.id,body:{rtc_id:v}}})}catch(I){throw this._enableMediaTracks(m,_),new i.NexmoApiError(I)}}async updateAudioConstraints(v={}){let m=this._findRtcObjectByType("audio");if(m&&m.pc)try{const _=await a.default.getUserAudio(v);return _.getTracks().forEach(T=>{const I=m.pc.getSenders().find($=>$.track.kind===T.kind);I&&(T.enabled=I.track.enabled,I.replaceTrack(T))}),a.default.closeStream(m.stream),m.stream=_,_}catch(_){return _}else throw new i.NexmoApiError("error:media:stream:not-found")}mute(v=!1,m=null){const T="audio:mute:"+(v?"on":"off");let I=[],$={};if(m!==null){if($[0]=Object.values(this.rtcObjects).find(x=>x.streamIndex===m),!$[0])throw new i.NexmoClientError("error:media:stream:not-found")}else $=this.rtcObjects;return Object.values($).forEach(x=>{const N=x.stream.getAudioTracks(),j=this._setMediaTracksAndMute(x.rtc_id,N,v,T);I.push(j)}),Promise.all(I)}async earmuff(v){try{if(this.me===null)throw new i.NexmoClientError("error:self");{let m="audio:earmuff:off";v&&(m="audio:earmuff:on");const{response:_}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:m,to:this.parentConversation.me.id}});return _}}catch(m){throw new i.NexmoApiError(m)}}async enable(v){try{if(this.parentConversation.me===null)throw new i.NexmoClientError("error:self");{const{offer:m}=v??{};let _=await(m!==void 0?this._execAnswer(v):this._handleAudio(v)),T=v&&(v.autoPlayAudio||v.autoPlayAudio===void 0);return(!v||T)&&a.default.playAudioStream(_),_}}catch(m){throw m}}disable(){let v=[];v.push(this._cleanConversationProperties());for(const m in this.rtcObjects)v.push(this._disableLeg(m));return Promise.all(v)}async sayText(v){try{const m=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:say",cid:this.parentConversation.id,from:this.parentConversation.me.id,body:{text:v.text,voice_name:v.voice_name||"Amy",level:v.level||1,queue:v.queue||!0,loop:v.loop||1,ssml:v.ssml||!1}}});return new o.default(this.parentConversation,m)}catch(m){throw new i.NexmoApiError(m)}}async sendDTMF(v){try{if(!s.default.validateDTMF(v))throw new i.NexmoClientError("error:audio:dtmf:invalid-digit");if(!(this._findRtcObjectByType("audio")||{}).rtc_id)throw new i.NexmoClientError("error:audio:dtmf:audio-disabled");const{id:_,timestamp:T}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:dtmf",from:this.parentConversation.me.id,body:{digit:v,channel:{type:"app",id:this._findRtcObjectByType("audio").rtc_id}}}}),I={body:{digit:v,dtmf_id:""},cid:this.parentConversation.id,from:this.parentConversation.me.id,id:_,timestamp:T,type:"audio:dtmf"},$=new o.default(this.parentConversation,I);return this.parentConversation.events.set(I.id,$),$}catch(m){throw new i.NexmoApiError(m)}}async playStream(v){try{const m=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:play",body:v}});return new o.default(this.parentConversation,m)}catch(m){throw new i.NexmoApiError(m)}}async startRinging(){try{const v=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:ringing:start",from:this.parentConversation.me.id,body:{}}});return new o.default(this.parentConversation,v)}catch(v){throw new i.NexmoApiError(v)}}async stopRinging(){try{const v=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.parentConversation.id}/events`,data:{type:"audio:ringing:stop",from:this.parentConversation.me.id,body:{}}});return new o.default(this.parentConversation,v)}catch(v){throw new i.NexmoApiError(v)}}}r.default=l,e.exports=l}(Yc,Yc.exports)),Yc.exports}var el={exports:{}},tl={exports:{}},B0;function mI(){return B0||(B0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(r,"__esModule",{value:!0});const n=t(Ii()),i=Ar,a=t(ia);class s extends a.default{constructor(u,c){super(u,c),this.log=i.getLogger(this.constructor.name),this.type="image",this.conversation=u,this.state={seen_by:{},delivered_to:{}},c&&c.body&&c.body.timestamp&&(this.timestamp=c.body.timestamp),Object.assign(this,c)}seen(){return super.seen()}delivered(){return super.delivered()}async del(){return await n.default.networkRequest({type:"DELETE",url:this.body.representations.original.url,token:this.conversation.application.session.config.token}),super.del()}async fetchImage(u="thumbnail",c=this.body.representations){try{return n.default._fetchImage(c[u].url,this.conversation.application.session.config.token)}catch(l){throw this.log.error(l),l}}}r.default=s,e.exports=s}(tl,tl.exports)),tl.exports}var q0;function vee(){return q0||(q0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(r,"__esModule",{value:!0});const n=Ar,i=t(ia),a=t(jg),s=t(mI()),o=t(Fg());class u{constructor(l,p){this.log=n.getLogger(this.constructor.name),this.application=l,this.conversation=p,this.constructed_event=null,this._handleEventMap={"event:delete":this._processDelete,image:this._processImage,"image:delivered":this._processDelivered,"image:seen":this._processSeen,"member:invited":this._processMember,"member:joined":this._processMember,"member:left":this._processMember,"audio:ringing:start":this._processMember,"leg:status:update":this._processLegStatus,"member:media":this._processMedia,text:this._processText,"text:delivered":this._processDelivered,"text:seen":this._processSeen,"audio:mute:on":this._processMuteForMedia,"audio:mute:off":this._processMuteForMedia,message:this._processMessage,"message:delivered":this._processDelivered,"message:seen":this._processSeen,"message:submitted":this._processSubmitted,"message:rejected":this._processRejected,"message:undeliverable":this._processUndeliverable}}handleEvent(l){return this._handleEventMap.hasOwnProperty(l.type)?this._handleEventMap[l.type].call(this,l)||new i.default(this.conversation,l):new i.default(this.conversation,l)}_processDelivered(l){let p=this.conversation.events.get(l.body.event_id);return p?(p.state=p.state||{},p.state.delivered_to=p.state.delivered_to||{},p.state.delivered_to[l.from]=l.timestamp,p):(this.log.warn("NXMEvent not found"),null)}_processDelete(l){var p;let v=this.conversation.events.get((p=l==null?void 0:l.body)===null||p===void 0?void 0:p.event_id);return v?(v.body.text&&(v.body.text=""),v.body.representations&&(v.body.representations=""),v.body.timestamp={deleted:l.timestamp},v):(this.log.warn("NXMEvent not found"),null)}_processImage(l){var p;const v=new s.default(this.conversation,l);return((p=this.conversation.me)===null||p===void 0?void 0:p.id)!==v.from&&v.delivered(),v}_processMember(l){return this.application.calls.has(this.conversation.id)&&this.application.calls.get(this.conversation.id)._handleStatusChange(l),this.conversation.members.has(l.from)&&this.conversation.members.get(l.from)._handleEvent(l),new i.default(this.conversation,l)}_processLegStatus(l){return this.conversation.members.has(l.from)&&this.conversation.members.get(l.from)._handleEvent(l),new i.default(this.conversation,l)}_processMedia(l){return this.conversation.members.has(l.from)&&this.conversation.members.get(l.from)._handleEvent(l),null}_processMuteForMedia(l){return this.conversation.media.rtcObjects[l.body.rtc_id]?l.streamIndex=this.conversation.media.rtcObjects[l.body.rtc_id].streamIndex:this.log.warn("No audio stream was found"),null}_processSeen(l){let p=this.conversation.events.get(l.body.event_id);return p?(p.state=p.state||{},p.state.seen_by=p.state.seen_by||{},p.state.seen_by[l.from]=l.timestamp,p):(this.log.warn("NXMEvent not found"),null)}_processText(l){var p,v;const m=new a.default(this.conversation,l);return((v=(p=this.conversation)===null||p===void 0?void 0:p.me)===null||v===void 0?void 0:v.id)!==m.from&&m.delivered(),m}_processMessage(l){var p,v;const m=new o.default(this.conversation,l);return((v=(p=this.conversation)===null||p===void 0?void 0:p.me)===null||v===void 0?void 0:v.id)!==m.from&&m.delivered(),m}_processSubmitted(l){let p=this.conversation.events.get(l.body.event_id);return p?(p.state=p.state||{},p.state.submitted_to=p.state.submitted_to||{},p.state.submitted_to[l.from]=l.timestamp,p):(this.log.warn("NXMEvent not found"),null)}_processRejected(l){let p=this.conversation.events.get(l.body.event_id);return p?(p.state=p.state||{},p.state.rejected_by=p.state.rejected_by||{},p.state.rejected_by[l.from]=l.timestamp,p):(this.log.warn("NXMEvent not found"),null)}_processUndeliverable(l){let p=this.conversation.events.get(l.body.event_id);return p?(p.state=p.state||{},p.state.undeliverable_to=p.state.undeliverable_to||{},p.state.undeliverable_to[l.from]=l.timestamp,p):(this.log.warn("NXMEvent not found"),null)}}r.default=u,e.exports=u}(el,el.exports)),el.exports}var Av={exports:{}};(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});class t{constructor(i={}){this.page_size=i.page_size||10,this.order=i.order||"asc",this.cursor=i.cursor||"",this.state=i.state||"",i.event_type&&(this.event_type=i.event_type)}}r.default=t,e.exports=t})(Av,Av.exports);var gI=Av.exports,rl={exports:{}},Pv={exports:{}};(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});const t=Hn;class n{constructor(a={}){this.page_size=a.page_size,this.order=a.order,this.cursor=a.cursor,this.application=a.application,a.event_type&&a.event_type.length>0&&(this.event_type=a.event_type)}hasPrev(){return this.cursor.prev?this.cursor.prev.length>0:!1}hasNext(){return this.cursor.next?this.cursor.next.length>0:!1}_getConfig(a){return{page_size:this.page_size,order:this.order,cursor:a,...this.event_type&&{event_type:this.event_type}}}_getError(){return Promise.reject(new t.NexmoClientError("error:invalid-cursor"))}}r.default=n,e.exports=n})(Pv,Pv.exports);var Hf=Pv.exports,z0;function mee(){return z0||(z0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(r,"__esModule",{value:!0});const n=t(Hf),i=t(ia),a=t(jg),s=t(mI()),o=t(Fg());class u extends n.default{constructor(l){super(l),this.items=new Map,this.conversation=l.conversation,l.items.forEach(p=>{switch(p.type){case"text":this.items.set(p.id,new a.default(this.conversation,p));break;case"image":this.items.set(p.id,new s.default(this.conversation,p));break;case"message":this.items.set(p.id,new o.default(this.conversation,p));break;default:this.items.set(p.id,new i.default(this.conversation,p));break}}),this.conversation.events=new Map([...this.conversation.events,...this.items])}getPrev(){return this.hasPrev()?this.conversation.getEvents(this._getConfig(this.cursor.prev)):this._getError()}getNext(){return this.hasNext()?this.conversation.getEvents(this._getConfig(this.cursor.next)):this._getError()}}r.default=u,e.exports=u}(rl,rl.exports)),rl.exports}var nl={exports:{}},W0;function gee(){return W0||(W0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(r,"__esModule",{value:!0});const n=t(Hf),i=t(Dg());class a extends n.default{constructor(o){super(o),this.conversation=o.conversation,this.items=new Map,o.items.forEach(u=>{this.items.set(u.id,new i.default(this.conversation,u))})}getPrev(){return this.hasPrev()?this.conversation.getMembers(this._getConfig(this.cursor.prev)):this._getError()}getNext(){return this.hasNext()?this.conversation.getMembers(this._getConfig(this.cursor.next)):this._getError()}}r.default=a,e.exports=a}(nl,nl.exports)),nl.exports}var H0;function yI(){return H0||(H0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(x){return x&&x.__esModule?x:{default:x}};Object.defineProperty(r,"__esModule",{value:!0});const n=Da,i=Ar,a=Hn,s=t(Dg()),o=t(ia),u=t(jg),c=t(Fg()),l=t(hee()),p=t(vee()),v=t(Ii()),m=t(gI),_=t(mee()),T=t(gee()),I=t(Gf());class ${constructor(N,j){this.log=i.getLogger(this.constructor.name),this.application=N,this.id=null,this.name=null,this.display_name=null,this.timestamp=null,this.members=new Map,this.events=new Map,this.sequence_number=0,this.pageConfig=new m.default(((this.application.session||{}).config||{}).events_page_config),this.events_page_last=null,this.members_page_last=null,this.conversationEventHandler=new p.default(N,this),this.media=new l.default(this),this.me=null,this._updateObjectInstance(j),n.mixin($)}_updateObjectInstance(N){for(let j in N)switch(j){case"id":this.id=N.id;break;case"name":this.name=N.name;break;case"display_name":this.display_name=N.display_name;break;case"members":N.members.forEach(J=>{if(this.members.has(J.member_id))this.members.get(J.member_id)._normalise(J),J.user_id===this.application.me.id&&J.state!=="LEFT"&&(this.me=this.members.get(J.member_id),this.members.set(this.me.id,this.me));else{const G=new s.default(this,J);J.user_id===this.application.me.id&&J.state!=="LEFT"&&(this.me=G),this.members.set(G.id,G)}});break;case"timestamp":this.timestamp=N.timestamp;break;case"sequence_number":this.sequence_number=N.sequence_number;break;case"member_id":const X={id:N.member_id,state:N.state,user:this.application.me};if(this.members.has(N.member_id)){const J=this.members.get(N.member_id);Object.assign(J,X)}else{const J=new s.default(this,X);this.me=J,this.members.set(J.id,J)}break}}async join(N){var j,X;try{let J={state:"joined",channel:{type:"app"},user:{...!N&&{name:this.application.me.name,id:this.application.me.id},...N&&N.user_name&&{name:N.user_name},...N&&N.user_id&&{id:N.user_id}}};!((j=this===null||this===void 0?void 0:this.me)===null||j===void 0)&&j.id&&((X=this===null||this===void 0?void 0:this.me)===null||X===void 0?void 0:X.state)!=="LEFT"&&(J.from=this.me.id);const G=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/members`,version:"v0.3",data:J}),L=new s.default(this,G);return G._embedded.user.id===this.application.me.id&&(this.me=L,this.members.set(L.id,L)),this.application.getConversation(this.id,I.default.CONVERSATION_API_VERSION.v3),L}catch(J){throw new a.NexmoApiError(J)}}async del(){try{const N=await this.application.session.sendNetworkRequest({type:"DELETE",path:`conversations/${this.id}`});return this.application.conversations.delete(this.id),N}catch(N){throw new a.NexmoApiError(N)}}deleteEvent(N){return N.del()}async invite(N){var j,X;if(!N||!N.id&&!N.user_name)throw new a.NexmoClientError("error:invite:missing:params");const J={state:"invited",user:{...N.id&&{id:N.id},...N.user_name&&{name:N.user_name}},media:N.media,channel:{from:{type:"app"},to:{type:"app"},type:"app"}};!((j=this===null||this===void 0?void 0:this.me)===null||j===void 0)&&j.id&&((X=this===null||this===void 0?void 0:this.me)===null||X===void 0?void 0:X.state)!=="LEFT"&&(J.from=this.me.id);try{const G=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/members`,version:"v0.3",data:J});return new s.default(this,G)}catch(G){throw new a.NexmoApiError(G)}}inviteWithAudio(N){return!N||!N.id&&!N.user_name?Promise.reject(new a.NexmoClientError("error:invite:missing:params")):(N.media={audio_settings:{enabled:!0,muted:!1,earmuffed:!1}},this.invite(N))}leave(N){return this.me.kick(N)}async sendText(N){try{if(this.me===null)throw new a.NexmoClientError("error:self");const j={type:"text",cid:this.id,from:this.me.id,body:{text:N}},{id:X,timestamp:J}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:j});return j.id=X,j.body.timestamp=J,new u.default(this,j)}catch(j){throw new a.NexmoApiError(j)}}async sendCustomEvent({type:N,body:j}){try{if(this.me===null)throw new a.NexmoClientError("error:self");if(!N||typeof N!="string"||N.length<1)throw new a.NexmoClientError("error:custom-event:invalid");const X={type:`custom:${N}`,cid:this.id,from:this.me.id,body:j},{id:J,timestamp:G}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:X});return X.id=J,X.timestamp=G,new o.default(this,X)}catch(X){throw new a.NexmoApiError(X)}}async sendEphemeralEvent(N){try{if(this.me===null)throw new a.NexmoClientError("error:self");const j={type:"ephemeral",cid:this.id,from:this.me.id,body:N},{id:X,timestamp:J}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:j});return j.timestamp=J,new o.default(this,j)}catch(j){throw new a.NexmoApiError(j)}}async uploadImage(N,j={quality_ratio:"100",medium_size_ratio:"50",thumbnail_size_ratio:"30"}){const X=new FormData;X.append("file",N),X.append("quality_ratio",j.quality_ratio),X.append("medium_size_ratio",j.medium_size_ratio),X.append("thumbnail_size_ratio",j.thumbnail_size_ratio);const J=await v.default.networkRequest({type:"POST",url:this.application.session.config.ips_url,data:X,token:this.application.session.config.token});return J.upload.addEventListener("progress",G=>{G.lengthComputable&&this.log.debug("uploading image "+G.loaded+"/"+G.total)},!1),J.onreadystatechange=()=>{J.status!==200&&this.log.error(J)},J}async sendImage(N,j={quality_ratio:"100",medium_size_ratio:"50",thumbnail_size_ratio:"30"}){const X=await this.uploadImage(N,j);return X.onreadystatechange=()=>{if(X.readyState===4&&X.status===200)try{this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:{type:"image",from:this.me.id,body:{representations:JSON.parse(X.responseText)}}}),this.log.info(X)}catch(J){this.log.error(new a.NexmoApiError(J))}},X}abortSendImage(N){return N instanceof XMLHttpRequest?N.abort():new a.NexmoClientError("error:invalid:param:type")}async sendMessage(N){if(this.me===null)throw new a.NexmoClientError("error:self");if(!(N!=null&&N.message_type))throw new a.NexmoClientError("error:message-event:invalid");try{const j={type:"message",cid:this.id,from:this.me.id,body:{...N}},{id:X,timestamp:J}=await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:j});return j.id=X,j.body.timestamp=J,new c.default(this,j)}catch(j){throw new a.NexmoApiError(j)}}async _typing(N){const j={cid:this.id,from:this.me.id};try{return await this.application.session.sendNetworkRequest({type:"POST",path:`conversations/${this.id}/events`,data:j}),`text:typing:${N}:success`}catch(X){throw new a.NexmoApiError(X)}}startTyping(){return this._typing("on")}stopTyping(){return this._typing("off")}async getEvents(N={}){const j=`${this.application.session.config.nexmo_api_url}/beta2/conversations/${this.id}/events`;let X=Object.keys(N).length===0?this.pageConfig:new m.default(N);try{const J=await v.default.paginationRequest(j,X,this.application.session.config.token);J.application=this.application,J.conversation=this;const G=new _.default(J);return this.events_page_last=G,G}catch(J){throw new a.NexmoApiError(J)}}async getMembers(N={}){const j=`${this.application.session.config.nexmo_api_url}/beta2/conversations/${this.id}/members`;let X=Object.keys(N).length===0?this.pageConfig:new m.default(N);try{const J=await v.default.paginationRequest(j,X,this.application.session.config.token);J.application=this.application,J.conversation=this;const G=new T.default(J);return this.members_page_last=G,G}catch(J){throw new a.NexmoApiError(J)}}async getMyMember(){try{const N=await this.application.session.sendNetworkRequest({type:"GET",path:`conversations/${this.id}/members/me`,version:"v0.3"});return new s.default(this,N)}catch(N){throw new a.NexmoApiError(N)}}async getMember(N){try{const j=await this.application.session.sendNetworkRequest({type:"GET",path:`conversations/${this.id}/members/${N}`,version:"v0.3"});return new s.default(this,j)}catch(j){throw new a.NexmoApiError(j)}}_handleEvent(N){var j,X;if(N.type.startsWith("rtc"))return this.emit(N.type,N),Promise.resolve(N);this.sequence_number++,N.body&&N.body.event_id&&typeof N.body.event_id=="string"&&(N.body.event_id=parseInt(N.body.event_id));let J={memberId:N.from};if(!((j=N==null?void 0:N.body)===null||j===void 0)&&j.user){const{id:L,name:re,display_name:ue,image_url:ee,custom_data:ye}=N.body.user;J={...J,...L&&{userId:L},...re&&{userName:re},...ue&&{displayName:ue},...ee&&{imageUrl:ee},...ye&&{customData:ye}}}else if(!((X=N==null?void 0:N._embedded)===null||X===void 0)&&X.from_user){const{id:L,name:re,display_name:ue,image_url:ee,custom_data:ye}=N._embedded.from_user;J={...J,...L&&{userId:L},...re&&{userName:re},...ue&&{displayName:ue},...ee&&{imageUrl:ee},...ye&&{customData:ye}}}let G=this.conversationEventHandler.handleEvent(N);return["text:typing:on","text:typing:off","ephemeral"].includes(N.type)||this.events.set(G.id,G),N.type.startsWith("custom:")?(this.emit(G.type,J,G),Promise.resolve(N)):(this.emit(N.type,J,G),Promise.resolve(N))}}r.default=$,e.exports=$}(Vc,Vc.exports)),Vc.exports}var il={exports:{}},G0;function bI(){return G0||(G0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(r,"__esModule",{value:!0});const n=Da,i=Ar,a=Hn,s=t(Wf());class o{constructor(c,l,p){this.application=c,this.log=i.getLogger(this.constructor.name),this.from=p,this.conversation=null,this.rtcObjects={},this.CALL_STATUS={STARTED:"started",RINGING:"ringing",ANSWERED:"answered",COMPLETED:"completed",BUSY:"busy",TIMEOUT:"timeout",UNANSWERED:"unanswered",REJECTED:"rejected",FAILED:"failed"},this.CALL_DIRECTION={INBOUND:"inbound",OUTBOUND:"outbound"},Object.freeze(this.CALL_DIRECTION),this.STATUS_PERMITTED_FLOW=new Map([["STARTED",new Set([this.CALL_STATUS.RINGING,this.CALL_STATUS.ANSWERED,this.CALL_STATUS.FAILED,this.CALL_STATUS.TIMEOUT,this.CALL_STATUS.UNANSWERED,this.CALL_STATUS.REJECTED,this.CALL_STATUS.BUSY])],["RINGING",new Set([this.CALL_STATUS.ANSWERED,this.CALL_STATUS.FAILED,this.CALL_STATUS.TIMEOUT,this.CALL_STATUS.UNANSWERED,this.CALL_STATUS.REJECTED,this.CALL_STATUS.BUSY])],["ANSWERED",new Set([this.CALL_STATUS.COMPLETED,this.CALL_STATUS.FAILED])]]),Object.freeze(this.STATUS_PERMITTED_FLOW),this.status=null,this.call_disconnect_timeout=null,this.direction=this.CALL_DIRECTION.INBOUND,this._setupConversationObject(l),n.mixin(o)}_enableStatsEvents(){this.conversation.media._enableStatsEvents()}_attachCallListeners(){this.log.debug("_attachCallListeners : ",{nxmCall:this});try{this.conversation.releaseGroup("call_module"),this.conversation.on("member:media","call_module",(c,l)=>{this.application.calls&&this.application.calls.has(this.conversation.id)&&this.application.calls.get(this.conversation.id)._handleStatusChange(l)})}catch(c){this.log.error("_attachCallListeners_error: ",{e:c})}}_isValidStatusTransition(c){if(!c)throw new a.NexmoClientError(`Provide the status to validate the transition from '${this.status}'`);if(!this.status)return!0;const l=this.status.toUpperCase();return!this.STATUS_PERMITTED_FLOW.has(l)||this.status===c?!1:this.STATUS_PERMITTED_FLOW.get(l).has(c)}hangUpIfAllLeft(){if(this.log.debug("hangUpIfAllLeft: ",{nxmCall:this}),!this.conversation.me||this.conversation.me.state==="LEFT"||this.conversation.members.size<=1)return Promise.resolve();for(let c of this.conversation.members.values())if(c.state!=="LEFT"&&this.conversation.me.user.id!==c.user.id)return Promise.resolve();return this.hangUp()}_setupConversationObject(c,l){c&&(this.conversation=c,c.me?(this.to=new Map(c.members),this.from&&this.to.delete(this.from.id)):this.log.warn("missing own member object"),this._attachCallListeners())}_setFrom(c){this.from=c}_setOffer(c){this.offer=c}_handleStatusChange(c){var l;const p=this.conversation?((l=this.conversation.me)===null||l===void 0?void 0:l.id)===c.from:!0,v=this.direction===this.CALL_DIRECTION.OUTBOUND;this.log.debug("_handleStatusChange: ",{event:c},`_isEventFromMe: ${p} _isOutbound: ${v}`);let m=new Map;if(m.set("member:joined",async()=>{if(c.body.channel&&c.body.channel.id)try{this._setStatusAndEmit(this.CALL_STATUS.STARTED);return}catch(_){throw this._setStatusAndEmit(this.CALL_STATUS.FAILED),this.log.error(_),_}return Promise.resolve()}),m.set("member:invited",()=>(c.body.invited_by===null&&c.body.user.media&&c.body.user.media.audio_settings&&this._setStatusAndEmit(this.CALL_STATUS.STARTED),Promise.resolve())),m.set("rtc:hangup",()=>this.status===this.CALL_STATUS.ANSWERED?(this._setStatusAndEmit(this.CALL_STATUS.COMPLETED),Promise.resolve()):p&&v||!p&&!v?(this._setStatusAndEmit(this.CALL_STATUS.UNANSWERED),Promise.resolve()):(this._setStatusAndEmit(this.CALL_STATUS.REJECTED),Promise.resolve())),m.set("member:left",()=>{if(!c.body.timestamp.hasOwnProperty("joined")&&this.status!==this.CALL_STATUS.ANSWERED)return p&&v||!p&&!v?(this._setStatusAndEmit(this.CALL_STATUS.UNANSWERED),Promise.resolve()):(this._setStatusAndEmit(this.CALL_STATUS.REJECTED),Promise.resolve())}),m.set("member:media",()=>(this.status!==this.CALL_STATUS.ANSWERED&&c.body.audio&&(p&&c.body.channel&&(this.id=c.body.channel.id),(!p||!v)&&this.id&&this._setStatusAndEmit(this.CALL_STATUS.ANSWERED)),Promise.resolve())),m.set("sip:ringing",()=>(this.status!==this.CALL_STATUS.RINGING&&this._setStatusAndEmit(this.CALL_STATUS.RINGING),Promise.resolve())),m.set("sip:hangup",()=>{switch(c.body.reason.sip_code){case 486:this._setStatusAndEmit(this.CALL_STATUS.BUSY);break;case 487:this._setStatusAndEmit(this.CALL_STATUS.TIMEOUT);break;case 403:this._setStatusAndEmit(this.CALL_STATUS.FAILED);break}return Promise.resolve()}),m.set("knocking:delete:success",()=>(this._setStatusAndEmit(this.CALL_STATUS.UNANSWERED),Promise.resolve())),m.has(c.type))return m.get(c.type).call(this)}_setStatusAndEmit(c){this._isValidStatusTransition(c)&&(this.status=c,this.log.debug(`_setStatusAndEmit: ${c}`,{nxmCall:this}),this.application.emit("call:status:changed",this))}async answer(c=!0){if(this.log.debug(`answer: { autoPlayAudio: ${c}`),this.conversation)try{await this.conversation.join();const l=await this.conversation.media.enable({autoPlayAudio:c,offer:this.offer});return this.offer=void 0,l}catch(l){throw this._setStatusAndEmit(this.CALL_STATUS.FAILED),this.log.error(l),l}else throw new a.NexmoClientError("error:call:answer")}async createCall(c,l=!0){if(this.log.debug(`createCall: { usernames: ${c}, autoPlayAudio: ${l} }`),!c||!Array.isArray(c)||c.length===0)return Promise.reject(new a.NexmoClientError("error:application:call:params"));try{const p=await this.application.newConversationAndJoin({display_name:"CALL_"+this.application.me.name+"_"+c.join("_").replace(" ","")});p.members.set(p.me.id,p.me),this.from=p.me,this.successful_invited_members=new Map;const v=c.map(async _=>{try{const T=await p.inviteWithAudio({user_name:_});return p.members.set(T.id,T),this.successful_invited_members.set(T.id,T),T}catch(T){return this.log.error(T),T}}),m=async()=>{if(this.successful_invited_members.size>0)return await p.media.enable({audio:{muted:!1,earmuffed:!1},autoPlayAudio:l}),this.application.calls.set(p.id,this),v;throw v};return await Promise.all(v),this._setupConversationObject(p),await m()}catch(p){throw this.log.error(p),this._setStatusAndEmit(this.CALL_STATUS.FAILED),p}}async createServerCall(c,l,p){this.log.debug(`createServerCall: { user: ${c}, type: ${l}, custom_data: `,{custom_data:p});const v={type:l};l==="phone"?v.number=c:v.user=c;try{const{stream:m,legId:_,rtcObjects:T}=await s.default.prewarmLeg(this);this.log.debug("createServerCall: ",{stream:m},{legId:_},{rtcObjects:T}),this.rtcObjects=T,this.stream=m,this.id=_,this.application._call_draft_list.set(_,this),s.default.playAudioStream(m);const I={type:"POST",path:"knocking",data:{channel:{type:"app",from:{type:"app"},to:v,id:_||null},...p&&Object.keys(p).length&&{properties:{custom_data:p}}}};try{const $=await this.application.session.sendNetworkRequest(I);this.knocking_id=$.id}catch($){throw new a.NexmoApiError($)}return s.default.cleanCallMediaIfFailed(this),m}catch(m){throw s.default.cleanMediaProperties(this),m}}async hangUp(c){if(this.log.debug(`hangUp: { reason: ${c} }`),this.conversation&&await this.conversation.media.disable(),!this.knocking_id&&this.conversation)return this.conversation.leave(c).catch(l=>{if(l.type!=="conversation:error:invalid-member-state")return Promise.reject(l)});{let l=`knocking/${this.knocking_id}`;if(c){let p=new URLSearchParams;Object.keys(c).forEach(v=>{p.append(v,c[v])}),l+=`?${p.toString()}`}try{const p=await this.application.session.sendNetworkRequest({type:"DELETE",path:l});return this.application._call_draft_list.get(this.client_ref)._handleStatusChange(p),this.application._call_draft_list.delete(this.client_ref),p}catch(p){if(this.conversation)return this.log.error(new a.NexmoApiError(p)),this.conversation.leave(c).catch(v=>{if(v.type!=="conversation:error:invalid-member-state")return Promise.reject(v)});this.log.debug("hangup: Problem cancelling the call. Knocking cancel failed and Conversation. Leave not available",p);return}}}reject(c){return this.log.debug(`reject: { reason: ${c} }`),this.conversation?this.conversation.leave(c):Promise.reject(new a.NexmoClientError("error:call:reject"))}}r.default=o,e.exports=o}(il,il.exports)),il.exports}var Mv={exports:{}};(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});const t=Ar;class n{constructor(a){this.log=t.getLogger(this.constructor.name),this.application=a,this._handleSipCallEventMap={"sip:hangup":this._processSipHangup,"sip:ringing":this._processSipRinging}}_handleSipCallEvent(a){if(this.log.debug("_handleSipCallEvent: ",{event:a}),!this.application.calls.has(a.cid)){this.log.warn("There is no call object for this Conversation id.");return}const s=this.application.calls.get(a.cid);if(this._handleSipCallEventMap.hasOwnProperty(a.type))return this._handleSipCallEventMap[a.type].call(this,s,a)}_processSipHangup(a,s){this.log.debug("_processSipHangup: ",s),a._handleStatusChange(s)}_processSipRinging(a,s){this.log.debug("_processSipRinging: ",s),a._handleStatusChange(s)}}r.default=n,e.exports=n})(Mv,Mv.exports);var yee=Mv.exports,xv={exports:{}};(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});const t=Ar;class n{constructor(a){this.log=t.getLogger(this.constructor.name),this.application=a,this._handleRtcEventMap={"rtc:transfer":this._processRtcTransfer,"rtc:answer":this._processRtcAnswer,"rtc:hangup":this._processRtcHangup}}_handleRtcEvent(a){if(this._handleRtcEventMap.hasOwnProperty(a.type))return this._handleRtcEventMap[a.type].call(this,a)}_processRtcTransfer(a){this.log.debug("_processRtcTransfer: ",{event:a});const s=this.application.conversations.get(a.body.transferred_from),o=this.application.conversations.get(a.cid),u=this.application.calls.get(a.body.transferred_from);if(!u){this.log.warn("NXMCall transfer for unknown nxmCall");return}u.conversation.members.get(a.body.was_member).transferred_to=o,u._setupConversationObject(o),u.transferred=!0,this.application.calls.set(a.cid,u),this.application.calls.delete(a.body.transferred_from),s&&(o.members.get(a.from).transferred_from=s,o.media._attachEndingEventHandlers(),Object.entries(o.media.rtcObjects).length===0&&Object.entries(s.media.rtcObjects).length!==0&&Object.assign(o.media.rtcObjects,s.media.rtcObjects),!o.media.pc&&s.media.pc&&Object.assign(o.media.pc=s.media.pc),o.application.activeStreams.length===0&&s.application.activeStreams.length>0&&(o.application.activeStreams=s.application.activeStreams))}_processRtcAnswer(a){this.log.debug("_processRtcAnswer: ",{event:a}),this.application.calls.has(a.cid)&&(this.application.calls.get(a.cid).id=a.body.rtc_id)}_processRtcHangup(a){this.log.debug("_processRtcHangup: ",{event:a}),this.application.calls.has(a.cid)&&this.application.calls.get(a.cid)._handleStatusChange(a)}}r.default=n,e.exports=n})(xv,xv.exports);var bee=xv.exports,al={exports:{}},V0;function _ee(){return V0||(V0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(r,"__esModule",{value:!0});const n=Ar,i=t(ia),a=t(bI()),s=t(Ii()),o=t(Wf());class u{constructor(l){this.log=n.getLogger(this.constructor.name),this.application=l,this._handleApplicationEventMap={"member:joined":this._processMemberJoined,"member:invited":this._processMemberInvited}}handleEvent(l){const p=this.application.conversations.get(l.cid),v=Object.assign({},l);return this._handleApplicationEventMap.hasOwnProperty(l.type)?this._handleApplicationEventMap[l.type].call(this,p,new i.default(p,v),l):new i.default(p,v)}_processMemberJoined(l,p,v){try{if(p.body.channel&&this.application._call_draft_list.has(p.body.channel.id)){this.log.debug("_processMemberJoined: outbound serverCall from sdk",{event:p});const m=this.application._call_draft_list.get(p.body.channel.id);let _=((m.rtcObjects||{})[p.body.channel.id]||{}).pc;if(m._setFrom(l.me),m._setupConversationObject(l,p.body.channel.id),l.media._attachEndingEventHandlers(),Object.entries(l.media.rtcObjects).length===0&&Object.entries(m.rtcObjects).length!==0&&Object.assign(l.media.rtcObjects,m.rtcObjects),!l.media.pc&&_&&Object.assign(l.media.pc=_),l.application.activeStreams.length===0&&m.application.activeStreams.length>0&&(l.application.activeStreams=m.application.activeStreams),delete m.client_ref,delete m.knocking_id,m.rtcStats&&(l.media.rtcStats=m.rtcStats),this.application._call_draft_list.delete(p.body.channel.id),this.application.calls.set(l.id,m),m._handleStatusChange(p),this.log.debug("_processMemberJoined: processedCall ",{nxmCall:m}),l.members&&p.body.member_id){const T=l.members.get(p.body.member_id);T&&this.application.emit("member:call",T,m)}setTimeout(()=>{l!=null&&l.me&&o.default.emitMediaStream(l.me,_,m.stream)},200)}return this.log.debug("_processMemberJoined: default member joined: ",{event:p}),p}catch(m){this.log.error("_processMemberJoined: ",{e:m})}}_processMemberInvited(l,p){var v,m,_,T,I,$;try{if(!l)return this.log.warn(`no conversation object for ${p.type}`),p;if(((v=l.me)===null||v===void 0?void 0:v.user.id)===p.body.invited_by||!(!((_=(m=p.body.user.media)===null||m===void 0?void 0:m.audio_settings)===null||_===void 0)&&_.enabled))return p;const x=s.default.getMemberNumberFromEventOrNull(p.body.channel)||s.default.getMemberFromNameOrNull(l,p.body.invited_by)||"unknown",N=new a.default(this.application,l,x);return this.application.calls.set(l.id,N),!((T=p.body)===null||T===void 0)&&T.sdp&&this.application.session.config.enableInboundOffer&&N._setOffer({sdp:p.body.sdp,leg_id:p.body.channel.id}),!((I=l.display_name)===null||I===void 0)&&I.startsWith("CALL_")||N._handleStatusChange(p),this.application.emit("member:call",this.application.conversations.get(p.cid).members.get(($=p.body)===null||$===void 0?void 0:$.member_id),N),p}catch(x){this.log.error("_processMemberInvited: ",{e:x})}}}r.default=u,e.exports=u}(al,al.exports)),al.exports}var Nv={exports:{}};(function(e,r){var t=Ne&&Ne.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(r,"__esModule",{value:!0});const n=t(Hf);class i extends n.default{constructor(s){super(s),this.items=new Map,s.items.forEach(o=>{const u=this.application.updateOrCreateConversation(o);this.items.set(u.id,u)})}getPrev(){return this.hasPrev()?this.application.getConversations(this._getConfig(this.cursor.prev)):this._getError()}getNext(){return this.hasNext()?this.application.getConversations(this._getConfig(this.cursor.next)):this._getError()}}r.default=i,e.exports=i})(Nv,Nv.exports);var wee=Nv.exports,Lv={exports:{}},Dv={exports:{}};(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});const t=Da;class n{constructor(a,s){var o,u;this.application=a,this.id=(o=s==null?void 0:s.id)!==null&&o!==void 0?o:null,this._embedded=(u=s==null?void 0:s._embedded)!==null&&u!==void 0?u:null,t.mixin(n)}}r.default=n,e.exports=n})(Dv,Dv.exports);var See=Dv.exports;(function(e,r){var t=Ne&&Ne.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(r,"__esModule",{value:!0});const n=t(Hf),i=t(See);class a extends n.default{constructor(o){super(o),this.items=new Map,o.items.forEach(u=>{this.items.set(u.id,new i.default(this.application,u))})}getPrev(){return this.hasPrev()?this.application.getUserSessions(this._getConfig(this.cursor.prev)):this._getError()}getNext(){return this.hasNext()?this.application.getUserSessions(this._getConfig(this.cursor.next)):this._getError()}}r.default=a,e.exports=a})(Lv,Lv.exports);var Tee=Lv.exports,sl={exports:{}},K0;function Cee(){return K0||(K0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(r,"__esModule",{value:!0}),r.ConversationEventsProcessor=r.EventsQueue=void 0;const n=Hn,i=t(Ii()),a=Ar;class s{constructor(c){this.callback=c,this.cidMap=new Map,this.log=a.getLogger(this.constructor.name)}async enqueue(c,l){var p,v,m,_,T,I,$,x;const{cid:N,id:j}=c,X=Number(j);if(!N||isNaN(X))return this.callback(c);if(((v=(p=l.conversations.get(N))===null||p===void 0?void 0:p.me)===null||v===void 0?void 0:v.state)==="LEFT")return this.callback(c);if(!this.cidMap.get(N)){this.log.debug(`enqueue: create new ConversationEventsProcessor for ${N}`);const G=new o(N,X-1,l);if(this.cidMap.set(N,G),c.type=="member:media"&&(!((_=(m=c.body)===null||m===void 0?void 0:m.media)===null||_===void 0)&&_.audio)||c.type=="member:joined"&&(!((I=(T=c.body)===null||T===void 0?void 0:T.channel)===null||I===void 0)&&I.id)&&((x=($=c.body)===null||$===void 0?void 0:$.channel)===null||x===void 0?void 0:x.knocking_id)===void 0){G.processing=!0,G.lastEventIdProcessed=0;try{await new Promise(ee=>setTimeout(ee,G.eventRequestWaitTime));const L=ee=>{var ye;return(ye=ee.find(Z=>(Z==null?void 0:Z.type)==="rtc:transfer"&&(Z==null?void 0:Z.from)===c.from))===null||ye===void 0?void 0:ye.id};let re=[Array.from(Array(5).keys()).map(ee=>X+1+ee),Array.from(Array(5).keys()).map(ee=>X-1-ee)].flatMap(ee=>ee).map(ee=>G.eventsMap.get(ee)).filter(ee=>ee),ue;if((ue=L(re))===void 0){const ee=Math.max(X-20,1);re=await G.fetchConversationEvents(ee,20)}(ue=L(re))!==void 0&&(ue=Number(ue),G.lastEventIdProcessed=Math.max(ue-1,0),re.slice(ue).forEach(ee=>G.enqueue(Number(ee.id),ee)))}finally{G.processing=!1}}}const J=this.cidMap.get(N);J.enqueue(X,c),J.processing||(J.processing=!0,await J.processEvents())}}r.EventsQueue=s;class o{constructor(c,l,p){this.cid=c,this.eventsMap=new Map,this.callback=v=>p._handleEvent(v),this.lastEventIdProcessed=l,this.largestEventIdInQueue=l,this.processing=!1,this.application=p,this.eventsFetchRange=9,this.eventRequestWaitTime=p.session.config.eventQueueWaitTime,this.log=a.getLogger(this.constructor.name)}enqueue(c,l){return c>this.largestEventIdInQueue&&(this.largestEventIdInQueue=c),c>this.lastEventIdProcessed&&this.eventsMap.set(c,l),l}dequeue(c){const l=this.eventsMap.get(c);return this.eventsMap.delete(c),l}async processEvents(){const c=()=>(this.eventsMap.clear(),this.log.debug("processEvents: Done Processing"),this.processing=!1);if(this.eventsMap.size<1)return c();const l=this.lastEventIdProcessed+1,p=await this.processNextEvent(l,1);return p?(this.lastEventIdProcessed=Number(p.id),this.processEvents()):c()}async processNextEvent(c,l){this.log.debug(`processNextEvent: processing event number ${c}`);const p=this.dequeue(c);try{if(p)return await this.callback(p),p;if(l>0)return await new Promise(v=>setTimeout(v,this.eventRequestWaitTime)),this.processNextEvent(c,l-1);if(this.largestEventIdInQueue>c){this.log.debug(`processNextEvent: largestEventIdInQueue-${this.largestEventIdInQueue} > eventId-${c}`);const v=await this.fetchEventsAndProcess(c);return v?(this.log.debug("processNextEvent: foundEvent ",{foundEvent:v}),await this.callback(v),v):(this.log.debug(`processNextEvent: not found process next ${c+1}`),this.processNextEvent(c+1,l))}return}catch{return}}async fetchEventsAndProcess(c){try{const l=await this.fetchConversationEvents(c,this.eventsFetchRange);this.log.debug("fetchEventsAndProcess: fetched events list ",{eventsList:l});let p;return l.forEach(v=>{v.cid=this.cid;const m=Number(v.id);isNaN(m)||m<c||(m>c?(this.log.debug(`fetchEventsAndProcess: event > missingEvent ${m} `,{missingEvent:c}),this.enqueue(m,v)):(this.log.debug("fetchEventsAndProcess: foundEvent ",{event:v}),p=v))}),p}catch(l){this.log.debug("fetchEventsAndProcess: error ",{e:l});return}}async fetchConversationEvents(c,l){this.log.debug("fetchConversationEvents: ",this.cid,c);const p=this.largestEventIdInQueue>c?this.largestEventIdInQueue+l:c+l,v=`${this.application.session.config.nexmo_api_url}/beta2/conversations/${this.cid}/events`;try{return(await i.default.paginationRequest(v,{start_id:c,end_id:p},this.application.session.config.token)).items}catch(m){throw new n.NexmoApiError(m)}}}r.ConversationEventsProcessor=o,e.exports={EventsQueue:s,ConversationEventsProcessor:o}}(sl,sl.exports)),sl.exports}var J0;function Gf(){return J0||(J0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(J){return J&&J.__esModule?J:{default:J}};Object.defineProperty(r,"__esModule",{value:!0});const n=Da,i=Ar,a=Hn,s=t(k$),o=t(yI()),u=t(bI()),c=t(yee),l=t(bee),p=t(_ee()),v=t(Ii()),m=t(gI),_=t(wee),T=t(Tee),I=Cee(),$=t(Dg());let x=null,N=null,j=null;class X{constructor(G,L){this.log=i.getLogger(this.constructor.name),this.session=G,this.conversations=new Map,this.synced_conversations_count=0,this.start_sync_time=0,this.stop_sync_time=0,this.calls=new Map,this._call_draft_list=new Map,this.pageConfig=new m.default((G.config||{}).conversations_page_config),this.conversations_page_last=null,this.activeStreams=[],x=new c.default(this),N=new l.default(this),j=new p.default(this),this.me=null,Object.assign(this,L),n.mixin(X)}updateOrCreateConversation(G){const L=this.conversations.get(G.id);return L?(L._updateObjectInstance(G),this.conversations.set(G.id,L)):this.conversations.set(G.id,new o.default(this,G)),this.conversations.get(G.id)}async _enqueueEvent(G){this.session.config.enableEventsQueue?(this.eventsQueue||(this.eventsQueue=new I.EventsQueue(L=>this._handleEvent(L))),this.eventsQueue.enqueue(G,this)):this._handleEvent(G)}async _handleEvent(G){var L,re,ue,ee,ye,Z,qe;const Qe=!((L=G._embedded)===null||L===void 0)&&L.from_user?((ue=(re=G._embedded)===null||re===void 0?void 0:re.from_user)===null||ue===void 0?void 0:ue.id)===((ee=this.me)===null||ee===void 0?void 0:ee.id):((Z=(ye=G.body)===null||ye===void 0?void 0:ye.user)===null||Z===void 0?void 0:Z.user_id)===((qe=this.me)===null||qe===void 0?void 0:qe.id),Nt=v.default._checkIfUserIsReInvited(this.conversations,G);if(G.type.startsWith("sip"))return x._handleSipCallEvent(G),G;if(this.conversations.has(G.cid)&&G.type!=="rtc:transfer"&&!Nt)return G.type.startsWith("rtc")&&N._handleRtcEvent(G),this.conversations.get(G.cid)._handleEvent(G),(G.type==="member:joined"||G.type==="member:invited")&&Qe&&this._handleApplicationEvent(G),G;if(G.cid)try{Nt&&this.conversations.delete(G.cid);let vt;return v.default._isCallEvent(G)?vt=await this.getConversation(G.cid,X.CONVERSATION_API_VERSION.v1):vt=await this.getConversation(G.cid,X.CONVERSATION_API_VERSION.v3),this.conversations.set(G.cid,vt),await vt._handleEvent(G),await this._handleApplicationEvent(G),G.type.startsWith("rtc")&&N._handleRtcEvent(G),Promise.resolve(G)}catch(vt){return this.log.error(vt),Promise.reject(vt)}}async updateToken(G){if(this.session.connection&&this.session.connection.disconnected)return this.session.config.token=G,this.session.connection.io.opts.query.token=G,Promise.resolve();const L={url:`${this.session.config.nexmo_api_url}/v0.2/sessions/${this.session.session_id}`,type:"PUT",token:G};try{await v.default.networkRequest(L),this.me&&(this.session.config.token=G,this.session.connection.io.opts.query.token=G)}catch(re){throw new a.NexmoApiError(re)}}async _handleApplicationEvent(G){try{this.log.debug("_handleApplicationEvent: ",{event:G});const L=j.handleEvent(G),re=this.conversations.get(G.cid);let ue;if(re.members.has((L||{}).from))ue=re.members.get(L.from);else if(G.type==="member:joined"||G.type==="member:invited"){const ee={...G.body,...G.from&&{member_id:G.from}};ue=new $.default(re,ee)}else try{ue=await re.getMember(L.from)}catch(ee){this.log.warn(`There is an error getting the member ${ee}`)}return this.emit(L.type,ue,L),G}catch(L){throw this.log.error("_handleApplicationEvent: ",L),L}}async inAppCall(G){if(!G||!Array.isArray(G)||G.length===0)return Promise.reject(new a.NexmoClientError("error:application:call:params"));try{const L=new u.default(this);return await L.createCall(G),L.direction=L.CALL_DIRECTION.OUTBOUND,L}catch(L){throw L}}async callServer(G,L="phone",re={}){try{const ue=new u.default(this);return ue.direction=ue.CALL_DIRECTION.OUTBOUND,await ue.createServerCall(G,L,re),ue}catch(ue){throw ue}}async reconnectCall(G,L,re={}){try{if(!G||!L)throw new a.NexmoClientError("error:missing:params");const ue=await this.getConversation(G,X.CONVERSATION_API_VERSION.v1);await ue.media.enable({...re,reconnectRtcId:L});const ee=new u.default(this,ue),ye=Array.from(ue.events.values()).map(Z=>Z.type);return ye.includes("sip:answered")?ee.status=ee.CALL_STATUS.ANSWERED:ye.includes("sip:ringing")?ee.status=ee.CALL_STATUS.RINGING:ee.status=ee.CALL_STATUS.STARTED,ee.rtcObjects=ue.media.rtcObjects,this.calls.set(ue.id,ee),ee}catch(ue){throw ue}}async newConversation(G={}){try{const L=await this.session.sendNetworkRequest({type:"POST",path:"conversations",data:G}),re=new o.default(this,L);return this.conversations.set(re.id,re),this.getConversation(re.id,X.CONVERSATION_API_VERSION.v1)}catch(L){throw new a.NexmoApiError(L)}}async newConversationAndJoin(G){const L=await this.newConversation(G);return await L.join(),L}async getConversation(G,L=X.CONVERSATION_API_VERSION.v3){if(L!==X.CONVERSATION_API_VERSION.v1&&L!==X.CONVERSATION_API_VERSION.v3)throw new a.NexmoClientError("error:conversation-service:version");let re;if(L===X.CONVERSATION_API_VERSION.v1)try{re=await this.session.sendNetworkRequest({type:"GET",path:`conversations/${G}`}),re.id=re.uuid,delete re.uuid}catch(ee){throw new a.NexmoApiError(ee)}else try{re=await this.session.sendNetworkRequest({type:"GET",path:`conversations/${G}`,version:"v0.3"})}catch(ee){throw new a.NexmoApiError(ee)}const ue=this.updateOrCreateConversation(re);if(L===X.CONVERSATION_API_VERSION.v3&&!ue.me)try{const ee=await ue.getMyMember();ue.me=ee,ue.members.set(ee.id,ee)}catch{try{const ye=await ue.getMyMember();ue.me=ye,ue.members.set(ye.id,ye)}catch{this.log.warn(`You don't have any membership in ${ue.id}`)}}if(this.session.config.sync==="full"){const{items:ee}=await ue.getEvents();return ue.events=ee,ue}else return ue}async getConversations(G={}){const L=`${this.session.config.nexmo_api_url}/beta2/users/${this.me.id}/conversations`;let re=Object.keys(G).length===0?this.pageConfig:new m.default(G);try{const ue=await v.default.paginationRequest(L,re,this.session.config.token);ue.application=this;const ee=new _.default(ue);return this.conversations_page_last=ee,ee}catch(ue){throw new a.NexmoApiError(ue)}}syncConversations(G){const L=Array.from(G.values()),re=L.length,ue=new Date;this.start_sync_time=typeof window<"u"&&window.performance?window.performance.now():ue.getTime();const ee=async()=>{this.synced_conversations_percentage=Number((this.synced_conversations_count/re*100).toFixed(2));const ye={sync_progress:this.synced_conversations_percentage};if(this.emit("sync:progress",ye),this.log.info("Loading sync progress: "+this.synced_conversations_count+"/"+re+" - "+this.synced_conversations_percentage+"%"),this.synced_conversations_percentage>=100){const Z=new Date;this.stop_sync_time=typeof window<"u"&&window.performance?window.performance.now():Z.getTime(),this.log.info("Loaded conversations in "+(this.stop_sync_time-this.start_sync_time)+"ms")}this.synced_conversations_count<re&&(await this.getConversation(L[this.synced_conversations_count].id),ee(),this.synced_conversations_count++,this.sync_progress_buffer++)};ee()}async getUser(G=this.me.id){try{const L=await this.session.sendNetworkRequest({type:"GET",path:`users/${G}`});return new s.default(this,L)}catch(L){throw new a.NexmoApiError(L)}}async getUserSessions(G={}){var L;const re=((L=G)===null||L===void 0?void 0:L.user_id)||this.me.id,ue=`${this.session.config.nexmo_api_url}/v0.3/users/${re}/sessions`;let ee=Object.keys(G).length===0?this.pageConfig:new m.default(G);try{const ye=await v.default.paginationRequest(ue,ee,this.session.config.token,X.CONVERSATION_API_VERSION.v3);ye.application=this;const Z=new T.default(ye);return this.user_sessions_page_last=Z,Z}catch(ye){throw new a.NexmoApiError(ye)}}}r.default=X,X.CONVERSATION_API_VERSION={v1:"v0.1",v3:"v0.3"},e.exports=X}(Gc,Gc.exports)),Gc.exports}var Y0;function Ii(){return Y0||(Y0=1,function(e,r){var t=Ne&&Ne.__importDefault||function(p){return p&&p.__esModule?p:{default:p}};Object.defineProperty(r,"__esModule",{value:!0});const n=t(DZ),i=t(_$),a=t(Gf()),s=4e4,o=2e4,u=new RegExp(`"|'|<|>|&|\\|/`),c=new RegExp(`"|'|<|>|\\|javascript:`);class l{static getMemberFromNameOrNull(v,m){if(!v||!m)return null;for(let _ of v.members.values())if(_.user.name===m)return _;return null}static getMemberNumberFromEventOrNull(v){const m=v&&v.from;return m&&(m.number||m.uri)?m.number||m.uri:null}static isSanitizedInput(v){return!u.test(v)}static isSanitizedUrlInput(v){return!c.test(v)}static checkIsSanitized([v,m]){if(m==null)return!0;switch(typeof m){case"string":return v.includes("url")||v.includes("uri")?l.isSanitizedUrlInput(m):l.isSanitizedInput(m);case"object":return Array.isArray(m)?m.every(_=>l.checkIsSanitized(["dummy",_])):Object.entries(m).every(l.checkIsSanitized);default:return!0}}static networkRequest(v){return new Promise((m,_)=>{!v.token&&!v.url.includes("logging")&&!v.url.includes("ping")&&_({response:{type:"error:user:token",description:"network error on request. Please create a new session."}});const T=new XMLHttpRequest;let I;T.open(v.type,v.url,!0),v.token&&T.setRequestHeader("Authorization","Bearer "+v.token),v&&v.url.includes("image")?(T.responseType="",I=v.data,T.onloadstart=()=>{m(T)}):(T.responseType=v.responseType||"json",I=v.data?JSON.stringify(v.data):null,T.setRequestHeader("Content-type","application/json; charset=utf-8")),T.onload=()=>{T.status===200||T.status===201||T.status===204?m(T):_(T)},T.onerror=$=>{_($)},T.send(I)})}static async paginationRequest(v,m,_,T=a.default.CONVERSATION_API_VERSION.v1){try{const I=await l.networkRequest({type:"GET",url:l.addUrlSearchParams(v,m),token:_}),{page_size:$,_embedded:x,_links:N}=I.response,j=v.split("/").pop().trim();return{items:T===a.default.CONVERSATION_API_VERSION.v1?x.data[j]:x[j],cursor:{prev:N.prev?new URLSearchParams(N.prev.href).get("cursor"):"",next:N.next?new URLSearchParams(N.next.href).get("cursor"):"",self:N.self?new URLSearchParams(N.self.href).get("cursor"):""},page_size:$,order:m.order||"asc",event_type:m.event_type||null}}catch({response:I}){const $=I||{type:"error:network:get-request",description:"network error on nexmo get request"};throw $.validation&&($.description=$.validation[Object.keys($.validation)[0]]),$}}static addUrlSearchParams(v,m={}){let _=new URL(v);return Object.keys(m).forEach(T=>{m[T]&&!(typeof m[T]=="string"&&m[T].length<1)&&m[T]!==null&&_.searchParams.set(T,m[T])}),_.href}static deepMergeObj(v,m){const _=JSON.parse(JSON.stringify(v));for(let T in m)Object.prototype.toString.call(m[T])==="[object Object]"?_[T]=l.deepMergeObj(_[T],m[T]):_[T]=m[T];return _}static injectScript(v,m){if(typeof document<"u"){let _=document.getElementsByTagName("head")[0],T=document.createElement("script");T.async=!0,T.src=v,T.onload=T.onreadystatechange=()=>{(!T.readyState||/loaded|complete/.test(T.readyState))&&(T.onload=T.onreadystatechange=null,T=null,m&&m())},_.insertBefore(T,_.firstChild)}}static allocateUUID(){return n.default.v4()}static validateDTMF(v){return typeof v=="string"?/^[\da-dA-D#*pP]{1,45}$$/.test(v):!1}static _getBugsnagKey(){return"76498fc1ca8d9b0a173a44e2b873d7ed"}static updateMemberLegs(v,m){if(v){const _=v.find(T=>T.leg_id===m.body.leg_id);if(!_)v.push({leg_id:m.body.leg_id,status:m.body.status});else if(_.status!==m.body.status){let T=v.indexOf(_);v.fill(_.status=m.body.status,T,T++)}}else v=[{leg_id:m.body.leg_id,status:m.body.status}];return v}static _isCallEvent(v){const{channel:m,media:_}=v.body;return!!(v.type==="rtc:transfer"||m&&(_&&_.audio_settings&&_.audio_settings.enabled||_&&_.audio&&_.audio.enabled||m.knocking_id))}static async _fetchImage(v,m){const{response:_}=await l.networkRequest({type:"GET",url:v,responseType:"arraybuffer",token:m}),T=new Uint8Array(_);let I="";const $=8*1024;let x;for(x=0;x<T.length/$;x++)I+=String.fromCharCode.apply(null,T.subarray(x*$,(x+1)*$));return I+=String.fromCharCode.apply(null,T.subarray(x*$)),"data:image/jpeg;base64,"+btoa(I)}static async _checkHttpConnectivity(v){const m=Date.now();try{await l.networkRequest({type:"GET",url:v});const _=Date.now()-m;return{url:v,canConnect:!0,connectionTime:_}}catch(_){return{url:v,canConnect:!1,error:_}}}static _checkWsConnectivity(v,m,_){return new Promise((T,I)=>{const $=Object.assign({path:m},_),x=Date.now(),N=i.default.connect(v,$),j=setTimeout(()=>T({url:v,canConnect:!1}),o);N.on("connect",()=>{const X=Date.now()-x;N.disconnect(),clearTimeout(j),T({url:v,canConnect:!0,connectionTime:X})}),N.on("error",X=>{N.disconnect(),clearTimeout(j),T({url:v,canConnect:!1,error:X})})})}static async _checkMediaServers(v,m,_){try{const{response:T}=await l.networkRequest({type:"GET",url:`${m}/v0.3/discovery/media/${_}`,token:v}),I=T.map($=>l._checkMediaConnectivity($.ip,$.port));return await Promise.all(I)}catch{return[]}}static async _checkMediaConnectivity(v,m){return new Promise(async(_,T)=>{const I={iceServers:[{urls:`stun:${v}:${m}`}]},$=new RTCPeerConnection(I),x=Date.now(),N=await $.createOffer({offerToReceiveAudio:!0});$.setLocalDescription(N);const j=setTimeout(()=>{$.close(),_({ip:v,canConnect:!1})},s);$.addEventListener("icecandidate",X=>{var J;if(((J=X==null?void 0:X.candidate)===null||J===void 0?void 0:J.type)==="srflx"){const G=Date.now()-x;clearTimeout(j),$.close(),_({ip:v,canConnect:!0,connectionTime:G})}}),$.addEventListener("icecandidateerror",X=>{X.errorCode&&($.close(),clearTimeout(j),_({ip:v,canConnect:!1,error:X}))})})}static _checkIfUserIsReInvited(v,m){var _;if(!v.has(m.cid)||!(m.type==="member:invited"||m.type==="member:joined"))return!1;const T=(_=v.get(m.cid))===null||_===void 0?void 0:_.me;return T?T.user.name===m.body.user.name&&T.state==="LEFT":!1}}r.default=l,e.exports=l}(Wc,Wc.exports)),Wc.exports}var jv={exports:{}};(function(e,r){Object.defineProperty(r,"__esModule",{value:!0});const t=Ar,n=Hn;class i{constructor(s){if(this.log=t.getLogger(this.constructor.name),!s)throw new n.NexmoClientError("no emitter object passed for the Error Emitter");this.emitter=s,this.LISTENER_GROUP="NXM-errors"}emitResponseIfError(s){if(this._isTypeError(s.type))return this.emitter.emit(s.type,this.LISTENER_GROUP,s)}cleanup(){return this.emitter.releaseGroup(this.LISTENER_GROUP)}_isTypeError(s){return s.indexOf("error")!==-1}}r.default=i,e.exports=i})(jv,jv.exports);var Eee=jv.exports;(function(e,r){var t=Ne&&Ne.__importDefault||function(I){return I&&I.__esModule?I:{default:I}};Object.defineProperty(r,"__esModule",{value:!0});const n=Da,i=t(EX),a=t(Ar),s=Hn,o=t(_$),u=t(_Z),c=t(kZ),l=t(Ii()),p=t(Gf()),v=t(Eee),m=t(k$),_=t(Wf());i.default.reg(a.default),i.default.apply(a.default,{template:"[%t] %l (NXM-%n):",timestampFormatter:I=>I.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),levelFormatter:I=>I.toUpperCase(),nameFormatter:I=>I||"SDK"});class T{constructor($={}){const x=$;if(this.config={debug:"silent",log_reporter:{enabled:!1,bugsnag_key:null},environment:"production",ips_url:"https://api-us.vonage.com/v1/image",nexmo_api_url:"https://api-us.vonage.com",path:"/v2/rtc",repository:"https://github.com/Nexmo/conversation-js-sdk",SDK_version:"9.6.1",socket_io:{reconnection:!0,reconnectionAttempts:5,reconnectionDelay:2e3,randomizationFactor:.75,reconnectionDelayMax:15e3,forceNew:!0,autoConnect:!0,transports:["websocket"]},sync:"none",url:"https://ws-us.vonage.com",iceServers:[],rtcstats:{remote_collection:!0,remote_collection_url:"https://hlg.tokbox.com/prod/logging/nexmo_client_js_stats",remote_collection_interval:5e3,emit_events:!1,emit_rtc_analytics:!1,emit_interval:1e3},conversations_page_config:{page_size:10,order:"asc",cursor:""},events_page_config:{page_size:10,order:"asc",event_type:""},enableEventsQueue:!0,eventQueueWaitTime:50,enableInboundOffer:!1,acknowledgeEvents:!0,token:null},this.config.socket_io.query={token:"",SDK_version:this.config.SDK_version,session_version:$.enableInboundOffer?"0.0.3":"0.0.1",acknowledge_events:this.config.acknowledgeEvents,OS_family:"js",OS_revision:typeof navigator<"u"?navigator.userAgent:typeof window<"u"?window.navigator.userAgent:"Generic JS navigator"},this.sessionReady=!1,this.disconnectTimestamp=null,this.session_id=null,this.apiKey=null,this.requests={},this.application=null,["debug","info","warn","error"].includes(x.debug)?a.default.setLevel(x.debug):x.debug===!0?a.default.setLevel("debug"):a.default.setLevel("silent"),this.log=a.default.noConflict(),this.config=l.default.deepMergeObj(this.config,this._sanitizeConfig(x)),this.config.log_reporter.enabled){const N={apiKey:this.config.log_reporter.bugsnag_key||l.default._getBugsnagKey(),appVersion:this.config.socket_io.query.SDK_version,releaseStage:this.config.environment};Ne.NXMbugsnagClient=u.default(N)}n.mixin(T)}_createAndSetConnection(){let $,x=Object.assign({path:this.config.path},this.config.socket_io);return $=o.default.connect(this.config.url,x),this.connection=$,$.on("connect",()=>{this.emit("ready"),this.sessionReady=!0,this.log.info("websocket ready")}),$.on("disconnect",(N,j)=>{this.emit("disconnect",N==="io client disconnect"?T.DISCONNECT_REASON.ClientDisconnected:N==="io server disconnect"&&this.session_id?T.DISCONNECT_REASON.TokenExpired:T.DISCONNECT_REASON.ConnectionError),this.disconnectTimestamp=Date.now(),this.log.info("websocket disconnected",N,j)}),$.io.on("reconnect",N=>{this.emit("reconnect",N),this.log.info("websocket reconnect",N),l.default.networkRequest({url:`${this.config.url.replace("wss://","https://")}/v2/rtc/metrics`,type:"POST",token:this.config.token,data:{sessionId:this.session_id,metrics:[{name:"TIME_TO_RECONNECT_SUCCESS",time:this.disconnectTimestamp?Date.now()-this.disconnectTimestamp:void 0,attempt:N}]}}).catch(j=>{this.log.warn("Failed to publish socket reconnection metrics",j)})}),$.io.on("reconnect_attempt",N=>{this.emit("reconnecting",N),this.log.info("websocket reconnecting",N)}),$.on("connect_error",N=>{this.emit("error",new s.NexmoClientError(N)),this.log.error("Socket.io reported a generic error",N)}),$.io.on("reconnect_failed",()=>{this.emit("error",new s.NexmoClientError("error:client:reconnection_failed")),this.log.error("websocket reconnection error")}),$.io.on("packet",N=>{if(N.type!==2||N.data[0]==="echo")return;const j=N.data[2];j&&typeof j=="function"&&j();const X=N.data[1];if(X.type=N.data[0],this.log.debug("<--",X.type,X),this.requests["session:login"]){const J=this.requests["session:login"].callback;delete this.requests["session:login"],J(X)}else if(X.rid in this.requests){const J=this.requests[X.rid].callback;delete this.requests[X.rid],delete X.delay,this.errorsEmitter&&this.errorsEmitter.emitResponseIfError(X),J(X)}else this.errorsEmitter&&X.type.startsWith("system:error:")?this.errorsEmitter.emitResponseIfError(X):X.type.startsWith("session:")?this.updateSession(X):this.application&&this.application._enqueueEvent(X)}),$}_sanitizeConfig($){let x=$;return $.sync&&["none","lite","full"].indexOf($.sync)===-1&&(this.log.warn(`invalid param '${$.sync}' for sync, reverting to ${this.config.sync}`),x.sync=this.config.sync),x}sendRequest($,x){$.tid=l.default.allocateUUID();const N=$.type;delete $.type,this.log.debug("-->",N,$),this.log.info("-->",N,$.tid),this.connection.emit(N,$),this.requests[$.tid]={type:N,request:$,callback:x}}async sendNetworkRequest($){const x=$.version||"beta",N=`${this.config.nexmo_api_url}/${x}/${$.path}`;if(!($.type==="GET"||$.type==="DELETE")&&($.data={...$.data,originating_session:this.session_id},!l.default.checkIsSanitized(["data",$.data])))throw new s.NexmoClientError("error:input:unsanitized");try{const j={type:$.type,url:N,data:$.data?$.data:null,token:($.data||{}).token?$.data.token:this.config.token||null};this.log.debug("sendNetworkRequest: ",{request:j});const{response:X}=await l.default.networkRequest(j);return X}catch({response:j}){throw j}}createSession($){return this.config.socket_io.query.token=$,this._createAndSetConnection(),new Promise((x,N)=>{this.log.info(`Client-SDK Version: ${this.config.SDK_version}`),this.config.token=null,this.requests["session:login"]={type:"session:login",callback:async j=>{if(j.type==="session:success")if(this.session_id=j.body.id,this.apiKey=j.body.api_key,this.config.token=$,this.connection.io.opts.query={session_id:this.session_id,token:this.config.token},(!this.application||this.application.me&&this.application.me.id!==j.body.user_id)&&(this.application=new p.default(this,{})),this.application.me||(this.application.me=new m.default(this.application,{id:j.body.user_id,name:j.body.name})),this.errorsEmitter||(this.errorsEmitter=new v.default(this.application)),this.config.log_reporter.enabled&&(Ne.NXMbugsnagClient.user={id:this.application.me.id,name:this.application.me.name,session_id:j.body.id}),this.config.sync!=="none")try{await this.application.getConversations(),x(this.application)}catch(X){N(X)}else x(this.application);else N(new s.NexmoApiError(j))}}})}deleteSession(){return new Promise(async($,x)=>{const N=()=>this.sendRequest({type:"session:logout",body:{}},j=>{j.type==="session:logged-out"||j.type==="session:terminated"?(this.disconnect(),delete this.errorsEmitter,delete this.application,delete this.connection,this.requests={},this.sessionReady=!1,$(j)):x(j)});if(this.application){let j=[];if(this.application.conversations.size)for(let X of this.application.conversations.values())j.push(X.media.disable());try{await Promise.all(j)}catch(X){this.log.error("deleteSession: ",X)}return N()}else return N()})}updateSession($){$.type==="session:success"&&(this.session_id=$.body.id,this.connection.io.opts.query.session_id=$.body.id,this.application&&$.body.pending_events&&$.body.pending_events.forEach(x=>this.application._enqueueEvent(x)))}disconnect(){return this.connection.disconnect()}connect(){return this.connection.connect()}async connectivityReport($,x){const j={machineInfo:{ip:_.default.isNode()?void 0:await c.default.v4()},connectivityReport:[]};try{const{response:X}=await l.default.networkRequest({type:"GET",url:`${this.config.nexmo_api_url}/v0.3/discovery/api`,token:$});let J=X;x!=null&&x.dcListCallback&&(J=x.dcListCallback(J));for(const G in J){const L=J[G].endpoint,re=J[G].https,ue=J[G].ws;try{const ee=await l.default._checkHttpConnectivity(re),ye=await l.default._checkWsConnectivity(ue,this.config.path,this.config.socket_io),Z=await l.default._checkMediaServers($,L,G),qe={name:G,signalConnectionReport:{https:ee,ws:ye},mediaConnectionReport:Z};j.connectivityReport.push(qe)}catch(ee){this.log.error(`Error generating report for ${G}`,ee)}}}catch(X){this.log.error("Error fetching nexmo servers information",X)}return j}async checkMediaServers($,x,N){return await l.default._checkMediaServers($,x,N)}async checkMediaConnectivity($,x){return await l.default._checkMediaConnectivity($,x)}}r.default=T,T.DISCONNECT_REASON={ClientDisconnected:"ClientDisconnected",TokenExpired:"TokenExpired",ConnectionError:"ConnectionError"},e.exports=T})(lv,lv.exports);var kee=lv.exports;const Ree=pT(kee),Li=new $a("nexmo-chat"),$ee=["us-3","us-4","eu-3","eu-4","ap-3","ap-4"];class _I extends qv{constructor(){super(...arguments);pt(this,"rtc");pt(this,"application");pt(this,"conversation")}get _client(){if(this.rtc)return this.rtc;const t=Iee(this.region);return this.rtc=new Ree({nexmo_api_url:`https://api-${this.region}.${t}`,url:`wss://ws-${this.region}.${t}`}),this.rtc}async create(){const{identity:t,token:n}=await this.issueChatToken();Li.info(`Connecting chat, identity: ${t}, token: ${n}`),this.identity=t,this.application=await this._client.createSession(n)}async destroy(){this.rtc&&(await this.rtc.deleteSession(),this.rtc=null,this.application=null,this.conversation=null)}async join(t){const n=await this.application.getConversation(t);n.me.state==="JOINED"?Li.info("already joined conversation:",t):(await n.join(),Li.info("success joined conversation:",t)),this.registerEvents(n),this.conversation=n}async preview(t){await this.conversation.sendCustomEvent({type:"ujet_preview",body:{chat_preview:t,chat_preview_updated_at:new Date().toJSON()}})}async fetchMessages(t){const n=await this.conversation.getEvents({event_type:"message",order:"desc",page_size:100}),i=[];return n.items.forEach(a=>{const s=a._embedded.from_user.name,o=X0(a,s);t[o.$index]&&(o.file=t[o.$index]),this.trackInTask(o),i.push(o)}),i.reverse()}async sendMessage(t){try{const n=await this.conversation.sendMessage({message_type:"text",text:JSON.stringify(t)});return Li.info(`Message sent from ${this.conversation.id}, id: ${n.id}`),parseInt(n.id,10)}catch(n){Li.warn(`Failed to send a message from ${this.conversation.id}`,{error:n})}}startTyping(){this.conversation&&this.conversation.startTyping()}stopTyping(){this.conversation&&this.conversation.stopTyping()}registerConversationEvents(){this.registerEvents(this.conversation)}registerEvents(t){t.on("message",(n,i)=>{const a=X0(i,n.userName);Li.info(`Message added from ${this.conversation.id}, index: ${a.$index}, sid: ${a.$sid}, timestamp: ${a.$timestamp}, user type: ${a.$userType}`),a.$userType!=="end_user"&&this.ping(),this.trackInTask(a),this.events.triggerEvent("message",a)}),t.on("member:joined",n=>{Li.info("conversation: memberJoined",n),this.events.triggerEvent("memberJoined",n.userName)}),t.on("member:left",n=>{Li.info("conversation: memberLeft",n),this.events.triggerEvent("memberLeft",n.userName)}),t.on("text:typing:on",n=>{/^end_user/.test(n.userName)||this.events.triggerEvent("typingStarted",n.userName)}),t.on("text:typing:off",n=>{/^end_user/.test(n.userName)||this.events.triggerEvent("typingEnded",n.userName)})}}pt(_I,"type","nexmo_conversations");zv(_I);function Iee(e){return $ee.indexOf(e)>-1?"vonage.com":"nexmo.com"}function X0(e,r){const{id:t,timestamp:n,body:i}=e,[a,s]=r.split("-");let o=0;s&&(o=parseInt(s,10));const u={$index:parseInt(t,10),$sid:t,$timestamp:new Date(Date.parse(n)),$userType:a,$userId:o};try{const c=JSON.parse(i.text);return c.message&&!c.type?{...u,...c,type:"message"}:{...u,...c}}catch(c){return Li.warn("Format message failed",{error:c,data:i.text}),{...u,type:"text",content:i.text}}}exports.Client=mA;exports.ENVIRONMENT=CI;exports.EventManager=Bv;exports.Logger=$a;exports.MediaStore=aT;exports.OPTIONS=Br;exports.PostSessionStatus=Qs;exports.VERSION=Fv;exports.addProviderType=zv;exports.consoleLoggerHandler=rO;