UNPKG

strophe.js

Version:

Strophe.js is an XMPP library for JavaScript

1 lines 67.9 kB
!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";const t={AUTH:"jabber:iq:auth",BIND:"urn:ietf:params:xml:ns:xmpp-bind",BOSH:"urn:xmpp:xbosh",CLIENT:"jabber:client",COMPONENT:"jabber:component:accept",DISCO_INFO:"http://jabber.org/protocol/disco#info",DISCO_ITEMS:"http://jabber.org/protocol/disco#items",DELAY:"urn:xmpp:delay",FRAMING:"urn:ietf:params:xml:ns:xmpp-framing",HTTPBIND:"http://jabber.org/protocol/httpbind",MUC:"http://jabber.org/protocol/muc",PROFILE:"jabber:iq:profile",ROSTER:"jabber:iq:roster",SASL:"urn:ietf:params:xml:ns:xmpp-sasl",SERVER:"jabber:server",SESSION:"urn:ietf:params:xml:ns:xmpp-session",SM:"urn:xmpp:sm:3",STANZAS:"urn:ietf:params:xml:ns:xmpp-stanzas",STREAM:"http://etherx.jabber.org/streams",VERSION:"jabber:iq:version",XHTML:"http://www.w3.org/1999/xhtml",XHTML_IM:"http://jabber.org/protocol/xhtml-im"},s={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"]},n={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,RECONNECTING:13},i={BAD_FORMAT:"bad-format",CONFLICT:"conflict",MISSING_JID_NODE:"x-strophe-bad-non-anon-jid",NO_AUTH_MECH:"no-auth-mech",UNKNOWN_REASON:"unknown"},r={DEBUG:0,INFO:1,WARN:2,ERROR:3,FATAL:4},o={NORMAL:1,TEXT:3,CDATA:4,FRAGMENT:11};let a=r.DEBUG;const l={setLogLevel(e){if(e<r.DEBUG||e>r.FATAL)throw new Error("Invalid log level supplied to setLogLevel");a=e},log(e,t){e<a||(e>=r.ERROR?null===console||void 0===console||console.error(t):e===r.INFO?null===console||void 0===console||console.info(t):e===r.WARN?null===console||void 0===console||console.warn(t):e===r.DEBUG&&(null===console||void 0===console||console.debug(t)))},debug(e){this.log(r.DEBUG,e)},info(e){this.log(r.INFO,e)},warn(e){this.log(r.WARN,e)},error(e){this.log(r.ERROR,e)},fatal(e){this.log(r.FATAL,e)}};function c(e,t){const s=w(e),n=A(s);if(n)throw new Error(`Parser Error: ${n}`);const i=T(s);if(["message","iq","presence"].includes(i.nodeName.toLowerCase())&&"jabber:client"!==i.namespaceURI&&"jabber:server"!==i.namespaceURI){const e=`Invalid namespaceURI ${i.namespaceURI}`;if(t)throw new Error(e);l.error(e)}return i}function h(e){void 0!==e.stack&&l.fatal(e.stack),l.fatal("error: "+e.message)}function d(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|63&s)):(t+=String.fromCharCode(192|s>>6&31),t+=String.fromCharCode(128|63&s))}return t}function u(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}function _(e){let t="";const s=new Uint8Array(e),n=s.byteLength;for(let e=0;e<n;e++)t+=String.fromCharCode(s[e]);return btoa(t)}function p(e){var t;return null===(t=Uint8Array.from(atob(e),e=>e.charCodeAt(0)))||void 0===t?void 0:t.buffer}function m(e){return(new TextEncoder).encode(e).buffer}function g(e){if("undefined"==typeof document)return void l.error("addCookies: not adding any cookies, since there's no document object");const t=e||{};for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){let s="",n="",i="";const r=t[e],o="object"==typeof r,a=escape(unescape(o?r.value:r));if(o){const e=r;s=e.expires?";expires="+e.expires:"",n=e.domain?";domain="+e.domain:"",i=e.path?";path="+e.path:""}document.cookie=e+"="+a+s+n+i}}let f=null;function b(){return f||(f=document.implementation.createDocument("jabber:client","strophe",null)),f}function S(e){return b().createTextNode(e)}function y(e){const t=Array.from(e.childNodes);return 1===t.length&&t[0].nodeType===o.TEXT||t.forEach(t=>{"body"!==t.nodeName.toLowerCase()&&(t.nodeType!==o.TEXT||/\S/.test(t.nodeValue)?t.nodeType===o.NORMAL&&y(t):e.removeChild(t))}),e}function w(e){return(new DOMParser).parseFromString(e,"text/xml")}function A(e){var t;const s="parsererror"===(null===(t=e.firstElementChild)||void 0===t?void 0:t.nodeName)?e.firstElementChild:e.getElementsByTagNameNS("http://www.w3.org/1999/xhtml","parsererror")[0];return"parsererror"===(null==s?void 0:s.nodeName)?null==s?void 0:s.textContent:null}function T(e){if(e.firstElementChild)return e.firstElementChild;let t,s=0;const n=e.childNodes;for(;t=n[s++];)if(1===t.nodeType)return t;return null}function N(e,t,s){if(!e)return null;const n=b().createElement(e);if(!s||"string"!=typeof s&&"number"!=typeof s){if("string"==typeof t||"number"==typeof t)return n.appendChild(S(t.toString())),n}else n.appendChild(S(s.toString()));if(!t)return n;if(Array.isArray(t))for(const e of t)Array.isArray(e)&&null!=e[0]&&null!=e[1]&&n.setAttribute(e[0],e[1]);else if("object"==typeof t)for(const e of Object.keys(t))e&&null!=t[e]&&n.setAttribute(e,t[e].toString());return n}function x(e){for(let t=0;t<s.tags.length;t++)if(e===s.tags[t])return!0;return!1}function v(e,t){const n=s.attributes[e];if((null==n?void 0:n.length)>0)for(let e=0;e<n.length;e++)if(t===n[e])return!0;return!1}function C(e){for(let t=0;t<s.css.length;t++)if(e===s.css[t])return!0;return!1}function E(e){if(e.nodeType===o.NORMAL)return function(e){var t;let n;const i=e.nodeName.toLowerCase();if(x(i))try{if(n=N(i),i in s.attributes){const r=s.attributes[i];for(let s=0;s<r.length;s++){const i=r[s];let o=e.getAttribute(i);if(null!=o&&""!==o)if("style"===i&&"object"==typeof o&&(o=null!==(t=o.cssText)&&void 0!==t?t:o),"style"===i){const e=[],t=o.split(";");for(let s=0;s<t.length;s++){const n=t[s].split(":"),i=n[0].replace(/^\s*/,"").replace(/\s*$/,"").toLowerCase();if(C(i)){const t=n[1].replace(/^\s*/,"").replace(/\s*$/,"");e.push(i+": "+t)}}e.length>0&&(o=e.join("; "),n.setAttribute(i,o))}else n.setAttribute(i,o)}for(let t=0;t<e.childNodes.length;t++)n.appendChild(E(e.childNodes[t]))}}catch(e){n=S("")}else{n=b().createDocumentFragment();for(let t=0;t<e.childNodes.length;t++)n.appendChild(E(e.childNodes[t]))}return n}(e);if(e.nodeType===o.FRAGMENT){const t=b().createDocumentFragment();for(let s=0;s<e.childNodes.length;s++)t.appendChild(E(e.childNodes[s]));return t}return e.nodeType===o.TEXT?S(e.nodeValue):void 0}function k(e){let t;if(e.nodeType===o.NORMAL){const s=e;t=N(s.tagName);for(let e=0;e<s.attributes.length;e++)t.setAttribute(s.attributes[e].nodeName,s.attributes[e].value);for(let e=0;e<s.childNodes.length;e++)t.appendChild(k(s.childNodes[e]))}else e.nodeType===o.TEXT&&(t=b().createTextNode(e.nodeValue));return t}function R(e){return e.replace(/\&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/'/g,"&apos;").replace(/"/g,"&quot;")}function I(e,t,s){for(let n=0;n<e.childNodes.length;n++){const i=e.childNodes[n];i.nodeType!==o.NORMAL||t&&!O(i,t)||s(i)}}function O(e,t){return e.tagName===t}function M(e){return e.getAttribute("xmlns")||e.namespaceURI}function H(e){if(!e)return null;let t="";e.childNodes.length||e.nodeType!==o.TEXT||(t+=e.nodeValue);for(const s of e.childNodes)s.nodeType===o.TEXT&&(t+=s.nodeValue);return R(t)}function q(e){return e.indexOf("@")<0?null:e.split("@")[0]}function L(e){const t=F(e);if(t.indexOf("@")<0)return t;{const e=t.split("@");return e.splice(0,1),e.join("@")}}function D(e){if(!e)return null;const t=e.split("/");return t.length<2?null:(t.splice(0,1),t.join("/"))}function F(e){return e?e.split("/")[0]:null}const B={utf16to8:d,xorArrayBuffers:u,arrayBufToBase64:_,base64ToArrayBuf:p,stringToArrayBuf:m,addCookies:g};var j,$,P,U,z=Object.freeze({__proto__:null,addCookies:g,arrayBufToBase64:_,base64ToArrayBuf:p,copyElement:k,createHtml:E,default:B,escapeNode:function(e){return"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")},forEachChild:I,getBareJidFromJid:F,getDomainFromJid:L,getFirstElementChild:T,getNamespace:M,getNodeFromJid:q,getParserError:A,getResourceFromJid:D,getText:H,handleError:h,isTagEqual:O,stringToArrayBuf:m,stripWhitespace:y,toElement:c,unescapeNode:function(e){return"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,"\\")},utf16to8:d,validAttribute:v,validCSS:C,validTag:x,xmlElement:N,xmlGenerator:b,xmlHtmlNode:w,xmlTextNode:S,xmlescape:R,xmlunescape:function(e){return e=(e=(e=(e=(e=e.replace(/\&amp;/g,"&")).replace(/&lt;/g,"<")).replace(/&gt;/g,">")).replace(/&apos;/g,"'")).replace(/&quot;/g,'"')},xorArrayBuffers:u});function W(e,t,s,n){return new(s||(s=Promise))(function(i,r){function o(e){try{l(n.next(e))}catch(e){r(e)}}function a(e){try{l(n.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(o,a)}l((n=n.apply(e,t||[])).next())})}function J(e,t,s,n){if("a"===s&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?n:"a"===s?n.call(e):n?n.value:t.get(e)}function G(e,t,s,n,i){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?i.call(e,s):i?i.value=s:t.set(e,s),s}function X(e,t){return new Y(e,t)}function K(e){return new Y("message",e)}function V(e){return new Y("iq",e)}function Q(e){return new Y("presence",e)}"function"==typeof SuppressedError&&SuppressedError;class Y{constructor(e,s){j.set(this,void 0),$.set(this,void 0),P.set(this,void 0),U.set(this,void 0),"presence"!==e&&"message"!==e&&"iq"!==e||(s&&!s.xmlns?s.xmlns=t.CLIENT:s||(s={xmlns:t.CLIENT})),G(this,P,e,"f"),G(this,U,s,"f")}static fromString(e){const t=c(e,!0),s=new Y("");return G(s,j,t,"f"),s}buildTree(){return N(J(this,P,"f"),J(this,U,"f"))}get nodeTree(){return J(this,j,"f")||G(this,j,this.buildTree(),"f"),J(this,j,"f")}get node(){return J(this,$,"f")||G(this,$,this.tree(),"f"),J(this,$,"f")}set node(e){G(this,$,e,"f")}static serialize(e){if(!e)return null;const t=e instanceof Y?e.tree():e,s=[...Array(t.attributes.length).keys()].map(e=>t.attributes[e].nodeName);s.sort();let n=s.reduce((e,s)=>`${e} ${s}="${R(t.attributes.getNamedItem(s).value)}"`,`<${t.nodeName}`);if(t.childNodes.length>0){n+=">";for(let e=0;e<t.childNodes.length;e++){const s=t.childNodes[e];switch(s.nodeType){case o.NORMAL:n+=Y.serialize(s);break;case o.TEXT:n+=R(s.nodeValue);break;case o.CDATA:n+="<![CDATA["+s.nodeValue+"]]>"}}n+="</"+t.nodeName+">"}else n+="/>";return n}tree(){return this.nodeTree}toString(){return Y.serialize(this.tree())}up(){return this.node=this.node.parentElement?this.node.parentElement:this.node.parentNode,this}root(){return this.node=this.tree(),this}attrs(e){for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(null!=e[t]?this.node.setAttribute(t,e[t].toString()):this.node.removeAttribute(t));return this}c(e,t,s){const n=N(e,t,s);return this.node.appendChild(n),"string"!=typeof s&&"number"!=typeof s&&(this.node=n),this}cnode(e){let t;e instanceof Y&&(e=e.tree());const s=b();try{t=void 0!==s.importNode}catch(e){t=!1}const n=t?s.importNode(e,!0):k(e);return this.node.appendChild(n),this.node=n,this}t(e){const t=S(e);return this.node.appendChild(t),this}h(e){const t=b().createElement("body");t.innerHTML=e;const s=E(t);for(;s.childNodes.length>0;)this.node.appendChild(s.childNodes[0]);return this}}j=new WeakMap,$=new WeakMap,P=new WeakMap,U=new WeakMap;let Z=0;class ee{constructor(e,t,s,n=0){this.id=++Z,this.xmlData=e,this.data=Y.serialize(e),this.origFunc=t,this.func=t,this.rid=s,this.date=NaN,this.sends=n,this.abort=!1,this.dead=null,this.age=()=>this.date?((new Date).valueOf()-this.date.valueOf())/1e3:0,this.timeDead=()=>this.dead?((new Date).valueOf()-this.dead.valueOf())/1e3:0,this.xhr=this._newXHR()}getResponse(){var e;const t=null===(e=this.xhr.responseXML)||void 0===e?void 0:e.documentElement;if(t){if("parsererror"===t.tagName)throw l.error("invalid response received"),l.error("responseText: "+this.xhr.responseText),l.error("responseXML: "+Y.serialize(t)),new Error("parsererror")}else if(this.xhr.responseText){l.debug("Got responseText but no responseXML; attempting to parse it with DOMParser...");const e=w(this.xhr.responseText),t=A(e);if(!e||t){t&&(l.error("invalid response received: "+t),l.error("responseText: "+this.xhr.responseText));const e=new Error;throw e.name=i.BAD_FORMAT,e}}return null!=t?t:null}_newXHR(){const e=new XMLHttpRequest;return e.overrideMimeType&&e.overrideMimeType("text/xml; charset=utf-8"),e.onreadystatechange=this.func.bind(null,this),e}}let te=1.1,se=.1;class ne{constructor(e){var t;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.strip=null!==(t=ne.prototype.strip)&&void 0!==t&&t,this.lastResponseHeaders=null,this._requests=[]}static setTimeoutMultiplier(e){te=e}static getTimeoutMultplier(){return te}static setSecondaryTimeoutMultiplier(e){se=e}static getSecondaryTimeoutMultplier(){return se}_buildBody(){const e=X("body",{rid:this.rid++,xmlns:t.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()&&sessionStorage.removeItem("strophe-bosh-session"),this._conn.nextValidRid(this.rid)}_connect(e,s,n){this.wait=e||this.wait,this.hold=s||this.hold,this.errors=0;const i=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":t.BOSH});n&&i.attrs({route:n});const r=this._conn._connect_cb;this._requests.push(new ee(i.tree(),this._onRequestStateChange.bind(this,r.bind(this._conn)),Number(i.tree().getAttribute("rid")))),this._throttledRequestHandler()}_attach(e,t,s,i,r,o,a){this._conn.jid=e,this.sid=t,this.rid=s,this._conn.connect_callback=i,this._conn.domain=L(this._conn.jid),this._conn.authenticated=!0,this._conn.connected=!0,this.wait=r||this.wait,this.hold=o||this.hold,this.window=a||this.window,this._conn._changeConnectStatus(n.ATTACHED,null)}_restore(e,t,s,n,i){const r=JSON.parse(sessionStorage.getItem("strophe-bosh-session"));if(!(null!=r&&r.rid&&r.sid&&r.jid&&(null==e||F(r.jid)===F(e)||null===q(e)&&L(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&&sessionStorage.setItem("strophe-bosh-session",JSON.stringify({jid:this._conn.jid,rid:this.rid,sid:this.sid})):sessionStorage.removeItem("strophe-bosh-session")}_connect_cb(e){const t=e.getAttribute("type");if(null!==t&&"terminate"===t){let t=e.getAttribute("condition");l.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(n.CONNFAIL,t)):this._conn._changeConnectStatus(n.CONNFAIL,"unknown"),this._conn._doDisconnect(t),n.CONNFAIL}this.sid||(this.sid=e.getAttribute("sid"));const s=e.getAttribute("requests");s&&(this.window=parseInt(s,10));const i=e.getAttribute("hold");i&&(this.hold=parseInt(i,10));const r=e.getAttribute("wait");r&&(this.wait=parseInt(r,10));const o=e.getAttribute("inactivity");o&&(this.inactivity=parseInt(o,10))}_disconnect(e){this._sendTerminate(e)}_doDisconnect(){this.sid=null,this.rid=Math.floor(4294967295*Math.random()),this._conn._sessionCachingSupported()&&sessionStorage.removeItem("strophe-bosh-session"),this._conn.nextValidRid(this.rid)}_emptyQueue(){return 0===this._requests.length}_callProtocolErrorHandlers(e){const t=ne._getRequestStatus(e),s=this._conn.protocolErrorHandlers.HTTP[t];s&&s.call(this,t)}_hitError(e){this.errors++,l.warn("request errored, status: "+e+", number of errors: "+this.errors),this.errors>4&&this._conn._onDisconnectTimeout()}_no_auth_received(e){l.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 ee(t.tree(),this._onRequestStateChange.bind(this,e),Number(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&&(l.debug("no requests during idle cycle, sending blank request"),e.push(null)),!this._conn.paused){if(this._requests.length<2&&e.length>0){const s=this._buildBody();for(let n=0;n<e.length;n++)null!==e[n]&&("restart"===e[n]?s.attrs({to:this._conn.domain,"xml:lang":"en","xmpp:restart":"true","xmlns:xmpp":t.BOSH}):s.cnode(e[n]).up());delete this._conn._data,this._conn._data=[],this._requests.push(new ee(s.tree(),this._onRequestStateChange.bind(this,this._conn._dataRecv.bind(this._conn)),Number(s.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(te*this.wait)&&this._throttledRequestHandler(),e>Math.floor(te*this.wait)&&(l.warn("Request "+this._requests[0].id+" timed out, over "+Math.floor(te*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){l.error(`Caught an error while retrieving a request's status, reqStatus: ${s}, message: ${e.message}`)}return void 0===s&&(s="number"==typeof t?t:0),s}_onRequestStateChange(e,t){if(l.debug("request id "+t.id+"."+t.sends+" state changed to "+t.xhr.readyState),t.abort)return void(t.abort=!1);if(4!==t.xhr.readyState)return;const s=ne._getRequestStatus(t);if(this.lastResponseHeaders=t.xhr.getAllResponseHeaders(),this._conn.disconnecting&&s>=400)return this._hitError(s),void this._callProtocolErrorHandlers(t);const i=this._requests[0]===t,r=this._requests[1]===t,o=s>0&&s<500,a=t.sends>this._conn.maxRetries;(o||a)&&(this._removeRequest(t),l.debug("request id "+t.id+" should now be removed")),200===s?((r||i&&this._requests.length>0&&this._requests[0].age()>Math.floor(te*this.wait))&&this._restartRequest(0),this._conn.nextValidRid(t.rid+1),l.debug("request id "+t.id+"."+t.sends+" got 200"),e(t),this.errors=0):0===s||s>=400&&s<600||s>=12e3?(l.error("request id "+t.id+"."+t.sends+" error "+s+" happened"),this._hitError(s),this._callProtocolErrorHandlers(t),s>=400&&s<500&&(this._conn._changeConnectStatus(n.DISCONNECTING,null),this._conn._doDisconnect())):l.error("request id "+t.id+"."+t.sends+" error "+s+" happened"),o||a?a&&!this._conn.connected&&this._conn._changeConnectStatus(n.CONNFAIL,"giving-up"):this._throttledRequestHandler()}_processRequest(e){var t,s,i,r,o,a;let c=this._requests[e];const h=ne._getRequestStatus(c,-1);if(c.sends>this._conn.maxRetries)return void this._conn._onDisconnectTimeout();const d=c.age(),u=!isNaN(d)&&d>Math.floor(te*this.wait),_=null!==c.dead&&c.timeDead()>Math.floor(se*this.wait),p=4===c.xhr.readyState&&(h<1||h>=500);if((u||_||p)&&(_&&l.error(`Request ${this._requests[e].id} timed out (secondary), restarting`),c.abort=!0,c.xhr.abort(),c.xhr.onreadystatechange=function(){},this._requests[e]=new ee(c.xmlData,c.origFunc,c.rid,c.sends),c=this._requests[e]),0===c.xhr.readyState){l.debug("request id "+c.id+"."+c.sends+" posting");try{const e=this._conn.options.contentType||"text/xml; charset=utf-8";c.xhr.open("POST",this._conn.service,!this._conn.options.sync),void 0!==c.xhr.setRequestHeader&&c.xhr.setRequestHeader("Content-Type",e),this._conn.options.withCredentials&&(c.xhr.withCredentials=!0)}catch(e){return l.error("XHR open failed: "+e.toString()),this._conn.connected||this._conn._changeConnectStatus(n.CONNFAIL,"bad-service"),void this._conn.disconnect()}const e=()=>{if(c.date=(new Date).valueOf(),this._conn.options.customHeaders){const e=this._conn.options.customHeaders;for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&c.xhr.setRequestHeader(t,e[t])}c.xhr.send(c.data)};if(c.sends>1){const t=1e3*Math.min(Math.floor(te*this.wait),Math.pow(c.sends,3));setTimeout(function(){e()},t)}else e();c.sends++,this.strip&&"body"===c.xmlData.nodeName&&c.xmlData.childNodes.length?null===(s=(t=this._conn).xmlOutput)||void 0===s||s.call(t,c.xmlData.children[0]):null===(r=(i=this._conn).xmlOutput)||void 0===r||r.call(i,c.xmlData),null===(a=(o=this._conn).rawOutput)||void 0===a||a.call(o,c.data)}else l.debug("_processRequest: "+(0===e?"first":"second")+" request has readyState of "+c.xhr.readyState)}_removeRequest(e){l.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){l.debug("_sendTerminate was called");const t=this._buildBody().attrs({type:"terminate"}),s=e instanceof Y?e.tree():e;e&&t.cnode(s);const n=new ee(t.tree(),this._onRequestStateChange.bind(this,this._conn._dataRecv.bind(this._conn)),Number(t.tree().getAttribute("rid")));this._requests.push(n),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?l.debug("_throttledRequestHandler called with "+this._requests.length+" requests"):l.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))}}class ie{constructor(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.matchBareFromJid?this.from=r?F(r):null:this.from=r,this.user=!0}getNamespace(e){let t=M(e);return t&&this.options.ignoreNamespaceFragment&&(t=t.split("#")[0]),t}namespaceMatch(e){var t;if(!this.ns||this.getNamespace(e)===this.ns)return!0;for(const s of null!==(t=e.children)&&void 0!==t?t:[]){if(this.getNamespace(s)===this.ns)return!0;if(this.namespaceMatch(s))return!0}return!1}isMatch(e){let t=e.getAttribute("from");this.options.matchBareFromJid&&(t=F(t));const s=e.getAttribute("type");return!(!this.namespaceMatch(e)||this.name&&!O(e,this.name)||this.type&&(Array.isArray(this.type)?-1===this.type.indexOf(null!=s?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 h(e),e}return t}toString(){return"{Handler: "+this.handler+"("+this.name+","+this.id+","+this.ns+")}"}}class re{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+")}"}}class oe{constructor(e,t,s){this.mechname=e,this.isClientFirst=t,this.priority=s,this._connection=null}test(e){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}}class ae extends oe{constructor(e="ANONYMOUS",t=!1,s=20){super(e,t,s)}test(e){return null===e.authcid}}class le extends oe{constructor(e="EXTERNAL",t=!0,s=10){super(e,t,s)}onChallenge(e){return e.authcid===e.authzid?"":e.authzid}}class ce extends oe{constructor(e="OAUTHBEARER",t=!0,s=40){super(e,t,s)}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+="",B.utf16to8(t)}}class he extends oe{constructor(e="PLAIN",t=!0,s=50){super(e,t,s)}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,B.utf16to8(r)}}const de={supported:()=>"undefined"!=typeof crypto&&void 0!==crypto.subtle,scramResponse(e,t,s,n){return W(this,void 0,void 0,function*(){const i=e._sasl_data.cnonce,r=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=B.base64ToArrayBuf(r[2]);break;case"i":n=parseInt(r[2],10);break;case"m":return}}if(isNaN(n)||n<4096)l.warn("Failing SCRAM authentication because server supplied iteration count < 4096.");else{if(s)return{nonce:t,salt:s,iter:n};l.warn("Failing SCRAM authentication because server supplied incorrect salt.")}}(t);if(!r||r.nonce.slice(0,i.length)!==i)return l.warn("Failing SCRAM authentication because server supplied incorrect nonce."),e._sasl_data={},e._sasl_failure_cb(null);let o,a;const{pass:c}=e;if("string"==typeof e.pass||e.pass instanceof String){const e=yield function(e,t,s,n,i){return W(this,void 0,void 0,function*(){const r=yield crypto.subtle.deriveBits({name:"PBKDF2",salt:t,iterations:s,hash:{name:n}},yield crypto.subtle.importKey("raw",B.stringToArrayBuf(e),"PBKDF2",!1,["deriveBits"]),i),o=yield crypto.subtle.importKey("raw",r,{name:"HMAC",hash:n},!1,["sign"]);return{ck:yield crypto.subtle.sign("HMAC",o,B.stringToArrayBuf("Client Key")),sk:yield crypto.subtle.sign("HMAC",o,B.stringToArrayBuf("Server Key"))}})}(c,r.salt,r.iter,s,n);o=e.ck,a=e.sk}else{if((null==c?void 0:c.name)!==s||(null==c?void 0:c.salt)!==B.arrayBufToBase64(r.salt)||(null==c?void 0:c.iter)!==r.iter)return e._sasl_failure_cb(null);{const{ck:e,sk:t}=c;o=B.base64ToArrayBuf(e),a=B.base64ToArrayBuf(t)}}const h=e._sasl_data["client-first-message-bare"],d=t,u=`c=biws,r=${r.nonce}`,_=`${h},${d},${u}`,p=yield function(e,t,s){return W(this,void 0,void 0,function*(){const n=yield crypto.subtle.importKey("raw",yield crypto.subtle.digest(s,t),{name:"HMAC",hash:s},!1,["sign"]),i=yield crypto.subtle.sign("HMAC",n,B.stringToArrayBuf(e));return B.xorArrayBuffers(t,i)})}(_,o,s),m=yield function(e,t,s){return W(this,void 0,void 0,function*(){const n=yield crypto.subtle.importKey("raw",t,{name:"HMAC",hash:s},!1,["sign"]);return crypto.subtle.sign("HMAC",n,B.stringToArrayBuf(e))})}(_,a,s);return e._sasl_data["server-signature"]=B.arrayBufToBase64(m),e._sasl_data.keys={name:s,iter:r.iter,salt:B.arrayBufToBase64(r.salt),ck:B.arrayBufToBase64(o),sk:B.arrayBufToBase64(a)},`${u},p=${B.arrayBufToBase64(p)}`})},clientChallenge(e,t){const s=t||function(){const e=new Uint8Array(16);return B.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,B.utf16to8(`n,,${n}`)}};class ue extends oe{constructor(e="SCRAM-SHA-1",t=!0,s=60){super(e,t,s)}test(e){return null!==e.authcid&&de.supported()}onChallenge(e,t){return W(this,void 0,void 0,function*(){return yield de.scramResponse(e,t,"SHA-1",160)})}clientChallenge(e,t){return de.clientChallenge(e,t)}}class _e extends oe{constructor(e="SCRAM-SHA-256",t=!0,s=70){super(e,t,s)}test(e){return null!==e.authcid&&de.supported()}onChallenge(e,t){return W(this,void 0,void 0,function*(){return yield de.scramResponse(e,t,"SHA-256",256)})}clientChallenge(e,t){return de.clientChallenge(e,t)}}class pe extends oe{constructor(e="SCRAM-SHA-384",t=!0,s=71){super(e,t,s)}test(e){return null!==e.authcid&&de.supported()}onChallenge(e,t){return W(this,void 0,void 0,function*(){return yield de.scramResponse(e,t,"SHA-384",384)})}clientChallenge(e,t){return de.clientChallenge(e,t)}}class me extends oe{constructor(e="SCRAM-SHA-512",t=!0,s=72){super(e,t,s)}test(e){return null!==e.authcid&&de.supported()}onChallenge(e,t){return W(this,void 0,void 0,function*(){return yield de.scramResponse(e,t,"SHA-512",512)})}clientChallenge(e,t){return de.clientChallenge(e,t)}}class ge extends oe{constructor(e="X-OAUTH2",t=!0,s=30){super(e,t,s)}test(e){return null!==e.pass}onChallenge(e){let t="\0";return null!==e.authcid&&(t+=e.authzid),t+="\0",t+=e.pass,B.utf16to8(t)}}class fe extends Error{constructor(e){super(e),this.name="StropheSessionError"}}class be{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:"!==location.protocol?s+="ws":s+="wss",s+="://"+location.host,0!==t.indexOf("/")?s+=location.pathname+t:s+=t,e.service=s}}_buildStream(){return X("open",{xmlns:t.FRAMING,to:this._conn.domain,version:"1.0"})}_checkStreamError(e,s){let n;if(n=e.getElementsByTagNameNS?e.getElementsByTagNameNS(t.STREAM,"error"):e.getElementsByTagName("stream:error"),0===n.length)return!1;const i=n[0];let r="",o="";for(let e=0;e<i.childNodes.length;e++){const t=i.childNodes[e];if(t.nodeType===t.ELEMENT_NODE){if("urn:ietf:params:xml:ns:xmpp-streams"!==t.getAttribute("xmlns"))break}"text"===t.nodeName?o=t.textContent||"":r=t.nodeName}let a="WebSocket stream error: ";return a+=r||"unknown",o&&(a+=" - "+o),l.error(a),this._conn._changeConnectStatus(s,r),this._conn._doDisconnect(),!0}_reset(){}_connect(){this._closeSocket(),this.socket=new WebSocket(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,n.CONNFAIL))return n.CONNFAIL}_handleStreamStart(e){let s=null;const i=e.getAttribute("xmlns");"string"!=typeof i?s="Missing xmlns in <open />":i!==t.FRAMING&&(s="Wrong xmlns in <open />: "+i);const r=e.getAttribute("version");return"string"!=typeof r?s="Missing version in <open />":"1.0"!==r&&(s="Wrong version in <open />: "+r),!s||(this._conn._changeConnectStatus(n.CONNFAIL,s),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 DOMParser).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 DOMParser).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(n.REDIRECT,"Received see-other-uri, resetting connection"),this._conn.reset(),this._conn.service=s,this._connect())}else this._conn._changeConnectStatus(n.CONNFAIL,"Received closing stream"),this._conn._doDisconnect()}else{this._replaceMessageHandler();const t=this._streamWrap(e.data),s=(new DOMParser).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!==WebSocket.CLOSED){e&&this._conn.send(e);const s=X("close",{xmlns:t.FRAMING});this._conn.xmlOutput(s.tree());const n=Y.serialize(s);this._conn.rawOutput(n);try{this.socket.send(n)}catch(e){l.warn(`Couldn't send <close /> tag. "${e.message}"`)}}setTimeout(()=>this._conn._doDisconnect(),0)}_doDisconnect(){l.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){l.debug(e.message)}this.socket=null}_emptyQueue(){return!0}_onClose(e){this._conn.connected&&!this._conn.disconnecting?(l.error("Websocket closed unexpectedly"),this._conn._doDisconnect()):e&&1006===e.code&&!this._conn.connected&&this.socket?(l.error("Websocket closed unexcectedly"),this._conn._changeConnectStatus(n.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._conn._doDisconnect()):l.debug("Websocket closed")}_no_auth_received(e){l.error("Server did not offer a supported authentication mechanism"),this._conn._changeConnectStatus(n.CONNFAIL,i.NO_AUTH_MECH),null==e||e.call(this._conn),this._conn._doDisconnect()}_onDisconnectTimeout(){}_abortAllRequests(){}_onError(e){l.error("Websocket error "+JSON.stringify(e)),this._conn._changeConnectStatus(n.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]){const s="restart"===e[t]?this._buildStream().tree():e[t];if("restart"===s)throw new Error("Wrong type for stanza");const n=Y.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 DOMParser).parseFromString(e.data,"text/xml").documentElement,!this._handleStreamStart(t))return}else{const s=this._streamWrap(e.data);t=(new DOMParser).parseFromString(s,"text/xml").documentElement}return this._checkStreamError(t,n.ERROR)?void 0:this._conn.disconnecting&&"presence"===t.firstElementChild.nodeName&&"unavailable"===t.firstElementChild.getAttribute("type")?(this._conn.xmlInput(t),void this._conn.rawInput(Y.serialize(t))):void this._conn._dataRecv(t,e.data)}_onOpen(){l.debug("Websocket open");const e=this._buildStream();this._conn.xmlOutput(e.tree());const t=Y.serialize(e);this._conn.rawOutput(t),this.socket.send(t)}_send(){this._conn.flush()}_sendRestart(){clearTimeout(this._conn._idleTimeout),this._conn._onIdle.bind(this._conn)()}}class Se extends be{constructor(e){super(e),this._conn=e,this._initWorker()}_initWorker(){this.worker&&(this.worker.port.postMessage(["_bye"]),this.worker.port.close()),this.worker=new SharedWorker(this._conn.options.worker,"Strophe XMPP Connection"),this.worker.onerror=e=>{null===console||void 0===console||console.error(e),l.error(`Shared Worker Error: ${e}`)}}_setSocket(){this.socket={send:e=>this.worker.port.postMessage(["send",e]),close:()=>this.worker.port.postMessage(["_closeSocket"]),onopen:()=>{},onerror:e=>this._onError(e),onclose:e=>this._onClose(e),onmessage:()=>{},readyState:null}}_connect(){this._initWorker(),this._setSocket(),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,3]),this._attachLifecycleListeners()}_attach(e){this._initWorker(),this._setSocket(),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,3]),this._attachLifecycleListeners()}_role(e,t){this._conn.role=e,"secondary"===e&&(this._messageHandler=e=>this._onMessage(e),t&&(this._conn.jid=t)),this._conn.onRoleChanged(e)}_promote(e){this._conn.role="primary",e&&(this._conn.jid=e),this._conn.onRoleChanged("primary")}_smFeatures(){this.worker.port.postMessage(["_smFeatures"])}_bound(e){this.worker.port.postMessage(["_bound",e])}_ping(){this.worker.port.postMessage(["_pong"])}_onStanzaSent(e){this._conn.onForeignStanzaSent(c(e))}_smNoState(){this._conn._proceedToBind()}_smEnabled(e,t,s){var n;null===(n=this._conn.sm)||void 0===n||n._onEnabled(e,t,s)}_smResumed(e,t,s){var i;const r=this._conn;null===(i=r.sm)||void 0===i||i._onResumed(e,t,s),r.jid=e,"primary"===r.role&&(r.do_bind=!1,r.authenticated=!0,r.restored=!0,r._changeConnectStatus(n.CONNECTED,null))}_smFailed(){var e;const t=this._conn;null===(e=t.sm)||void 0===e||e._onFailed(),"primary"===t.role&&(t.do_bind=!0,t._proceedToBind())}_attachLifecycleListeners(){this._lifecycleAttached||"undefined"==typeof window||(window.addEventListener("pagehide",()=>this.worker.port.postMessage(["_bye"])),window.addEventListener("pageshow",()=>this.worker.port.postMessage(["_pong"])),document.addEventListener("freeze",()=>this.worker.port.postMessage(["_relinquish"])),document.addEventListener("resume",()=>this.worker.port.postMessage(["_pong"])),this._lifecycleAttached=!0)}_onClose(e){if(this._conn.connected&&!this._conn.disconnecting)l.error("Websocket closed unexpectedly"),this._conn._doDisconnect();else if(this._conn.connected||this._conn.disconnecting)l.debug("Websocket closed");else{const t="string"==typeof e?e:"The shared websocket connection could not be established or was lost.";l.error(`Shared websocket closed while connecting: ${t}`),this._conn._changeConnectStatus(n.CONNFAIL,t),this._conn._doDisconnect()}}_attachCallback(e,t,s){e===n.ATTACHED?(this._conn.jid=t,this._conn.authenticated=!0,this._conn.connected=!0,this._conn.restored=!0,this._conn._changeConnectStatus(n.ATTACHED)):e===n.ATTACHFAIL&&(this._conn.authenticated=!1,this._conn.connected=!1,this._conn.restored=!1,this._conn._changeConnectStatus(n.ATTACHFAIL))}_disconnect(e){e&&this._conn.send(e);const s=X("close",{xmlns:t.FRAMING});this._conn.xmlOutput(s.tree());const n=Y.serialize(s);this._conn.rawOutput(n),this.worker.port.postMessage(["send",n]),this._conn._doDisconnect()}_closeSocket(){this.socket.close()}_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){l.error(String(e))}else if("log"===s){const e={debug:r.DEBUG,info:r.INFO,warn:r.WARN,error:r.ERROR,fatal:r.FATAL},s=t[1],n=t[2];l.log(e[s],n)}else l.error(`Found unhandled service worker message: ${t}`)}}const ye=2**32,we=["iq","presence","message"];function Ae(e){if("string"!=typeof e)return null;const t=parseInt(e,10);return Number.isNaN(t)||t<0?null:t%ye}function Te(e){return we.includes(e)}function Ne(e){const t=e.indexOf(">");if(-1===t)return e;const s=e.slice(0,t),n=e.slice(t),i=s.replace(/\sfrom=(["'])[\s\S]*?\1/,"");return i===s?e:i+n}function xe(e,s,n){if(e.includes(t.DELAY))return e;const i=`<delay xmlns="${t.DELAY}" stamp="${new Date(n).toISOString()}"/>`;if(e.endsWith("/>"))return`${e.slice(0,-2)}>${i}</${s}>`;const r=e.lastIndexOf(`</${s}`);return-1===r?e:e.slice(0,r)+i+e.slice(r)}class ve{constructor(){this.store=new Map}load(e){const t=this.store.get(e);return t?JSON.parse(t):null}save(e,t){this.store.set(e,JSON.stringify(t))}clear(e){this.store.delete(e)}}class Ce{constructor(){if("undefined"==typeof sessionStorage)throw new Error("SessionStorageBackend requires a sessionStorage global (browser page context)")}load(e){const t=sessionStorage.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch(t){return l.warn(`Discarding unparseable SM state for ${e}: ${t.message}`),null}}save(e,t){sessionStorage.setItem(e,JSON.stringify(t))}clear(e){sessionStorage.removeItem(e)}}class Ee{constructor(e,t={}){this._sendRaw=e,this._options=Object.assign({maxUnacked:5,requestResume:!0},t),this._storage=this._options.storage||new ve,this._storageKey=null,this._state={boundJid:null,enableSent:!1,enabled:!1,hIn:0,hOutAcked:0,id:null,location:null,max:null,resumeSupported:!1,resumed:!1,sinceLastAck:0,unacked:[]},this._resumePending=!1,this._pendingResend=[],this.serverSupported=!1}get state(){return this._state}get enabled(){return this._state.enabled}get resumed(){return this._state.resumed}get boundJid(){return this._state.boundJid}get resumePending(){return this._resumePending}initialize(e){this._storageKey=`strophe-sm:${e.split("/")[0].toLowerCase()}`;const t=this._storage.load(this._storageKey);t&&(this._state=Object.assign(Object.assign({},{boundJid:null,enableSent:!1,enabled:!1,hIn:0,hOutAcked:0,id:null,location:null,max:null,resumeSupported:!1,resumed:!1,sinceLastAck:0,unacked:[]}),t))}hasResumableState(){return!(!this._state.id||!this._state.resumeSupported)}reset(){this._state={boundJid:null,enableSent:!1,enabled:!1,hIn:0,hOutAcked:0,id:null,location:null,max:null,resumeSupported:!1,resumed:!1,sinceLastAck:0,unacked:[]},this._resumePending=!1,this._pendingResend=[],this.serverSupported=!1}clearPersistedState(){this._storageKey&&this._storage.clear(this._storageKey)}sendEnable(e){const s=this._state;if(s.enableSent)return void l.warn("StreamManagement.sendEnable called but <enable/> was already sent for this session");s.enableSent=!0,s.enabled=!1,s.resumed=!1,s.id=null,s.max=null,s.location=null,s.resumeSupported=!1,s.hIn=0,s.hOutAcked=0,s.sinceLastAck=0,s.unacked=[],s.boundJid=e;const n=this._options.requestResume?' resume="true"':"",i=this._options.max?` max="${this._options.max}"`:"";this._sendRaw(`<enable xmlns="${t.SM}"${n}${i}/>`),this._persist()}sendResume(){const e=this._state;var s;this.hasResumableState()?(this._resumePending=!0,this._sendRaw(`<resume xmlns="${t.SM}" h="${e.hIn}" previd="${s=e.id,s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/'/g,"&apos;").replace(/"/g,"&quot;")}"/>`)):l.warn("StreamManagement.sendResume called without resumable state")}isTracking(){return this._state.enableSent}trackOutbound(e){const t=this._state;if(!t.enableSent||!Te(e.name))return;t.unacked.push({name:e.name,stanza:e.serialized,queuedAt:Date.now()}),t.sinceLastAck+=1;const s=this._options.maxUnacked;s>0&&t.sinceLastAck%s===0&&this.requestAck(),this._persist()}onInbound(e){if(Te(e.name))this.onInboundStanza(e.name);else switch(e.name){case"r":this._state.enabled&&this.sendAck();break;case"a":this._handleAck(e);break;case"enabled":this._handleEnabled(e);break;case"resumed":this._handleResumed(e);break;case"failed":this._handleFailed(e)}}requestAck(){this._sendRaw(`<r xmlns="${t.SM}"/>`)}sendAck(){this._sendRaw(`<a xmlns="${t.SM}" h="${this._state.hIn}"/>`)}onInboundStanza(e){this._state.enabled&&Te(e)&&(this._state.hIn=(this._state.hIn+1)%ye,this._persist())}onGracefulClose(){this._state.enabled&&this.sendAck(),this.clearPersistedState(),this._state={boundJid:null,enableSent:!1,enabled:!1,hIn:0,hOutAcked:0,id:null,location:null,max:null,resumeSupported:!1,resumed:!1,sinceLastAck:0,unacked:[]},this._resumePending=!1,this._pendingResend=[]}onEnabled(){}onResumed(){}onFailed(e,t){}_reconcile(e){const t=this._state;let s=(e-t.hOutAcked+ye)%ye;s>t.unacked.length&&(l.error(`StreamManagement: server acked ${s} stanzas but only ${t.unacked.length} are unacknowledged (h=${e}, previous h=${t.hOutAcked})`),s=t.unacked.length),t.unacked=t.unacked.slice(s),t.hOutAcked=e}_handleAck(e){const t=this._state;if(!t.enableSent&&!t.enabled)return;const s=Ae(e.attrs.h);null!==s?(this._reconcile(s),t.sinceLastAck=0,this._persist()):l.error("StreamManagement: received <a/> without a valid h attribute")}_handleEnabled(e){const t=this._state;if(!t.enableSent)return void l.warn("StreamManagement: received <enabled/> but <enable/> was not sent; ignoring");t.enabled=!0,t.id=e.attrs.id||null;const s=parseInt(e.attrs.max,10);t.max=Number.isNaN(s)?null:s,t.location=e.attrs.location||null,t.resumeSupported=["true","1"].includes(e.attrs.resume),this._resendPending(),this._persist(),this.onEnabled()}_handleResumed(e){const t=this._state;if(!t.id)return void l.warn("StreamManagement: received <resumed/> without resumable state; ignoring");this._resumePending=!1,t.resumed=!0,t.enabled=!0,t.enableSent=!0;const s=Ae(e.attrs.h);null!==s&&this._reconcile(s),t.sinceLastAck=0;for(const e of t.unacked)this._sendRaw(Ne(e.stanza));t.unacked.length&&this.requestAck(),this._persist(),this.onResumed()}_handleFailed(e){const t=this._state;if(!t.enableSent&&!t.id)return;const s=this._resumePending;this._resumePending=!1;const n=Ae(e.attrs.h);null!==n&&this._reconcile(n),s&&(this._pendingResend=this._pendingResend.concat(t.unacked)),this._state={boundJid:null,enableSent:!1,enabled:!1,hIn:0,hOutAcked:0,id:null,location:null,max:null,resumeSupported:!1,resumed:!1,sinceLastAck:0,unacked:[]},this.clearPersistedState(),this.onFailed(e,s)}_resendPending(){const e=this._pendingResend;if(!e.length)return;this._pendingResend=[];const t=this._state;for(const s of e){const e=Ne(s.stanza),n="message"===s.name?xe(e,s.name,s.queuedAt):e;this._sendRaw(n),t.unacked.push(Object.assign(Object.assign({},s),{stanza:n})),t.sinceLastAck+=1}this.requestAck()}_persist(){this._storageKey&&this._storage.save(this._storageKey,this._state)}}class ke{constructor(){this.serverSupported=!1,this._state={boundJid:null,enableSent:!1,enabled:!1,hIn:0,hOutAcked:0,id:null,location:null,max:null,resumeSupported:!1,resumed:!1,sinceLastAck:0,unacked:[]}}get state(){return this._state}get enabled(){return this._state.enabled}get resumed(){return this._state.resumed}get boundJid(){return this._state.boundJid}get resumePending(){return!1}initialize(e){}hasResumableState(){return!1}reset(){this._state={boundJid:null,enableSent:!1,enabled:!1,hIn:0,hOutAcked:0,id:null,location:null,max:null,resumeSupported:!1,resumed:!1,sinceLastAck:0,unacked:[]},this.serverSupported=!1}sendResume(){}sendEnable(e){}isTracking(){return!1}trackOutbound(e){}onInbound(e){}onInboundStanza(e){}onGracefulClose(){}onEnabled(){}onResumed(){}onFailed(e,t){}_onEnabled(e,t,s){const n=this._state;n.enabled=!0,n.id=e,n.max=t,n.boundJid=s,this.onEnabled()}_onResumed(e,t,s){const n=this._state;n.resumed=!0,n.enabled=!0,n.boundJid=e,void 0!==t&&(n.id=t),void 0!==s&&(n.max=s),this.onResumed()}_onFailed(){this._state={boundJid:null,enableSent:!1,enabled:!1,hIn:0,hOutAcked:0,id:null,location:null,max:null,resumeSupported:!1,resumed:!1,sinceLastAck:0,unacked:[]},this.onFailed(void 0,!0)}}function Re(e){const t={};for(let s=0;s<e.attributes.length;s++){const n=e.attributes[s];t[n.name]=n.value}return{name:e.tagName,attrs:t,serialized:(new XMLSerializer).serializeToString(e)}}const Ie={},Oe={};class Me{constructor(e,s={}){if(this.service=e,this.options=s,this.setProtocol(),this._smHandlers=[],s.enableStreamManagement)if(s.worker)this.sm=new ke;else{const e=Object.assign({},s.streamManagement||{});e.storage||"undefined"==typeof sessionStorage||(e.storage=new Ce),this.sm=new Ee(e=>{this._data.push(c(e)),this._proto._send()},e)}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._scheduleIdle(),g(this.options.cookies),this.registerSASLMechanisms(this.options.mechanisms),this.iqFallbackHandler=new ie(e=>(this.send(V({type:"error",id:e.getAttribute("id")}).c("error",{type:"cancel"}).c("service-unavailable",{xmlns:t.STANZAS})),!1),null,null,["get","set"],null,null);for(const e in Ie)if(Object.prototype.hasOwnProperty.call(Ie,e)){const t=function(){};t.prototype=Ie[e],this[e]=new t,this[e].init(this)}}static addConnectionPlugin(e,t){Ie[e]=t}static addProtocol(e,t){Oe[e]=t}setProtocol(){const e=this.options.protocol||"",t=Oe[e];if(t)this._proto=new t(this);else if(this.options.worker)this._proto=new Se(this);else if(0===this.service.indexOf("ws:")||0===this.service.indexOf("wss:")||0===e.indexOf("ws"))this._proto=new be(this);else{if(e)throw new Error(`Strophe: unknown connection protocol "${e}". Valid values are "ws" and "wss"; other transports must first be registered with Connection.addProtocol().`);this._proto=new ne(this)}}reset(){var e;this._proto._reset(),null===(e=this.sm)||void 0===e||e.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}hasResumed(){var e;return!!(null===(e=this.sm)||void 0===e?void 0:e.resumed)}isStreamManagementEnabled(){var e;return!!(null===(e=this.sm)||void 0===e?void 0:e.enabled)}