12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- diff --git a/node_modules/strophe.js/dist/strophe.common.js b/node_modules/strophe.js/dist/strophe.common.js
- index 41e432f..4da268e 100644
- --- a/node_modules/strophe.js/dist/strophe.common.js
- +++ b/node_modules/strophe.js/dist/strophe.common.js
- @@ -4999,7 +4999,7 @@ Strophe.Websocket = class Websocket {
- Strophe.warn("Couldn't send <close /> tag.");
- }
- }
- - setTimeout(() => this._conn._doDisconnect, 0);
- + setTimeout(() => this._conn._doDisconnect(), 0);
- }
-
- /** PrivateFunction: _doDisconnect
- diff --git a/node_modules/strophe.js/dist/strophe.esm.js b/node_modules/strophe.js/dist/strophe.esm.js
- index ea4e224..aadd705 100644
- --- a/node_modules/strophe.js/dist/strophe.esm.js
- +++ b/node_modules/strophe.js/dist/strophe.esm.js
- @@ -4995,7 +4995,7 @@ Strophe.Websocket = class Websocket {
- Strophe.warn("Couldn't send <close /> tag.");
- }
- }
- - setTimeout(() => this._conn._doDisconnect, 0);
- + setTimeout(() => this._conn._doDisconnect(), 0);
- }
-
- /** PrivateFunction: _doDisconnect
- diff --git a/node_modules/strophe.js/dist/strophe.umd.js b/node_modules/strophe.js/dist/strophe.umd.js
- index 22f1bb3..afa802a 100644
- --- a/node_modules/strophe.js/dist/strophe.umd.js
- +++ b/node_modules/strophe.js/dist/strophe.umd.js
- @@ -5160,7 +5160,7 @@
- Strophe.warn("Couldn't send <close /> tag.");
- }
- }
- - setTimeout(() => this._conn._doDisconnect, 0);
- + setTimeout(() => this._conn._doDisconnect(), 0);
- }
-
- /** PrivateFunction: _doDisconnect
- diff --git a/node_modules/strophe.js/dist/strophe.umd.min.js b/node_modules/strophe.js/dist/strophe.umd.min.js
- index 420f86e..f118796 100644
- --- a/node_modules/strophe.js/dist/strophe.umd.min.js
- +++ b/node_modules/strophe.js/dist/strophe.umd.min.js
- @@ -1 +1 @@
- -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).strophe={})}(this,(function(e){"use strict";var t="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};const s=function(){let e=t.WebSocket;if(void 0===e)try{e=require("ws")}catch(e){throw new Error('You must install the "ws" package to use Strophe in nodejs.')}return e}();const n=function(){let e=t.DOMParser;if(void 0===e)try{e=require("@xmldom/xmldom").DOMParser}catch(e){throw new Error('You must install the "@xmldom/xmldom" package to use Strophe in nodejs.')}return e}();function i(){if("undefined"==typeof document)try{return(new(0,require("@xmldom/xmldom").DOMImplementation)).createDocument("jabber:client","strophe",null)}catch(e){throw new Error('You must install the "@xmldom/xmldom" package to use Strophe in nodejs.')}if(void 0===document.implementation.createDocument||document.implementation.createDocument&&document.documentMode&&document.documentMode<10){const e=function(){const e=["Msxml2.DOMDocument.6.0","Msxml2.DOMDocument.5.0","Msxml2.DOMDocument.4.0","MSXML2.DOMDocument.3.0","MSXML2.DOMDocument","MSXML.DOMDocument","Microsoft.XMLDOM"];for(let t=0;t<e.length;t++)try{return new ActiveXObject(e[t])}catch(e){}}();return e.appendChild(e.createElement("strophe")),e}return document.implementation.createDocument("jabber:client","strophe",null)}class r{constructor(e,t,s){this.mechname=e,this.isClientFirst=t,this.priority=s}test(){return!0}onStart(e){this._connection=e}onChallenge(e,t){throw new Error("You should implement challenge handling!")}clientChallenge(e){if(!this.isClientFirst)throw new Error("clientChallenge should not be called if isClientFirst is false!");return this.onChallenge(e)}onFailure(){this._connection=null}onSuccess(){this._connection=null}}const o={utf16to8(e){let t="";const s=e.length;for(let n=0;n<s;n++){const s=e.charCodeAt(n);s>=0&&s<=127?t+=e.charAt(n):s>2047?(t+=String.fromCharCode(224|s>>12&15),t+=String.fromCharCode(128|s>>6&63),t+=String.fromCharCode(128|s>>0&63)):(t+=String.fromCharCode(192|s>>6&31),t+=String.fromCharCode(128|s>>0&63))}return t},xorArrayBuffers(e,t){const s=new Uint8Array(e),n=new Uint8Array(t),i=new Uint8Array(e.byteLength);for(let t=0;t<e.byteLength;t++)i[t]=s[t]^n[t];return i.buffer},arrayBufToBase64(e){let t="";const s=new Uint8Array(e),n=s.byteLength;for(let e=0;e<n;e++)t+=String.fromCharCode(s[e]);return window.btoa(t)},base64ToArrayBuf(e){var t;return null===(t=Uint8Array.from(atob(e),(e=>e.charCodeAt(0))))||void 0===t?void 0:t.buffer},stringToArrayBuf:e=>new TextEncoder("utf-8").encode(e).buffer,addCookies(e){e=e||{};for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let s="",n="",i="";const r=e[t],o="object"==typeof r,a=escape(unescape(o?r.value:r));o&&(s=r.expires?";expires="+r.expires:"",n=r.domain?";domain="+r.domain:"",i=r.path?";path="+r.path:""),document.cookie=t+"="+a+s+n+i}}};const a={async scramResponse(e,t,s,n){var i,r,a;const l=e._sasl_data.cnonce,h=function(e){let t,s,n;const i=/([a-z]+)=([^,]+)(,|$)/;for(;e.match(i);){const r=e.match(i);switch(e=e.replace(r[0],""),r[1]){case"r":t=r[2];break;case"s":s=o.base64ToArrayBuf(r[2]);break;case"i":n=parseInt(r[2],10);break;default:return}}if(isNaN(n)||n<4096)f.warn("Failing SCRAM authentication because server supplied iteration count < 4096.");else{if(s)return{nonce:t,salt:s,iter:n};f.warn("Failing SCRAM authentication because server supplied incorrect salt.")}}(t);if(!h&&(null==h?void 0:h.nonce.slice(0,l.length))!==l)return f.warn("Failing SCRAM authentication because server supplied incorrect nonce."),e._sasl_data={},e._sasl_failure_cb();let c,d;if((null===(i=e.pass)||void 0===i?void 0:i.name)===s&&(null===(r=e.pass)||void 0===r?void 0:r.salt)===o.arrayBufToBase64(h.salt)&&(null===(a=e.pass)||void 0===a?void 0:a.iter)===h.iter)c=o.base64ToArrayBuf(e.pass.ck),d=o.base64ToArrayBuf(e.pass.sk);else{if(!("string"==typeof e.pass||e.pass instanceof String))return e._sasl_failure_cb();{const t=await async function(e,t,s,n,i){const r=await window.crypto.subtle.deriveBits({name:"PBKDF2",salt:t,iterations:s,hash:{name:n}},await window.crypto.subtle.importKey("raw",o.stringToArrayBuf(e),"PBKDF2",!1,["deriveBits"]),i),a=await window.crypto.subtle.importKey("raw",r,{name:"HMAC",hash:n},!1,["sign"]);return{ck:await window.crypto.subtle.sign("HMAC",a,o.stringToArrayBuf("Client Key")),sk:await window.crypto.subtle.sign("HMAC",a,o.stringToArrayBuf("Server Key"))}}(e.pass,h.salt,h.iter,s,n);c=t.ck,d=t.sk}}const u=e._sasl_data["client-first-message-bare"],_=t,p=`c=biws,r=${h.nonce}`,m=`${u},${_},${p}`,g=await async function(e,t,s){const n=await window.crypto.subtle.importKey("raw",await window.crypto.subtle.digest(s,t),{name:"HMAC",hash:s},!1,["sign"]),i=await window.crypto.subtle.sign("HMAC",n,o.stringToArrayBuf(e));return o.xorArrayBuffers(t,i)}(m,c,s),S=await async function(e,t,s){const n=await window.crypto.subtle.importKey("raw",t,{name:"HMAC",hash:s},!1,["sign"]);return window.crypto.subtle.sign("HMAC",n,o.stringToArrayBuf(e))}(m,d,s);return e._sasl_data["server-signature"]=o.arrayBufToBase64(S),e._sasl_data.keys={name:s,iter:h.iter,salt:o.arrayBufToBase64(h.salt),ck:o.arrayBufToBase64(c),sk:o.arrayBufToBase64(d)},`${p},p=${o.arrayBufToBase64(g)}`},clientChallenge(e,t){const s=t||function(){const e=new Uint8Array(16);return o.arrayBufToBase64(crypto.getRandomValues(e).buffer)}(),n=`n=${e.authcid},r=${s}`;return e._sasl_data.cnonce=s,e._sasl_data["client-first-message-bare"]=n,`n,,${n}`}};function l(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(e);return t<0?void 0:t}var h=function(e){if(0===arguments.length)throw new TypeError("1 argument required, but only 0 present.");if((e=(e=`${e}`).replace(/[ \t\n\f\r]/g,"")).length%4==0&&(e=e.replace(/==?$/,"")),e.length%4==1||/[^+/0-9A-Za-z]/.test(e))return null;let t="",s=0,n=0;for(let i=0;i<e.length;i++)s<<=6,s|=l(e[i]),n+=6,24===n&&(t+=String.fromCharCode((16711680&s)>>16),t+=String.fromCharCode((65280&s)>>8),t+=String.fromCharCode(255&s),s=n=0);return 12===n?(s>>=4,t+=String.fromCharCode(s)):18===n&&(s>>=2,t+=String.fromCharCode((65280&s)>>8),t+=String.fromCharCode(255&s)),t};function c(e){if(e>=0&&e<64)return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[e]}var d=function(e){if(0===arguments.length)throw new TypeError("1 argument required, but only 0 present.");let t;for(e=`${e}`,t=0;t<e.length;t++)if(e.charCodeAt(t)>255)return null;let s="";for(t=0;t<e.length;t+=3){const n=[void 0,void 0,void 0,void 0];n[0]=e.charCodeAt(t)>>2,n[1]=(3&e.charCodeAt(t))<<4,e.length>t+1&&(n[1]|=e.charCodeAt(t+1)>>4,n[2]=(15&e.charCodeAt(t+1))<<2),e.length>t+2&&(n[2]|=e.charCodeAt(t+2)>>6,n[3]=63&e.charCodeAt(t+2));for(let e=0;e<n.length;e++)void 0===n[e]?s+="=":s+=c(n[e])}return s};var u={atob:h,btoa:d};function _(e,t){return new f.Builder(e,t)}function p(e){return new f.Builder("message",e)}function m(e){return new f.Builder("iq",e)}function g(e){return new f.Builder("presence",e)}const f={VERSION:"1.6.0",NS:{HTTPBIND:"http://jabber.org/protocol/httpbind",BOSH:"urn:xmpp:xbosh",CLIENT:"jabber:client",AUTH:"jabber:iq:auth",ROSTER:"jabber:iq:roster",PROFILE:"jabber:iq:profile",DISCO_INFO:"http://jabber.org/protocol/disco#info",DISCO_ITEMS:"http://jabber.org/protocol/disco#items",MUC:"http://jabber.org/protocol/muc",SASL:"urn:ietf:params:xml:ns:xmpp-sasl",STREAM:"http://etherx.jabber.org/streams",FRAMING:"urn:ietf:params:xml:ns:xmpp-framing",BIND:"urn:ietf:params:xml:ns:xmpp-bind",SESSION:"urn:ietf:params:xml:ns:xmpp-session",VERSION:"jabber:iq:version",STANZAS:"urn:ietf:params:xml:ns:xmpp-stanzas",XHTML_IM:"http://jabber.org/protocol/xhtml-im",XHTML:"http://www.w3.org/1999/xhtml"},XHTML:{tags:["a","blockquote","br","cite","em","img","li","ol","p","span","strong","ul","body"],attributes:{a:["href"],blockquote:["style"],br:[],cite:["style"],em:[],img:["src","alt","style","height","width"],li:["style"],ol:["style"],p:["style"],span:["style"],strong:[],ul:["style"],body:[]},css:["background-color","color","font-family","font-size","font-style","font-weight","margin-left","margin-right","text-align","text-decoration"],validTag(e){for(let t=0;t<f.XHTML.tags.length;t++)if(e===f.XHTML.tags[t])return!0;return!1},validAttribute(e,t){if(void 0!==f.XHTML.attributes[e]&&f.XHTML.attributes[e].length>0)for(let s=0;s<f.XHTML.attributes[e].length;s++)if(t===f.XHTML.attributes[e][s])return!0;return!1},validCSS(e){for(let t=0;t<f.XHTML.css.length;t++)if(e===f.XHTML.css[t])return!0;return!1}},Status:{ERROR:0,CONNECTING:1,CONNFAIL:2,AUTHENTICATING:3,AUTHFAIL:4,CONNECTED:5,DISCONNECTED:6,DISCONNECTING:7,ATTACHED:8,REDIRECT:9,CONNTIMEOUT:10,BINDREQUIRED:11,ATTACHFAIL:12},ErrorCondition:{BAD_FORMAT:"bad-format",CONFLICT:"conflict",MISSING_JID_NODE:"x-strophe-bad-non-anon-jid",NO_AUTH_MECH:"no-auth-mech",UNKNOWN_REASON:"unknown"},LogLevel:{DEBUG:0,INFO:1,WARN:2,ERROR:3,FATAL:4},ElementType:{NORMAL:1,TEXT:3,CDATA:4,FRAGMENT:11},TIMEOUT:1.1,SECONDARY_TIMEOUT:.1,addNamespace(e,t){f.NS[e]=t},forEachChild(e,t,s){for(let n=0;n<e.childNodes.length;n++){const i=e.childNodes[n];i.nodeType!==f.ElementType.NORMAL||t&&!this.isTagEqual(i,t)||s(i)}},isTagEqual:(e,t)=>e.tagName===t,_xmlGenerator:null,xmlGenerator:()=>(f._xmlGenerator||(f._xmlGenerator=i()),f._xmlGenerator),xmlElement(e){if(!e)return null;const t=f.xmlGenerator().createElement(e);for(let e=1;e<arguments.length;e++){const s=arguments[e];if(s)if("string"==typeof s||"number"==typeof s)t.appendChild(f.xmlTextNode(s));else if("object"==typeof s&&"function"==typeof s.sort)for(let e=0;e<s.length;e++){const n=s[e];"object"==typeof n&&"function"==typeof n.sort&&void 0!==n[1]&&null!==n[1]&&t.setAttribute(n[0],n[1])}else if("object"==typeof s)for(const e in s)Object.prototype.hasOwnProperty.call(s,e)&&void 0!==s[e]&&null!==s[e]&&t.setAttribute(e,s[e])}return t},xmlescape:e=>e=(e=(e=(e=(e=e.replace(/\&/g,"&")).replace(/</g,"<")).replace(/>/g,">")).replace(/'/g,"'")).replace(/"/g,"""),xmlunescape:e=>e=(e=(e=(e=(e=e.replace(/\&/g,"&")).replace(/</g,"<")).replace(/>/g,">")).replace(/'/g,"'")).replace(/"/g,'"'),xmlTextNode:e=>f.xmlGenerator().createTextNode(e),xmlHtmlNode(e){let t;if(n){t=(new n).parseFromString(e,"text/xml")}else t=new ActiveXObject("Microsoft.XMLDOM"),t.async="false",t.loadXML(e);return t},getText(e){if(!e)return null;let t="";0===e.childNodes.length&&e.nodeType===f.ElementType.TEXT&&(t+=e.nodeValue);for(let s=0;s<e.childNodes.length;s++)e.childNodes[s].nodeType===f.ElementType.TEXT&&(t+=e.childNodes[s].nodeValue);return f.xmlescape(t)},copyElement(e){let t;if(e.nodeType===f.ElementType.NORMAL){t=f.xmlElement(e.tagName);for(let s=0;s<e.attributes.length;s++)t.setAttribute(e.attributes[s].nodeName,e.attributes[s].value);for(let s=0;s<e.childNodes.length;s++)t.appendChild(f.copyElement(e.childNodes[s]))}else e.nodeType===f.ElementType.TEXT&&(t=f.xmlGenerator().createTextNode(e.nodeValue));return t},createHtml(e){let t;if(e.nodeType===f.ElementType.NORMAL){const s=e.nodeName.toLowerCase();if(f.XHTML.validTag(s))try{t=f.xmlElement(s);for(let n=0;n<f.XHTML.attributes[s].length;n++){const i=f.XHTML.attributes[s][n];let r=e.getAttribute(i);if(null!=r&&""!==r&&!1!==r&&0!==r)if("style"===i&&"object"==typeof r&&void 0!==r.cssText&&(r=r.cssText),"style"===i){const e=[],s=r.split(";");for(let t=0;t<s.length;t++){const n=s[t].split(":"),i=n[0].replace(/^\s*/,"").replace(/\s*$/,"").toLowerCase();if(f.XHTML.validCSS(i)){const t=n[1].replace(/^\s*/,"").replace(/\s*$/,"");e.push(i+": "+t)}}e.length>0&&(r=e.join("; "),t.setAttribute(i,r))}else t.setAttribute(i,r)}for(let s=0;s<e.childNodes.length;s++)t.appendChild(f.createHtml(e.childNodes[s]))}catch(e){t=f.xmlTextNode("")}else{t=f.xmlGenerator().createDocumentFragment();for(let s=0;s<e.childNodes.length;s++)t.appendChild(f.createHtml(e.childNodes[s]))}}else if(e.nodeType===f.ElementType.FRAGMENT){t=f.xmlGenerator().createDocumentFragment();for(let s=0;s<e.childNodes.length;s++)t.appendChild(f.createHtml(e.childNodes[s]))}else e.nodeType===f.ElementType.TEXT&&(t=f.xmlTextNode(e.nodeValue));return t},escapeNode:e=>"string"!=typeof e?e:e.replace(/^\s+|\s+$/g,"").replace(/\\/g,"\\5c").replace(/ /g,"\\20").replace(/\"/g,"\\22").replace(/\&/g,"\\26").replace(/\'/g,"\\27").replace(/\//g,"\\2f").replace(/:/g,"\\3a").replace(/</g,"\\3c").replace(/>/g,"\\3e").replace(/@/g,"\\40"),unescapeNode:e=>"string"!=typeof e?e:e.replace(/\\20/g," ").replace(/\\22/g,'"').replace(/\\26/g,"&").replace(/\\27/g,"'").replace(/\\2f/g,"/").replace(/\\3a/g,":").replace(/\\3c/g,"<").replace(/\\3e/g,">").replace(/\\40/g,"@").replace(/\\5c/g,"\\"),getNodeFromJid:e=>e.indexOf("@")<0?null:e.split("@")[0],getDomainFromJid(e){const t=f.getBareJidFromJid(e);if(t.indexOf("@")<0)return t;{const e=t.split("@");return e.splice(0,1),e.join("@")}},getResourceFromJid(e){if(!e)return null;const t=e.split("/");return t.length<2?null:(t.splice(0,1),t.join("/"))},getBareJidFromJid:e=>e?e.split("/")[0]:null,_handleError(e){void 0!==e.stack&&f.fatal(e.stack),e.sourceURL?f.fatal("error: "+this.handler+" "+e.sourceURL+":"+e.line+" - "+e.name+": "+e.message):e.fileName?f.fatal("error: "+this.handler+" "+e.fileName+":"+e.lineNumber+" - "+e.name+": "+e.message):f.fatal("error: "+e.message)},log(e,t){var s;e===this.LogLevel.FATAL&&(null===(s=console)||void 0===s||s.error(t))},debug(e){this.log(this.LogLevel.DEBUG,e)},info(e){this.log(this.LogLevel.INFO,e)},warn(e){this.log(this.LogLevel.WARN,e)},error(e){this.log(this.LogLevel.ERROR,e)},fatal(e){this.log(this.LogLevel.FATAL,e)},serialize(e){if(!e)return null;"function"==typeof e.tree&&(e=e.tree());const t=[...Array(e.attributes.length).keys()].map((t=>e.attributes[t].nodeName));t.sort();let s=t.reduce(((t,s)=>`${t} ${s}="${f.xmlescape(e.attributes.getNamedItem(s).value)}"`),`<${e.nodeName}`);if(e.childNodes.length>0){s+=">";for(let t=0;t<e.childNodes.length;t++){const n=e.childNodes[t];switch(n.nodeType){case f.ElementType.NORMAL:s+=f.serialize(n);break;case f.ElementType.TEXT:s+=f.xmlescape(n.nodeValue);break;case f.ElementType.CDATA:s+="<![CDATA["+n.nodeValue+"]]>"}}s+="</"+e.nodeName+">"}else s+="/>";return s},_requestId:0,_connectionPlugins:{},addConnectionPlugin(e,t){f._connectionPlugins[e]=t},Builder:class{constructor(e,t){"presence"!==e&&"message"!==e&&"iq"!==e||(t&&!t.xmlns?t.xmlns=f.NS.CLIENT:t||(t={xmlns:f.NS.CLIENT})),this.nodeTree=f.xmlElement(e,t),this.node=this.nodeTree}tree(){return this.nodeTree}toString(){return f.serialize(this.nodeTree)}up(){return this.node=this.node.parentNode,this}root(){return this.node=this.nodeTree,this}attrs(e){for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(void 0===e[t]?this.node.removeAttribute(t):this.node.setAttribute(t,e[t]));return this}c(e,t,s){const n=f.xmlElement(e,t,s);return this.node.appendChild(n),"string"!=typeof s&&"number"!=typeof s&&(this.node=n),this}cnode(e){let t;const s=f.xmlGenerator();try{t=void 0!==s.importNode}catch(e){t=!1}const n=t?s.importNode(e,!0):f.copyElement(e);return this.node.appendChild(n),this.node=n,this}t(e){const t=f.xmlTextNode(e);return this.node.appendChild(t),this}h(e){const t=f.xmlGenerator().createElement("body");t.innerHTML=e;const s=f.createHtml(t);for(;s.childNodes.length>0;)this.node.appendChild(s.childNodes[0]);return this}},Handler:function(e,t,s,n,i,r,o){this.handler=e,this.ns=t,this.name=s,this.type=n,this.id=i,this.options=o||{matchBareFromJid:!1,ignoreNamespaceFragment:!1},this.options.matchBare&&(f.warn('The "matchBare" option is deprecated, use "matchBareFromJid" instead.'),this.options.matchBareFromJid=this.options.matchBare,delete this.options.matchBare),this.options.matchBareFromJid?this.from=r?f.getBareJidFromJid(r):null:this.from=r,this.user=!0}};f.Handler.prototype={getNamespace(e){let t=e.getAttribute("xmlns");return t&&this.options.ignoreNamespaceFragment&&(t=t.split("#")[0]),t},namespaceMatch(e){let t=!1;return!this.ns||(f.forEachChild(e,null,(e=>{this.getNamespace(e)===this.ns&&(t=!0)})),t||this.getNamespace(e)===this.ns)},isMatch(e){let t=e.getAttribute("from");this.options.matchBareFromJid&&(t=f.getBareJidFromJid(t));const s=e.getAttribute("type");return!(!this.namespaceMatch(e)||this.name&&!f.isTagEqual(e,this.name)||this.type&&(Array.isArray(this.type)?-1===this.type.indexOf(s):s!==this.type)||this.id&&e.getAttribute("id")!==this.id||this.from&&t!==this.from)},run(e){let t=null;try{t=this.handler(e)}catch(e){throw f._handleError(e),e}return t},toString(){return"{Handler: "+this.handler+"("+this.name+","+this.id+","+this.ns+")}"}},f.TimedHandler=class{constructor(e,t){this.period=e,this.handler=t,this.lastCalled=(new Date).getTime(),this.user=!0}run(){return this.lastCalled=(new Date).getTime(),this.handler()}reset(){this.lastCalled=(new Date).getTime()}toString(){return"{TimedHandler: "+this.handler+"("+this.period+")}"}},f.Connection=class{constructor(e,t){this.service=e,this.options=t||{},this.setProtocol(),this.jid="",this.domain=null,this.features=null,this._sasl_data={},this.do_bind=!1,this.do_session=!1,this.mechanisms={},this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this.protocolErrorHandlers={HTTP:{},websocket:{}},this._idleTimeout=null,this._disconnectTimeout=null,this.authenticated=!1,this.connected=!1,this.disconnecting=!1,this.do_authentication=!0,this.paused=!1,this.restored=!1,this._data=[],this._uniqueId=0,this._sasl_success_handler=null,this._sasl_failure_handler=null,this._sasl_challenge_handler=null,this.maxRetries=5,this._idleTimeout=setTimeout((()=>this._onIdle()),100),o.addCookies(this.options.cookies),this.registerSASLMechanisms(this.options.mechanisms),this.iqFallbackHandler=new f.Handler((e=>this.send(m({type:"error",id:e.getAttribute("id")}).c("error",{type:"cancel"}).c("service-unavailable",{xmlns:f.NS.STANZAS}))),null,"iq",["get","set"]);for(const e in f._connectionPlugins)if(Object.prototype.hasOwnProperty.call(f._connectionPlugins,e)){const t=function(){};t.prototype=f._connectionPlugins[e],this[e]=new t,this[e].init(this)}}setProtocol(){const e=this.options.protocol||"";this.options.worker?this._proto=new f.WorkerWebsocket(this):0===this.service.indexOf("ws:")||0===this.service.indexOf("wss:")||0===e.indexOf("ws")?this._proto=new f.Websocket(this):this._proto=new f.Bosh(this)}reset(){this._proto._reset(),this.do_session=!1,this.do_bind=!1,this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this.authenticated=!1,this.connected=!1,this.disconnecting=!1,this.restored=!1,this._data=[],this._requests=[],this._uniqueId=0}pause(){this.paused=!0}resume(){this.paused=!1}getUniqueId(e){const t="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}));return"string"==typeof e||"number"==typeof e?t+":"+e:t+""}addProtocolErrorHandler(e,t,s){this.protocolErrorHandlers[e][t]=s}connect(e,t,s,n,i,r,o){let a=arguments.length>7&&void 0!==arguments[7]?arguments[7]:3e3;this.jid=e,this.authzid=f.getBareJidFromJid(this.jid),this.authcid=o||f.getNodeFromJid(this.jid),this.pass=t,this.scram_keys=null,this.connect_callback=s,this.disconnecting=!1,this.connected=!1,this.authenticated=!1,this.restored=!1,this.disconnection_timeout=a,this.domain=f.getDomainFromJid(this.jid),this._changeConnectStatus(f.Status.CONNECTING,null),this._proto._connect(n,i,r)}attach(e,t,s,n,i,r,o){if(this._proto._attach)return this._proto._attach(e,t,s,n,i,r,o);{const e=new Error('The "attach" method is not available for your connection protocol');throw e.name="StropheSessionError",e}}restore(e,t,s,n,i){if(!this._sessionCachingSupported()){const e=new Error('The "restore" method can only be used with a BOSH connection.');throw e.name="StropheSessionError",e}this._proto._restore(e,t,s,n,i)}_sessionCachingSupported(){if(this._proto instanceof f.Bosh){if(!JSON)return!1;try{sessionStorage.setItem("_strophe_","_strophe_"),sessionStorage.removeItem("_strophe_")}catch(e){return!1}return!0}return!1}xmlInput(e){}xmlOutput(e){}rawInput(e){}rawOutput(e){}nextValidRid(e){}send(e){if(null!==e){if("function"==typeof e.sort)for(let t=0;t<e.length;t++)this._queueData(e[t]);else"function"==typeof e.tree?this._queueData(e.tree()):this._queueData(e);this._proto._send()}}flush(){clearTimeout(this._idleTimeout),this._onIdle()}sendPresence(e,t,s,n){let i=null;"function"==typeof e.tree&&(e=e.tree());let r=e.getAttribute("id");if(r||(r=this.getUniqueId("sendPresence"),e.setAttribute("id",r)),"function"==typeof t||"function"==typeof s){const e=this.addHandler((e=>{i&&this.deleteTimedHandler(i),"error"===e.getAttribute("type")?s&&s(e):t&&t(e)}),null,"presence",null,r);n&&(i=this.addTimedHandler(n,(()=>(this.deleteHandler(e),s&&s(null),!1))))}return this.send(e),r}sendIQ(e,t,s,n){let i=null;"function"==typeof e.tree&&(e=e.tree());let r=e.getAttribute("id");if(r||(r=this.getUniqueId("sendIQ"),e.setAttribute("id",r)),"function"==typeof t||"function"==typeof s){const e=this.addHandler((e=>{i&&this.deleteTimedHandler(i);const n=e.getAttribute("type");if("result"===n)t&&t(e);else{if("error"!==n){const e=new Error(`Got bad IQ type of ${n}`);throw e.name="StropheError",e}s&&s(e)}}),null,"iq",["error","result"],r);n&&(i=this.addTimedHandler(n,(()=>(this.deleteHandler(e),s&&s(null),!1))))}return this.send(e),r}_queueData(e){if(null===e||!e.tagName||!e.childNodes){const e=new Error("Cannot queue non-DOMElement.");throw e.name="StropheError",e}this._data.push(e)}_sendRestart(){this._data.push("restart"),this._proto._sendRestart(),this._idleTimeout=setTimeout((()=>this._onIdle()),100)}addTimedHandler(e,t){const s=new f.TimedHandler(e,t);return this.addTimeds.push(s),s}deleteTimedHandler(e){this.removeTimeds.push(e)}addHandler(e,t,s,n,i,r,o){const a=new f.Handler(e,t,s,n,i,r,o);return this.addHandlers.push(a),a}deleteHandler(e){this.removeHandlers.push(e);const t=this.addHandlers.indexOf(e);t>=0&&this.addHandlers.splice(t,1)}registerSASLMechanisms(e){this.mechanisms={},(e=e||[f.SASLAnonymous,f.SASLExternal,f.SASLOAuthBearer,f.SASLXOAuth2,f.SASLPlain,f.SASLSHA1,f.SASLSHA256,f.SASLSHA384,f.SASLSHA512]).forEach((e=>this.registerSASLMechanism(e)))}registerSASLMechanism(e){const t=new e;this.mechanisms[t.mechname]=t}disconnect(e){if(this._changeConnectStatus(f.Status.DISCONNECTING,e),e?f.warn("Disconnect was called because: "+e):f.info("Disconnect was called"),this.connected){let e=!1;this.disconnecting=!0,this.authenticated&&(e=g({xmlns:f.NS.CLIENT,type:"unavailable"})),this._disconnectTimeout=this._addSysTimedHandler(this.disconnection_timeout,this._onDisconnectTimeout.bind(this)),this._proto._disconnect(e)}else f.warn("Disconnect was called before Strophe connected to the server"),this._proto._abortAllRequests(),this._doDisconnect()}_changeConnectStatus(e,t,s){for(const s in f._connectionPlugins)if(Object.prototype.hasOwnProperty.call(f._connectionPlugins,s)){const n=this[s];if(n.statusChanged)try{n.statusChanged(e,t)}catch(e){f.error(`${s} plugin caused an exception changing status: ${e}`)}}if(this.connect_callback)try{this.connect_callback(e,t,s)}catch(e){f._handleError(e),f.error(`User connection callback caused an exception: ${e}`)}}_doDisconnect(e){"number"==typeof this._idleTimeout&&clearTimeout(this._idleTimeout),null!==this._disconnectTimeout&&(this.deleteTimedHandler(this._disconnectTimeout),this._disconnectTimeout=null),f.debug("_doDisconnect was called"),this._proto._doDisconnect(),this.authenticated=!1,this.disconnecting=!1,this.restored=!1,this.handlers=[],this.timedHandlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this._changeConnectStatus(f.Status.DISCONNECTED,e),this.connected=!1}_dataRecv(e,t){const s=this._proto._reqToData(e);if(null===s)return;for(this.xmlInput!==f.Connection.prototype.xmlInput&&(s.nodeName===this._proto.strip&&s.childNodes.length?this.xmlInput(s.childNodes[0]):this.xmlInput(s)),this.rawInput!==f.Connection.prototype.rawInput&&(t?this.rawInput(t):this.rawInput(f.serialize(s)));this.removeHandlers.length>0;){const e=this.removeHandlers.pop(),t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)}for(;this.addHandlers.length>0;)this.handlers.push(this.addHandlers.pop());if(this.disconnecting&&this._proto._emptyQueue())return void this._doDisconnect();const n=s.getAttribute("type");if(null!==n&&"terminate"===n){if(this.disconnecting)return;let e=s.getAttribute("condition");const t=s.getElementsByTagName("conflict");return null!==e?("remote-stream-error"===e&&t.length>0&&(e="conflict"),this._changeConnectStatus(f.Status.CONNFAIL,e)):this._changeConnectStatus(f.Status.CONNFAIL,f.ErrorCondition.UNKOWN_REASON),void this._doDisconnect(e)}f.forEachChild(s,null,(e=>{const t=[];this.handlers=this.handlers.reduce(((s,n)=>{try{!n.isMatch(e)||!this.authenticated&&n.user?s.push(n):(n.run(e)&&s.push(n),t.push(n))}catch(e){f.warn("Removing Strophe handlers due to uncaught exception: "+e.message)}return s}),[]),!t.length&&this.iqFallbackHandler.isMatch(e)&&this.iqFallbackHandler.run(e)}))}_connect_cb(e,t,s){let n;f.debug("_connect_cb was called"),this.connected=!0;try{n=this._proto._reqToData(e)}catch(e){if(e.name!==f.ErrorCondition.BAD_FORMAT)throw e;this._changeConnectStatus(f.Status.CONNFAIL,f.ErrorCondition.BAD_FORMAT),this._doDisconnect(f.ErrorCondition.BAD_FORMAT)}if(!n)return;this.xmlInput!==f.Connection.prototype.xmlInput&&(n.nodeName===this._proto.strip&&n.childNodes.length?this.xmlInput(n.childNodes[0]):this.xmlInput(n)),this.rawInput!==f.Connection.prototype.rawInput&&(s?this.rawInput(s):this.rawInput(f.serialize(n)));if(this._proto._connect_cb(n)===f.Status.CONNFAIL)return;let i;if(i=n.getElementsByTagNameNS?n.getElementsByTagNameNS(f.NS.STREAM,"features").length>0:n.getElementsByTagName("stream:features").length>0||n.getElementsByTagName("features").length>0,!i)return void this._proto._no_auth_received(t);const r=Array.from(n.getElementsByTagName("mechanism")).map((e=>this.mechanisms[e.textContent])).filter((e=>e));0!==r.length||0!==n.getElementsByTagName("auth").length?!1!==this.do_authentication&&this.authenticate(r):this._proto._no_auth_received(t)}sortMechanismsByPriority(e){for(let t=0;t<e.length-1;++t){let s=t;for(let n=t+1;n<e.length;++n)e[n].priority>e[s].priority&&(s=n);if(s!==t){const n=e[t];e[t]=e[s],e[s]=n}}return e}authenticate(e){this._attemptSASLAuth(e)||this._attemptLegacyAuth()}_attemptSASLAuth(e){e=this.sortMechanismsByPriority(e||[]);let t=!1;for(let s=0;s<e.length;++s){if(!e[s].test(this))continue;this._sasl_success_handler=this._addSysHandler(this._sasl_success_cb.bind(this),null,"success",null,null),this._sasl_failure_handler=this._addSysHandler(this._sasl_failure_cb.bind(this),null,"failure",null,null),this._sasl_challenge_handler=this._addSysHandler(this._sasl_challenge_cb.bind(this),null,"challenge",null,null),this._sasl_mechanism=e[s],this._sasl_mechanism.onStart(this);const n=_("auth",{xmlns:f.NS.SASL,mechanism:this._sasl_mechanism.mechname});if(this._sasl_mechanism.isClientFirst){const e=this._sasl_mechanism.clientChallenge(this);n.t(u.btoa(e))}this.send(n.tree()),t=!0;break}return t}async _sasl_challenge_cb(e){const t=u.atob(f.getText(e)),s=await this._sasl_mechanism.onChallenge(this,t),n=_("response",{xmlns:f.NS.SASL});return""!==s&&n.t(u.btoa(s)),this.send(n.tree()),!0}_attemptLegacyAuth(){null===f.getNodeFromJid(this.jid)?(this._changeConnectStatus(f.Status.CONNFAIL,f.ErrorCondition.MISSING_JID_NODE),this.disconnect(f.ErrorCondition.MISSING_JID_NODE)):(this._changeConnectStatus(f.Status.AUTHENTICATING,null),this._addSysHandler(this._onLegacyAuthIQResult.bind(this),null,null,null,"_auth_1"),this.send(m({type:"get",to:this.domain,id:"_auth_1"}).c("query",{xmlns:f.NS.AUTH}).c("username",{}).t(f.getNodeFromJid(this.jid)).tree()))}_onLegacyAuthIQResult(e){const t=m({type:"set",id:"_auth_2"}).c("query",{xmlns:f.NS.AUTH}).c("username",{}).t(f.getNodeFromJid(this.jid)).up().c("password").t(this.pass);return f.getResourceFromJid(this.jid)||(this.jid=f.getBareJidFromJid(this.jid)+"/strophe"),t.up().c("resource",{}).t(f.getResourceFromJid(this.jid)),this._addSysHandler(this._auth2_cb.bind(this),null,null,null,"_auth_2"),this.send(t.tree()),!1}_sasl_success_cb(e){if(this._sasl_data["server-signature"]){let t;const s=/([a-z]+)=([^,]+)(,|$)/,n=u.atob(f.getText(e)).match(s);if("v"===n[1]&&(t=n[2]),t!==this._sasl_data["server-signature"])return this.deleteHandler(this._sasl_failure_handler),this._sasl_failure_handler=null,this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null),this._sasl_data={},this._sasl_failure_cb(null)}f.info("SASL authentication succeeded."),this._sasl_data.keys&&(this.scram_keys=this._sasl_data.keys),this._sasl_mechanism&&this._sasl_mechanism.onSuccess(),this.deleteHandler(this._sasl_failure_handler),this._sasl_failure_handler=null,this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null);const t=[],s=(e,t)=>{for(;e.length;)this.deleteHandler(e.pop());return this._onStreamFeaturesAfterSASL(t),!1};return t.push(this._addSysHandler((e=>s(t,e)),null,"stream:features",null,null)),t.push(this._addSysHandler((e=>s(t,e)),f.NS.STREAM,"features",null,null)),this._sendRestart(),!1}_onStreamFeaturesAfterSASL(e){this.features=e;for(let t=0;t<e.childNodes.length;t++){const s=e.childNodes[t];"bind"===s.nodeName&&(this.do_bind=!0),"session"===s.nodeName&&(this.do_session=!0)}return this.do_bind?(this.options.explicitResourceBinding?this._changeConnectStatus(f.Status.BINDREQUIRED,null):this.bind(),!1):(this._changeConnectStatus(f.Status.AUTHFAIL,null),!1)}bind(){if(!this.do_bind)return void f.log(f.LogLevel.INFO,'Strophe.Connection.prototype.bind called but "do_bind" is false');this._addSysHandler(this._onResourceBindResultIQ.bind(this),null,null,null,"_bind_auth_2");const e=f.getResourceFromJid(this.jid);e?this.send(m({type:"set",id:"_bind_auth_2"}).c("bind",{xmlns:f.NS.BIND}).c("resource",{}).t(e).tree()):this.send(m({type:"set",id:"_bind_auth_2"}).c("bind",{xmlns:f.NS.BIND}).tree())}_onResourceBindResultIQ(e){if("error"===e.getAttribute("type")){f.warn("Resource binding failed.");let t;return e.getElementsByTagName("conflict").length>0&&(t=f.ErrorCondition.CONFLICT),this._changeConnectStatus(f.Status.AUTHFAIL,t,e),!1}const t=e.getElementsByTagName("bind");if(!(t.length>0))return f.warn("Resource binding failed."),this._changeConnectStatus(f.Status.AUTHFAIL,null,e),!1;{const e=t[0].getElementsByTagName("jid");e.length>0&&(this.authenticated=!0,this.jid=f.getText(e[0]),this.do_session?this._establishSession():this._changeConnectStatus(f.Status.CONNECTED,null))}}_establishSession(){if(!this.do_session)throw new Error(`Strophe.Connection.prototype._establishSession called but apparently ${f.NS.SESSION} wasn't advertised by the server`);this._addSysHandler(this._onSessionResultIQ.bind(this),null,null,null,"_session_auth_2"),this.send(m({type:"set",id:"_session_auth_2"}).c("session",{xmlns:f.NS.SESSION}).tree())}_onSessionResultIQ(e){if("result"===e.getAttribute("type"))this.authenticated=!0,this._changeConnectStatus(f.Status.CONNECTED,null);else if("error"===e.getAttribute("type"))return this.authenticated=!1,f.warn("Session creation failed."),this._changeConnectStatus(f.Status.AUTHFAIL,null,e),!1;return!1}_sasl_failure_cb(e){return this._sasl_success_handler&&(this.deleteHandler(this._sasl_success_handler),this._sasl_success_handler=null),this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null),this._sasl_mechanism&&this._sasl_mechanism.onFailure(),this._changeConnectStatus(f.Status.AUTHFAIL,null,e),!1}_auth2_cb(e){return"result"===e.getAttribute("type")?(this.authenticated=!0,this._changeConnectStatus(f.Status.CONNECTED,null)):"error"===e.getAttribute("type")&&(this._changeConnectStatus(f.Status.AUTHFAIL,null,e),this.disconnect("authentication failed")),!1}_addSysTimedHandler(e,t){const s=new f.TimedHandler(e,t);return s.user=!1,this.addTimeds.push(s),s}_addSysHandler(e,t,s,n,i){const r=new f.Handler(e,t,s,n,i);return r.user=!1,this.addHandlers.push(r),r}_onDisconnectTimeout(){return f.debug("_onDisconnectTimeout was called"),this._changeConnectStatus(f.Status.CONNTIMEOUT,null),this._proto._onDisconnectTimeout(),this._doDisconnect(),!1}_onIdle(){for(;this.addTimeds.length>0;)this.timedHandlers.push(this.addTimeds.pop());for(;this.removeTimeds.length>0;){const e=this.removeTimeds.pop(),t=this.timedHandlers.indexOf(e);t>=0&&this.timedHandlers.splice(t,1)}const e=(new Date).getTime(),t=[];for(let s=0;s<this.timedHandlers.length;s++){const n=this.timedHandlers[s];if(this.authenticated||!n.user){n.lastCalled+n.period-e<=0?n.run()&&t.push(n):t.push(n)}}this.timedHandlers=t,clearTimeout(this._idleTimeout),this._proto._onIdle(),this.connected&&(this._idleTimeout=setTimeout((()=>this._onIdle()),100))}},f.SASLMechanism=r,f.SASLAnonymous=class extends r{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"ANONYMOUS",arguments.length>1&&void 0!==arguments[1]&&arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:20)}test(e){return null===e.authcid}},f.SASLPlain=class extends r{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"PLAIN",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:50)}test(e){return null!==e.authcid}onChallenge(e){const{authcid:t,authzid:s,domain:n,pass:i}=e;if(!n)throw new Error("SASLPlain onChallenge: domain is not defined!");let r=s!==`${t}@${n}`?s:"";return r+="\0",r+=t,r+="\0",r+=i,o.utf16to8(r)}},f.SASLSHA1=class extends r{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"SCRAM-SHA-1",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:60)}test(e){return null!==e.authcid}async onChallenge(e,t){return a.scramResponse(e,t,"SHA-1",160)}clientChallenge(e,t){return a.clientChallenge(e,t)}},f.SASLSHA256=class extends r{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"SCRAM-SHA-256",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:70)}test(e){return null!==e.authcid}async onChallenge(e,t){return a.scramResponse(e,t,"SHA-256",256)}clientChallenge(e,t){return a.clientChallenge(e,t)}},f.SASLSHA384=class extends r{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"SCRAM-SHA-384",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:71)}test(e){return null!==e.authcid}async onChallenge(e,t){return a.scramResponse(e,t,"SHA-384",384)}clientChallenge(e,t){return a.clientChallenge(e,t)}},f.SASLSHA512=class extends r{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"SCRAM-SHA-512",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:72)}test(e){return null!==e.authcid}async onChallenge(e,t){return a.scramResponse(e,t,"SHA-512",512)}clientChallenge(e,t){return a.clientChallenge(e,t)}},f.SASLOAuthBearer=class extends r{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"OAUTHBEARER",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:40)}test(e){return null!==e.pass}onChallenge(e){let t="n,";return null!==e.authcid&&(t=t+"a="+e.authzid),t+=",",t+="",t+="auth=Bearer ",t+=e.pass,t+="",t+="",o.utf16to8(t)}},f.SASLExternal=class extends r{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"EXTERNAL",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:10)}onChallenge(e){return e.authcid===e.authzid?"":e.authzid}},f.SASLXOAuth2=class extends r{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"X-OAUTH2",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:30)}test(e){return null!==e.pass}onChallenge(e){let t="\0";return null!==e.authcid&&(t+=e.authzid),t+="\0",t+=e.pass,o.utf16to8(t)}};var S={Strophe:f,$build:_,$iq:m,$msg:p,$pres:g};f.Request=class{constructor(e,t,s,n){this.id=++f._requestId,this.xmlData=e,this.data=f.serialize(e),this.origFunc=t,this.func=t,this.rid=s,this.date=NaN,this.sends=n||0,this.abort=!1,this.dead=null,this.age=function(){if(!this.date)return 0;return(new Date-this.date)/1e3},this.timeDead=function(){if(!this.dead)return 0;return(new Date-this.dead)/1e3},this.xhr=this._newXHR()}getResponse(){let e=null;if(this.xhr.responseXML&&this.xhr.responseXML.documentElement){if(e=this.xhr.responseXML.documentElement,"parsererror"===e.tagName)throw f.error("invalid response received"),f.error("responseText: "+this.xhr.responseText),f.error("responseXML: "+f.serialize(this.xhr.responseXML)),new Error("parsererror")}else if(this.xhr.responseText){if(f.debug("Got responseText but no responseXML; attempting to parse it with DOMParser..."),e=(new n).parseFromString(this.xhr.responseText,"application/xml").documentElement,!e)throw new Error("Parsing produced null node");if(e.querySelector("parsererror")){f.error("invalid response received: "+e.querySelector("parsererror").textContent),f.error("responseText: "+this.xhr.responseText);const t=new Error;throw t.name=f.ErrorCondition.BAD_FORMAT,t}}return e}_newXHR(){let e=null;return window.XMLHttpRequest?(e=new XMLHttpRequest,e.overrideMimeType&&e.overrideMimeType("text/xml; charset=utf-8")):window.ActiveXObject&&(e=new ActiveXObject("Microsoft.XMLHTTP")),e.onreadystatechange=this.func.bind(null,this),e}},f.Bosh=class e{constructor(e){this._conn=e,this.rid=Math.floor(4294967295*Math.random()),this.sid=null,this.hold=1,this.wait=60,this.window=5,this.errors=0,this.inactivity=null,this.lastResponseHeaders=null,this._requests=[]}_buildBody(){const e=_("body",{rid:this.rid++,xmlns:f.NS.HTTPBIND});return null!==this.sid&&e.attrs({sid:this.sid}),this._conn.options.keepalive&&this._conn._sessionCachingSupported()&&this._cacheSession(),e}_reset(){this.rid=Math.floor(4294967295*Math.random()),this.sid=null,this.errors=0,this._conn._sessionCachingSupported()&&window.sessionStorage.removeItem("strophe-bosh-session"),this._conn.nextValidRid(this.rid)}_connect(e,t,s){this.wait=e||this.wait,this.hold=t||this.hold,this.errors=0;const n=this._buildBody().attrs({to:this._conn.domain,"xml:lang":"en",wait:this.wait,hold:this.hold,content:"text/xml; charset=utf-8",ver:"1.6","xmpp:version":"1.0","xmlns:xmpp":f.NS.BOSH});s&&n.attrs({route:s});const i=this._conn._connect_cb;this._requests.push(new f.Request(n.tree(),this._onRequestStateChange.bind(this,i.bind(this._conn)),n.tree().getAttribute("rid"))),this._throttledRequestHandler()}_attach(e,t,s,n,i,r,o){this._conn.jid=e,this.sid=t,this.rid=s,this._conn.connect_callback=n,this._conn.domain=f.getDomainFromJid(this._conn.jid),this._conn.authenticated=!0,this._conn.connected=!0,this.wait=i||this.wait,this.hold=r||this.hold,this.window=o||this.window,this._conn._changeConnectStatus(f.Status.ATTACHED,null)}_restore(e,t,s,n,i){const r=JSON.parse(window.sessionStorage.getItem("strophe-bosh-session"));if(!(null!=r&&r.rid&&r.sid&&r.jid&&(null==e||f.getBareJidFromJid(r.jid)===f.getBareJidFromJid(e)||null===f.getNodeFromJid(e)&&f.getDomainFromJid(r.jid)===e))){const e=new Error("_restore: no restoreable session.");throw e.name="StropheSessionError",e}this._conn.restored=!0,this._attach(r.jid,r.sid,r.rid,t,s,n,i)}_cacheSession(){this._conn.authenticated?this._conn.jid&&this.rid&&this.sid&&window.sessionStorage.setItem("strophe-bosh-session",JSON.stringify({jid:this._conn.jid,rid:this.rid,sid:this.sid})):window.sessionStorage.removeItem("strophe-bosh-session")}_connect_cb(e){const t=e.getAttribute("type");if(null!==t&&"terminate"===t){let t=e.getAttribute("condition");f.error("BOSH-Connection failed: "+t);const s=e.getElementsByTagName("conflict");return null!==t?("remote-stream-error"===t&&s.length>0&&(t="conflict"),this._conn._changeConnectStatus(f.Status.CONNFAIL,t)):this._conn._changeConnectStatus(f.Status.CONNFAIL,"unknown"),this._conn._doDisconnect(t),f.Status.CONNFAIL}this.sid||(this.sid=e.getAttribute("sid"));const s=e.getAttribute("requests");s&&(this.window=parseInt(s,10));const n=e.getAttribute("hold");n&&(this.hold=parseInt(n,10));const i=e.getAttribute("wait");i&&(this.wait=parseInt(i,10));const r=e.getAttribute("inactivity");r&&(this.inactivity=parseInt(r,10))}_disconnect(e){this._sendTerminate(e)}_doDisconnect(){this.sid=null,this.rid=Math.floor(4294967295*Math.random()),this._conn._sessionCachingSupported()&&window.sessionStorage.removeItem("strophe-bosh-session"),this._conn.nextValidRid(this.rid)}_emptyQueue(){return 0===this._requests.length}_callProtocolErrorHandlers(t){const s=e._getRequestStatus(t),n=this._conn.protocolErrorHandlers.HTTP[s];n&&n.call(this,s)}_hitError(e){this.errors++,f.warn("request errored, status: "+e+", number of errors: "+this.errors),this.errors>4&&this._conn._onDisconnectTimeout()}_no_auth_received(e){f.warn("Server did not yet offer a supported authentication mechanism. Sending a blank poll request."),e=e?e.bind(this._conn):this._conn._connect_cb.bind(this._conn);const t=this._buildBody();this._requests.push(new f.Request(t.tree(),this._onRequestStateChange.bind(this,e),t.tree().getAttribute("rid"))),this._throttledRequestHandler()}_onDisconnectTimeout(){this._abortAllRequests()}_abortAllRequests(){for(;this._requests.length>0;){const e=this._requests.pop();e.abort=!0,e.xhr.abort(),e.xhr.onreadystatechange=function(){}}}_onIdle(){const e=this._conn._data;if(this._conn.authenticated&&0===this._requests.length&&0===e.length&&!this._conn.disconnecting&&(f.debug("no requests during idle cycle, sending blank request"),e.push(null)),!this._conn.paused){if(this._requests.length<2&&e.length>0){const t=this._buildBody();for(let s=0;s<e.length;s++)null!==e[s]&&("restart"===e[s]?t.attrs({to:this._conn.domain,"xml:lang":"en","xmpp:restart":"true","xmlns:xmpp":f.NS.BOSH}):t.cnode(e[s]).up());delete this._conn._data,this._conn._data=[],this._requests.push(new f.Request(t.tree(),this._onRequestStateChange.bind(this,this._conn._dataRecv.bind(this._conn)),t.tree().getAttribute("rid"))),this._throttledRequestHandler()}if(this._requests.length>0){const e=this._requests[0].age();null!==this._requests[0].dead&&this._requests[0].timeDead()>Math.floor(f.SECONDARY_TIMEOUT*this.wait)&&this._throttledRequestHandler(),e>Math.floor(f.TIMEOUT*this.wait)&&(f.warn("Request "+this._requests[0].id+" timed out, over "+Math.floor(f.TIMEOUT*this.wait)+" seconds since last activity"),this._throttledRequestHandler())}}}static _getRequestStatus(e,t){let s;if(4===e.xhr.readyState)try{s=e.xhr.status}catch(e){f.error("Caught an error while retrieving a request's status, reqStatus: "+s)}return void 0===s&&(s="number"==typeof t?t:0),s}_onRequestStateChange(t,s){if(f.debug("request id "+s.id+"."+s.sends+" state changed to "+s.xhr.readyState),s.abort)return void(s.abort=!1);if(4!==s.xhr.readyState)return;const n=e._getRequestStatus(s);if(this.lastResponseHeaders=s.xhr.getAllResponseHeaders(),this._conn.disconnecting&&n>=400)return this._hitError(n),void this._callProtocolErrorHandlers(s);const i=this._requests[0]===s,r=this._requests[1]===s,o=n>0&&n<500,a=s.sends>this._conn.maxRetries;(o||a)&&(this._removeRequest(s),f.debug("request id "+s.id+" should now be removed")),200===n?((r||i&&this._requests.length>0&&this._requests[0].age()>Math.floor(f.SECONDARY_TIMEOUT*this.wait))&&this._restartRequest(0),this._conn.nextValidRid(Number(s.rid)+1),f.debug("request id "+s.id+"."+s.sends+" got 200"),t(s),this.errors=0):0===n||n>=400&&n<600||n>=12e3?(f.error("request id "+s.id+"."+s.sends+" error "+n+" happened"),this._hitError(n),this._callProtocolErrorHandlers(s),n>=400&&n<500&&(this._conn._changeConnectStatus(f.Status.DISCONNECTING,null),this._conn._doDisconnect())):f.error("request id "+s.id+"."+s.sends+" error "+n+" happened"),o||a?a&&!this._conn.connected&&this._conn._changeConnectStatus(f.Status.CONNFAIL,"giving-up"):this._throttledRequestHandler()}_processRequest(t){let s=this._requests[t];const n=e._getRequestStatus(s,-1);if(s.sends>this._conn.maxRetries)return void this._conn._onDisconnectTimeout();const i=s.age(),r=!isNaN(i)&&i>Math.floor(f.TIMEOUT*this.wait),o=null!==s.dead&&s.timeDead()>Math.floor(f.SECONDARY_TIMEOUT*this.wait),a=4===s.xhr.readyState&&(n<1||n>=500);if((r||o||a)&&(o&&f.error(`Request ${this._requests[t].id} timed out (secondary), restarting`),s.abort=!0,s.xhr.abort(),s.xhr.onreadystatechange=function(){},this._requests[t]=new f.Request(s.xmlData,s.origFunc,s.rid,s.sends),s=this._requests[t]),0===s.xhr.readyState){f.debug("request id "+s.id+"."+s.sends+" posting");try{const e=this._conn.options.contentType||"text/xml; charset=utf-8";s.xhr.open("POST",this._conn.service,!this._conn.options.sync),void 0!==s.xhr.setRequestHeader&&s.xhr.setRequestHeader("Content-Type",e),this._conn.options.withCredentials&&(s.xhr.withCredentials=!0)}catch(e){return f.error("XHR open failed: "+e.toString()),this._conn.connected||this._conn._changeConnectStatus(f.Status.CONNFAIL,"bad-service"),void this._conn.disconnect()}const e=()=>{if(s.date=new Date,this._conn.options.customHeaders){const e=this._conn.options.customHeaders;for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&s.xhr.setRequestHeader(t,e[t])}s.xhr.send(s.data)};if(s.sends>1){const t=1e3*Math.min(Math.floor(f.TIMEOUT*this.wait),Math.pow(s.sends,3));setTimeout((function(){e()}),t)}else e();s.sends++,this._conn.xmlOutput!==f.Connection.prototype.xmlOutput&&(s.xmlData.nodeName===this.strip&&s.xmlData.childNodes.length?this._conn.xmlOutput(s.xmlData.childNodes[0]):this._conn.xmlOutput(s.xmlData)),this._conn.rawOutput!==f.Connection.prototype.rawOutput&&this._conn.rawOutput(s.data)}else f.debug("_processRequest: "+(0===t?"first":"second")+" request has readyState of "+s.xhr.readyState)}_removeRequest(e){f.debug("removing request");for(let t=this._requests.length-1;t>=0;t--)e===this._requests[t]&&this._requests.splice(t,1);e.xhr.onreadystatechange=function(){},this._throttledRequestHandler()}_restartRequest(e){const t=this._requests[e];null===t.dead&&(t.dead=new Date),this._processRequest(e)}_reqToData(e){try{return e.getResponse()}catch(e){if("parsererror"!==e.message)throw e;this._conn.disconnect("strophe-parsererror")}}_sendTerminate(e){f.debug("_sendTerminate was called");const t=this._buildBody().attrs({type:"terminate"});e&&t.cnode(e.tree());const s=new f.Request(t.tree(),this._onRequestStateChange.bind(this,this._conn._dataRecv.bind(this._conn)),t.tree().getAttribute("rid"));this._requests.push(s),this._throttledRequestHandler()}_send(){clearTimeout(this._conn._idleTimeout),this._throttledRequestHandler(),this._conn._idleTimeout=setTimeout((()=>this._conn._onIdle()),100)}_sendRestart(){this._throttledRequestHandler(),clearTimeout(this._conn._idleTimeout)}_throttledRequestHandler(){this._requests?f.debug("_throttledRequestHandler called with "+this._requests.length+" requests"):f.debug("_throttledRequestHandler called with undefined requests"),this._requests&&0!==this._requests.length&&(this._requests.length>0&&this._processRequest(0),this._requests.length>1&&Math.abs(this._requests[0].rid-this._requests[1].rid)<this.window&&this._processRequest(1))}},f.Bosh.prototype.strip=null,f.Websocket=class{constructor(e){this._conn=e,this.strip="wrapper";const t=e.service;if(0!==t.indexOf("ws:")&&0!==t.indexOf("wss:")){let s="";"ws"===e.options.protocol&&"https:"!==window.location.protocol?s+="ws":s+="wss",s+="://"+window.location.host,0!==t.indexOf("/")?s+=window.location.pathname+t:s+=t,e.service=s}}_buildStream(){return _("open",{xmlns:f.NS.FRAMING,to:this._conn.domain,version:"1.0"})}_checkStreamError(e,t){let s;if(s=e.getElementsByTagNameNS?e.getElementsByTagNameNS(f.NS.STREAM,"error"):e.getElementsByTagName("stream:error"),0===s.length)return!1;const n=s[0];let i="",r="";for(let e=0;e<n.childNodes.length;e++){const t=n.childNodes[e];if("urn:ietf:params:xml:ns:xmpp-streams"!==t.getAttribute("xmlns"))break;"text"===t.nodeName?r=t.textContent:i=t.nodeName}let o="WebSocket stream error: ";return o+=i||"unknown",r&&(o+=" - "+r),f.error(o),this._conn._changeConnectStatus(t,i),this._conn._doDisconnect(),!0}_reset(){}_connect(){this._closeSocket(),this.socket=new s(this._conn.service,"xmpp"),this.socket.onopen=()=>this._onOpen(),this.socket.onerror=e=>this._onError(e),this.socket.onclose=e=>this._onClose(e),this.socket.onmessage=e=>this._onInitialMessage(e)}_connect_cb(e){if(this._checkStreamError(e,f.Status.CONNFAIL))return f.Status.CONNFAIL}_handleStreamStart(e){let t=!1;const s=e.getAttribute("xmlns");"string"!=typeof s?t="Missing xmlns in <open />":s!==f.NS.FRAMING&&(t="Wrong xmlns in <open />: "+s);const n=e.getAttribute("version");return"string"!=typeof n?t="Missing version in <open />":"1.0"!==n&&(t="Wrong version in <open />: "+n),!t||(this._conn._changeConnectStatus(f.Status.CONNFAIL,t),this._conn._doDisconnect(),!1)}_onInitialMessage(e){if(0===e.data.indexOf("<open ")||0===e.data.indexOf("<?xml")){const t=e.data.replace(/^(<\?.*?\?>\s*)*/,"");if(""===t)return;const s=(new n).parseFromString(t,"text/xml").documentElement;this._conn.xmlInput(s),this._conn.rawInput(e.data),this._handleStreamStart(s)&&this._connect_cb(s)}else if(0===e.data.indexOf("<close ")){const t=(new n).parseFromString(e.data,"text/xml").documentElement;this._conn.xmlInput(t),this._conn.rawInput(e.data);const s=t.getAttribute("see-other-uri");if(s){const e=this._conn.service;(e.indexOf("wss:")>=0&&s.indexOf("wss:")>=0||e.indexOf("ws:")>=0)&&(this._conn._changeConnectStatus(f.Status.REDIRECT,"Received see-other-uri, resetting connection"),this._conn.reset(),this._conn.service=s,this._connect())}else this._conn._changeConnectStatus(f.Status.CONNFAIL,"Received closing stream"),this._conn._doDisconnect()}else{this._replaceMessageHandler();const t=this._streamWrap(e.data),s=(new n).parseFromString(t,"text/xml").documentElement;this._conn._connect_cb(s,null,e.data)}}_replaceMessageHandler(){this.socket.onmessage=e=>this._onMessage(e)}_disconnect(e){if(this.socket&&this.socket.readyState!==s.CLOSED){e&&this._conn.send(e);const t=_("close",{xmlns:f.NS.FRAMING});this._conn.xmlOutput(t.tree());const s=f.serialize(t);this._conn.rawOutput(s);try{this.socket.send(s)}catch(e){f.warn("Couldn't send <close /> tag.")}}setTimeout((()=>this._conn._doDisconnect),0)}_doDisconnect(){f.debug("WebSockets _doDisconnect was called"),this._closeSocket()}_streamWrap(e){return"<wrapper>"+e+"</wrapper>"}_closeSocket(){if(this.socket)try{this.socket.onclose=null,this.socket.onerror=null,this.socket.onmessage=null,this.socket.close()}catch(e){f.debug(e.message)}this.socket=null}_emptyQueue(){return!0}_onClose(e){this._conn.connected&&!this._conn.disconnecting?(f.error("Websocket closed unexpectedly"),this._conn._doDisconnect()):e&&1006===e.code&&!this._conn.connected&&this.socket?(f.error("Websocket closed unexcectedly"),this._conn._changeConnectStatus(f.Status.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._conn._doDisconnect()):f.debug("Websocket closed")}_no_auth_received(e){f.error("Server did not offer a supported authentication mechanism"),this._conn._changeConnectStatus(f.Status.CONNFAIL,f.ErrorCondition.NO_AUTH_MECH),e&&e.call(this._conn),this._conn._doDisconnect()}_onDisconnectTimeout(){}_abortAllRequests(){}_onError(e){f.error("Websocket error "+JSON.stringify(e)),this._conn._changeConnectStatus(f.Status.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._disconnect()}_onIdle(){const e=this._conn._data;if(e.length>0&&!this._conn.paused){for(let t=0;t<e.length;t++)if(null!==e[t]){let s;s="restart"===e[t]?this._buildStream().tree():e[t];const n=f.serialize(s);this._conn.xmlOutput(s),this._conn.rawOutput(n),this.socket.send(n)}this._conn._data=[]}}_onMessage(e){let t;const s='<close xmlns="urn:ietf:params:xml:ns:xmpp-framing" />';if(e.data===s)return this._conn.rawInput(s),this._conn.xmlInput(e),void(this._conn.disconnecting||this._conn._doDisconnect());if(0===e.data.search("<open ")){if(t=(new n).parseFromString(e.data,"text/xml").documentElement,!this._handleStreamStart(t))return}else{const s=this._streamWrap(e.data);t=(new n).parseFromString(s,"text/xml").documentElement}return this._checkStreamError(t,f.Status.ERROR)?void 0:this._conn.disconnecting&&"presence"===t.firstChild.nodeName&&"unavailable"===t.firstChild.getAttribute("type")?(this._conn.xmlInput(t),void this._conn.rawInput(f.serialize(t))):void this._conn._dataRecv(t,e.data)}_onOpen(){f.debug("Websocket open");const e=this._buildStream();this._conn.xmlOutput(e.tree());const t=f.serialize(e);this._conn.rawOutput(t),this.socket.send(t)}_reqToData(e){return e}_send(){this._conn.flush()}_sendRestart(){clearTimeout(this._conn._idleTimeout),this._conn._onIdle.bind(this._conn)()}};const b={};b.debug=f.LogLevel.DEBUG,b.info=f.LogLevel.INFO,b.warn=f.LogLevel.WARN,b.error=f.LogLevel.ERROR,b.fatal=f.LogLevel.FATAL,f.WorkerWebsocket=class extends f.Websocket{constructor(e){super(e),this._conn=e,this.worker=new SharedWorker(this._conn.options.worker,"Strophe XMPP Connection"),this.worker.onerror=e=>{var t;null===(t=console)||void 0===t||t.error(e),f.log(f.LogLevel.ERROR,`Shared Worker Error: ${e}`)}}get socket(){return{send:e=>this.worker.port.postMessage(["send",e])}}_connect(){this._messageHandler=e=>this._onInitialMessage(e),this.worker.port.start(),this.worker.port.onmessage=e=>this._onWorkerMessage(e),this.worker.port.postMessage(["_connect",this._conn.service,this._conn.jid])}_attach(e){this._messageHandler=e=>this._onMessage(e),this._conn.connect_callback=e,this.worker.port.start(),this.worker.port.onmessage=e=>this._onWorkerMessage(e),this.worker.port.postMessage(["_attach",this._conn.service])}_attachCallback(e,t){e===f.Status.ATTACHED?(this._conn.jid=t,this._conn.authenticated=!0,this._conn.connected=!0,this._conn.restored=!0,this._conn._changeConnectStatus(f.Status.ATTACHED)):e===f.Status.ATTACHFAIL&&(this._conn.authenticated=!1,this._conn.connected=!1,this._conn.restored=!1,this._conn._changeConnectStatus(f.Status.ATTACHFAIL))}_disconnect(e,t){t&&this._conn.send(t);const s=_("close",{xmlns:f.NS.FRAMING});this._conn.xmlOutput(s.tree());const n=f.serialize(s);this._conn.rawOutput(n),this.worker.port.postMessage(["send",n]),this._conn._doDisconnect()}_onClose(e){this._conn.connected&&!this._conn.disconnecting?(f.error("Websocket closed unexpectedly"),this._conn._doDisconnect()):e&&1006===e.code&&!this._conn.connected?(f.error("Websocket closed unexcectedly"),this._conn._changeConnectStatus(f.Status.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._conn._doDisconnect()):f.debug("Websocket closed")}_closeSocket(){this.worker.port.postMessage(["_closeSocket"])}_replaceMessageHandler(){this._messageHandler=e=>this._onMessage(e)}_onWorkerMessage(e){const{data:t}=e,s=t[0];if("_onMessage"===s)this._messageHandler(t[1]);else if(s in this)try{this[s].apply(this,e.data.slice(1))}catch(e){f.log(f.LogLevel.ERROR,e)}else if("log"===s){const e=t[1],s=t[2];f.log(b[e],s)}else f.log(f.LogLevel.ERROR,`Found unhandled service worker message: ${t}`)}},t.$build=S.$build,t.$iq=S.$iq,t.$msg=S.$msg,t.$pres=S.$pres,t.Strophe=S.Strophe,e.$build=_,e.$iq=m,e.$msg=p,e.$pres=g,e.Strophe=f,Object.defineProperty(e,"__esModule",{value:!0})}));
- +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).strophe={})}(this,(function(e){"use strict";var t="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};const s=function(){let e=t.WebSocket;if(void 0===e)try{e=require("ws")}catch(e){throw new Error('You must install the "ws" package to use Strophe in nodejs.')}return e}();const n=function(){let e=t.DOMParser;if(void 0===e)try{e=require("@xmldom/xmldom").DOMParser}catch(e){throw new Error('You must install the "@xmldom/xmldom" package to use Strophe in nodejs.')}return e}();function i(){if("undefined"==typeof document)try{return(new(0,require("@xmldom/xmldom").DOMImplementation)).createDocument("jabber:client","strophe",null)}catch(e){throw new Error('You must install the "@xmldom/xmldom" package to use Strophe in nodejs.')}if(void 0===document.implementation.createDocument||document.implementation.createDocument&&document.documentMode&&document.documentMode<10){const e=function(){const e=["Msxml2.DOMDocument.6.0","Msxml2.DOMDocument.5.0","Msxml2.DOMDocument.4.0","MSXML2.DOMDocument.3.0","MSXML2.DOMDocument","MSXML.DOMDocument","Microsoft.XMLDOM"];for(let t=0;t<e.length;t++)try{return new ActiveXObject(e[t])}catch(e){}}();return e.appendChild(e.createElement("strophe")),e}return document.implementation.createDocument("jabber:client","strophe",null)}class r{constructor(e,t,s){this.mechname=e,this.isClientFirst=t,this.priority=s}test(){return!0}onStart(e){this._connection=e}onChallenge(e,t){throw new Error("You should implement challenge handling!")}clientChallenge(e){if(!this.isClientFirst)throw new Error("clientChallenge should not be called if isClientFirst is false!");return this.onChallenge(e)}onFailure(){this._connection=null}onSuccess(){this._connection=null}}const o={utf16to8(e){let t="";const s=e.length;for(let n=0;n<s;n++){const s=e.charCodeAt(n);s>=0&&s<=127?t+=e.charAt(n):s>2047?(t+=String.fromCharCode(224|s>>12&15),t+=String.fromCharCode(128|s>>6&63),t+=String.fromCharCode(128|s>>0&63)):(t+=String.fromCharCode(192|s>>6&31),t+=String.fromCharCode(128|s>>0&63))}return t},xorArrayBuffers(e,t){const s=new Uint8Array(e),n=new Uint8Array(t),i=new Uint8Array(e.byteLength);for(let t=0;t<e.byteLength;t++)i[t]=s[t]^n[t];return i.buffer},arrayBufToBase64(e){let t="";const s=new Uint8Array(e),n=s.byteLength;for(let e=0;e<n;e++)t+=String.fromCharCode(s[e]);return window.btoa(t)},base64ToArrayBuf(e){var t;return null===(t=Uint8Array.from(atob(e),(e=>e.charCodeAt(0))))||void 0===t?void 0:t.buffer},stringToArrayBuf:e=>new TextEncoder("utf-8").encode(e).buffer,addCookies(e){e=e||{};for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let s="",n="",i="";const r=e[t],o="object"==typeof r,a=escape(unescape(o?r.value:r));o&&(s=r.expires?";expires="+r.expires:"",n=r.domain?";domain="+r.domain:"",i=r.path?";path="+r.path:""),document.cookie=t+"="+a+s+n+i}}};const a={async scramResponse(e,t,s,n){var i,r,a;const l=e._sasl_data.cnonce,h=function(e){let t,s,n;const i=/([a-z]+)=([^,]+)(,|$)/;for(;e.match(i);){const r=e.match(i);switch(e=e.replace(r[0],""),r[1]){case"r":t=r[2];break;case"s":s=o.base64ToArrayBuf(r[2]);break;case"i":n=parseInt(r[2],10);break;default:return}}if(isNaN(n)||n<4096)f.warn("Failing SCRAM authentication because server supplied iteration count < 4096.");else{if(s)return{nonce:t,salt:s,iter:n};f.warn("Failing SCRAM authentication because server supplied incorrect salt.")}}(t);if(!h&&(null==h?void 0:h.nonce.slice(0,l.length))!==l)return f.warn("Failing SCRAM authentication because server supplied incorrect nonce."),e._sasl_data={},e._sasl_failure_cb();let c,d;if((null===(i=e.pass)||void 0===i?void 0:i.name)===s&&(null===(r=e.pass)||void 0===r?void 0:r.salt)===o.arrayBufToBase64(h.salt)&&(null===(a=e.pass)||void 0===a?void 0:a.iter)===h.iter)c=o.base64ToArrayBuf(e.pass.ck),d=o.base64ToArrayBuf(e.pass.sk);else{if(!("string"==typeof e.pass||e.pass instanceof String))return e._sasl_failure_cb();{const t=await async function(e,t,s,n,i){const r=await window.crypto.subtle.deriveBits({name:"PBKDF2",salt:t,iterations:s,hash:{name:n}},await window.crypto.subtle.importKey("raw",o.stringToArrayBuf(e),"PBKDF2",!1,["deriveBits"]),i),a=await window.crypto.subtle.importKey("raw",r,{name:"HMAC",hash:n},!1,["sign"]);return{ck:await window.crypto.subtle.sign("HMAC",a,o.stringToArrayBuf("Client Key")),sk:await window.crypto.subtle.sign("HMAC",a,o.stringToArrayBuf("Server Key"))}}(e.pass,h.salt,h.iter,s,n);c=t.ck,d=t.sk}}const u=e._sasl_data["client-first-message-bare"],_=t,p=`c=biws,r=${h.nonce}`,m=`${u},${_},${p}`,g=await async function(e,t,s){const n=await window.crypto.subtle.importKey("raw",await window.crypto.subtle.digest(s,t),{name:"HMAC",hash:s},!1,["sign"]),i=await window.crypto.subtle.sign("HMAC",n,o.stringToArrayBuf(e));return o.xorArrayBuffers(t,i)}(m,c,s),S=await async function(e,t,s){const n=await window.crypto.subtle.importKey("raw",t,{name:"HMAC",hash:s},!1,["sign"]);return window.crypto.subtle.sign("HMAC",n,o.stringToArrayBuf(e))}(m,d,s);return e._sasl_data["server-signature"]=o.arrayBufToBase64(S),e._sasl_data.keys={name:s,iter:h.iter,salt:o.arrayBufToBase64(h.salt),ck:o.arrayBufToBase64(c),sk:o.arrayBufToBase64(d)},`${p},p=${o.arrayBufToBase64(g)}`},clientChallenge(e,t){const s=t||function(){const e=new Uint8Array(16);return o.arrayBufToBase64(crypto.getRandomValues(e).buffer)}(),n=`n=${e.authcid},r=${s}`;return e._sasl_data.cnonce=s,e._sasl_data["client-first-message-bare"]=n,`n,,${n}`}};function l(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(e);return t<0?void 0:t}var h=function(e){if(0===arguments.length)throw new TypeError("1 argument required, but only 0 present.");if((e=(e=`${e}`).replace(/[ \t\n\f\r]/g,"")).length%4==0&&(e=e.replace(/==?$/,"")),e.length%4==1||/[^+/0-9A-Za-z]/.test(e))return null;let t="",s=0,n=0;for(let i=0;i<e.length;i++)s<<=6,s|=l(e[i]),n+=6,24===n&&(t+=String.fromCharCode((16711680&s)>>16),t+=String.fromCharCode((65280&s)>>8),t+=String.fromCharCode(255&s),s=n=0);return 12===n?(s>>=4,t+=String.fromCharCode(s)):18===n&&(s>>=2,t+=String.fromCharCode((65280&s)>>8),t+=String.fromCharCode(255&s)),t};function c(e){if(e>=0&&e<64)return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[e]}var d=function(e){if(0===arguments.length)throw new TypeError("1 argument required, but only 0 present.");let t;for(e=`${e}`,t=0;t<e.length;t++)if(e.charCodeAt(t)>255)return null;let s="";for(t=0;t<e.length;t+=3){const n=[void 0,void 0,void 0,void 0];n[0]=e.charCodeAt(t)>>2,n[1]=(3&e.charCodeAt(t))<<4,e.length>t+1&&(n[1]|=e.charCodeAt(t+1)>>4,n[2]=(15&e.charCodeAt(t+1))<<2),e.length>t+2&&(n[2]|=e.charCodeAt(t+2)>>6,n[3]=63&e.charCodeAt(t+2));for(let e=0;e<n.length;e++)void 0===n[e]?s+="=":s+=c(n[e])}return s};var u={atob:h,btoa:d};function _(e,t){return new f.Builder(e,t)}function p(e){return new f.Builder("message",e)}function m(e){return new f.Builder("iq",e)}function g(e){return new f.Builder("presence",e)}const f={VERSION:"1.6.0",NS:{HTTPBIND:"http://jabber.org/protocol/httpbind",BOSH:"urn:xmpp:xbosh",CLIENT:"jabber:client",AUTH:"jabber:iq:auth",ROSTER:"jabber:iq:roster",PROFILE:"jabber:iq:profile",DISCO_INFO:"http://jabber.org/protocol/disco#info",DISCO_ITEMS:"http://jabber.org/protocol/disco#items",MUC:"http://jabber.org/protocol/muc",SASL:"urn:ietf:params:xml:ns:xmpp-sasl",STREAM:"http://etherx.jabber.org/streams",FRAMING:"urn:ietf:params:xml:ns:xmpp-framing",BIND:"urn:ietf:params:xml:ns:xmpp-bind",SESSION:"urn:ietf:params:xml:ns:xmpp-session",VERSION:"jabber:iq:version",STANZAS:"urn:ietf:params:xml:ns:xmpp-stanzas",XHTML_IM:"http://jabber.org/protocol/xhtml-im",XHTML:"http://www.w3.org/1999/xhtml"},XHTML:{tags:["a","blockquote","br","cite","em","img","li","ol","p","span","strong","ul","body"],attributes:{a:["href"],blockquote:["style"],br:[],cite:["style"],em:[],img:["src","alt","style","height","width"],li:["style"],ol:["style"],p:["style"],span:["style"],strong:[],ul:["style"],body:[]},css:["background-color","color","font-family","font-size","font-style","font-weight","margin-left","margin-right","text-align","text-decoration"],validTag(e){for(let t=0;t<f.XHTML.tags.length;t++)if(e===f.XHTML.tags[t])return!0;return!1},validAttribute(e,t){if(void 0!==f.XHTML.attributes[e]&&f.XHTML.attributes[e].length>0)for(let s=0;s<f.XHTML.attributes[e].length;s++)if(t===f.XHTML.attributes[e][s])return!0;return!1},validCSS(e){for(let t=0;t<f.XHTML.css.length;t++)if(e===f.XHTML.css[t])return!0;return!1}},Status:{ERROR:0,CONNECTING:1,CONNFAIL:2,AUTHENTICATING:3,AUTHFAIL:4,CONNECTED:5,DISCONNECTED:6,DISCONNECTING:7,ATTACHED:8,REDIRECT:9,CONNTIMEOUT:10,BINDREQUIRED:11,ATTACHFAIL:12},ErrorCondition:{BAD_FORMAT:"bad-format",CONFLICT:"conflict",MISSING_JID_NODE:"x-strophe-bad-non-anon-jid",NO_AUTH_MECH:"no-auth-mech",UNKNOWN_REASON:"unknown"},LogLevel:{DEBUG:0,INFO:1,WARN:2,ERROR:3,FATAL:4},ElementType:{NORMAL:1,TEXT:3,CDATA:4,FRAGMENT:11},TIMEOUT:1.1,SECONDARY_TIMEOUT:.1,addNamespace(e,t){f.NS[e]=t},forEachChild(e,t,s){for(let n=0;n<e.childNodes.length;n++){const i=e.childNodes[n];i.nodeType!==f.ElementType.NORMAL||t&&!this.isTagEqual(i,t)||s(i)}},isTagEqual:(e,t)=>e.tagName===t,_xmlGenerator:null,xmlGenerator:()=>(f._xmlGenerator||(f._xmlGenerator=i()),f._xmlGenerator),xmlElement(e){if(!e)return null;const t=f.xmlGenerator().createElement(e);for(let e=1;e<arguments.length;e++){const s=arguments[e];if(s)if("string"==typeof s||"number"==typeof s)t.appendChild(f.xmlTextNode(s));else if("object"==typeof s&&"function"==typeof s.sort)for(let e=0;e<s.length;e++){const n=s[e];"object"==typeof n&&"function"==typeof n.sort&&void 0!==n[1]&&null!==n[1]&&t.setAttribute(n[0],n[1])}else if("object"==typeof s)for(const e in s)Object.prototype.hasOwnProperty.call(s,e)&&void 0!==s[e]&&null!==s[e]&&t.setAttribute(e,s[e])}return t},xmlescape:e=>e=(e=(e=(e=(e=e.replace(/\&/g,"&")).replace(/</g,"<")).replace(/>/g,">")).replace(/'/g,"'")).replace(/"/g,"""),xmlunescape:e=>e=(e=(e=(e=(e=e.replace(/\&/g,"&")).replace(/</g,"<")).replace(/>/g,">")).replace(/'/g,"'")).replace(/"/g,'"'),xmlTextNode:e=>f.xmlGenerator().createTextNode(e),xmlHtmlNode(e){let t;if(n){t=(new n).parseFromString(e,"text/xml")}else t=new ActiveXObject("Microsoft.XMLDOM"),t.async="false",t.loadXML(e);return t},getText(e){if(!e)return null;let t="";0===e.childNodes.length&&e.nodeType===f.ElementType.TEXT&&(t+=e.nodeValue);for(let s=0;s<e.childNodes.length;s++)e.childNodes[s].nodeType===f.ElementType.TEXT&&(t+=e.childNodes[s].nodeValue);return f.xmlescape(t)},copyElement(e){let t;if(e.nodeType===f.ElementType.NORMAL){t=f.xmlElement(e.tagName);for(let s=0;s<e.attributes.length;s++)t.setAttribute(e.attributes[s].nodeName,e.attributes[s].value);for(let s=0;s<e.childNodes.length;s++)t.appendChild(f.copyElement(e.childNodes[s]))}else e.nodeType===f.ElementType.TEXT&&(t=f.xmlGenerator().createTextNode(e.nodeValue));return t},createHtml(e){let t;if(e.nodeType===f.ElementType.NORMAL){const s=e.nodeName.toLowerCase();if(f.XHTML.validTag(s))try{t=f.xmlElement(s);for(let n=0;n<f.XHTML.attributes[s].length;n++){const i=f.XHTML.attributes[s][n];let r=e.getAttribute(i);if(null!=r&&""!==r&&!1!==r&&0!==r)if("style"===i&&"object"==typeof r&&void 0!==r.cssText&&(r=r.cssText),"style"===i){const e=[],s=r.split(";");for(let t=0;t<s.length;t++){const n=s[t].split(":"),i=n[0].replace(/^\s*/,"").replace(/\s*$/,"").toLowerCase();if(f.XHTML.validCSS(i)){const t=n[1].replace(/^\s*/,"").replace(/\s*$/,"");e.push(i+": "+t)}}e.length>0&&(r=e.join("; "),t.setAttribute(i,r))}else t.setAttribute(i,r)}for(let s=0;s<e.childNodes.length;s++)t.appendChild(f.createHtml(e.childNodes[s]))}catch(e){t=f.xmlTextNode("")}else{t=f.xmlGenerator().createDocumentFragment();for(let s=0;s<e.childNodes.length;s++)t.appendChild(f.createHtml(e.childNodes[s]))}}else if(e.nodeType===f.ElementType.FRAGMENT){t=f.xmlGenerator().createDocumentFragment();for(let s=0;s<e.childNodes.length;s++)t.appendChild(f.createHtml(e.childNodes[s]))}else e.nodeType===f.ElementType.TEXT&&(t=f.xmlTextNode(e.nodeValue));return t},escapeNode:e=>"string"!=typeof e?e:e.replace(/^\s+|\s+$/g,"").replace(/\\/g,"\\5c").replace(/ /g,"\\20").replace(/\"/g,"\\22").replace(/\&/g,"\\26").replace(/\'/g,"\\27").replace(/\//g,"\\2f").replace(/:/g,"\\3a").replace(/</g,"\\3c").replace(/>/g,"\\3e").replace(/@/g,"\\40"),unescapeNode:e=>"string"!=typeof e?e:e.replace(/\\20/g," ").replace(/\\22/g,'"').replace(/\\26/g,"&").replace(/\\27/g,"'").replace(/\\2f/g,"/").replace(/\\3a/g,":").replace(/\\3c/g,"<").replace(/\\3e/g,">").replace(/\\40/g,"@").replace(/\\5c/g,"\\"),getNodeFromJid:e=>e.indexOf("@")<0?null:e.split("@")[0],getDomainFromJid(e){const t=f.getBareJidFromJid(e);if(t.indexOf("@")<0)return t;{const e=t.split("@");return e.splice(0,1),e.join("@")}},getResourceFromJid(e){if(!e)return null;const t=e.split("/");return t.length<2?null:(t.splice(0,1),t.join("/"))},getBareJidFromJid:e=>e?e.split("/")[0]:null,_handleError(e){void 0!==e.stack&&f.fatal(e.stack),e.sourceURL?f.fatal("error: "+this.handler+" "+e.sourceURL+":"+e.line+" - "+e.name+": "+e.message):e.fileName?f.fatal("error: "+this.handler+" "+e.fileName+":"+e.lineNumber+" - "+e.name+": "+e.message):f.fatal("error: "+e.message)},log(e,t){var s;e===this.LogLevel.FATAL&&(null===(s=console)||void 0===s||s.error(t))},debug(e){this.log(this.LogLevel.DEBUG,e)},info(e){this.log(this.LogLevel.INFO,e)},warn(e){this.log(this.LogLevel.WARN,e)},error(e){this.log(this.LogLevel.ERROR,e)},fatal(e){this.log(this.LogLevel.FATAL,e)},serialize(e){if(!e)return null;"function"==typeof e.tree&&(e=e.tree());const t=[...Array(e.attributes.length).keys()].map((t=>e.attributes[t].nodeName));t.sort();let s=t.reduce(((t,s)=>`${t} ${s}="${f.xmlescape(e.attributes.getNamedItem(s).value)}"`),`<${e.nodeName}`);if(e.childNodes.length>0){s+=">";for(let t=0;t<e.childNodes.length;t++){const n=e.childNodes[t];switch(n.nodeType){case f.ElementType.NORMAL:s+=f.serialize(n);break;case f.ElementType.TEXT:s+=f.xmlescape(n.nodeValue);break;case f.ElementType.CDATA:s+="<![CDATA["+n.nodeValue+"]]>"}}s+="</"+e.nodeName+">"}else s+="/>";return s},_requestId:0,_connectionPlugins:{},addConnectionPlugin(e,t){f._connectionPlugins[e]=t},Builder:class{constructor(e,t){"presence"!==e&&"message"!==e&&"iq"!==e||(t&&!t.xmlns?t.xmlns=f.NS.CLIENT:t||(t={xmlns:f.NS.CLIENT})),this.nodeTree=f.xmlElement(e,t),this.node=this.nodeTree}tree(){return this.nodeTree}toString(){return f.serialize(this.nodeTree)}up(){return this.node=this.node.parentNode,this}root(){return this.node=this.nodeTree,this}attrs(e){for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(void 0===e[t]?this.node.removeAttribute(t):this.node.setAttribute(t,e[t]));return this}c(e,t,s){const n=f.xmlElement(e,t,s);return this.node.appendChild(n),"string"!=typeof s&&"number"!=typeof s&&(this.node=n),this}cnode(e){let t;const s=f.xmlGenerator();try{t=void 0!==s.importNode}catch(e){t=!1}const n=t?s.importNode(e,!0):f.copyElement(e);return this.node.appendChild(n),this.node=n,this}t(e){const t=f.xmlTextNode(e);return this.node.appendChild(t),this}h(e){const t=f.xmlGenerator().createElement("body");t.innerHTML=e;const s=f.createHtml(t);for(;s.childNodes.length>0;)this.node.appendChild(s.childNodes[0]);return this}},Handler:function(e,t,s,n,i,r,o){this.handler=e,this.ns=t,this.name=s,this.type=n,this.id=i,this.options=o||{matchBareFromJid:!1,ignoreNamespaceFragment:!1},this.options.matchBare&&(f.warn('The "matchBare" option is deprecated, use "matchBareFromJid" instead.'),this.options.matchBareFromJid=this.options.matchBare,delete this.options.matchBare),this.options.matchBareFromJid?this.from=r?f.getBareJidFromJid(r):null:this.from=r,this.user=!0}};f.Handler.prototype={getNamespace(e){let t=e.getAttribute("xmlns");return t&&this.options.ignoreNamespaceFragment&&(t=t.split("#")[0]),t},namespaceMatch(e){let t=!1;return!this.ns||(f.forEachChild(e,null,(e=>{this.getNamespace(e)===this.ns&&(t=!0)})),t||this.getNamespace(e)===this.ns)},isMatch(e){let t=e.getAttribute("from");this.options.matchBareFromJid&&(t=f.getBareJidFromJid(t));const s=e.getAttribute("type");return!(!this.namespaceMatch(e)||this.name&&!f.isTagEqual(e,this.name)||this.type&&(Array.isArray(this.type)?-1===this.type.indexOf(s):s!==this.type)||this.id&&e.getAttribute("id")!==this.id||this.from&&t!==this.from)},run(e){let t=null;try{t=this.handler(e)}catch(e){throw f._handleError(e),e}return t},toString(){return"{Handler: "+this.handler+"("+this.name+","+this.id+","+this.ns+")}"}},f.TimedHandler=class{constructor(e,t){this.period=e,this.handler=t,this.lastCalled=(new Date).getTime(),this.user=!0}run(){return this.lastCalled=(new Date).getTime(),this.handler()}reset(){this.lastCalled=(new Date).getTime()}toString(){return"{TimedHandler: "+this.handler+"("+this.period+")}"}},f.Connection=class{constructor(e,t){this.service=e,this.options=t||{},this.setProtocol(),this.jid="",this.domain=null,this.features=null,this._sasl_data={},this.do_bind=!1,this.do_session=!1,this.mechanisms={},this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this.protocolErrorHandlers={HTTP:{},websocket:{}},this._idleTimeout=null,this._disconnectTimeout=null,this.authenticated=!1,this.connected=!1,this.disconnecting=!1,this.do_authentication=!0,this.paused=!1,this.restored=!1,this._data=[],this._uniqueId=0,this._sasl_success_handler=null,this._sasl_failure_handler=null,this._sasl_challenge_handler=null,this.maxRetries=5,this._idleTimeout=setTimeout((()=>this._onIdle()),100),o.addCookies(this.options.cookies),this.registerSASLMechanisms(this.options.mechanisms),this.iqFallbackHandler=new f.Handler((e=>this.send(m({type:"error",id:e.getAttribute("id")}).c("error",{type:"cancel"}).c("service-unavailable",{xmlns:f.NS.STANZAS}))),null,"iq",["get","set"]);for(const e in f._connectionPlugins)if(Object.prototype.hasOwnProperty.call(f._connectionPlugins,e)){const t=function(){};t.prototype=f._connectionPlugins[e],this[e]=new t,this[e].init(this)}}setProtocol(){const e=this.options.protocol||"";this.options.worker?this._proto=new f.WorkerWebsocket(this):0===this.service.indexOf("ws:")||0===this.service.indexOf("wss:")||0===e.indexOf("ws")?this._proto=new f.Websocket(this):this._proto=new f.Bosh(this)}reset(){this._proto._reset(),this.do_session=!1,this.do_bind=!1,this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this.authenticated=!1,this.connected=!1,this.disconnecting=!1,this.restored=!1,this._data=[],this._requests=[],this._uniqueId=0}pause(){this.paused=!0}resume(){this.paused=!1}getUniqueId(e){const t="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}));return"string"==typeof e||"number"==typeof e?t+":"+e:t+""}addProtocolErrorHandler(e,t,s){this.protocolErrorHandlers[e][t]=s}connect(e,t,s,n,i,r,o){let a=arguments.length>7&&void 0!==arguments[7]?arguments[7]:3e3;this.jid=e,this.authzid=f.getBareJidFromJid(this.jid),this.authcid=o||f.getNodeFromJid(this.jid),this.pass=t,this.scram_keys=null,this.connect_callback=s,this.disconnecting=!1,this.connected=!1,this.authenticated=!1,this.restored=!1,this.disconnection_timeout=a,this.domain=f.getDomainFromJid(this.jid),this._changeConnectStatus(f.Status.CONNECTING,null),this._proto._connect(n,i,r)}attach(e,t,s,n,i,r,o){if(this._proto._attach)return this._proto._attach(e,t,s,n,i,r,o);{const e=new Error('The "attach" method is not available for your connection protocol');throw e.name="StropheSessionError",e}}restore(e,t,s,n,i){if(!this._sessionCachingSupported()){const e=new Error('The "restore" method can only be used with a BOSH connection.');throw e.name="StropheSessionError",e}this._proto._restore(e,t,s,n,i)}_sessionCachingSupported(){if(this._proto instanceof f.Bosh){if(!JSON)return!1;try{sessionStorage.setItem("_strophe_","_strophe_"),sessionStorage.removeItem("_strophe_")}catch(e){return!1}return!0}return!1}xmlInput(e){}xmlOutput(e){}rawInput(e){}rawOutput(e){}nextValidRid(e){}send(e){if(null!==e){if("function"==typeof e.sort)for(let t=0;t<e.length;t++)this._queueData(e[t]);else"function"==typeof e.tree?this._queueData(e.tree()):this._queueData(e);this._proto._send()}}flush(){clearTimeout(this._idleTimeout),this._onIdle()}sendPresence(e,t,s,n){let i=null;"function"==typeof e.tree&&(e=e.tree());let r=e.getAttribute("id");if(r||(r=this.getUniqueId("sendPresence"),e.setAttribute("id",r)),"function"==typeof t||"function"==typeof s){const e=this.addHandler((e=>{i&&this.deleteTimedHandler(i),"error"===e.getAttribute("type")?s&&s(e):t&&t(e)}),null,"presence",null,r);n&&(i=this.addTimedHandler(n,(()=>(this.deleteHandler(e),s&&s(null),!1))))}return this.send(e),r}sendIQ(e,t,s,n){let i=null;"function"==typeof e.tree&&(e=e.tree());let r=e.getAttribute("id");if(r||(r=this.getUniqueId("sendIQ"),e.setAttribute("id",r)),"function"==typeof t||"function"==typeof s){const e=this.addHandler((e=>{i&&this.deleteTimedHandler(i);const n=e.getAttribute("type");if("result"===n)t&&t(e);else{if("error"!==n){const e=new Error(`Got bad IQ type of ${n}`);throw e.name="StropheError",e}s&&s(e)}}),null,"iq",["error","result"],r);n&&(i=this.addTimedHandler(n,(()=>(this.deleteHandler(e),s&&s(null),!1))))}return this.send(e),r}_queueData(e){if(null===e||!e.tagName||!e.childNodes){const e=new Error("Cannot queue non-DOMElement.");throw e.name="StropheError",e}this._data.push(e)}_sendRestart(){this._data.push("restart"),this._proto._sendRestart(),this._idleTimeout=setTimeout((()=>this._onIdle()),100)}addTimedHandler(e,t){const s=new f.TimedHandler(e,t);return this.addTimeds.push(s),s}deleteTimedHandler(e){this.removeTimeds.push(e)}addHandler(e,t,s,n,i,r,o){const a=new f.Handler(e,t,s,n,i,r,o);return this.addHandlers.push(a),a}deleteHandler(e){this.removeHandlers.push(e);const t=this.addHandlers.indexOf(e);t>=0&&this.addHandlers.splice(t,1)}registerSASLMechanisms(e){this.mechanisms={},(e=e||[f.SASLAnonymous,f.SASLExternal,f.SASLOAuthBearer,f.SASLXOAuth2,f.SASLPlain,f.SASLSHA1,f.SASLSHA256,f.SASLSHA384,f.SASLSHA512]).forEach((e=>this.registerSASLMechanism(e)))}registerSASLMechanism(e){const t=new e;this.mechanisms[t.mechname]=t}disconnect(e){if(this._changeConnectStatus(f.Status.DISCONNECTING,e),e?f.warn("Disconnect was called because: "+e):f.info("Disconnect was called"),this.connected){let e=!1;this.disconnecting=!0,this.authenticated&&(e=g({xmlns:f.NS.CLIENT,type:"unavailable"})),this._disconnectTimeout=this._addSysTimedHandler(this.disconnection_timeout,this._onDisconnectTimeout.bind(this)),this._proto._disconnect(e)}else f.warn("Disconnect was called before Strophe connected to the server"),this._proto._abortAllRequests(),this._doDisconnect()}_changeConnectStatus(e,t,s){for(const s in f._connectionPlugins)if(Object.prototype.hasOwnProperty.call(f._connectionPlugins,s)){const n=this[s];if(n.statusChanged)try{n.statusChanged(e,t)}catch(e){f.error(`${s} plugin caused an exception changing status: ${e}`)}}if(this.connect_callback)try{this.connect_callback(e,t,s)}catch(e){f._handleError(e),f.error(`User connection callback caused an exception: ${e}`)}}_doDisconnect(e){"number"==typeof this._idleTimeout&&clearTimeout(this._idleTimeout),null!==this._disconnectTimeout&&(this.deleteTimedHandler(this._disconnectTimeout),this._disconnectTimeout=null),f.debug("_doDisconnect was called"),this._proto._doDisconnect(),this.authenticated=!1,this.disconnecting=!1,this.restored=!1,this.handlers=[],this.timedHandlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this._changeConnectStatus(f.Status.DISCONNECTED,e),this.connected=!1}_dataRecv(e,t){const s=this._proto._reqToData(e);if(null===s)return;for(this.xmlInput!==f.Connection.prototype.xmlInput&&(s.nodeName===this._proto.strip&&s.childNodes.length?this.xmlInput(s.childNodes[0]):this.xmlInput(s)),this.rawInput!==f.Connection.prototype.rawInput&&(t?this.rawInput(t):this.rawInput(f.serialize(s)));this.removeHandlers.length>0;){const e=this.removeHandlers.pop(),t=this.handlers.indexOf(e);t>=0&&this.handlers.splice(t,1)}for(;this.addHandlers.length>0;)this.handlers.push(this.addHandlers.pop());if(this.disconnecting&&this._proto._emptyQueue())return void this._doDisconnect();const n=s.getAttribute("type");if(null!==n&&"terminate"===n){if(this.disconnecting)return;let e=s.getAttribute("condition");const t=s.getElementsByTagName("conflict");return null!==e?("remote-stream-error"===e&&t.length>0&&(e="conflict"),this._changeConnectStatus(f.Status.CONNFAIL,e)):this._changeConnectStatus(f.Status.CONNFAIL,f.ErrorCondition.UNKOWN_REASON),void this._doDisconnect(e)}f.forEachChild(s,null,(e=>{const t=[];this.handlers=this.handlers.reduce(((s,n)=>{try{!n.isMatch(e)||!this.authenticated&&n.user?s.push(n):(n.run(e)&&s.push(n),t.push(n))}catch(e){f.warn("Removing Strophe handlers due to uncaught exception: "+e.message)}return s}),[]),!t.length&&this.iqFallbackHandler.isMatch(e)&&this.iqFallbackHandler.run(e)}))}_connect_cb(e,t,s){let n;f.debug("_connect_cb was called"),this.connected=!0;try{n=this._proto._reqToData(e)}catch(e){if(e.name!==f.ErrorCondition.BAD_FORMAT)throw e;this._changeConnectStatus(f.Status.CONNFAIL,f.ErrorCondition.BAD_FORMAT),this._doDisconnect(f.ErrorCondition.BAD_FORMAT)}if(!n)return;this.xmlInput!==f.Connection.prototype.xmlInput&&(n.nodeName===this._proto.strip&&n.childNodes.length?this.xmlInput(n.childNodes[0]):this.xmlInput(n)),this.rawInput!==f.Connection.prototype.rawInput&&(s?this.rawInput(s):this.rawInput(f.serialize(n)));if(this._proto._connect_cb(n)===f.Status.CONNFAIL)return;let i;if(i=n.getElementsByTagNameNS?n.getElementsByTagNameNS(f.NS.STREAM,"features").length>0:n.getElementsByTagName("stream:features").length>0||n.getElementsByTagName("features").length>0,!i)return void this._proto._no_auth_received(t);const r=Array.from(n.getElementsByTagName("mechanism")).map((e=>this.mechanisms[e.textContent])).filter((e=>e));0!==r.length||0!==n.getElementsByTagName("auth").length?!1!==this.do_authentication&&this.authenticate(r):this._proto._no_auth_received(t)}sortMechanismsByPriority(e){for(let t=0;t<e.length-1;++t){let s=t;for(let n=t+1;n<e.length;++n)e[n].priority>e[s].priority&&(s=n);if(s!==t){const n=e[t];e[t]=e[s],e[s]=n}}return e}authenticate(e){this._attemptSASLAuth(e)||this._attemptLegacyAuth()}_attemptSASLAuth(e){e=this.sortMechanismsByPriority(e||[]);let t=!1;for(let s=0;s<e.length;++s){if(!e[s].test(this))continue;this._sasl_success_handler=this._addSysHandler(this._sasl_success_cb.bind(this),null,"success",null,null),this._sasl_failure_handler=this._addSysHandler(this._sasl_failure_cb.bind(this),null,"failure",null,null),this._sasl_challenge_handler=this._addSysHandler(this._sasl_challenge_cb.bind(this),null,"challenge",null,null),this._sasl_mechanism=e[s],this._sasl_mechanism.onStart(this);const n=_("auth",{xmlns:f.NS.SASL,mechanism:this._sasl_mechanism.mechname});if(this._sasl_mechanism.isClientFirst){const e=this._sasl_mechanism.clientChallenge(this);n.t(u.btoa(e))}this.send(n.tree()),t=!0;break}return t}async _sasl_challenge_cb(e){const t=u.atob(f.getText(e)),s=await this._sasl_mechanism.onChallenge(this,t),n=_("response",{xmlns:f.NS.SASL});return""!==s&&n.t(u.btoa(s)),this.send(n.tree()),!0}_attemptLegacyAuth(){null===f.getNodeFromJid(this.jid)?(this._changeConnectStatus(f.Status.CONNFAIL,f.ErrorCondition.MISSING_JID_NODE),this.disconnect(f.ErrorCondition.MISSING_JID_NODE)):(this._changeConnectStatus(f.Status.AUTHENTICATING,null),this._addSysHandler(this._onLegacyAuthIQResult.bind(this),null,null,null,"_auth_1"),this.send(m({type:"get",to:this.domain,id:"_auth_1"}).c("query",{xmlns:f.NS.AUTH}).c("username",{}).t(f.getNodeFromJid(this.jid)).tree()))}_onLegacyAuthIQResult(e){const t=m({type:"set",id:"_auth_2"}).c("query",{xmlns:f.NS.AUTH}).c("username",{}).t(f.getNodeFromJid(this.jid)).up().c("password").t(this.pass);return f.getResourceFromJid(this.jid)||(this.jid=f.getBareJidFromJid(this.jid)+"/strophe"),t.up().c("resource",{}).t(f.getResourceFromJid(this.jid)),this._addSysHandler(this._auth2_cb.bind(this),null,null,null,"_auth_2"),this.send(t.tree()),!1}_sasl_success_cb(e){if(this._sasl_data["server-signature"]){let t;const s=/([a-z]+)=([^,]+)(,|$)/,n=u.atob(f.getText(e)).match(s);if("v"===n[1]&&(t=n[2]),t!==this._sasl_data["server-signature"])return this.deleteHandler(this._sasl_failure_handler),this._sasl_failure_handler=null,this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null),this._sasl_data={},this._sasl_failure_cb(null)}f.info("SASL authentication succeeded."),this._sasl_data.keys&&(this.scram_keys=this._sasl_data.keys),this._sasl_mechanism&&this._sasl_mechanism.onSuccess(),this.deleteHandler(this._sasl_failure_handler),this._sasl_failure_handler=null,this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null);const t=[],s=(e,t)=>{for(;e.length;)this.deleteHandler(e.pop());return this._onStreamFeaturesAfterSASL(t),!1};return t.push(this._addSysHandler((e=>s(t,e)),null,"stream:features",null,null)),t.push(this._addSysHandler((e=>s(t,e)),f.NS.STREAM,"features",null,null)),this._sendRestart(),!1}_onStreamFeaturesAfterSASL(e){this.features=e;for(let t=0;t<e.childNodes.length;t++){const s=e.childNodes[t];"bind"===s.nodeName&&(this.do_bind=!0),"session"===s.nodeName&&(this.do_session=!0)}return this.do_bind?(this.options.explicitResourceBinding?this._changeConnectStatus(f.Status.BINDREQUIRED,null):this.bind(),!1):(this._changeConnectStatus(f.Status.AUTHFAIL,null),!1)}bind(){if(!this.do_bind)return void f.log(f.LogLevel.INFO,'Strophe.Connection.prototype.bind called but "do_bind" is false');this._addSysHandler(this._onResourceBindResultIQ.bind(this),null,null,null,"_bind_auth_2");const e=f.getResourceFromJid(this.jid);e?this.send(m({type:"set",id:"_bind_auth_2"}).c("bind",{xmlns:f.NS.BIND}).c("resource",{}).t(e).tree()):this.send(m({type:"set",id:"_bind_auth_2"}).c("bind",{xmlns:f.NS.BIND}).tree())}_onResourceBindResultIQ(e){if("error"===e.getAttribute("type")){f.warn("Resource binding failed.");let t;return e.getElementsByTagName("conflict").length>0&&(t=f.ErrorCondition.CONFLICT),this._changeConnectStatus(f.Status.AUTHFAIL,t,e),!1}const t=e.getElementsByTagName("bind");if(!(t.length>0))return f.warn("Resource binding failed."),this._changeConnectStatus(f.Status.AUTHFAIL,null,e),!1;{const e=t[0].getElementsByTagName("jid");e.length>0&&(this.authenticated=!0,this.jid=f.getText(e[0]),this.do_session?this._establishSession():this._changeConnectStatus(f.Status.CONNECTED,null))}}_establishSession(){if(!this.do_session)throw new Error(`Strophe.Connection.prototype._establishSession called but apparently ${f.NS.SESSION} wasn't advertised by the server`);this._addSysHandler(this._onSessionResultIQ.bind(this),null,null,null,"_session_auth_2"),this.send(m({type:"set",id:"_session_auth_2"}).c("session",{xmlns:f.NS.SESSION}).tree())}_onSessionResultIQ(e){if("result"===e.getAttribute("type"))this.authenticated=!0,this._changeConnectStatus(f.Status.CONNECTED,null);else if("error"===e.getAttribute("type"))return this.authenticated=!1,f.warn("Session creation failed."),this._changeConnectStatus(f.Status.AUTHFAIL,null,e),!1;return!1}_sasl_failure_cb(e){return this._sasl_success_handler&&(this.deleteHandler(this._sasl_success_handler),this._sasl_success_handler=null),this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null),this._sasl_mechanism&&this._sasl_mechanism.onFailure(),this._changeConnectStatus(f.Status.AUTHFAIL,null,e),!1}_auth2_cb(e){return"result"===e.getAttribute("type")?(this.authenticated=!0,this._changeConnectStatus(f.Status.CONNECTED,null)):"error"===e.getAttribute("type")&&(this._changeConnectStatus(f.Status.AUTHFAIL,null,e),this.disconnect("authentication failed")),!1}_addSysTimedHandler(e,t){const s=new f.TimedHandler(e,t);return s.user=!1,this.addTimeds.push(s),s}_addSysHandler(e,t,s,n,i){const r=new f.Handler(e,t,s,n,i);return r.user=!1,this.addHandlers.push(r),r}_onDisconnectTimeout(){return f.debug("_onDisconnectTimeout was called"),this._changeConnectStatus(f.Status.CONNTIMEOUT,null),this._proto._onDisconnectTimeout(),this._doDisconnect(),!1}_onIdle(){for(;this.addTimeds.length>0;)this.timedHandlers.push(this.addTimeds.pop());for(;this.removeTimeds.length>0;){const e=this.removeTimeds.pop(),t=this.timedHandlers.indexOf(e);t>=0&&this.timedHandlers.splice(t,1)}const e=(new Date).getTime(),t=[];for(let s=0;s<this.timedHandlers.length;s++){const n=this.timedHandlers[s];if(this.authenticated||!n.user){n.lastCalled+n.period-e<=0?n.run()&&t.push(n):t.push(n)}}this.timedHandlers=t,clearTimeout(this._idleTimeout),this._proto._onIdle(),this.connected&&(this._idleTimeout=setTimeout((()=>this._onIdle()),100))}},f.SASLMechanism=r,f.SASLAnonymous=class extends r{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"ANONYMOUS",arguments.length>1&&void 0!==arguments[1]&&arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:20)}test(e){return null===e.authcid}},f.SASLPlain=class extends r{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"PLAIN",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:50)}test(e){return null!==e.authcid}onChallenge(e){const{authcid:t,authzid:s,domain:n,pass:i}=e;if(!n)throw new Error("SASLPlain onChallenge: domain is not defined!");let r=s!==`${t}@${n}`?s:"";return r+="\0",r+=t,r+="\0",r+=i,o.utf16to8(r)}},f.SASLSHA1=class extends r{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"SCRAM-SHA-1",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:60)}test(e){return null!==e.authcid}async onChallenge(e,t){return a.scramResponse(e,t,"SHA-1",160)}clientChallenge(e,t){return a.clientChallenge(e,t)}},f.SASLSHA256=class extends r{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"SCRAM-SHA-256",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:70)}test(e){return null!==e.authcid}async onChallenge(e,t){return a.scramResponse(e,t,"SHA-256",256)}clientChallenge(e,t){return a.clientChallenge(e,t)}},f.SASLSHA384=class extends r{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"SCRAM-SHA-384",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:71)}test(e){return null!==e.authcid}async onChallenge(e,t){return a.scramResponse(e,t,"SHA-384",384)}clientChallenge(e,t){return a.clientChallenge(e,t)}},f.SASLSHA512=class extends r{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"SCRAM-SHA-512",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:72)}test(e){return null!==e.authcid}async onChallenge(e,t){return a.scramResponse(e,t,"SHA-512",512)}clientChallenge(e,t){return a.clientChallenge(e,t)}},f.SASLOAuthBearer=class extends r{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"OAUTHBEARER",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:40)}test(e){return null!==e.pass}onChallenge(e){let t="n,";return null!==e.authcid&&(t=t+"a="+e.authzid),t+=",",t+="",t+="auth=Bearer ",t+=e.pass,t+="",t+="",o.utf16to8(t)}},f.SASLExternal=class extends r{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"EXTERNAL",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:10)}onChallenge(e){return e.authcid===e.authzid?"":e.authzid}},f.SASLXOAuth2=class extends r{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"X-OAUTH2",!(arguments.length>1&&void 0!==arguments[1])||arguments[1],arguments.length>2&&void 0!==arguments[2]?arguments[2]:30)}test(e){return null!==e.pass}onChallenge(e){let t="\0";return null!==e.authcid&&(t+=e.authzid),t+="\0",t+=e.pass,o.utf16to8(t)}};var S={Strophe:f,$build:_,$iq:m,$msg:p,$pres:g};f.Request=class{constructor(e,t,s,n){this.id=++f._requestId,this.xmlData=e,this.data=f.serialize(e),this.origFunc=t,this.func=t,this.rid=s,this.date=NaN,this.sends=n||0,this.abort=!1,this.dead=null,this.age=function(){if(!this.date)return 0;return(new Date-this.date)/1e3},this.timeDead=function(){if(!this.dead)return 0;return(new Date-this.dead)/1e3},this.xhr=this._newXHR()}getResponse(){let e=null;if(this.xhr.responseXML&&this.xhr.responseXML.documentElement){if(e=this.xhr.responseXML.documentElement,"parsererror"===e.tagName)throw f.error("invalid response received"),f.error("responseText: "+this.xhr.responseText),f.error("responseXML: "+f.serialize(this.xhr.responseXML)),new Error("parsererror")}else if(this.xhr.responseText){if(f.debug("Got responseText but no responseXML; attempting to parse it with DOMParser..."),e=(new n).parseFromString(this.xhr.responseText,"application/xml").documentElement,!e)throw new Error("Parsing produced null node");if(e.querySelector("parsererror")){f.error("invalid response received: "+e.querySelector("parsererror").textContent),f.error("responseText: "+this.xhr.responseText);const t=new Error;throw t.name=f.ErrorCondition.BAD_FORMAT,t}}return e}_newXHR(){let e=null;return window.XMLHttpRequest?(e=new XMLHttpRequest,e.overrideMimeType&&e.overrideMimeType("text/xml; charset=utf-8")):window.ActiveXObject&&(e=new ActiveXObject("Microsoft.XMLHTTP")),e.onreadystatechange=this.func.bind(null,this),e}},f.Bosh=class e{constructor(e){this._conn=e,this.rid=Math.floor(4294967295*Math.random()),this.sid=null,this.hold=1,this.wait=60,this.window=5,this.errors=0,this.inactivity=null,this.lastResponseHeaders=null,this._requests=[]}_buildBody(){const e=_("body",{rid:this.rid++,xmlns:f.NS.HTTPBIND});return null!==this.sid&&e.attrs({sid:this.sid}),this._conn.options.keepalive&&this._conn._sessionCachingSupported()&&this._cacheSession(),e}_reset(){this.rid=Math.floor(4294967295*Math.random()),this.sid=null,this.errors=0,this._conn._sessionCachingSupported()&&window.sessionStorage.removeItem("strophe-bosh-session"),this._conn.nextValidRid(this.rid)}_connect(e,t,s){this.wait=e||this.wait,this.hold=t||this.hold,this.errors=0;const n=this._buildBody().attrs({to:this._conn.domain,"xml:lang":"en",wait:this.wait,hold:this.hold,content:"text/xml; charset=utf-8",ver:"1.6","xmpp:version":"1.0","xmlns:xmpp":f.NS.BOSH});s&&n.attrs({route:s});const i=this._conn._connect_cb;this._requests.push(new f.Request(n.tree(),this._onRequestStateChange.bind(this,i.bind(this._conn)),n.tree().getAttribute("rid"))),this._throttledRequestHandler()}_attach(e,t,s,n,i,r,o){this._conn.jid=e,this.sid=t,this.rid=s,this._conn.connect_callback=n,this._conn.domain=f.getDomainFromJid(this._conn.jid),this._conn.authenticated=!0,this._conn.connected=!0,this.wait=i||this.wait,this.hold=r||this.hold,this.window=o||this.window,this._conn._changeConnectStatus(f.Status.ATTACHED,null)}_restore(e,t,s,n,i){const r=JSON.parse(window.sessionStorage.getItem("strophe-bosh-session"));if(!(null!=r&&r.rid&&r.sid&&r.jid&&(null==e||f.getBareJidFromJid(r.jid)===f.getBareJidFromJid(e)||null===f.getNodeFromJid(e)&&f.getDomainFromJid(r.jid)===e))){const e=new Error("_restore: no restoreable session.");throw e.name="StropheSessionError",e}this._conn.restored=!0,this._attach(r.jid,r.sid,r.rid,t,s,n,i)}_cacheSession(){this._conn.authenticated?this._conn.jid&&this.rid&&this.sid&&window.sessionStorage.setItem("strophe-bosh-session",JSON.stringify({jid:this._conn.jid,rid:this.rid,sid:this.sid})):window.sessionStorage.removeItem("strophe-bosh-session")}_connect_cb(e){const t=e.getAttribute("type");if(null!==t&&"terminate"===t){let t=e.getAttribute("condition");f.error("BOSH-Connection failed: "+t);const s=e.getElementsByTagName("conflict");return null!==t?("remote-stream-error"===t&&s.length>0&&(t="conflict"),this._conn._changeConnectStatus(f.Status.CONNFAIL,t)):this._conn._changeConnectStatus(f.Status.CONNFAIL,"unknown"),this._conn._doDisconnect(t),f.Status.CONNFAIL}this.sid||(this.sid=e.getAttribute("sid"));const s=e.getAttribute("requests");s&&(this.window=parseInt(s,10));const n=e.getAttribute("hold");n&&(this.hold=parseInt(n,10));const i=e.getAttribute("wait");i&&(this.wait=parseInt(i,10));const r=e.getAttribute("inactivity");r&&(this.inactivity=parseInt(r,10))}_disconnect(e){this._sendTerminate(e)}_doDisconnect(){this.sid=null,this.rid=Math.floor(4294967295*Math.random()),this._conn._sessionCachingSupported()&&window.sessionStorage.removeItem("strophe-bosh-session"),this._conn.nextValidRid(this.rid)}_emptyQueue(){return 0===this._requests.length}_callProtocolErrorHandlers(t){const s=e._getRequestStatus(t),n=this._conn.protocolErrorHandlers.HTTP[s];n&&n.call(this,s)}_hitError(e){this.errors++,f.warn("request errored, status: "+e+", number of errors: "+this.errors),this.errors>4&&this._conn._onDisconnectTimeout()}_no_auth_received(e){f.warn("Server did not yet offer a supported authentication mechanism. Sending a blank poll request."),e=e?e.bind(this._conn):this._conn._connect_cb.bind(this._conn);const t=this._buildBody();this._requests.push(new f.Request(t.tree(),this._onRequestStateChange.bind(this,e),t.tree().getAttribute("rid"))),this._throttledRequestHandler()}_onDisconnectTimeout(){this._abortAllRequests()}_abortAllRequests(){for(;this._requests.length>0;){const e=this._requests.pop();e.abort=!0,e.xhr.abort(),e.xhr.onreadystatechange=function(){}}}_onIdle(){const e=this._conn._data;if(this._conn.authenticated&&0===this._requests.length&&0===e.length&&!this._conn.disconnecting&&(f.debug("no requests during idle cycle, sending blank request"),e.push(null)),!this._conn.paused){if(this._requests.length<2&&e.length>0){const t=this._buildBody();for(let s=0;s<e.length;s++)null!==e[s]&&("restart"===e[s]?t.attrs({to:this._conn.domain,"xml:lang":"en","xmpp:restart":"true","xmlns:xmpp":f.NS.BOSH}):t.cnode(e[s]).up());delete this._conn._data,this._conn._data=[],this._requests.push(new f.Request(t.tree(),this._onRequestStateChange.bind(this,this._conn._dataRecv.bind(this._conn)),t.tree().getAttribute("rid"))),this._throttledRequestHandler()}if(this._requests.length>0){const e=this._requests[0].age();null!==this._requests[0].dead&&this._requests[0].timeDead()>Math.floor(f.SECONDARY_TIMEOUT*this.wait)&&this._throttledRequestHandler(),e>Math.floor(f.TIMEOUT*this.wait)&&(f.warn("Request "+this._requests[0].id+" timed out, over "+Math.floor(f.TIMEOUT*this.wait)+" seconds since last activity"),this._throttledRequestHandler())}}}static _getRequestStatus(e,t){let s;if(4===e.xhr.readyState)try{s=e.xhr.status}catch(e){f.error("Caught an error while retrieving a request's status, reqStatus: "+s)}return void 0===s&&(s="number"==typeof t?t:0),s}_onRequestStateChange(t,s){if(f.debug("request id "+s.id+"."+s.sends+" state changed to "+s.xhr.readyState),s.abort)return void(s.abort=!1);if(4!==s.xhr.readyState)return;const n=e._getRequestStatus(s);if(this.lastResponseHeaders=s.xhr.getAllResponseHeaders(),this._conn.disconnecting&&n>=400)return this._hitError(n),void this._callProtocolErrorHandlers(s);const i=this._requests[0]===s,r=this._requests[1]===s,o=n>0&&n<500,a=s.sends>this._conn.maxRetries;(o||a)&&(this._removeRequest(s),f.debug("request id "+s.id+" should now be removed")),200===n?((r||i&&this._requests.length>0&&this._requests[0].age()>Math.floor(f.SECONDARY_TIMEOUT*this.wait))&&this._restartRequest(0),this._conn.nextValidRid(Number(s.rid)+1),f.debug("request id "+s.id+"."+s.sends+" got 200"),t(s),this.errors=0):0===n||n>=400&&n<600||n>=12e3?(f.error("request id "+s.id+"."+s.sends+" error "+n+" happened"),this._hitError(n),this._callProtocolErrorHandlers(s),n>=400&&n<500&&(this._conn._changeConnectStatus(f.Status.DISCONNECTING,null),this._conn._doDisconnect())):f.error("request id "+s.id+"."+s.sends+" error "+n+" happened"),o||a?a&&!this._conn.connected&&this._conn._changeConnectStatus(f.Status.CONNFAIL,"giving-up"):this._throttledRequestHandler()}_processRequest(t){let s=this._requests[t];const n=e._getRequestStatus(s,-1);if(s.sends>this._conn.maxRetries)return void this._conn._onDisconnectTimeout();const i=s.age(),r=!isNaN(i)&&i>Math.floor(f.TIMEOUT*this.wait),o=null!==s.dead&&s.timeDead()>Math.floor(f.SECONDARY_TIMEOUT*this.wait),a=4===s.xhr.readyState&&(n<1||n>=500);if((r||o||a)&&(o&&f.error(`Request ${this._requests[t].id} timed out (secondary), restarting`),s.abort=!0,s.xhr.abort(),s.xhr.onreadystatechange=function(){},this._requests[t]=new f.Request(s.xmlData,s.origFunc,s.rid,s.sends),s=this._requests[t]),0===s.xhr.readyState){f.debug("request id "+s.id+"."+s.sends+" posting");try{const e=this._conn.options.contentType||"text/xml; charset=utf-8";s.xhr.open("POST",this._conn.service,!this._conn.options.sync),void 0!==s.xhr.setRequestHeader&&s.xhr.setRequestHeader("Content-Type",e),this._conn.options.withCredentials&&(s.xhr.withCredentials=!0)}catch(e){return f.error("XHR open failed: "+e.toString()),this._conn.connected||this._conn._changeConnectStatus(f.Status.CONNFAIL,"bad-service"),void this._conn.disconnect()}const e=()=>{if(s.date=new Date,this._conn.options.customHeaders){const e=this._conn.options.customHeaders;for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&s.xhr.setRequestHeader(t,e[t])}s.xhr.send(s.data)};if(s.sends>1){const t=1e3*Math.min(Math.floor(f.TIMEOUT*this.wait),Math.pow(s.sends,3));setTimeout((function(){e()}),t)}else e();s.sends++,this._conn.xmlOutput!==f.Connection.prototype.xmlOutput&&(s.xmlData.nodeName===this.strip&&s.xmlData.childNodes.length?this._conn.xmlOutput(s.xmlData.childNodes[0]):this._conn.xmlOutput(s.xmlData)),this._conn.rawOutput!==f.Connection.prototype.rawOutput&&this._conn.rawOutput(s.data)}else f.debug("_processRequest: "+(0===t?"first":"second")+" request has readyState of "+s.xhr.readyState)}_removeRequest(e){f.debug("removing request");for(let t=this._requests.length-1;t>=0;t--)e===this._requests[t]&&this._requests.splice(t,1);e.xhr.onreadystatechange=function(){},this._throttledRequestHandler()}_restartRequest(e){const t=this._requests[e];null===t.dead&&(t.dead=new Date),this._processRequest(e)}_reqToData(e){try{return e.getResponse()}catch(e){if("parsererror"!==e.message)throw e;this._conn.disconnect("strophe-parsererror")}}_sendTerminate(e){f.debug("_sendTerminate was called");const t=this._buildBody().attrs({type:"terminate"});e&&t.cnode(e.tree());const s=new f.Request(t.tree(),this._onRequestStateChange.bind(this,this._conn._dataRecv.bind(this._conn)),t.tree().getAttribute("rid"));this._requests.push(s),this._throttledRequestHandler()}_send(){clearTimeout(this._conn._idleTimeout),this._throttledRequestHandler(),this._conn._idleTimeout=setTimeout((()=>this._conn._onIdle()),100)}_sendRestart(){this._throttledRequestHandler(),clearTimeout(this._conn._idleTimeout)}_throttledRequestHandler(){this._requests?f.debug("_throttledRequestHandler called with "+this._requests.length+" requests"):f.debug("_throttledRequestHandler called with undefined requests"),this._requests&&0!==this._requests.length&&(this._requests.length>0&&this._processRequest(0),this._requests.length>1&&Math.abs(this._requests[0].rid-this._requests[1].rid)<this.window&&this._processRequest(1))}},f.Bosh.prototype.strip=null,f.Websocket=class{constructor(e){this._conn=e,this.strip="wrapper";const t=e.service;if(0!==t.indexOf("ws:")&&0!==t.indexOf("wss:")){let s="";"ws"===e.options.protocol&&"https:"!==window.location.protocol?s+="ws":s+="wss",s+="://"+window.location.host,0!==t.indexOf("/")?s+=window.location.pathname+t:s+=t,e.service=s}}_buildStream(){return _("open",{xmlns:f.NS.FRAMING,to:this._conn.domain,version:"1.0"})}_checkStreamError(e,t){let s;if(s=e.getElementsByTagNameNS?e.getElementsByTagNameNS(f.NS.STREAM,"error"):e.getElementsByTagName("stream:error"),0===s.length)return!1;const n=s[0];let i="",r="";for(let e=0;e<n.childNodes.length;e++){const t=n.childNodes[e];if("urn:ietf:params:xml:ns:xmpp-streams"!==t.getAttribute("xmlns"))break;"text"===t.nodeName?r=t.textContent:i=t.nodeName}let o="WebSocket stream error: ";return o+=i||"unknown",r&&(o+=" - "+r),f.error(o),this._conn._changeConnectStatus(t,i),this._conn._doDisconnect(),!0}_reset(){}_connect(){this._closeSocket(),this.socket=new s(this._conn.service,"xmpp"),this.socket.onopen=()=>this._onOpen(),this.socket.onerror=e=>this._onError(e),this.socket.onclose=e=>this._onClose(e),this.socket.onmessage=e=>this._onInitialMessage(e)}_connect_cb(e){if(this._checkStreamError(e,f.Status.CONNFAIL))return f.Status.CONNFAIL}_handleStreamStart(e){let t=!1;const s=e.getAttribute("xmlns");"string"!=typeof s?t="Missing xmlns in <open />":s!==f.NS.FRAMING&&(t="Wrong xmlns in <open />: "+s);const n=e.getAttribute("version");return"string"!=typeof n?t="Missing version in <open />":"1.0"!==n&&(t="Wrong version in <open />: "+n),!t||(this._conn._changeConnectStatus(f.Status.CONNFAIL,t),this._conn._doDisconnect(),!1)}_onInitialMessage(e){if(0===e.data.indexOf("<open ")||0===e.data.indexOf("<?xml")){const t=e.data.replace(/^(<\?.*?\?>\s*)*/,"");if(""===t)return;const s=(new n).parseFromString(t,"text/xml").documentElement;this._conn.xmlInput(s),this._conn.rawInput(e.data),this._handleStreamStart(s)&&this._connect_cb(s)}else if(0===e.data.indexOf("<close ")){const t=(new n).parseFromString(e.data,"text/xml").documentElement;this._conn.xmlInput(t),this._conn.rawInput(e.data);const s=t.getAttribute("see-other-uri");if(s){const e=this._conn.service;(e.indexOf("wss:")>=0&&s.indexOf("wss:")>=0||e.indexOf("ws:")>=0)&&(this._conn._changeConnectStatus(f.Status.REDIRECT,"Received see-other-uri, resetting connection"),this._conn.reset(),this._conn.service=s,this._connect())}else this._conn._changeConnectStatus(f.Status.CONNFAIL,"Received closing stream"),this._conn._doDisconnect()}else{this._replaceMessageHandler();const t=this._streamWrap(e.data),s=(new n).parseFromString(t,"text/xml").documentElement;this._conn._connect_cb(s,null,e.data)}}_replaceMessageHandler(){this.socket.onmessage=e=>this._onMessage(e)}_disconnect(e){if(this.socket&&this.socket.readyState!==s.CLOSED){e&&this._conn.send(e);const t=_("close",{xmlns:f.NS.FRAMING});this._conn.xmlOutput(t.tree());const s=f.serialize(t);this._conn.rawOutput(s);try{this.socket.send(s)}catch(e){f.warn("Couldn't send <close /> tag.")}}setTimeout((()=>this._conn._doDisconnect()),0)}_doDisconnect(){f.debug("WebSockets _doDisconnect was called"),this._closeSocket()}_streamWrap(e){return"<wrapper>"+e+"</wrapper>"}_closeSocket(){if(this.socket)try{this.socket.onclose=null,this.socket.onerror=null,this.socket.onmessage=null,this.socket.close()}catch(e){f.debug(e.message)}this.socket=null}_emptyQueue(){return!0}_onClose(e){this._conn.connected&&!this._conn.disconnecting?(f.error("Websocket closed unexpectedly"),this._conn._doDisconnect()):e&&1006===e.code&&!this._conn.connected&&this.socket?(f.error("Websocket closed unexcectedly"),this._conn._changeConnectStatus(f.Status.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._conn._doDisconnect()):f.debug("Websocket closed")}_no_auth_received(e){f.error("Server did not offer a supported authentication mechanism"),this._conn._changeConnectStatus(f.Status.CONNFAIL,f.ErrorCondition.NO_AUTH_MECH),e&&e.call(this._conn),this._conn._doDisconnect()}_onDisconnectTimeout(){}_abortAllRequests(){}_onError(e){f.error("Websocket error "+JSON.stringify(e)),this._conn._changeConnectStatus(f.Status.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._disconnect()}_onIdle(){const e=this._conn._data;if(e.length>0&&!this._conn.paused){for(let t=0;t<e.length;t++)if(null!==e[t]){let s;s="restart"===e[t]?this._buildStream().tree():e[t];const n=f.serialize(s);this._conn.xmlOutput(s),this._conn.rawOutput(n),this.socket.send(n)}this._conn._data=[]}}_onMessage(e){let t;const s='<close xmlns="urn:ietf:params:xml:ns:xmpp-framing" />';if(e.data===s)return this._conn.rawInput(s),this._conn.xmlInput(e),void(this._conn.disconnecting||this._conn._doDisconnect());if(0===e.data.search("<open ")){if(t=(new n).parseFromString(e.data,"text/xml").documentElement,!this._handleStreamStart(t))return}else{const s=this._streamWrap(e.data);t=(new n).parseFromString(s,"text/xml").documentElement}return this._checkStreamError(t,f.Status.ERROR)?void 0:this._conn.disconnecting&&"presence"===t.firstChild.nodeName&&"unavailable"===t.firstChild.getAttribute("type")?(this._conn.xmlInput(t),void this._conn.rawInput(f.serialize(t))):void this._conn._dataRecv(t,e.data)}_onOpen(){f.debug("Websocket open");const e=this._buildStream();this._conn.xmlOutput(e.tree());const t=f.serialize(e);this._conn.rawOutput(t),this.socket.send(t)}_reqToData(e){return e}_send(){this._conn.flush()}_sendRestart(){clearTimeout(this._conn._idleTimeout),this._conn._onIdle.bind(this._conn)()}};const b={};b.debug=f.LogLevel.DEBUG,b.info=f.LogLevel.INFO,b.warn=f.LogLevel.WARN,b.error=f.LogLevel.ERROR,b.fatal=f.LogLevel.FATAL,f.WorkerWebsocket=class extends f.Websocket{constructor(e){super(e),this._conn=e,this.worker=new SharedWorker(this._conn.options.worker,"Strophe XMPP Connection"),this.worker.onerror=e=>{var t;null===(t=console)||void 0===t||t.error(e),f.log(f.LogLevel.ERROR,`Shared Worker Error: ${e}`)}}get socket(){return{send:e=>this.worker.port.postMessage(["send",e])}}_connect(){this._messageHandler=e=>this._onInitialMessage(e),this.worker.port.start(),this.worker.port.onmessage=e=>this._onWorkerMessage(e),this.worker.port.postMessage(["_connect",this._conn.service,this._conn.jid])}_attach(e){this._messageHandler=e=>this._onMessage(e),this._conn.connect_callback=e,this.worker.port.start(),this.worker.port.onmessage=e=>this._onWorkerMessage(e),this.worker.port.postMessage(["_attach",this._conn.service])}_attachCallback(e,t){e===f.Status.ATTACHED?(this._conn.jid=t,this._conn.authenticated=!0,this._conn.connected=!0,this._conn.restored=!0,this._conn._changeConnectStatus(f.Status.ATTACHED)):e===f.Status.ATTACHFAIL&&(this._conn.authenticated=!1,this._conn.connected=!1,this._conn.restored=!1,this._conn._changeConnectStatus(f.Status.ATTACHFAIL))}_disconnect(e,t){t&&this._conn.send(t);const s=_("close",{xmlns:f.NS.FRAMING});this._conn.xmlOutput(s.tree());const n=f.serialize(s);this._conn.rawOutput(n),this.worker.port.postMessage(["send",n]),this._conn._doDisconnect()}_onClose(e){this._conn.connected&&!this._conn.disconnecting?(f.error("Websocket closed unexpectedly"),this._conn._doDisconnect()):e&&1006===e.code&&!this._conn.connected?(f.error("Websocket closed unexcectedly"),this._conn._changeConnectStatus(f.Status.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._conn._doDisconnect()):f.debug("Websocket closed")}_closeSocket(){this.worker.port.postMessage(["_closeSocket"])}_replaceMessageHandler(){this._messageHandler=e=>this._onMessage(e)}_onWorkerMessage(e){const{data:t}=e,s=t[0];if("_onMessage"===s)this._messageHandler(t[1]);else if(s in this)try{this[s].apply(this,e.data.slice(1))}catch(e){f.log(f.LogLevel.ERROR,e)}else if("log"===s){const e=t[1],s=t[2];f.log(b[e],s)}else f.log(f.LogLevel.ERROR,`Found unhandled service worker message: ${t}`)}},t.$build=S.$build,t.$iq=S.$iq,t.$msg=S.$msg,t.$pres=S.$pres,t.Strophe=S.Strophe,e.$build=_,e.$iq=m,e.$msg=p,e.$pres=g,e.Strophe=f,Object.defineProperty(e,"__esModule",{value:!0})}));
|