ue-softphone-sdk-beta 4.0.45 → 4.0.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- var ueSoftPhone=function(){"use strict";var extendStatics=function(e,t){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},extendStatics(e,t)};function __extends$1(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var __assign=function(){return __assign=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},__assign.apply(this,arguments)};function __awaiter(e,t,n,r){return new(n||(n=Promise))(function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((r=r.apply(e,t||[])).next())})}function __generator(e,t){var n,r,i,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(a){return function(c){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,a[0]&&(s=0)),s;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,r=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){s.label=a[1];break}if(6===a[0]&&s.label<i[1]){s.label=i[1],i=a;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(a);break}i[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}"function"==typeof SuppressedError&&SuppressedError;const t$1=Object.create(null);t$1.open="0",t$1.close="1",t$1.ping="2",t$1.pong="3",t$1.message="4",t$1.upgrade="5",t$1.noop="6";const e=Object.create(null);Object.keys(t$1).forEach(t=>{e[t$1[t]]=t});const s={type:"error",data:"parser error"},n="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),i="function"==typeof ArrayBuffer,r=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,o=({type:e,data:t},s,o)=>n&&t instanceof Blob?s?o(t):a(t,o):i&&(t instanceof ArrayBuffer||r(t))?s?o(t):a(new Blob([t]),o):o(t$1[e]+(t||"")),a=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function h(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let c;const u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<64;e++)p[u.charCodeAt(e)]=e;const l="function"==typeof ArrayBuffer,d=(t,n)=>{if("string"!=typeof t)return{type:"message",data:y(t,n)};const r=t.charAt(0);return"b"===r?{type:"message",data:f(t.substring(1),n)}:e[r]?t.length>1?{type:e[r],data:t.substring(1)}:{type:e[r]}:s},f=(e,t)=>{if(l){const n=(e=>{let t,n,r,i,s,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const u=new ArrayBuffer(o),l=new Uint8Array(u);for(t=0;t<a;t+=4)n=p[e.charCodeAt(t)],r=p[e.charCodeAt(t+1)],i=p[e.charCodeAt(t+2)],s=p[e.charCodeAt(t+3)],l[c++]=n<<2|r>>4,l[c++]=(15&r)<<4|i>>2,l[c++]=(3&i)<<6|63&s;return u})(e);return y(n,t)}return{base64:!0,data:e}},y=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,g=String.fromCharCode(30);function m(){return new TransformStream({transform(e,t){!function(e,t){n&&e.data instanceof Blob?e.data.arrayBuffer().then(h).then(t):i&&(e.data instanceof ArrayBuffer||r(e.data))?t(h(e.data)):o(e,!1,e=>{c||(c=new TextEncoder),t(c.encode(e))})}(e,n=>{const r=n.length;let i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);const e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{i=new Uint8Array(9);const e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&"string"!=typeof e.data&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}})}let b;function v(e){return e.reduce((e,t)=>e+t.length,0)}function w(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let i=0;i<t;i++)n[i]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function k(e){if(e)return function(e){for(var t in k.prototype)e[t]=k.prototype[t];return e}(e)}k.prototype.on=k.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},k.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},k.prototype.off=k.prototype.removeListener=k.prototype.removeAllListeners=k.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<r.length;i++)if((n=r[i])===t||n.fn===t){r.splice(i,1);break}return 0===r.length&&delete this._callbacks["$"+e],this},k.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){r=0;for(var i=(n=n.slice(0)).length;r<i;++r)n[r].apply(this,t)}return this},k.prototype.emitReserved=k.prototype.emit,k.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},k.prototype.hasListeners=function(e){return!!this.listeners(e).length};const _="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function E(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const A=_.setTimeout,O=_.clearTimeout;function T(e,t){t.useNativeTimers?(e.setTimeoutFn=A.bind(_),e.clearTimeoutFn=O.bind(_)):(e.setTimeoutFn=_.setTimeout.bind(_),e.clearTimeoutFn=_.clearTimeout.bind(_))}class R extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}let C$1=class extends k{constructor(e){super(),this.writable=!1,T(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,n){return super.emitReserved("error",new R(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=d(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}(e);return t.length?"?"+t:""}};const B="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),N=64,S={};let x,L=0,q=0;function P(e){let t="";do{t=B[e%N]+t,e=Math.floor(e/N)}while(e>0);return t}function j(){const e=P(+new Date);return e!==x?(L=0,x=e):e+"."+P(L++)}for(;q<N;q++)S[B[q]]=q;let U=!1;try{U="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const D=U;function I(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||D))return new XMLHttpRequest}catch(e){}if(!t)try{return new(_[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function F(){}const M=null!=new I({xdomain:!1}).responseType;class V extends k{constructor(e,t){super(),T(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.data=void 0!==t.data?t.data:null,this.create()}create(){var e;const t=E(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd;const n=this.xhr=new I(t);try{n.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{n.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.opts.cookieJar)||void 0===e||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(n.timeout=this.opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(n)),4===n.readyState&&(200===n.status||1223===n.status?this.onLoad():this.setTimeoutFn(()=>{this.onError("number"==typeof n.status?n.status:0)},0))},n.send(this.data)}catch(e){return void this.setTimeoutFn(()=>{this.onError(e)},0)}"undefined"!=typeof document&&(this.index=V.requestsCount++,V.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=F,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete V.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}function H(){for(let e in V.requests)V.requests.hasOwnProperty(e)&&V.requests[e].abort()}V.requestsCount=0,V.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",H):"function"==typeof addEventListener&&addEventListener("onpagehide"in _?"pagehide":"unload",H,!1));const K="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Y=_.WebSocket||_.MozWebSocket,W="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),z$1={websocket:class extends C$1{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,n=W?{}:E(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=W?new Y(e,t,n):t?new Y(e,t):new Y(e)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;o(n,this.supportsBinary,e=>{try{this.ws.send(e)}catch(e){}r&&K(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=j()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!Y}},webtransport:class extends C$1{get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(e=>{const t=function(e,t){b||(b=new TextDecoder);const n=[];let r=0,i=-1,o=!1;return new TransformStream({transform(a,c){for(n.push(a);;){if(0===r){if(v(n)<1)break;const e=w(n,1);o=!(128&~e[0]),i=127&e[0],r=i<126?3:126===i?1:2}else if(1===r){if(v(n)<2)break;const e=w(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(2===r){if(v(n)<8)break;const e=w(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),o=t.getUint32(0);if(o>Math.pow(2,21)-1){c.enqueue(s);break}i=o*Math.pow(2,32)+t.getUint32(4),r=3}else{if(v(n)<i)break;const e=w(n,i);c.enqueue(d(o?e:b.decode(e),t)),r=0}if(0===i||i>e){c.enqueue(s);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=m();r.readable.pipeTo(e.writable),this.writer=r.writable.getWriter();const i=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this.writer.write(o).then(()=>this.onOpen())})}))}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;this.writer.write(n).then(()=>{r&&K(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}},polling:class extends C$1{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let n=location.port;n||(n=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||n!==e.port}const t=e&&e.forceBase64;this.supportsBinary=M&&!t,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const n=e.split(g),r=[];for(let e=0;e<n.length;e++){const i=d(n[e],t);if(r.push(i),"error"===i.type)break}return r})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const n=e.length,r=new Array(n);let i=0;e.forEach((e,s)=>{o(e,!1,e=>{r[s]=e,++i===n&&t(r.join(g))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=j()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new V(this.uri(),e)}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}},J=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,$=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Q(e){const t=e,n=e.indexOf("["),r=e.indexOf("]");-1!=n&&-1!=r&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let i=J.exec(e||""),s={},o=14;for(;o--;)s[$[o]]=i[o]||"";return-1!=n&&-1!=r&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=function(e,t){const n=t.replace(/\/{2,9}/g,"/").split("/");return"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1),"/"==t.slice(-1)&&n.splice(n.length-1,1),n}(0,s.path),s.queryKey=function(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}(0,s.query),s}class X extends k{constructor(e,t={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=Q(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=Q(t.host).host),T(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},n=e.split("&");for(let e=0,r=n.length;e<r;e++){let r=n[e].split("=");t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new z$1[e](n)}open(){let e;if(this.opts.rememberUpgrade&&X.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",e=>this.onClose("transport close",e))}probe(e){let t=this.createTransport(e),n=!1;X.priorWebsocketSuccess=!1;const r=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!n)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;X.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(u(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function i(){n||(n=!0,u(),t.close(),t=null)}const s=e=>{const n=new Error("probe error: "+e);n.transport=t.name,i(),this.emitReserved("upgradeError",n)};function o(){s("transport closed")}function a(){s("socket closed")}function c(e){t&&e.name!==t.name&&i()}const u=()=>{t.removeListener("open",r),t.removeListener("error",s),t.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};t.once("open",r),t.once("error",s),t.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onOpen(){if(this.readyState="open",X.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn(()=>{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let n=0;n<this.writeBuffer.length;n++){const r=this.writeBuffer[n].data;if(r&&(e+="string"==typeof(t=r)?function(e){let t=0,n=0;for(let r=0,i=e.length;r<i;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}(t):Math.ceil(1.33*(t.byteLength||t.size))),n>0&&e>this.maxPayload)return this.writeBuffer.slice(0,n);e+=2}var t;return this.writeBuffer}write(e,t,n){return this.sendPacket("message",e,t,n),this}send(e,t,n){return this.sendPacket("message",e,t,n),this}sendPacket(e,t,n,r){if("function"==typeof t&&(r=t,t=void 0),"function"==typeof n&&(r=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const i={type:e,data:t,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}onError(e){X.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let n=0;const r=e.length;for(;n<r;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}X.protocol=4;const G="function"==typeof ArrayBuffer,Z=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,tt=Object.prototype.toString,et="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===tt.call(Blob),st="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===tt.call(File);function nt(e){return G&&(e instanceof ArrayBuffer||Z(e))||et&&e instanceof Blob||st&&e instanceof File}function it(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(it(e[t]))return!0;return!1}if(nt(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return it(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&it(e[t]))return!0;return!1}function rt(e){const t=[],n=e.data,r=e;return r.data=ot(n,t),r.attachments=t.length,{packet:r,buffers:t}}function ot(e,t){if(!e)return e;if(nt(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){const n=new Array(e.length);for(let r=0;r<e.length;r++)n[r]=ot(e[r],t);return n}if("object"==typeof e&&!(e instanceof Date)){const n={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=ot(e[r],t));return n}return e}function at(e,t){return e.data=ht(e.data,t),delete e.attachments,e}function ht(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=ht(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=ht(e[n],t));return e}const ct=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var pt;function lt(e){return"[object Object]"===Object.prototype.toString.call(e)}!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(pt||(pt={}));class dt extends k{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===pt.BINARY_EVENT;n||t.type===pt.BINARY_ACK?(t.type=n?pt.EVENT:pt.ACK,this.reconstructor=new ft(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!nt(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(void 0===pt[n.type])throw new Error("unknown packet type "+n.type);if(n.type===pt.BINARY_EVENT||n.type===pt.BINARY_ACK){const r=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const i=e.substring(r,t);if(i!=Number(i)||"-"!==e.charAt(t))throw new Error("Illegal attachments");n.attachments=Number(i)}if("/"===e.charAt(t+1)){const r=t+1;for(;++t&&","!==e.charAt(t)&&t!==e.length;);n.nsp=e.substring(r,t)}else n.nsp="/";const r=e.charAt(t+1);if(""!==r&&Number(r)==r){const r=t+1;for(;++t;){const n=e.charAt(t);if(null==n||Number(n)!=n){--t;break}if(t===e.length)break}n.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(!dt.isPayloadValid(n.type,r))throw new Error("invalid payload");n.data=r}return n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case pt.CONNECT:return lt(t);case pt.DISCONNECT:return void 0===t;case pt.CONNECT_ERROR:return"string"==typeof t||lt(t);case pt.EVENT:case pt.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===ct.indexOf(t[0]));case pt.ACK:case pt.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ft{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=at(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var yt=Object.freeze({__proto__:null,protocol:5,get PacketType(){return pt},Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==pt.EVENT&&e.type!==pt.ACK||!it(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===pt.EVENT?pt.BINARY_EVENT:pt.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==pt.BINARY_EVENT&&e.type!==pt.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=rt(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},Decoder:dt});function gt(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const mt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class bt extends k{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[gt(e,"open",this.onopen.bind(this)),gt(e,"packet",this.onpacket.bind(this)),gt(e,"error",this.onerror.bind(this)),gt(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(mt.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const n={type:pt.EVENT,data:t,options:{}};if(n.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,r=t.pop();this._registerAckCallback(e,r),n.id=e}const r=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!r||!this.connected)||(this.connected?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){var n;const r=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===r)return void(this.acks[e]=t);const i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},r);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(i),t.apply(this,[null,...e])}}emitWithAck(e,...t){const n=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise((r,i)=>{t.push((e,t)=>n?e?i(e):r(t):r(e)),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>{if(n===this._queue[0])return null!==e?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...r)),n.pending=!1,this._drainQueue()}),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:pt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case pt.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case pt.EVENT:case pt.BINARY_EVENT:this.onevent(e);break;case pt.ACK:case pt.BINARY_ACK:this.onack(e);break;case pt.DISCONNECT:this.ondisconnect();break;case pt.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...r){n||(n=!0,t.packet({type:pt.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:pt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function vt(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}vt.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+n:e-n}return 0|Math.min(e,this.max)},vt.prototype.reset=function(){this.attempts=0},vt.prototype.setMin=function(e){this.ms=e},vt.prototype.setMax=function(e){this.max=e},vt.prototype.setJitter=function(e){this.jitter=e};class wt extends k{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,T(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=t.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new vt({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||yt;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new X(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=gt(t,"open",function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},s=gt(t,"error",i);if(!1!==this._timeout){const e=this._timeout,n=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(s),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(gt(e,"ping",this.onping.bind(this)),gt(e,"data",this.ondata.bind(this)),gt(e,"error",this.onerror.bind(this)),gt(e,"close",this.onclose.bind(this)),gt(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){K(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new bt(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const e of t)if(this.nsps[e].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const kt={};function _t(e,t){"object"==typeof e&&(t=e,e=void 0);const n=function(e,t="",n){let r=e;n=n||"undefined"!=typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==n?n.protocol+"//"+e:"https://"+e),r=Q(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const i=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+t,r.href=r.protocol+"://"+i+(n&&n.port===r.port?"":":"+r.port),r}(e,(t=t||{}).path||"/socket.io"),r=n.source,i=n.id,s=n.path,o=kt[i]&&s in kt[i].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new wt(r,t):(kt[i]||(kt[i]=new wt(r,t)),a=kt[i]),n.query&&!t.query&&(t.query=n.queryKey),a.socket(n.path,t)}Object.assign(_t,{Manager:wt,Socket:bt,io:_t,connect:_t});var NOT_OPEN_AUDIO={notOpenAudioMsg:"麦克风没有开启",notOpenAudioCode:403,notOpenAudioMsgEn:"Permission dismissed"},AUDIO_FORBIDDEN={forbiddenAudioMsg:"请先检查您的麦克风是否开启",forbiddenAudioCode:0,forbiddenAudioMsgEn:"Permission denied"},LIBRARY_VERSION="0.20.0",Parameters=function(){function e(e){for(var t in this.parameters={},e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}return e.prototype.setParam=function(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())},e.prototype.getParam=function(e){if(e)return this.parameters[e.toLowerCase()]},e.prototype.hasParam=function(e){return!(!e||void 0===this.parameters[e.toLowerCase()])},e.prototype.deleteParam=function(e){if(e=e.toLowerCase(),this.hasParam(e)){var t=this.parameters[e];return delete this.parameters[e],t}},e.prototype.clearParams=function(){this.parameters={}},e}(),NameAddrHeader=function(e){function t(t,n,r){var i=e.call(this,r)||this;return i.uri=t,i._displayName=n,i}return __extends$1(t,e),Object.defineProperty(t.prototype,"friendlyName",{get:function(){return this.displayName||this.uri.aor},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"displayName",{get:function(){return this._displayName},set:function(e){this._displayName=e},enumerable:!1,configurable:!0}),t.prototype.clone=function(){return new t(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))},t.prototype.toString=function(){var e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";for(var t in e+="<"+this.uri.toString()+">",this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e},t}(Parameters),URI=function(e){function t(t,n,r,i,s,o){void 0===t&&(t="sip");var a=e.call(this,s||{})||this;if(a.headers={},!r)throw new TypeError('missing or invalid "host" parameter');for(var c in o)o.hasOwnProperty(c)&&a.setHeader(c,o[c]);return a.raw={scheme:t,user:n,host:r,port:i},a.normal={scheme:t.toLowerCase(),user:n,host:r.toLowerCase(),port:i},a}return __extends$1(t,e),Object.defineProperty(t.prototype,"scheme",{get:function(){return this.normal.scheme},set:function(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"user",{get:function(){return this.normal.user},set:function(e){this.normal.user=this.raw.user=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"host",{get:function(){return this.normal.host},set:function(e){this.raw.host=e,this.normal.host=e.toLowerCase()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"aor",{get:function(){return this.normal.user+"@"+this.normal.host},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"port",{get:function(){return this.normal.port},set:function(e){this.normal.port=this.raw.port=e},enumerable:!1,configurable:!0}),t.prototype.setHeader=function(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]},t.prototype.getHeader=function(e){if(e)return this.headers[this.headerize(e)]},t.prototype.hasHeader=function(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))},t.prototype.deleteHeader=function(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){var t=this.headers[e];return delete this.headers[e],t}},t.prototype.clearHeaders=function(){this.headers={}},t.prototype.clone=function(){return new t(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))},t.prototype.toRaw=function(){return this._toString(this._raw)},t.prototype.toString=function(){return this._toString(this._normal)},Object.defineProperty(t.prototype,"_normal",{get:function(){return this.normal},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_raw",{get:function(){return this.raw},enumerable:!1,configurable:!0}),t.prototype._toString=function(e){var t=e.scheme+":";for(var n in e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port),this.parameters)this.parameters.hasOwnProperty(n)&&(t+=";"+n,null!==this.parameters[n]&&(t+="="+this.parameters[n]));var r=[];for(var i in this.headers)if(this.headers.hasOwnProperty(i))for(var s in this.headers[i])this.headers[i].hasOwnProperty(s)&&r.push(i+"="+this.headers[i][s]);return r.length>0&&(t+="?"+r.join("&")),t},t.prototype.escapeUser=function(e){var t;try{t=decodeURIComponent(e)}catch(e){throw e}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")},t.prototype.headerize=function(e){for(var t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},n=e.toLowerCase().replace(/_/g,"-").split("-"),r=n.length,i="",s=0;s<r;s++)0!==s&&(i+="-"),i+=n[s].charAt(0).toUpperCase()+n[s].substring(1);return t[i]&&(i=t[i]),i},t}(Parameters);function equivalentURI(e,t){if(e.scheme!==t.scheme)return!1;if(e.user!==t.user||e.host!==t.host||e.port!==t.port)return!1;if(!function(e,t){var n=Object.keys(e.parameters),r=Object.keys(t.parameters),i=n.filter(function(e){return r.includes(e)});return!!i.every(function(n){return e.parameters[n]===t.parameters[n]})&&(!!["user","ttl","method","transport"].every(function(n){return e.hasParam(n)&&t.hasParam(n)||!e.hasParam(n)&&!t.hasParam(n)})&&!!["maddr"].every(function(n){return e.hasParam(n)&&t.hasParam(n)||!e.hasParam(n)&&!t.hasParam(n)}))}(e,t))return!1;var n=Object.keys(e.headers),r=Object.keys(t.headers);if(0!==n.length||0!==r.length){if(n.length!==r.length)return!1;var i=n.filter(function(e){return r.includes(e)});if(i.length!==r.length)return!1;if(!i.every(function(n){return e.headers[n].length&&t.headers[n].length&&e.headers[n][0]===t.headers[n][0]}))return!1}return!0}var SyntaxError=function(e){function t(n,r,i,s){var o=e.call(this)||this;return o.message=n,o.expected=r,o.found=i,o.location=s,o.name="SyntaxError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(o,t),o}return __extends$1(t,e),t.buildMessage=function(e,t){function n(e){return e.charCodeAt(0).toString(16).toUpperCase()}function r(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(e){return"\\x0"+n(e)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(e){return"\\x"+n(e)})}function i(e){return e.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(e){return"\\x0"+n(e)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(e){return"\\x"+n(e)})}function s(e){switch(e.type){case"literal":return'"'+r(e.text)+'"';case"class":var t=e.parts.map(function(e){return Array.isArray(e)?i(e[0])+"-"+i(e[1]):i(e)});return"["+(e.inverted?"^":"")+t+"]";case"any":return"any character";case"end":return"end of input";case"other":return e.description}}return"Expected "+function(e){var t,n,r=e.map(s);if(r.sort(),r.length>0){for(t=1,n=1;t<r.length;t++)r[t-1]!==r[t]&&(r[n]=r[t],n++);r.length=n}switch(r.length){case 1:return r[0];case 2:return r[0]+" or "+r[1];default:return r.slice(0,-1).join(", ")+", or "+r[r.length-1]}}(e)+" but "+(((o=t)?'"'+r(o)+'"':"end of input")+" found.");var o},t}(Error);function peg$parse(e,t){t=void 0!==t?t:{};var n,r,i,s,o={},a={Contact:119,Name_Addr_Header:156,Record_Route:176,Request_Response:81,SIP_URI:45,Subscription_State:186,Supported:191,Require:182,Via:194,absoluteURI:84,Call_ID:118,Content_Disposition:130,Content_Length:135,Content_Type:136,CSeq:146,displayName:122,Event:149,From:151,host:52,Max_Forwards:154,Min_SE:213,Proxy_Authenticate:157,quoted_string:40,Refer_To:178,Replaces:179,Session_Expires:210,stun_URI:217,To:192,turn_URI:223,uuid:226,WWW_Authenticate:209,challenge:158,sipfrag:230,Referred_By:231},c=119,u=["\r\n",b("\r\n",!1),/^[0-9]/,S([["0","9"]],!1,!1),/^[a-zA-Z]/,S([["a","z"],["A","Z"]],!1,!1),/^[0-9a-fA-F]/,S([["0","9"],["a","f"],["A","F"]],!1,!1),/^[\0-\xFF]/,S([["\0","ÿ"]],!1,!1),/^["]/,S(['"'],!1,!1)," ",b(" ",!1),"\t",b("\t",!1),/^[a-zA-Z0-9]/,S([["a","z"],["A","Z"],["0","9"]],!1,!1),";",b(";",!1),"/",b("/",!1),"?",b("?",!1),":",b(":",!1),"@",b("@",!1),"&",b("&",!1),"=",b("=",!1),"+",b("+",!1),"$",b("$",!1),",",b(",",!1),"-",b("-",!1),"_",b("_",!1),".",b(".",!1),"!",b("!",!1),"~",b("~",!1),"*",b("*",!1),"'",b("'",!1),"(",b("(",!1),")",b(")",!1),"%",b("%",!1),function(){return" "},function(){return":"},/^[!-~]/,S([["!","~"]],!1,!1),/^[\x80-\uFFFF]/,S([["€","￿"]],!1,!1),/^[\x80-\xBF]/,S([["€","¿"]],!1,!1),/^[a-f]/,S([["a","f"]],!1,!1),"`",b("`",!1),"<",b("<",!1),">",b(">",!1),"\\",b("\\",!1),"[",b("[",!1),"]",b("]",!1),"{",b("{",!1),"}",b("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,S([["!","'"]],!1,!1),/^[*-[]/,S([["*","["]],!1,!1),/^[\]-~]/,S([["]","~"]],!1,!1),function(e){return e},/^[#-[]/,S([["#","["]],!1,!1),/^[\0-\t]/,S([["\0","\t"]],!1,!1),/^[\x0B-\f]/,S([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,S([["",""]],!1,!1),function(){(t=t||{data:{}}).data.uri=new URI(t.data.scheme,t.data.user,t.data.host,t.data.port),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port},function(){(t=t||{data:{}}).data.uri=new URI(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params,"SIP_URI"===t.startRule&&(t.data=t.data.uri)},"sips",b("sips",!0),"sip",b("sip",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(){(t=t||{data:{}}).data.user=decodeURIComponent(v().slice(0,-1))},function(){(t=t||{data:{}}).data.password=v()},function(){return(t=t||{data:{}}).data.host=v(),t.data.host},function(){return(t=t||{data:{}}).data.host_type="domain",v()},/^[a-zA-Z0-9_\-]/,S([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,S([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",v()},"::",b("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",v()},function(){return(t=t||{data:{}}).data.host_type="IPv4",v()},"25",b("25",!1),/^[0-5]/,S([["0","5"]],!1,!1),"2",b("2",!1),/^[0-4]/,S([["0","4"]],!1,!1),"1",b("1",!1),/^[1-9]/,S([["1","9"]],!1,!1),function(e){return t=t||{data:{}},e=parseInt(e.join("")),t.data.port=e,e},"transport=",b("transport=",!0),"udp",b("udp",!0),"tcp",b("tcp",!0),"sctp",b("sctp",!0),"tls",b("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",b("user=",!0),"phone",b("phone",!0),"ip",b("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",b("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",b("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",b("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",b("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,n){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),n=null===n?void 0:n[1],t.data.uri_params[e.toLowerCase()]=n},function(e,n){e=e.join("").toLowerCase(),n=n.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(n):t.data.uri_headers[e]=[n]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new URI(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params)},"//",b("//",!1),function(){(t=t||{data:{}}).data.scheme=v()},b("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=v()},"INVITE",b("INVITE",!1),"ACK",b("ACK",!1),"VXACH",b("VXACH",!1),"OPTIONS",b("OPTIONS",!1),"BYE",b("BYE",!1),"CANCEL",b("CANCEL",!1),"REGISTER",b("REGISTER",!1),"SUBSCRIBE",b("SUBSCRIBE",!1),"NOTIFY",b("NOTIFY",!1),"REFER",b("REFER",!1),"PUBLISH",b("PUBLISH",!1),function(){return(t=t||{data:{}}).data.method=v(),t.data.method},function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},function(){(t=t||{data:{}}).data.reason_phrase=v()},function(){(t=t||{data:{}}).data=v()},function(){var e,n;for(n=(t=t||{data:{}}).data.multi_header.length,e=0;e<n;e++)if(null===t.data.multi_header[e].parsed){t.data=null;break}null!==t.data?t.data=t.data.multi_header:t.data=-1},function(){var e;(t=t||{data:{}}).data.multi_header||(t.data.multi_header=[]);try{e=new NameAddrHeader(t.data.uri,t.data.displayName,t.data.params),delete t.data.uri,delete t.data.displayName,delete t.data.params}catch(t){e=null}t.data.multi_header.push({position:h,offset:y().start.offset,parsed:e})},function(e){'"'===(e=v().trim())[0]&&(e=e.substring(1,e.length-1)),(t=t||{data:{}}).data.displayName=e},"q",b("q",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.q=e},"expires",b("expires",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.expires=e},function(e){return parseInt(e.join(""))},"0",b("0",!1),function(){return parseFloat(v())},function(e,n){(t=t||{data:{}}).data.params||(t.data.params={}),n=null===n?void 0:n[1],t.data.params[e.toLowerCase()]=n},"render",b("render",!0),"session",b("session",!0),"icon",b("icon",!0),"alert",b("alert",!0),function(){"Content_Disposition"===(t=t||{data:{}}).startRule&&(t.data.type=v().toLowerCase())},"handling",b("handling",!0),"optional",b("optional",!0),"required",b("required",!0),function(e){(t=t||{data:{}}).data=parseInt(e.join(""))},function(){(t=t||{data:{}}).data=v()},"text",b("text",!0),"image",b("image",!0),"audio",b("audio",!0),"video",b("video",!0),"application",b("application",!0),"message",b("message",!0),"multipart",b("multipart",!0),"x-",b("x-",!0),function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},function(e){(t=t||{data:{}}).data=e},function(e){(t=t||{data:{}}).data.event=e.toLowerCase()},function(){var e=(t=t||{data:{}}).data.tag;t.data=new NameAddrHeader(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"tag",b("tag",!0),function(e){(t=t||{data:{}}).data.tag=e},function(e){(t=t||{data:{}}).data=parseInt(e.join(""))},function(e){(t=t||{data:{}}).data=e},function(){(t=t||{data:{}}).data=new NameAddrHeader(t.data.uri,t.data.displayName,t.data.params)},"digest",b("Digest",!0),"realm",b("realm",!0),function(e){(t=t||{data:{}}).data.realm=e},"domain",b("domain",!0),"nonce",b("nonce",!0),function(e){(t=t||{data:{}}).data.nonce=e},"opaque",b("opaque",!0),function(e){(t=t||{data:{}}).data.opaque=e},"stale",b("stale",!0),"true",b("true",!0),function(){(t=t||{data:{}}).data.stale=!0},"false",b("false",!0),function(){(t=t||{data:{}}).data.stale=!1},"algorithm",b("algorithm",!0),"md5",b("MD5",!0),"md5-sess",b("MD5-sess",!0),function(e){(t=t||{data:{}}).data.algorithm=e.toUpperCase()},"qop",b("qop",!0),"auth-int",b("auth-int",!0),"auth",b("auth",!0),function(e){(t=t||{data:{}}).data.qop||(t.data.qop=[]),t.data.qop.push(e.toLowerCase())},function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},function(){var e,n;for(n=(t=t||{data:{}}).data.multi_header.length,e=0;e<n;e++)if(null===t.data.multi_header[e].parsed){t.data=null;break}null!==t.data?t.data=t.data.multi_header:t.data=-1},function(){var e;(t=t||{data:{}}).data.multi_header||(t.data.multi_header=[]);try{e=new NameAddrHeader(t.data.uri,t.data.displayName,t.data.params),delete t.data.uri,delete t.data.displayName,delete t.data.params}catch(t){e=null}t.data.multi_header.push({position:h,offset:y().start.offset,parsed:e})},function(){(t=t||{data:{}}).data=new NameAddrHeader(t.data.uri,t.data.displayName,t.data.params)},function(){(t=t||{data:{}}).data.replaces_from_tag&&t.data.replaces_to_tag||(t.data=-1)},function(){(t=t||{data:{}}).data={call_id:t.data}},"from-tag",b("from-tag",!0),function(e){(t=t||{data:{}}).data.replaces_from_tag=e},"to-tag",b("to-tag",!0),function(e){(t=t||{data:{}}).data.replaces_to_tag=e},"early-only",b("early-only",!0),function(){(t=t||{data:{}}).data.early_only=!0},function(e,t){return t},function(e,t){return function(e,t){return[e].concat(t)}(e,t)},function(e){"Require"===(t=t||{data:{}}).startRule&&(t.data=e||[])},function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},"active",b("active",!0),"pending",b("pending",!0),"terminated",b("terminated",!0),function(){(t=t||{data:{}}).data.state=v()},"reason",b("reason",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.reason=e)},function(e){t=t||{data:{}},void 0!==e&&(t.data.expires=e)},"retry_after",b("retry_after",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.retry_after=e)},"deactivated",b("deactivated",!0),"probation",b("probation",!0),"rejected",b("rejected",!0),"timeout",b("timeout",!0),"giveup",b("giveup",!0),"noresource",b("noresource",!0),"invariant",b("invariant",!0),function(e){"Supported"===(t=t||{data:{}}).startRule&&(t.data=e||[])},function(){var e=(t=t||{data:{}}).data.tag;t.data=new NameAddrHeader(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"ttl",b("ttl",!0),function(e){(t=t||{data:{}}).data.ttl=e},"maddr",b("maddr",!0),function(e){(t=t||{data:{}}).data.maddr=e},"received",b("received",!0),function(e){(t=t||{data:{}}).data.received=e},"branch",b("branch",!0),function(e){(t=t||{data:{}}).data.branch=e},"rport",b("rport",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.rport=e.join(""))},function(e){(t=t||{data:{}}).data.protocol=e},b("UDP",!0),b("TCP",!0),b("TLS",!0),b("SCTP",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data.host=v()},function(e){(t=t||{data:{}}).data.port=parseInt(e.join(""))},function(e){return parseInt(e.join(""))},function(e){"Session_Expires"===(t=t||{data:{}}).startRule&&(t.data.deltaSeconds=e)},"refresher",b("refresher",!1),"uas",b("uas",!1),"uac",b("uac",!1),function(e){"Session_Expires"===(t=t||{data:{}}).startRule&&(t.data.refresher=e)},function(e){"Min_SE"===(t=t||{data:{}}).startRule&&(t.data=e)},"stuns",b("stuns",!0),"stun",b("stun",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(e){(t=t||{data:{}}).data.host=e},"?transport=",b("?transport=",!1),"turns",b("turns",!0),"turn",b("turn",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data=v()},"Referred-By",b("Referred-By",!1),"b",b("b",!1),"cid",b("cid",!1)],l=[E('2 ""6 7!'),E('4"""5!7#'),E('4$""5!7%'),E('4&""5!7\''),E(";'.# &;("),E('4(""5!7)'),E('4*""5!7+'),E('2,""6,7-'),E('2.""6.7/'),E('40""5!71'),E('22""6273.‰ &24""6475.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),E(";).# &;,"),E('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),E('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),E('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/&#0#*;$&&&#/\'$8":Z" )("\'#&\'#'),E(';.." &"'),E("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),E('%%$;2/&#0#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),E('4\\""5!7].# &;3'),E('4^""5!7_'),E('4`""5!7a'),E(';!.) &4b""5!7c'),E('%$;).• &2F""6F7G.‰ &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/ž#0›*;).• &2F""6F7G.‰ &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),E('%$;).‰ &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/’#0*;).‰ &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),E('2T""6T7U.ã &2V""6V7W.× &2f""6f7g.Ë &2h""6h7i.¿ &2:""6:7;.³ &2D""6D7E.§ &22""6273.› &28""6879. &2j""6j7k.ƒ &;&.} &24""6475.q &2l""6l7m.e &2n""6n7o.Y &26""6677.M &2>""6>7?.A &2p""6p7q.5 &2r""6r7s.) &;\'.# &;('),E('%$;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W.› &2f""6f7g. &2h""6h7i.ƒ &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s/Ĵ#0ı*;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W.› &2f""6f7g. &2h""6h7i.ƒ &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s&&&#/"!&,)'),E("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),E("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),E("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),E("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),E("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),E('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),E('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),E("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),E("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),E("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),E("%;//0#;&/'$8\":~\" )(\"'#&'#"),E("%;&/0#;//'$8\":~\" )(\"'#&'#"),E("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),E('4""5!7€.A &4""5!7‚.5 &4ƒ""5!7„.) &;3.# &;.'),E("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),E("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:…$!!)($'#(#'#(\"'#&'#"),E(';..G &2L""6L7M.; &4†""5!7‡./ &4ƒ""5!7„.# &;3'),E('%2j""6j7k/J#4ˆ""5!7‰.5 &4Š""5!7‹.) &4Œ""5!7/#$+")("\'#&\'#'),E("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:Ž$ )($'#(#'#(\"'#&'#"),E("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:& )(&'#(%'#($'#(#'#(\"'#&'#"),E('%3""5$7‘.) &3’""5#7“/\' 8!:”!! )'),E('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:•# )(#\'#("\'#&\'#'),E("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),E('2<""6<7=.q &2>""6>7?.e &2@""6@7A.Y &2B""6B7C.M &2D""6D7E.A &22""6273.5 &26""6677.) &24""6475'),E('%$;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E0e*;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E&/& 8!:–! )'),E('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),E("%;U.) &;\\.# &;X/& 8!:—! )"),E('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:˜# )(#\'#("\'#&\'#'),E('$4™""5!7š/,#0)*4™""5!7š&&&#'),E('%4$""5!7%/?#$4›""5!7œ0)*4›""5!7œ&/#$+")("\'#&\'#'),E('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:# )(#\'#("\'#&\'#'),E('%%;Z/³#28""6879/¤$;Z/›$28""6879/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ސ &%2ž""6ž7Ÿ/¤#;Z/›$28""6879/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.۹ &%2ž""6ž7Ÿ/Œ#;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ٺ &%2ž""6ž7Ÿ/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ؓ &%2ž""6ž7Ÿ/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.ׄ &%2ž""6ž7Ÿ/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.֍ &%2ž""6ž7Ÿ/,#;[/#$+")("\'#&\'#.ծ &%2ž""6ž7Ÿ/,#;Z/#$+")("\'#&\'#.Տ &%;Z/›#2ž""6ž7Ÿ/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ӈ &%;Z/ª#%28""6879/,#;Z/#$+")("\'#&\'#." &"/ƒ$2ž""6ž7Ÿ/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.а &%;Z/¹#%28""6879/,#;Z/#$+")("\'#&\'#." &"/’$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2ž""6ž7Ÿ/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ί &%;Z/È#%28""6879/,#;Z/#$+")("\'#&\'#." &"/¡$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2ž""6ž7Ÿ/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.˕ &%;Z/×#%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/‰$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2ž""6ž7Ÿ/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ȑ &%;Z/þ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/×$%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/‰$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2ž""6ž7Ÿ/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ħ &%;Z/Ĝ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/õ$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Î$%28""6879/,#;Z/#$+")("\'#&\'#." &"/§$%28""6879/,#;Z/#$+")("\'#&\'#." &"/€$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2ž""6ž7Ÿ/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!: ! )'),E('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),E("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),E("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),E('%2¢""6¢7£/2#4¤""5!7¥/#$+")("\'#&\'#.˜ &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#\'#("\'#&\'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4¬""5!7­/,#;!/#$+")("\'#&\'#.# &;!'),E('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:®!! )'),E('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),E(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),E('%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("\'#&\'#'),E('%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("\'#&\'#'),E('%3Á""5\'7Â/1#;/($8":Ã"! )("\'#&\'#'),E('%3Ä""5$7Å/1#;ð/($8":Æ"! )("\'#&\'#'),E('%3Ç""5&7È/1#;T/($8":É"! )("\'#&\'#'),E('%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":Ì" )("\'#&\'#'),E('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":Í""! )("\'#&\'#'),E('%$;j/&#0#*;j&&&#/"!&,)'),E('%$;j/&#0#*;j&&&#/"!&,)'),E(";k.) &;+.# &;-"),E('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),E('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),E('%;n/A#2>""6>7?/2$;o/)$8#:Î#"" )(#\'#("\'#&\'#'),E("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),E("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),E('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),E(";‘.# &;r"),E("%;/G#;'/>$;s/5$;'/,$;„/#$+%)(%'#($'#(#'#(\"'#&'#"),E(";M.# &;t"),E("%;/E#28\"\"6879/6$;u.# &;x/'$8#:Ï# )(#'#(\"'#&'#"),E('%;v.# &;w/J#%26""6677/,#;ƒ/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),E('%2Ð""6Ð7Ñ/:#;€/1$;w." &"/#$+#)(#\'#("\'#&\'#'),E('%24""6475/,#;{/#$+")("\'#&\'#'),E("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),E(";*.) &;+.# &;-"),E(';+. &;-.‰ &22""6273.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),E('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),E('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),E("$;~0#*;~&"),E(';+.w &;-.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),E('%%;"/‡#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:Ò! )'),E(";.# &;‚"),E('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),E('$;+.ƒ &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A/Œ#0‰*;+.ƒ &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A&&&#'),E("$;y0#*;y&"),E('%3’""5#7Ó/q#24""6475/b$$;!/&#0#*;!&&&#/L$2J""6J7K/=$$;!/&#0#*;!&&&#/\'$8%:Ô% )(%\'#($\'#(#\'#("\'#&\'#'),E('2Õ""6Õ7Ö'),E('2×""6×7Ø'),E('2Ù""6Ù7Ú'),E('2Û""6Û7Ü'),E('2Ý""6Ý7Þ'),E('2ß""6ß7à'),E('2á""6á7â'),E('2ã""6ã7ä'),E('2å""6å7æ'),E('2ç""6ç7è'),E('2é""6é7ê'),E("%;….Y &;†.S &;ˆ.M &;‰.G &;Š.A &;‹.; &;Œ.5 &;./ &;.) &;Ž.# &;6/& 8!:ë! )"),E("%;„/G#;'/>$;’/5$;'/,$;”/#$+%)(%'#($'#(#'#(\"'#&'#"),E("%;“/' 8!:ì!! )"),E("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),E("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),E("%;¶/Y#$%;A/,#;¶/#$+\")(\"'#&'#06*%;A/,#;¶/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":î" )("\'#&\'#'),E("%;:.c &%;˜/Y#$%;A/,#;˜/#$+\")(\"'#&'#06*%;A/,#;˜/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:ï! )"),E("%;L.# &;™/]#$%;B/,#;›/#$+\")(\"'#&'#06*%;B/,#;›/#$+\")(\"'#&'#&/'$8\":ð\" )(\"'#&'#"),E("%;š.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),E("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:ñ!! )"),E(";œ.) &;.# &; "),E("%3ò\"\"5!7ó/:#;</1$;Ÿ/($8#:ô#! )(#'#(\"'#&'#"),E("%3õ\"\"5'7ö/:#;</1$;ž/($8#:÷#! )(#'#(\"'#&'#"),E("%$;!/&#0#*;!&&&#/' 8!:ø!! )"),E('%2ù""6ù7ú/o#%2J""6J7K/M#;!." &"/?$;!." &"/1$;!." &"/#$+$)($\'#(#\'#("\'#&\'#." &"/\'$8":û" )("\'#&\'#'),E('%;6/J#%;</,#;¡/#$+")("\'#&\'#." &"/)$8":ü""! )("\'#&\'#'),E(";6.) &;T.# &;H"),E("%;£/Y#$%;B/,#;¤/#$+\")(\"'#&'#06*%;B/,#;¤/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E('%3ý""5&7þ.G &3ÿ""5\'7Ā.; &3ā""5$7Ă./ &3ă""5%7Ą.# &;6/& 8!:ą! )'),E(";¥.# &; "),E('%3Ć""5(7ć/M#;</D$3Ĉ""5(7ĉ./ &3Ċ""5(7ċ.# &;6/#$+#)(#\'#("\'#&\'#'),E("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%$;!/&#0#*;!&&&#/' 8!:Č!! )"),E("%;©/& 8!:č! )"),E("%;ª/k#;;/b$;¯/Y$$%;B/,#;°/#$+\")(\"'#&'#06*%;B/,#;°/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),E(";«.# &;¬"),E('3Ď""5$7ď.S &3Đ""5%7đ.G &3Ē""5%7ē.; &3Ĕ""5%7ĕ./ &3Ė""5+7ė.# &;­'),E('3Ę""5\'7ę./ &3Ě""5)7ě.# &;­'),E(";6.# &;®"),E('%3Ĝ""5"7ĝ/,#;6/#$+")("\'#&\'#'),E(";­.# &;6"),E("%;6/5#;</,$;±/#$+#)(#'#(\"'#&'#"),E(";6.# &;H"),E("%;³/5#;./,$;/#$+#)(#'#(\"'#&'#"),E("%$;!/&#0#*;!&&&#/' 8!:Ğ!! )"),E("%;ž/' 8!:ğ!! )"),E('%;¶/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ġ"!!)("\'#&\'#'),E('%%;7/e#$%2J""6J7K/,#;7/#$+")("\'#&\'#0<*%2J""6J7K/,#;7/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),E("%;L.# &;™/]#$%;B/,#;¸/#$+\")(\"'#&'#06*%;B/,#;¸/#$+\")(\"'#&'#&/'$8\":ġ\" )(\"'#&'#"),E(";¹.# &; "),E("%3Ģ\"\"5#7ģ/:#;</1$;6/($8#:Ĥ#! )(#'#(\"'#&'#"),E("%$;!/&#0#*;!&&&#/' 8!:ĥ!! )"),E("%;ž/' 8!:Ħ!! )"),E("%$;š0#*;š&/x#;@/o$;M/f$;?/]$$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8%:ħ% )(%'#($'#(#'#(\"'#&'#"),E(";¾"),E("%3Ĩ\"\"5&7ĩ/k#;./b$;Á/Y$$%;A/,#;Á/#$+\")(\"'#&'#06*%;A/,#;Á/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#.# &;¿"),E("%;6/k#;./b$;À/Y$$%;A/,#;À/#$+\")(\"'#&'#06*%;A/,#;À/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),E("%;6/;#;</2$;6.# &;H/#$+#)(#'#(\"'#&'#"),E(";Â.G &;Ä.A &;Æ.; &;È.5 &;É./ &;Ê.) &;Ë.# &;À"),E("%3Ī\"\"5%7ī/5#;</,$;Ã/#$+#)(#'#(\"'#&'#"),E("%;I/' 8!:Ĭ!! )"),E("%3ĭ\"\"5&7Į/—#;</Ž$;D/…$;Å/|$$%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#0C*%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#&/,$;E/#$+&)(&'#(%'#($'#(#'#(\"'#&'#"),E(";t.# &;w"),E("%3į\"\"5%7İ/5#;</,$;Ç/#$+#)(#'#(\"'#&'#"),E("%;I/' 8!:ı!! )"),E("%3IJ\"\"5&7ij/:#;</1$;I/($8#:Ĵ#! )(#'#(\"'#&'#"),E('%3ĵ""5%7Ķ/]#;</T$%3ķ""5$7ĸ/& 8!:Ĺ! ).4 &%3ĺ""5%7Ļ/& 8!:ļ! )/#$+#)(#\'#("\'#&\'#'),E('%3Ľ""5)7ľ/R#;</I$3Ŀ""5#7ŀ./ &3Ł""5(7ł.# &;6/($8#:Ń#! )(#\'#("\'#&\'#'),E('%3ń""5#7Ņ/“#;</Š$;D/$%;Ì/e#$%2D""6D7E/,#;Ì/#$+")("\'#&\'#0<*%2D""6D7E/,#;Ì/#$+")("\'#&\'#&/#$+")("\'#&\'#/,$;E/#$+%)(%\'#($\'#(#\'#("\'#&\'#'),E('%3ņ""5(7Ň./ &3ň""5$7ʼn.# &;6/\' 8!:Ŋ!! )'),E("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%;Ï/G#;./>$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),E("%$;!/&#0#*;!&&&#/' 8!:ŋ!! )"),E("%;Ñ/]#$%;A/,#;Ñ/#$+\")(\"'#&'#06*%;A/,#;Ñ/#$+\")(\"'#&'#&/'$8\":Ō\" )(\"'#&'#"),E("%;™/]#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8\":ō\" )(\"'#&'#"),E('%;L.O &;™.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/\'$8":Ŏ" )("\'#&\'#'),E("%;Ô/]#$%;B/,#;Õ/#$+\")(\"'#&'#06*%;B/,#;Õ/#$+\")(\"'#&'#&/'$8\":ŏ\" )(\"'#&'#"),E("%;–/& 8!:Ő! )"),E('%3ő""5(7Œ/:#;</1$;6/($8#:œ#! )(#\'#("\'#&\'#.g &%3Ŕ""5&7ŕ/:#;</1$;6/($8#:Ŗ#! )(#\'#("\'#&\'#.: &%3ŗ""5*7Ř/& 8!:ř! ).# &; '),E('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:Ŝ!! )'),E("%;Ø/Y#$%;A/,#;Ø/#$+\")(\"'#&'#06*%;A/,#;Ø/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%;™/Y#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%$;!/&#0#*;!&&&#/' 8!:ŝ!! )"),E("%;Û/Y#$%;B/,#;Ü/#$+\")(\"'#&'#06*%;B/,#;Ü/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E('%3Ş""5&7ş.; &3Š""5\'7š./ &3Ţ""5*7ţ.# &;6/& 8!:Ť! )'),E("%3ť\"\"5&7Ŧ/:#;</1$;Ý/($8#:ŧ#! )(#'#(\"'#&'#.} &%3õ\"\"5'7ö/:#;</1$;ž/($8#:Ũ#! )(#'#(\"'#&'#.P &%3ũ\"\"5+7Ū/:#;</1$;ž/($8#:ū#! )(#'#(\"'#&'#.# &; "),E('3Ŭ""5+7ŭ.k &3Ů""5)7ů._ &3Ű""5(7ű.S &3Ų""5\'7ų.G &3Ŵ""5&7ŵ.; &3Ŷ""5*7ŷ./ &3Ÿ""5)7Ź.# &;6'),E(';1." &"'),E('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:ź!! )'),E("%;L.# &;™/]#$%;B/,#;á/#$+\")(\"'#&'#06*%;B/,#;á/#$+\")(\"'#&'#&/'$8\":Ż\" )(\"'#&'#"),E(";¹.# &; "),E("%;ã/Y#$%;A/,#;ã/#$+\")(\"'#&'#06*%;A/,#;ã/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%;ê/k#;./b$;í/Y$$%;B/,#;ä/#$+\")(\"'#&'#06*%;B/,#;ä/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),E(";å.; &;æ.5 &;ç./ &;è.) &;é.# &; "),E("%3ż\"\"5#7Ž/:#;</1$;ð/($8#:ž#! )(#'#(\"'#&'#"),E("%3ſ\"\"5%7ƀ/:#;</1$;T/($8#:Ɓ#! )(#'#(\"'#&'#"),E("%3Ƃ\"\"5(7ƃ/F#;</=$;\\.) &;Y.# &;X/($8#:Ƅ#! )(#'#(\"'#&'#"),E("%3ƅ\"\"5&7Ɔ/:#;</1$;6/($8#:Ƈ#! )(#'#(\"'#&'#"),E("%3ƈ\"\"5%7Ɖ/A#;</8$$;!0#*;!&/($8#:Ɗ#! )(#'#(\"'#&'#"),E("%;ë/G#;;/>$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#(\"'#&'#"),E('%3’""5#7Ó.# &;6/\' 8!:Ƌ!! )'),E('%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/\' 8!:Ɛ!! )'),E('%;î/D#%;C/,#;ï/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),E("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),E('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:ƒ!! )'),E('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:Ɠ!! )'),E(";¾"),E('%;ž/^#$%;B/,#;ó/#$+")("\'#&\'#06*%;B/,#;ó/#$+")("\'#&\'#&/($8":Ɣ"!!)("\'#&\'#'),E(";ô.# &; "),E('%2ƕ""6ƕ7Ɩ/L#;</C$2Ɨ""6Ɨ7Ƙ.) &2ƙ""6ƙ7ƚ/($8#:ƛ#! )(#\'#("\'#&\'#'),E('%;ž/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ɯ"!!)("\'#&\'#'),E("%;6/5#;0/,$;÷/#$+#)(#'#(\"'#&'#"),E("$;2.) &;4.# &;.0/*;2.) &;4.# &;.&"),E("$;%0#*;%&"),E("%;ú/;#28\"\"6879/,$;û/#$+#)(#'#(\"'#&'#"),E('%3Ɲ""5%7ƞ.) &3Ɵ""5$7Ơ/\' 8!:ơ!! )'),E('%;ü/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),E("%;\\.) &;X.# &;‚/' 8!:Ƣ!! )"),E(';".S &;!.M &2F""6F7G.A &2J""6J7K.5 &2H""6H7I.) &2N""6N7O'),E('2L""6L7M.• &2B""6B7C.‰ &2<""6<7=.} &2R""6R7S.q &2T""6T7U.e &2V""6V7W.Y &2P""6P7Q.M &2@""6@7A.A &2D""6D7E.5 &22""6273.) &2>""6>7?'),E('%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),E('%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/\' 8!:ơ!! )'),E('%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/\' 8!:Ʃ!! )'),E("%;Ą/‡#2F\"\"6F7G/x$;ă/o$2F\"\"6F7G/`$;ă/W$2F\"\"6F7G/H$;ă/?$2F\"\"6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),E("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),E("%;ă/,#;ă/#$+\")(\"'#&'#"),E("%;ă/5#;ă/,$;ă/#$+#)(#'#(\"'#&'#"),E("%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),E('%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("\'#&\'#0<*%;B/2#;ĉ.# &; /#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),E(";™.# &;L"),E("%2Ư\"\"6Ư7ư/5#;</,$;Ċ/#$+#)(#'#(\"'#&'#"),E("%;D/S#;,/J$2:\"\"6:7;/;$;,.# &;T/,$;E/#$+%)(%'#($'#(#'#(\"'#&'#")],h=0,d=0,p=[{line:1,column:1}],g=0,f=[],m=0;if(void 0!==t.startRule){if(!(t.startRule in a))throw new Error("Can't start parsing from rule \""+t.startRule+'".');c=a[t.startRule]}function v(){return e.substring(d,h)}function y(){return w(d,h)}function b(e,t){return{type:"literal",text:e,ignoreCase:t}}function S(e,t,n){return{type:"class",parts:e,inverted:t,ignoreCase:n}}function T(t){var n,r=p[t];if(r)return r;for(n=t-1;!p[n];)n--;for(r={line:(r=p[n]).line,column:r.column};n<t;)10===e.charCodeAt(n)?(r.line++,r.column=1):r.column++,n++;return p[t]=r,r}function w(e,t){var n=T(e),r=T(t);return{start:{offset:e,line:n.line,column:n.column},end:{offset:t,line:r.line,column:r.column}}}function R(e){h<g||(h>g&&(g=h,f=[]),f.push(e))}function E(e){return e.split("").map(function(e){return e.charCodeAt(0)-32})}if(t.data={},n=function t(n){for(var r,i=l[n],s=0,a=[],c=i.length,p=[],g=[];;){for(;s<c;)switch(i[s]){case 0:g.push(u[i[s+1]]),s+=2;break;case 1:g.push(void 0),s++;break;case 2:g.push(null),s++;break;case 3:g.push(o),s++;break;case 4:g.push([]),s++;break;case 5:g.push(h),s++;break;case 6:g.pop(),s++;break;case 7:h=g.pop(),s++;break;case 8:g.length-=i[s+1],s+=2;break;case 9:g.splice(-2,1),s++;break;case 10:g[g.length-2].push(g.pop()),s++;break;case 11:g.push(g.splice(g.length-i[s+1],i[s+1])),s+=2;break;case 12:g.push(e.substring(g.pop(),h)),s++;break;case 13:p.push(c),a.push(s+3+i[s+1]+i[s+2]),g[g.length-1]?(c=s+3+i[s+1],s+=3):(c=s+3+i[s+1]+i[s+2],s+=3+i[s+1]);break;case 14:p.push(c),a.push(s+3+i[s+1]+i[s+2]),g[g.length-1]===o?(c=s+3+i[s+1],s+=3):(c=s+3+i[s+1]+i[s+2],s+=3+i[s+1]);break;case 15:p.push(c),a.push(s+3+i[s+1]+i[s+2]),g[g.length-1]!==o?(c=s+3+i[s+1],s+=3):(c=s+3+i[s+1]+i[s+2],s+=3+i[s+1]);break;case 16:g[g.length-1]!==o?(p.push(c),a.push(s),c=s+2+i[s+1],s+=2):s+=2+i[s+1];break;case 17:p.push(c),a.push(s+3+i[s+1]+i[s+2]),e.length>h?(c=s+3+i[s+1],s+=3):(c=s+3+i[s+1]+i[s+2],s+=3+i[s+1]);break;case 18:p.push(c),a.push(s+4+i[s+2]+i[s+3]),e.substr(h,u[i[s+1]].length)===u[i[s+1]]?(c=s+4+i[s+2],s+=4):(c=s+4+i[s+2]+i[s+3],s+=4+i[s+2]);break;case 19:p.push(c),a.push(s+4+i[s+2]+i[s+3]),e.substr(h,u[i[s+1]].length).toLowerCase()===u[i[s+1]]?(c=s+4+i[s+2],s+=4):(c=s+4+i[s+2]+i[s+3],s+=4+i[s+2]);break;case 20:p.push(c),a.push(s+4+i[s+2]+i[s+3]),u[i[s+1]].test(e.charAt(h))?(c=s+4+i[s+2],s+=4):(c=s+4+i[s+2]+i[s+3],s+=4+i[s+2]);break;case 21:g.push(e.substr(h,i[s+1])),h+=i[s+1],s+=2;break;case 22:g.push(u[i[s+1]]),h+=u[i[s+1]].length,s+=2;break;case 23:g.push(o),0===m&&R(u[i[s+1]]),s+=2;break;case 24:d=g[g.length-1-i[s+1]],s+=2;break;case 25:d=h,s++;break;case 26:r=i.slice(s+4,s+4+i[s+3]).map(function(e){return g[g.length-1-e]}),g.splice(g.length-i[s+2],i[s+2],u[i[s+1]].apply(null,r)),s+=4+i[s+3];break;case 27:g.push(t(i[s+1])),s+=2;break;case 28:m++,s++;break;case 29:m--,s++;break;default:throw new Error("Invalid opcode: "+i[s]+".")}if(!(p.length>0))break;c=p.pop(),s=a.pop()}return g[0]}(c),n!==o&&h===e.length)return n;throw n!==o&&h<e.length&&R({type:"end"}),r=f,i=g<e.length?e.charAt(g):null,s=g<e.length?w(g,g+1):w(g,g),new SyntaxError(SyntaxError.buildMessage(r,i),r,i,s)}var parse=peg$parse,Grammar,C;!function(e){e.parse=function(e,t){var n={startRule:t};try{parse(e,n)}catch(e){n.data=-1}return n.data},e.nameAddrHeaderParse=function(t){var n=e.parse(t,"Name_Addr_Header");return-1!==n?n:void 0},e.URIParse=function(t){var n=e.parse(t,"SIP_URI");return-1!==n?n:void 0}}(Grammar||(Grammar={})),function(e){e.ACK="ACK",e.BYE="BYE",e.CANCEL="CANCEL",e.INFO="INFO",e.INVITE="INVITE",e.MESSAGE="MESSAGE",e.NOTIFY="NOTIFY",e.OPTIONS="OPTIONS",e.REGISTER="REGISTER",e.UPDATE="UPDATE",e.SUBSCRIBE="SUBSCRIBE",e.PUBLISH="PUBLISH",e.REFER="REFER",e.PRACK="PRACK"}(C||(C={}));var REASON_PHRASE={100:"Trying",180:"Ringing",181:"Call Is Being Forwarded",182:"Queued",183:"Session Progress",199:"Early Dialog Terminated",200:"OK",202:"Accepted",204:"No Notification",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",305:"Use Proxy",380:"Alternative Service",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",410:"Gone",412:"Conditional Request Failed",413:"Request Entity Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Unsupported URI Scheme",417:"Unknown Resource-Priority",420:"Bad Extension",421:"Extension Required",422:"Session Interval Too Small",423:"Interval Too Brief",428:"Use Identity Header",429:"Provide Referrer Identity",430:"Flow Failed",433:"Anonymity Disallowed",436:"Bad Identity-Info",437:"Unsupported Certificate",438:"Invalid Identity Header",439:"First Hop Lacks Outbound Support",440:"Max-Breadth Exceeded",469:"Bad Info Package",470:"Consent Needed",478:"Unresolvable Destination",480:"Temporarily Unavailable",481:"Call/Transaction Does Not Exist",482:"Loop Detected",483:"Too Many Hops",484:"Address Incomplete",485:"Ambiguous",486:"Busy Here",487:"Request Terminated",488:"Not Acceptable Here",489:"Bad Event",491:"Request Pending",493:"Undecipherable",494:"Security Agreement Required",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Server Time-out",505:"Version Not Supported",513:"Message Too Large",580:"Precondition Failure",600:"Busy Everywhere",603:"Decline",604:"Does Not Exist Anywhere",606:"Not Acceptable"};function createRandomToken(e,t){void 0===t&&(t=32);for(var n="",r=0;r<e;r++){n+=Math.floor(Math.random()*t).toString(t)}return n}function getReasonPhrase(e){return REASON_PHRASE[e]||""}function newTag(){return createRandomToken(10)}function headerize(e){for(var t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},n=e.toLowerCase().replace(/_/g,"-").split("-"),r=n.length,i="",s=0;s<r;s++)0!==s&&(i+="-"),i+=n[s].charAt(0).toUpperCase()+n[s].substring(1);return t[i]&&(i=t[i]),i}function utf8Length(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length}var IncomingMessage=function(){function e(){this.headers={}}return e.prototype.addHeader=function(e,t){var n={raw:t};e=headerize(e),this.headers[e]?this.headers[e].push(n):this.headers[e]=[n]},e.prototype.getHeader=function(e){var t=this.headers[headerize(e)];if(t)return t[0]?t[0].raw:void 0},e.prototype.getHeaders=function(e){var t=this.headers[headerize(e)],n=[];if(!t)return[];for(var r=0,i=t;r<i.length;r++){var s=i[r];n.push(s.raw)}return n},e.prototype.hasHeader=function(e){return!!this.headers[headerize(e)]},e.prototype.parseHeader=function(e,t){if(void 0===t&&(t=0),e=headerize(e),this.headers[e]&&!(t>=this.headers[e].length)){var n=this.headers[e][t],r=n.raw;if(n.parsed)return n.parsed;var i=Grammar.parse(r,e.replace(/-/g,"_"));return-1===i?void this.headers[e].splice(t,1):(n.parsed=i,i)}},e.prototype.s=function(e,t){return void 0===t&&(t=0),this.parseHeader(e,t)},e.prototype.setHeader=function(e,t){this.headers[headerize(e)]=[{raw:t}]},e.prototype.toString=function(){return this.data},e}(),IncomingRequestMessage=function(e){function t(){return e.call(this)||this}return __extends$1(t,e),t}(IncomingMessage),IncomingResponseMessage=function(e){function t(){return e.call(this)||this}return __extends$1(t,e),t}(IncomingMessage),OutgoingRequestMessage=function(){function e(t,n,r,i,s,o,a){this.headers={},this.extraHeaders=[],this.options=e.getDefaultOptions(),s&&(this.options=__assign(__assign({},this.options),s),this.options.optionTags&&this.options.optionTags.length&&(this.options.optionTags=this.options.optionTags.slice()),this.options.routeSet&&this.options.routeSet.length&&(this.options.routeSet=this.options.routeSet.slice())),o&&o.length&&(this.extraHeaders=o.slice()),a&&(this.body={body:a.content,contentType:a.contentType}),this.method=t,this.ruri=n.clone(),this.fromURI=r.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:newTag(),this.from=e.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=i.clone(),this.toTag=this.options.toTag,this.to=e.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+createRandomToken(15),this.cseq=this.options.cseq,this.setHeader("route",this.options.routeSet),this.setHeader("via",""),this.setHeader("to",this.to.toString()),this.setHeader("from",this.from.toString()),this.setHeader("cseq",this.cseq+" "+this.method),this.setHeader("call-id",this.callId),this.setHeader("max-forwards","70")}return e.getDefaultOptions=function(){return{callId:"",callIdPrefix:"",cseq:1,toDisplayName:"",toTag:"",fromDisplayName:"",fromTag:"",forceRport:!1,hackViaTcp:!1,optionTags:["outbound"],routeSet:[],userAgentString:"sip.js",viaHost:""}},e.makeNameAddrHeader=function(e,t,n){var r={};return n&&(r.tag=n),new NameAddrHeader(e,t,r)},e.prototype.getHeader=function(e){var t=this.headers[headerize(e)];if(t){if(t[0])return t[0]}else for(var n=new RegExp("^\\s*"+e+"\\s*:","i"),r=0,i=this.extraHeaders;r<i.length;r++){var s=i[r];if(n.test(s))return s.substring(s.indexOf(":")+1).trim()}},e.prototype.getHeaders=function(e){var t=[],n=this.headers[headerize(e)];if(n)for(var r=0,i=n;r<i.length;r++){var s=i[r];t.push(s)}else for(var o=new RegExp("^\\s*"+e+"\\s*:","i"),a=0,c=this.extraHeaders;a<c.length;a++){var u=c[a];o.test(u)&&t.push(u.substring(u.indexOf(":")+1).trim())}return t},e.prototype.hasHeader=function(e){if(this.headers[headerize(e)])return!0;for(var t=new RegExp("^\\s*"+e+"\\s*:","i"),n=0,r=this.extraHeaders;n<r.length;n++){var i=r[n];if(t.test(i))return!0}return!1},e.prototype.setHeader=function(e,t){this.headers[headerize(e)]=t instanceof Array?t:[t]},e.prototype.setViaHeader=function(e,t){this.options.hackViaTcp&&(t="TCP");var n="SIP/2.0/"+t;n+=" "+this.options.viaHost+";branch="+e,this.options.forceRport&&(n+=";rport"),this.setHeader("via",n),this.branch=e},e.prototype.toString=function(){var e="";for(var t in e+=this.method+" "+this.ruri.toRaw()+" SIP/2.0\r\n",this.headers)if(this.headers[t])for(var n=0,r=this.headers[t];n<r.length;n++){e+=t+": "+r[n]+"\r\n"}for(var i=0,s=this.extraHeaders;i<s.length;i++){e+=(t=s[i]).trim()+"\r\n"}return e+="Supported: "+this.options.optionTags.join(", ")+"\r\n",e+="User-Agent: "+this.options.userAgentString+"\r\n",this.body?"string"==typeof this.body?(e+="Content-Length: "+utf8Length(this.body)+"\r\n\r\n",e+=this.body):this.body.body&&this.body.contentType?(e+="Content-Type: "+this.body.contentType+"\r\n",e+="Content-Length: "+utf8Length(this.body.body)+"\r\n\r\n",e+=this.body.body):e+="Content-Length: 0\r\n\r\n":e+="Content-Length: 0\r\n\r\n",e},e}();function contentTypeToContentDisposition(e){return"application/sdp"===e?"session":"render"}function fromBodyLegacy(e){var t="string"==typeof e?e:e.body,n="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:contentTypeToContentDisposition(n),contentType:n,content:t}}function isBody(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function getBody(e){var t,n,r,i;e instanceof IncomingRequestMessage&&(e.body&&(t=(i=e.parseHeader("Content-Disposition"))?i.type:void 0,n=e.parseHeader("Content-Type"),r=e.body));e instanceof IncomingResponseMessage&&(e.body&&(t=(i=e.parseHeader("Content-Disposition"))?i.type:void 0,n=e.parseHeader("Content-Type"),r=e.body));if(e instanceof OutgoingRequestMessage&&e.body)if(t=e.getHeader("Content-Disposition"),n=e.getHeader("Content-Type"),"string"==typeof e.body){if(!n)throw new Error("Header content type header does not equal body content type.");r=e.body}else{if(n&&n!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");n=e.body.contentType,r=e.body.body}if(isBody(e)&&(t=e.contentDisposition,n=e.contentType,r=e.content),r){if(n&&!t&&(t=contentTypeToContentDisposition(n)),!t)throw new Error("Content disposition undefined.");if(!n)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:n,content:r}}}var Md5=function(){function e(){this._dataLength=0,this._bufferLength=0,this._state=new Int32Array(4),this._buffer=new ArrayBuffer(68),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}return e.hashStr=function(e,t){return void 0===t&&(t=!1),this.onePassHasher.start().appendStr(e).end(t)},e.hashAsciiStr=function(e,t){return void 0===t&&(t=!1),this.onePassHasher.start().appendAsciiStr(e).end(t)},e._hex=function(t){var n,r,i,s,o=e.hexChars,a=e.hexOut;for(s=0;s<4;s+=1)for(r=8*s,n=t[s],i=0;i<8;i+=2)a[r+1+i]=o.charAt(15&n),n>>>=4,a[r+0+i]=o.charAt(15&n),n>>>=4;return a.join("")},e._md5cycle=function(e,t){var n=e[0],r=e[1],i=e[2],s=e[3];r=((r+=((i=((i+=((s=((s+=((n=((n+=(r&i|~r&s)+t[0]-680876936|0)<<7|n>>>25)+r|0)&r|~n&i)+t[1]-389564586|0)<<12|s>>>20)+n|0)&n|~s&r)+t[2]+606105819|0)<<17|i>>>15)+s|0)&s|~i&n)+t[3]-1044525330|0)<<22|r>>>10)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r&i|~r&s)+t[4]-176418897|0)<<7|n>>>25)+r|0)&r|~n&i)+t[5]+1200080426|0)<<12|s>>>20)+n|0)&n|~s&r)+t[6]-1473231341|0)<<17|i>>>15)+s|0)&s|~i&n)+t[7]-45705983|0)<<22|r>>>10)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r&i|~r&s)+t[8]+1770035416|0)<<7|n>>>25)+r|0)&r|~n&i)+t[9]-1958414417|0)<<12|s>>>20)+n|0)&n|~s&r)+t[10]-42063|0)<<17|i>>>15)+s|0)&s|~i&n)+t[11]-1990404162|0)<<22|r>>>10)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r&i|~r&s)+t[12]+1804603682|0)<<7|n>>>25)+r|0)&r|~n&i)+t[13]-40341101|0)<<12|s>>>20)+n|0)&n|~s&r)+t[14]-1502002290|0)<<17|i>>>15)+s|0)&s|~i&n)+t[15]+1236535329|0)<<22|r>>>10)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r&s|i&~s)+t[1]-165796510|0)<<5|n>>>27)+r|0)&i|r&~i)+t[6]-1069501632|0)<<9|s>>>23)+n|0)&r|n&~r)+t[11]+643717713|0)<<14|i>>>18)+s|0)&n|s&~n)+t[0]-373897302|0)<<20|r>>>12)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r&s|i&~s)+t[5]-701558691|0)<<5|n>>>27)+r|0)&i|r&~i)+t[10]+38016083|0)<<9|s>>>23)+n|0)&r|n&~r)+t[15]-660478335|0)<<14|i>>>18)+s|0)&n|s&~n)+t[4]-405537848|0)<<20|r>>>12)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r&s|i&~s)+t[9]+568446438|0)<<5|n>>>27)+r|0)&i|r&~i)+t[14]-1019803690|0)<<9|s>>>23)+n|0)&r|n&~r)+t[3]-187363961|0)<<14|i>>>18)+s|0)&n|s&~n)+t[8]+1163531501|0)<<20|r>>>12)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r&s|i&~s)+t[13]-1444681467|0)<<5|n>>>27)+r|0)&i|r&~i)+t[2]-51403784|0)<<9|s>>>23)+n|0)&r|n&~r)+t[7]+1735328473|0)<<14|i>>>18)+s|0)&n|s&~n)+t[12]-1926607734|0)<<20|r>>>12)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r^i^s)+t[5]-378558|0)<<4|n>>>28)+r|0)^r^i)+t[8]-2022574463|0)<<11|s>>>21)+n|0)^n^r)+t[11]+1839030562|0)<<16|i>>>16)+s|0)^s^n)+t[14]-35309556|0)<<23|r>>>9)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r^i^s)+t[1]-1530992060|0)<<4|n>>>28)+r|0)^r^i)+t[4]+1272893353|0)<<11|s>>>21)+n|0)^n^r)+t[7]-155497632|0)<<16|i>>>16)+s|0)^s^n)+t[10]-1094730640|0)<<23|r>>>9)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r^i^s)+t[13]+681279174|0)<<4|n>>>28)+r|0)^r^i)+t[0]-358537222|0)<<11|s>>>21)+n|0)^n^r)+t[3]-722521979|0)<<16|i>>>16)+s|0)^s^n)+t[6]+76029189|0)<<23|r>>>9)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r^i^s)+t[9]-640364487|0)<<4|n>>>28)+r|0)^r^i)+t[12]-421815835|0)<<11|s>>>21)+n|0)^n^r)+t[15]+530742520|0)<<16|i>>>16)+s|0)^s^n)+t[2]-995338651|0)<<23|r>>>9)+i|0,r=((r+=((s=((s+=(r^((n=((n+=(i^(r|~s))+t[0]-198630844|0)<<6|n>>>26)+r|0)|~i))+t[7]+1126891415|0)<<10|s>>>22)+n|0)^((i=((i+=(n^(s|~r))+t[14]-1416354905|0)<<15|i>>>17)+s|0)|~n))+t[5]-57434055|0)<<21|r>>>11)+i|0,r=((r+=((s=((s+=(r^((n=((n+=(i^(r|~s))+t[12]+1700485571|0)<<6|n>>>26)+r|0)|~i))+t[3]-1894986606|0)<<10|s>>>22)+n|0)^((i=((i+=(n^(s|~r))+t[10]-1051523|0)<<15|i>>>17)+s|0)|~n))+t[1]-2054922799|0)<<21|r>>>11)+i|0,r=((r+=((s=((s+=(r^((n=((n+=(i^(r|~s))+t[8]+1873313359|0)<<6|n>>>26)+r|0)|~i))+t[15]-30611744|0)<<10|s>>>22)+n|0)^((i=((i+=(n^(s|~r))+t[6]-1560198380|0)<<15|i>>>17)+s|0)|~n))+t[13]+1309151649|0)<<21|r>>>11)+i|0,r=((r+=((s=((s+=(r^((n=((n+=(i^(r|~s))+t[4]-145523070|0)<<6|n>>>26)+r|0)|~i))+t[11]-1120210379|0)<<10|s>>>22)+n|0)^((i=((i+=(n^(s|~r))+t[2]+718787259|0)<<15|i>>>17)+s|0)|~n))+t[9]-343485551|0)<<21|r>>>11)+i|0,e[0]=n+e[0]|0,e[1]=r+e[1]|0,e[2]=i+e[2]|0,e[3]=s+e[3]|0},e.prototype.start=function(){return this._dataLength=0,this._bufferLength=0,this._state.set(e.stateIdentity),this},e.prototype.appendStr=function(t){var n,r,i=this._buffer8,s=this._buffer32,o=this._bufferLength;for(r=0;r<t.length;r+=1){if((n=t.charCodeAt(r))<128)i[o++]=n;else if(n<2048)i[o++]=(n>>>6)+192,i[o++]=63&n|128;else if(n<55296||n>56319)i[o++]=(n>>>12)+224,i[o++]=n>>>6&63|128,i[o++]=63&n|128;else{if((n=1024*(n-55296)+(t.charCodeAt(++r)-56320)+65536)>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");i[o++]=(n>>>18)+240,i[o++]=n>>>12&63|128,i[o++]=n>>>6&63|128,i[o++]=63&n|128}o>=64&&(this._dataLength+=64,e._md5cycle(this._state,s),o-=64,s[0]=s[16])}return this._bufferLength=o,this},e.prototype.appendAsciiStr=function(t){for(var n,r=this._buffer8,i=this._buffer32,s=this._bufferLength,o=0;;){for(n=Math.min(t.length-o,64-s);n--;)r[s++]=t.charCodeAt(o++);if(s<64)break;this._dataLength+=64,e._md5cycle(this._state,i),s=0}return this._bufferLength=s,this},e.prototype.appendByteArray=function(t){for(var n,r=this._buffer8,i=this._buffer32,s=this._bufferLength,o=0;;){for(n=Math.min(t.length-o,64-s);n--;)r[s++]=t[o++];if(s<64)break;this._dataLength+=64,e._md5cycle(this._state,i),s=0}return this._bufferLength=s,this},e.prototype.getState=function(){var e=this,t=e._state;return{buffer:String.fromCharCode.apply(null,e._buffer8),buflen:e._bufferLength,length:e._dataLength,state:[t[0],t[1],t[2],t[3]]}},e.prototype.setState=function(e){var t,n=e.buffer,r=e.state,i=this._state;for(this._dataLength=e.length,this._bufferLength=e.buflen,i[0]=r[0],i[1]=r[1],i[2]=r[2],i[3]=r[3],t=0;t<n.length;t+=1)this._buffer8[t]=n.charCodeAt(t)},e.prototype.end=function(t){void 0===t&&(t=!1);var n,r=this._bufferLength,i=this._buffer8,s=this._buffer32,o=1+(r>>2);if(this._dataLength+=r,i[r]=128,i[r+1]=i[r+2]=i[r+3]=0,s.set(e.buffer32Identity.subarray(o),o),r>55&&(e._md5cycle(this._state,s),s.set(e.buffer32Identity)),(n=8*this._dataLength)<=4294967295)s[14]=n;else{var a=n.toString(16).match(/(.*?)(.{0,8})$/);if(null===a)return;var c=parseInt(a[2],16),u=parseInt(a[1],16)||0;s[14]=c,s[15]=u}return e._md5cycle(this._state,s),t?this._state:e._hex(this._state)},e.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),e.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),e.hexChars="0123456789abcdef",e.hexOut=[],e.onePassHasher=new e,e}();function MD5(e){return Md5.hashStr(e)}"5d41402abc4b2a76b9719d911017c592"!==Md5.hashStr("hello")&&console.error("Md5 self test failed.");var DigestAuthentication=function(){function e(e,t,n,r){this.logger=e.getLogger("sipjs.digestauthentication"),this.username=n,this.password=r,this.ha1=t,this.nc=0,this.ncHex="00000000"}return e.prototype.authenticate=function(e,t,n){if(this.algorithm=t.algorithm,this.realm=t.realm,this.nonce=t.nonce,this.opaque=t.opaque,this.stale=t.stale,this.algorithm){if("MD5"!==this.algorithm)return this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"),!1}else this.algorithm="MD5";if(!this.realm)return this.logger.warn("challenge without Digest realm, authentication aborted"),!1;if(!this.nonce)return this.logger.warn("challenge without Digest nonce, authentication aborted"),!1;if(t.qop)if(t.qop.indexOf("auth")>-1)this.qop="auth";else{if(!(t.qop.indexOf("auth-int")>-1))return this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"),!1;this.qop="auth-int"}else this.qop=void 0;return this.method=e.method,this.uri=e.ruri,this.cnonce=createRandomToken(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(n),!0},e.prototype.toString=function(){var e=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return e.push("algorithm="+this.algorithm),e.push('username="'+this.username+'"'),e.push('realm="'+this.realm+'"'),e.push('nonce="'+this.nonce+'"'),e.push('uri="'+this.uri+'"'),e.push('response="'+this.response+'"'),this.opaque&&e.push('opaque="'+this.opaque+'"'),this.qop&&(e.push("qop="+this.qop),e.push('cnonce="'+this.cnonce+'"'),e.push("nc="+this.ncHex)),"Digest "+e.join(", ")},e.prototype.updateNcHex=function(){var e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e},e.prototype.calculateResponse=function(e){var t,n;""!==(t=this.ha1)&&void 0!==t||(t=MD5(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(n=MD5(this.method+":"+this.uri),this.response=MD5(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+n)):"auth-int"===this.qop?(n=MD5(this.method+":"+this.uri+":"+MD5(e||"")),this.response=MD5(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+n)):void 0===this.qop&&(n=MD5(this.method+":"+this.uri),this.response=MD5(t+":"+this.nonce+":"+n))},e}(),Parser;function constructOutgoingResponse(e,t){var n="\r\n";if(t.statusCode<100||t.statusCode>699)throw new TypeError("Invalid statusCode: "+t.statusCode);var r=t.reasonPhrase?t.reasonPhrase:getReasonPhrase(t.statusCode),i="SIP/2.0 "+t.statusCode+" "+r+n;t.statusCode>=100&&t.statusCode,t.statusCode;var s="From: "+e.getHeader("From")+n,o="Call-ID: "+e.callId+n,a="CSeq: "+e.cseq+" "+e.method+n,c=e.getHeaders("via").reduce(function(e,t){return e+"Via: "+t+n},""),u="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){var l=t.toTag;l||(l=newTag()),u+=";tag="+l}u+=n;var h="";t.supported&&(h="Supported: "+t.supported.join(", ")+n);var d="";t.userAgent&&(d="User-Agent: "+t.userAgent+n);var p="";return t.extraHeaders&&(p=t.extraHeaders.reduce(function(e,t){return e+t.trim()+n},"")),i+=c,i+=s,i+=u,i+=a,i+=o,i+=h,i+=d,i+=p,t.body?(i+="Content-Type: "+t.body.contentType+n,i+="Content-Length: "+utf8Length(t.body.content)+n+n,i+=t.body.content):i+="Content-Length: 0\r\n\r\n",{message:i}}!function(e){function t(e,t){var n=t,r=0,i=0;if(e.substring(n,n+2).match(/(^\r\n)/))return-2;for(;0===r;){if(-1===(i=e.indexOf("\r\n",n)))return i;!e.substring(i+2,i+4).match(/(^\r\n)/)&&e.charAt(i+2).match(/(^\s+)/)?n=i+2:r=i}return r}function n(e,t,n,r){var i,s=t.indexOf(":",n),o=t.substring(n,s).trim(),a=t.substring(s+1,r).trim();switch(o.toLowerCase()){case"via":case"v":e.addHeader("via",a),1===e.getHeaders("via").length?(i=e.parseHeader("Via"))&&(e.via=i,e.viaBranch=i.branch):i=0;break;case"from":case"f":e.setHeader("from",a),(i=e.parseHeader("from"))&&(e.from=i,e.fromTag=i.getParam("tag"));break;case"to":case"t":e.setHeader("to",a),(i=e.parseHeader("to"))&&(e.to=i,e.toTag=i.getParam("tag"));break;case"record-route":if(-1===(i=Grammar.parse(a,"Record_Route"))){i=void 0;break}if(!(i instanceof Array)){i=void 0;break}i.forEach(function(t){e.addHeader("record-route",a.substring(t.position,t.offset)),e.headers["Record-Route"][e.getHeaders("record-route").length-1].parsed=t.parsed});break;case"call-id":case"i":e.setHeader("call-id",a),(i=e.parseHeader("call-id"))&&(e.callId=a);break;case"contact":case"m":if(-1===(i=Grammar.parse(a,"Contact"))){i=void 0;break}if(!(i instanceof Array)){i=void 0;break}i.forEach(function(t){e.addHeader("contact",a.substring(t.position,t.offset)),e.headers.Contact[e.getHeaders("contact").length-1].parsed=t.parsed});break;case"content-length":case"l":e.setHeader("content-length",a),i=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",a),i=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",a),(i=e.parseHeader("cseq"))&&(e.cseq=i.value),e instanceof IncomingResponseMessage&&(e.method=i.method);break;case"max-forwards":e.setHeader("max-forwards",a),i=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",a),i=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",a),i=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",a),(i=e.parseHeader("refer-to"))&&(e.referTo=i);break;default:e.addHeader(o.toLowerCase(),a),i=0}return void 0!==i||{error:"error parsing header '"+o+"'"}}e.getHeader=t,e.parseHeader=n,e.parseMessage=function(e,r){var i=0,s=e.indexOf("\r\n");if(-1!==s){var o,a=e.substring(0,s),c=Grammar.parse(a,"Request_Response");if(-1!==c){var u;for(c.status_code?((o=new IncomingResponseMessage).statusCode=c.status_code,o.reasonPhrase=c.reason_phrase):((o=new IncomingRequestMessage).method=c.method,o.ruri=c.uri),o.data=e,i=s+2;;){if(-2===(s=t(e,i))){u=i+2;break}if(-1===s)return void r.error("malformed message");var l=n(o,e,i,s);if(l&&!0!==l)return void r.error(l.error);i=s+2}return o.hasHeader("content-length")?o.body=e.substr(u,Number(o.getHeader("content-length"))):o.body=e.substring(u),o}r.warn('error parsing first line of SIP message: "'+a+'"')}else r.warn("no CRLF found, not a SIP message, discarded")}}(Parser||(Parser={}));var Dialog=function(){function e(e,t){this.core=e,this.dialogState=t,this.core.dialogs.set(this.id,this)}return e.initialDialogStateForUserAgentClient=function(e,t){var n=t.getHeaders("record-route").reverse(),r=t.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");var i=r.uri,s=e.cseq,o=e.callId,a=e.fromTag,c=t.toTag;if(!o)throw new Error("Call id undefined.");if(!a)throw new Error("From tag undefined.");if(!c)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");var u=e.from.uri,l=e.to.uri;if(!t.statusCode)throw new Error("Incoming response status code undefined.");return{id:o+a+c,early:t.statusCode<200,callId:o,localTag:a,remoteTag:c,localSequenceNumber:s,remoteSequenceNumber:undefined,localURI:u,remoteURI:l,remoteTarget:i,routeSet:n,secure:!1}},e.initialDialogStateForUserAgentServer=function(e,t,n){void 0===n&&(n=!1);var r=e.getHeaders("record-route"),i=e.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");var s=i.uri,o=e.cseq,a=e.callId,c=t,u=e.fromTag,l=e.from.uri;return{id:a+c+u,early:n,callId:a,localTag:c,remoteTag:u,localSequenceNumber:undefined,remoteSequenceNumber:o,localURI:e.to.uri,remoteURI:l,remoteTarget:s,routeSet:r,secure:!1}},e.prototype.dispose=function(){this.core.dialogs.delete(this.id)},Object.defineProperty(e.prototype,"id",{get:function(){return this.dialogState.id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"early",{get:function(){return this.dialogState.early},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"callId",{get:function(){return this.dialogState.callId},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localTag",{get:function(){return this.dialogState.localTag},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteTag",{get:function(){return this.dialogState.remoteTag},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localSequenceNumber",{get:function(){return this.dialogState.localSequenceNumber},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteSequenceNumber",{get:function(){return this.dialogState.remoteSequenceNumber},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localURI",{get:function(){return this.dialogState.localURI},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteURI",{get:function(){return this.dialogState.remoteURI},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteTarget",{get:function(){return this.dialogState.remoteTarget},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"routeSet",{get:function(){return this.dialogState.routeSet},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"secure",{get:function(){return this.dialogState.secure},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"userAgentCore",{get:function(){return this.core},enumerable:!1,configurable:!0}),e.prototype.confirm=function(){this.dialogState.early=!1},e.prototype.receiveRequest=function(e){if(e.method!==C.ACK){if(this.remoteSequenceNumber){if(e.cseq<=this.remoteSequenceNumber)throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?");this.dialogState.remoteSequenceNumber=e.cseq}this.remoteSequenceNumber||(this.dialogState.remoteSequenceNumber=e.cseq)}},e.prototype.recomputeRouteSet=function(e){this.dialogState.routeSet=e.getHeaders("record-route").reverse()},e.prototype.createOutgoingRequestMessage=function(e,t){var n,r=this.remoteURI,i=this.remoteTag,s=this.localURI,o=this.localTag,a=this.callId;n=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;var c=this.remoteTarget,u=this.routeSet,l=t&&t.extraHeaders,h=t&&t.body;return this.userAgentCore.makeOutgoingRequestMessage(e,c,s,r,{callId:a,cseq:n,fromTag:o,toTag:i,routeSet:u},l,h)},e.prototype.incrementLocalSequenceNumber=function(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1},e.prototype.sequenceGuard=function(e){return e.method===C.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))},e}(),SessionState$1,SignalingState;!function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(SessionState$1||(SessionState$1={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(SignalingState||(SignalingState={}));var T1=500,T2=4e3,T4=5e3,Timers={T1:T1,T2:T2,T4:T4,TIMER_B:64*T1,TIMER_D:0*T1,TIMER_F:6*T1,TIMER_H:64*T1,TIMER_I:0*T4,TIMER_J:0*T1,TIMER_K:0*T4,TIMER_L:64*T1,TIMER_M:64*T1,TIMER_N:64*T1,PROVISIONAL_RESPONSE_INTERVAL:6e4},Exception=function(e){function t(t){var n=this.constructor,r=e.call(this,t)||this;return Object.setPrototypeOf(r,n.prototype),r}return __extends$1(t,e),t}(Error),TransactionStateError=function(e){function t(t){return e.call(this,t||"Transaction state error.")||this}return __extends$1(t,e),t}(Exception),TransportError=function(e){function t(t){return e.call(this,t||"Unspecified transport error.")||this}return __extends$1(t,e),t}(Exception),Transaction=function(){function e(e,t,n,r,i){this._transport=e,this._user=t,this._id=n,this._state=r,this.listeners=new Array,this.logger=t.loggerFactory.getLogger(i,n),this.logger.debug("Constructing ".concat(this.typeToString()," with id ").concat(this.id,"."))}return e.prototype.dispose=function(){this.logger.debug("Destroyed ".concat(this.typeToString()," with id ").concat(this.id,"."))},Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"kind",{get:function(){throw new Error("Invalid kind.")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transport",{get:function(){return this._transport},enumerable:!1,configurable:!0}),e.prototype.addStateChangeListener=function(e,t){var n=this,r=function(){n.removeStateChangeListener(r),e()};!0===(null==t?void 0:t.once)?this.listeners.push(r):this.listeners.push(e)},e.prototype.notifyStateChangeListeners=function(){this.listeners.slice().forEach(function(e){return e()})},e.prototype.removeStateChangeListener=function(e){this.listeners=this.listeners.filter(function(t){return t!==e})},e.prototype.logTransportError=function(e,t){this.logger.error(e.message),this.logger.error("Transport error occurred in ".concat(this.typeToString()," with id ").concat(this.id,".")),this.logger.error(t)},e.prototype.send=function(e){var t=this;return this.transport.send(e).catch(function(e){if(e instanceof TransportError)throw t.onTransportError(e),e;var n;throw n=e&&"string"==typeof e.message?new TransportError(e.message):new TransportError,t.onTransportError(n),n})},e.prototype.setState=function(e){this.logger.debug('State change to "'.concat(e,'" on ').concat(this.typeToString()," with id ").concat(this.id,".")),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.notifyStateChangeListeners()},e.prototype.typeToString=function(){return"UnknownType"},e}(),ClientTransaction=function(e){function t(n,r,i,s,o){var a=e.call(this,r,i,t.makeId(n),s,o)||this;return a._request=n,a.user=i,n.setViaHeader(a.id,r.protocol),a}return __extends$1(t,e),t.makeId=function(e){if("CANCEL"===e.method){if(!e.branch)throw new Error("Outgoing CANCEL request without a branch.");return e.branch}return"z9hG4bK"+Math.floor(1e7*Math.random())},Object.defineProperty(t.prototype,"request",{get:function(){return this._request},enumerable:!1,configurable:!0}),t.prototype.onRequestTimeout=function(){this.user.onRequestTimeout&&this.user.onRequestTimeout()},t}(Transaction),TransactionState;!function(e){e.Accepted="Accepted",e.Calling="Calling",e.Completed="Completed",e.Confirmed="Confirmed",e.Proceeding="Proceeding",e.Terminated="Terminated",e.Trying="Trying"}(TransactionState||(TransactionState={}));var InviteClientTransaction=function(e){function t(t,n,r){var i=e.call(this,t,n,r,TransactionState.Calling,"sip.transaction.ict")||this;return i.ackRetransmissionCache=new Map,i.B=setTimeout(function(){return i.timerB()},Timers.TIMER_B),i.send(t.toString()).catch(function(e){i.logTransportError(e,"Failed to send initial outgoing request.")}),i}return __extends$1(t,e),t.prototype.dispose=function(){this.B&&(clearTimeout(this.B),this.B=void 0),this.D&&(clearTimeout(this.D),this.D=void 0),this.M&&(clearTimeout(this.M),this.M=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"ict"},enumerable:!1,configurable:!0}),t.prototype.ackResponse=function(e){var t=this,n=e.toTag;if(!n)throw new Error("To tag undefined.");var r="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(r,this.transport.protocol),this.ackRetransmissionCache.set(n,e),this.send(e.toString()).catch(function(e){t.logTransportError(e,"Failed to send ACK to 2xx response.")})},t.prototype.receiveResponse=function(e){var t=this,n=e.statusCode;if(!n||n<100||n>699)throw new Error("Invalid status code ".concat(n));switch(this.state){case TransactionState.Calling:if(n>=100&&n<=199)return this.stateTransition(TransactionState.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(n>=200&&n<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(TransactionState.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(n>=300&&n<=699)return this.stateTransition(TransactionState.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case TransactionState.Proceeding:if(n>=100&&n<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(n>=200&&n<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(TransactionState.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(n>=300&&n<=699)return this.stateTransition(TransactionState.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case TransactionState.Accepted:if(n>=200&&n<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));var r=this.ackRetransmissionCache.get(e.toTag);return r?void this.send(r.toString()).catch(function(e){t.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")}):void 0}break;case TransactionState.Completed:if(n>=300&&n<=699)return void this.ack(e);break;case TransactionState.Terminated:break;default:throw new Error("Invalid state ".concat(this.state))}var i="Received unexpected ".concat(n," response while in state ").concat(this.state,".");this.logger.warn(i)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"INVITE client transaction"},t.prototype.ack=function(e){var t=this,n=this.request.ruri,r=this.request.callId,i=this.request.cseq,s=this.request.getHeader("from"),o=e.getHeader("to"),a=this.request.getHeader("via"),c=this.request.getHeader("route");if(!s)throw new Error("From undefined.");if(!o)throw new Error("To undefined.");if(!a)throw new Error("Via undefined.");var u="ACK ".concat(n," SIP/2.0\r\n");c&&(u+="Route: ".concat(c,"\r\n")),u+="Via: ".concat(a,"\r\n"),u+="To: ".concat(o,"\r\n"),u+="From: ".concat(s,"\r\n"),u+="Call-ID: ".concat(r,"\r\n"),u+="CSeq: ".concat(i," ACK\r\n"),u+="Max-Forwards: 70\r\n",u+="Content-Length: 0\r\n\r\n",this.send(u).catch(function(e){t.logTransportError(e,"Failed to send ACK to non-2xx response.")})},t.prototype.stateTransition=function(e,t){var n=this;void 0===t&&(t=!1);var r=function(){throw new Error("Invalid state transition from ".concat(n.state," to ").concat(e))};switch(e){case TransactionState.Calling:r();break;case TransactionState.Proceeding:this.state!==TransactionState.Calling&&r();break;case TransactionState.Accepted:case TransactionState.Completed:this.state!==TransactionState.Calling&&this.state!==TransactionState.Proceeding&&r();break;case TransactionState.Terminated:this.state!==TransactionState.Calling&&this.state!==TransactionState.Accepted&&this.state!==TransactionState.Completed&&(t||r());break;default:r()}this.B&&(clearTimeout(this.B),this.B=void 0),TransactionState.Proceeding,e===TransactionState.Completed&&(this.D=setTimeout(function(){return n.timerD()},Timers.TIMER_D)),e===TransactionState.Accepted&&(this.M=setTimeout(function(){return n.timerM()},Timers.TIMER_M)),e===TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timerA=function(){},t.prototype.timerB=function(){this.logger.debug("Timer B expired for INVITE client transaction ".concat(this.id,".")),this.state===TransactionState.Calling&&(this.onRequestTimeout(),this.stateTransition(TransactionState.Terminated))},t.prototype.timerD=function(){this.logger.debug("Timer D expired for INVITE client transaction ".concat(this.id,".")),this.state===TransactionState.Completed&&this.stateTransition(TransactionState.Terminated)},t.prototype.timerM=function(){this.logger.debug("Timer M expired for INVITE client transaction ".concat(this.id,".")),this.state===TransactionState.Accepted&&this.stateTransition(TransactionState.Terminated)},t}(ClientTransaction),ServerTransaction=function(e){function t(t,n,r,i,s){var o=e.call(this,n,r,t.viaBranch,i,s)||this;return o._request=t,o.user=r,o}return __extends$1(t,e),Object.defineProperty(t.prototype,"request",{get:function(){return this._request},enumerable:!1,configurable:!0}),t}(Transaction),InviteServerTransaction=function(e){function t(t,n,r){return e.call(this,t,n,r,TransactionState.Proceeding,"sip.transaction.ist")||this}return __extends$1(t,e),t.prototype.dispose=function(){this.stopProgressExtensionTimer(),this.H&&(clearTimeout(this.H),this.H=void 0),this.I&&(clearTimeout(this.I),this.I=void 0),this.L&&(clearTimeout(this.L),this.L=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"ist"},enumerable:!1,configurable:!0}),t.prototype.receiveRequest=function(e){var t=this;switch(this.state){case TransactionState.Proceeding:if(e.method===C.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(function(e){t.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case TransactionState.Accepted:if(e.method===C.INVITE)return;break;case TransactionState.Completed:if(e.method===C.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch(function(e){t.logTransportError(e,"Failed to send retransmission of final response.")})}if(e.method===C.ACK)return void this.stateTransition(TransactionState.Confirmed);break;case TransactionState.Confirmed:case TransactionState.Terminated:if(e.method===C.INVITE||e.method===C.ACK)return;break;default:throw new Error("Invalid state ".concat(this.state))}var n="INVITE server transaction received unexpected ".concat(e.method," request while in state ").concat(this.state,".");this.logger.warn(n)},t.prototype.receiveResponse=function(e,t){var n=this;if(e<100||e>699)throw new Error("Invalid status code ".concat(e));switch(this.state){case TransactionState.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch(function(e){n.logTransportError(e,"Failed to send 1xx response.")});if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(TransactionState.Accepted),void this.send(t).catch(function(e){n.logTransportError(e,"Failed to send 2xx response.")});if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(TransactionState.Completed),void this.send(t).catch(function(e){n.logTransportError(e,"Failed to send non-2xx final response.")});break;case TransactionState.Accepted:if(e>=200&&e<=299)return void this.send(t).catch(function(e){n.logTransportError(e,"Failed to send 2xx response.")});break;case TransactionState.Completed:case TransactionState.Confirmed:case TransactionState.Terminated:break;default:throw new Error("Invalid state ".concat(this.state))}var r="INVITE server transaction received unexpected ".concat(e," response from TU while in state ").concat(this.state,".");throw this.logger.error(r),new Error(r)},t.prototype.retransmitAcceptedResponse=function(){var e=this;this.state===TransactionState.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch(function(t){e.logTransportError(t,"Failed to send 2xx response.")})},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e)},t.prototype.typeToString=function(){return"INVITE server transaction"},t.prototype.stateTransition=function(e){var t=this,n=function(){throw new Error("Invalid state transition from ".concat(t.state," to ").concat(e))};switch(e){case TransactionState.Proceeding:n();break;case TransactionState.Accepted:case TransactionState.Completed:this.state!==TransactionState.Proceeding&&n();break;case TransactionState.Confirmed:this.state!==TransactionState.Completed&&n();break;case TransactionState.Terminated:this.state!==TransactionState.Accepted&&this.state!==TransactionState.Completed&&this.state!==TransactionState.Confirmed&&n();break;default:n()}this.stopProgressExtensionTimer(),e===TransactionState.Accepted&&(this.L=setTimeout(function(){return t.timerL()},Timers.TIMER_L)),e===TransactionState.Completed&&(this.H=setTimeout(function(){return t.timerH()},Timers.TIMER_H)),e===TransactionState.Confirmed&&(this.I=setTimeout(function(){return t.timerI()},Timers.TIMER_I)),e===TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.startProgressExtensionTimer=function(){var e=this;void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval(function(){if(e.logger.debug("Progress extension timer expired for INVITE server transaction ".concat(e.id,".")),!e.lastProvisionalResponse)throw new Error("Last provisional response undefined.");e.send(e.lastProvisionalResponse).catch(function(t){e.logTransportError(t,"Failed to send retransmission of provisional response.")})},Timers.PROVISIONAL_RESPONSE_INTERVAL))},t.prototype.stopProgressExtensionTimer=function(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)},t.prototype.timerG=function(){},t.prototype.timerH=function(){this.logger.debug("Timer H expired for INVITE server transaction ".concat(this.id,".")),this.state===TransactionState.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(TransactionState.Terminated))},t.prototype.timerI=function(){this.logger.debug("Timer I expired for INVITE server transaction ".concat(this.id,".")),this.stateTransition(TransactionState.Terminated)},t.prototype.timerL=function(){this.logger.debug("Timer L expired for INVITE server transaction ".concat(this.id,".")),this.state===TransactionState.Accepted&&this.stateTransition(TransactionState.Terminated)},t}(ServerTransaction),NonInviteClientTransaction=function(e){function t(t,n,r){var i=e.call(this,t,n,r,TransactionState.Trying,"sip.transaction.nict")||this;return i.F=setTimeout(function(){return i.timerF()},Timers.TIMER_F),i.send(t.toString()).catch(function(e){i.logTransportError(e,"Failed to send initial outgoing request.")}),i}return __extends$1(t,e),t.prototype.dispose=function(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"nict"},enumerable:!1,configurable:!0}),t.prototype.receiveResponse=function(e){var t=e.statusCode;if(!t||t<100||t>699)throw new Error("Invalid status code ".concat(t));switch(this.state){case TransactionState.Trying:if(t>=100&&t<=199)return this.stateTransition(TransactionState.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(TransactionState.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case TransactionState.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(TransactionState.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case TransactionState.Completed:case TransactionState.Terminated:return;default:throw new Error("Invalid state ".concat(this.state))}var n="Non-INVITE client transaction received unexpected ".concat(t," response while in state ").concat(this.state,".");this.logger.warn(n)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"non-INVITE client transaction"},t.prototype.stateTransition=function(e,t){var n=this;void 0===t&&(t=!1);var r=function(){throw new Error("Invalid state transition from ".concat(n.state," to ").concat(e))};switch(e){case TransactionState.Trying:r();break;case TransactionState.Proceeding:this.state!==TransactionState.Trying&&r();break;case TransactionState.Completed:this.state!==TransactionState.Trying&&this.state!==TransactionState.Proceeding&&r();break;case TransactionState.Terminated:this.state!==TransactionState.Trying&&this.state!==TransactionState.Proceeding&&this.state!==TransactionState.Completed&&(t||r());break;default:r()}e===TransactionState.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(function(){return n.timerK()},Timers.TIMER_K)),e===TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timerF=function(){this.logger.debug("Timer F expired for non-INVITE client transaction ".concat(this.id,".")),this.state!==TransactionState.Trying&&this.state!==TransactionState.Proceeding||(this.onRequestTimeout(),this.stateTransition(TransactionState.Terminated))},t.prototype.timerK=function(){this.state===TransactionState.Completed&&this.stateTransition(TransactionState.Terminated)},t}(ClientTransaction),NonInviteServerTransaction=function(e){function t(t,n,r){return e.call(this,t,n,r,TransactionState.Trying,"sip.transaction.nist")||this}return __extends$1(t,e),t.prototype.dispose=function(){this.J&&(clearTimeout(this.J),this.J=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"nist"},enumerable:!1,configurable:!0}),t.prototype.receiveRequest=function(e){var t=this;switch(this.state){case TransactionState.Trying:break;case TransactionState.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(function(e){t.logTransportError(e,"Failed to send retransmission of provisional response.")});break;case TransactionState.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(function(e){t.logTransportError(e,"Failed to send retransmission of final response.")});break;case TransactionState.Terminated:break;default:throw new Error("Invalid state ".concat(this.state))}},t.prototype.receiveResponse=function(e,t){var n=this;if(e<100||e>699)throw new Error("Invalid status code ".concat(e));if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case TransactionState.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(TransactionState.Proceeding),void this.send(t).catch(function(e){n.logTransportError(e,"Failed to send provisional response.")});if(e>=200&&e<=699)return this.stateTransition(TransactionState.Completed),void this.send(t).catch(function(e){n.logTransportError(e,"Failed to send final response.")});break;case TransactionState.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(TransactionState.Completed),void this.send(t).catch(function(e){n.logTransportError(e,"Failed to send final response.")});break;case TransactionState.Completed:return;case TransactionState.Terminated:break;default:throw new Error("Invalid state ".concat(this.state))}var r="Non-INVITE server transaction received unexpected ".concat(e," response from TU while in state ").concat(this.state,".");throw this.logger.error(r),new Error(r)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"non-INVITE server transaction"},t.prototype.stateTransition=function(e,t){var n=this;void 0===t&&(t=!1);var r=function(){throw new Error("Invalid state transition from ".concat(n.state," to ").concat(e))};switch(e){case TransactionState.Trying:r();break;case TransactionState.Proceeding:this.state!==TransactionState.Trying&&r();break;case TransactionState.Completed:this.state!==TransactionState.Trying&&this.state!==TransactionState.Proceeding&&r();break;case TransactionState.Terminated:this.state!==TransactionState.Proceeding&&this.state!==TransactionState.Completed&&(t||r());break;default:r()}e===TransactionState.Completed&&(this.J=setTimeout(function(){return n.timerJ()},Timers.TIMER_J)),e===TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timerJ=function(){this.logger.debug("Timer J expired for NON-INVITE server transaction ".concat(this.id,".")),this.state===TransactionState.Completed&&this.stateTransition(TransactionState.Terminated)},t}(ServerTransaction),UserAgentClient=function(){function e(e,t,n,r){this.transactionConstructor=e,this.core=t,this.message=n,this.delegate=r,this.challenged=!1,this.stale=!1,this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}return e.prototype.dispose=function(){this.transaction.dispose()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.core.loggerFactory},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transaction",{get:function(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction},enumerable:!1,configurable:!0}),e.prototype.cancel=function(t,n){var r=this;if(void 0===n&&(n={}),!this.transaction)throw new Error("Transaction undefined.");if(!this.message.to)throw new Error("To undefined.");if(!this.message.from)throw new Error("From undefined.");var i=this.core.makeOutgoingRequestMessage(C.CANCEL,this.message.ruri,this.message.from.uri,this.message.to.uri,{toTag:this.message.toTag,fromTag:this.message.fromTag,callId:this.message.callId,cseq:this.message.cseq},n.extraHeaders);return i.branch=this.message.branch,this.message.headers.Route&&(i.headers.Route=this.message.headers.Route),t&&i.setHeader("Reason",t),this.transaction.state===TransactionState.Proceeding?new e(NonInviteClientTransaction,this.core,i):this.transaction.addStateChangeListener(function(){r.transaction&&r.transaction.state===TransactionState.Proceeding&&new e(NonInviteClientTransaction,r.core,i)},{once:!0}),i},e.prototype.authenticationGuard=function(e,t){var n,r,i=e.statusCode;if(!i)throw new Error("Response status code undefined.");if(401!==i&&407!==i)return!0;if(401===i?(n=e.parseHeader("www-authenticate"),r="authorization"):(n=e.parseHeader("proxy-authenticate"),r="proxy-authorization"),!n)return this.logger.warn(i+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==n.stale))return this.logger.warn(i+" apparently in authentication loop, cannot authenticate"),!0;if(!this.credentials&&(this.credentials=this.core.configuration.authenticationFactory(),!this.credentials))return this.logger.warn("Unable to obtain credentials, cannot authenticate"),!0;if(!this.credentials.authenticate(this.message,n))return!0;this.challenged=!0,n.stale&&(this.stale=!0);var s=this.message.cseq+=1;return t&&t.localSequenceNumber&&(t.incrementLocalSequenceNumber(),s=this.message.cseq=t.localSequenceNumber),this.message.setHeader("cseq",s+" "+this.message.method),this.message.setHeader(r,this.credentials.toString()),this.init(),!1},e.prototype.onRequestTimeout=function(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");var e=new IncomingResponseMessage;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)},e.prototype.onTransportError=function(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");var t=new IncomingResponseMessage;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)},e.prototype.receiveResponse=function(e){if(this.authenticationGuard(e)){var t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e});break;case/^2[0-9]{2}$/.test(t):this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e});break;case/^3[0-9]{2}$/.test(t):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error("Invalid status code ".concat(t))}}},e.prototype.init=function(){var e=this,t={loggerFactory:this.loggerFactory,onRequestTimeout:function(){return e.onRequestTimeout()},onStateChange:function(t){t===TransactionState.Terminated&&(e.core.userAgentClients.delete(r),n===e._transaction&&e.dispose())},onTransportError:function(t){return e.onTransportError(t)},receiveResponse:function(t){return e.receiveResponse(t)}},n=new this.transactionConstructor(this.message,this.core.transport,t);this._transaction=n;var r=n.id+n.request.method;this.core.userAgentClients.set(r,this)},e}(),ByeUserAgentClient=function(e){function t(t,n,r){var i,s=t.createOutgoingRequestMessage(C.BYE,r);return i=e.call(this,NonInviteClientTransaction,t.userAgentCore,s,n)||this,t.dispose(),i}return __extends$1(t,e),t}(UserAgentClient),UserAgentServer=function(){function e(e,t,n,r){this.transactionConstructor=e,this.core=t,this.message=n,this.delegate=r,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=n.toTag?n.toTag:newTag(),this.init()}return e.prototype.dispose=function(){this.transaction.dispose()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.core.loggerFactory},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transaction",{get:function(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){if(void 0===e&&(e={statusCode:200}),!this.acceptable)throw new TransactionStateError("".concat(this.message.method," not acceptable in state ").concat(this.transaction.state,"."));var t=e.statusCode;if(t<200||t>299)throw new TypeError("Invalid statusCode: ".concat(t));return this.reply(e)},e.prototype.progress=function(e){if(void 0===e&&(e={statusCode:180}),!this.progressable)throw new TransactionStateError("".concat(this.message.method," not progressable in state ").concat(this.transaction.state,"."));var t=e.statusCode;if(t<101||t>199)throw new TypeError("Invalid statusCode: ".concat(t));return this.reply(e)},e.prototype.redirect=function(e,t){if(void 0===t&&(t={statusCode:302}),!this.redirectable)throw new TransactionStateError("".concat(this.message.method," not redirectable in state ").concat(this.transaction.state,"."));var n=t.statusCode;if(n<300||n>399)throw new TypeError("Invalid statusCode: ".concat(n));var r=new Array;return e.forEach(function(e){return r.push("Contact: ".concat(e.toString()))}),t.extraHeaders=(t.extraHeaders||[]).concat(r),this.reply(t)},e.prototype.reject=function(e){if(void 0===e&&(e={statusCode:480}),!this.rejectable)throw new TransactionStateError("".concat(this.message.method," not rejectable in state ").concat(this.transaction.state,"."));var t=e.statusCode;if(t<400||t>699)throw new TypeError("Invalid statusCode: ".concat(t));return this.reply(e)},e.prototype.trying=function(e){if(!this.tryingable)throw new TransactionStateError("".concat(this.message.method," not tryingable in state ").concat(this.transaction.state,"."));return this.reply({statusCode:100})},e.prototype.receiveCancel=function(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)},Object.defineProperty(e.prototype,"acceptable",{get:function(){if(this.transaction instanceof InviteServerTransaction)return this.transaction.state===TransactionState.Proceeding||this.transaction.state===TransactionState.Accepted;if(this.transaction instanceof NonInviteServerTransaction)return this.transaction.state===TransactionState.Trying||this.transaction.state===TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"progressable",{get:function(){if(this.transaction instanceof InviteServerTransaction)return this.transaction.state===TransactionState.Proceeding;if(this.transaction instanceof NonInviteServerTransaction)return!1;throw new Error("Unknown transaction type.")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"redirectable",{get:function(){if(this.transaction instanceof InviteServerTransaction)return this.transaction.state===TransactionState.Proceeding;if(this.transaction instanceof NonInviteServerTransaction)return this.transaction.state===TransactionState.Trying||this.transaction.state===TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"rejectable",{get:function(){if(this.transaction instanceof InviteServerTransaction)return this.transaction.state===TransactionState.Proceeding;if(this.transaction instanceof NonInviteServerTransaction)return this.transaction.state===TransactionState.Trying||this.transaction.state===TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"tryingable",{get:function(){if(this.transaction instanceof InviteServerTransaction)return this.transaction.state===TransactionState.Proceeding;if(this.transaction instanceof NonInviteServerTransaction)return this.transaction.state===TransactionState.Trying;throw new Error("Unknown transaction type.")},enumerable:!1,configurable:!0}),e.prototype.reply=function(e){e.toTag||100===e.statusCode||(e.toTag=this.toTag),e.userAgent=e.userAgent||this.core.configuration.userAgentHeaderFieldValue,e.supported=e.supported||this.core.configuration.supportedOptionTagsResponse;var t=constructOutgoingResponse(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t},e.prototype.init=function(){var e=this,t={loggerFactory:this.loggerFactory,onStateChange:function(t){t===TransactionState.Terminated&&(e.core.userAgentServers.delete(r),e.dispose())},onTransportError:function(t){e.logger.error(t.message),e.delegate&&e.delegate.onTransportError?e.delegate.onTransportError(t):e.logger.error("User agent server response transport error.")}},n=new this.transactionConstructor(this.message,this.core.transport,t);this._transaction=n;var r=n.id;this.core.userAgentServers.set(n.id,this)},e}(),ByeUserAgentServer=function(e){function t(t,n,r){return e.call(this,NonInviteServerTransaction,t.userAgentCore,n,r)||this}return __extends$1(t,e),t}(UserAgentServer),InfoUserAgentClient=function(e){function t(t,n,r){var i=t.createOutgoingRequestMessage(C.INFO,r);return e.call(this,NonInviteClientTransaction,t.userAgentCore,i,n)||this}return __extends$1(t,e),t}(UserAgentClient),InfoUserAgentServer=function(e){function t(t,n,r){return e.call(this,NonInviteServerTransaction,t.userAgentCore,n,r)||this}return __extends$1(t,e),t}(UserAgentServer),MessageUserAgentClient=function(e){function t(t,n,r){return e.call(this,NonInviteClientTransaction,t,n,r)||this}return __extends$1(t,e),t}(UserAgentClient),MessageUserAgentServer=function(e){function t(t,n,r){return e.call(this,NonInviteServerTransaction,t,n,r)||this}return __extends$1(t,e),t}(UserAgentServer),NotifyUserAgentClient=function(e){function t(t,n,r){var i=t.createOutgoingRequestMessage(C.NOTIFY,r);return e.call(this,NonInviteClientTransaction,t.userAgentCore,i,n)||this}return __extends$1(t,e),t}(UserAgentClient);function instanceOfDialog(e){return void 0!==e.userAgentCore}var NotifyUserAgentServer=function(e){function t(t,n,r){var i=instanceOfDialog(t)?t.userAgentCore:t;return e.call(this,NonInviteServerTransaction,i,n,r)||this}return __extends$1(t,e),t}(UserAgentServer),PrackUserAgentClient=function(e){function t(t,n,r){var i,s=t.createOutgoingRequestMessage(C.PRACK,r);return i=e.call(this,NonInviteClientTransaction,t.userAgentCore,s,n)||this,t.signalingStateTransition(s),i}return __extends$1(t,e),t}(UserAgentClient),PrackUserAgentServer=function(e){function t(t,n,r){var i=e.call(this,NonInviteServerTransaction,t.userAgentCore,n,r)||this;return t.signalingStateTransition(n),i.dialog=t,i}return __extends$1(t,e),t.prototype.accept=function(t){return void 0===t&&(t={statusCode:200}),t.body&&this.dialog.signalingStateTransition(t.body),e.prototype.accept.call(this,t)},t}(UserAgentServer),ReInviteUserAgentClient=function(e){function t(t,n,r){var i=this,s=t.createOutgoingRequestMessage(C.INVITE,r);return(i=e.call(this,InviteClientTransaction,t.userAgentCore,s,n)||this).delegate=n,t.signalingStateTransition(s),t.reinviteUserAgentClient=i,i.dialog=t,i}return __extends$1(t,e),t.prototype.receiveResponse=function(e){var t=this;if(this.authenticationGuard(e,this.dialog)){var n=e.statusCode?e.statusCode.toString():"";if(!n)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(n):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(n):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:this.dialog,prack:function(e){throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(n):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:function(e){return t.dialog.ack(e)}});break;case/^3[0-9]{2}$/.test(n):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(n):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error("Invalid status code ".concat(n))}}},t}(UserAgentClient),ReInviteUserAgentServer=function(e){function t(t,n,r){var i=e.call(this,InviteServerTransaction,t.userAgentCore,n,r)||this;return t.reinviteUserAgentServer=i,i.dialog=t,i}return __extends$1(t,e),t.prototype.accept=function(t){void 0===t&&(t={statusCode:200}),t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(this.dialog.routeSet.map(function(e){return"Record-Route: ".concat(e)}));var n=e.prototype.accept.call(this,t),r=this.dialog,i=__assign(__assign({},n),{session:r});return t.body&&this.dialog.signalingStateTransition(t.body),this.dialog.reConfirm(),i},t.prototype.progress=function(t){void 0===t&&(t={statusCode:180});var n=e.prototype.progress.call(this,t),r=this.dialog,i=__assign(__assign({},n),{session:r});return t.body&&this.dialog.signalingStateTransition(t.body),i},t.prototype.redirect=function(e,t){throw this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")},t.prototype.reject=function(t){return void 0===t&&(t={statusCode:488}),this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,e.prototype.reject.call(this,t)},t}(UserAgentServer),ReferUserAgentClient=function(e){function t(t,n,r){var i=t.createOutgoingRequestMessage(C.REFER,r);return e.call(this,NonInviteClientTransaction,t.userAgentCore,i,n)||this}return __extends$1(t,e),t}(UserAgentClient);function instanceOfSessionDialog(e){return void 0!==e.userAgentCore}var ReferUserAgentServer=function(e){function t(t,n,r){var i=instanceOfSessionDialog(t)?t.userAgentCore:t;return e.call(this,NonInviteServerTransaction,i,n,r)||this}return __extends$1(t,e),t}(UserAgentServer),SessionDialog=function(e){function t(t,n,r,i){var s=e.call(this,n,r)||this;return s.initialTransaction=t,s._signalingState=SignalingState.Initial,s.ackWait=!1,s.ackProcessing=!1,s.delegate=i,t instanceof InviteServerTransaction&&(s.ackWait=!0),s.early||s.start2xxRetransmissionTimer(),s.signalingStateTransition(t.request),s.logger=n.loggerFactory.getLogger("sip.invite-dialog"),s.logger.log("INVITE dialog ".concat(s.id," constructed")),s}return __extends$1(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._signalingState=SignalingState.Closed,this._offer=void 0,this._answer=void 0,this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.logger.log("INVITE dialog ".concat(this.id," destroyed"))},Object.defineProperty(t.prototype,"sessionState",{get:function(){return this.early?SessionState$1.Early:this.ackWait?SessionState$1.AckWait:this._signalingState===SignalingState.Closed?SessionState$1.Terminated:SessionState$1.Confirmed},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"signalingState",{get:function(){return this._signalingState},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"offer",{get:function(){return this._offer},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"answer",{get:function(){return this._answer},enumerable:!1,configurable:!0}),t.prototype.confirm=function(){this.early&&this.start2xxRetransmissionTimer(),e.prototype.confirm.call(this)},t.prototype.reConfirm=function(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()},t.prototype.ack=function(e){var t;if(void 0===e&&(e={}),this.logger.log("INVITE dialog ".concat(this.id," sending ACK request")),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof InviteClientTransaction))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}var n=this.createOutgoingRequestMessage(C.ACK,{cseq:t.request.cseq,extraHeaders:e.extraHeaders,body:e.body});return t.ackResponse(n),this.signalingStateTransition(n),{message:n}},t.prototype.bye=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending BYE request")),this.initialTransaction instanceof InviteServerTransaction){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==TransactionState.Terminated)throw new Error("UAS MUST NOT send a BYE on a confirmed dialog until it has received an ACK for its 2xx response or until the server transaction times out.")}return new ByeUserAgentClient(this,e,t)},t.prototype.info=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending INFO request")),this.early)throw new Error("Dialog not confirmed.");return new InfoUserAgentClient(this,e,t)},t.prototype.invite=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending INVITE request")),this.early)throw new Error("Dialog not confirmed.");if(this.reinviteUserAgentClient)throw new Error("There is an ongoing re-INVITE client transaction.");if(this.reinviteUserAgentServer)throw new Error("There is an ongoing re-INVITE server transaction.");return new ReInviteUserAgentClient(this,e,t)},t.prototype.message=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending MESSAGE request")),this.early)throw new Error("Dialog not confirmed.");var n=this.createOutgoingRequestMessage(C.MESSAGE,t);return new MessageUserAgentClient(this.core,n,e)},t.prototype.notify=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending NOTIFY request")),this.early)throw new Error("Dialog not confirmed.");return new NotifyUserAgentClient(this,e,t)},t.prototype.prack=function(e,t){return this.logger.log("INVITE dialog ".concat(this.id," sending PRACK request")),new PrackUserAgentClient(this,e,t)},t.prototype.refer=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending REFER request")),this.early)throw new Error("Dialog not confirmed.");return new ReferUserAgentClient(this,e,t)},t.prototype.receiveRequest=function(t){var n=this;if(this.logger.log("INVITE dialog ".concat(this.id," received ").concat(t.method," request")),t.method!==C.ACK)if(this.sequenceGuard(t)){if(e.prototype.receiveRequest.call(this,t),t.method===C.INVITE){var r=function(){var e=n.ackWait?"waiting for initial ACK":"processing initial ACK";n.logger.warn("INVITE dialog ".concat(n.id," received re-INVITE while ").concat(e));n.logger.warn("RFC 5407 suggests the following to avoid this race condition... Note: Implementation issues are outside the scope of this document, but the following tip is provided for avoiding race conditions of this type. The caller can delay sending re-INVITE F6 for some period of time (2 seconds, perhaps), after which the caller can reasonably assume that its ACK has been received. Implementors can decouple the actions of the user (e.g., pressing the hold button) from the actions of the protocol (the sending of re-INVITE F6), so that the UA can behave like this. In this case, it is the implementor's choice as to how long to wait. In most cases, such an implementation may be useful to prevent the type of race condition shown in this section. This document expresses no preference about whether or not they should wait for an ACK to be delivered. After considering the impact on user experience, implementors should decide whether or not to wait for a while, because the user experience depends on the implementation and has no direct bearing on protocol behavior.")},i=Math.floor(10*Math.random())+1,s=["Retry-After: ".concat(i)];if(this.ackProcessing)return this.core.replyStateless(t,{statusCode:500,extraHeaders:s}),void r();if(this.ackWait&&this.signalingState!==SignalingState.Stable)return this.core.replyStateless(t,{statusCode:500,extraHeaders:s}),void r();if(this.reinviteUserAgentServer)return void this.core.replyStateless(t,{statusCode:500,extraHeaders:s});if(this.reinviteUserAgentClient)return void this.core.replyStateless(t,{statusCode:491})}if(t.method===C.INVITE){var o=t.parseHeader("contact");if(!o)throw new Error("Contact undefined.");if(!(o instanceof NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=o.uri}switch(t.method){case C.BYE:var a=new ByeUserAgentServer(this,t);this.delegate&&this.delegate.onBye?this.delegate.onBye(a):a.accept(),this.dispose();break;case C.INFO:a=new InfoUserAgentServer(this,t);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(a):a.reject({statusCode:469,extraHeaders:["Recv-Info:"]});break;case C.INVITE:a=new ReInviteUserAgentServer(this,t);this.signalingStateTransition(t),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(a):a.reject({statusCode:488});break;case C.MESSAGE:a=new MessageUserAgentServer(this.core,t);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(a):a.accept();break;case C.NOTIFY:a=new NotifyUserAgentServer(this,t);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(a):a.accept();break;case C.PRACK:a=new PrackUserAgentServer(this,t);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(a):a.accept();break;case C.REFER:a=new ReferUserAgentServer(this,t);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(a):a.reject();break;default:this.logger.log("INVITE dialog ".concat(this.id," received unimplemented ").concat(t.method," request")),this.core.replyStateless(t,{statusCode:501})}}else this.logger.log("INVITE dialog ".concat(this.id," rejected out of order ").concat(t.method," request."));else{if(this.ackWait){if(this.initialTransaction instanceof InviteClientTransaction)return void this.logger.warn("INVITE dialog ".concat(this.id," received unexpected ").concat(t.method," request, dropping."));if(this.initialTransaction.request.cseq!==t.cseq)return void this.logger.warn("INVITE dialog ".concat(this.id," received unexpected ").concat(t.method," request, dropping."));this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn("INVITE dialog ".concat(this.id," received unexpected ").concat(t.method," request, dropping."));if(this.reinviteUserAgentServer.transaction.request.cseq!==t.cseq)return void this.logger.warn("INVITE dialog ".concat(this.id," received unexpected ").concat(t.method," request, dropping."));this.reinviteUserAgentServer=void 0}if(this.signalingStateTransition(t),this.delegate&&this.delegate.onAck){var c=this.delegate.onAck({message:t});c instanceof Promise&&(this.ackProcessing=!0,c.then(function(){return n.ackProcessing=!1}).catch(function(){return n.ackProcessing=!1}))}}},t.prototype.reliableSequenceGuard=function(e){var t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){var n=e.getHeader("require"),r=e.getHeader("rseq"),i=n&&n.includes("100rel")&&r?Number(r):void 0;if(i){if(this.rseq&&this.rseq+1!==i)return!1;this.rseq=this.rseq?this.rseq+1:i}}return!0},t.prototype.signalingStateRollback=function(){this._signalingState!==SignalingState.HaveLocalOffer&&this.signalingState!==SignalingState.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=SignalingState.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)},t.prototype.signalingStateTransition=function(e){var t=getBody(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===SignalingState.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof IncomingRequestMessage)switch(this._signalingState){case SignalingState.Initial:case SignalingState.Stable:this._signalingState=SignalingState.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case SignalingState.HaveLocalOffer:this._signalingState=SignalingState.Stable,this._answer=t;break;case SignalingState.HaveRemoteOffer:case SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof IncomingResponseMessage)switch(this._signalingState){case SignalingState.Initial:case SignalingState.Stable:this._signalingState=SignalingState.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case SignalingState.HaveLocalOffer:this._signalingState=SignalingState.Stable,this._answer=t;break;case SignalingState.HaveRemoteOffer:case SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof OutgoingRequestMessage)switch(this._signalingState){case SignalingState.Initial:case SignalingState.Stable:this._signalingState=SignalingState.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case SignalingState.HaveLocalOffer:break;case SignalingState.HaveRemoteOffer:this._signalingState=SignalingState.Stable,this._answer=t;break;case SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(isBody(e))switch(this._signalingState){case SignalingState.Initial:case SignalingState.Stable:this._signalingState=SignalingState.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case SignalingState.HaveLocalOffer:break;case SignalingState.HaveRemoteOffer:this._signalingState=SignalingState.Stable,this._answer=t;break;case SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}}},t.prototype.start2xxRetransmissionTimer=function(){var e=this;if(this.initialTransaction instanceof InviteServerTransaction){var t=this.initialTransaction,n=Timers.T1,r=function(){e.ackWait?(e.logger.log("No ACK for 2xx response received, attempting retransmission"),t.retransmitAcceptedResponse(),n=Math.min(2*n,Timers.T2),e.invite2xxTimer=setTimeout(r,n)):e.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(r,n);var i=function(){t.state===TransactionState.Terminated&&(t.removeStateChangeListener(i),e.invite2xxTimer&&(clearTimeout(e.invite2xxTimer),e.invite2xxTimer=void 0),e.ackWait&&(e.delegate&&e.delegate.onAckTimeout?e.delegate.onAckTimeout():e.bye()))};t.addStateChangeListener(i)}},t.prototype.startReInvite2xxRetransmissionTimer=function(){var e=this;if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof InviteServerTransaction){var t=this.reinviteUserAgentServer.transaction,n=Timers.T1,r=function(){e.reinviteUserAgentServer?(e.logger.log("No ACK for 2xx response received, attempting retransmission"),t.retransmitAcceptedResponse(),n=Math.min(2*n,Timers.T2),e.invite2xxTimer=setTimeout(r,n)):e.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(r,n);var i=function(){t.state===TransactionState.Terminated&&(t.removeStateChangeListener(i),e.invite2xxTimer&&(clearTimeout(e.invite2xxTimer),e.invite2xxTimer=void 0),e.reinviteUserAgentServer)};t.addStateChangeListener(i)}},t}(Dialog),SubscriptionState$1;!function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(SubscriptionState$1||(SubscriptionState$1={}));var AllowedMethods=[C.ACK,C.BYE,C.CANCEL,C.INFO,C.INVITE,C.MESSAGE,C.NOTIFY,C.OPTIONS,C.PRACK,C.REFER,C.REGISTER,C.SUBSCRIBE],ReSubscribeUserAgentClient=function(e){function t(t,n,r){var i=this,s=t.createOutgoingRequestMessage(C.SUBSCRIBE,r);return(i=e.call(this,NonInviteClientTransaction,t.userAgentCore,s,n)||this).dialog=t,i}return __extends$1(t,e),t.prototype.waitNotifyStop=function(){},t.prototype.receiveResponse=function(t){if(t.statusCode&&t.statusCode>=200&&t.statusCode<300){var n=t.getHeader("Expires");if(n){var r=Number(n);this.dialog.subscriptionExpires>r&&(this.dialog.subscriptionExpires=r)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(t.statusCode&&t.statusCode>=400&&t.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(t.statusCode)&&this.dialog.terminate()}e.prototype.receiveResponse.call(this,t)},t}(UserAgentClient),SubscriptionDialog=function(e){function t(t,n,r,i,s,o){var a=e.call(this,i,s)||this;return a.delegate=o,a._autoRefresh=!1,a._subscriptionEvent=t,a._subscriptionExpires=n,a._subscriptionExpiresInitial=n,a._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),a._subscriptionRefresh=void 0,a._subscriptionRefreshLastSet=void 0,a._subscriptionState=r,a.logger=i.loggerFactory.getLogger("sip.subscribe-dialog"),a.logger.log("SUBSCRIBE dialog ".concat(a.id," constructed")),a}return __extends$1(t,e),t.initialDialogStateForSubscription=function(e,t){var n=t.getHeaders("record-route"),r=t.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");var i=r.uri,s=e.cseq,o=e.callId,a=e.fromTag,c=t.fromTag;if(!o)throw new Error("Call id undefined.");if(!a)throw new Error("From tag undefined.");if(!c)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");return{id:o+a+c,early:!1,callId:o,localTag:a,remoteTag:c,localSequenceNumber:s,remoteSequenceNumber:undefined,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:i,routeSet:n,secure:!1}},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.N&&(clearTimeout(this.N),this.N=void 0),this.refreshTimerClear(),this.logger.log("SUBSCRIBE dialog ".concat(this.id," destroyed"))},Object.defineProperty(t.prototype,"autoRefresh",{get:function(){return this._autoRefresh},set:function(e){this._autoRefresh=!0,this.refreshTimerSet()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionEvent",{get:function(){return this._subscriptionEvent},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionExpires",{get:function(){var e=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,t=this._subscriptionExpires-e;return Math.max(t,0)},set:function(e){if(e<0)throw new Error("Expires must be greater than or equal to zero.");if(this._subscriptionExpires=e,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this.autoRefresh){var t=this.subscriptionRefresh;(void 0===t||t>=e)&&this.refreshTimerSet()}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionExpiresInitial",{get:function(){return this._subscriptionExpiresInitial},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionRefresh",{get:function(){if(void 0!==this._subscriptionRefresh&&void 0!==this._subscriptionRefreshLastSet){var e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionState",{get:function(){return this._subscriptionState},enumerable:!1,configurable:!0}),t.prototype.receiveRequest=function(t){if(this.logger.log("SUBSCRIBE dialog ".concat(this.id," received ").concat(t.method," request")),this.sequenceGuard(t))if(e.prototype.receiveRequest.call(this,t),t.method===C.NOTIFY)this.onNotify(t);else this.logger.log("SUBSCRIBE dialog ".concat(this.id," received unimplemented ").concat(t.method," request")),this.core.replyStateless(t,{statusCode:501});else this.logger.log("SUBSCRIBE dialog ".concat(this.id," rejected out of order ").concat(t.method," request."))},t.prototype.refresh=function(){var e="Allow: "+AllowedMethods.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: "+this.subscriptionExpiresInitial),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)},t.prototype.subscribe=function(e,t){var n=this;if(void 0===t&&(t={}),this.subscriptionState!==SubscriptionState$1.Pending&&this.subscriptionState!==SubscriptionState$1.Active)throw new Error("Invalid state ".concat(this.subscriptionState,'. May only re-subscribe while in state "pending" or "active".'));this.logger.log("SUBSCRIBE dialog ".concat(this.id," sending SUBSCRIBE request"));var r=new ReSubscribeUserAgentClient(this,e,t);return this.N&&(clearTimeout(this.N),this.N=void 0),this.N=setTimeout(function(){return n.timerN()},Timers.TIMER_N),r},t.prototype.terminate=function(){this.stateTransition(SubscriptionState$1.Terminated),this.onTerminated()},t.prototype.unsubscribe=function(){var e="Allow: "+AllowedMethods.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: 0"),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)},t.prototype.onNotify=function(e){var t=e.parseHeader("Event").event;if(t&&t===this.subscriptionEvent){this.N&&(clearTimeout(this.N),this.N=void 0);var n=e.parseHeader("Subscription-State");if(n&&n.state){var r=n.state,i=n.expires?Math.max(n.expires,0):void 0;switch(r){case"pending":this.stateTransition(SubscriptionState$1.Pending,i);break;case"active":this.stateTransition(SubscriptionState$1.Active,i);break;case"terminated":this.stateTransition(SubscriptionState$1.Terminated,i);break;default:this.logger.warn("Unrecognized subscription state.")}var s=new NotifyUserAgentServer(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(s):s.accept()}else this.core.replyStateless(e,{statusCode:489})}else this.core.replyStateless(e,{statusCode:489})},t.prototype.onRefresh=function(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)},t.prototype.onTerminated=function(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()},t.prototype.refreshTimerClear=function(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)},t.prototype.refreshTimerSet=function(){var e=this;if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){var t=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(t/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout(function(){e.refreshTimer=void 0,e._subscriptionRefresh=void 0,e._subscriptionRefreshLastSet=void 0,e.onRefresh(e.refresh())},t)}},t.prototype.stateTransition=function(e,t){var n=this,r=function(){n.logger.warn("Invalid subscription state transition from ".concat(n.subscriptionState," to ").concat(e))};switch(e){case SubscriptionState$1.Initial:case SubscriptionState$1.NotifyWait:return void r();case SubscriptionState$1.Pending:if(this.subscriptionState!==SubscriptionState$1.NotifyWait&&this.subscriptionState!==SubscriptionState$1.Pending)return void r();break;case SubscriptionState$1.Active:case SubscriptionState$1.Terminated:if(this.subscriptionState!==SubscriptionState$1.NotifyWait&&this.subscriptionState!==SubscriptionState$1.Pending&&this.subscriptionState!==SubscriptionState$1.Active)return void r();break;default:return void r()}e===SubscriptionState$1.Pending&&t&&(this.subscriptionExpires=t),e===SubscriptionState$1.Active&&t&&(this.subscriptionExpires=t),e===SubscriptionState$1.Terminated&&this.dispose(),this._subscriptionState=e},t.prototype.timerN=function(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==SubscriptionState$1.Terminated&&(this.stateTransition(SubscriptionState$1.Terminated),this.onTerminated())},t}(Dialog),Levels;!function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(Levels||(Levels={}));var Logger=function(){function e(e,t,n){this.logger=e,this.category=t,this.label=n}return e.prototype.error=function(e){this.genericLog(Levels.error,e)},e.prototype.warn=function(e){this.genericLog(Levels.warn,e)},e.prototype.log=function(e){this.genericLog(Levels.log,e)},e.prototype.debug=function(e){this.genericLog(Levels.debug,e)},e.prototype.genericLog=function(e,t){this.logger.genericLog(e,this.category,this.label,t)},Object.defineProperty(e.prototype,"level",{get:function(){return this.logger.level},set:function(e){this.logger.level=e},enumerable:!1,configurable:!0}),e}(),LoggerFactory=function(){function e(){this.builtinEnabled=!0,this._level=Levels.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}return Object.defineProperty(e.prototype,"level",{get:function(){return this._level},set:function(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:Levels.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connector",{get:function(){return this._connector},set:function(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0},enumerable:!1,configurable:!0}),e.prototype.getLogger=function(e,t){if(t&&3===this.level)return new Logger(this,e,t);if(this.loggers[e])return this.loggers[e];var n=new Logger(this,e);return this.loggers[e]=n,n},e.prototype.genericLog=function(e,t,n,r){this.level>=e&&this.builtinEnabled&&this.print(e,t,n,r),this.connector&&this.connector(Levels[e],t,n,r)},e.prototype.print=function(e,t,n,r){if("string"==typeof r){var i=[new Date,t];n&&i.push(n),r=i.concat(r).join(" | ")}switch(e){case Levels.error:console.error(r);break;case Levels.warn:console.warn(r);break;case Levels.log:console.log(r);break;case Levels.debug:console.debug(r)}},e}();!function(e){function t(t,n,r){return e.call(this,NonInviteClientTransaction,t,n,r)||this}__extends$1(t,e)}(UserAgentClient);var InviteUserAgentClient=function(e){function t(t,n,r){var i=e.call(this,InviteClientTransaction,t,n,r)||this;return i.confirmedDialogAcks=new Map,i.confirmedDialogs=new Map,i.earlyDialogs=new Map,i.delegate=r,i}return __extends$1(t,e),t.prototype.dispose=function(){this.earlyDialogs.forEach(function(e){return e.dispose()}),this.earlyDialogs.clear(),e.prototype.dispose.call(this)},t.prototype.onTransportError=function(t){if(this.transaction.state===TransactionState.Calling)return e.prototype.onTransportError.call(this,t);this.logger.error(t.message),this.logger.error("User agent client request transport error while sending ACK.")},t.prototype.receiveResponse=function(e){var t=this;if(this.authenticationGuard(e)){var n=e.statusCode?e.statusCode.toString():"";if(!n)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(n):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(n):if(!e.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping.");var r=Dialog.initialDialogStateForUserAgentClient(this.message,e),i=this.earlyDialogs.get(r.id);if(!i){if(!((a=this.transaction)instanceof InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");i=new SessionDialog(a,this.core,r),this.earlyDialogs.set(i.id,i)}if(!i.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping.");i.signalingState!==SignalingState.Initial&&i.signalingState!==SignalingState.HaveLocalOffer||i.signalingStateTransition(e);var s=i;return void(this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:s,prack:function(e){return s.prack(void 0,e)}}));case/^2[0-9]{2}$/.test(n):if(!e.toTag)return void this.logger.error("2xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("2xx INVITE response received without a Contact header field, dropping.");r=Dialog.initialDialogStateForUserAgentClient(this.message,e);var o=this.confirmedDialogs.get(r.id);if(o){if(u=this.confirmedDialogAcks.get(r.id)){if(!((a=this.transaction)instanceof InviteClientTransaction))throw new Error("Client transaction not instance of InviteClientTransaction.");a.ackResponse(u.message)}return}if(o=this.earlyDialogs.get(r.id))o.confirm(),o.recomputeRouteSet(e),this.earlyDialogs.delete(o.id),this.confirmedDialogs.set(o.id,o);else{var a;if(!((a=this.transaction)instanceof InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");o=new SessionDialog(a,this.core,r),this.confirmedDialogs.set(o.id,o)}o.signalingState!==SignalingState.Initial&&o.signalingState!==SignalingState.HaveLocalOffer||o.signalingStateTransition(e);var c=o;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:c,ack:function(e){var n=c.ack(e);return t.confirmedDialogAcks.set(c.id,n),n}});else{var u=c.ack();this.confirmedDialogAcks.set(c.id,u)}return;case/^3[0-9]{2}$/.test(n):return this.earlyDialogs.forEach(function(e){return e.dispose()}),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(n):return this.earlyDialogs.forEach(function(e){return e.dispose()}),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error("Invalid status code ".concat(n))}}},t}(UserAgentClient),InviteUserAgentServer=function(e){function t(t,n,r){var i=e.call(this,InviteServerTransaction,t,n,r)||this;return i.core=t,i}return __extends$1(t,e),t.prototype.dispose=function(){this.earlyDialog&&this.earlyDialog.dispose(),e.prototype.dispose.call(this)},t.prototype.accept=function(t){if(void 0===t&&(t={statusCode:200}),!this.acceptable)throw new TransactionStateError("".concat(this.message.method," not acceptable in state ").concat(this.transaction.state,"."));if(!this.confirmedDialog)if(this.earlyDialog)this.earlyDialog.confirm(),this.confirmedDialog=this.earlyDialog,this.earlyDialog=void 0;else{var n=this.transaction;if(!(n instanceof InviteServerTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");var r=Dialog.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new SessionDialog(n,this.core,r)}var i=this.message.getHeaders("record-route").map(function(e){return"Record-Route: ".concat(e)}),s="Contact: ".concat(this.core.configuration.contact.toString()),o="Allow: "+AllowedMethods.toString();if(!t.body)if(this.confirmedDialog.signalingState===SignalingState.Stable)t.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===SignalingState.Initial||this.confirmedDialog.signalingState===SignalingState.HaveRemoteOffer)throw new Error("Response must have a body.");t.statusCode=t.statusCode||200,t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(i),t.extraHeaders.push(o),t.extraHeaders.push(s);var a=e.prototype.accept.call(this,t),c=this.confirmedDialog,u=__assign(__assign({},a),{session:c});return t.body&&this.confirmedDialog.signalingState!==SignalingState.Stable&&this.confirmedDialog.signalingStateTransition(t.body),u},t.prototype.progress=function(t){if(void 0===t&&(t={statusCode:180}),!this.progressable)throw new TransactionStateError("".concat(this.message.method," not progressable in state ").concat(this.transaction.state,"."));if(!this.earlyDialog){var n=this.transaction;if(!(n instanceof InviteServerTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");var r=Dialog.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new SessionDialog(n,this.core,r)}var i=this.message.getHeaders("record-route").map(function(e){return"Record-Route: ".concat(e)}),s="Contact: ".concat(this.core.configuration.contact);t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(i),t.extraHeaders.push(s);var o=e.prototype.progress.call(this,t),a=this.earlyDialog,c=__assign(__assign({},o),{session:a});return t.body&&this.earlyDialog.signalingState!==SignalingState.Stable&&this.earlyDialog.signalingStateTransition(t.body),c},t.prototype.redirect=function(t,n){return void 0===n&&(n={statusCode:302}),e.prototype.redirect.call(this,t,n)},t.prototype.reject=function(t){return void 0===t&&(t={statusCode:486}),e.prototype.reject.call(this,t)},t}(UserAgentServer),PublishUserAgentClient=function(e){function t(t,n,r){return e.call(this,NonInviteClientTransaction,t,n,r)||this}return __extends$1(t,e),t}(UserAgentClient);!function(e){function t(t,n,r){return e.call(this,NonInviteServerTransaction,t.userAgentCore,n,r)||this}__extends$1(t,e)}(UserAgentServer);var RegisterUserAgentClient=function(e){function t(t,n,r){return e.call(this,NonInviteClientTransaction,t,n,r)||this}return __extends$1(t,e),t}(UserAgentClient),RegisterUserAgentServer=function(e){function t(t,n,r){var i=e.call(this,NonInviteServerTransaction,t,n,r)||this;return i.core=t,i}return __extends$1(t,e),t}(UserAgentServer),SubscribeUserAgentClient=function(e){function t(t,n,r){var i=this,s=n.getHeader("Event");if(!s)throw new Error("Event undefined");var o=n.getHeader("Expires");if(!o)throw new Error("Expires undefined");return(i=e.call(this,NonInviteClientTransaction,t,n,r)||this).delegate=r,i.subscriberId=n.callId+n.fromTag+s,i.subscriptionExpiresRequested=i.subscriptionExpires=Number(o),i.subscriptionEvent=s,i.subscriptionState=SubscriptionState$1.NotifyWait,i.waitNotifyStart(),i}return __extends$1(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype.onNotify=function(e){var t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});var n=e.message.parseHeader("Subscription-State");if(!n||!n.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});var r=n.state;switch(r){case"pending":case"active":case"terminated":break;default:return this.logger.warn("Invalid subscription state ".concat(r)),void e.reject({statusCode:489})}if("terminated"!==r&&!e.message.parseHeader("contact"))return this.logger.warn("Failed to parse contact."),void e.reject({statusCode:489});if(this.dialog)throw new Error("Dialog already created. This implementation only supports install of single subscriptions.");switch(this.waitNotifyStop(),this.subscriptionExpires=n.expires?Math.min(this.subscriptionExpires,Math.max(n.expires,0)):this.subscriptionExpires,r){case"pending":this.subscriptionState=SubscriptionState$1.Pending;break;case"active":this.subscriptionState=SubscriptionState$1.Active;break;case"terminated":this.subscriptionState=SubscriptionState$1.Terminated;break;default:throw new Error("Unrecognized state ".concat(r,"."))}if(this.subscriptionState!==SubscriptionState$1.Terminated){var i=SubscriptionDialog.initialDialogStateForSubscription(this.message,e.message);this.dialog=new SubscriptionDialog(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,i)}if(this.delegate&&this.delegate.onNotify){var s=e,o=this.dialog;this.delegate.onNotify({request:s,subscription:o})}else e.accept()},t.prototype.waitNotifyStart=function(){var e=this;this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout(function(){return e.timerN()},Timers.TIMER_N))},t.prototype.waitNotifyStop=function(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)},t.prototype.receiveResponse=function(t){if(this.authenticationGuard(t)){if(t.statusCode&&t.statusCode>=200&&t.statusCode<300){var n=t.getHeader("Expires");if(n){var r=Number(n);r>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),r<this.subscriptionExpires&&(this.subscriptionExpires=r)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE");this.dialog&&this.dialog.subscriptionExpires>this.subscriptionExpires&&(this.dialog.subscriptionExpires=this.subscriptionExpires)}t.statusCode&&t.statusCode>=300&&t.statusCode<700&&this.waitNotifyStop(),e.prototype.receiveResponse.call(this,t)}},t.prototype.timerN=function(){this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."),this.waitNotifyStop(),this.delegate&&this.delegate.onNotifyTimeout&&this.delegate.onNotifyTimeout()},t}(UserAgentClient),SubscribeUserAgentServer=function(e){function t(t,n,r){var i=e.call(this,NonInviteServerTransaction,t,n,r)||this;return i.core=t,i}return __extends$1(t,e),t}(UserAgentServer),acceptedBodyTypes=["application/sdp","application/dtmf-relay"],UserAgentCore=function(){function e(e,t){void 0===t&&(t={}),this.userAgentClients=new Map,this.userAgentServers=new Map,this.configuration=e,this.delegate=t,this.dialogs=new Map,this.subscribers=new Map,this.logger=e.loggerFactory.getLogger("sip.user-agent-core")}return e.prototype.dispose=function(){this.reset()},e.prototype.reset=function(){this.dialogs.forEach(function(e){return e.dispose()}),this.dialogs.clear(),this.subscribers.forEach(function(e){return e.dispose()}),this.subscribers.clear(),this.userAgentClients.forEach(function(e){return e.dispose()}),this.userAgentClients.clear(),this.userAgentServers.forEach(function(e){return e.dispose()}),this.userAgentServers.clear()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.configuration.loggerFactory},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transport",{get:function(){var e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e},enumerable:!1,configurable:!0}),e.prototype.invite=function(e,t){return new InviteUserAgentClient(this,e,t)},e.prototype.message=function(e,t){return new MessageUserAgentClient(this,e,t)},e.prototype.publish=function(e,t){return new PublishUserAgentClient(this,e,t)},e.prototype.register=function(e,t){return new RegisterUserAgentClient(this,e,t)},e.prototype.subscribe=function(e,t){return new SubscribeUserAgentClient(this,e,t)},e.prototype.request=function(e,t){return new UserAgentClient(NonInviteClientTransaction,this,e,t)},e.prototype.makeOutgoingRequestMessage=function(e,t,n,r,i,s,o){var a=this.configuration.sipjsId,c=this.configuration.displayName,u=this.configuration.viaForceRport,l=this.configuration.hackViaTcp,h=this.configuration.supportedOptionTags.slice();e===C.REGISTER&&h.push("path","gruu"),e===C.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&h.push("gruu");var d=this.configuration.routeSet,p=this.configuration.userAgentHeaderFieldValue,g=this.configuration.viaHost,f=__assign(__assign({},{callIdPrefix:a,forceRport:u,fromDisplayName:c,hackViaTcp:l,optionTags:h,routeSet:d,userAgentString:p,viaHost:g}),i);return new OutgoingRequestMessage(e,t,n,r,f,s,o)},e.prototype.receiveIncomingRequestFromTransport=function(e){this.receiveRequestFromTransport(e)},e.prototype.receiveIncomingResponseFromTransport=function(e){this.receiveResponseFromTransport(e)},e.prototype.replyStateless=function(e,t){var n=this,r=this.configuration.userAgentHeaderFieldValue,i=this.configuration.supportedOptionTagsResponse;t=__assign(__assign({},t),{userAgent:r,supported:i});var s=constructOutgoingResponse(e,t);return this.transport.send(s.message).catch(function(t){t instanceof Error&&n.logger.error(t.message),n.logger.error("Transport error occurred sending stateless reply to ".concat(e.method," request."))}),s},e.prototype.receiveRequestFromTransport=function(e){var t=e.viaBranch,n=this.userAgentServers.get(t);e.method===C.ACK&&n&&n.transaction.state===TransactionState.Accepted&&n instanceof InviteUserAgentServer?this.logger.warn("Discarding out of dialog ACK after 2xx response sent on transaction ".concat(t,".")):e.method!==C.CANCEL?n?n.transaction.receiveRequest(e):this.receiveRequest(e):n?(this.replyStateless(e,{statusCode:200}),n.transaction instanceof InviteServerTransaction&&n.transaction.state===TransactionState.Proceeding&&n instanceof InviteUserAgentServer&&n.receiveCancel(e)):this.replyStateless(e,{statusCode:481})},e.prototype.receiveRequest=function(e){if(AllowedMethods.includes(e.method)){if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"===e.ruri.scheme){var t=e.ruri,n=function(e){return!!e&&e.user===t.user};if(!n(this.configuration.aor)&&!(n(this.configuration.contact.uri)||n(this.configuration.contact.pubGruu)||n(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==C.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==C.INVITE||e.hasHeader("Contact")){if(!e.toTag){var r=e.viaBranch;if(!this.userAgentServers.has(r))if(Array.from(this.userAgentServers.values()).some(function(t){return t.transaction.request.fromTag===e.fromTag&&t.transaction.request.callId===e.callId&&t.transaction.request.cseq===e.cseq}))return void this.replyStateless(e,{statusCode:482})}e.toTag?this.receiveInsideDialogRequest(e):this.receiveOutsideDialogRequest(e)}else this.replyStateless(e,{statusCode:400,reasonPhrase:"Missing Contact Header"})}else this.replyStateless(e,{statusCode:416})}else{var i="Allow: "+AllowedMethods.toString();this.replyStateless(e,{statusCode:405,extraHeaders:[i]})}},e.prototype.receiveInsideDialogRequest=function(e){if(e.method===C.NOTIFY){var t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});var n=e.callId+e.toTag+t.event,r=this.subscribers.get(n);if(r){var i=new NotifyUserAgentServer(this,e);return void r.onNotify(i)}}var s=e.callId+e.toTag+e.fromTag,o=this.dialogs.get(s);if(o){if(e.method===C.OPTIONS){var a="Allow: "+AllowedMethods.toString(),c="Accept: "+acceptedBodyTypes.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[a,c]})}o.receiveRequest(e)}else e.method!==C.ACK&&this.replyStateless(e,{statusCode:481})},e.prototype.receiveOutsideDialogRequest=function(e){switch(e.method){case C.ACK:break;case C.BYE:this.replyStateless(e,{statusCode:481});break;case C.CANCEL:throw new Error("Unexpected out of dialog request method ".concat(e.method,"."));case C.INFO:this.replyStateless(e,{statusCode:405});break;case C.INVITE:var t=new InviteUserAgentServer(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject();break;case C.MESSAGE:t=new MessageUserAgentServer(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept();break;case C.NOTIFY:t=new NotifyUserAgentServer(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405});break;case C.OPTIONS:var n="Allow: "+AllowedMethods.toString(),r="Accept: "+acceptedBodyTypes.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[n,r]});break;case C.REFER:t=new ReferUserAgentServer(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405});break;case C.REGISTER:t=new RegisterUserAgentServer(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405});break;case C.SUBSCRIBE:t=new SubscribeUserAgentServer(this,e);this.delegate.onSubscribe?this.delegate.onSubscribe(t):t.reject({statusCode:480});break;default:throw new Error("Unexpected out of dialog request method ".concat(e.method,"."))}},e.prototype.receiveResponseFromTransport=function(e){if(e.getHeaders("via").length>1)this.logger.warn("More than one Via header field present in the response, dropping");else{var t=e.viaBranch+e.method,n=this.userAgentClients.get(t);n?n.transaction.receiveResponse(e):this.logger.warn("Discarding unmatched ".concat(e.statusCode," response to ").concat(e.method," ").concat(t,"."))}},e}(),ContentTypeUnsupportedError=function(e){function t(t){return e.call(this,t||"Unsupported content type.")||this}return __extends$1(t,e),t}(Exception),RequestPendingError=function(e){function t(t){return e.call(this,t||"Request pending.")||this}return __extends$1(t,e),t}(Exception),SessionDescriptionHandlerError=function(e){function t(t){return e.call(this,t||"Unspecified session description handler error.")||this}return __extends$1(t,e),t}(Exception),SessionTerminatedError=function(e){function t(){return e.call(this,"The session has terminated.")||this}return __extends$1(t,e),t}(Exception),StateTransitionError=function(e){function t(t){return e.call(this,t||"An error occurred during state transition.")||this}return __extends$1(t,e),t}(Exception),Ack=function(){function e(e){this.incomingAckRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingAckRequest.message},enumerable:!1,configurable:!0}),e}(),Bye=function(){function e(e){this.incomingByeRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingByeRequest.message},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){return this.incomingByeRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingByeRequest.reject(e),Promise.resolve()},e}(),EmitterImpl=function(){function e(){this.listeners=new Array}return e.prototype.addListener=function(e,t){var n=this,r=function(t){n.removeListener(r),e(t)};!0===(null==t?void 0:t.once)?this.listeners.push(r):this.listeners.push(e)},e.prototype.emit=function(e){this.listeners.slice().forEach(function(t){return t(e)})},e.prototype.removeAllListeners=function(){this.listeners=[]},e.prototype.removeListener=function(e){this.listeners=this.listeners.filter(function(t){return t!==e})},e.prototype.on=function(e){return this.addListener(e)},e.prototype.off=function(e){return this.removeListener(e)},e.prototype.once=function(e){return this.addListener(e,{once:!0})},e}(),Info=function(){function e(e){this.incomingInfoRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingInfoRequest.message},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){return this.incomingInfoRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingInfoRequest.reject(e),Promise.resolve()},e}(),Message=function(){function e(e){this.incomingMessageRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingMessageRequest.message},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){return this.incomingMessageRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingMessageRequest.reject(e),Promise.resolve()},e}(),Notification=function(){function e(e){this.incomingNotifyRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingNotifyRequest.message},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){return this.incomingNotifyRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingNotifyRequest.reject(e),Promise.resolve()},e}(),Referral=function(){function e(e,t){this.incomingReferRequest=e,this.session=t}return Object.defineProperty(e.prototype,"referTo",{get:function(){var e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof NameAddrHeader))throw new Error("Failed to parse Refer-To header.");return e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"referredBy",{get:function(){return this.incomingReferRequest.message.getHeader("referred-by")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"replaces",{get:function(){var e=this.referTo.uri.getHeader("replaces");return e instanceof Array?e[0]:e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingReferRequest.message},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){return void 0===e&&(e={statusCode:202}),this.incomingReferRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingReferRequest.reject(e),Promise.resolve()},e.prototype.makeInviter=function(e){if(this.inviter)return this.inviter;var t=this.referTo.uri.clone();t.clearHeaders();var n=((e=e||{}).extraHeaders||[]).slice(),r=this.replaces;r&&n.push("Replaces: "+decodeURIComponent(r));var i=this.referredBy;return i&&n.push("Referred-By: "+i),e.extraHeaders=n,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter},e}(),SessionState;!function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(SessionState||(SessionState={}));var Session=function(){function e(e,t){void 0===t&&(t={}),this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=SessionState.Initial,this.delegate=t.delegate,this._stateEventEmitter=new EmitterImpl,this._userAgent=e}return e.prototype.dispose=function(){var e=this;switch(this.logger.log("Session ".concat(this.id," in state ").concat(this._state," is being disposed")),delete this.userAgent._sessions[this.id],this._sessionDescriptionHandler&&this._sessionDescriptionHandler.close(),this.state){case SessionState.Initial:case SessionState.Establishing:break;case SessionState.Established:return new Promise(function(t){e._bye({onAccept:function(){return t()},onRedirect:function(){return t()},onReject:function(){return t()}})});case SessionState.Terminating:case SessionState.Terminated:break;default:throw new Error("Unknown state.")}return Promise.resolve()},Object.defineProperty(e.prototype,"assertedIdentity",{get:function(){return this._assertedIdentity},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dialog",{get:function(){return this._dialog},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"replacee",{get:function(){return this._replacee},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandler",{get:function(){return this._sessionDescriptionHandler},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandlerFactory",{get:function(){return this.userAgent.configuration.sessionDescriptionHandlerFactory},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandlerModifiers",{get:function(){return this._sessionDescriptionHandlerModifiers||[]},set:function(e){this._sessionDescriptionHandlerModifiers=e.slice()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandlerOptions",{get:function(){return this._sessionDescriptionHandlerOptions||{}},set:function(e){this._sessionDescriptionHandlerOptions=__assign({},e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandlerModifiersReInvite",{get:function(){return this._sessionDescriptionHandlerModifiersReInvite||[]},set:function(e){this._sessionDescriptionHandlerModifiersReInvite=e.slice()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandlerOptionsReInvite",{get:function(){return this._sessionDescriptionHandlerOptionsReInvite||{}},set:function(e){this._sessionDescriptionHandlerOptionsReInvite=__assign({},e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"userAgent",{get:function(){return this._userAgent},enumerable:!1,configurable:!0}),e.prototype.bye=function(e){void 0===e&&(e={});var t="Session.bye() may only be called if established session.";switch(this.state){case SessionState.Initial:"function"==typeof this.cancel?(t+=" However Inviter.invite() has not yet been called.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called.",t+=" Perhaps you should have called Invitation.reject()?");break;case SessionState.Establishing:"function"==typeof this.cancel?(t+=" However a dialog does not yet exist.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called (or not yet resolved).",t+=" Perhaps you should have called Invitation.reject()?");break;case SessionState.Established:var n=e.requestDelegate,r=this.copyRequestOptions(e.requestOptions);return this._bye(n,r);case SessionState.Terminating:t+=" However this session is already terminating.","function"==typeof this.cancel?t+=" Perhaps you have already called Inviter.cancel()?":"function"==typeof this.reject&&(t+=" Perhaps you have already called Session.bye()?");break;case SessionState.Terminated:t+=" However this session is already terminated.";break;default:throw new Error("Unknown state")}return this.logger.error(t),Promise.reject(new Error("Invalid session state ".concat(this.state)))},e.prototype.info=function(e){if(void 0===e&&(e={}),this.state!==SessionState.Established){return this.logger.error("Session.info() may only be called if established session."),Promise.reject(new Error("Invalid session state ".concat(this.state)))}var t=e.requestDelegate,n=this.copyRequestOptions(e.requestOptions);return this._info(t,n)},e.prototype.invite=function(e){var t=this;if(void 0===e&&(e={}),this.logger.log("Session.invite"),this.state!==SessionState.Established)return Promise.reject(new Error("Invalid session state ".concat(this.state)));if(this.pendingReinvite)return Promise.reject(new RequestPendingError("Reinvite in progress. Please wait until complete, then try again."));this.pendingReinvite=!0,e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiersReInvite=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptionsReInvite=e.sessionDescriptionHandlerOptions);var n={onAccept:function(n){var r=getBody(n.message);if(!r)return t.logger.error("Received 2xx response to re-INVITE without a session description"),t.ackAndBye(n,400,"Missing session description"),t.stateTransition(SessionState.Terminated),void(t.pendingReinvite=!1);if(e.withoutSdp){var i={sessionDescriptionHandlerOptions:t.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:t.sessionDescriptionHandlerModifiersReInvite};t.setOfferAndGetAnswer(r,i).then(function(e){n.ack({body:e})}).catch(function(e){t.logger.error("Failed to handle offer in 2xx response to re-INVITE"),t.logger.error(e.message),t.state===SessionState.Terminated?n.ack():(t.ackAndBye(n,488,"Bad Media Description"),t.stateTransition(SessionState.Terminated))}).then(function(){t.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(n)})}else{i={sessionDescriptionHandlerOptions:t.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:t.sessionDescriptionHandlerModifiersReInvite};t.setAnswer(r,i).then(function(){n.ack()}).catch(function(e){t.logger.error("Failed to handle answer in 2xx response to re-INVITE"),t.logger.error(e.message),t.state!==SessionState.Terminated?(t.ackAndBye(n,488,"Bad Media Description"),t.stateTransition(SessionState.Terminated)):n.ack()}).then(function(){t.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(n)})}},onProgress:function(e){},onRedirect:function(e){},onReject:function(n){t.logger.warn("Received a non-2xx response to re-INVITE"),t.pendingReinvite=!1,e.withoutSdp?e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(n):t.rollbackOffer().catch(function(e){if(t.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),t.logger.error(e.message),t.state!==SessionState.Terminated){if(!t.dialog)throw new Error("Dialog undefined.");var n=[];n.push("Reason: "+t.getReasonHeaderValue(500,"Internal Server Error")),t.dialog.bye(void 0,{extraHeaders:n}),t.stateTransition(SessionState.Terminated)}}).then(function(){e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(n)})},onTrying:function(e){}},r=e.requestOptions||{};if(r.extraHeaders=(r.extraHeaders||[]).slice(),r.extraHeaders.push("Allow: "+AllowedMethods.toString()),r.extraHeaders.push("Contact: "+this._contact),e.withoutSdp){if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return Promise.resolve(this.dialog.invite(n,r))}var i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(i).then(function(e){if(!t.dialog)throw t.pendingReinvite=!1,new Error("Dialog undefined.");return r.body=e,t.dialog.invite(n,r)}).catch(function(e){throw t.logger.error(e.message),t.logger.error("Failed to send re-INVITE"),t.pendingReinvite=!1,e})},e.prototype.message=function(e){if(void 0===e&&(e={}),this.state!==SessionState.Established){return this.logger.error("Session.message() may only be called if established session."),Promise.reject(new Error("Invalid session state ".concat(this.state)))}var t=e.requestDelegate,n=this.copyRequestOptions(e.requestOptions);return this._message(t,n)},e.prototype.refer=function(e,t){if(void 0===t&&(t={}),this.state!==SessionState.Established){return this.logger.error("Session.refer() may only be called if established session."),Promise.reject(new Error("Invalid session state ".concat(this.state)))}var n=t.requestDelegate,r=this.copyRequestOptions(t.requestOptions);return r.extraHeaders=r.extraHeaders?r.extraHeaders.concat(this.referExtraHeaders(this.referToString(e))):this.referExtraHeaders(this.referToString(e)),this._refer(t.onNotify,n,r)},e.prototype._bye=function(e,t){var n=this;if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));var r=this.dialog;switch(r.sessionState){case SessionState$1.Initial:case SessionState$1.Early:throw new Error("Invalid dialog state ".concat(r.sessionState));case SessionState$1.AckWait:return this.stateTransition(SessionState.Terminating),new Promise(function(i){r.delegate={onAck:function(){var s=r.bye(e,t);return n.stateTransition(SessionState.Terminated),i(s),Promise.resolve()},onAckTimeout:function(){var s=r.bye(e,t);n.stateTransition(SessionState.Terminated),i(s)}}});case SessionState$1.Confirmed:var i=r.bye(e,t);return this.stateTransition(SessionState.Terminated),Promise.resolve(i);case SessionState$1.Terminated:throw new Error("Invalid dialog state ".concat(r.sessionState));default:throw new Error("Unrecognized state.")}},e.prototype._info=function(e,t){return this.dialog?Promise.resolve(this.dialog.info(e,t)):Promise.reject(new Error("Session dialog undefined."))},e.prototype._message=function(e,t){return this.dialog?Promise.resolve(this.dialog.message(e,t)):Promise.reject(new Error("Session dialog undefined."))},e.prototype._refer=function(e,t,n){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,n))):Promise.reject(new Error("Session dialog undefined."))},e.prototype.ackAndBye=function(e,t,n){e.ack();var r=[];t&&r.push("Reason: "+this.getReasonHeaderValue(t,n)),e.session.bye(void 0,{extraHeaders:r})},e.prototype.onAckRequest=function(e){var t=this;if(this.logger.log("Session.onAckRequest"),this.state!==SessionState.Established&&this.state!==SessionState.Terminating)return this.logger.error("ACK received while in state ".concat(this.state,", dropping request")),Promise.resolve();var n=this.dialog;if(!n)throw new Error("Dialog undefined.");var r={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};if(this.delegate&&this.delegate.onAck){var i=new Ack(e);this.delegate.onAck(i)}switch(this.pendingReinviteAck=!1,n.signalingState){case SignalingState.Initial:this.logger.error("Invalid signaling state ".concat(n.signalingState,"."));var s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return n.bye(void 0,{extraHeaders:s}),this.stateTransition(SessionState.Terminated),Promise.resolve();case SignalingState.Stable:var o=getBody(e.message);return o?"render"===o.contentDisposition?(this._renderbody=o.content,this._rendertype=o.contentType,Promise.resolve()):"session"!==o.contentDisposition?Promise.resolve():this.setAnswer(o,r).catch(function(e){t.logger.error(e.message);var r=["Reason: "+t.getReasonHeaderValue(488,"Bad Media Description")];n.bye(void 0,{extraHeaders:r}),t.stateTransition(SessionState.Terminated)}):Promise.resolve();case SignalingState.HaveLocalOffer:this.logger.error("Invalid signaling state ".concat(n.signalingState,"."));s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return n.bye(void 0,{extraHeaders:s}),this.stateTransition(SessionState.Terminated),Promise.resolve();case SignalingState.HaveRemoteOffer:this.logger.error("Invalid signaling state ".concat(n.signalingState,"."));s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return n.bye(void 0,{extraHeaders:s}),this.stateTransition(SessionState.Terminated),Promise.resolve();case SignalingState.Closed:default:throw new Error("Invalid signaling state ".concat(n.signalingState,"."))}},e.prototype.onByeRequest=function(e){if(this.logger.log("Session.onByeRequest"),this.state===SessionState.Established){if(this.delegate&&this.delegate.onBye){var t=new Bye(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(SessionState.Terminated)}else this.logger.error("BYE received while in state ".concat(this.state,", dropping request"))},e.prototype.onInfoRequest=function(e){if(this.logger.log("Session.onInfoRequest"),this.state===SessionState.Established)if(this.delegate&&this.delegate.onInfo){var t=new Info(e);this.delegate.onInfo(t)}else e.accept();else this.logger.error("INFO received while in state ".concat(this.state,", dropping request"))},e.prototype.onInviteRequest=function(e){var t=this;if(this.logger.log("Session.onInviteRequest"),this.state===SessionState.Established){this.pendingReinviteAck=!0;var n=["Contact: "+this._contact];if(e.message.hasHeader("P-Asserted-Identity")){var r=e.message.getHeader("P-Asserted-Identity");if(!r)throw new Error("Header undefined.");this._assertedIdentity=Grammar.nameAddrHeaderParse(r)}var i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(i).then(function(r){var i=e.accept({statusCode:200,extraHeaders:n,body:r});t.delegate&&t.delegate.onInvite&&t.delegate.onInvite(e.message,i.message,200)}).catch(function(r){if(t.logger.error(r.message),t.logger.error("Failed to handle to re-INVITE request"),!t.dialog)throw new Error("Dialog undefined.");if(t.logger.error(t.dialog.signalingState),t.dialog.signalingState!==SignalingState.Stable)t.rollbackOffer().then(function(){var n=e.reject({statusCode:488});t.delegate&&t.delegate.onInvite&&t.delegate.onInvite(e.message,n.message,488)}).catch(function(r){t.logger.error(r.message),t.logger.error("Failed to rollback offer on re-INVITE request");var i=e.reject({statusCode:488});if(t.state!==SessionState.Terminated){if(!t.dialog)throw new Error("Dialog undefined.");[].push("Reason: "+t.getReasonHeaderValue(500,"Internal Server Error")),t.dialog.bye(void 0,{extraHeaders:n}),t.stateTransition(SessionState.Terminated)}t.delegate&&t.delegate.onInvite&&t.delegate.onInvite(e.message,i.message,488)});else{var i=e.reject({statusCode:488});t.delegate&&t.delegate.onInvite&&t.delegate.onInvite(e.message,i.message,488)}})}else this.logger.error("INVITE received while in state ".concat(this.state,", dropping request"))},e.prototype.onMessageRequest=function(e){if(this.logger.log("Session.onMessageRequest"),this.state===SessionState.Established)if(this.delegate&&this.delegate.onMessage){var t=new Message(e);this.delegate.onMessage(t)}else e.accept();else this.logger.error("MESSAGE received while in state ".concat(this.state,", dropping request"))},e.prototype.onNotifyRequest=function(e){if(this.logger.log("Session.onNotifyRequest"),this.state===SessionState.Established)if(this.onNotify){var t=new Notification(e);this.onNotify(t)}else if(this.delegate&&this.delegate.onNotify){t=new Notification(e);this.delegate.onNotify(t)}else e.accept();else this.logger.error("NOTIFY received while in state ".concat(this.state,", dropping request"))},e.prototype.onPrackRequest=function(e){if(this.logger.log("Session.onPrackRequest"),this.state===SessionState.Established)throw new Error("Unimplemented.");this.logger.error("PRACK received while in state ".concat(this.state,", dropping request"))},e.prototype.onReferRequest=function(e){var t=this;if(this.logger.log("Session.onReferRequest"),this.state===SessionState.Established){if(!e.message.hasHeader("refer-to"))return this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),void e.reject();var n=new Referral(e,this);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(n):(this.logger.log("No delegate available to handle REFER, automatically accepting and following."),n.accept().then(function(){return n.makeInviter(t._referralInviterOptions).invite()}).catch(function(e){t.logger.error(e.message)}))}else this.logger.error("REFER received while in state ".concat(this.state,", dropping request"))},e.prototype.generateResponseOfferAnswer=function(e,t){if(this.dialog)return this.generateResponseOfferAnswerInDialog(t);var n=getBody(e.message);return n&&"session"===n.contentDisposition?this.setOfferAndGetAnswer(n,t):this.getOffer(t)},e.prototype.generateResponseOfferAnswerInDialog=function(e){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case SignalingState.Initial:return this.getOffer(e);case SignalingState.HaveLocalOffer:return Promise.resolve(void 0);case SignalingState.HaveRemoteOffer:if(!this.dialog.offer)throw new Error("Session offer undefined in signaling state ".concat(this.dialog.signalingState,"."));return this.setOfferAndGetAnswer(this.dialog.offer,e);case SignalingState.Stable:return this.state!==SessionState.Established?Promise.resolve(void 0):this.getOffer(e);case SignalingState.Closed:default:throw new Error("Invalid signaling state ".concat(this.dialog.signalingState,"."))}},e.prototype.getOffer=function(e){var t=this,n=this.setupSessionDescriptionHandler(),r=e.sessionDescriptionHandlerOptions,i=e.sessionDescriptionHandlerModifiers;try{return n.getDescription(r,i).then(function(e){return fromBodyLegacy(e)}).catch(function(e){t.logger.error("Session.getOffer: SDH getDescription rejected...");var n=e instanceof Error?e:new Error("Session.getOffer unknown error.");throw t.logger.error(n.message),n})}catch(e){this.logger.error("Session.getOffer: SDH getDescription threw...");var s=e instanceof Error?e:new Error(e);return this.logger.error(s.message),Promise.reject(s)}},e.prototype.rollbackOffer=function(){var e=this,t=this.setupSessionDescriptionHandler();if(void 0===t.rollbackDescription)return Promise.resolve();try{return t.rollbackDescription().catch(function(t){e.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");var n=t instanceof Error?t:new Error("Session.rollbackOffer unknown error.");throw e.logger.error(n.message),n})}catch(e){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");var n=e instanceof Error?e:new Error(e);return this.logger.error(n.message),Promise.reject(n)}},e.prototype.setAnswer=function(e,t){var n=this,r=this.setupSessionDescriptionHandler(),i=t.sessionDescriptionHandlerOptions,s=t.sessionDescriptionHandlerModifiers;try{if(!r.hasDescription(e.contentType))return Promise.reject(new ContentTypeUnsupportedError)}catch(e){this.logger.error("Session.setAnswer: SDH hasDescription threw...");var o=e instanceof Error?e:new Error(e);return this.logger.error(o.message),Promise.reject(o)}try{return r.setDescription(e.content,i,s).catch(function(e){n.logger.error("Session.setAnswer: SDH setDescription rejected...");var t=e instanceof Error?e:new Error("Session.setAnswer unknown error.");throw n.logger.error(t.message),t})}catch(e){this.logger.error("Session.setAnswer: SDH setDescription threw...");o=e instanceof Error?e:new Error(e);return this.logger.error(o.message),Promise.reject(o)}},e.prototype.setOfferAndGetAnswer=function(e,t){var n=this,r=this.setupSessionDescriptionHandler(),i=t.sessionDescriptionHandlerOptions,s=t.sessionDescriptionHandlerModifiers;try{if(!r.hasDescription(e.contentType))return Promise.reject(new ContentTypeUnsupportedError)}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");var o=e instanceof Error?e:new Error(e);return this.logger.error(o.message),Promise.reject(o)}try{return r.setDescription(e.content,i,s).then(function(){return r.getDescription(i,s)}).then(function(e){return fromBodyLegacy(e)}).catch(function(e){n.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");var t=e instanceof Error?e:new Error("Session.setOfferAndGetAnswer unknown error.");throw n.logger.error(t.message),t})}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");o=e instanceof Error?e:new Error(e);return this.logger.error(o.message),Promise.reject(o)}},e.prototype.setSessionDescriptionHandler=function(e){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=e},e.prototype.setupSessionDescriptionHandler=function(){var e;return this._sessionDescriptionHandler||(this._sessionDescriptionHandler=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions),(null===(e=this.delegate)||void 0===e?void 0:e.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler,!1)),this._sessionDescriptionHandler},e.prototype.stateTransition=function(e){var t=this,n=function(){throw new Error("Invalid state transition from ".concat(t._state," to ").concat(e))};switch(this._state){case SessionState.Initial:e!==SessionState.Establishing&&e!==SessionState.Established&&e!==SessionState.Terminating&&e!==SessionState.Terminated&&n();break;case SessionState.Establishing:e!==SessionState.Established&&e!==SessionState.Terminating&&e!==SessionState.Terminated&&n();break;case SessionState.Established:e!==SessionState.Terminating&&e!==SessionState.Terminated&&n();break;case SessionState.Terminating:e!==SessionState.Terminated&&n();break;case SessionState.Terminated:n();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log("Session ".concat(this.id," transitioned to state ").concat(this._state)),this._stateEventEmitter.emit(this._state),e===SessionState.Terminated&&this.dispose()},e.prototype.copyRequestOptions=function(e){return void 0===e&&(e={}),{extraHeaders:e.extraHeaders?e.extraHeaders.slice():void 0,body:e.body?{contentDisposition:e.body.contentDisposition||"render",contentType:e.body.contentType||"text/plain",content:e.body.content||""}:void 0}},e.prototype.getReasonHeaderValue=function(e,t){var n=e,r=getReasonPhrase(e);return!r&&t&&(r=t),"SIP;cause="+n+';text="'+r+'"'},e.prototype.referExtraHeaders=function(e){var t=[];return t.push("Referred-By: <"+this.userAgent.configuration.uri+">"),t.push("Contact: "+this._contact),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.push("Refer-To: "+e),t},e.prototype.referToString=function(e){var t;if(e instanceof URI)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");var n=e.remoteIdentity.friendlyName,r=e.dialog.remoteTarget.toString(),i=e.dialog.callId,s=e.dialog.remoteTag,o=e.dialog.localTag,a=encodeURIComponent("".concat(i,";to-tag=").concat(s,";from-tag=").concat(o));t='"'.concat(n,'" <').concat(r,"?Replaces=").concat(a,">")}return t},e}(),SIPExtension;!function(e){e.Required="Required",e.Supported="Supported",e.Unsupported="Unsupported"}(SIPExtension||(SIPExtension={}));var UserAgentRegisteredOptionTags={"100rel":!0,199:!0,answermode:!0,"early-session":!0,eventlist:!0,explicitsub:!0,"from-change":!0,"geolocation-http":!0,"geolocation-sip":!0,gin:!0,gruu:!0,histinfo:!0,ice:!0,join:!0,"multiple-refer":!0,norefersub:!0,nosub:!0,outbound:!0,path:!0,policy:!0,precondition:!0,pref:!0,privacy:!0,"recipient-list-invite":!0,"recipient-list-message":!0,"recipient-list-subscribe":!0,replaces:!0,"resource-priority":!0,"sdp-anat":!0,"sec-agree":!0,tdialog:!0,timer:!0,uui:!0},Invitation=function(e){function t(t,n){var r=e.call(this,t)||this;r.incomingInviteRequest=n,r.disposed=!1,r.expiresTimer=void 0,r.isCanceled=!1,r.rel100="none",r.rseq=Math.floor(1e4*Math.random()),r.userNoAnswerTimer=void 0,r.waitingForPrack=!1,r.logger=t.getLogger("sip.Invitation");var i=r.incomingInviteRequest.message,s=i.getHeader("require");s&&s.toLowerCase().includes("100rel")&&(r.rel100="required");var o=i.getHeader("supported");if(o&&o.toLowerCase().includes("100rel")&&(r.rel100="supported"),i.toTag=n.toTag,"string"!=typeof i.toTag)throw new TypeError("toTag should have been a string.");if(r.userNoAnswerTimer=setTimeout(function(){n.reject({statusCode:480}),r.stateTransition(SessionState.Terminated)},r.userAgent.configuration.noAnswerTimeout?1e3*r.userAgent.configuration.noAnswerTimeout:6e4),i.hasHeader("expires")){var a=1e3*Number(i.getHeader("expires")||0);r.expiresTimer=setTimeout(function(){r.state===SessionState.Initial&&(n.reject({statusCode:487}),r.stateTransition(SessionState.Terminated))},a)}var c=r.request.getHeader("P-Asserted-Identity");c&&(r._assertedIdentity=Grammar.nameAddrHeaderParse(c)),r._contact=r.userAgent.contact.toString();var u=i.parseHeader("Content-Disposition");return u&&"render"===u.type&&(r._renderbody=i.body,r._rendertype=i.getHeader("Content-Type")),r._id=i.callId+i.fromTag,r.userAgent._sessions[r._id]=r,r}return __extends$1(t,e),t.prototype.dispose=function(){var t=this;if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.expiresTimer&&(clearTimeout(this.expiresTimer),this.expiresTimer=void 0),this.userNoAnswerTimer&&(clearTimeout(this.userNoAnswerTimer),this.userNoAnswerTimer=void 0),this.prackNeverArrived(),this.state){case SessionState.Initial:case SessionState.Establishing:return this.reject().then(function(){return e.prototype.dispose.call(t)});case SessionState.Established:case SessionState.Terminating:case SessionState.Terminated:return e.prototype.dispose.call(this);default:throw new Error("Unknown state.")}},Object.defineProperty(t.prototype,"autoSendAnInitialProvisionalResponse",{get:function(){return"required"!==this.rel100&&this.userAgent.configuration.sendInitialProvisionalResponse},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"body",{get:function(){return this.incomingInviteRequest.message.body},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"localIdentity",{get:function(){return this.request.to},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"remoteIdentity",{get:function(){return this.request.from},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"request",{get:function(){return this.incomingInviteRequest.message},enumerable:!1,configurable:!0}),t.prototype.accept=function(e){var t=this;if(void 0===e&&(e={}),this.logger.log("Invitation.accept"),this.state!==SessionState.Initial){var n=new Error("Invalid session state ".concat(this.state));return this.logger.error(n.message),Promise.reject(n)}return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.stateTransition(SessionState.Establishing),this.sendAccept(e).then(function(e){e.message;var n=e.session;n.delegate={onAck:function(e){return t.onAckRequest(e)},onAckTimeout:function(){return t.onAckTimeout()},onBye:function(e){return t.onByeRequest(e)},onInfo:function(e){return t.onInfoRequest(e)},onInvite:function(e){return t.onInviteRequest(e)},onMessage:function(e){return t.onMessageRequest(e)},onNotify:function(e){return t.onNotifyRequest(e)},onPrack:function(e){return t.onPrackRequest(e)},onRefer:function(e){return t.onReferRequest(e)}},t._dialog=n,t.stateTransition(SessionState.Established),t._replacee&&t._replacee._bye()}).catch(function(e){return t.handleResponseError(e)})},t.prototype.progress=function(e){var t=this;if(void 0===e&&(e={}),this.logger.log("Invitation.progress"),this.state!==SessionState.Initial){var n=new Error("Invalid session state ".concat(this.state));return this.logger.error(n.message),Promise.reject(n)}var r=e.statusCode||180;if(r<100||r>199)throw new TypeError("Invalid statusCode: "+r);return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.waitingForPrack?(this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),Promise.resolve()):100===e.statusCode?this.sendProgressTrying().then(function(){}).catch(function(e){return t.handleResponseError(e)}):"required"===this.rel100||"supported"===this.rel100&&e.rel100||"supported"===this.rel100&&this.userAgent.configuration.sipExtension100rel===SIPExtension.Required?this.sendProgressReliableWaitForPrack(e).then(function(){}).catch(function(e){return t.handleResponseError(e)}):this.sendProgress(e).then(function(){}).catch(function(e){return t.handleResponseError(e)})},t.prototype.reject=function(e){if(void 0===e&&(e={}),this.logger.log("Invitation.reject"),this.state!==SessionState.Initial&&this.state!==SessionState.Establishing){var t=new Error("Invalid session state ".concat(this.state));return this.logger.error(t.message),Promise.reject(t)}var n=e.statusCode||480,r=e.reasonPhrase?e.reasonPhrase:getReasonPhrase(n),i=e.extraHeaders||[];if(n<300||n>699)throw new TypeError("Invalid statusCode: "+n);var s=e.body?fromBodyLegacy(e.body):void 0;return n<400?this.incomingInviteRequest.redirect([],{statusCode:n,reasonPhrase:r,extraHeaders:i,body:s}):this.incomingInviteRequest.reject({statusCode:n,reasonPhrase:r,extraHeaders:i,body:s}),this.stateTransition(SessionState.Terminated),Promise.resolve()},t.prototype._onCancel=function(e){this.logger.log("Invitation._onCancel"),this.state===SessionState.Initial||this.state===SessionState.Establishing?(this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(SessionState.Terminated)):this.logger.error("CANCEL received while in state ".concat(this.state,", dropping request"))},t.prototype.handlePrackOfferAnswer=function(e){if(!this.dialog)throw new Error("Dialog undefined.");var t=getBody(e.message);if(!t||"session"!==t.contentDisposition)return Promise.resolve(void 0);var n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case SignalingState.Initial:throw new Error("Invalid signaling state ".concat(this.dialog.signalingState,"."));case SignalingState.Stable:return this.setAnswer(t,n).then(function(){});case SignalingState.HaveLocalOffer:throw new Error("Invalid signaling state ".concat(this.dialog.signalingState,"."));case SignalingState.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,n);case SignalingState.Closed:default:throw new Error("Invalid signaling state ".concat(this.dialog.signalingState,"."))}},t.prototype.handleResponseError=function(e){var t=480;if(e instanceof Error?this.logger.error(e.message):this.logger.error(e),e instanceof ContentTypeUnsupportedError?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof SessionDescriptionHandlerError?this.logger.error("A session description handler occurred while sending response"):e instanceof SessionTerminatedError?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof TransactionStateError&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===SessionState.Initial||this.state===SessionState.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(SessionState.Terminated)}catch(e){throw this.logger.error("An error occurred attempting to reject the request while handling another error"),e}if(!this.isCanceled)throw e;this.logger.warn("An error occurred while attempting to formulate and send a response to an incoming INVITE. However a CANCEL was received and processed while doing so which can (and often does) result in errors occurring as the session terminates in the meantime. Said error is being ignored.")},t.prototype.onAckTimeout=function(){if(this.logger.log("Invitation.onAckTimeout"),!this.dialog)throw new Error("Dialog undefined.");this.logger.log("No ACK received for an extended period of time, terminating session"),this.dialog.bye(),this.stateTransition(SessionState.Terminated)},t.prototype.sendAccept=function(e){var t=this;void 0===e&&(e={});var n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},r=e.extraHeaders||[];return this.waitingForPrack?this.waitForArrivalOfPrack().then(function(){return clearTimeout(t.userNoAnswerTimer)}).then(function(){return t.generateResponseOfferAnswer(t.incomingInviteRequest,n)}).then(function(e){return t.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:r})}):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,n).then(function(e){return t.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:r})}))},t.prototype.sendProgress=function(e){void 0===e&&(e={});var t=e.statusCode||180,n=e.reasonPhrase,r=(e.extraHeaders||[]).slice(),i=e.body?fromBodyLegacy(e.body):void 0;if(183===t&&!i)return this.sendProgressWithSDP(e);try{var s=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:n,extraHeaders:r,body:i});return this._dialog=s.session,Promise.resolve(s)}catch(e){return Promise.reject(e)}},t.prototype.sendProgressWithSDP=function(e){var t=this;void 0===e&&(e={});var n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},r=e.statusCode||183,i=e.reasonPhrase,s=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,n).then(function(e){return t.incomingInviteRequest.progress({statusCode:r,reasonPhrase:i,extraHeaders:s,body:e})}).then(function(e){return t._dialog=e.session,e})},t.prototype.sendProgressReliable=function(e){return void 0===e&&(e={}),e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this.sendProgressWithSDP(e)},t.prototype.sendProgressReliableWaitForPrack=function(e){var t=this;void 0===e&&(e={});var n,r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.statusCode||183,s=e.reasonPhrase,o=(e.extraHeaders||[]).slice();return o.push("Require: 100rel"),o.push("RSeq: "+this.rseq++),new Promise(function(e,a){t.waitingForPrack=!0,t.generateResponseOfferAnswer(t.incomingInviteRequest,r).then(function(e){return n=e,t.incomingInviteRequest.progress({statusCode:i,reasonPhrase:s,extraHeaders:o,body:n})}).then(function(r){var c,u;t._dialog=r.session,r.session.delegate={onPrack:function(n){c=n,clearTimeout(l),clearTimeout(p),t.waitingForPrack&&(t.waitingForPrack=!1,t.handlePrackOfferAnswer(c).then(function(n){try{u=c.accept({statusCode:200,body:n}),t.prackArrived(),e({prackRequest:c,prackResponse:u,progressResponse:r})}catch(e){a(e)}}).catch(function(e){return a(e)}))}};var l=setTimeout(function(){t.waitingForPrack&&(t.waitingForPrack=!1,t.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(p),t.reject({statusCode:504}).then(function(){return a(new SessionTerminatedError)}).catch(function(e){return a(e)}))},64*Timers.T1),h=function(){try{t.incomingInviteRequest.progress({statusCode:i,reasonPhrase:s,extraHeaders:o,body:n})}catch(e){return t.waitingForPrack=!1,void a(e)}p=setTimeout(h,d*=2)},d=Timers.T1,p=setTimeout(h,d)}).catch(function(e){t.waitingForPrack=!1,a(e)})})},t.prototype.sendProgressTrying=function(){try{var e=this.incomingInviteRequest.trying();return Promise.resolve(e)}catch(e){return Promise.reject(e)}},t.prototype.waitForArrivalOfPrack=function(){var e=this;if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise(function(t,n){e.waitingForPrackResolve=t,e.waitingForPrackReject=n}),this.waitingForPrackPromise},t.prototype.prackArrived=function(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0},t.prototype.prackNeverArrived=function(){this.waitingForPrackReject&&this.waitingForPrackReject(new SessionTerminatedError),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0},t}(Session),Inviter=function(e){function t(t,n,r){void 0===r&&(r={});var i=e.call(this,t,r)||this;i.disposed=!1,i.earlyMedia=!1,i.earlyMediaSessionDescriptionHandlers=new Map,i.isCanceled=!1,i.inviteWithoutSdp=!1,i.logger=t.getLogger("sip.Inviter"),i.earlyMedia=void 0!==r.earlyMedia?r.earlyMedia:i.earlyMedia,i.fromTag=newTag(),i.inviteWithoutSdp=void 0!==r.inviteWithoutSdp?r.inviteWithoutSdp:i.inviteWithoutSdp;var s=__assign({},r);s.params=__assign({},r.params);var o=r.anonymous||!1,a=t.contact.toString({anonymous:o,outbound:o?!t.contact.tempGruu:!t.contact.pubGruu});o&&t.configuration.uri&&(s.params.fromDisplayName="Anonymous",s.params.fromUri="sip:anonymous@anonymous.invalid");var c=t.userAgentCore.configuration.aor;if(s.params.fromUri&&(c="string"==typeof s.params.fromUri?Grammar.URIParse(s.params.fromUri):s.params.fromUri),!c)throw new TypeError("Invalid from URI: "+s.params.fromUri);var u=n;if(s.params.toUri&&(u="string"==typeof s.params.toUri?Grammar.URIParse(s.params.toUri):s.params.toUri),!u)throw new TypeError("Invalid to URI: "+s.params.toUri);var l=__assign({},s.params);l.fromTag=i.fromTag;var h=(s.extraHeaders||[]).slice();o&&t.configuration.uri&&(h.push("P-Preferred-Identity: "+t.configuration.uri.toString()),h.push("Privacy: id")),h.push("Contact: "+a),h.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.configuration.sipExtension100rel===SIPExtension.Required&&h.push("Require: 100rel"),t.configuration.sipExtensionReplaces===SIPExtension.Required&&h.push("Require: replaces"),s.extraHeaders=h;return i.outgoingRequestMessage=t.userAgentCore.makeOutgoingRequestMessage(C.INVITE,n,c,u,l,h,undefined),i._contact=a,i._referralInviterOptions=s,i._renderbody=r.renderbody,i._rendertype=r.rendertype,r.sessionDescriptionHandlerModifiers&&(i.sessionDescriptionHandlerModifiers=r.sessionDescriptionHandlerModifiers),r.sessionDescriptionHandlerOptions&&(i.sessionDescriptionHandlerOptions=r.sessionDescriptionHandlerOptions),r.sessionDescriptionHandlerModifiersReInvite&&(i.sessionDescriptionHandlerModifiersReInvite=r.sessionDescriptionHandlerModifiersReInvite),r.sessionDescriptionHandlerOptionsReInvite&&(i.sessionDescriptionHandlerOptionsReInvite=r.sessionDescriptionHandlerOptionsReInvite),i._id=i.outgoingRequestMessage.callId+i.fromTag,i.userAgent._sessions[i._id]=i,i}return __extends$1(t,e),t.prototype.dispose=function(){var t=this;if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.disposeEarlyMedia(),this.state){case SessionState.Initial:case SessionState.Establishing:return this.cancel().then(function(){return e.prototype.dispose.call(t)});case SessionState.Established:case SessionState.Terminating:case SessionState.Terminated:return e.prototype.dispose.call(this);default:throw new Error("Unknown state.")}},Object.defineProperty(t.prototype,"body",{get:function(){return this.outgoingRequestMessage.body},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"localIdentity",{get:function(){return this.outgoingRequestMessage.from},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"remoteIdentity",{get:function(){return this.outgoingRequestMessage.to},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"request",{get:function(){return this.outgoingRequestMessage},enumerable:!1,configurable:!0}),t.prototype.cancel=function(e){if(void 0===e&&(e={}),this.logger.log("Inviter.cancel"),this.state!==SessionState.Initial&&this.state!==SessionState.Establishing){var t=new Error("Invalid session state ".concat(this.state));return this.logger.error(t.message),Promise.reject(t)}if(this.isCanceled=!0,this.stateTransition(SessionState.Terminating),this.outgoingInviteRequest){var n=void 0;e.statusCode&&e.reasonPhrase&&(n=function(e,t){if(e&&e<200||e>699)throw new TypeError("Invalid statusCode: "+e);if(e)return"SIP;cause="+e+';text="'+(getReasonPhrase(e)||t)+'"'}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(n,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(SessionState.Terminated);return Promise.resolve()},t.prototype.invite=function(t){var n=this;if(void 0===t&&(t={}),this.logger.log("Inviter.invite"),this.state!==SessionState.Initial)return e.prototype.invite.call(this,t);if(t.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=t.sessionDescriptionHandlerModifiers),t.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=t.sessionDescriptionHandlerOptions),t.withoutSdp||this.inviteWithoutSdp)return this._renderbody&&this._rendertype&&(this.outgoingRequestMessage.body={contentType:this._rendertype,body:this._renderbody}),this.stateTransition(SessionState.Establishing),Promise.resolve(this.sendInvite(t));var r={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(r).then(function(e){return n.outgoingRequestMessage.body={body:e.content,contentType:e.contentType},n.stateTransition(SessionState.Establishing),n.sendInvite(t)}).catch(function(e){throw n.logger.log(e.message),n.stateTransition(SessionState.Terminated),e})},t.prototype.sendInvite=function(e){var t=this;return void 0===e&&(e={}),this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:function(n){return t.dialog?(t.logger.log("Additional confirmed dialog, sending ACK and BYE"),void t.ackAndBye(n)):t.isCanceled?(t.logger.log("Canceled session accepted, sending ACK and BYE"),t.ackAndBye(n),void t.stateTransition(SessionState.Terminated)):(t.notifyReferer(n),void t.onAccept(n).then(function(){t.disposeEarlyMedia()}).catch(function(){t.disposeEarlyMedia()}).then(function(){e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(n)}))},onProgress:function(n){t.isCanceled||(t.notifyReferer(n),t.onProgress(n).catch(function(){t.disposeEarlyMedia()}).then(function(){e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(n)}))},onRedirect:function(n){t.notifyReferer(n),t.onRedirect(n),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(n)},onReject:function(n){t.notifyReferer(n),t.onReject(n),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(n)},onTrying:function(n){t.notifyReferer(n),t.onTrying(n),e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(n)}}),this.outgoingInviteRequest},t.prototype.disposeEarlyMedia=function(){this.earlyMediaSessionDescriptionHandlers.forEach(function(e){e.close()}),this.earlyMediaSessionDescriptionHandlers.clear()},t.prototype.notifyReferer=function(e){var t=this;if(this._referred){if(!(this._referred instanceof Session))throw new Error("Referred session not instance of session");if(this._referred.dialog){if(!e.message.statusCode)throw new Error("Status code undefined.");if(!e.message.reasonPhrase)throw new Error("Reason phrase undefined.");var n=e.message.statusCode,r=e.message.reasonPhrase,i="SIP/2.0 ".concat(n," ").concat(r).trim();this._referred.dialog.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:i}}).delegate={onReject:function(){t._referred=void 0}}}}},t.prototype.onAccept=function(e){var t=this;if(this.logger.log("Inviter.onAccept"),this.state!==SessionState.Establishing)return this.logger.error("Accept received while in state ".concat(this.state,", dropping response")),Promise.reject(new Error("Invalid session state ".concat(this.state)));var n=e.message,r=e.session;switch(n.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=Grammar.nameAddrHeaderParse(n.getHeader("P-Asserted-Identity"))),r.delegate={onAck:function(e){return t.onAckRequest(e)},onBye:function(e){return t.onByeRequest(e)},onInfo:function(e){return t.onInfoRequest(e)},onInvite:function(e){return t.onInviteRequest(e)},onMessage:function(e){return t.onMessageRequest(e)},onNotify:function(e){return t.onNotifyRequest(e)},onPrack:function(e){return t.onPrackRequest(e)},onRefer:function(e){return t.onReferRequest(e)}},this._dialog=r,r.signalingState){case SignalingState.Initial:case SignalingState.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(SessionState.Terminated),Promise.reject(new Error("Bad Media Description"));case SignalingState.HaveRemoteOffer:if(!this._dialog.offer)throw new Error("Session offer undefined in signaling state ".concat(this._dialog.signalingState,"."));var i={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,i).then(function(n){e.ack({body:n}),t.stateTransition(SessionState.Established)}).catch(function(n){throw t.ackAndBye(e,488,"Invalid session description"),t.stateTransition(SessionState.Terminated),n});case SignalingState.Stable:if(this.earlyMediaSessionDescriptionHandlers.size>0){var s=this.earlyMediaSessionDescriptionHandlers.get(r.id);if(!s)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(s),this.earlyMediaSessionDescriptionHandlers.delete(r.id),e.ack(),this.stateTransition(SessionState.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==r){if(this.earlyMedia){this.logger.error("You have set the 'earlyMedia' option to 'true' which requires that your INVITE requests do not fork and yet this INVITE request did in fact fork. Consequentially and not surprisingly the end point which accepted the INVITE (confirmed dialog) does not match the end point with which early media has been setup (early dialog) and thus this session is unable to proceed. In accordance with the SIP specifications, the SIP servers your end point is connected to determine if an INVITE forks and the forking behavior of those servers cannot be controlled by this library. If you wish to use early media with this library you must configure those servers accordingly. Alternatively you may set the 'earlyMedia' to 'false' which will allow this library to function with any INVITE requests which do fork.")}var o=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(o.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(SessionState.Terminated),Promise.reject(o)}return e.ack(),this.stateTransition(SessionState.Established),Promise.resolve()}var a=r.answer;if(!a)throw new Error("Answer is undefined.");i={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(a,i).then(function(){var n;t._renderbody&&t._rendertype&&(n={body:{contentDisposition:"render",contentType:t._rendertype,content:t._renderbody}}),e.ack(n),t.stateTransition(SessionState.Established)}).catch(function(n){throw t.logger.error(n.message),t.ackAndBye(e,488,"Not Acceptable Here"),t.stateTransition(SessionState.Terminated),n});case SignalingState.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}},t.prototype.onProgress=function(e){var t,n=this;if(this.logger.log("Inviter.onProgress"),this.state!==SessionState.Establishing)return this.logger.error("Progress received while in state ".concat(this.state,", dropping response")),Promise.reject(new Error("Invalid session state ".concat(this.state)));if(!this.outgoingInviteRequest)throw new Error("Outgoing INVITE request undefined.");var r=e.message,i=e.session;r.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=Grammar.nameAddrHeaderParse(r.getHeader("P-Asserted-Identity")));var s=r.getHeader("require"),o=r.getHeader("rseq"),a=!!(s&&s.includes("100rel")&&o?Number(o):void 0),c=[];switch(a&&c.push("RAck: "+r.getHeader("rseq")+" "+r.getHeader("cseq")),i.signalingState){case SignalingState.Initial:return a&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:c})),Promise.resolve();case SignalingState.HaveLocalOffer:return a&&e.prack({extraHeaders:c}),Promise.resolve();case SignalingState.HaveRemoteOffer:if(!a)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();var u=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(t=this.delegate)||void 0===t?void 0:t.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(u,!0),this.earlyMediaSessionDescriptionHandlers.set(i.id,u),u.setDescription(r.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then(function(){return u.getDescription(n.sessionDescriptionHandlerOptions,n.sessionDescriptionHandlerModifiers)}).then(function(t){var n={contentDisposition:"session",contentType:t.contentType,content:t.body};e.prack({extraHeaders:c,body:n})}).catch(function(e){throw n.stateTransition(SessionState.Terminated),e});case SignalingState.Stable:if(a&&e.prack({extraHeaders:c}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=i;var l=i.answer;if(!l)throw new Error("Answer is undefined.");var h={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(l,h).catch(function(e){throw n.stateTransition(SessionState.Terminated),e})}return Promise.resolve();case SignalingState.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}},t.prototype.onRedirect=function(e){this.logger.log("Inviter.onRedirect"),this.state===SessionState.Establishing||this.state===SessionState.Terminating?this.stateTransition(SessionState.Terminated):this.logger.error("Redirect received while in state ".concat(this.state,", dropping response"))},t.prototype.onReject=function(e){this.logger.log("Inviter.onReject"),this.state===SessionState.Establishing||this.state===SessionState.Terminating?this.stateTransition(SessionState.Terminated):this.logger.error("Reject received while in state ".concat(this.state,", dropping response"))},t.prototype.onTrying=function(e){this.logger.log("Inviter.onTrying"),this.state===SessionState.Establishing||this.logger.error("Trying received while in state ".concat(this.state,", dropping response"))},t}(Session),Messager=function(){function e(e,t,n,r,i){void 0===r&&(r="text/plain"),void 0===i&&(i={}),this.logger=e.getLogger("sip.Messager"),i.params=i.params||{};var s=e.userAgentCore.configuration.aor;if(i.params.fromUri&&(s="string"==typeof i.params.fromUri?Grammar.URIParse(i.params.fromUri):i.params.fromUri),!s)throw new TypeError("Invalid from URI: "+i.params.fromUri);var o=t;if(i.params.toUri&&(o="string"==typeof i.params.toUri?Grammar.URIParse(i.params.toUri):i.params.toUri),!o)throw new TypeError("Invalid to URI: "+i.params.toUri);var a=i.params?__assign({},i.params):{},c=(i.extraHeaders||[]).slice(),u={contentDisposition:"render",contentType:r,content:n};this.request=e.userAgentCore.makeOutgoingRequestMessage(C.MESSAGE,t,s,o,a,c,u),this.userAgent=e}return e.prototype.message=function(e){return void 0===e&&(e={}),this.userAgent.userAgentCore.request(this.request,e.requestDelegate),Promise.resolve()},e}(),PublisherState,RegistererState;!function(e){e.Initial="Initial",e.Published="Published",e.Unpublished="Unpublished",e.Terminated="Terminated"}(PublisherState||(PublisherState={})),function(){function e(e,t,n,r){void 0===r&&(r={}),this.disposed=!1,this._state=PublisherState.Initial,this._stateEventEmitter=new EmitterImpl,this.userAgent=e,r.extraHeaders=(r.extraHeaders||[]).slice(),r.contentType=r.contentType||"text/plain","number"!=typeof r.expires||r.expires%1!=0?r.expires=3600:r.expires=Number(r.expires),"boolean"!=typeof r.unpublishOnClose&&(r.unpublishOnClose=!0),this.target=t,this.event=n,this.options=r,this.pubRequestExpires=r.expires,this.logger=e.getLogger("sip.Publisher");var i,s=r.params||{},o=s.fromUri?s.fromUri:e.userAgentCore.configuration.aor,a=s.toUri?s.toUri:t;if(r.body&&r.contentType){i={contentDisposition:"render",contentType:r.contentType,content:r.body}}var c=(r.extraHeaders||[]).slice();this.request=e.userAgentCore.makeOutgoingRequestMessage(C.PUBLISH,t,o,a,s,c,i),this.id=this.target.toString()+":"+this.event,this.userAgent._publishers[this.id]=this}e.prototype.dispose=function(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log("Publisher ".concat(this.id," in state ").concat(this.state," is being disposed")),delete this.userAgent._publishers[this.id],this.options.unpublishOnClose&&this.state===PublisherState.Published?this.unpublish():(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,this.pubRequestEtag=void 0,Promise.resolve()))},Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),e.prototype.publish=function(e,t){if(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.options.body=e,this.pubRequestBody=this.options.body,0===this.pubRequestExpires){if(void 0===this.options.expires)throw new Error("Expires undefined.");this.pubRequestExpires=this.options.expires,this.pubRequestEtag=void 0}return this.sendPublishRequest(),Promise.resolve()},e.prototype.unpublish=function(e){return this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,void 0!==this.pubRequestEtag&&this.sendPublishRequest(),Promise.resolve()},e.prototype.receiveResponse=function(e){var t=this,n=e.statusCode||0;switch(!0){case/^1[0-9]{2}$/.test(n.toString()):break;case/^2[0-9]{2}$/.test(n.toString()):if(e.hasHeader("SIP-ETag")?this.pubRequestEtag=e.getHeader("SIP-ETag"):this.logger.warn("SIP-ETag header missing in a 200-class response to PUBLISH"),e.hasHeader("Expires")){var r=Number(e.getHeader("Expires"));"number"==typeof r&&r>=0&&r<=this.pubRequestExpires?this.pubRequestExpires=r:this.logger.warn("Bad Expires header in a 200-class response to PUBLISH")}else this.logger.warn("Expires header missing in a 200-class response to PUBLISH");0!==this.pubRequestExpires?(this.publishRefreshTimer=setTimeout(function(){return t.refreshRequest()},900*this.pubRequestExpires),this._state!==PublisherState.Published&&this.stateTransition(PublisherState.Published)):this.stateTransition(PublisherState.Unpublished);break;case/^412$/.test(n.toString()):if(void 0!==this.pubRequestEtag&&0!==this.pubRequestExpires){if(this.logger.warn("412 response to PUBLISH, recovering"),this.pubRequestEtag=void 0,void 0===this.options.body)throw new Error("Body undefined.");this.publish(this.options.body)}else this.logger.warn("412 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.stateTransition(PublisherState.Unpublished),this.stateTransition(PublisherState.Terminated);break;case/^423$/.test(n.toString()):if(0!==this.pubRequestExpires&&e.hasHeader("Min-Expires")){var i=Number(e.getHeader("Min-Expires"));if("number"==typeof i||i>this.pubRequestExpires){if(this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"),this.pubRequestExpires=i,void 0===this.options.body)throw new Error("Body undefined.");this.publish(this.options.body)}else this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"),this.pubRequestExpires=0,this.stateTransition(PublisherState.Unpublished),this.stateTransition(PublisherState.Terminated)}else this.logger.warn("423 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.stateTransition(PublisherState.Unpublished),this.stateTransition(PublisherState.Terminated);break;default:this.pubRequestExpires=0,this.stateTransition(PublisherState.Unpublished),this.stateTransition(PublisherState.Terminated)}0===this.pubRequestExpires&&(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestEtag=void 0)},e.prototype.send=function(){var e=this;return this.userAgent.userAgentCore.publish(this.request,{onAccept:function(t){return e.receiveResponse(t.message)},onProgress:function(t){return e.receiveResponse(t.message)},onRedirect:function(t){return e.receiveResponse(t.message)},onReject:function(t){return e.receiveResponse(t.message)},onTrying:function(t){return e.receiveResponse(t.message)}})},e.prototype.refreshRequest=function(){if(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,void 0===this.pubRequestEtag)throw new Error("Etag undefined");if(0===this.pubRequestExpires)throw new Error("Expires zero");this.sendPublishRequest()},e.prototype.sendPublishRequest=function(){var e=__assign({},this.options);e.extraHeaders=(this.options.extraHeaders||[]).slice(),e.extraHeaders.push("Event: "+this.event),e.extraHeaders.push("Expires: "+this.pubRequestExpires),void 0!==this.pubRequestEtag&&e.extraHeaders.push("SIP-If-Match: "+this.pubRequestEtag);var t,n,r=this.target,i=this.options.params||{};if(void 0!==this.pubRequestBody){if(void 0===this.options.contentType)throw new Error("Content type undefined.");t={body:this.pubRequestBody,contentType:this.options.contentType}}return t&&(n=fromBodyLegacy(t)),this.request=this.userAgent.userAgentCore.makeOutgoingRequestMessage(C.PUBLISH,r,i.fromUri?i.fromUri:this.userAgent.userAgentCore.configuration.aor,i.toUri?i.toUri:this.target,i,e.extraHeaders,n),this.send()},e.prototype.stateTransition=function(e){var t=this,n=function(){throw new Error("Invalid state transition from ".concat(t._state," to ").concat(e))};switch(this._state){case PublisherState.Initial:e!==PublisherState.Published&&e!==PublisherState.Unpublished&&e!==PublisherState.Terminated&&n();break;case PublisherState.Published:e!==PublisherState.Unpublished&&e!==PublisherState.Terminated&&n();break;case PublisherState.Unpublished:e!==PublisherState.Published&&e!==PublisherState.Terminated&&n();break;case PublisherState.Terminated:n();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log("Publication transitioned to state ".concat(this._state)),this._stateEventEmitter.emit(this._state),e===PublisherState.Terminated&&this.dispose()}}(),function(e){e.Initial="Initial",e.Registered="Registered",e.Unregistered="Unregistered",e.Terminated="Terminated"}(RegistererState||(RegistererState={}));var Registerer=function(){function e(t,n){void 0===n&&(n={});var r=this;this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=RegistererState.Initial,this._waiting=!1,this._stateEventEmitter=new EmitterImpl,this._waitingEventEmitter=new EmitterImpl,this.userAgent=t;var i=t.configuration.uri.clone();if(i.user=void 0,this.options=__assign(__assign(__assign({},e.defaultOptions()),{registrar:i}),e.stripUndefinedProperties(n)),this.options.extraContactHeaderParams=(this.options.extraContactHeaderParams||[]).slice(),this.options.extraHeaders=(this.options.extraHeaders||[]).slice(),!this.options.registrar)throw new Error("Registrar undefined.");if(this.options.registrar=this.options.registrar.clone(),this.options.regId&&!this.options.instanceId?this.options.instanceId=e.newUUID():!this.options.regId&&this.options.instanceId&&(this.options.regId=1),this.options.instanceId&&-1===Grammar.parse(this.options.instanceId,"uuid"))throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");var s=this.options.registrar,o=this.options.params&&this.options.params.fromUri||t.userAgentCore.configuration.aor,a=this.options.params&&this.options.params.toUri||t.configuration.uri,c=this.options.params||{},u=(n.extraHeaders||[]).slice();if(this.request=t.userAgentCore.makeOutgoingRequestMessage(C.REGISTER,s,o,a,c,u,void 0),this.expires=this.options.expires||e.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||e.defaultRefreshFrequency,this.refreshFrequency<50||this.refreshFrequency>99)throw new Error("Invalid refresh frequency. The value represents a percentage of the expiration time and should be between 50 and 99.");this.logger=t.getLogger("sip.Registerer"),this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(function(e){var t=r.options[e];if("registrar"===e)r.logger.log("· "+e+": "+t);else r.logger.log("· "+e+": "+JSON.stringify(t))})),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}return e.defaultOptions=function(){return{expires:e.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new URI("sip","anonymous","anonymous.invalid"),refreshFrequency:e.defaultRefreshFrequency}},e.newUUID=function(){var e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=Math.floor(16*Math.random());return("x"===e?t:t%4+8).toString(16)});return e},e.stripUndefinedProperties=function(e){return Object.keys(e).reduce(function(t,n){return void 0!==e[n]&&(t[n]=e[n]),t},{})},Object.defineProperty(e.prototype,"contacts",{get:function(){return this._contacts.slice()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"retryAfter",{get:function(){return this._retryAfter},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){var e=this;return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log("Registerer ".concat(this.id," in state ").concat(this.state," is being disposed")),delete this.userAgent._registerers[this.id],new Promise(function(t){var n=function(){if(!e.waiting&&e._state===RegistererState.Registered)return e.stateChange.addListener(function(){e.terminated(),t()},{once:!0}),void e.unregister();e.terminated(),t()};e.waiting?e.waitingChange.addListener(function(){n()},{once:!0}):n()}))},e.prototype.register=function(e){var t=this;if(void 0===e&&(e={}),this.state===RegistererState.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();var n=new RequestPendingError("REGISTER request already in progress, waiting for final response");return Promise.reject(n)}e.requestOptions&&(this.options=__assign(__assign({},this.options),e.requestOptions));var r=(this.options.extraHeaders||[]).slice();r.push("Contact: "+this.generateContactHeader(this.expires)),r.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),this.request.extraHeaders=r,this.waitingToggle(!0);var i=this.userAgent.userAgentCore.register(this.request,{onAccept:function(n){var r;n.message.hasHeader("expires")&&(r=Number(n.message.getHeader("expires"))),t._contacts=n.message.getHeaders("contact");var i,s,o=t._contacts.length;if(!o)return t.logger.error("No Contact header in response to REGISTER, dropping response."),void t.unregistered();for(;o--;){if(!(i=n.message.parseHeader("contact",o)))throw new Error("Contact undefined");if(t.userAgent.contact.pubGruu&&equivalentURI(i.uri,t.userAgent.contact.pubGruu)){r=Number(i.getParam("expires"));break}if(""===t.userAgent.configuration.contactName){if(i.uri.user===t.userAgent.contact.uri.user){r=Number(i.getParam("expires"));break}}else if(equivalentURI(i.uri,t.userAgent.contact.uri)){r=Number(i.getParam("expires"));break}i=void 0}if(void 0===i)return t.logger.error("No Contact header pointing to us, dropping response"),t.unregistered(),void t.waitingToggle(!1);if(void 0===r)return t.logger.error("Contact pointing to us is missing expires parameter, dropping response"),t.unregistered(),void t.waitingToggle(!1);i.hasParam("temp-gruu")&&((s=i.getParam("temp-gruu"))&&(t.userAgent.contact.tempGruu=Grammar.URIParse(s.replace(/"/g,""))));i.hasParam("pub-gruu")&&((s=i.getParam("pub-gruu"))&&(t.userAgent.contact.pubGruu=Grammar.URIParse(s.replace(/"/g,""))));t.registered(r),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(n),t.waitingToggle(!1)},onProgress:function(t){e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:function(n){t.logger.error("Redirect received. Not supported."),t.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(n),t.waitingToggle(!1)},onReject:function(n){if(423===n.message.statusCode)return n.message.hasHeader("min-expires")?(t.expires=Number(n.message.getHeader("min-expires")),t.waitingToggle(!1),void t.register()):(t.logger.error("423 response received for REGISTER without Min-Expires, dropping response"),t.unregistered(),void t.waitingToggle(!1));t.logger.warn("Failed to register, status code ".concat(n.message.statusCode));var r=NaN;if(500===n.message.statusCode||503===n.message.statusCode){var i=n.message.getHeader("retry-after");i&&(r=Number.parseInt(i,void 0))}t._retryAfter=isNaN(r)?void 0:r,t.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(n),t._retryAfter=void 0,t.waitingToggle(!1)},onTrying:function(t){e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(i)},e.prototype.unregister=function(e){var t=this;if(void 0===e&&(e={}),this.state===RegistererState.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==RegistererState.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();var n=new RequestPendingError("REGISTER request already in progress, waiting for final response");return Promise.reject(n)}this._state===RegistererState.Registered||e.all||this.logger.warn("Not currently registered, but sending an unregister anyway.");var r=(e.requestOptions&&e.requestOptions.extraHeaders||[]).slice();this.request.extraHeaders=r,e.all?(r.push("Contact: *"),r.push("Expires: 0")):r.push("Contact: "+this.generateContactHeader(0)),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),this.waitingToggle(!0);var i=this.userAgent.userAgentCore.register(this.request,{onAccept:function(n){t._contacts=n.message.getHeaders("contact"),t.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(n),t.waitingToggle(!1)},onProgress:function(t){e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:function(n){t.logger.error("Unregister redirected. Not currently supported."),t.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(n),t.waitingToggle(!1)},onReject:function(n){t.logger.error("Unregister rejected with status code ".concat(n.message.statusCode)),t.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(n),t.waitingToggle(!1)},onTrying:function(t){e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(i)},e.prototype.clearTimers=function(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)},e.prototype.generateContactHeader=function(e){var t=this.userAgent.contact.toString();return this.options.regId&&this.options.instanceId&&(t+=";reg-id="+this.options.regId,t+=';+sip.instance="<urn:uuid:'+this.options.instanceId+'>"'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach(function(e){t+=";"+e}),t+=";expires="+e},e.prototype.registered=function(e){var t=this;this.clearTimers(),this.registrationTimer=setTimeout(function(){t.registrationTimer=void 0,t.register()},this.refreshFrequency/100*e*1e3),this.registrationExpiredTimer=setTimeout(function(){t.logger.warn("Registration expired"),t.unregistered()},1e3*e),this._state!==RegistererState.Registered&&this.stateTransition(RegistererState.Registered)},e.prototype.unregistered=function(){this.clearTimers(),this._state!==RegistererState.Unregistered&&this.stateTransition(RegistererState.Unregistered)},e.prototype.terminated=function(){this.clearTimers(),this._state!==RegistererState.Terminated&&this.stateTransition(RegistererState.Terminated)},e.prototype.stateTransition=function(e){var t=this,n=function(){throw new Error("Invalid state transition from ".concat(t._state," to ").concat(e))};switch(this._state){case RegistererState.Initial:e!==RegistererState.Registered&&e!==RegistererState.Unregistered&&e!==RegistererState.Terminated&&n();break;case RegistererState.Registered:e!==RegistererState.Unregistered&&e!==RegistererState.Terminated&&n();break;case RegistererState.Unregistered:e!==RegistererState.Registered&&e!==RegistererState.Terminated&&n();break;case RegistererState.Terminated:n();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log("Registration transitioned to state ".concat(this._state)),this._stateEventEmitter.emit(this._state),e===RegistererState.Terminated&&this.dispose()},Object.defineProperty(e.prototype,"waiting",{get:function(){return this._waiting},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"waitingChange",{get:function(){return this._waitingEventEmitter},enumerable:!1,configurable:!0}),e.prototype.waitingToggle=function(e){if(this._waiting===e)throw new Error("Invalid waiting transition from ".concat(this._waiting," to ").concat(e));this._waiting=e,this.logger.log("Waiting toggled to ".concat(this._waiting)),this._waitingEventEmitter.emit(this._waiting)},e.prototype.waitingWarning=function(){this.logger.warn("An attempt was made to send a REGISTER request while a prior one was still in progress. RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response from the registrar for the previous one or the previous REGISTER request has timed out. Note that if the transport disconnects, you still must wait for the prior request to time out before sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.")},e.prototype.stateError=function(){var e=this.state===RegistererState.Terminated?"is in 'Terminated' state":"has been disposed",t="An attempt was made to send a REGISTER request when the Registerer ".concat(e,".");t+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",t+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(t)},e.defaultExpires=600,e.defaultRefreshFrequency=99,e}(),SubscriptionState;!function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Subscribed="Subscribed",e.Terminated="Terminated"}(SubscriptionState||(SubscriptionState={}));var Subscription=function(){function e(e,t){void 0===t&&(t={}),this._disposed=!1,this._state=SubscriptionState.Initial,this._logger=e.getLogger("sip.Subscription"),this._stateEventEmitter=new EmitterImpl,this._userAgent=e,this.delegate=t.delegate}return e.prototype.dispose=function(){return this._disposed||(this._disposed=!0,this._stateEventEmitter.removeAllListeners()),Promise.resolve()},Object.defineProperty(e.prototype,"dialog",{get:function(){return this._dialog},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"disposed",{get:function(){return this._disposed},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),e.prototype.stateTransition=function(e){var t=this,n=function(){throw new Error("Invalid state transition from ".concat(t._state," to ").concat(e))};switch(this._state){case SubscriptionState.Initial:e!==SubscriptionState.NotifyWait&&e!==SubscriptionState.Terminated&&n();break;case SubscriptionState.NotifyWait:e!==SubscriptionState.Subscribed&&e!==SubscriptionState.Terminated&&n();break;case SubscriptionState.Subscribed:e!==SubscriptionState.Terminated&&n();break;case SubscriptionState.Terminated:n();break;default:throw new Error("Unrecognized state.")}this._state!==e&&(this._state=e,this._logger.log("Subscription ".concat(this._dialog?this._dialog.id:void 0," transitioned to ").concat(this._state)),this._stateEventEmitter.emit(this._state),e===SubscriptionState.Terminated&&this.dispose())},e}();!function(e){function t(t,n,r,i){void 0===i&&(i={});var s=e.call(this,t,i)||this;return s.body=void 0,s.logger=t.getLogger("sip.Subscriber"),i.body&&(s.body={body:i.body,contentType:i.contentType?i.contentType:"application/sdp"}),s.targetURI=n,s.event=r,void 0===i.expires?s.expires=3600:"number"!=typeof i.expires?(s.logger.warn('Option "expires" must be a number. Using default of 3600.'),s.expires=3600):s.expires=i.expires,s.extraHeaders=(i.extraHeaders||[]).slice(),s.subscriberRequest=s.initSubscriberRequest(),s.outgoingRequestMessage=s.subscriberRequest.message,s.id=s.outgoingRequestMessage.callId+s.outgoingRequestMessage.from.parameters.tag+s.event,s._userAgent._subscriptions[s.id]=s,s}__extends$1(t,e),t.prototype.dispose=function(){var t=this;return this.disposed?Promise.resolve():(this.logger.log("Subscription ".concat(this.id," in state ").concat(this.state," is being disposed")),delete this._userAgent._subscriptions[this.id],this.retryAfterTimer&&(clearTimeout(this.retryAfterTimer),this.retryAfterTimer=void 0),this.subscriberRequest.dispose(),e.prototype.dispose.call(this).then(function(){if(t.state===SubscriptionState.Subscribed){if(!t._dialog)throw new Error("Dialog undefined.");if(t._dialog.subscriptionState===SubscriptionState$1.Pending||t._dialog.subscriptionState===SubscriptionState$1.Active){var e=t._dialog;return new Promise(function(t,n){e.delegate={onTerminated:function(){return t()}},e.unsubscribe()})}}}))},t.prototype.subscribe=function(e){var t=this;switch(this.subscriberRequest.state){case SubscriptionState$1.Initial:this.state===SubscriptionState.Initial&&this.stateTransition(SubscriptionState.NotifyWait),this.subscriberRequest.subscribe().then(function(e){e.success?(e.success.subscription&&(t._dialog=e.success.subscription,t._dialog.delegate={onNotify:function(e){return t.onNotify(e)},onRefresh:function(e){return t.onRefresh(e)},onTerminated:function(){t.state!==SubscriptionState.Terminated&&t.stateTransition(SubscriptionState.Terminated)}}),t.onNotify(e.success.request)):e.failure&&t.unsubscribe()});break;case SubscriptionState$1.NotifyWait:case SubscriptionState$1.Pending:break;case SubscriptionState$1.Active:if(this._dialog)this._dialog.refresh().delegate={onAccept:function(e){return t.onAccepted(e)},onRedirect:function(e){return t.unsubscribe()},onReject:function(e){return t.unsubscribe()}};case SubscriptionState$1.Terminated:}return Promise.resolve()},t.prototype.unsubscribe=function(e){if(this.disposed)return Promise.resolve();switch(this.subscriberRequest.state){case SubscriptionState$1.Initial:case SubscriptionState$1.NotifyWait:break;case SubscriptionState$1.Pending:case SubscriptionState$1.Active:this._dialog&&this._dialog.unsubscribe();break;case SubscriptionState$1.Terminated:break;default:throw new Error("Unknown state.")}return this.stateTransition(SubscriptionState.Terminated),Promise.resolve()},t.prototype._refresh=function(){return this.subscriberRequest.state===SubscriptionState$1.Active?this.subscribe():Promise.resolve()},t.prototype.onAccepted=function(e){},t.prototype.onNotify=function(e){var t=this;if(this.disposed)e.accept();else{if(this.state!==SubscriptionState.Subscribed&&this.stateTransition(SubscriptionState.Subscribed),this.delegate&&this.delegate.onNotify){var n=new Notification(e);this.delegate.onNotify(n)}else e.accept();var r=e.message.parseHeader("Subscription-State");if(r&&r.state&&"terminated"===r.state){if(r.reason)switch(this.logger.log("Terminated subscription with reason ".concat(r.reason)),r.reason){case"deactivated":case"timeout":return this.initSubscriberRequest(),void this.subscribe();case"probation":case"giveup":return this.initSubscriberRequest(),void(r.params&&r.params["retry-after"]?this.retryAfterTimer=setTimeout(function(){t.subscribe()},r.params["retry-after"]):this.subscribe())}this.unsubscribe()}}},t.prototype.onRefresh=function(e){var t=this;e.delegate={onAccept:function(e){return t.onAccepted(e)}}},t.prototype.initSubscriberRequest=function(){var e=this,t={extraHeaders:this.extraHeaders,body:this.body?fromBodyLegacy(this.body):void 0};return this.subscriberRequest=new SubscriberRequest(this._userAgent.userAgentCore,this.targetURI,this.event,this.expires,t),this.subscriberRequest.delegate={onAccept:function(t){return e.onAccepted(t)}},this.subscriberRequest}}(Subscription);var SubscriberRequest=function(){function e(e,t,n,r,i,s){this.core=e,this.target=t,this.event=n,this.expires=r,this.subscribed=!1,this.logger=e.loggerFactory.getLogger("sip.Subscriber"),this.delegate=s;var o="Allow: "+AllowedMethods.toString(),a=(i&&i.extraHeaders||[]).slice();a.push(o),a.push("Event: "+this.event),a.push("Expires: "+this.expires),a.push("Contact: "+this.core.configuration.contact.toString());var c=i&&i.body;this.message=e.makeOutgoingRequestMessage(C.SUBSCRIBE,this.target,this.core.configuration.aor,this.target,{},a,c)}return e.prototype.dispose=function(){this.request&&(this.request.waitNotifyStop(),this.request.dispose(),this.request=void 0)},Object.defineProperty(e.prototype,"state",{get:function(){return this.subscription?this.subscription.subscriptionState:this.subscribed?SubscriptionState$1.NotifyWait:SubscriptionState$1.Initial},enumerable:!1,configurable:!0}),e.prototype.subscribe=function(){var e=this;return this.subscribed?Promise.reject(new Error("Not in initial state. Did you call subscribe more than once?")):(this.subscribed=!0,new Promise(function(t){if(!e.message)throw new Error("Message undefined.");e.request=e.core.subscribe(e.message,{onAccept:function(t){e.delegate&&e.delegate.onAccept&&e.delegate.onAccept(t)},onNotify:function(n){e.subscription=n.subscription,e.subscription&&(e.subscription.autoRefresh=!0),t({success:n})},onNotifyTimeout:function(){t({failure:{}})},onRedirect:function(e){t({failure:{response:e}})},onReject:function(e){t({failure:{response:e}})}})}))},e}(),TransportState,UserAgentState;function defaultMediaStreamFactory(){return function(e){return e.audio||e.video?void 0===navigator.mediaDevices?Promise.reject(new Error("Media devices not available in insecure contexts.")):navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices,e):Promise.resolve(new MediaStream)}}function defaultPeerConnectionConfiguration(){return{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",peerIdentity:void 0,rtcpMuxPolicy:"require"}}!function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(TransportState||(TransportState={})),function(e){e.Started="Started",e.Stopped="Stopped"}(UserAgentState||(UserAgentState={}));var SessionDescriptionHandler=function(){function e(e,t,n){e.debug("SessionDescriptionHandler.constructor"),this.logger=e,this.mediaStreamFactory=t,this.sessionDescriptionHandlerConfiguration=n,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==n?void 0:n.peerConnectionConfiguration),this.initPeerConnectionEventHandlers()}return Object.defineProperty(e.prototype,"localMediaStream",{get:function(){return this._localMediaStream},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteMediaStream",{get:function(){return this._remoteMediaStream},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dataChannel",{get:function(){return this._dataChannel},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"peerConnection",{get:function(){return this._peerConnection},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"peerConnectionDelegate",{get:function(){return this._peerConnectionDelegate},set:function(e){this._peerConnectionDelegate=e},enumerable:!1,configurable:!0}),e.dispatchAddTrackEvent=function(e,t){e.dispatchEvent(new MediaStreamTrackEvent("addtrack",{track:t}))},e.dispatchRemoveTrackEvent=function(e,t){e.dispatchEvent(new MediaStreamTrackEvent("removetrack",{track:t}))},e.prototype.close=function(){this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this._peerConnection.getReceivers().forEach(function(e){e.track&&e.track.stop()}),this._peerConnection.getSenders().forEach(function(e){e.track&&e.track.stop()}),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)},e.prototype.getDescription=function(e,t){var n,r,i=this;if(this.logger.debug("SessionDescriptionHandler.getDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==e?void 0:e.onDataChannel;var s=null===(n=null==e?void 0:e.offerOptions)||void 0===n?void 0:n.iceRestart,o=void 0===(null==e?void 0:e.iceGatheringTimeout)?null===(r=this.sessionDescriptionHandlerConfiguration)||void 0===r?void 0:r.iceGatheringTimeout:null==e?void 0:e.iceGatheringTimeout;return this.getLocalMediaStream(e).then(function(){return i.updateDirection(e)}).then(function(){return i.createDataChannel(e)}).then(function(){return i.createLocalOfferOrAnswer(e)}).then(function(e){return i.applyModifiers(e,t)}).then(function(e){return i.setLocalSessionDescription(e)}).then(function(){return i.waitForIceGatheringComplete(s,o)}).then(function(){return i.getLocalSessionDescription()}).then(function(e){return{body:e.sdp,contentType:"application/sdp"}}).catch(function(e){throw i.logger.error("SessionDescriptionHandler.getDescription failed - "+e),e})},e.prototype.hasDescription=function(e){return this.logger.debug("SessionDescriptionHandler.hasDescription"),"application/sdp"===e},e.prototype.sendDtmf=function(e,t){if(this.logger.debug("SessionDescriptionHandler.sendDtmf"),void 0===this._peerConnection)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"),!1;var n=this._peerConnection.getSenders();if(0===n.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;var r=n[0].dtmf;if(!r)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;var i=null==t?void 0:t.duration,s=null==t?void 0:t.interToneGap;try{r.insertDTMF(e,i,s)}catch(e){return this.logger.error(e),!1}return this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: "+e.toString()),!0},e.prototype.setDescription=function(e,t,n){var r=this;if(this.logger.debug("SessionDescriptionHandler.setDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==t?void 0:t.onDataChannel;var i="have-local-offer"===this._peerConnection.signalingState?"answer":"offer";return this.getLocalMediaStream(t).then(function(){return r.applyModifiers({sdp:e,type:i},n)}).then(function(e){return r.setRemoteSessionDescription(e)}).catch(function(e){throw r.logger.error("SessionDescriptionHandler.setDescription failed - "+e),e})},e.prototype.applyModifiers=function(e,t){var n=this;return this.logger.debug("SessionDescriptionHandler.applyModifiers"),t&&0!==t.length?t.reduce(function(e,t){return e.then(t)},Promise.resolve(e)).then(function(e){if(n.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"),!e.sdp||!e.type)throw new Error("Invalid SDP.");return{sdp:e.sdp,type:e.type}}):Promise.resolve(e)},e.prototype.createDataChannel=function(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));if(!0!==(null==e?void 0:e.dataChannel))return Promise.resolve();if(this._dataChannel)return Promise.resolve();switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.createDataChannel - creating data channel");try{return this._dataChannel=this._peerConnection.createDataChannel((null==e?void 0:e.dataChannelLabel)||"",null==e?void 0:e.dataChannelOptions),this.onDataChannel&&this.onDataChannel(this._dataChannel),Promise.resolve()}catch(e){return Promise.reject(e)}case"have-remote-offer":return Promise.resolve();default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}},e.prototype.createLocalOfferOrAnswer=function(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP offer"),this._peerConnection.createOffer(null==e?void 0:e.offerOptions);case"have-remote-offer":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"),this._peerConnection.createAnswer(null==e?void 0:e.answerOptions);default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}},e.prototype.getLocalMediaStream=function(e){var t=this;if(this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));var n=__assign({},null==e?void 0:e.constraints);if(this.localMediaStreamConstraints){if(n.audio=n.audio||this.localMediaStreamConstraints.audio,n.video=n.video||this.localMediaStreamConstraints.video,JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(n.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(n.video))return Promise.resolve()}else void 0===n.audio&&void 0===n.video&&(n={audio:!0});return this.localMediaStreamConstraints=n,this.mediaStreamFactory(n,this).then(function(e){return t.setLocalMediaStream(e)})},e.prototype.setLocalMediaStream=function(t){var n=this;if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");var r=this._peerConnection,i=this._localMediaStream,s=[],o=function(t){var o=t.kind;if("audio"!==o&&"video"!==o)throw new Error("Unknown new track kind ".concat(o,"."));var a=r.getSenders().find(function(e){return e.track&&e.track.kind===o});a?s.push(new Promise(function(e){n.logger.debug("SessionDescriptionHandler.setLocalMediaStream - replacing sender ".concat(o," track")),e()}).then(function(){return a.replaceTrack(t).then(function(){var n=i.getTracks().find(function(e){return e.kind===o});n&&(n.stop(),i.removeTrack(n),e.dispatchRemoveTrackEvent(i,n)),i.addTrack(t),e.dispatchAddTrackEvent(i,t)}).catch(function(e){throw n.logger.error("SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ".concat(o," track")),e})})):s.push(new Promise(function(e){n.logger.debug("SessionDescriptionHandler.setLocalMediaStream - adding sender ".concat(o," track")),e()}).then(function(){try{r.addTrack(t,i)}catch(e){throw n.logger.error("SessionDescriptionHandler.setLocalMediaStream - failed to add sender ".concat(o," track")),e}i.addTrack(t),e.dispatchAddTrackEvent(i,t)}))},a=t.getAudioTracks();a.length&&o(a[0]);var c=t.getVideoTracks();return c.length&&o(c[0]),s.reduce(function(e,t){return e.then(function(){return t})},Promise.resolve())},e.prototype.getLocalSessionDescription=function(){if(this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));var e=this._peerConnection.localDescription;return e?Promise.resolve(e):Promise.reject(new Error("Failed to get local session description"))},e.prototype.setLocalSessionDescription=function(e){return this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"),void 0===this._peerConnection?Promise.reject(new Error("Peer connection closed.")):this._peerConnection.setLocalDescription(e)},e.prototype.setRemoteSessionDescription=function(e){if(this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));var t,n=e.sdp;switch(this._peerConnection.signalingState){case"stable":t="offer";break;case"have-local-offer":t="answer";break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return n?this._peerConnection.setRemoteDescription({sdp:n,type:t}):(this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"),Promise.reject(new Error("SDP is undefined")))},e.prototype.setRemoteTrack=function(t){this.logger.debug("SessionDescriptionHandler.setRemoteTrack");var n=this._remoteMediaStream;n.getTrackById(t.id)?this.logger.debug("SessionDescriptionHandler.setRemoteTrack - have remote ".concat(t.kind," track")):"audio"===t.kind?(this.logger.debug("SessionDescriptionHandler.setRemoteTrack - adding remote ".concat(t.kind," track")),n.getAudioTracks().forEach(function(t){t.stop(),n.removeTrack(t),e.dispatchRemoveTrackEvent(n,t)}),n.addTrack(t),e.dispatchAddTrackEvent(n,t)):"video"===t.kind&&(this.logger.debug("SessionDescriptionHandler.setRemoteTrack - adding remote ".concat(t.kind," track")),n.getVideoTracks().forEach(function(t){t.stop(),n.removeTrack(t),e.dispatchRemoveTrackEvent(n,t)}),n.addTrack(t),e.dispatchAddTrackEvent(n,t))},e.prototype.updateDirection=function(e){var t=this;if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.updateDirection - setting offer direction");this._peerConnection.getTransceivers().forEach(function(t){if(t.direction){var n=function(t){switch(t){case"inactive":case"recvonly":return(null==e?void 0:e.hold)?"inactive":"recvonly";case"sendonly":case"sendrecv":return(null==e?void 0:e.hold)?"sendonly":"sendrecv";case"stopped":return"stopped";default:throw new Error("Should never happen")}}(t.direction);t.direction!==n&&(t.direction=n)}});break;case"have-remote-offer":this.logger.debug("SessionDescriptionHandler.updateDirection - setting answer direction");var n=function(){var e=t._peerConnection.remoteDescription;if(!e)throw new Error("Failed to read remote offer");var n=/a=sendrecv\r\n|a=sendonly\r\n|a=recvonly\r\n|a=inactive\r\n/.exec(e.sdp);if(n)switch(n[0]){case"a=inactive\r\n":return"inactive";case"a=recvonly\r\n":return"recvonly";case"a=sendonly\r\n":return"sendonly";case"a=sendrecv\r\n":return"sendrecv";default:throw new Error("Should never happen")}return"sendrecv"}(),r=function(){switch(n){case"inactive":return"inactive";case"recvonly":return"sendonly";case"sendonly":return(null==e?void 0:e.hold)?"inactive":"recvonly";case"sendrecv":return(null==e?void 0:e.hold)?"sendonly":"sendrecv";default:throw new Error("Should never happen")}}();this._peerConnection.getTransceivers().forEach(function(e){e.direction&&"stopped"!==e.direction&&e.direction!==r&&(e.direction=r)});break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return Promise.resolve()},e.prototype.iceGatheringComplete=function(){this.logger.debug("SessionDescriptionHandler.iceGatheringComplete"),void 0!==this.iceGatheringCompleteTimeoutId&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - clearing timeout"),clearTimeout(this.iceGatheringCompleteTimeoutId),this.iceGatheringCompleteTimeoutId=void 0),void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - resolving promise"),this.iceGatheringCompleteResolve&&this.iceGatheringCompleteResolve(),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0)},e.prototype.waitForIceGatheringComplete=function(e,t){var n=this;return void 0===e&&(e=!1),void 0===t&&(t=0),this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"),void 0===this._peerConnection?Promise.reject("Peer connection closed."):e||"complete"!==this._peerConnection.iceGatheringState?(void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - rejecting prior waiting promise"),this.iceGatheringCompleteReject&&this.iceGatheringCompleteReject(new Error("Promise superseded.")),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0),this.iceGatheringCompletePromise=new Promise(function(e,r){n.iceGatheringCompleteResolve=e,n.iceGatheringCompleteReject=r,t>0&&(n.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in "+t),n.iceGatheringCompleteTimeoutId=setTimeout(function(){n.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"),n.iceGatheringComplete()},t))}),this.iceGatheringCompletePromise):(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"),Promise.resolve())},e.prototype.initPeerConnectionEventHandlers=function(){var e=this;if(this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"),!this._peerConnection)throw new Error("Peer connection undefined.");var t=this._peerConnection;t.onconnectionstatechange=function(n){var r,i=t.connectionState;e.logger.debug("SessionDescriptionHandler.onconnectionstatechange ".concat(i)),(null===(r=e._peerConnectionDelegate)||void 0===r?void 0:r.onconnectionstatechange)&&e._peerConnectionDelegate.onconnectionstatechange(n)},t.ondatachannel=function(t){var n;e.logger.debug("SessionDescriptionHandler.ondatachannel"),e._dataChannel=t.channel,e.onDataChannel&&e.onDataChannel(e._dataChannel),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.ondatachannel)&&e._peerConnectionDelegate.ondatachannel(t)},t.onicecandidate=function(t){var n;e.logger.debug("SessionDescriptionHandler.onicecandidate"),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.onicecandidate)&&e._peerConnectionDelegate.onicecandidate(t)},t.onicecandidateerror=function(t){var n;e.logger.debug("SessionDescriptionHandler.onicecandidateerror"),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.onicecandidateerror)&&e._peerConnectionDelegate.onicecandidateerror(t)},t.oniceconnectionstatechange=function(n){var r,i=t.iceConnectionState;e.logger.debug("SessionDescriptionHandler.oniceconnectionstatechange ".concat(i)),(null===(r=e._peerConnectionDelegate)||void 0===r?void 0:r.oniceconnectionstatechange)&&e._peerConnectionDelegate.oniceconnectionstatechange(n)},t.onicegatheringstatechange=function(n){var r,i=t.iceGatheringState;e.logger.debug("SessionDescriptionHandler.onicegatheringstatechange ".concat(i)),"complete"===i&&e.iceGatheringComplete(),(null===(r=e._peerConnectionDelegate)||void 0===r?void 0:r.onicegatheringstatechange)&&e._peerConnectionDelegate.onicegatheringstatechange(n)},t.onnegotiationneeded=function(t){var n;e.logger.debug("SessionDescriptionHandler.onnegotiationneeded"),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.onnegotiationneeded)&&e._peerConnectionDelegate.onnegotiationneeded(t)},t.onsignalingstatechange=function(n){var r,i=t.signalingState;e.logger.debug("SessionDescriptionHandler.onsignalingstatechange ".concat(i)),(null===(r=e._peerConnectionDelegate)||void 0===r?void 0:r.onsignalingstatechange)&&e._peerConnectionDelegate.onsignalingstatechange(n)},t.onstatsended=function(t){var n;e.logger.debug("SessionDescriptionHandler.onstatsended"),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.onstatsended)&&e._peerConnectionDelegate.onstatsended(t)},t.ontrack=function(t){var n,r=t.track.kind,i=t.track.enabled?"enabled":"disabled";e.logger.debug("SessionDescriptionHandler.ontrack ".concat(r," ").concat(i)),e.setRemoteTrack(t.track),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.ontrack)&&e._peerConnectionDelegate.ontrack(t)}},e}();function defaultSessionDescriptionHandlerFactory(e){return function(t,n){void 0===e&&(e=defaultMediaStreamFactory());var r={iceGatheringTimeout:void 0!==(null==n?void 0:n.iceGatheringTimeout)?null==n?void 0:n.iceGatheringTimeout:5e3,peerConnectionConfiguration:__assign(__assign({},defaultPeerConnectionConfiguration()),null==n?void 0:n.peerConnectionConfiguration)},i=t.userAgent.getLogger("sip.SessionDescriptionHandler");return new SessionDescriptionHandler(i,e,r)}}var Transport=function(){function e(t,n){if(this._state=TransportState.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new EmitterImpl,this.logger=t,n){var r=n,i=null==r?void 0:r.wsServers,s=null==r?void 0:r.maxReconnectionAttempts;if(void 0!==i){var o='The transport option "wsServers" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(o)}if(void 0!==s){o='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(o)}i&&!n.server&&("string"==typeof i&&(n.server=i),i instanceof Array&&(n.server=i[0]))}this.configuration=__assign(__assign({},e.defaultOptions),n);var a=this.configuration.server,c=Grammar.parse(a,"absoluteURI");if(-1===c)throw this.logger.error('Invalid WebSocket Server URL "'.concat(a,'"')),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(c.scheme))throw this.logger.error('Invalid scheme in WebSocket Server URL "'.concat(a,'"')),new Error("Invalid scheme in WebSocket Server URL");this._protocol=c.scheme.toUpperCase()}return e.prototype.dispose=function(){return this.disconnect()},Object.defineProperty(e.prototype,"protocol",{get:function(){return this._protocol},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"server",{get:function(){return this.configuration.server},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"ws",{get:function(){return this._ws},enumerable:!1,configurable:!0}),e.prototype.connect=function(){return this._connect()},e.prototype.disconnect=function(){return this._disconnect()},e.prototype.isConnected=function(){return this.state===TransportState.Connected},e.prototype.send=function(e){return this._send(e)},e.prototype._connect=function(){var e,t=this;switch(this.logger.log("Connecting ".concat(this.server)),this.state){case TransportState.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(TransportState.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case TransportState.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(TransportState.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case TransportState.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(TransportState.Connecting)}catch(e){if(e instanceof StateTransitionError)return Promise.reject(e);throw e}break;case TransportState.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(TransportState.Connecting)}catch(e){if(e instanceof StateTransitionError)return Promise.reject(e);throw e}break;default:throw new Error("Unknown state")}try{(e=new WebSocket(this.server,"sip")).binaryType="arraybuffer",e.addEventListener("close",function(n){return t.onWebSocketClose(n,e)}),e.addEventListener("error",function(n){return t.onWebSocketError(n,e)}),e.addEventListener("open",function(n){return t.onWebSocketOpen(n,e)}),e.addEventListener("message",function(n){return t.onWebSocketMessage(n,e)}),this._ws=e}catch(e){return this._ws=void 0,this.logger.error("WebSocket construction failed."),this.logger.error(e),new Promise(function(n,r){t.connectResolve=n,t.connectReject=r,t.transitionState(TransportState.Disconnected,e)})}return this.connectPromise=new Promise(function(n,r){t.connectResolve=n,t.connectReject=r,t.connectTimeout=setTimeout(function(){t.logger.warn("Connect timed out. Exceeded time set in configuration.connectionTimeout: "+t.configuration.connectionTimeout+"s."),e.close(1e3)},1e3*t.configuration.connectionTimeout)}),this.connectPromise},e.prototype._disconnect=function(){var e=this;switch(this.logger.log("Disconnecting ".concat(this.server)),this.state){case TransportState.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(TransportState.Disconnecting)}catch(e){if(e instanceof StateTransitionError)return Promise.reject(e);throw e}break;case TransportState.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(TransportState.Disconnecting)}catch(e){if(e instanceof StateTransitionError)return Promise.reject(e);throw e}break;case TransportState.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(TransportState.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case TransportState.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(TransportState.Disconnecting));if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");return Promise.resolve();default:throw new Error("Unknown state")}if(!this._ws)throw new Error("WebSocket must be defined.");var t=this._ws;return this.disconnectPromise=new Promise(function(n,r){e.disconnectResolve=n,e.disconnectReject=r;try{t.close(1e3)}catch(t){throw e.logger.error("WebSocket close failed."),e.logger.error(t),t}}),this.disconnectPromise},e.prototype._send=function(e){if(!0===this.configuration.traceSip&&this.logger.log("Sending WebSocket message:\n\n"+e+"\n"),this._state!==TransportState.Connected)return Promise.reject(new Error("Not connected."));if(!this._ws)throw new Error("WebSocket undefined.");try{this._ws.send(e)}catch(e){return e instanceof Error?Promise.reject(e):Promise.reject(new Error("WebSocket send failed."))}return Promise.resolve()},e.prototype.onWebSocketClose=function(e,t){if(t===this._ws){var n="WebSocket closed ".concat(this.server," (code: ").concat(e.code,")"),r=this.disconnectPromise?void 0:new Error(n);r&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(n),this._ws=void 0,this.transitionState(TransportState.Disconnected,r)}},e.prototype.onWebSocketError=function(e,t){t===this._ws&&this.logger.error("WebSocket error occurred.")},e.prototype.onWebSocketMessage=function(e,t){if(t===this._ws){var n,r=e.data;if(/^(\r\n)+$/.test(r))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(r){if("string"!=typeof r){try{n=(new TextDecoder).decode(new Uint8Array(r))}catch(e){return this.logger.error(e),void this.logger.error("Received WebSocket binary message failed to be converted into string, message discarded")}!0===this.configuration.traceSip&&this.logger.log("Received WebSocket binary message:\n\n"+n+"\n")}else n=r,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+n+"\n");if(this.state===TransportState.Connected){if(this.onMessage)try{this.onMessage(n)}catch(e){throw this.logger.error(e),this.logger.error("Exception thrown by onMessage callback"),e}}else this.logger.warn("Received message while not connected, discarding...")}else this.logger.warn("Received empty message, discarding...")}},e.prototype.onWebSocketOpen=function(e,t){t===this._ws&&this._state===TransportState.Connecting&&(this.logger.log("WebSocket opened ".concat(this.server)),this.transitionState(TransportState.Connected))},e.prototype.transitionLoopDetectedError=function(e){var t="A state transition loop has been detected.";return t+=" An attempt to transition from ".concat(this._state," to ").concat(e," before the prior transition completed."),t+=" Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?",this.logger.error(t),new StateTransitionError("Loop detected.")},e.prototype.transitionState=function(e,t){var n=this,r=function(){throw new Error("Invalid state transition from ".concat(n._state," to ").concat(e))};if(this.transitioningState)throw this.transitionLoopDetectedError(e);switch(this.transitioningState=!0,this._state){case TransportState.Connecting:e!==TransportState.Connected&&e!==TransportState.Disconnecting&&e!==TransportState.Disconnected&&r();break;case TransportState.Connected:e!==TransportState.Disconnecting&&e!==TransportState.Disconnected&&r();break;case TransportState.Disconnecting:e!==TransportState.Connecting&&e!==TransportState.Disconnected&&r();break;case TransportState.Disconnected:e!==TransportState.Connecting&&r();break;default:throw new Error("Unknown state.")}var i=this._state;this._state=e;var s=this.connectResolve,o=this.connectReject;i===TransportState.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);var a=this.disconnectResolve,c=this.disconnectReject;if(i===TransportState.Disconnecting&&(this.disconnectPromise=void 0,this.disconnectResolve=void 0,this.disconnectReject=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),this.logger.log("Transitioned from ".concat(i," to ").concat(this._state)),this._stateEventEmitter.emit(this._state),e===TransportState.Connected&&(this.startSendingKeepAlives(),this.onConnect))try{this.onConnect()}catch(e){throw this.logger.error(e),this.logger.error("Exception thrown by onConnect callback"),e}if(i===TransportState.Connected&&(this.stopSendingKeepAlives(),this.onDisconnect))try{t?this.onDisconnect(t):this.onDisconnect()}catch(e){throw this.logger.error(e),this.logger.error("Exception thrown by onDisconnect callback"),e}if(i===TransportState.Connecting){if(!s)throw new Error("Connect resolve undefined.");if(!o)throw new Error("Connect reject undefined.");e===TransportState.Connected?s():o(t||new Error("Connect aborted."))}if(i===TransportState.Disconnecting){if(!a)throw new Error("Disconnect resolve undefined.");if(!c)throw new Error("Disconnect reject undefined.");e===TransportState.Disconnected?a():c(t||new Error("Disconnect aborted."))}this.transitioningState=!1},e.prototype.clearKeepAliveTimeout=function(){this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveDebounceTimeout=void 0},e.prototype.sendKeepAlive=function(){var e=this;return this.keepAliveDebounceTimeout?Promise.resolve():(this.keepAliveDebounceTimeout=setTimeout(function(){e.clearKeepAliveTimeout()},1e3*this.configuration.keepAliveDebounce),this.send("\r\n\r\n"))},e.prototype.startSendingKeepAlives=function(){var e,t,n=this;this.configuration.keepAliveInterval&&!this.keepAliveInterval&&(this.keepAliveInterval=setInterval(function(){n.sendKeepAlive(),n.startSendingKeepAlives()},(e=this.configuration.keepAliveInterval,t=.8*e,1e3*(Math.random()*(e-t)+t))))},e.prototype.stopSendingKeepAlives=function(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0},e.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0},e}(),UserAgent=function(){function e(t){void 0===t&&(t={});var n=this;if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=UserAgentState.Stopped,this.unloadListener=function(){n.stop()},this._stateEventEmitter=new EmitterImpl,this.delegate=t.delegate,this.options=__assign(__assign(__assign(__assign(__assign({},e.defaultOptions()),{sipjsId:createRandomToken(5)}),{uri:new URI("sip","anonymous."+createRandomToken(6),"anonymous.invalid")}),{viaHost:createRandomToken(12)+".invalid"}),e.stripUndefinedProperties(t)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){var r=Math.floor(254*Math.random()+1);this.options.viaHost="192.0.2."+r}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new LoggerFactory,this.logger=this.loggerFactory.getLogger("sip.UserAgent"),this.loggerFactory.builtinEnabled=this.options.logBuiltinEnabled,this.loggerFactory.connector=this.options.logConnector,this.options.logLevel){case"error":this.loggerFactory.level=Levels.error;break;case"warn":this.loggerFactory.level=Levels.warn;break;case"log":this.loggerFactory.level=Levels.log;break;case"debug":this.loggerFactory.level=Levels.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(function(e){var t=n.options[e];switch(e){case"uri":case"sessionDescriptionHandlerFactory":n.logger.log("· "+e+": "+t);break;case"authorizationPassword":n.logger.log("· "+e+": NOT SHOWN");break;case"transportConstructor":n.logger.log("· "+e+": "+t.name);break;default:n.logger.log("· "+e+": "+JSON.stringify(t))}})),this.options.transportOptions){var i=this.options.transportOptions,s=i.maxReconnectionAttempts,o=i.reconnectionTimeout;if(void 0!==s){var a='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(a)}if(void 0!==o){a='The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(a)}void 0===t.reconnectionDelay&&void 0!==o&&(this.options.reconnectionDelay=o),void 0===t.reconnectionAttempts&&void 0!==s&&(this.options.reconnectionAttempts=s)}if(void 0!==t.reconnectionDelay){a='The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(a)}if(void 0!==t.reconnectionAttempts){a='The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(a)}this._transport=new this.options.transportConstructor(this.getLogger("sip.Transport"),this.options.transportOptions),this.initTransportCallbacks(),this._contact=this.initContact(),this._userAgentCore=this.initCore(),this.options.autoStart&&this.start()}return e.makeURI=function(e){return Grammar.URIParse(e)},e.defaultOptions=function(){return{allowLegacyNotifications:!1,authorizationHa1:"",authorizationPassword:"",authorizationUsername:"",autoStart:!1,autoStop:!0,delegate:{},contactName:"",contactParams:{transport:"ws"},displayName:"",forceRport:!1,hackAllowUnregisteredOptionTags:!1,hackIpInContact:!1,hackViaTcp:!1,logBuiltinEnabled:!0,logConfiguration:!0,logConnector:function(){},logLevel:"log",noAnswerTimeout:60,preloadedRouteSet:[],reconnectionAttempts:0,reconnectionDelay:4,sendInitialProvisionalResponse:!0,sessionDescriptionHandlerFactory:defaultSessionDescriptionHandlerFactory(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:SIPExtension.Unsupported,sipExtensionReplaces:SIPExtension.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:Transport,transportOptions:{},uri:new URI("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/"+LIBRARY_VERSION,viaHost:""}},e.stripUndefinedProperties=function(e){return Object.keys(e).reduce(function(t,n){return void 0!==e[n]&&(t[n]=e[n]),t},{})},Object.defineProperty(e.prototype,"configuration",{get:function(){return this.options},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"contact",{get:function(){return this._contact},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transport",{get:function(){return this._transport},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"userAgentCore",{get:function(){return this._userAgentCore},enumerable:!1,configurable:!0}),e.prototype.getLogger=function(e,t){return this.loggerFactory.getLogger(e,t)},e.prototype.getLoggerFactory=function(){return this.loggerFactory},e.prototype.isConnected=function(){return this.transport.isConnected()},e.prototype.reconnect=function(){var e=this;return this.state===UserAgentState.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(function(){return e.transport.connect()})},e.prototype.start=function(){if(this.state===UserAgentState.Started)return this.logger.warn("User agent already started"),Promise.resolve();if(this.logger.log("Starting ".concat(this.configuration.uri)),this.transitionState(UserAgentState.Started),this.options.autoStop){var e=!("undefined"==typeof chrome||!chrome.app||!chrome.app.runtime);"undefined"==typeof window||"function"!=typeof window.addEventListener||e||window.addEventListener("unload",this.unloadListener)}return this.transport.connect()},e.prototype.stop=function(){return __awaiter(this,void 0,void 0,function(){var e,t,n,r,i,s,o,a,c,u,l,h,d,p,g,f,m,v,y,b,S,T,w,R,E,I,_,A=this;return __generator(this,function(C){switch(C.label){case 0:if(this.state===UserAgentState.Stopped)return this.logger.warn("User agent already stopped"),[2,Promise.resolve()];for(l in this.logger.log("Stopping ".concat(this.configuration.uri)),this.transitionState(UserAgentState.Stopped),this.options.autoStop&&(e=!("undefined"==typeof chrome||!chrome.app||!chrome.app.runtime),"undefined"!=typeof window&&window.removeEventListener&&!e&&window.removeEventListener("unload",this.unloadListener)),t=__assign({},this._publishers),n=__assign({},this._registerers),r=__assign({},this._sessions),i=__assign({},this._subscriptions),s=this.transport,o=this.userAgentCore,this.logger.log("Dispose of registerers"),a=function(e){return __generator(this,function(t){switch(t.label){case 0:return n[e]?[4,n[e].dispose().catch(function(t){throw A.logger.error(t.message),delete A._registerers[e],t})]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})},u=[],c=n)u.push(l);h=0,C.label=1;case 1:return h<u.length?(l=u[h])in c?[5,a(l)]:[3,3]:[3,4];case 2:C.sent(),C.label=3;case 3:return h++,[3,1];case 4:for(f in this.logger.log("Dispose of sessions"),d=function(e){return __generator(this,function(t){switch(t.label){case 0:return r[e]?[4,r[e].dispose().catch(function(t){throw A.logger.error(t.message),delete A._sessions[e],t})]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})},g=[],p=r)g.push(f);m=0,C.label=5;case 5:return m<g.length?(f=g[m])in p?[5,d(f)]:[3,7]:[3,8];case 6:C.sent(),C.label=7;case 7:return m++,[3,5];case 8:for(S in this.logger.log("Dispose of subscriptions"),v=function(e){return __generator(this,function(t){switch(t.label){case 0:return i[e]?[4,i[e].dispose().catch(function(t){throw A.logger.error(t.message),delete A._subscriptions[e],t})]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})},b=[],y=i)b.push(S);T=0,C.label=9;case 9:return T<b.length?(S=b[T])in y?[5,v(S)]:[3,11]:[3,12];case 10:C.sent(),C.label=11;case 11:return T++,[3,9];case 12:for(I in this.logger.log("Dispose of publishers"),w=function(e){return __generator(this,function(n){switch(n.label){case 0:return t[e]?[4,t[e].dispose().catch(function(t){throw A.logger.error(t.message),delete A._publishers[e],t})]:[3,2];case 1:n.sent(),n.label=2;case 2:return[2]}})},E=[],R=t)E.push(I);_=0,C.label=13;case 13:return _<E.length?(I=E[_])in R?[5,w(I)]:[3,15]:[3,16];case 14:C.sent(),C.label=15;case 15:return _++,[3,13];case 16:return this.logger.log("Dispose of transport"),[4,s.dispose().catch(function(e){throw A.logger.error(e.message),e})];case 17:return C.sent(),this.logger.log("Dispose of core"),o.dispose(),[2]}})})},e.prototype._makeInviter=function(e,t){return new Inviter(this,e,t)},e.prototype.attemptReconnection=function(e){var t=this;void 0===e&&(e=1);var n=this.options.reconnectionAttempts,r=this.options.reconnectionDelay;e>n?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log("Reconnection attempt ".concat(e," of ").concat(n," - trying")),setTimeout(function(){t.reconnect().then(function(){t.logger.log("Reconnection attempt ".concat(e," of ").concat(n," - succeeded"))}).catch(function(r){t.logger.error(r.message),t.logger.log("Reconnection attempt ".concat(e," of ").concat(n," - failed")),t.attemptReconnection(++e)})},1===e?0:1e3*r))},e.prototype.initContact=function(){var e=this,t=""!==this.options.contactName?this.options.contactName:createRandomToken(8),n=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new URI("sip",t,this.options.viaHost,void 0,n),toString:function(t){void 0===t&&(t={});var r=t.anonymous||!1,i=t.outbound||!1,s="<";return s+=r?e.contact.tempGruu||"sip:anonymous@anonymous.invalid;transport=".concat(n.transport?n.transport:"ws"):e.contact.pubGruu||e.contact.uri,i&&(s+=";ob"),s+=">"}}},e.prototype.initCore=function(){var e=this,t=[];t.push("outbound"),this.options.sipExtension100rel===SIPExtension.Supported&&t.push("100rel"),this.options.sipExtensionReplaces===SIPExtension.Supported&&t.push("replaces"),this.options.sipExtensionExtraSupported&&t.push.apply(t,this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(t=t.filter(function(e){return UserAgentRegisteredOptionTags[e]}));var n=(t=Array.from(new Set(t))).slice();(this.contact.pubGruu||this.contact.tempGruu)&&n.push("gruu");var r={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:t,supportedOptionTagsResponse:n,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:function(){var t=e.options.authorizationUsername?e.options.authorizationUsername:e.options.uri.user,n=e.options.authorizationPassword?e.options.authorizationPassword:void 0,r=e.options.authorizationHa1?e.options.authorizationHa1:void 0;return new DigestAuthentication(e.getLoggerFactory(),r,t,n)},transportAccessor:function(){return e.transport}},i={onInvite:function(t){var n,r=new Invitation(e,t);if(t.delegate={onCancel:function(e){r._onCancel(e)},onTransportError:function(t){e.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},t.trying(),e.options.sipExtensionReplaces!==SIPExtension.Unsupported){var i=t.message.parseHeader("replaces");if(i){var s=i.call_id;if("string"!=typeof s)throw new Error("Type of call id is not string");var o=i.replaces_to_tag;if("string"!=typeof o)throw new Error("Type of to tag is not string");var a=i.replaces_from_tag;if("string"!=typeof a)throw new Error("type of from tag is not string");var c=s+o+a,u=e.userAgentCore.dialogs.get(c);if(!u)return void r.reject({statusCode:481});if(!u.early&&!0===i.early_only)return void r.reject({statusCode:486});var l=e._sessions[s+a]||e._sessions[s+o]||void 0;if(!l)throw new Error("Session does not exist.");r._replacee=l}}if(null===(n=e.delegate)||void 0===n?void 0:n.onInvite)return r.autoSendAnInitialProvisionalResponse?void r.progress().then(function(){var t;if(void 0===(null===(t=e.delegate)||void 0===t?void 0:t.onInvite))throw new Error("onInvite undefined.");e.delegate.onInvite(r)}):void e.delegate.onInvite(r);r.reject({statusCode:486})},onMessage:function(t){if(e.delegate&&e.delegate.onMessage){var n=new Message(t);e.delegate.onMessage(n)}else t.accept()},onNotify:function(t){if(e.delegate&&e.delegate.onNotify){var n=new Notification(t);e.delegate.onNotify(n)}else e.options.allowLegacyNotifications?t.accept():t.reject({statusCode:481})},onRefer:function(t){e.logger.warn("Received an out of dialog REFER request"),e.delegate&&e.delegate.onReferRequest?e.delegate.onReferRequest(t):t.reject({statusCode:405})},onRegister:function(t){e.logger.warn("Received an out of dialog REGISTER request"),e.delegate&&e.delegate.onRegisterRequest?e.delegate.onRegisterRequest(t):t.reject({statusCode:405})},onSubscribe:function(t){e.logger.warn("Received an out of dialog SUBSCRIBE request"),e.delegate&&e.delegate.onSubscribeRequest?e.delegate.onSubscribeRequest(t):t.reject({statusCode:405})}};return new UserAgentCore(r,i)},e.prototype.initTransportCallbacks=function(){var e=this;this.transport.onConnect=function(){return e.onTransportConnect()},this.transport.onDisconnect=function(t){return e.onTransportDisconnect(t)},this.transport.onMessage=function(t){return e.onTransportMessage(t)}},e.prototype.onTransportConnect=function(){this.state!==UserAgentState.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()},e.prototype.onTransportDisconnect=function(e){this.state!==UserAgentState.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())},e.prototype.onTransportMessage=function(e){var t=this,n=Parser.parseMessage(e,this.getLogger("sip.Parser"));if(n)if(this.state===UserAgentState.Stopped&&n instanceof IncomingRequestMessage)this.logger.warn("Received ".concat(n.method," request while stopped. Dropping."));else{var r=function(){for(var e=0,r=["from","to","call_id","cseq","via"];e<r.length;e++){var i=r[e];if(!n.hasHeader(i))return t.logger.warn("Missing mandatory header field : ".concat(i,".")),!1}return!0};if(n instanceof IncomingRequestMessage){if(!r())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!n.toTag&&n.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(n,{statusCode:482});var i=utf8Length(n.body);if((s=n.getHeader("content-length"))&&i<Number(s))return void this.userAgentCore.replyStateless(n,{statusCode:400})}if(n instanceof IncomingResponseMessage){if(!r())return void this.logger.warn("Response missing mandatory header field. Dropping.");if(n.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(n.via.host!==this.options.viaHost||void 0!==n.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");var s;i=utf8Length(n.body);if((s=n.getHeader("content-length"))&&i<Number(s))return void this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping.")}if(n instanceof IncomingRequestMessage)this.userAgentCore.receiveIncomingRequestFromTransport(n);else{if(!(n instanceof IncomingResponseMessage))throw new Error("Invalid message type.");this.userAgentCore.receiveIncomingResponseFromTransport(n)}}else this.logger.warn("Failed to parse incoming message. Dropping.")},e.prototype.transitionState=function(e,t){var n=this,r=function(){throw new Error("Invalid state transition from ".concat(n._state," to ").concat(e))};switch(this._state){case UserAgentState.Started:e!==UserAgentState.Stopped&&r();break;case UserAgentState.Stopped:e!==UserAgentState.Started&&r();break;default:throw new Error("Unknown state.")}this.logger.log("Transitioned from ".concat(this._state," to ").concat(e)),this._state=e,this._stateEventEmitter.emit(this._state)},e}();function getAudio(e){var t=document.getElementById(e);if(t instanceof HTMLAudioElement)return t;var n=new Audio;return n.controls=!0,n.autoplay=!0,n.id="ueRemoteAudio",n.style.display="none",document.body.appendChild(n),document.getElementById(e)}function assignStream(e,t){t.autoplay=!0,t.srcObject=e,t.play().catch(function(e){}),e.onaddtrack=function(){t.load(),t.play().catch(function(e){})},e.onremovetrack=function(){t.load(),t.play().catch(function(e){})}}!function(){function e(e,t){void 0===t&&(t={});var n=this;this.attemptingReconnection=!1,this.connectRequested=!1,this.held=!1,this.muted=!1,this.registerer=void 0,this.registerRequested=!1,this.session=void 0,this.delegate=t.delegate,this.options=__assign({},t);var r=__assign({},t.userAgentOptions);if(r.transportConstructor||(r.transportConstructor=Transport),r.transportOptions||(r.transportOptions={server:e}),!r.uri&&t.aor){var i=UserAgent.makeURI(t.aor);if(!i)throw new Error("Failed to create valid URI from ".concat(t.aor));r.uri=i}this.userAgent=new UserAgent(r),this.userAgent.delegate={onConnect:function(){n.logger.log("[".concat(n.id,"] Connected")),n.delegate&&n.delegate.onServerConnect&&n.delegate.onServerConnect(),n.registerer&&n.registerRequested&&(n.logger.log("[".concat(n.id,"] Registering...")),n.registerer.register().catch(function(e){n.logger.error("[".concat(n.id,"] Error occurred registering after connection with server was obtained.")),n.logger.error(e.toString())}))},onDisconnect:function(e){n.logger.log("[".concat(n.id,"] Disconnected")),n.delegate&&n.delegate.onServerDisconnect&&n.delegate.onServerDisconnect(e),n.session&&(n.logger.log("[".concat(n.id,"] Hanging up...")),n.hangup().catch(function(e){n.logger.error("[".concat(n.id,"] Error occurred hanging up call after connection with server was lost.")),n.logger.error(e.toString())})),n.registerer&&(n.logger.log("[".concat(n.id,"] Unregistering...")),n.registerer.unregister().catch(function(e){n.logger.error("[".concat(n.id,"] Error occurred unregistering after connection with server was lost.")),n.logger.error(e.toString())})),e&&n.attemptReconnection()},onInvite:function(e){if(n.logger.log("[".concat(n.id,"] Received INVITE")),n.session)return n.logger.warn("[".concat(n.id,"] Session already in progress, rejecting INVITE...")),void e.reject().then(function(){n.logger.log("[".concat(n.id,"] Rejected INVITE"))}).catch(function(e){n.logger.error("[".concat(n.id,"] Failed to reject INVITE")),n.logger.error(e.toString())});var t={sessionDescriptionHandlerOptions:{constraints:n.constraints}};n.initSession(e,t),n.delegate&&n.delegate.onCallReceived?n.delegate.onCallReceived():(n.logger.warn("[".concat(n.id,"] No handler available, rejecting INVITE...")),e.reject().then(function(){n.logger.log("[".concat(n.id,"] Rejected INVITE"))}).catch(function(e){n.logger.error("[".concat(n.id,"] Failed to reject INVITE")),n.logger.error(e.toString())}))},onMessage:function(e){e.accept().then(function(){n.delegate&&n.delegate.onMessageReceived&&n.delegate.onMessageReceived(e.request.body)})}},this.logger=this.userAgent.getLogger("sip.SimpleUser"),window.addEventListener("online",function(){n.logger.log("[".concat(n.id,"] Online")),n.attemptReconnection()})}Object.defineProperty(e.prototype,"id",{get:function(){return this.options.userAgentOptions&&this.options.userAgentOptions.displayName||"Anonymous"},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localMediaStream",{get:function(){var e,t=null===(e=this.session)||void 0===e?void 0:e.sessionDescriptionHandler;if(t){if(!(t instanceof SessionDescriptionHandler))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.localMediaStream}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteMediaStream",{get:function(){var e,t=null===(e=this.session)||void 0===e?void 0:e.sessionDescriptionHandler;if(t){if(!(t instanceof SessionDescriptionHandler))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.remoteMediaStream}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localAudioTrack",{get:function(){var e;return null===(e=this.localMediaStream)||void 0===e?void 0:e.getTracks().find(function(e){return"audio"===e.kind})},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localVideoTrack",{get:function(){var e;return null===(e=this.localMediaStream)||void 0===e?void 0:e.getTracks().find(function(e){return"video"===e.kind})},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteAudioTrack",{get:function(){var e;return null===(e=this.remoteMediaStream)||void 0===e?void 0:e.getTracks().find(function(e){return"audio"===e.kind})},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteVideoTrack",{get:function(){var e;return null===(e=this.remoteMediaStream)||void 0===e?void 0:e.getTracks().find(function(e){return"video"===e.kind})},enumerable:!1,configurable:!0}),e.prototype.connect=function(){return this.logger.log("[".concat(this.id,"] Connecting UserAgent...")),this.connectRequested=!0,this.userAgent.state!==UserAgentState.Started?this.userAgent.start():this.userAgent.reconnect()},e.prototype.disconnect=function(){return this.logger.log("[".concat(this.id,"] Disconnecting UserAgent...")),this.connectRequested=!1,this.userAgent.stop()},e.prototype.isConnected=function(){return this.userAgent.isConnected()},e.prototype.register=function(e,t){var n=this;return this.logger.log("[".concat(this.id,"] Registering UserAgent...")),this.registerRequested=!0,this.registerer||(this.registerer=new Registerer(this.userAgent,e),this.registerer.stateChange.addListener(function(e){switch(e){case RegistererState.Initial:break;case RegistererState.Registered:n.delegate&&n.delegate.onRegistered&&n.delegate.onRegistered();break;case RegistererState.Unregistered:n.delegate&&n.delegate.onUnregistered&&n.delegate.onUnregistered();break;case RegistererState.Terminated:n.registerer=void 0;break;default:throw new Error("Unknown registerer state.")}})),this.registerer.register(t).then(function(){})},e.prototype.unregister=function(e){return this.logger.log("[".concat(this.id,"] Unregistering UserAgent...")),this.registerRequested=!1,this.registerer?this.registerer.unregister(e).then(function(){}):Promise.resolve()},e.prototype.call=function(e,t,n){if(this.logger.log("[".concat(this.id,"] Beginning Session...")),this.session)return Promise.reject(new Error("Session already exists."));var r=UserAgent.makeURI(e);if(!r)return Promise.reject(new Error('Failed to create a valid URI from "'.concat(e,'"')));t||(t={}),t.sessionDescriptionHandlerOptions||(t.sessionDescriptionHandlerOptions={}),t.sessionDescriptionHandlerOptions.constraints||(t.sessionDescriptionHandlerOptions.constraints=this.constraints);var i=new Inviter(this.userAgent,r,t);return this.sendInvite(i,t,n).then(function(){})},e.prototype.hangup=function(){return this.logger.log("[".concat(this.id,"] Hangup...")),this.terminate()},e.prototype.answer=function(e){return this.logger.log("[".concat(this.id,"] Accepting Invitation...")),this.session?this.session instanceof Invitation?(e||(e={}),e.sessionDescriptionHandlerOptions||(e.sessionDescriptionHandlerOptions={}),e.sessionDescriptionHandlerOptions.constraints||(e.sessionDescriptionHandlerOptions.constraints=this.constraints),this.session.accept(e)):Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))},e.prototype.decline=function(){return this.logger.log("[".concat(this.id,"] rejecting Invitation...")),this.session?this.session instanceof Invitation?this.session.reject():Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))},e.prototype.hold=function(){return this.logger.log("[".concat(this.id,"] holding session...")),this.setHold(!0)},e.prototype.unhold=function(){return this.logger.log("[".concat(this.id,"] unholding session...")),this.setHold(!1)},e.prototype.isHeld=function(){return this.held},e.prototype.mute=function(){this.logger.log("[".concat(this.id,"] disabling media tracks...")),this.setMute(!0)},e.prototype.unmute=function(){this.logger.log("[".concat(this.id,"] enabling media tracks...")),this.setMute(!1)},e.prototype.isMuted=function(){return this.muted},e.prototype.sendDTMF=function(e){if(this.logger.log("[".concat(this.id,"] sending DTMF...")),!/^[0-9A-D#*,]$/.exec(e))return Promise.reject(new Error("Invalid DTMF tone."));if(!this.session)return Promise.reject(new Error("Session does not exist."));this.logger.log("[".concat(this.id,"] Sending DTMF tone: ").concat(e));var t={body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:"Signal="+e+"\r\nDuration=2000"}};return this.session.info({requestOptions:t}).then(function(){})},e.prototype.message=function(e,t){this.logger.log("[".concat(this.id,"] sending message..."));var n=UserAgent.makeURI(e);return n?new Messager(this.userAgent,n,t).message():Promise.reject(new Error('Failed to create a valid URI from "'.concat(e,'"')))},Object.defineProperty(e.prototype,"constraints",{get:function(){var e,t={audio:!0,video:!1};return(null===(e=this.options.media)||void 0===e?void 0:e.constraints)&&(t=__assign({},this.options.media.constraints)),t},enumerable:!1,configurable:!0}),e.prototype.attemptReconnection=function(e){var t=this;void 0===e&&(e=1);var n=this.options.reconnectionAttempts||3,r=this.options.reconnectionDelay||4;this.connectRequested?(this.attemptingReconnection&&this.logger.log("[".concat(this.id,"] Reconnection attempt already in progress")),e>n?this.logger.log("[".concat(this.id,"] Reconnection maximum attempts reached")):(1===e?this.logger.log("[".concat(this.id,"] Reconnection attempt ").concat(e," of ").concat(n," - trying")):this.logger.log("[".concat(this.id,"] Reconnection attempt ").concat(e," of ").concat(n," - trying in ").concat(r," seconds")),this.attemptingReconnection=!0,setTimeout(function(){if(!t.connectRequested)return t.logger.log("[".concat(t.id,"] Reconnection attempt ").concat(e," of ").concat(n," - aborted")),void(t.attemptingReconnection=!1);t.userAgent.reconnect().then(function(){t.logger.log("[".concat(t.id,"] Reconnection attempt ").concat(e," of ").concat(n," - succeeded")),t.attemptingReconnection=!1}).catch(function(r){t.logger.log("[".concat(t.id,"] Reconnection attempt ").concat(e," of ").concat(n," - failed")),t.logger.error(r.message),t.attemptingReconnection=!1,t.attemptReconnection(++e)})},1===e?0:1e3*r))):this.logger.log("[".concat(this.id,"] Reconnection not currently desired"))},e.prototype.cleanupMedia=function(){this.options.media&&(this.options.media.local&&this.options.media.local.video&&(this.options.media.local.video.srcObject=null,this.options.media.local.video.pause()),this.options.media.remote&&(this.options.media.remote.audio&&(this.options.media.remote.audio.srcObject=null,this.options.media.remote.audio.pause()),this.options.media.remote.video&&(this.options.media.remote.video.srcObject=null,this.options.media.remote.video.pause())))},e.prototype.enableReceiverTracks=function(e){if(!this.session)throw new Error("Session does not exist.");var t=this.session.sessionDescriptionHandler;if(!(t instanceof SessionDescriptionHandler))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");var n=t.peerConnection;if(!n)throw new Error("Peer connection closed.");n.getReceivers().forEach(function(t){t.track&&(t.track.enabled=e)})},e.prototype.enableSenderTracks=function(e){if(!this.session)throw new Error("Session does not exist.");var t=this.session.sessionDescriptionHandler;if(!(t instanceof SessionDescriptionHandler))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");var n=t.peerConnection;if(!n)throw new Error("Peer connection closed.");n.getSenders().forEach(function(t){t.track&&(t.track.enabled=e)})},e.prototype.initSession=function(e,t){var n=this;this.session=e,this.delegate&&this.delegate.onCallCreated&&this.delegate.onCallCreated(),this.session.stateChange.addListener(function(t){if(n.session===e)switch(n.logger.log("[".concat(n.id,"] session state changed to ").concat(t)),t){case SessionState.Initial:case SessionState.Establishing:break;case SessionState.Established:n.setupLocalMedia(),n.setupRemoteMedia(),n.delegate&&n.delegate.onCallAnswered&&n.delegate.onCallAnswered();break;case SessionState.Terminating:case SessionState.Terminated:n.session=void 0,n.cleanupMedia(),n.delegate&&n.delegate.onCallHangup&&n.delegate.onCallHangup();break;default:throw new Error("Unknown session state.")}}),this.session.delegate={onInfo:function(e){var t;if(void 0!==(null===(t=n.delegate)||void 0===t?void 0:t.onCallDTMFReceived)){var r=e.request.getHeader("content-type");if(r&&/^application\/dtmf-relay/i.exec(r)){var i=e.request.body.split("\r\n",2);if(2===i.length){var s,o=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;if(o.test(i[0])&&(s=i[0].replace(o,"$2")),s){var a,c=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;c.test(i[1])&&(a=parseInt(i[1].replace(c,"$2"),10)),a?e.accept().then(function(){if(n.delegate&&n.delegate.onCallDTMFReceived){if(!s||!a)throw new Error("Tone or duration undefined.");n.delegate.onCallDTMFReceived(s,a)}}).catch(function(e){n.logger.error(e.message)}):e.reject()}else e.reject()}else e.reject()}else e.reject()}else e.reject()},onRefer:function(e){e.accept().then(function(){return n.sendInvite(e.makeInviter(t),t)}).catch(function(e){n.logger.error(e.message)})}}},e.prototype.sendInvite=function(e,t,n){var r=this;return this.initSession(e,t),e.invite(n).then(function(){r.logger.log("[".concat(r.id,"] sent INVITE"))})},e.prototype.setHold=function(e){var t=this;if(!this.session)return Promise.reject(new Error("Session does not exist."));var n=this.session;if(this.held===e)return Promise.resolve();if(!(this.session.sessionDescriptionHandler instanceof SessionDescriptionHandler))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");var r={requestDelegate:{onAccept:function(){t.held=e,t.enableReceiverTracks(!t.held),t.enableSenderTracks(!t.held&&!t.muted),t.delegate&&t.delegate.onCallHold&&t.delegate.onCallHold(t.held)},onReject:function(){t.logger.warn("[".concat(t.id,"] re-invite request was rejected")),t.enableReceiverTracks(!t.held),t.enableSenderTracks(!t.held&&!t.muted),t.delegate&&t.delegate.onCallHold&&t.delegate.onCallHold(t.held)}}},i=n.sessionDescriptionHandlerOptionsReInvite;return i.hold=e,n.sessionDescriptionHandlerOptionsReInvite=i,this.session.invite(r).then(function(){t.enableReceiverTracks(!e),t.enableSenderTracks(!e&&!t.muted)}).catch(function(e){throw e instanceof RequestPendingError&&t.logger.error("[".concat(t.id,"] A hold request is already in progress.")),e})},e.prototype.setMute=function(e){this.session?this.session.state===SessionState.Established?(this.muted=e,this.enableSenderTracks(!this.held&&!this.muted)):this.logger.warn("[".concat(this.id,"] An established session is required to enable/disable media tracks")):this.logger.warn("[".concat(this.id,"] A session is required to enabled/disable media tracks"))},e.prototype.setupLocalMedia=function(){var e,t,n=this;if(!this.session)throw new Error("Session does not exist.");var r=null===(t=null===(e=this.options.media)||void 0===e?void 0:e.local)||void 0===t?void 0:t.video;if(r){var i=this.localMediaStream;if(!i)throw new Error("Local media stream undefiend.");r.srcObject=i,r.volume=0,r.play().catch(function(e){n.logger.error("[".concat(n.id,"] Failed to play local media")),n.logger.error(e.message)})}},e.prototype.setupRemoteMedia=function(){var e,t,n,r,i=this;if(!this.session)throw new Error("Session does not exist.");var s=(null===(t=null===(e=this.options.media)||void 0===e?void 0:e.remote)||void 0===t?void 0:t.video)||(null===(r=null===(n=this.options.media)||void 0===n?void 0:n.remote)||void 0===r?void 0:r.audio);if(s){var o=this.remoteMediaStream;if(!o)throw new Error("Remote media stream undefiend.");s.autoplay=!0,s.srcObject=o,s.play().catch(function(e){i.logger.error("[".concat(i.id,"] Failed to play remote media")),i.logger.error(e.message)}),o.onaddtrack=function(){i.logger.log("[".concat(i.id,"] Remote media onaddtrack")),s.load(),s.play().catch(function(e){i.logger.error("[".concat(i.id,"] Failed to play remote media")),i.logger.error(e.message)})}}},e.prototype.terminate=function(){var e=this;if(this.logger.log("[".concat(this.id,"] Terminating...")),!this.session)return Promise.reject(new Error("Session does not exist."));switch(this.session.state){case SessionState.Initial:if(this.session instanceof Inviter)return this.session.cancel().then(function(){e.logger.log("[".concat(e.id,"] Inviter never sent INVITE (canceled)"))});if(this.session instanceof Invitation)return this.session.reject().then(function(){e.logger.log("[".concat(e.id,"] Invitation rejected (sent 480)"))});throw new Error("Unknown session type.");case SessionState.Establishing:if(this.session instanceof Inviter)return this.session.cancel().then(function(){e.logger.log("[".concat(e.id,"] Inviter canceled (sent CANCEL)"))});if(this.session instanceof Invitation)return this.session.reject().then(function(){e.logger.log("[".concat(e.id,"] Invitation rejected (sent 480)"))});throw new Error("Unknown session type.");case SessionState.Established:return this.session.bye().then(function(){e.logger.log("[".concat(e.id,"] Session ended (sent BYE)"))});case SessionState.Terminating:case SessionState.Terminated:break;default:throw new Error("Unknown state")}return this.logger.log("[".concat(this.id,"] Terminating in state ").concat(this.session.state,", no action taken")),Promise.resolve()}}();var audioElement=getAudio("ueRemoteAudio"),UeWebrtc=function(){function e(e){var t=this;this.registerRequested=!1,this.attemptingReconnection=!1,this.connectRequested=!1,this.requestDelegate={onAccept:function(e){},onProgress:function(e){},onRedirect:function(e){},onReject:function(e){return __awaiter(t,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,this.disconnect()];case 1:return e.sent(),[4,this.connect()];case 2:return e.sent(),this.register(),[2]}})})},onTrying:function(e){}},this.accept=function(){return __awaiter(t,void 0,void 0,function(){var e;return __generator(this,function(t){return e={sessionDescriptionHandlerOptions:{constraints:{audio:!0,video:!1}}},[2,this.Ginvitation.accept(e)]})})},this.ueUnregisterWebrtc=function(){return __awaiter(t,void 0,void 0,function(){return __generator(this,function(e){return this.registerer?[2,this.registerer.unregister({all:!0}).then(function(e){}).catch(function(e){})]:[2,!1]})})};var n=UserAgent.makeURI("sip:"+e.sip+"@"+e.server);if(!n)throw new Error("Failed to create URI");var r={onConnect:function(e){return __awaiter(t,void 0,void 0,function(){return __generator(this,function(e){return this.registerer&&this.registerRequested&&this.registerer.register().catch(function(e){}),[2]})})},onDisconnect:function(e){t.registerer&&t.registerer.unregister().catch(function(e){}),e&&t.attemptReconnection()},onInvite:function(e){t.Ginvitation=e;var n=e;n.delegate={onRefer:function(e){}},n.stateChange.addListener(function(e){switch(e){case SessionState.Initial:case SessionState.Establishing:break;case SessionState.Established:var t=n.sessionDescriptionHandler;if(!(t&&t instanceof SessionDescriptionHandler))throw new Error("Invalid session description handler.");audioElement&&assignStream(t.remoteMediaStream,audioElement);break;case SessionState.Terminating:case SessionState.Terminated:break;default:throw new Error("Unknown session state.")}});var r={sessionDescriptionHandlerOptions:{constraints:{audio:!0,video:!1}}},i=t.Ginvitation.incomingInviteRequest.message.headers["X-Calltype"][0].raw;"callout"!==i&&"callTask"!==i||e.accept(r).then(function(){}).catch(function(e){})}},i={logBuiltinEnabled:!1,delegate:r,displayName:"WEBRTC",uri:n,transportOptions:{server:"wss://"+e.server},authorizationUsername:e.sip,authorizationHa1:e.secret,reconnectionDelay:0};this.userAgent=new UserAgent(i),window.addEventListener("online",function(){return __awaiter(t,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return window.sessionStorage.getItem("kickoff")?[2]:[4,this.attemptReconnection()];case 1:return e.sent(),this.register(),[2]}})})})}return e.prototype.register=function(){var e=this;return this.registerRequested=!0,this.registerer||(this.registerer=new Registerer(this.userAgent,{expires:10}),this.registerer.stateChange.addListener(function(t){switch(t){case RegistererState.Initial:case RegistererState.Registered:case RegistererState.Unregistered:break;case RegistererState.Terminated:e.registerer=void 0;break;default:throw new Error("Unknown registerer state.")}})),this.registerer.register({requestDelegate:this.requestDelegate}).then(function(){})},e.prototype.unregister=function(e){return this.registerRequested=!1,this.registerer?this.registerer.unregister(e).then(function(){}):Promise.resolve()},e.prototype.attemptReconnection=function(e){var t=this;void 0===e&&(e=1);this.connectRequested&&(e>1||(this.attemptingReconnection=!0,setTimeout(function(){t.connectRequested?t.userAgent.reconnect().then(function(){t.attemptingReconnection=!1}).catch(function(n){t.attemptingReconnection=!1,t.attemptReconnection(++e)}):t.attemptingReconnection=!1},0)))},e.prototype.sendDTMF=function(e){if(!/^[0-9A-D#*,]$/.exec(e))return Promise.reject(new Error("Invalid DTMF tone."));if(!this.Ginvitation)return Promise.reject(new Error("Session does not exist."));var t={body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:"Signal="+e+"\r\nDuration=2000"}};return this.Ginvitation.info({requestOptions:t}).then(function(){})},e.prototype.disconnect=function(){return this.connectRequested=!1,this.userAgent.stop()},e.prototype.connect=function(){return this.connectRequested=!0,this.userAgent.state!==UserAgentState.Started?this.userAgent.start():this.userAgent.reconnect()},e.prototype.isConnected=function(){return this.userAgent.isConnected()},e}();const version$2="3.7.7",VERSION=version$2,_hasBuffer="function"==typeof Buffer,_TD="function"==typeof TextDecoder?new TextDecoder:void 0,_TE="function"==typeof TextEncoder?new TextEncoder:void 0,b64ch="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",b64chs=Array.prototype.slice.call(b64ch),b64tab=(e=>{let t={};return e.forEach((e,n)=>t[e]=n),t})(b64chs),b64re=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,_fromCC=String.fromCharCode.bind(String),_U8Afrom="function"==typeof Uint8Array.from?Uint8Array.from.bind(Uint8Array):e=>new Uint8Array(Array.prototype.slice.call(e,0)),_mkUriSafe=e=>e.replace(/=/g,"").replace(/[+\/]/g,e=>"+"==e?"-":"_"),_tidyB64=e=>e.replace(/[^A-Za-z0-9\+\/]/g,""),btoaPolyfill=e=>{let t,n,r,i,s="";const o=e.length%3;for(let o=0;o<e.length;){if((n=e.charCodeAt(o++))>255||(r=e.charCodeAt(o++))>255||(i=e.charCodeAt(o++))>255)throw new TypeError("invalid character found");t=n<<16|r<<8|i,s+=b64chs[t>>18&63]+b64chs[t>>12&63]+b64chs[t>>6&63]+b64chs[63&t]}return o?s.slice(0,o-3)+"===".substring(o):s},_btoa="function"==typeof btoa?e=>btoa(e):_hasBuffer?e=>Buffer.from(e,"binary").toString("base64"):btoaPolyfill,_fromUint8Array=_hasBuffer?e=>Buffer.from(e).toString("base64"):e=>{let t=[];for(let n=0,r=e.length;n<r;n+=4096)t.push(_fromCC.apply(null,e.subarray(n,n+4096)));return _btoa(t.join(""))},fromUint8Array=(e,t=!1)=>t?_mkUriSafe(_fromUint8Array(e)):_fromUint8Array(e),cb_utob=e=>{if(e.length<2)return(t=e.charCodeAt(0))<128?e:t<2048?_fromCC(192|t>>>6)+_fromCC(128|63&t):_fromCC(224|t>>>12&15)+_fromCC(128|t>>>6&63)+_fromCC(128|63&t);var t=65536+1024*(e.charCodeAt(0)-55296)+(e.charCodeAt(1)-56320);return _fromCC(240|t>>>18&7)+_fromCC(128|t>>>12&63)+_fromCC(128|t>>>6&63)+_fromCC(128|63&t)},re_utob=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,utob=e=>e.replace(re_utob,cb_utob),_encode=_hasBuffer?e=>Buffer.from(e,"utf8").toString("base64"):_TE?e=>_fromUint8Array(_TE.encode(e)):e=>_btoa(utob(e)),encode=(e,t=!1)=>t?_mkUriSafe(_encode(e)):_encode(e),encodeURI=e=>encode(e,!0),re_btou=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,cb_btou=e=>{switch(e.length){case 4:var t=((7&e.charCodeAt(0))<<18|(63&e.charCodeAt(1))<<12|(63&e.charCodeAt(2))<<6|63&e.charCodeAt(3))-65536;return _fromCC((t>>>10)+55296)+_fromCC(56320+(1023&t));case 3:return _fromCC((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return _fromCC((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},btou=e=>e.replace(re_btou,cb_btou),atobPolyfill=e=>{if(e=e.replace(/\s+/g,""),!b64re.test(e))throw new TypeError("malformed base64.");e+="==".slice(2-(3&e.length));let t,n,r,i="";for(let s=0;s<e.length;)t=b64tab[e.charAt(s++)]<<18|b64tab[e.charAt(s++)]<<12|(n=b64tab[e.charAt(s++)])<<6|(r=b64tab[e.charAt(s++)]),i+=64===n?_fromCC(t>>16&255):64===r?_fromCC(t>>16&255,t>>8&255):_fromCC(t>>16&255,t>>8&255,255&t);return i},_atob="function"==typeof atob?e=>atob(_tidyB64(e)):_hasBuffer?e=>Buffer.from(e,"base64").toString("binary"):atobPolyfill,_toUint8Array=_hasBuffer?e=>_U8Afrom(Buffer.from(e,"base64")):e=>_U8Afrom(_atob(e).split("").map(e=>e.charCodeAt(0))),toUint8Array=e=>_toUint8Array(_unURI(e)),_decode=_hasBuffer?e=>Buffer.from(e,"base64").toString("utf8"):_TD?e=>_TD.decode(_toUint8Array(e)):e=>btou(_atob(e)),_unURI=e=>_tidyB64(e.replace(/[-_]/g,e=>"-"==e?"+":"/")),decode=e=>_decode(_unURI(e)),isValid=e=>{if("string"!=typeof e)return!1;const t=e.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(t)||!/[^\s0-9a-zA-Z\-_]/.test(t)},_noEnum=e=>({value:e,enumerable:!1,writable:!0,configurable:!0}),extendString=function(){const e=(e,t)=>Object.defineProperty(String.prototype,e,_noEnum(t));e("fromBase64",function(){return decode(this)}),e("toBase64",function(e){return encode(this,e)}),e("toBase64URI",function(){return encode(this,!0)}),e("toBase64URL",function(){return encode(this,!0)}),e("toUint8Array",function(){return toUint8Array(this)})},extendUint8Array=function(){const e=(e,t)=>Object.defineProperty(Uint8Array.prototype,e,_noEnum(t));e("toBase64",function(e){return fromUint8Array(this,e)}),e("toBase64URI",function(){return fromUint8Array(this,!0)}),e("toBase64URL",function(){return fromUint8Array(this,!0)})},extendBuiltins=()=>{extendString(),extendUint8Array()},gBase64={version:version$2,VERSION:VERSION,atob:_atob,atobPolyfill:atobPolyfill,btoa:_btoa,btoaPolyfill:btoaPolyfill,fromBase64:decode,toBase64:encode,encode:encode,encodeURI:encodeURI,encodeURL:encodeURI,utob:utob,btou:btou,decode:decode,isValid:isValid,fromUint8Array:fromUint8Array,toUint8Array:toUint8Array,extendString:extendString,extendUint8Array:extendUint8Array,extendBuiltins:extendBuiltins};var global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch(t){try{return cachedSetTimeout.call(null,e,0)}catch(t){return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch(t){try{return cachedClearTimeout.call(null,e)}catch(t){return cachedClearTimeout.call(this,e)}}}"function"==typeof global$1.setTimeout&&(cachedSetTimeout=setTimeout),"function"==typeof global$1.clearTimeout&&(cachedClearTimeout=clearTimeout);var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&&currentQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex<t;)currentQueue&&currentQueue[queueIndex].run();queueIndex=-1,t=queue.length}currentQueue=null,draining=!1,runClearTimeout(e)}}function nextTick(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];queue.push(new Item(e,t)),1!==queue.length||draining||runTimeout(drainQueue)}function Item(e,t){this.fun=e,this.array=t}Item.prototype.run=function(){this.fun.apply(null,this.array)};var title="browser",platform="browser",browser=!0,env={},argv=[],version$1="",versions={},release={},config={};function noop(){}var on=noop,addListener=noop,once=noop,off=noop,removeListener=noop,removeAllListeners=noop,emit=noop;function binding(e){throw new Error("process.binding is not supported")}function cwd(){return"/"}function chdir(e){throw new Error("process.chdir is not supported")}function umask(){return 0}var performance=global$1.performance||{},performanceNow=performance.now||performance.mozNow||performance.msNow||performance.oNow||performance.webkitNow||function(){return(new Date).getTime()};function hrtime(e){var t=.001*performanceNow.call(performance),n=Math.floor(t),r=Math.floor(t%1*1e9);return e&&(n-=e[0],(r-=e[1])<0&&(n--,r+=1e9)),[n,r]}var startTime=new Date;function uptime(){return(new Date-startTime)/1e3}var browser$1={nextTick:nextTick,title:title,browser:browser,env:env,argv:argv,version:version$1,versions:versions,on:on,addListener:addListener,once:once,off:off,removeListener:removeListener,removeAllListeners:removeAllListeners,emit:emit,binding:binding,cwd:cwd,chdir:chdir,umask:umask,hrtime:hrtime,platform:platform,release:release,config:config,uptime:uptime},commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var md5$1={exports:{}};(function(module){(function(){var ERROR="input is invalid type",WINDOW="object"==typeof window,root=WINDOW?window:{};root.JS_MD5_NO_WINDOW&&(WINDOW=!1);var WEB_WORKER=!WINDOW&&"object"==typeof self,NODE_JS=!root.JS_MD5_NO_NODE_JS&&"object"==typeof browser$1&&browser$1.versions&&browser$1.versions.node;NODE_JS?root=commonjsGlobal:WEB_WORKER&&(root=self);var COMMON_JS=!root.JS_MD5_NO_COMMON_JS&&module.exports,ARRAY_BUFFER=!root.JS_MD5_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,HEX_CHARS="0123456789abcdef".split(""),EXTRA=[128,32768,8388608,-2147483648],SHIFT=[0,8,16,24],OUTPUT_TYPES=["hex","array","digest","buffer","arrayBuffer","base64"],BASE64_ENCODE_CHAR="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),blocks=[],buffer8;if(ARRAY_BUFFER){var buffer=new ArrayBuffer(68);buffer8=new Uint8Array(buffer),blocks=new Uint32Array(buffer)}!root.JS_MD5_NO_NODE_JS&&Array.isArray||(Array.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),!ARRAY_BUFFER||!root.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});var createOutputMethod=function(e){return function(t){return new Md5(!0).update(t)[e]()}},createMethod=function(){var e=createOutputMethod("hex");NODE_JS&&(e=nodeWrap(e)),e.create=function(){return new Md5},e.update=function(t){return e.create().update(t)};for(var t=0;t<OUTPUT_TYPES.length;++t){var n=OUTPUT_TYPES[t];e[n]=createOutputMethod(n)}return e},nodeWrap=function(method){var crypto=eval("require('crypto')"),Buffer=eval("require('buffer').Buffer"),nodeMethod=function(e){if("string"==typeof e)return crypto.createHash("md5").update(e,"utf8").digest("hex");if(null==e)throw ERROR;return e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),Array.isArray(e)||ArrayBuffer.isView(e)||e.constructor===Buffer?crypto.createHash("md5").update(new Buffer(e)).digest("hex"):method(e)};return nodeMethod};function Md5(e){if(e)blocks[0]=blocks[16]=blocks[1]=blocks[2]=blocks[3]=blocks[4]=blocks[5]=blocks[6]=blocks[7]=blocks[8]=blocks[9]=blocks[10]=blocks[11]=blocks[12]=blocks[13]=blocks[14]=blocks[15]=0,this.blocks=blocks,this.buffer8=buffer8;else if(ARRAY_BUFFER){var t=new ArrayBuffer(68);this.buffer8=new Uint8Array(t),this.blocks=new Uint32Array(t)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}Md5.prototype.update=function(e){if(!this.finalized){var t,n=typeof e;if("string"!==n){if("object"!==n)throw ERROR;if(null===e)throw ERROR;if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!(Array.isArray(e)||ARRAY_BUFFER&&ArrayBuffer.isView(e)))throw ERROR;t=!0}for(var r,i,s=0,o=e.length,a=this.blocks,c=this.buffer8;s<o;){if(this.hashed&&(this.hashed=!1,a[0]=a[16],a[16]=a[1]=a[2]=a[3]=a[4]=a[5]=a[6]=a[7]=a[8]=a[9]=a[10]=a[11]=a[12]=a[13]=a[14]=a[15]=0),t)if(ARRAY_BUFFER)for(i=this.start;s<o&&i<64;++s)c[i++]=e[s];else for(i=this.start;s<o&&i<64;++s)a[i>>2]|=e[s]<<SHIFT[3&i++];else if(ARRAY_BUFFER)for(i=this.start;s<o&&i<64;++s)(r=e.charCodeAt(s))<128?c[i++]=r:r<2048?(c[i++]=192|r>>6,c[i++]=128|63&r):r<55296||r>=57344?(c[i++]=224|r>>12,c[i++]=128|r>>6&63,c[i++]=128|63&r):(r=65536+((1023&r)<<10|1023&e.charCodeAt(++s)),c[i++]=240|r>>18,c[i++]=128|r>>12&63,c[i++]=128|r>>6&63,c[i++]=128|63&r);else for(i=this.start;s<o&&i<64;++s)(r=e.charCodeAt(s))<128?a[i>>2]|=r<<SHIFT[3&i++]:r<2048?(a[i>>2]|=(192|r>>6)<<SHIFT[3&i++],a[i>>2]|=(128|63&r)<<SHIFT[3&i++]):r<55296||r>=57344?(a[i>>2]|=(224|r>>12)<<SHIFT[3&i++],a[i>>2]|=(128|r>>6&63)<<SHIFT[3&i++],a[i>>2]|=(128|63&r)<<SHIFT[3&i++]):(r=65536+((1023&r)<<10|1023&e.charCodeAt(++s)),a[i>>2]|=(240|r>>18)<<SHIFT[3&i++],a[i>>2]|=(128|r>>12&63)<<SHIFT[3&i++],a[i>>2]|=(128|r>>6&63)<<SHIFT[3&i++],a[i>>2]|=(128|63&r)<<SHIFT[3&i++]);this.lastByteIndex=i,this.bytes+=i-this.start,i>=64?(this.start=i-64,this.hash(),this.hashed=!0):this.start=i}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this}},Md5.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[t>>2]|=EXTRA[3&t],t>=56&&(this.hashed||this.hash(),e[0]=e[16],e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.bytes<<3,e[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},Md5.prototype.hash=function(){var e,t,n,r,i,s,o=this.blocks;this.first?t=((t=((e=((e=o[0]-680876937)<<7|e>>>25)-271733879|0)^(n=((n=(-271733879^(r=((r=(-1732584194^2004318071&e)+o[1]-117830708)<<12|r>>>20)+e|0)&(-271733879^e))+o[2]-1126478375)<<17|n>>>15)+r|0)&(r^e))+o[3]-1316259209)<<22|t>>>10)+n|0:(e=this.h0,t=this.h1,n=this.h2,t=((t+=((e=((e+=((r=this.h3)^t&(n^r))+o[0]-680876936)<<7|e>>>25)+t|0)^(n=((n+=(t^(r=((r+=(n^e&(t^n))+o[1]-389564586)<<12|r>>>20)+e|0)&(e^t))+o[2]+606105819)<<17|n>>>15)+r|0)&(r^e))+o[3]-1044525330)<<22|t>>>10)+n|0),t=((t+=((e=((e+=(r^t&(n^r))+o[4]-176418897)<<7|e>>>25)+t|0)^(n=((n+=(t^(r=((r+=(n^e&(t^n))+o[5]+1200080426)<<12|r>>>20)+e|0)&(e^t))+o[6]-1473231341)<<17|n>>>15)+r|0)&(r^e))+o[7]-45705983)<<22|t>>>10)+n|0,t=((t+=((e=((e+=(r^t&(n^r))+o[8]+1770035416)<<7|e>>>25)+t|0)^(n=((n+=(t^(r=((r+=(n^e&(t^n))+o[9]-1958414417)<<12|r>>>20)+e|0)&(e^t))+o[10]-42063)<<17|n>>>15)+r|0)&(r^e))+o[11]-1990404162)<<22|t>>>10)+n|0,t=((t+=((e=((e+=(r^t&(n^r))+o[12]+1804603682)<<7|e>>>25)+t|0)^(n=((n+=(t^(r=((r+=(n^e&(t^n))+o[13]-40341101)<<12|r>>>20)+e|0)&(e^t))+o[14]-1502002290)<<17|n>>>15)+r|0)&(r^e))+o[15]+1236535329)<<22|t>>>10)+n|0,t=((t+=((r=((r+=(t^n&((e=((e+=(n^r&(t^n))+o[1]-165796510)<<5|e>>>27)+t|0)^t))+o[6]-1069501632)<<9|r>>>23)+e|0)^e&((n=((n+=(e^t&(r^e))+o[11]+643717713)<<14|n>>>18)+r|0)^r))+o[0]-373897302)<<20|t>>>12)+n|0,t=((t+=((r=((r+=(t^n&((e=((e+=(n^r&(t^n))+o[5]-701558691)<<5|e>>>27)+t|0)^t))+o[10]+38016083)<<9|r>>>23)+e|0)^e&((n=((n+=(e^t&(r^e))+o[15]-660478335)<<14|n>>>18)+r|0)^r))+o[4]-405537848)<<20|t>>>12)+n|0,t=((t+=((r=((r+=(t^n&((e=((e+=(n^r&(t^n))+o[9]+568446438)<<5|e>>>27)+t|0)^t))+o[14]-1019803690)<<9|r>>>23)+e|0)^e&((n=((n+=(e^t&(r^e))+o[3]-187363961)<<14|n>>>18)+r|0)^r))+o[8]+1163531501)<<20|t>>>12)+n|0,t=((t+=((r=((r+=(t^n&((e=((e+=(n^r&(t^n))+o[13]-1444681467)<<5|e>>>27)+t|0)^t))+o[2]-51403784)<<9|r>>>23)+e|0)^e&((n=((n+=(e^t&(r^e))+o[7]+1735328473)<<14|n>>>18)+r|0)^r))+o[12]-1926607734)<<20|t>>>12)+n|0,t=((t+=((s=(r=((r+=((i=t^n)^(e=((e+=(i^r)+o[5]-378558)<<4|e>>>28)+t|0))+o[8]-2022574463)<<11|r>>>21)+e|0)^e)^(n=((n+=(s^t)+o[11]+1839030562)<<16|n>>>16)+r|0))+o[14]-35309556)<<23|t>>>9)+n|0,t=((t+=((s=(r=((r+=((i=t^n)^(e=((e+=(i^r)+o[1]-1530992060)<<4|e>>>28)+t|0))+o[4]+1272893353)<<11|r>>>21)+e|0)^e)^(n=((n+=(s^t)+o[7]-155497632)<<16|n>>>16)+r|0))+o[10]-1094730640)<<23|t>>>9)+n|0,t=((t+=((s=(r=((r+=((i=t^n)^(e=((e+=(i^r)+o[13]+681279174)<<4|e>>>28)+t|0))+o[0]-358537222)<<11|r>>>21)+e|0)^e)^(n=((n+=(s^t)+o[3]-722521979)<<16|n>>>16)+r|0))+o[6]+76029189)<<23|t>>>9)+n|0,t=((t+=((s=(r=((r+=((i=t^n)^(e=((e+=(i^r)+o[9]-640364487)<<4|e>>>28)+t|0))+o[12]-421815835)<<11|r>>>21)+e|0)^e)^(n=((n+=(s^t)+o[15]+530742520)<<16|n>>>16)+r|0))+o[2]-995338651)<<23|t>>>9)+n|0,t=((t+=((r=((r+=(t^((e=((e+=(n^(t|~r))+o[0]-198630844)<<6|e>>>26)+t|0)|~n))+o[7]+1126891415)<<10|r>>>22)+e|0)^((n=((n+=(e^(r|~t))+o[14]-1416354905)<<15|n>>>17)+r|0)|~e))+o[5]-57434055)<<21|t>>>11)+n|0,t=((t+=((r=((r+=(t^((e=((e+=(n^(t|~r))+o[12]+1700485571)<<6|e>>>26)+t|0)|~n))+o[3]-1894986606)<<10|r>>>22)+e|0)^((n=((n+=(e^(r|~t))+o[10]-1051523)<<15|n>>>17)+r|0)|~e))+o[1]-2054922799)<<21|t>>>11)+n|0,t=((t+=((r=((r+=(t^((e=((e+=(n^(t|~r))+o[8]+1873313359)<<6|e>>>26)+t|0)|~n))+o[15]-30611744)<<10|r>>>22)+e|0)^((n=((n+=(e^(r|~t))+o[6]-1560198380)<<15|n>>>17)+r|0)|~e))+o[13]+1309151649)<<21|t>>>11)+n|0,t=((t+=((r=((r+=(t^((e=((e+=(n^(t|~r))+o[4]-145523070)<<6|e>>>26)+t|0)|~n))+o[11]-1120210379)<<10|r>>>22)+e|0)^((n=((n+=(e^(r|~t))+o[2]+718787259)<<15|n>>>17)+r|0)|~e))+o[9]-343485551)<<21|t>>>11)+n|0,this.first?(this.h0=e+1732584193|0,this.h1=t-271733879|0,this.h2=n-1732584194|0,this.h3=r+271733878|0,this.first=!1):(this.h0=this.h0+e|0,this.h1=this.h1+t|0,this.h2=this.h2+n|0,this.h3=this.h3+r|0)},Md5.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3;return HEX_CHARS[e>>4&15]+HEX_CHARS[15&e]+HEX_CHARS[e>>12&15]+HEX_CHARS[e>>8&15]+HEX_CHARS[e>>20&15]+HEX_CHARS[e>>16&15]+HEX_CHARS[e>>28&15]+HEX_CHARS[e>>24&15]+HEX_CHARS[t>>4&15]+HEX_CHARS[15&t]+HEX_CHARS[t>>12&15]+HEX_CHARS[t>>8&15]+HEX_CHARS[t>>20&15]+HEX_CHARS[t>>16&15]+HEX_CHARS[t>>28&15]+HEX_CHARS[t>>24&15]+HEX_CHARS[n>>4&15]+HEX_CHARS[15&n]+HEX_CHARS[n>>12&15]+HEX_CHARS[n>>8&15]+HEX_CHARS[n>>20&15]+HEX_CHARS[n>>16&15]+HEX_CHARS[n>>28&15]+HEX_CHARS[n>>24&15]+HEX_CHARS[r>>4&15]+HEX_CHARS[15&r]+HEX_CHARS[r>>12&15]+HEX_CHARS[r>>8&15]+HEX_CHARS[r>>20&15]+HEX_CHARS[r>>16&15]+HEX_CHARS[r>>28&15]+HEX_CHARS[r>>24&15]},Md5.prototype.toString=Md5.prototype.hex,Md5.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3;return[255&e,e>>8&255,e>>16&255,e>>24&255,255&t,t>>8&255,t>>16&255,t>>24&255,255&n,n>>8&255,n>>16&255,n>>24&255,255&r,r>>8&255,r>>16&255,r>>24&255]},Md5.prototype.array=Md5.prototype.digest,Md5.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(16),t=new Uint32Array(e);return t[0]=this.h0,t[1]=this.h1,t[2]=this.h2,t[3]=this.h3,e},Md5.prototype.buffer=Md5.prototype.arrayBuffer,Md5.prototype.base64=function(){for(var e,t,n,r="",i=this.array(),s=0;s<15;)e=i[s++],t=i[s++],n=i[s++],r+=BASE64_ENCODE_CHAR[e>>>2]+BASE64_ENCODE_CHAR[63&(e<<4|t>>>4)]+BASE64_ENCODE_CHAR[63&(t<<2|n>>>6)]+BASE64_ENCODE_CHAR[63&n];return e=i[s],r+=BASE64_ENCODE_CHAR[e>>>2]+BASE64_ENCODE_CHAR[e<<4&63]+"=="};var exports=createMethod();COMMON_JS?module.exports=exports:root.md5=exports})()})(md5$1);var md5Exports=md5$1.exports,md5=getDefaultExportFromCjs(md5Exports),BI_RM="0123456789abcdefghijklmnopqrstuvwxyz";function int2char(e){return BI_RM.charAt(e)}function op_and(e,t){return e&t}function op_or(e,t){return e|t}function op_xor(e,t){return e^t}function op_andnot(e,t){return e&~t}function lbit(e){if(0==e)return-1;var t=0;return 65535&e||(e>>=16,t+=16),255&e||(e>>=8,t+=8),15&e||(e>>=4,t+=4),3&e||(e>>=2,t+=2),1&e||++t,t}function cbit(e){for(var t=0;0!=e;)e&=e-1,++t;return t}var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",b64pad="=",decoder$1;function hex2b64(e){var t,n,r="";for(t=0;t+3<=e.length;t+=3)n=parseInt(e.substring(t,t+3),16),r+=b64map.charAt(n>>6)+b64map.charAt(63&n);for(t+1==e.length?(n=parseInt(e.substring(t,t+1),16),r+=b64map.charAt(n<<2)):t+2==e.length&&(n=parseInt(e.substring(t,t+2),16),r+=b64map.charAt(n>>2)+b64map.charAt((3&n)<<4));(3&r.length)>0;)r+=b64pad;return r}function b64tohex(e){var t,n="",r=0,i=0;for(t=0;t<e.length&&e.charAt(t)!=b64pad;++t){var s=b64map.indexOf(e.charAt(t));s<0||(0==r?(n+=int2char(s>>2),i=3&s,r=1):1==r?(n+=int2char(i<<2|s>>4),i=15&s,r=2):2==r?(n+=int2char(i),n+=int2char(s>>2),i=3&s,r=3):(n+=int2char(i<<2|s>>4),n+=int2char(15&s),r=0))}return 1==r&&(n+=int2char(i<<2)),n}var Hex={decode:function(e){var t;if(void 0===decoder$1){var n="0123456789ABCDEF",r=" \f\n\r\t \u2028\u2029";for(decoder$1={},t=0;t<16;++t)decoder$1[n.charAt(t)]=t;for(n=n.toLowerCase(),t=10;t<16;++t)decoder$1[n.charAt(t)]=t;for(t=0;t<8;++t)decoder$1[r.charAt(t)]=-1}var i=[],s=0,o=0;for(t=0;t<e.length;++t){var a=e.charAt(t);if("="==a)break;if(-1!=(a=decoder$1[a])){if(void 0===a)throw new Error("Illegal character at offset "+t);s|=a,++o>=2?(i[i.length]=s,s=0,o=0):s<<=4}}if(o)throw new Error("Hex encoding incomplete: 4 bits missing");return i}},decoder,Base64={decode:function(e){var t;if(void 0===decoder){var n="= \f\n\r\t \u2028\u2029";for(decoder=Object.create(null),t=0;t<64;++t)decoder["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(t)]=t;for(decoder["-"]=62,decoder._=63,t=0;t<9;++t)decoder[n.charAt(t)]=-1}var r=[],i=0,s=0;for(t=0;t<e.length;++t){var o=e.charAt(t);if("="==o)break;if(-1!=(o=decoder[o])){if(void 0===o)throw new Error("Illegal character at offset "+t);i|=o,++s>=4?(r[r.length]=i>>16,r[r.length]=i>>8&255,r[r.length]=255&i,i=0,s=0):i<<=6}}switch(s){case 1:throw new Error("Base64 encoding incomplete: at least 2 bits missing");case 2:r[r.length]=i>>10;break;case 3:r[r.length]=i>>16,r[r.length]=i>>8&255}return r},re:/-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/,unarmor:function(e){var t=Base64.re.exec(e);if(t)if(t[1])e=t[1];else{if(!t[2])throw new Error("RegExp out of sync");e=t[2]}return Base64.decode(e)}},max=1e13,Int10=function(){function e(e){this.buf=[+e||0]}return e.prototype.mulAdd=function(e,t){var n,r,i=this.buf,s=i.length;for(n=0;n<s;++n)(r=i[n]*e+t)<max?t=0:r-=(t=0|r/max)*max,i[n]=r;t>0&&(i[n]=t)},e.prototype.sub=function(e){var t,n,r=this.buf,i=r.length;for(t=0;t<i;++t)(n=r[t]-e)<0?(n+=max,e=1):e=0,r[t]=n;for(;0===r[r.length-1];)r.pop()},e.prototype.toString=function(e){if(10!=(e||10))throw new Error("only base 10 is supported");for(var t=this.buf,n=t[t.length-1].toString(),r=t.length-2;r>=0;--r)n+=(max+t[r]).toString().substring(1);return n},e.prototype.valueOf=function(){for(var e=this.buf,t=0,n=e.length-1;n>=0;--n)t=t*max+e[n];return t},e.prototype.simplify=function(){var e=this.buf;return 1==e.length?e[0]:this},e}(),ellipsis="…",reTimeS=/^(\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/,reTimeL=/^(\d\d\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/;function stringCut(e,t){return e.length>t&&(e=e.substring(0,t)+ellipsis),e}var Stream=function(){function e(t,n){this.hexDigits="0123456789ABCDEF",t instanceof e?(this.enc=t.enc,this.pos=t.pos):(this.enc=t,this.pos=n)}return e.prototype.get=function(e){if(void 0===e&&(e=this.pos++),e>=this.enc.length)throw new Error("Requesting byte offset ".concat(e," on a stream of length ").concat(this.enc.length));return"string"==typeof this.enc?this.enc.charCodeAt(e):this.enc[e]},e.prototype.hexByte=function(e){return this.hexDigits.charAt(e>>4&15)+this.hexDigits.charAt(15&e)},e.prototype.hexDump=function(e,t,n){for(var r="",i=e;i<t;++i)if(r+=this.hexByte(this.get(i)),!0!==n)switch(15&i){case 7:r+=" ";break;case 15:r+="\n";break;default:r+=" "}return r},e.prototype.isASCII=function(e,t){for(var n=e;n<t;++n){var r=this.get(n);if(r<32||r>176)return!1}return!0},e.prototype.parseStringISO=function(e,t){for(var n="",r=e;r<t;++r)n+=String.fromCharCode(this.get(r));return n},e.prototype.parseStringUTF=function(e,t){for(var n="",r=e;r<t;){var i=this.get(r++);n+=i<128?String.fromCharCode(i):i>191&&i<224?String.fromCharCode((31&i)<<6|63&this.get(r++)):String.fromCharCode((15&i)<<12|(63&this.get(r++))<<6|63&this.get(r++))}return n},e.prototype.parseStringBMP=function(e,t){for(var n,r,i="",s=e;s<t;)n=this.get(s++),r=this.get(s++),i+=String.fromCharCode(n<<8|r);return i},e.prototype.parseTime=function(e,t,n){var r=this.parseStringISO(e,t),i=(n?reTimeS:reTimeL).exec(r);return i?(n&&(i[1]=+i[1],i[1]+=+i[1]<70?2e3:1900),r=i[1]+"-"+i[2]+"-"+i[3]+" "+i[4],i[5]&&(r+=":"+i[5],i[6]&&(r+=":"+i[6],i[7]&&(r+="."+i[7]))),i[8]&&(r+=" UTC","Z"!=i[8]&&(r+=i[8],i[9]&&(r+=":"+i[9]))),r):"Unrecognized time: "+r},e.prototype.parseInteger=function(e,t){for(var n,r=this.get(e),i=r>127,s=i?255:0,o="";r==s&&++e<t;)r=this.get(e);if(0===(n=t-e))return i?-1:0;if(n>4){for(o=r,n<<=3;!(128&(+o^s));)o=+o<<1,--n;o="("+n+" bit)\n"}i&&(r-=256);for(var a=new Int10(r),c=e+1;c<t;++c)a.mulAdd(256,this.get(c));return o+a.toString()},e.prototype.parseBitString=function(e,t,n){for(var r=this.get(e),i="("+((t-e-1<<3)-r)+" bit)\n",s="",o=e+1;o<t;++o){for(var a=this.get(o),c=o==t-1?r:0,u=7;u>=c;--u)s+=a>>u&1?"1":"0";if(s.length>n)return i+stringCut(s,n)}return i+s},e.prototype.parseOctetString=function(e,t,n){if(this.isASCII(e,t))return stringCut(this.parseStringISO(e,t),n);var r=t-e,i="("+r+" byte)\n";r>(n/=2)&&(t=e+n);for(var s=e;s<t;++s)i+=this.hexByte(this.get(s));return r>n&&(i+=ellipsis),i},e.prototype.parseOID=function(e,t,n){for(var r="",i=new Int10,s=0,o=e;o<t;++o){var a=this.get(o);if(i.mulAdd(128,127&a),s+=7,!(128&a)){if(""===r)if((i=i.simplify())instanceof Int10)i.sub(80),r="2."+i.toString();else{var c=i<80?i<40?0:1:2;r=c+"."+(i-40*c)}else r+="."+i.toString();if(r.length>n)return stringCut(r,n);i=new Int10,s=0}}return s>0&&(r+=".incomplete"),r},e}(),ASN1=function(){function e(e,t,n,r,i){if(!(r instanceof ASN1Tag))throw new Error("Invalid tag value.");this.stream=e,this.header=t,this.length=n,this.tag=r,this.sub=i}return e.prototype.typeName=function(){switch(this.tag.tagClass){case 0:switch(this.tag.tagNumber){case 0:return"EOC";case 1:return"BOOLEAN";case 2:return"INTEGER";case 3:return"BIT_STRING";case 4:return"OCTET_STRING";case 5:return"NULL";case 6:return"OBJECT_IDENTIFIER";case 7:return"ObjectDescriptor";case 8:return"EXTERNAL";case 9:return"REAL";case 10:return"ENUMERATED";case 11:return"EMBEDDED_PDV";case 12:return"UTF8String";case 16:return"SEQUENCE";case 17:return"SET";case 18:return"NumericString";case 19:return"PrintableString";case 20:return"TeletexString";case 21:return"VideotexString";case 22:return"IA5String";case 23:return"UTCTime";case 24:return"GeneralizedTime";case 25:return"GraphicString";case 26:return"VisibleString";case 27:return"GeneralString";case 28:return"UniversalString";case 30:return"BMPString"}return"Universal_"+this.tag.tagNumber.toString();case 1:return"Application_"+this.tag.tagNumber.toString();case 2:return"["+this.tag.tagNumber.toString()+"]";case 3:return"Private_"+this.tag.tagNumber.toString()}},e.prototype.content=function(e){if(void 0===this.tag)return null;void 0===e&&(e=1/0);var t=this.posContent(),n=Math.abs(this.length);if(!this.tag.isUniversal())return null!==this.sub?"("+this.sub.length+" elem)":this.stream.parseOctetString(t,t+n,e);switch(this.tag.tagNumber){case 1:return 0===this.stream.get(t)?"false":"true";case 2:return this.stream.parseInteger(t,t+n);case 3:return this.sub?"("+this.sub.length+" elem)":this.stream.parseBitString(t,t+n,e);case 4:return this.sub?"("+this.sub.length+" elem)":this.stream.parseOctetString(t,t+n,e);case 6:return this.stream.parseOID(t,t+n,e);case 16:case 17:return null!==this.sub?"("+this.sub.length+" elem)":"(no elem)";case 12:return stringCut(this.stream.parseStringUTF(t,t+n),e);case 18:case 19:case 20:case 21:case 22:case 26:return stringCut(this.stream.parseStringISO(t,t+n),e);case 30:return stringCut(this.stream.parseStringBMP(t,t+n),e);case 23:case 24:return this.stream.parseTime(t,t+n,23==this.tag.tagNumber)}return null},e.prototype.toString=function(){return this.typeName()+"@"+this.stream.pos+"[header:"+this.header+",length:"+this.length+",sub:"+(null===this.sub?"null":this.sub.length)+"]"},e.prototype.toPrettyString=function(e){void 0===e&&(e="");var t=e+this.typeName()+" @"+this.stream.pos;if(this.length>=0&&(t+="+"),t+=this.length,this.tag.tagConstructed?t+=" (constructed)":!this.tag.isUniversal()||3!=this.tag.tagNumber&&4!=this.tag.tagNumber||null===this.sub||(t+=" (encapsulates)"),t+="\n",null!==this.sub){e+=" ";for(var n=0,r=this.sub.length;n<r;++n)t+=this.sub[n].toPrettyString(e)}return t},e.prototype.posStart=function(){return this.stream.pos},e.prototype.posContent=function(){return this.stream.pos+this.header},e.prototype.posEnd=function(){return this.stream.pos+this.header+Math.abs(this.length)},e.prototype.toHexString=function(){return this.stream.hexDump(this.posStart(),this.posEnd(),!0)},e.decodeLength=function(e){var t=e.get(),n=127&t;if(n==t)return n;if(n>6)throw new Error("Length over 48 bits not supported at position "+(e.pos-1));if(0===n)return null;t=0;for(var r=0;r<n;++r)t=256*t+e.get();return t},e.prototype.getHexStringValue=function(){var e=this.toHexString(),t=2*this.header,n=2*this.length;return e.substr(t,n)},e.decode=function(t){var n;n=t instanceof Stream?t:new Stream(t,0);var r=new Stream(n),i=new ASN1Tag(n),s=e.decodeLength(n),o=n.pos,a=o-r.pos,c=null,u=function(){var t=[];if(null!==s){for(var r=o+s;n.pos<r;)t[t.length]=e.decode(n);if(n.pos!=r)throw new Error("Content size is not correct for container starting at offset "+o)}else try{for(;;){var i=e.decode(n);if(i.tag.isEOC())break;t[t.length]=i}s=o-n.pos}catch(e){throw new Error("Exception while decoding undefined length content: "+e)}return t};if(i.tagConstructed)c=u();else if(i.isUniversal()&&(3==i.tagNumber||4==i.tagNumber))try{if(3==i.tagNumber&&0!=n.get())throw new Error("BIT STRINGs with unused bits cannot encapsulate.");c=u();for(var l=0;l<c.length;++l)if(c[l].tag.isEOC())throw new Error("EOC is not supposed to be actual content.")}catch(e){c=null}if(null===c){if(null===s)throw new Error("We can't skip over an invalid tag with undefined length at offset "+o);n.pos=o+Math.abs(s)}return new e(r,a,s,i,c)},e}(),ASN1Tag=function(){function e(e){var t=e.get();if(this.tagClass=t>>6,this.tagConstructed=!!(32&t),this.tagNumber=31&t,31==this.tagNumber){var n=new Int10;do{t=e.get(),n.mulAdd(128,127&t)}while(128&t);this.tagNumber=n.simplify()}}return e.prototype.isUniversal=function(){return 0===this.tagClass},e.prototype.isEOC=function(){return 0===this.tagClass&&0===this.tagNumber},e}(),dbits,canary=0xdeadbeefcafe,j_lm=15715070==(16777215&canary),lowprimes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],lplim=(1<<26)/lowprimes[lowprimes.length-1],BigInteger=function(){function e(e,t,n){null!=e&&("number"==typeof e?this.fromNumber(e,t,n):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}return e.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var n,r=(1<<t)-1,i=!1,s="",o=this.t,a=this.DB-o*this.DB%t;if(o-- >0)for(a<this.DB&&(n=this[o]>>a)>0&&(i=!0,s=int2char(n));o>=0;)a<t?(n=(this[o]&(1<<a)-1)<<t-a,n|=this[--o]>>(a+=this.DB-t)):(n=this[o]>>(a-=t)&r,a<=0&&(a+=this.DB,--o)),n>0&&(i=!0),i&&(s+=int2char(n));return i?s:"0"},e.prototype.negate=function(){var t=nbi();return e.ZERO.subTo(this,t),t},e.prototype.abs=function(){return this.s<0?this.negate():this},e.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var n=this.t;if(0!=(t=n-e.t))return this.s<0?-t:t;for(;--n>=0;)if(0!=(t=this[n]-e[n]))return t;return 0},e.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+nbits(this[this.t-1]^this.s&this.DM)},e.prototype.mod=function(t){var n=nbi();return this.abs().divRemTo(t,null,n),this.s<0&&n.compareTo(e.ZERO)>0&&t.subTo(n,n),n},e.prototype.modPowInt=function(e,t){var n;return n=e<256||t.isEven()?new Classic(t):new Montgomery(t),this.exp(e,n)},e.prototype.clone=function(){var e=nbi();return this.copyTo(e),e},e.prototype.intValue=function(){if(this.s<0){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<<this.DB|this[0]},e.prototype.byteValue=function(){return 0==this.t?this.s:this[0]<<24>>24},e.prototype.shortValue=function(){return 0==this.t?this.s:this[0]<<16>>16},e.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1},e.prototype.toByteArray=function(){var e=this.t,t=[];t[0]=this.s;var n,r=this.DB-e*this.DB%8,i=0;if(e-- >0)for(r<this.DB&&(n=this[e]>>r)!=(this.s&this.DM)>>r&&(t[i++]=n|this.s<<this.DB-r);e>=0;)r<8?(n=(this[e]&(1<<r)-1)<<8-r,n|=this[--e]>>(r+=this.DB-8)):(n=this[e]>>(r-=8)&255,r<=0&&(r+=this.DB,--e)),128&n&&(n|=-256),0==i&&(128&this.s)!=(128&n)&&++i,(i>0||n!=this.s)&&(t[i++]=n);return t},e.prototype.equals=function(e){return 0==this.compareTo(e)},e.prototype.min=function(e){return this.compareTo(e)<0?this:e},e.prototype.max=function(e){return this.compareTo(e)>0?this:e},e.prototype.and=function(e){var t=nbi();return this.bitwiseTo(e,op_and,t),t},e.prototype.or=function(e){var t=nbi();return this.bitwiseTo(e,op_or,t),t},e.prototype.xor=function(e){var t=nbi();return this.bitwiseTo(e,op_xor,t),t},e.prototype.andNot=function(e){var t=nbi();return this.bitwiseTo(e,op_andnot,t),t},e.prototype.not=function(){for(var e=nbi(),t=0;t<this.t;++t)e[t]=this.DM&~this[t];return e.t=this.t,e.s=~this.s,e},e.prototype.shiftLeft=function(e){var t=nbi();return e<0?this.rShiftTo(-e,t):this.lShiftTo(e,t),t},e.prototype.shiftRight=function(e){var t=nbi();return e<0?this.lShiftTo(-e,t):this.rShiftTo(e,t),t},e.prototype.getLowestSetBit=function(){for(var e=0;e<this.t;++e)if(0!=this[e])return e*this.DB+lbit(this[e]);return this.s<0?this.t*this.DB:-1},e.prototype.bitCount=function(){for(var e=0,t=this.s&this.DM,n=0;n<this.t;++n)e+=cbit(this[n]^t);return e},e.prototype.testBit=function(e){var t=Math.floor(e/this.DB);return t>=this.t?0!=this.s:!!(this[t]&1<<e%this.DB)},e.prototype.setBit=function(e){return this.changeBit(e,op_or)},e.prototype.clearBit=function(e){return this.changeBit(e,op_andnot)},e.prototype.flipBit=function(e){return this.changeBit(e,op_xor)},e.prototype.add=function(e){var t=nbi();return this.addTo(e,t),t},e.prototype.subtract=function(e){var t=nbi();return this.subTo(e,t),t},e.prototype.multiply=function(e){var t=nbi();return this.multiplyTo(e,t),t},e.prototype.divide=function(e){var t=nbi();return this.divRemTo(e,t,null),t},e.prototype.remainder=function(e){var t=nbi();return this.divRemTo(e,null,t),t},e.prototype.divideAndRemainder=function(e){var t=nbi(),n=nbi();return this.divRemTo(e,t,n),[t,n]},e.prototype.modPow=function(e,t){var n,r,i=e.bitLength(),s=nbv(1);if(i<=0)return s;n=i<18?1:i<48?3:i<144?4:i<768?5:6,r=i<8?new Classic(t):t.isEven()?new Barrett(t):new Montgomery(t);var o=[],a=3,c=n-1,u=(1<<n)-1;if(o[1]=r.convert(this),n>1){var l=nbi();for(r.sqrTo(o[1],l);a<=u;)o[a]=nbi(),r.mulTo(l,o[a-2],o[a]),a+=2}var h,d,p=e.t-1,g=!0,f=nbi();for(i=nbits(e[p])-1;p>=0;){for(i>=c?h=e[p]>>i-c&u:(h=(e[p]&(1<<i+1)-1)<<c-i,p>0&&(h|=e[p-1]>>this.DB+i-c)),a=n;!(1&h);)h>>=1,--a;if((i-=a)<0&&(i+=this.DB,--p),g)o[h].copyTo(s),g=!1;else{for(;a>1;)r.sqrTo(s,f),r.sqrTo(f,s),a-=2;a>0?r.sqrTo(s,f):(d=s,s=f,f=d),r.mulTo(f,o[h],s)}for(;p>=0&&!(e[p]&1<<i);)r.sqrTo(s,f),d=s,s=f,f=d,--i<0&&(i=this.DB-1,--p)}return r.revert(s)},e.prototype.modInverse=function(t){var n=t.isEven();if(this.isEven()&&n||0==t.signum())return e.ZERO;for(var r=t.clone(),i=this.clone(),s=nbv(1),o=nbv(0),a=nbv(0),c=nbv(1);0!=r.signum();){for(;r.isEven();)r.rShiftTo(1,r),n?(s.isEven()&&o.isEven()||(s.addTo(this,s),o.subTo(t,o)),s.rShiftTo(1,s)):o.isEven()||o.subTo(t,o),o.rShiftTo(1,o);for(;i.isEven();)i.rShiftTo(1,i),n?(a.isEven()&&c.isEven()||(a.addTo(this,a),c.subTo(t,c)),a.rShiftTo(1,a)):c.isEven()||c.subTo(t,c),c.rShiftTo(1,c);r.compareTo(i)>=0?(r.subTo(i,r),n&&s.subTo(a,s),o.subTo(c,o)):(i.subTo(r,i),n&&a.subTo(s,a),c.subTo(o,c))}return 0!=i.compareTo(e.ONE)?e.ZERO:c.compareTo(t)>=0?c.subtract(t):c.signum()<0?(c.addTo(t,c),c.signum()<0?c.add(t):c):c},e.prototype.pow=function(e){return this.exp(e,new NullExp)},e.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),n=e.s<0?e.negate():e.clone();if(t.compareTo(n)<0){var r=t;t=n,n=r}var i=t.getLowestSetBit(),s=n.getLowestSetBit();if(s<0)return t;for(i<s&&(s=i),s>0&&(t.rShiftTo(s,t),n.rShiftTo(s,n));t.signum()>0;)(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),(i=n.getLowestSetBit())>0&&n.rShiftTo(i,n),t.compareTo(n)>=0?(t.subTo(n,t),t.rShiftTo(1,t)):(n.subTo(t,n),n.rShiftTo(1,n));return s>0&&n.lShiftTo(s,n),n},e.prototype.isProbablePrime=function(e){var t,n=this.abs();if(1==n.t&&n[0]<=lowprimes[lowprimes.length-1]){for(t=0;t<lowprimes.length;++t)if(n[0]==lowprimes[t])return!0;return!1}if(n.isEven())return!1;for(t=1;t<lowprimes.length;){for(var r=lowprimes[t],i=t+1;i<lowprimes.length&&r<lplim;)r*=lowprimes[i++];for(r=n.modInt(r);t<i;)if(r%lowprimes[t++]==0)return!1}return n.millerRabin(e)},e.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e[t]=this[t];e.t=this.t,e.s=this.s},e.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this[0]=e:e<-1?this[0]=e+this.DV:this.t=0},e.prototype.fromString=function(t,n){var r;if(16==n)r=4;else if(8==n)r=3;else if(256==n)r=8;else if(2==n)r=1;else if(32==n)r=5;else{if(4!=n)return void this.fromRadix(t,n);r=2}this.t=0,this.s=0;for(var i=t.length,s=!1,o=0;--i>=0;){var a=8==r?255&+t[i]:intAt(t,i);a<0?"-"==t.charAt(i)&&(s=!0):(s=!1,0==o?this[this.t++]=a:o+r>this.DB?(this[this.t-1]|=(a&(1<<this.DB-o)-1)<<o,this[this.t++]=a>>this.DB-o):this[this.t-1]|=a<<o,(o+=r)>=this.DB&&(o-=this.DB))}8==r&&128&+t[0]&&(this.s=-1,o>0&&(this[this.t-1]|=(1<<this.DB-o)-1<<o)),this.clamp(),s&&e.ZERO.subTo(this,this)},e.prototype.clamp=function(){for(var e=this.s&this.DM;this.t>0&&this[this.t-1]==e;)--this.t},e.prototype.dlShiftTo=function(e,t){var n;for(n=this.t-1;n>=0;--n)t[n+e]=this[n];for(n=e-1;n>=0;--n)t[n]=0;t.t=this.t+e,t.s=this.s},e.prototype.drShiftTo=function(e,t){for(var n=e;n<this.t;++n)t[n-e]=this[n];t.t=Math.max(this.t-e,0),t.s=this.s},e.prototype.lShiftTo=function(e,t){for(var n=e%this.DB,r=this.DB-n,i=(1<<r)-1,s=Math.floor(e/this.DB),o=this.s<<n&this.DM,a=this.t-1;a>=0;--a)t[a+s+1]=this[a]>>r|o,o=(this[a]&i)<<n;for(a=s-1;a>=0;--a)t[a]=0;t[s]=o,t.t=this.t+s+1,t.s=this.s,t.clamp()},e.prototype.rShiftTo=function(e,t){t.s=this.s;var n=Math.floor(e/this.DB);if(n>=this.t)t.t=0;else{var r=e%this.DB,i=this.DB-r,s=(1<<r)-1;t[0]=this[n]>>r;for(var o=n+1;o<this.t;++o)t[o-n-1]|=(this[o]&s)<<i,t[o-n]=this[o]>>r;r>0&&(t[this.t-n-1]|=(this.s&s)<<i),t.t=this.t-n,t.clamp()}},e.prototype.subTo=function(e,t){for(var n=0,r=0,i=Math.min(e.t,this.t);n<i;)r+=this[n]-e[n],t[n++]=r&this.DM,r>>=this.DB;if(e.t<this.t){for(r-=e.s;n<this.t;)r+=this[n],t[n++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;n<e.t;)r-=e[n],t[n++]=r&this.DM,r>>=this.DB;r-=e.s}t.s=r<0?-1:0,r<-1?t[n++]=this.DV+r:r>0&&(t[n++]=r),t.t=n,t.clamp()},e.prototype.multiplyTo=function(t,n){var r=this.abs(),i=t.abs(),s=r.t;for(n.t=s+i.t;--s>=0;)n[s]=0;for(s=0;s<i.t;++s)n[s+r.t]=r.am(0,i[s],n,s,0,r.t);n.s=0,n.clamp(),this.s!=t.s&&e.ZERO.subTo(n,n)},e.prototype.squareTo=function(e){for(var t=this.abs(),n=e.t=2*t.t;--n>=0;)e[n]=0;for(n=0;n<t.t-1;++n){var r=t.am(n,t[n],e,2*n,0,1);(e[n+t.t]+=t.am(n+1,2*t[n],e,2*n+1,r,t.t-n-1))>=t.DV&&(e[n+t.t]-=t.DV,e[n+t.t+1]=1)}e.t>0&&(e[e.t-1]+=t.am(n,t[n],e,2*n,0,1)),e.s=0,e.clamp()},e.prototype.divRemTo=function(t,n,r){var i=t.abs();if(!(i.t<=0)){var s=this.abs();if(s.t<i.t)return null!=n&&n.fromInt(0),void(null!=r&&this.copyTo(r));null==r&&(r=nbi());var o=nbi(),a=this.s,c=t.s,u=this.DB-nbits(i[i.t-1]);u>0?(i.lShiftTo(u,o),s.lShiftTo(u,r)):(i.copyTo(o),s.copyTo(r));var l=o.t,h=o[l-1];if(0!=h){var d=h*(1<<this.F1)+(l>1?o[l-2]>>this.F2:0),p=this.FV/d,g=(1<<this.F1)/d,f=1<<this.F2,m=r.t,v=m-l,y=null==n?nbi():n;for(o.dlShiftTo(v,y),r.compareTo(y)>=0&&(r[r.t++]=1,r.subTo(y,r)),e.ONE.dlShiftTo(l,y),y.subTo(o,o);o.t<l;)o[o.t++]=0;for(;--v>=0;){var b=r[--m]==h?this.DM:Math.floor(r[m]*p+(r[m-1]+f)*g);if((r[m]+=o.am(0,b,r,v,0,l))<b)for(o.dlShiftTo(v,y),r.subTo(y,r);r[m]<--b;)r.subTo(y,r)}null!=n&&(r.drShiftTo(l,n),a!=c&&e.ZERO.subTo(n,n)),r.t=l,r.clamp(),u>0&&r.rShiftTo(u,r),a<0&&e.ZERO.subTo(r,r)}}},e.prototype.invDigit=function(){if(this.t<1)return 0;var e=this[0];if(!(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},e.prototype.isEven=function(){return 0==(this.t>0?1&this[0]:this.s)},e.prototype.exp=function(t,n){if(t>4294967295||t<1)return e.ONE;var r=nbi(),i=nbi(),s=n.convert(this),o=nbits(t)-1;for(s.copyTo(r);--o>=0;)if(n.sqrTo(r,i),(t&1<<o)>0)n.mulTo(i,s,r);else{var a=r;r=i,i=a}return n.revert(r)},e.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},e.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),n=Math.pow(e,t),r=nbv(n),i=nbi(),s=nbi(),o="";for(this.divRemTo(r,i,s);i.signum()>0;)o=(n+s.intValue()).toString(e).substr(1)+o,i.divRemTo(r,i,s);return s.intValue().toString(e)+o},e.prototype.fromRadix=function(t,n){this.fromInt(0),null==n&&(n=10);for(var r=this.chunkSize(n),i=Math.pow(n,r),s=!1,o=0,a=0,c=0;c<t.length;++c){var u=intAt(t,c);u<0?"-"==t.charAt(c)&&0==this.signum()&&(s=!0):(a=n*a+u,++o>=r&&(this.dMultiply(i),this.dAddOffset(a,0),o=0,a=0))}o>0&&(this.dMultiply(Math.pow(n,o)),this.dAddOffset(a,0)),s&&e.ZERO.subTo(this,this)},e.prototype.fromNumber=function(t,n,r){if("number"==typeof n)if(t<2)this.fromInt(1);else for(this.fromNumber(t,r),this.testBit(t-1)||this.bitwiseTo(e.ONE.shiftLeft(t-1),op_or,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(n);)this.dAddOffset(2,0),this.bitLength()>t&&this.subTo(e.ONE.shiftLeft(t-1),this);else{var i=[],s=7&t;i.length=1+(t>>3),n.nextBytes(i),s>0?i[0]&=(1<<s)-1:i[0]=0,this.fromString(i,256)}},e.prototype.bitwiseTo=function(e,t,n){var r,i,s=Math.min(e.t,this.t);for(r=0;r<s;++r)n[r]=t(this[r],e[r]);if(e.t<this.t){for(i=e.s&this.DM,r=s;r<this.t;++r)n[r]=t(this[r],i);n.t=this.t}else{for(i=this.s&this.DM,r=s;r<e.t;++r)n[r]=t(i,e[r]);n.t=e.t}n.s=t(this.s,e.s),n.clamp()},e.prototype.changeBit=function(t,n){var r=e.ONE.shiftLeft(t);return this.bitwiseTo(r,n,r),r},e.prototype.addTo=function(e,t){for(var n=0,r=0,i=Math.min(e.t,this.t);n<i;)r+=this[n]+e[n],t[n++]=r&this.DM,r>>=this.DB;if(e.t<this.t){for(r+=e.s;n<this.t;)r+=this[n],t[n++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;n<e.t;)r+=e[n],t[n++]=r&this.DM,r>>=this.DB;r+=e.s}t.s=r<0?-1:0,r>0?t[n++]=r:r<-1&&(t[n++]=this.DV+r),t.t=n,t.clamp()},e.prototype.dMultiply=function(e){this[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},e.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this[this.t++]=0;for(this[t]+=e;this[t]>=this.DV;)this[t]-=this.DV,++t>=this.t&&(this[this.t++]=0),++this[t]}},e.prototype.multiplyLowerTo=function(e,t,n){var r=Math.min(this.t+e.t,t);for(n.s=0,n.t=r;r>0;)n[--r]=0;for(var i=n.t-this.t;r<i;++r)n[r+this.t]=this.am(0,e[r],n,r,0,this.t);for(i=Math.min(e.t,t);r<i;++r)this.am(0,e[r],n,r,0,t-r);n.clamp()},e.prototype.multiplyUpperTo=function(e,t,n){--t;var r=n.t=this.t+e.t-t;for(n.s=0;--r>=0;)n[r]=0;for(r=Math.max(t-this.t,0);r<e.t;++r)n[this.t+r-t]=this.am(t-r,e[r],n,0,0,this.t+r-t);n.clamp(),n.drShiftTo(1,n)},e.prototype.modInt=function(e){if(e<=0)return 0;var t=this.DV%e,n=this.s<0?e-1:0;if(this.t>0)if(0==t)n=this[0]%e;else for(var r=this.t-1;r>=0;--r)n=(t*n+this[r])%e;return n},e.prototype.millerRabin=function(t){var n=this.subtract(e.ONE),r=n.getLowestSetBit();if(r<=0)return!1;var i=n.shiftRight(r);(t=t+1>>1)>lowprimes.length&&(t=lowprimes.length);for(var s=nbi(),o=0;o<t;++o){s.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]);var a=s.modPow(i,this);if(0!=a.compareTo(e.ONE)&&0!=a.compareTo(n)){for(var c=1;c++<r&&0!=a.compareTo(n);)if(0==(a=a.modPowInt(2,this)).compareTo(e.ONE))return!1;if(0!=a.compareTo(n))return!1}}return!0},e.prototype.square=function(){var e=nbi();return this.squareTo(e),e},e.prototype.gcda=function(e,t){var n=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(n.compareTo(r)<0){var i=n;n=r,r=i}var s=n.getLowestSetBit(),o=r.getLowestSetBit();if(o<0)t(n);else{s<o&&(o=s),o>0&&(n.rShiftTo(o,n),r.rShiftTo(o,r));var a=function(){(s=n.getLowestSetBit())>0&&n.rShiftTo(s,n),(s=r.getLowestSetBit())>0&&r.rShiftTo(s,r),n.compareTo(r)>=0?(n.subTo(r,n),n.rShiftTo(1,n)):(r.subTo(n,r),r.rShiftTo(1,r)),n.signum()>0?setTimeout(a,0):(o>0&&r.lShiftTo(o,r),setTimeout(function(){t(r)},0))};setTimeout(a,10)}},e.prototype.fromNumberAsync=function(t,n,r,i){if("number"==typeof n)if(t<2)this.fromInt(1);else{this.fromNumber(t,r),this.testBit(t-1)||this.bitwiseTo(e.ONE.shiftLeft(t-1),op_or,this),this.isEven()&&this.dAddOffset(1,0);var s=this,o=function(){s.dAddOffset(2,0),s.bitLength()>t&&s.subTo(e.ONE.shiftLeft(t-1),s),s.isProbablePrime(n)?setTimeout(function(){i()},0):setTimeout(o,0)};setTimeout(o,0)}else{var a=[],c=7&t;a.length=1+(t>>3),n.nextBytes(a),c>0?a[0]&=(1<<c)-1:a[0]=0,this.fromString(a,256)}},e}(),NullExp=function(){function e(){}return e.prototype.convert=function(e){return e},e.prototype.revert=function(e){return e},e.prototype.mulTo=function(e,t,n){e.multiplyTo(t,n)},e.prototype.sqrTo=function(e,t){e.squareTo(t)},e}(),Classic=function(){function e(e){this.m=e}return e.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},e.prototype.revert=function(e){return e},e.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},e.prototype.mulTo=function(e,t,n){e.multiplyTo(t,n),this.reduce(n)},e.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},e}(),Montgomery=function(){function e(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}return e.prototype.convert=function(e){var t=nbi();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(BigInteger.ZERO)>0&&this.m.subTo(t,t),t},e.prototype.revert=function(e){var t=nbi();return e.copyTo(t),this.reduce(t),t},e.prototype.reduce=function(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(var t=0;t<this.m.t;++t){var n=32767&e[t],r=n*this.mpl+((n*this.mph+(e[t]>>15)*this.mpl&this.um)<<15)&e.DM;for(e[n=t+this.m.t]+=this.m.am(0,r,e,t,0,this.m.t);e[n]>=e.DV;)e[n]-=e.DV,e[++n]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},e.prototype.mulTo=function(e,t,n){e.multiplyTo(t,n),this.reduce(n)},e.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},e}(),Barrett=function(){function e(e){this.m=e,this.r2=nbi(),this.q3=nbi(),BigInteger.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e)}return e.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=nbi();return e.copyTo(t),this.reduce(t),t},e.prototype.revert=function(e){return e},e.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},e.prototype.mulTo=function(e,t,n){e.multiplyTo(t,n),this.reduce(n)},e.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},e}();function nbi(){return new BigInteger(null)}function parseBigInt(e,t){return new BigInteger(e,t)}var inBrowser="undefined"!=typeof navigator;inBrowser&&j_lm&&"Microsoft Internet Explorer"==navigator.appName?(BigInteger.prototype.am=function(e,t,n,r,i,s){for(var o=32767&t,a=t>>15;--s>=0;){var c=32767&this[e],u=this[e++]>>15,l=a*c+u*o;i=((c=o*c+((32767&l)<<15)+n[r]+(1073741823&i))>>>30)+(l>>>15)+a*u+(i>>>30),n[r++]=1073741823&c}return i},dbits=30):inBrowser&&j_lm&&"Netscape"!=navigator.appName?(BigInteger.prototype.am=function(e,t,n,r,i,s){for(;--s>=0;){var o=t*this[e++]+n[r]+i;i=Math.floor(o/67108864),n[r++]=67108863&o}return i},dbits=26):(BigInteger.prototype.am=function(e,t,n,r,i,s){for(var o=16383&t,a=t>>14;--s>=0;){var c=16383&this[e],u=this[e++]>>14,l=a*c+u*o;i=((c=o*c+((16383&l)<<14)+n[r]+i)>>28)+(l>>14)+a*u,n[r++]=268435455&c}return i},dbits=28),BigInteger.prototype.DB=dbits,BigInteger.prototype.DM=(1<<dbits)-1,BigInteger.prototype.DV=1<<dbits;var BI_FP=52;BigInteger.prototype.FV=Math.pow(2,BI_FP),BigInteger.prototype.F1=BI_FP-dbits,BigInteger.prototype.F2=2*dbits-BI_FP;var BI_RC=[],rr,vv;for(rr="0".charCodeAt(0),vv=0;vv<=9;++vv)BI_RC[rr++]=vv;for(rr="a".charCodeAt(0),vv=10;vv<36;++vv)BI_RC[rr++]=vv;for(rr="A".charCodeAt(0),vv=10;vv<36;++vv)BI_RC[rr++]=vv;function intAt(e,t){var n=BI_RC[e.charCodeAt(t)];return null==n?-1:n}function nbv(e){var t=nbi();return t.fromInt(e),t}function nbits(e){var t,n=1;return 0!=(t=e>>>16)&&(e=t,n+=16),0!=(t=e>>8)&&(e=t,n+=8),0!=(t=e>>4)&&(e=t,n+=4),0!=(t=e>>2)&&(e=t,n+=2),0!=(t=e>>1)&&(e=t,n+=1),n}BigInteger.ZERO=nbv(0),BigInteger.ONE=nbv(1);var Arcfour=function(){function e(){this.i=0,this.j=0,this.S=[]}return e.prototype.init=function(e){var t,n,r;for(t=0;t<256;++t)this.S[t]=t;for(n=0,t=0;t<256;++t)n=n+this.S[t]+e[t%e.length]&255,r=this.S[t],this.S[t]=this.S[n],this.S[n]=r;this.i=0,this.j=0},e.prototype.next=function(){var e;return this.i=this.i+1&255,this.j=this.j+this.S[this.i]&255,e=this.S[this.i],this.S[this.i]=this.S[this.j],this.S[this.j]=e,this.S[e+this.S[this.i]&255]},e}();function prng_newstate(){return new Arcfour}var rng_psize=256,rng_state,rng_pool=null,rng_pptr;if(null==rng_pool){rng_pool=[],rng_pptr=0;var t=void 0;if("undefined"!=typeof window&&window.crypto&&window.crypto.getRandomValues){var z=new Uint32Array(256);for(window.crypto.getRandomValues(z),t=0;t<z.length;++t)rng_pool[rng_pptr++]=255&z[t]}var count=0,onMouseMoveListener_1=function(e){if((count=count||0)>=256||rng_pptr>=rng_psize)window.removeEventListener?window.removeEventListener("mousemove",onMouseMoveListener_1,!1):window.detachEvent&&window.detachEvent("onmousemove",onMouseMoveListener_1);else try{var t=e.x+e.y;rng_pool[rng_pptr++]=255&t,count+=1}catch(e){}};"undefined"!=typeof window&&(window.addEventListener?window.addEventListener("mousemove",onMouseMoveListener_1,!1):window.attachEvent&&window.attachEvent("onmousemove",onMouseMoveListener_1))}function rng_get_byte(){if(null==rng_state){for(rng_state=prng_newstate();rng_pptr<rng_psize;){var e=Math.floor(65536*Math.random());rng_pool[rng_pptr++]=255&e}for(rng_state.init(rng_pool),rng_pptr=0;rng_pptr<rng_pool.length;++rng_pptr)rng_pool[rng_pptr]=0;rng_pptr=0}return rng_state.next()}var SecureRandom=function(){function e(){}return e.prototype.nextBytes=function(e){for(var t=0;t<e.length;++t)e[t]=rng_get_byte()},e}();function pkcs1pad1(e,t){if(t<e.length+22)return console.error("Message too long for RSA"),null;for(var n=t-e.length-6,r="",i=0;i<n;i+=2)r+="ff";return parseBigInt("0001"+r+"00"+e,16)}function pkcs1pad2(e,t){if(t<e.length+11)return console.error("Message too long for RSA"),null;for(var n=[],r=e.length-1;r>=0&&t>0;){var i=e.charCodeAt(r--);i<128?n[--t]=i:i>127&&i<2048?(n[--t]=63&i|128,n[--t]=i>>6|192):(n[--t]=63&i|128,n[--t]=i>>6&63|128,n[--t]=i>>12|224)}n[--t]=0;for(var s=new SecureRandom,o=[];t>2;){for(o[0]=0;0==o[0];)s.nextBytes(o);n[--t]=o[0]}return n[--t]=2,n[--t]=0,new BigInteger(n)}var RSAKey=function(){function e(){this.n=null,this.e=0,this.d=null,this.p=null,this.q=null,this.dmp1=null,this.dmq1=null,this.coeff=null}return e.prototype.doPublic=function(e){return e.modPowInt(this.e,this.n)},e.prototype.doPrivate=function(e){if(null==this.p||null==this.q)return e.modPow(this.d,this.n);for(var t=e.mod(this.p).modPow(this.dmp1,this.p),n=e.mod(this.q).modPow(this.dmq1,this.q);t.compareTo(n)<0;)t=t.add(this.p);return t.subtract(n).multiply(this.coeff).mod(this.p).multiply(this.q).add(n)},e.prototype.setPublic=function(e,t){null!=e&&null!=t&&e.length>0&&t.length>0?(this.n=parseBigInt(e,16),this.e=parseInt(t,16)):console.error("Invalid RSA public key")},e.prototype.encrypt=function(e){var t=this.n.bitLength()+7>>3,n=pkcs1pad2(e,t);if(null==n)return null;var r=this.doPublic(n);if(null==r)return null;for(var i=r.toString(16),s=i.length,o=0;o<2*t-s;o++)i="0"+i;return i},e.prototype.setPrivate=function(e,t,n){null!=e&&null!=t&&e.length>0&&t.length>0?(this.n=parseBigInt(e,16),this.e=parseInt(t,16),this.d=parseBigInt(n,16)):console.error("Invalid RSA private key")},e.prototype.setPrivateEx=function(e,t,n,r,i,s,o,a){null!=e&&null!=t&&e.length>0&&t.length>0?(this.n=parseBigInt(e,16),this.e=parseInt(t,16),this.d=parseBigInt(n,16),this.p=parseBigInt(r,16),this.q=parseBigInt(i,16),this.dmp1=parseBigInt(s,16),this.dmq1=parseBigInt(o,16),this.coeff=parseBigInt(a,16)):console.error("Invalid RSA private key")},e.prototype.generate=function(e,t){var n=new SecureRandom,r=e>>1;this.e=parseInt(t,16);for(var i=new BigInteger(t,16);;){for(;this.p=new BigInteger(e-r,1,n),0!=this.p.subtract(BigInteger.ONE).gcd(i).compareTo(BigInteger.ONE)||!this.p.isProbablePrime(10););for(;this.q=new BigInteger(r,1,n),0!=this.q.subtract(BigInteger.ONE).gcd(i).compareTo(BigInteger.ONE)||!this.q.isProbablePrime(10););if(this.p.compareTo(this.q)<=0){var s=this.p;this.p=this.q,this.q=s}var o=this.p.subtract(BigInteger.ONE),a=this.q.subtract(BigInteger.ONE),c=o.multiply(a);if(0==c.gcd(i).compareTo(BigInteger.ONE)){this.n=this.p.multiply(this.q),this.d=i.modInverse(c),this.dmp1=this.d.mod(o),this.dmq1=this.d.mod(a),this.coeff=this.q.modInverse(this.p);break}}},e.prototype.decrypt=function(e){var t=parseBigInt(e,16),n=this.doPrivate(t);return null==n?null:pkcs1unpad2(n,this.n.bitLength()+7>>3)},e.prototype.generateAsync=function(e,t,n){var r=new SecureRandom,i=e>>1;this.e=parseInt(t,16);var s=new BigInteger(t,16),o=this,a=function(){var t=function(){if(o.p.compareTo(o.q)<=0){var e=o.p;o.p=o.q,o.q=e}var t=o.p.subtract(BigInteger.ONE),r=o.q.subtract(BigInteger.ONE),i=t.multiply(r);0==i.gcd(s).compareTo(BigInteger.ONE)?(o.n=o.p.multiply(o.q),o.d=s.modInverse(i),o.dmp1=o.d.mod(t),o.dmq1=o.d.mod(r),o.coeff=o.q.modInverse(o.p),setTimeout(function(){n()},0)):setTimeout(a,0)},c=function(){o.q=nbi(),o.q.fromNumberAsync(i,1,r,function(){o.q.subtract(BigInteger.ONE).gcda(s,function(e){0==e.compareTo(BigInteger.ONE)&&o.q.isProbablePrime(10)?setTimeout(t,0):setTimeout(c,0)})})},u=function(){o.p=nbi(),o.p.fromNumberAsync(e-i,1,r,function(){o.p.subtract(BigInteger.ONE).gcda(s,function(e){0==e.compareTo(BigInteger.ONE)&&o.p.isProbablePrime(10)?setTimeout(c,0):setTimeout(u,0)})})};setTimeout(u,0)};setTimeout(a,0)},e.prototype.sign=function(e,t,n){var r=pkcs1pad1(getDigestHeader(n)+t(e).toString(),this.n.bitLength()/4);if(null==r)return null;var i=this.doPrivate(r);if(null==i)return null;var s=i.toString(16);return 1&s.length?"0"+s:s},e.prototype.verify=function(e,t,n){var r=parseBigInt(t,16),i=this.doPublic(r);return null==i?null:removeDigestHeader(i.toString(16).replace(/^1f+00/,""))==n(e).toString()},e}();function pkcs1unpad2(e,t){for(var n=e.toByteArray(),r=0;r<n.length&&0==n[r];)++r;if(n.length-r!=t-1||2!=n[r])return null;for(++r;0!=n[r];)if(++r>=n.length)return null;for(var i="";++r<n.length;){var s=255&n[r];s<128?i+=String.fromCharCode(s):s>191&&s<224?(i+=String.fromCharCode((31&s)<<6|63&n[r+1]),++r):(i+=String.fromCharCode((15&s)<<12|(63&n[r+1])<<6|63&n[r+2]),r+=2)}return i}var DIGEST_HEADERS={md2:"3020300c06082a864886f70d020205000410",md5:"3020300c06082a864886f70d020505000410",sha1:"3021300906052b0e03021a05000414",sha224:"302d300d06096086480165030402040500041c",sha256:"3031300d060960864801650304020105000420",sha384:"3041300d060960864801650304020205000430",sha512:"3051300d060960864801650304020305000440",ripemd160:"3021300906052b2403020105000414"};function getDigestHeader(e){return DIGEST_HEADERS[e]||""}function removeDigestHeader(e){for(var t in DIGEST_HEADERS)if(DIGEST_HEADERS.hasOwnProperty(t)){var n=DIGEST_HEADERS[t],r=n.length;if(e.substr(0,r)==n)return e.substr(r)}return e}var YAHOO={};YAHOO.lang={extend:function(e,t,n){if(!t||!e)throw new Error("YAHOO.lang.extend failed, please check that all dependencies are included.");var r=function(){};if(r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e,e.superclass=t.prototype,t.prototype.constructor==Object.prototype.constructor&&(t.prototype.constructor=t),n){var i;for(i in n)e.prototype[i]=n[i];var s=function(){},o=["toString","valueOf"];try{/MSIE/.test(navigator.userAgent)&&(s=function(e,t){for(i=0;i<o.length;i+=1){var n=o[i],r=t[n];"function"==typeof r&&r!=Object.prototype[n]&&(e[n]=r)}})}catch(e){}s(e.prototype,n)}}};var KJUR={};void 0!==KJUR.asn1&&KJUR.asn1||(KJUR.asn1={}),KJUR.asn1.ASN1Util=new function(){this.integerToByteHex=function(e){var t=e.toString(16);return t.length%2==1&&(t="0"+t),t},this.bigIntToMinTwosComplementsHex=function(e){var t=e.toString(16);if("-"!=t.substr(0,1))t.length%2==1?t="0"+t:t.match(/^[0-7]/)||(t="00"+t);else{var n=t.substr(1).length;n%2==1?n+=1:t.match(/^[0-7]/)||(n+=2);for(var r="",i=0;i<n;i++)r+="f";t=new BigInteger(r,16).xor(e).add(BigInteger.ONE).toString(16).replace(/^-/,"")}return t},this.getPEMStringFromHex=function(e,t){return hextopem(e,t)},this.newObject=function(e){var t=KJUR.asn1,n=t.DERBoolean,r=t.DERInteger,i=t.DERBitString,s=t.DEROctetString,o=t.DERNull,a=t.DERObjectIdentifier,c=t.DEREnumerated,u=t.DERUTF8String,l=t.DERNumericString,h=t.DERPrintableString,d=t.DERTeletexString,p=t.DERIA5String,g=t.DERUTCTime,f=t.DERGeneralizedTime,m=t.DERSequence,v=t.DERSet,y=t.DERTaggedObject,b=t.ASN1Util.newObject,S=Object.keys(e);if(1!=S.length)throw"key of param shall be only one.";var T=S[0];if(-1==":bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:".indexOf(":"+T+":"))throw"undefined key: "+T;if("bool"==T)return new n(e[T]);if("int"==T)return new r(e[T]);if("bitstr"==T)return new i(e[T]);if("octstr"==T)return new s(e[T]);if("null"==T)return new o(e[T]);if("oid"==T)return new a(e[T]);if("enum"==T)return new c(e[T]);if("utf8str"==T)return new u(e[T]);if("numstr"==T)return new l(e[T]);if("prnstr"==T)return new h(e[T]);if("telstr"==T)return new d(e[T]);if("ia5str"==T)return new p(e[T]);if("utctime"==T)return new g(e[T]);if("gentime"==T)return new f(e[T]);if("seq"==T){for(var w=e[T],R=[],E=0;E<w.length;E++){var I=b(w[E]);R.push(I)}return new m({array:R})}if("set"==T){for(w=e[T],R=[],E=0;E<w.length;E++){I=b(w[E]);R.push(I)}return new v({array:R})}if("tag"==T){var _=e[T];if("[object Array]"===Object.prototype.toString.call(_)&&3==_.length){var A=b(_[2]);return new y({tag:_[0],explicit:_[1],obj:A})}var C={};if(void 0!==_.explicit&&(C.explicit=_.explicit),void 0!==_.tag&&(C.tag=_.tag),void 0===_.obj)throw"obj shall be specified for 'tag'.";return C.obj=b(_.obj),new y(C)}},this.jsonToASN1HEX=function(e){return this.newObject(e).getEncodedHex()}},KJUR.asn1.ASN1Util.oidHexToInt=function(e){for(var t="",n=parseInt(e.substr(0,2),16),r=(t=Math.floor(n/40)+"."+n%40,""),i=2;i<e.length;i+=2){var s=("00000000"+parseInt(e.substr(i,2),16).toString(2)).slice(-8);if(r+=s.substr(1,7),"0"==s.substr(0,1))t=t+"."+new BigInteger(r,2).toString(10),r=""}return t},KJUR.asn1.ASN1Util.oidIntToHex=function(e){var t=function(e){var t=e.toString(16);return 1==t.length&&(t="0"+t),t},n=function(e){var n="",r=new BigInteger(e,10).toString(2),i=7-r.length%7;7==i&&(i=0);for(var s="",o=0;o<i;o++)s+="0";r=s+r;for(o=0;o<r.length-1;o+=7){var a=r.substr(o,7);o!=r.length-7&&(a="1"+a),n+=t(parseInt(a,2))}return n};if(!e.match(/^[0-9.]+$/))throw"malformed oid string: "+e;var r="",i=e.split("."),s=40*parseInt(i[0])+parseInt(i[1]);r+=t(s),i.splice(0,2);for(var o=0;o<i.length;o++)r+=n(i[o]);return r},KJUR.asn1.ASN1Object=function(){this.getLengthHexFromValue=function(){if(void 0===this.hV||null==this.hV)throw"this.hV is null or undefined.";if(this.hV.length%2==1)throw"value hex must be even length: n=0,v="+this.hV;var e=this.hV.length/2,t=e.toString(16);if(t.length%2==1&&(t="0"+t),e<128)return t;var n=t.length/2;if(n>15)throw"ASN.1 length too long to represent by 8x: n = "+e.toString(16);return(128+n).toString(16)+t},this.getEncodedHex=function(){return(null==this.hTLV||this.isModified)&&(this.hV=this.getFreshValueHex(),this.hL=this.getLengthHexFromValue(),this.hTLV=this.hT+this.hL+this.hV,this.isModified=!1),this.hTLV},this.getValueHex=function(){return this.getEncodedHex(),this.hV},this.getFreshValueHex=function(){return""}},KJUR.asn1.DERAbstractString=function(e){KJUR.asn1.DERAbstractString.superclass.constructor.call(this),this.getString=function(){return this.s},this.setString=function(e){this.hTLV=null,this.isModified=!0,this.s=e,this.hV=stohex(this.s)},this.setStringHex=function(e){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=e},this.getFreshValueHex=function(){return this.hV},void 0!==e&&("string"==typeof e?this.setString(e):void 0!==e.str?this.setString(e.str):void 0!==e.hex&&this.setStringHex(e.hex))},YAHOO.lang.extend(KJUR.asn1.DERAbstractString,KJUR.asn1.ASN1Object),KJUR.asn1.DERAbstractTime=function(e){KJUR.asn1.DERAbstractTime.superclass.constructor.call(this),this.localDateToUTC=function(e){return utc=e.getTime()+6e4*e.getTimezoneOffset(),new Date(utc)},this.formatDate=function(e,t,n){var r=this.zeroPadding,i=this.localDateToUTC(e),s=String(i.getFullYear());"utc"==t&&(s=s.substr(2,2));var o=s+r(String(i.getMonth()+1),2)+r(String(i.getDate()),2)+r(String(i.getHours()),2)+r(String(i.getMinutes()),2)+r(String(i.getSeconds()),2);if(!0===n){var a=i.getMilliseconds();if(0!=a){var c=r(String(a),3);o=o+"."+(c=c.replace(/[0]+$/,""))}}return o+"Z"},this.zeroPadding=function(e,t){return e.length>=t?e:new Array(t-e.length+1).join("0")+e},this.getString=function(){return this.s},this.setString=function(e){this.hTLV=null,this.isModified=!0,this.s=e,this.hV=stohex(e)},this.setByDateValue=function(e,t,n,r,i,s){var o=new Date(Date.UTC(e,t-1,n,r,i,s,0));this.setByDate(o)},this.getFreshValueHex=function(){return this.hV}},YAHOO.lang.extend(KJUR.asn1.DERAbstractTime,KJUR.asn1.ASN1Object),KJUR.asn1.DERAbstractStructured=function(e){KJUR.asn1.DERAbstractString.superclass.constructor.call(this),this.setByASN1ObjectArray=function(e){this.hTLV=null,this.isModified=!0,this.asn1Array=e},this.appendASN1Object=function(e){this.hTLV=null,this.isModified=!0,this.asn1Array.push(e)},this.asn1Array=new Array,void 0!==e&&void 0!==e.array&&(this.asn1Array=e.array)},YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured,KJUR.asn1.ASN1Object),KJUR.asn1.DERBoolean=function(){KJUR.asn1.DERBoolean.superclass.constructor.call(this),this.hT="01",this.hTLV="0101ff"},YAHOO.lang.extend(KJUR.asn1.DERBoolean,KJUR.asn1.ASN1Object),KJUR.asn1.DERInteger=function(e){KJUR.asn1.DERInteger.superclass.constructor.call(this),this.hT="02",this.setByBigInteger=function(e){this.hTLV=null,this.isModified=!0,this.hV=KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(e)},this.setByInteger=function(e){var t=new BigInteger(String(e),10);this.setByBigInteger(t)},this.setValueHex=function(e){this.hV=e},this.getFreshValueHex=function(){return this.hV},void 0!==e&&(void 0!==e.bigint?this.setByBigInteger(e.bigint):void 0!==e.int?this.setByInteger(e.int):"number"==typeof e?this.setByInteger(e):void 0!==e.hex&&this.setValueHex(e.hex))},YAHOO.lang.extend(KJUR.asn1.DERInteger,KJUR.asn1.ASN1Object),KJUR.asn1.DERBitString=function(e){if(void 0!==e&&void 0!==e.obj){var t=KJUR.asn1.ASN1Util.newObject(e.obj);e.hex="00"+t.getEncodedHex()}KJUR.asn1.DERBitString.superclass.constructor.call(this),this.hT="03",this.setHexValueIncludingUnusedBits=function(e){this.hTLV=null,this.isModified=!0,this.hV=e},this.setUnusedBitsAndHexValue=function(e,t){if(e<0||7<e)throw"unused bits shall be from 0 to 7: u = "+e;var n="0"+e;this.hTLV=null,this.isModified=!0,this.hV=n+t},this.setByBinaryString=function(e){var t=8-(e=e.replace(/0+$/,"")).length%8;8==t&&(t=0);for(var n=0;n<=t;n++)e+="0";var r="";for(n=0;n<e.length-1;n+=8){var i=e.substr(n,8),s=parseInt(i,2).toString(16);1==s.length&&(s="0"+s),r+=s}this.hTLV=null,this.isModified=!0,this.hV="0"+t+r},this.setByBooleanArray=function(e){for(var t="",n=0;n<e.length;n++)1==e[n]?t+="1":t+="0";this.setByBinaryString(t)},this.newFalseArray=function(e){for(var t=new Array(e),n=0;n<e;n++)t[n]=!1;return t},this.getFreshValueHex=function(){return this.hV},void 0!==e&&("string"==typeof e&&e.toLowerCase().match(/^[0-9a-f]+$/)?this.setHexValueIncludingUnusedBits(e):void 0!==e.hex?this.setHexValueIncludingUnusedBits(e.hex):void 0!==e.bin?this.setByBinaryString(e.bin):void 0!==e.array&&this.setByBooleanArray(e.array))},YAHOO.lang.extend(KJUR.asn1.DERBitString,KJUR.asn1.ASN1Object),KJUR.asn1.DEROctetString=function(e){if(void 0!==e&&void 0!==e.obj){var t=KJUR.asn1.ASN1Util.newObject(e.obj);e.hex=t.getEncodedHex()}KJUR.asn1.DEROctetString.superclass.constructor.call(this,e),this.hT="04"},YAHOO.lang.extend(KJUR.asn1.DEROctetString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERNull=function(){KJUR.asn1.DERNull.superclass.constructor.call(this),this.hT="05",this.hTLV="0500"},YAHOO.lang.extend(KJUR.asn1.DERNull,KJUR.asn1.ASN1Object),KJUR.asn1.DERObjectIdentifier=function(e){var t=function(e){var t=e.toString(16);return 1==t.length&&(t="0"+t),t},n=function(e){var n="",r=new BigInteger(e,10).toString(2),i=7-r.length%7;7==i&&(i=0);for(var s="",o=0;o<i;o++)s+="0";r=s+r;for(o=0;o<r.length-1;o+=7){var a=r.substr(o,7);o!=r.length-7&&(a="1"+a),n+=t(parseInt(a,2))}return n};KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this),this.hT="06",this.setValueHex=function(e){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=e},this.setValueOidString=function(e){if(!e.match(/^[0-9.]+$/))throw"malformed oid string: "+e;var r="",i=e.split("."),s=40*parseInt(i[0])+parseInt(i[1]);r+=t(s),i.splice(0,2);for(var o=0;o<i.length;o++)r+=n(i[o]);this.hTLV=null,this.isModified=!0,this.s=null,this.hV=r},this.setValueName=function(e){var t=KJUR.asn1.x509.OID.name2oid(e);if(""===t)throw"DERObjectIdentifier oidName undefined: "+e;this.setValueOidString(t)},this.getFreshValueHex=function(){return this.hV},void 0!==e&&("string"==typeof e?e.match(/^[0-2].[0-9.]+$/)?this.setValueOidString(e):this.setValueName(e):void 0!==e.oid?this.setValueOidString(e.oid):void 0!==e.hex?this.setValueHex(e.hex):void 0!==e.name&&this.setValueName(e.name))},YAHOO.lang.extend(KJUR.asn1.DERObjectIdentifier,KJUR.asn1.ASN1Object),KJUR.asn1.DEREnumerated=function(e){KJUR.asn1.DEREnumerated.superclass.constructor.call(this),this.hT="0a",this.setByBigInteger=function(e){this.hTLV=null,this.isModified=!0,this.hV=KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(e)},this.setByInteger=function(e){var t=new BigInteger(String(e),10);this.setByBigInteger(t)},this.setValueHex=function(e){this.hV=e},this.getFreshValueHex=function(){return this.hV},void 0!==e&&(void 0!==e.int?this.setByInteger(e.int):"number"==typeof e?this.setByInteger(e):void 0!==e.hex&&this.setValueHex(e.hex))},YAHOO.lang.extend(KJUR.asn1.DEREnumerated,KJUR.asn1.ASN1Object),KJUR.asn1.DERUTF8String=function(e){KJUR.asn1.DERUTF8String.superclass.constructor.call(this,e),this.hT="0c"},YAHOO.lang.extend(KJUR.asn1.DERUTF8String,KJUR.asn1.DERAbstractString),KJUR.asn1.DERNumericString=function(e){KJUR.asn1.DERNumericString.superclass.constructor.call(this,e),this.hT="12"},YAHOO.lang.extend(KJUR.asn1.DERNumericString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERPrintableString=function(e){KJUR.asn1.DERPrintableString.superclass.constructor.call(this,e),this.hT="13"},YAHOO.lang.extend(KJUR.asn1.DERPrintableString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERTeletexString=function(e){KJUR.asn1.DERTeletexString.superclass.constructor.call(this,e),this.hT="14"},YAHOO.lang.extend(KJUR.asn1.DERTeletexString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERIA5String=function(e){KJUR.asn1.DERIA5String.superclass.constructor.call(this,e),this.hT="16"},YAHOO.lang.extend(KJUR.asn1.DERIA5String,KJUR.asn1.DERAbstractString),KJUR.asn1.DERUTCTime=function(e){KJUR.asn1.DERUTCTime.superclass.constructor.call(this,e),this.hT="17",this.setByDate=function(e){this.hTLV=null,this.isModified=!0,this.date=e,this.s=this.formatDate(this.date,"utc"),this.hV=stohex(this.s)},this.getFreshValueHex=function(){return void 0===this.date&&void 0===this.s&&(this.date=new Date,this.s=this.formatDate(this.date,"utc"),this.hV=stohex(this.s)),this.hV},void 0!==e&&(void 0!==e.str?this.setString(e.str):"string"==typeof e&&e.match(/^[0-9]{12}Z$/)?this.setString(e):void 0!==e.hex?this.setStringHex(e.hex):void 0!==e.date&&this.setByDate(e.date))},YAHOO.lang.extend(KJUR.asn1.DERUTCTime,KJUR.asn1.DERAbstractTime),KJUR.asn1.DERGeneralizedTime=function(e){KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this,e),this.hT="18",this.withMillis=!1,this.setByDate=function(e){this.hTLV=null,this.isModified=!0,this.date=e,this.s=this.formatDate(this.date,"gen",this.withMillis),this.hV=stohex(this.s)},this.getFreshValueHex=function(){return void 0===this.date&&void 0===this.s&&(this.date=new Date,this.s=this.formatDate(this.date,"gen",this.withMillis),this.hV=stohex(this.s)),this.hV},void 0!==e&&(void 0!==e.str?this.setString(e.str):"string"==typeof e&&e.match(/^[0-9]{14}Z$/)?this.setString(e):void 0!==e.hex?this.setStringHex(e.hex):void 0!==e.date&&this.setByDate(e.date),!0===e.millis&&(this.withMillis=!0))},YAHOO.lang.extend(KJUR.asn1.DERGeneralizedTime,KJUR.asn1.DERAbstractTime),KJUR.asn1.DERSequence=function(e){KJUR.asn1.DERSequence.superclass.constructor.call(this,e),this.hT="30",this.getFreshValueHex=function(){for(var e="",t=0;t<this.asn1Array.length;t++){e+=this.asn1Array[t].getEncodedHex()}return this.hV=e,this.hV}},YAHOO.lang.extend(KJUR.asn1.DERSequence,KJUR.asn1.DERAbstractStructured),KJUR.asn1.DERSet=function(e){KJUR.asn1.DERSet.superclass.constructor.call(this,e),this.hT="31",this.sortFlag=!0,this.getFreshValueHex=function(){for(var e=new Array,t=0;t<this.asn1Array.length;t++){var n=this.asn1Array[t];e.push(n.getEncodedHex())}return 1==this.sortFlag&&e.sort(),this.hV=e.join(""),this.hV},void 0!==e&&void 0!==e.sortflag&&0==e.sortflag&&(this.sortFlag=!1)},YAHOO.lang.extend(KJUR.asn1.DERSet,KJUR.asn1.DERAbstractStructured),KJUR.asn1.DERTaggedObject=function(e){KJUR.asn1.DERTaggedObject.superclass.constructor.call(this),this.hT="a0",this.hV="",this.isExplicit=!0,this.asn1Object=null,this.setASN1Object=function(e,t,n){this.hT=t,this.isExplicit=e,this.asn1Object=n,this.isExplicit?(this.hV=this.asn1Object.getEncodedHex(),this.hTLV=null,this.isModified=!0):(this.hV=null,this.hTLV=n.getEncodedHex(),this.hTLV=this.hTLV.replace(/^../,t),this.isModified=!1)},this.getFreshValueHex=function(){return this.hV},void 0!==e&&(void 0!==e.tag&&(this.hT=e.tag),void 0!==e.explicit&&(this.isExplicit=e.explicit),void 0!==e.obj&&(this.asn1Object=e.obj,this.setASN1Object(this.isExplicit,this.hT,this.asn1Object)))},YAHOO.lang.extend(KJUR.asn1.DERTaggedObject,KJUR.asn1.ASN1Object);var __extends=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},e(t,n)};return function(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),JSEncryptRSAKey=function(e){function t(n){var r=e.call(this)||this;return n&&("string"==typeof n?r.parseKey(n):(t.hasPrivateKeyProperty(n)||t.hasPublicKeyProperty(n))&&r.parsePropertiesFrom(n)),r}return __extends(t,e),t.prototype.parseKey=function(e){try{var t=0,n=0,r=/^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/.test(e)?Hex.decode(e):Base64.unarmor(e),i=ASN1.decode(r);if(3===i.sub.length&&(i=i.sub[2].sub[0]),9===i.sub.length){t=i.sub[1].getHexStringValue(),this.n=parseBigInt(t,16),n=i.sub[2].getHexStringValue(),this.e=parseInt(n,16);var s=i.sub[3].getHexStringValue();this.d=parseBigInt(s,16);var o=i.sub[4].getHexStringValue();this.p=parseBigInt(o,16);var a=i.sub[5].getHexStringValue();this.q=parseBigInt(a,16);var c=i.sub[6].getHexStringValue();this.dmp1=parseBigInt(c,16);var u=i.sub[7].getHexStringValue();this.dmq1=parseBigInt(u,16);var l=i.sub[8].getHexStringValue();this.coeff=parseBigInt(l,16)}else{if(2!==i.sub.length)return!1;if(i.sub[0].sub){var h=i.sub[1].sub[0];t=h.sub[0].getHexStringValue(),this.n=parseBigInt(t,16),n=h.sub[1].getHexStringValue(),this.e=parseInt(n,16)}else t=i.sub[0].getHexStringValue(),this.n=parseBigInt(t,16),n=i.sub[1].getHexStringValue(),this.e=parseInt(n,16)}return!0}catch(e){return!1}},t.prototype.getPrivateBaseKey=function(){var e={array:[new KJUR.asn1.DERInteger({int:0}),new KJUR.asn1.DERInteger({bigint:this.n}),new KJUR.asn1.DERInteger({int:this.e}),new KJUR.asn1.DERInteger({bigint:this.d}),new KJUR.asn1.DERInteger({bigint:this.p}),new KJUR.asn1.DERInteger({bigint:this.q}),new KJUR.asn1.DERInteger({bigint:this.dmp1}),new KJUR.asn1.DERInteger({bigint:this.dmq1}),new KJUR.asn1.DERInteger({bigint:this.coeff})]};return new KJUR.asn1.DERSequence(e).getEncodedHex()},t.prototype.getPrivateBaseKeyB64=function(){return hex2b64(this.getPrivateBaseKey())},t.prototype.getPublicBaseKey=function(){var e=new KJUR.asn1.DERSequence({array:[new KJUR.asn1.DERObjectIdentifier({oid:"1.2.840.113549.1.1.1"}),new KJUR.asn1.DERNull]}),t=new KJUR.asn1.DERSequence({array:[new KJUR.asn1.DERInteger({bigint:this.n}),new KJUR.asn1.DERInteger({int:this.e})]}),n=new KJUR.asn1.DERBitString({hex:"00"+t.getEncodedHex()});return new KJUR.asn1.DERSequence({array:[e,n]}).getEncodedHex()},t.prototype.getPublicBaseKeyB64=function(){return hex2b64(this.getPublicBaseKey())},t.wordwrap=function(e,t){if(!e)return e;var n="(.{1,"+(t=t||64)+"})( +|$\n?)|(.{1,"+t+"})";return e.match(RegExp(n,"g")).join("\n")},t.prototype.getPrivateKey=function(){var e="-----BEGIN RSA PRIVATE KEY-----\n";return e+=t.wordwrap(this.getPrivateBaseKeyB64())+"\n",e+="-----END RSA PRIVATE KEY-----"},t.prototype.getPublicKey=function(){var e="-----BEGIN PUBLIC KEY-----\n";return e+=t.wordwrap(this.getPublicBaseKeyB64())+"\n",e+="-----END PUBLIC KEY-----"},t.hasPublicKeyProperty=function(e){return(e=e||{}).hasOwnProperty("n")&&e.hasOwnProperty("e")},t.hasPrivateKeyProperty=function(e){return(e=e||{}).hasOwnProperty("n")&&e.hasOwnProperty("e")&&e.hasOwnProperty("d")&&e.hasOwnProperty("p")&&e.hasOwnProperty("q")&&e.hasOwnProperty("dmp1")&&e.hasOwnProperty("dmq1")&&e.hasOwnProperty("coeff")},t.prototype.parsePropertiesFrom=function(e){this.n=e.n,this.e=e.e,e.hasOwnProperty("d")&&(this.d=e.d,this.p=e.p,this.q=e.q,this.dmp1=e.dmp1,this.dmq1=e.dmq1,this.coeff=e.coeff)},t}(RSAKey),_a,version=void 0!==browser$1?null===(_a=browser$1.env)||void 0===_a?void 0:_a.npm_package_version:void 0,JSEncrypt=function(){function e(e){void 0===e&&(e={}),e=e||{},this.default_key_size=e.default_key_size?parseInt(e.default_key_size,10):1024,this.default_public_exponent=e.default_public_exponent||"010001",this.log=e.log||!1,this.key=null}return e.prototype.setKey=function(e){this.log&&this.key&&console.warn("A key was already set, overriding existing."),this.key=new JSEncryptRSAKey(e)},e.prototype.setPrivateKey=function(e){this.setKey(e)},e.prototype.setPublicKey=function(e){this.setKey(e)},e.prototype.decrypt=function(e){try{return this.getKey().decrypt(b64tohex(e))}catch(e){return!1}},e.prototype.encrypt=function(e){try{return hex2b64(this.getKey().encrypt(e))}catch(e){return!1}},e.prototype.sign=function(e,t,n){try{return hex2b64(this.getKey().sign(e,t,n))}catch(e){return!1}},e.prototype.verify=function(e,t,n){try{return this.getKey().verify(e,b64tohex(t),n)}catch(e){return!1}},e.prototype.getKey=function(e){if(!this.key){if(this.key=new JSEncryptRSAKey,e&&"[object Function]"==={}.toString.call(e))return void this.key.generateAsync(this.default_key_size,this.default_public_exponent,e);this.key.generate(this.default_key_size,this.default_public_exponent)}return this.key},e.prototype.getPrivateKey=function(){return this.getKey().getPrivateKey()},e.prototype.getPrivateKeyB64=function(){return this.getKey().getPrivateBaseKeyB64()},e.prototype.getPublicKey=function(){return this.getKey().getPublicKey()},e.prototype.getPublicKeyB64=function(){return this.getKey().getPublicBaseKeyB64()},e.version=version,e}(),networkMonitoringConfig={requestState:!1,delay:0},hangupWav="https://softphone.useasy.cn/hangup.wav",ringingWav="https://softphone.useasy.cn/ring.wav",ueSoftphone=function(){function e(e){void 0===e&&(e={});var n=this;this.getWebrtcInfo=function(e,n,r){t.request(e+"/call/api/sip/webrtc/config/query",{verb:"GET",loginToken:t.loginToken,sessionId:t.agentInfo._id,success:function(e){e.success&&e.data?(t.agentextras=e.data,"WEBRTC"===r&&t.initWebrtcEvent(e.data)):n.error(__assign({},e))},error:function(e){n.error({error:e})}})},this.initAttachEvent=function(e,r,i,s){t.request(e+"/platform/action/refreshWsToken",{verb:"GET",loginToken:t.loginToken,sessionId:t.agentInfo._id,success:function(e){if(e&&e.data){var o="";i.forEach(function(e){"KF"===e.id&&(o=e.url)});var a={query:{accountId:s.accountId,agentNumber:s.agentNumber,agentId:s._id,token:e.data.wsToken,wsExtra:JSON.stringify({loginType:r,channelType:"SDK",ability:["call"]}),timestamp:e.data.timestamp,clientType:1,pushHangupStatistics:t.initOptions.pushHangupStatistics||!1,pushCallinRingStatistics:t.initOptions.pushCallinRingStatistics||!1},reconnectionDelay:3e3,"force new connection":!0,transports:["websocket"],timeout:5e3};n.attachEventCallbacks?(n.attachEventCallbacks.serve=o,n.attachEventCallbacks.SocketOptions=a,t.createEventHandle(n.attachEventCallbacks)):t.createEventHandle({serve:o,SocketOptions:a})}},error:function(e){i.error({error:e})}})},this.attachNetworkCallbacks={message:t.noop,error:t.noop,success:t.noop},this.initnNetworkMonitoring=function(e,r){var i="";e.forEach(function(e){"MONITOR"===e.id&&(i="https://"+e.url)}),n.attachNetworkCallbacks.success(),n.attachNetworkCallbacks.message({delay:100}),setInterval(function(){var e=(new Date).getTime();networkMonitoringConfig.requestState=!0,t.request(i+"/ready",{method:"GET",success:function(t){if(t.success){var r=(new Date).getTime();networkMonitoringConfig.delay=(r-e)/2,n.attachNetworkCallbacks.message({delay:networkMonitoringConfig.delay})}else n.attachNetworkCallbacks.error(),networkMonitoringConfig.delay=500,networkMonitoringConfig.requestState=!1},error:function(e){n.attachNetworkCallbacks.error(),networkMonitoringConfig.delay=500,networkMonitoringConfig.requestState=!1}})},1e4)},this.listenCallNetork=function(e){e&&(n.attachNetworkCallbacks.message=e.message&&"function"==typeof e.message?e.message:t.noop,n.attachNetworkCallbacks.success=e.success&&"function"==typeof e.success?e.success:t.noop,n.attachNetworkCallbacks.error=e.error&&"function"==typeof e.error?e.error:t.noop)},this.volumeCallbacks={message:t.noop,error:t.noop,success:t.noop},this.stopVolumeCallbacks={error:t.noop,success:t.noop},this.audioContext=null,this.analyser=null,this.dataArray=null,this.stream=null,this.volumeIntervalId=null,this.getMicrophoneVolume=function(){if(!n.analyser||!n.dataArray)return 0;n.analyser.getByteFrequencyData(n.dataArray);for(var e=0,t=0;t<n.dataArray.length;t++)e+=n.dataArray[t];return e/n.dataArray.length},this.initAudioDetection=function(){return __awaiter(n,void 0,void 0,function(){var e,t,n;return __generator(this,function(r){switch(r.label){case 0:if(this.audioContext)return[2];r.label=1;case 1:return r.trys.push([1,3,,4]),e=this,[4,navigator.mediaDevices.getUserMedia({audio:!0})];case 2:return e.stream=r.sent(),this.audioContext=new AudioContext,t=this.audioContext.createMediaStreamSource(this.stream),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=256,this.dataArray=new Uint8Array(this.analyser.frequencyBinCount),t.connect(this.analyser),[3,4];case 3:return n=r.sent(),this.volumeCallbacks.error(n),[3,4];case 4:return[2]}})})},this.startVolumeDetection=function(e,t){return __awaiter(n,void 0,void 0,function(){var t,n=this;return __generator(this,function(r){switch(r.label){case 0:return"WEBRTC"!==e.loginType?(this.volumeCallbacks.error("只有webrtc支持音量检测"),[2]):(this.clearVolumeDetection(),[4,this.initAudioDetection()]);case 1:return r.sent(),this.volumeCallbacks.success({code:"200",msg:"音频检测已初始化"}),e.interval||(e.interval=500),e.interval<100&&(e.interval=100),e.interval>5e3&&(e.interval=5e3),t=this.getMicrophoneVolume(),this.volumeCallbacks.message({volume:Math.round(t/255*100)}),this.volumeIntervalId=setInterval(function(){var e=n.getMicrophoneVolume();n.volumeCallbacks.message({volume:Math.round(e/255*100)})},e.interval),[2]}})})},this.clearVolumeDetection=function(){n.volumeIntervalId&&(clearInterval(n.volumeIntervalId),n.volumeIntervalId=null),n.stream&&(n.stream.getTracks().forEach(function(e){return e.stop()}),n.stream=null),n.audioContext&&(n.audioContext.close(),n.audioContext=null),n.analyser=null,n.dataArray=null},this.stopVolumeDetection=function(){try{n.clearVolumeDetection(),n.stopVolumeCallbacks.success({code:"200",msg:"音频检测关闭成功"})}catch(e){n.stopVolumeCallbacks.error(e)}},this.listenCallVolume=function(e){e&&(n.volumeCallbacks.message=e.message&&"function"==typeof e.message?e.message:t.noop,n.volumeCallbacks.success=e.success&&"function"==typeof e.success?e.success:t.noop,n.volumeCallbacks.error=e.error&&"function"==typeof e.error?e.error:t.noop),t.initOptions.volume||(t.initOptions.volume={open:!0,interval:500}),n.startVolumeDetection(__assign(__assign({},t.initOptions.volume),{loginType:t.initOptions.loginType}),"")},this.stopListenVolume=function(e){e&&(n.stopVolumeCallbacks.success=e.success&&"function"==typeof e.success?e.success:t.noop,n.stopVolumeCallbacks.error=e.error&&"function"==typeof e.error?e.error:t.noop),n.stopVolumeDetection()},this.turnOffRingCallbacks={error:t.noop,success:t.noop},this.muteRing=function(e){e&&(n.turnOffRingCallbacks.success=e.success&&"function"==typeof e.success?e.success:t.noop,n.turnOffRingCallbacks.error=e.error&&"function"==typeof e.error?e.error:t.noop);try{t.isCanRing=!1,AudioTaskInstance.ringAudioPause(),n.turnOffRingCallbacks.success({code:"200",msg:"关闭铃声成功"})}catch(e){n.turnOffRingCallbacks.error(e)}},this.sdkMonitorMsg=function(e){if(e.success=e&&"function"==typeof e.success?e.success:t.noop,e.error=e&&"function"==typeof e.error?e.error:t.noop,null!==e.type&&void 0!==e.type&&""!==e.type)if(null!==e.requestMsg&&void 0!==e.requestMsg&&""!==e.requestMsg&&"{}"!==JSON.stringify(e.requestMsg))if(t.initOptions.monitor)try{t.changeMonitorEventHandle(n.allMonitorEventCallbacks,e),e.success({code:"200",msg:"成功"})}catch(t){e.error(t)}else e.error({success:!1,message:"The monitor is not turned on when initializing!"});else e.error({success:!1,message:"Parameter requestMsg is required!"});else e.error({success:!1,message:"Parameter type is required!"})},this.closeSdkMonitor=function(e){if(e.success=e&&"function"==typeof e.success?e.success:t.noop,e.error=e&&"function"==typeof e.error?e.error:t.noop,null!==e.type&&void 0!==e.type&&""!==e.type&&0!==e.type.length)if(t.initOptions.monitor)try{e.type.forEach(function(e){switch(e){case"summary":clearInterval(t.summaryUeTimer);break;case"agent":clearInterval(t.agentUeTimer);break;case"queue":clearInterval(t.queueUeTimer)}}),e.success({code:"200",msg:"success"})}catch(t){e.error(t)}else e.error({success:!1,message:"The monitor is not turned on when initializing!"});else e.error({success:!1,message:"Parameter type is required!"})},this.initAgentQueue=function(e,r,i,s){(n.attachMonitorEventCallbacks||n.attachNlsTranslationEventCallbacks||n.allMonitorEventCallbacks)&&t.request(e+"/platform/action/refreshWsToken",{verb:"GET",loginToken:t.loginToken,sessionId:t.agentInfo._id,success:function(e){if(e&&e.data){var o="";i.forEach(function(e){"MONITOR"===e.id&&(o=e.url)});var a={query:{accountId:s.accountId,agentNumber:s.agentNumber,agentId:s._id,token:e.data.wsToken,wsExtra:JSON.stringify({loginType:r,channelType:"SDK",ability:["call"]}),timestamp:e.data.timestamp,clientType:3},reconnectionDelay:3e3,"force new connection":!0,transports:["websocket"],timeout:5e3};n.attachMonitorEventCallbacks&&t.UserConfig.isOpenCallQueue&&(n.attachMonitorEventCallbacks.serve=o,n.attachMonitorEventCallbacks.SocketOptions=a,t.createQueueMonitorEventHandle(n.attachMonitorEventCallbacks)),n.attachNlsTranslationEventCallbacks&&t.UserConfig.openNlsTranslation&&(n.attachNlsTranslationEventCallbacks.serve=o,n.attachNlsTranslationEventCallbacks.SocketOptions=a,t.createopenNlsTransEventHandle(n.attachNlsTranslationEventCallbacks)),n.allMonitorEventCallbacks&&t.UserConfig.monitor&&(n.allMonitorEventCallbacks.serve=o,n.allMonitorEventCallbacks.SocketOptions=a,t.createopenAllMonitorEventHandle(n.allMonitorEventCallbacks))}},error:function(e){t.log("失败"),i.error({error:e})}})},this.initQueue=function(e){t.request(e+"/call/monitor/agent/queue/query",{verb:"POST",body:{accountId:t.agentInfo.accountId,agentId:t.agentInfo._id},success:function(e){e&&e.data?n.attachMonitorEventCallbacks.message(e):n.attachMonitorEventCallbacks.error(e)},error:function(e){n.attachMonitorEventCallbacks.error(e)}})},this.listenCallQueueEvent=function(e){n.attachMonitorEventCallbacks=e},this.listenTranslationEvent=function(e){n.attachNlsTranslationEventCallbacks=e},this.listenMonitor=function(e){n.allMonitorEventCallbacks=e},this.openMediaAudio=function(e,t){var r,i=navigator,s=i.mediaDevices,o=i.getUserMedia,a=i.webkitGetUserMedia,c=i.mozGetUserMedia,u=i.msGetUserMedia,l=null===(r=s&&s.getUserMedia||o||a||c||u)||void 0===r?void 0:r.bind(navigator);return s&&s.getUserMedia?s.getUserMedia({audio:!0}).then(function(e){return __awaiter(n,void 0,void 0,function(){return __generator(this,function(t){return h(e),[2,!0]})})}).catch(function(n){var r=n.message.includes("Permission denied")||"NotAllowedError"===n.name;return t?(r?alert(AUDIO_FORBIDDEN.forbiddenAudioMsg):e&&alert(e),r?AUDIO_FORBIDDEN:NOT_OPEN_AUDIO):r?AUDIO_FORBIDDEN:NOT_OPEN_AUDIO}):new Promise(function(n,r){l?l({audio:!0},function(e){h(e),n(!0)},function(n){t&&e&&alert(e),r(NOT_OPEN_AUDIO)}):r(NOT_OPEN_AUDIO)});function h(e){e&&"function"==typeof e.getTracks&&e.getTracks().forEach(function(e){e.stop()})}},this.listenCallEvent=function(e){n.attachEventCallbacks=e,e&&null!=t.Socketinstance&&t.createEventHandle(n.attachEventCallbacks)},this.switchOutDevices=function(e){return __awaiter(n,void 0,void 0,function(){var n,r,i,s;return __generator(this,function(o){switch(o.label){case 0:if(e.success=e&&"function"==typeof e.success?e.success:t.noop,e.fail=e&&"function"==typeof e.fail?e.fail:t.noop,!e.deviceId||"string"!=typeof e.deviceId)return e.fail({success:!1,message:"Passing in an illegal deviceId!"}),[2];n=document.getElementById("ueRemoteAudio"),o.label=1;case 1:return o.trys.push([1,4,,5]),[4,navigator.mediaDevices.enumerateDevices()];case 2:return r=o.sent(),i=r.filter(function(e){return"audiooutput"===e.kind}),i.some(function(t){return t.deviceId===e.deviceId})?[4,n.setSinkId(e.deviceId)]:(e.fail({success:!1,message:"The deviceId is not in the output device list!"}),[2]);case 3:return o.sent(),[3,5];case 4:return s=o.sent(),e.fail(s),[3,5];case 5:return e.success({code:"200",msg:"切换音频输出设备成功"}),[2]}})})},this._callApi=function(){var e,r,i=n;return{callout:function(n){return __awaiter(this,void 0,void 0,function(){var s,o,a,c,u,l;return __generator(this,function(h){switch(h.label){case 0:if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null===t.loginToken||void 0===t.loginToken)return n.fail({success:!1,message:"initialization not complete!"}),[2];if("KICK_OFF"===t.loginToken)return n.fail({success:!1,message:"您的座席账号正在别处登录,当前页面电话条已退出。"}),[2];if(null===t.agentInfo||void 0===t.agentInfo)return n.fail({success:!1,message:"initialization not complete!"}),[2];if(null===n.customerNumber||void 0===n.customerNumber)return n.fail({success:!1,message:"Parameter customerNumber is required!"}),[2];if(s=t.initOptions.server||t.callApiUrl,o={customerNumber:n.customerNumber,agentNumber:t.agentInfo.agentNumber,accountId:t.agentInfo.accountId,agentId:t.agentInfo._id,loginType:n.loginType||t.agentInfo.loginType||t.initOptions.loginType},n.agentTimeout&&(o.agentTimeout=n.agentTimeout),n.customerTimeout&&(o.customerTimeout=n.customerTimeout),n.agentDisNumber&&(o.agentDisNumber=n.agentDisNumber),n.customerDisNumber&&(o.customerDisNumber=n.customerDisNumber),n.extras&&(o.extras=n.extras),n.numberGroupId&&(o.numberGroupId=n.numberGroupId),n.numberGroupName&&(o.numberGroupName=n.numberGroupName),a=t.initOptions,c=!0,"WEBRTC"!==a.loginType)return[3,4];h.label=1;case 1:return h.trys.push([1,3,,4]),[4,i.openMediaAudio("请打开麦克风权限!",c)];case 2:return u=h.sent()||{},t.log(u),!0!==u?(n.fail({success:!1,message:"无麦克风权限!"}),[2]):[3,4];case 3:return l=h.sent(),t.log(l),n.fail({success:!1,message:"无麦克风权限!"}),[2];case 4:return t.request(s+"/call/api/call/call/out",{verb:"POST",body:o,loginToken:t.loginToken,sessionId:t.agentInfo._id,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success(__assign(__assign({success:!0,message:"callout success"},u),e.data)):n.fail(__assign({success:!1,message:e.message,code:e.code},u))}}),[2]}})})},hangup:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/call/hangup",{verb:"POST",body:{},loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?(n.success({success:!0,message:"hangup success",data:e}),AudioTaskInstance.InvalidateHangup()):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},holdOrUnHold:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.type&&void 0!==n.type){var i=t.initOptions.server||t.callApiUrl,s={type:n.type};t.request(i+"/call/api/call/hold",{verb:"POST",body:s,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"holdOrUnHold success"}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"Parameter type is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},muteOrUnMute:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.type&&void 0!==n.type){var i=t.initOptions.server||t.callApiUrl,s="1"===n.type?"in":"all",o={type:n.type,direction:s};t.request(i+"/call/api/call/mute",{verb:"POST",body:o,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"muteOrUnMute success"}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"Parameter type is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},transfer:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.type&&void 0!==n.type)if(null!==n.number&&void 0!==n.number){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/call/transfer",{verb:"POST",body:n,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"transfer success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"Parameter number is required!"});else n.fail({success:!1,message:"Parameter type is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},consult:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.mode&&void 0!==n.mode)if(null!==n.number&&void 0!==n.number){n.agentNumber=t.agentInfo.agentNumber;var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/call/consult",{verb:"POST",body:n,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"consult success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"Parameter number is required!"});else n.fail({success:!1,message:"Parameter mode is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},cancelconsult:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/call/consult/cancel",{verb:"POST",body:n,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"cancelconsult success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},endConsult:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/call/consult/stop",{verb:"POST",body:n,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"endConsult success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},callbackConsult:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/call/consult/resume",{verb:"POST",body:n,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"resumeConsult success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},consultTransfer:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/call/consult/transfer",{verb:"POST",body:n,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"consultTransfer success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},threeWayCall:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/call/threeway",{verb:"POST",body:n,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"threeWayCall success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},evaluate:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.type&&void 0!==n.type){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/call/evaluate",{verb:"POST",body:n,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"evaluate success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"Parameter type is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},meeting:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.number&&void 0!==n.number){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/call/meeting",{verb:"POST",body:{meetingType:"phone",number:n.number},loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"meeting success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"Parameter number is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},listen:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.agentNumber&&void 0!==n.agentNumber)if(n.agentNumber!==t.agentInfo.agentNumber&&"0000"!==t.agentInfo.agentNumber){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/monitor/listen",{verb:"POST",body:{agentNumber:n.agentNumber,listenAgent:t.agentInfo.agentNumber},loginToken:t.loginToken,sessionId:t.agentInfo._id,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"listen success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"agentNumber is not allowed to be the same as the current login account!"});else n.fail({success:!1,message:"Parameter agentNumber is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},loot:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.agentNumber&&void 0!==n.agentNumber)if(n.agentNumber!==t.agentInfo.agentNumber&&"0000"!==t.agentInfo.agentNumber){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/monitor/lootCall",{verb:"POST",body:{agentNumber:n.agentNumber,lootAgent:t.agentInfo.agentNumber},loginToken:t.loginToken,sessionId:t.agentInfo._id,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"loot success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"agentNumber is not allowed to be the same as the current login account!"});else n.fail({success:!1,message:"Parameter agentNumber is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},forcedHangup:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.agentNumber&&void 0!==n.agentNumber)if(n.agentNumber!==t.agentInfo.agentNumber&&"0000"!==t.agentInfo.agentNumber){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/monitor/hangupChannel",{verb:"POST",body:{agentNumber:n.agentNumber,hangupAgent:t.agentInfo.agentNumber},loginToken:t.loginToken,sessionId:t.agentInfo._id,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"forcedHangup success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"agentNumber is not allowed to be the same as the current login account!"});else n.fail({success:!1,message:"Parameter agentNumber is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},breakIn:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.agentNumber&&void 0!==n.agentNumber)if(n.agentNumber!==t.agentInfo.agentNumber&&"0000"!==t.agentInfo.agentNumber){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/monitor/breakIn",{verb:"POST",body:{agentNumber:n.agentNumber,breakInAgent:t.agentInfo.agentNumber},loginToken:t.loginToken,sessionId:t.agentInfo._id,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"breakIn success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"agentNumber is not allowed to be the same as the current login account!"});else n.fail({success:!1,message:"Parameter agentNumber is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},whisper:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.agentNumber&&void 0!==n.agentNumber)if(n.agentNumber!==t.agentInfo.agentNumber&&"0000"!==t.agentInfo.agentNumber){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/monitor/whisper",{verb:"POST",body:{agentNumber:n.agentNumber,whisperAgent:t.agentInfo.agentNumber},loginToken:t.loginToken,sessionId:t.agentInfo._id,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"whisper success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"agentNumber is not allowed to be the same as the current login account!"});else n.fail({success:!1,message:"Parameter agentNumber is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})}}},this._agentApi=function(){var e=n;return{switchLoginType:function(n){return __awaiter(this,void 0,void 0,function(){var r,i,s,o,a=this;return __generator(this,function(c){return r=null,n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null===n.loginType||void 0===n.loginType?(n.fail({success:!1,message:"Parameter loginType is required!"}),[2]):null===t.agentInfo||void 0===t.agentInfo?(n.fail({success:!1,message:"initialization not complete!"}),[2]):(null!==n.loginNumber&&void 0!==n.loginNumber&&(r=n.loginNumber),"PSTN"!==n.loginType||(r=r||t.agentInfo.mobile)?("SIP"===n.loginType&&(r=r||t.agentInfo.sipNumber),"WEBRTC"===n.loginType&&(r=t.agentInfo.webrtcSipNumber),i=t.initOptions.server||t.callApiUrl,s={loginType:n.loginType,loginNumber:r},t.request(i+"/call/api/agent/v1/login-type/change",{verb:"POST",body:s,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,success:function(r){return __awaiter(a,void 0,void 0,function(){return __generator(this,function(s){switch(s.label){case 0:return r.success?(n.success(__assign({success:!0,message:"updateLoginType success"},o)),t.agentInfo.loginType=n.loginType,t.initOptions.loginType=n.loginType,"WEBRTC"!==n.loginType?[3,1]:(e._webPhoneApi().connect(),[3,4])):[3,5];case 1:return"PSTN"!==n.loginType?[3,3]:[4,t.request(i+"/platform/action/updateCallConfig",{verb:"POST",body:{agentCallConfig:{},mobile:n.loginNumber},loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId})];case 2:return s.sent(),e._webPhoneApi().disconnect(),[3,4];case 3:e._webPhoneApi().disconnect(),s.label=4;case 4:return[3,6];case 5:n.fail(__assign({success:!1,message:r.message,code:r.code},o)),s.label=6;case 6:return[2]}})})}}),[2]):(alert("请给座席绑定手机号,或者传入号码参数!"),n.fail({success:!1,message:"Please bind your mobile number"}),[2]))})})},findPhoneBarList:function(e){if(e.success=e&&"function"==typeof e.success?e.success:t.noop,e.fail=e&&"function"==typeof e.fail?e.fail:t.noop,null!==t.agentInfo&&void 0!==t.agentInfo){var n=t.initOptions.server||t.callApiUrl;t.request(n+"/call/api/phone/bar/all",{verb:"GET",loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,success:function(t){if(t.success){var n=[];t.data.forEach(function(e){var t={name:e.name,number:e.number};n.push(t)}),e.success({success:!0,data:n})}else e.fail({success:!1,message:t.message,code:t.code})}})}else e.fail({success:!1,message:"initialization not complete!"})},switchPhoneBar:function(e){if(e.success=e&&"function"==typeof e.success?e.success:t.noop,e.fail=e&&"function"==typeof e.fail?e.fail:t.noop,null!==e.stateNumber&&void 0!==e.stateNumber)if(null!==t.agentInfo&&void 0!==t.agentInfo){var n=t.initOptions.server||t.callApiUrl,r={stateNumber:e.stateNumber,accountId:t.agentInfo.accountId,agentNumber:t.agentInfo.agentNumber};t.request(n+"/call/api/agent/status/switch",{verb:"POST",body:r,loginToken:t.loginToken,sessionId:t.agentInfo._id,success:function(t){t.success?e.success({success:!0}):e.fail({success:!1,message:t.message,code:t.code})}})}else e.fail({success:!1,message:"initialization not complete!"});else e.fail({success:!1,message:"Parameter stateNumber is required!"})},logout:function(e){if(e.success=e&&"function"==typeof e.success?e.success:t.noop,e.fail=e&&"function"==typeof e.fail?e.fail:t.noop,null!==t.agentInfo&&void 0!==t.agentInfo){null!==e.toAnswerOffline&&void 0!==e.toAnswerOffline||(e.toAnswerOffline="0");var n=t.initOptions.server||t.callApiUrl,r={toAnswerOffline:e.toAnswerOffline};t.request(n+"/call/api/sdk/agent/logout",{verb:"POST",body:r,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,success:function(n){n.success?e&&(t.Socketinstance&&(t.Socketinstance.disconnect(),t.Socketinstance=null),t.MonitorSocketinstance&&(t.MonitorSocketinstance.disconnect(),t.MonitorSocketinstance=null),"WEBRTC"===t.UserConfig.loginType&&t.webPhone&&(window.sessionStorage.setItem("kickoff","true"),t.webPhone.disconnect(),t.webPhone=null),e.success({success:!0})):e&&e.fail({success:!1,message:n.message,code:n.code})}})}else e.fail({success:!1,message:"initialization not complete!"})},findIdleAgentsForQueue:function(e){if(e.success=e&&"function"==typeof e.success?e.success:t.noop,e.fail=e&&"function"==typeof e.fail?e.fail:t.noop,null!==t.agentInfo&&void 0!==t.agentInfo){var n=t.initOptions.server||t.callApiUrl;t.request(n+"/call/api/queue/acountFreeAgent/find",{verb:"POST",body:{},loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,success:function(t){t.success?e&&e.success({success:!0,dataList:t.data||[]}):e&&e.fail({success:!1,message:t.message,code:t.code})}})}else e.fail({success:!1,message:"initialization not complete!"})},getAvailableSipNumberList:function(e){if(e.success=e&&"function"==typeof e.success?e.success:t.noop,e.fail=e&&"function"==typeof e.fail?e.fail:t.noop,null!==t.agentInfo&&void 0!==t.agentInfo){var n=t.initOptions.server||t.callApiUrl;t.request(n+"/call/api/sip/avaliable/query",{verb:"POST",body:{},loginToken:t.loginToken,sessionId:t.agentInfo._id,success:function(t){if(t.success&&t.data){var n=[];t.data.forEach(function(e){var t={number:e.id,numberName:e.number};n.push(t)}),e.success({success:!0,data:n})}else e.fail({success:!1,message:t.message,code:t.code})}})}else e.fail({success:!1,message:"initialization not complete!"})}}},this._webPhoneApi=function(){return{accept:function(){t.webPhone.accept()},connect:function(){t.webPhone&&this.isConnected()||t.initWebrtcEvent(t.agentextras)},disconnect:function(){t.webPhone&&this.isConnected()&&t.webPhone.disconnect()},isConnected:function(){return t.webPhone.isConnected()},sendDTMF:function(e){t.webPhone.sendDTMF(e)}}},e.error="function"==typeof e.error?e.error:t.noop,e.success="function"==typeof e.success?e.success:t.noop,null!==e.accountName&&void 0!==e.accountName&&""!==e.accountName||null!==e.accountId&&void 0!==e.accountId&&""!==e.accountId?null!==e.accountName&&void 0!==e.accountName&&""!==e.accountName||null!==e.agentNumber&&void 0!==e.agentNumber&&""!==e.accountId?null!==e.password&&void 0!==e.password||null!==e.passwordPk&&void 0!==e.passwordPk?e.password&&e.passwordPk?e.error({message:"Invalid password, please use one of them"}):(null!==e.loginType&&void 0!==e.loginType||(e.loginType="PSTN"),null!==e.pushHangupStatistics&&void 0!==e.pushHangupStatistics||(e.pushHangupStatistics=!1),null!==e.pushCallinRingStatistics&&void 0!==e.pushCallinRingStatistics||(e.pushCallinRingStatistics=!1),this.init(e)):e.error({message:"Invalid password"}):e.error({message:"Invalid agentNumber or Invalid accountName"}):e.error({message:"Invalid accountId or Invalid accountName"})}var t;return e.noop=function(){},e.prototype.init=function(e){if(void 0===e&&(e={}),t.trace=t.noop,t.debug=t.noop,t.log=t.noop,t.warn=t.noop,t.error=t.noop,!0===e.debug||"all"===e.debug)t.trace=console.trace.bind(console),t.debug=console.debug.bind(console),t.log=console.log.bind(console),t.warn=console.warn.bind(console),t.error=console.error.bind(console);else if(Array.isArray(e.debug))for(var n in e.debug){var r=e.debug[n];switch(r){case"trace":t.trace=console.trace.bind(console);break;case"debug":t.debug=console.debug.bind(console);break;case"log":t.log=console.log.bind(console);break;case"warn":t.warn=console.warn.bind(console);break;case"error":t.error=console.error.bind(console);break;default:console.error("Unknown debugging option '"+r+"' (supported: 'trace', 'debug', 'log', warn', 'error')")}}t.log("Initializing library");var i=t.useDefaultDependencies({WebSocket:ueWebsocket});t.newWebSocket=i.newWebSocket,t.request=i.request,this.getDomain(e)},e.prototype.getDomain=function(e){return __awaiter(this,void 0,void 0,function(){var n,r,i,s=this;return __generator(this,function(o){return n=(null===(i=e.accountName)||void 0===i?void 0:i.split("@")[1])||e.accountId,r=e.server||t.callApiUrl,t.request(r+"/platform/public/cloudConfig?accountName="+n,{verb:"GET",success:function(n){n.success?(e.server="https://"+n.data.baseURL+"/api",t.callApiUrl="https://"+n.data.baseURL+"/api",s.login(e)):e.error({res:n})},error:function(t){e.error({error:t})}}),[2]})})},e.prototype.login=function(e){return __awaiter(this,void 0,void 0,function(){var n,r,i,s,o,a,c,u,l,h=this;return __generator(this,function(d){return t.log(e),t.UserConfig=e,n=e.server||t.callApiUrl,r=e.accountName?e.accountName:e.agentNumber+"@"+e.accountId,i=e.loginType,s=e.isOpenNetwork||!1,o=e.isOpenCallQueue||!1,a=e.openNlsTranslation||!1,c=e.monitor||!1,u={loginName:r,loginType:i,loginChannel:"SDK",password:"",clientType:1},e.password&&(u.password=e.password,t.request(n+"/platform/public/loginPre",{verb:"GET",success:function(r){if(r&&r.success&&r.data){var d=decodeURIComponent(gBase64.decode(r.data.pk)),p=new JSEncrypt;p.setPublicKey(d);var g=md5(u.password),f=p.encrypt(g);u.password=f,t.request(n+"/platform/public/login",{verb:"POST",body:u,success:function(r){r.success?t.request(n+"/platform/action/loginInfo",{verb:"GET",loginToken:r.data.loginToken,sessionId:r.data.sessionId,success:function(r){r.success?(r.data.agent&&(t.agentInfo=r.data.agent,t.loginToken=r.data.loginToken,t.initOptions=__assign(__assign({},e),{audioInfo:l}),e.success(__assign(__assign({},r),{msg:"登录成功"}))),h.initAttachEvent(n,i,r.data.pushServer,r.data.agent),s&&h.initnNetworkMonitoring(r.data.pushServer,""),(o||a||c)&&h.initAgentQueue(n,i,r.data.pushServer,r.data.agent),o&&h.initQueue(n),h.getWebrtcInfo(n,e,i),window.sessionStorage.removeItem("kickoff")):e.error(__assign(__assign({},r),l))},error:function(t){e.error(__assign({error:t},l))}}):e.error(__assign(__assign({},r),l))},error:function(t){e.error(__assign({error:t},l))}})}else e.error(__assign(__assign({},r),l))},error:function(t){e.error(__assign({error:t},l))}})),e.passwordPk&&(u.password=e.passwordPk,t.request(n+"/platform/public/login",{verb:"POST",body:u,success:function(r){r.success?t.request(n+"/platform/action/loginInfo",{verb:"GET",loginToken:r.data.loginToken,sessionId:r.data.sessionId,success:function(r){r.success?(r.data.agent&&(t.agentInfo=r.data.agent,t.loginToken=r.data.loginToken,t.initOptions=__assign(__assign({},e),{audioInfo:l}),e.success(__assign(__assign({},r),{msg:"登录成功"}))),h.initAttachEvent(n,i,r.data.pushServer,r.data.agent),s&&h.initnNetworkMonitoring(r.data.pushServer,""),(o||a||c)&&h.initAgentQueue(n,i,r.data.pushServer,r.data.agent),o&&h.initQueue(n),h.getWebrtcInfo(n,e,i),window.sessionStorage.removeItem("kickoff")):e.error(__assign(__assign({},r),l))},error:function(t){e.error(__assign({error:t},l))}}):e.error(__assign(__assign({},r),l))},error:function(t){e.error(__assign({error:t},l))}})),[2]})})},e.createEventHandle=function(e){void 0===e&&(e={}),e.success="function"==typeof e.success?e.success:t.noop,e.error="function"==typeof e.error?e.error:t.noop,e.message="function"==typeof e.message?e.message:t.noop,e.event="function"==typeof e.event?e.event:t.noop,e.server=null===e.serve||void 0===e.serve?"ws://152.136.72.209:3201/phoneBarGateway":e.serve,null!==e.SocketOptions&&void 0!==e.SocketOptions||(e.SocketOptions={},t.error({message:"login response error!"})),this.Socketinstance||(this.Socketinstance=t.newWebSocket(e.server,e.SocketOptions)),this.Socketinstance.on("connect",function(){e.success("connect event serve success!")}),this.Socketinstance.on("error",function(t,n){e.error({type:"socketError",error:t}),n&&"function"==typeof n&&n("error")}),this.Socketinstance.on("message",function(n,r){e.message({subtype:n.subType,data:n.data}),"WEBRTC"===t.initOptions.loginType&&judgementWebRtcSHandOrRing("WEBRTC",n.data),r&&"function"==typeof r&&r("success")}),this.Socketinstance.on("event",function(n){if("KICK_OFF"===n.subType&&(window.sessionStorage.setItem("kickoff","true"),!0===n.data.kickoff)){try{t.kickOffEvent()}catch(e){}e.event({message:"坐席账户在其他地方登录",data:n})}})},e.createQueueMonitorEventHandle=function(e){void 0===e&&(e={}),e.success="function"==typeof e.success?e.success:t.noop,e.error="function"==typeof e.error?e.error:t.noop,e.message="function"==typeof e.message?e.message:t.noop,e.server=null===e.serve||void 0===e.serve?"ue-dev1.useasy.cn":e.serve,null!==e.SocketOptions&&void 0!==e.SocketOptions||(e.SocketOptions={},t.error({message:"login response error!"})),null===this.MonitorSocketinstance&&(this.MonitorSocketinstance=t.newWebSocket(e.server,e.SocketOptions)),this.MonitorSocketinstance.on("connect",function(){e.success("connect event serve success!"),t.log("监控connect========")}),this.MonitorSocketinstance.on("error",function(t,n){e.error({type:"socketError",error:t}),n&&"function"==typeof n&&n("error")}),this.MonitorSocketinstance.on("event",function(n,r){if("KICK_OFF"===n.subType&&(window.sessionStorage.setItem("kickoff","true"),!0===n.data.kickoff)){try{t.kickOffEvent()}catch(e){}e.message({message:"坐席账户在其他地方登录",data:n})}e.message(n)}),this.MonitorSocketinstance.on("call",function(n,r){"queue"==n.subType&&t.UserConfig.isOpenCallQueue&&e.message({subtype:n.subType,data:n.data})})},e.createopenNlsTransEventHandle=function(e){void 0===e&&(e={}),e.success="function"==typeof e.success?e.success:t.noop,e.error="function"==typeof e.error?e.error:t.noop,e.message="function"==typeof e.message?e.message:t.noop,e.server=null===e.serve||void 0===e.serve?"ue-dev1.useasy.cn":e.serve,null!==e.SocketOptions&&void 0!==e.SocketOptions||(e.SocketOptions={},t.error({message:"login response error!"})),null===this.MonitorSocketinstance&&(this.MonitorSocketinstance=t.newWebSocket(e.server,e.SocketOptions)),this.MonitorSocketinstance.on("connect",function(){e.success("转译connect event serve success!"),t.log("转译监控connect========")}),this.MonitorSocketinstance.on("error",function(t,n){e.error({type:"socketError",error:t}),n&&"function"==typeof n&&n("error")}),this.MonitorSocketinstance.on("event",function(n,r){if("KICK_OFF"===n.subType&&(window.sessionStorage.setItem("kickoff","true"),!0===n.data.kickoff)){try{t.kickOffEvent()}catch(e){}e.message({message:"坐席账户在其他地方登录",data:n})}e.message(n)}),this.MonitorSocketinstance.on("call",function(n,r){"translation"==n.subType&&t.UserConfig.openNlsTranslation&&e.message({subtype:n.subType,data:n.data})})},e.createopenAllMonitorEventHandle=function(e){void 0===e&&(e={}),e.success="function"==typeof e.success?e.success:t.noop,e.error="function"==typeof e.error?e.error:t.noop,e.message="function"==typeof e.message?e.message:t.noop,e.server=null===e.serve||void 0===e.serve?"ue-dev1.useasy.cn":e.serve,null!==e.SocketOptions&&void 0!==e.SocketOptions||(e.SocketOptions={},t.error({message:"login response error!"})),null===this.MonitorSocketinstance&&(this.MonitorSocketinstance=t.newWebSocket(e.server,e.SocketOptions)),this.MonitorSocketinstance.on("connect",function(){e.success("转译connect event serve success!"),t.log("转译监控connect========")}),this.MonitorSocketinstance.on("error",function(t,n){e.error({type:"socketError",error:t}),n&&"function"==typeof n&&n("error")}),this.MonitorSocketinstance.on("event",function(n,r){if("KICK_OFF"===n.subType&&(window.sessionStorage.setItem("kickoff","true"),!0===n.data.kickoff)){try{t.kickOffEvent()}catch(e){}e.message({message:"坐席账户在其他地方登录",data:n})}e.message(n)}),t.UserConfig.monitor&&this.MonitorSocketinstance.on("monitor",function(n){t.UserConfig.monitor&&e.message({type:"agent",data:n})})},e.changeMonitorEventHandle=function(e,n){var r=this;void 0===e&&(e={}),e.success="function"==typeof e.success?e.success:t.noop,e.error="function"==typeof e.error?e.error:t.noop,e.message="function"==typeof e.message?e.message:t.noop,e.server=null===e.serve||void 0===e.serve?"ue-dev1.useasy.cn":e.serve,null!==e.SocketOptions&&void 0!==e.SocketOptions||(e.SocketOptions={},t.error({message:"login response error!"})),null===this.MonitorSocketinstance&&(this.MonitorSocketinstance=t.newWebSocket(e.server,e.SocketOptions)),t.UserConfig.monitor&&n&&(t.agentUeTimer&&clearInterval(t.agentUeTimer),t.queueUeTimer&&clearInterval(t.queueUeTimer),t.summaryUeTimer&&clearInterval(t.summaryUeTimer),n.type.forEach(function(i){var s;switch(i){case"agent":null!==r.MonitorSocketinstance&&(null===(s=r.MonitorSocketinstance)||void 0===s||s.emit("monitor","agent",JSON.stringify(__assign(__assign({},n.requestMsg),{monitorQueryAgent:t.agentInfo._id,accountId:t.agentInfo.accountId})))),t.agentUeTimer=window.setInterval(function(){var e;null===(e=r.MonitorSocketinstance)||void 0===e||e.emit("monitor","agent",JSON.stringify(__assign(__assign({},n.requestMsg),{monitorQueryAgent:t.agentInfo._id,accountId:t.agentInfo.accountId})))},3e3);break;case"queue":null!==r.MonitorSocketinstance&&r.handleHttpMonitor({type:"queue",url:"/call/monitor/detail/queue",data:{accountId:t.agentInfo.accountId,date:new Date}},e),t.queueUeTimer=window.setInterval(function(){r.handleHttpMonitor({type:"queue",url:"/call/monitor/detail/queue",data:{accountId:t.agentInfo.accountId,date:new Date}},e)},3e3);break;case"summary":null!==r.MonitorSocketinstance&&r.handleHttpMonitor({type:"summary",url:"/call/monitor/overview",data:{accountId:t.agentInfo.accountId,date:new Date}},e),t.summaryUeTimer=window.setInterval(function(){r.handleHttpMonitor({type:"summary",url:"/call/monitor/overview",data:{accountId:t.agentInfo.accountId,date:new Date}},e)},3e3)}}))},e.handleHttpMonitor=function(e,n){t.request(t.callApiUrl+e.url,{verb:"POST",body:e.data,success:function(r){r.success&&t.UserConfig.monitor?n.message({type:e.type,data:r.data}):n.error({type:e.type,data:r})}})},e.useDefaultDependencies=function(e){var n=e&&e.fetch||fetch,r=e&&e.Promise||Promise,i=e&&e.WebSocket||WebSocket;return{newWebSocket:function(e,t){return new i(e,t)},request:function(e,i){var s={method:i.verb,cache:"no-cache",headers:{"Content-Type":"application/json",loginToken:i.loginToken||"",sessionId:i.sessionId||"",clienttype:0}};i.encryptionFields&&(s.headers["ue-encryption-algorithm"]=i.encryptionAlgorithm||"aes",s.headers["ue-encryption-fields"]=i.encryptionFields),void 0!==i.withCredentials&&(s.credentials=!0===i.withCredentials?"include":i.withCredentials?i.withCredentials:"omit"),void 0!==i.body&&(s.body=JSON.stringify(i.body));var o=n(e,s).catch(function(e){return r.reject({message:"Probably a network error, is the gateway down?",error:e})});if(void 0!==i.timeout){var a=new r(function(e,t){var n=window.setTimeout(function(){return clearTimeout(n),i.error({message:"Request timed out",timeout:i.timeout}),t({message:"Request timed out",timeout:i.timeout})},i.timeout)});o=r.race([o,a])}return o.then(function(e){return e.ok?typeof i.success==typeof t.noop?e.json().then(function(e){i.success(e)}).catch(function(t){return i.error({message:"Failed to parse response body",error:t,response:e}),r.reject({message:"Failed to parse response body",error:t,response:e})}):void 0:(i.error({message:"API call failed",response:e}),r.reject({message:"API call failed",response:e}))}).catch(function(e){typeof i.error==typeof t.noop&&i.error(e.message||"<< internal error >>",e)}),o}}},Object.defineProperty(e.prototype,"agent",{get:function(){return this._agentApi()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"webrtc",{get:function(){return this._webPhoneApi()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"call",{get:function(){return this._callApi()},enumerable:!1,configurable:!0}),t=e,e.callApiUrl="https://app.useasy.cn/api",e.Socketinstance=null,e.AudioTask=null,e.MonitorSocketinstance=null,e.UserConfig=null,e.isCanRing=!0,e.kickOffEvent=function(){t.Socketinstance&&(t.Socketinstance.disconnect(),t.Socketinstance=null),t.MonitorSocketinstance&&(t.MonitorSocketinstance.disconnect(),t.MonitorSocketinstance=null),"WEBRTC"===t.UserConfig.loginType&&t.webPhone&&(window.sessionStorage.setItem("kickoff","true"),t.webPhone.disconnect(),t.webPhone=null)},e.initWebrtcEvent=function(e){return __awaiter(void 0,void 0,void 0,function(){return __generator(t,function(n){switch(n.label){case 0:return t.webPhone=new UeWebrtc({server:e.wssUrl,sip:e.sip,secret:e.password}),[4,this.webPhone.connect()];case 1:return n.sent(),this.webPhone.register(),[2]}})})},e}(),ueWebsocket=function(){function e(e,t){delete t.path,delete t.hostname,delete t.port,this.ws=_t.connect("wss://".concat(e),t)}return e.prototype.on=function(e,t){"connect"===e&&this.ws.on(e,t),"error"===e&&(this.ws.on("connect_error",t),this.ws.on("error",t),this.ws.on("disconnect",t),this.ws.on("reconnect_failed",t)),"message"===e&&this.ws.on("call",t),"event"===e&&this.ws.on("event",t),"call"===e&&this.ws.on("call",t),"monitor"===e&&this.ws.on("monitor",t)},e.prototype.emit=function(e,t,n){this.ws.emit(e,t,n)},e.prototype.disconnect=function(){this.ws.disconnect()},e}(),AudioTask=function(){function e(){var e=this;fetch(ringingWav).then(function(e){return e.blob()}).then(function(t){var n=URL.createObjectURL(t);e.ringAudio=new Audio(n),e.ringAudio.loop=!0,e.ringAudioRunning=!1}),fetch(hangupWav).then(function(e){return e.blob()}).then(function(t){var n=URL.createObjectURL(t);e.handupAudio=new Audio(n),e.hangupAllow=!0})}return e.prototype.ringAudioPlay=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,this.ringAudio.play()];case 1:return e.sent(),this.ringAudioRunning=!0,[2]}})})},e.prototype.ringAudioPause=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this.ringAudio.paused?[3,2]:[4,this.ringAudio.pause()];case 1:e.sent(),this.ringAudioRunning=!1,e.label=2;case 2:return[2]}})})},e.prototype.activeHangup=function(){this.hangupAllow=!0},e.prototype.InvalidateHangup=function(){this.hangupAllow=!1},e.prototype.triggerTask=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return this.hangupAllow?this.handupAudio.play():this.activeHangup(),[2]})})},e}(),AudioTaskInstance=new AudioTask,CALL_METHOD="WEBRTC",CALLEVENT_RING="ring",CALLEVENT_HANGUP="hangup",CALL_FROM_INCOMING="callin",CALL_FROM_INTERCOM="inner",CALL_FROM_TWOWAYCALL="twoWayCall",CALL_FROM_TRANSFER="transfer",CALL_FROM_AUTODIALOUT="autoCallout",judgementWebRtcSHandOrRing=function(e,t){e===CALL_METHOD&&(t.eventType!==CALLEVENT_RING||t.callType!==CALL_FROM_INCOMING&&t.callType!==CALL_FROM_INTERCOM&&t.callType!==CALL_FROM_TWOWAYCALL&&t.callType!==CALL_FROM_TRANSFER&&t.callType!==CALL_FROM_AUTODIALOUT||!ueSoftphone.isCanRing?AudioTaskInstance.ringAudioRunning&&AudioTaskInstance.ringAudioPause():AudioTaskInstance.ringAudioPlay(),t.eventType===CALLEVENT_HANGUP&&(AudioTaskInstance.triggerTask(),ueSoftphone.isCanRing=!0))};return ueSoftphone}();
1
+ var ueSoftPhone=function(){"use strict";var extendStatics=function(e,t){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},extendStatics(e,t)};function __extends$1(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var __assign=function(){return __assign=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},__assign.apply(this,arguments)};function __awaiter(e,t,n,r){return new(n||(n=Promise))(function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((r=r.apply(e,t||[])).next())})}function __generator(e,t){var n,r,i,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(a){return function(c){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,a[0]&&(s=0)),s;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,r=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){s.label=a[1];break}if(6===a[0]&&s.label<i[1]){s.label=i[1],i=a;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(a);break}i[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}"function"==typeof SuppressedError&&SuppressedError;const t$1=Object.create(null);t$1.open="0",t$1.close="1",t$1.ping="2",t$1.pong="3",t$1.message="4",t$1.upgrade="5",t$1.noop="6";const e=Object.create(null);Object.keys(t$1).forEach(t=>{e[t$1[t]]=t});const s={type:"error",data:"parser error"},n="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),i="function"==typeof ArrayBuffer,r=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,o=({type:e,data:t},s,o)=>n&&t instanceof Blob?s?o(t):a(t,o):i&&(t instanceof ArrayBuffer||r(t))?s?o(t):a(new Blob([t]),o):o(t$1[e]+(t||"")),a=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function h(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let c;const u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<64;e++)p[u.charCodeAt(e)]=e;const l="function"==typeof ArrayBuffer,d=(t,n)=>{if("string"!=typeof t)return{type:"message",data:y(t,n)};const r=t.charAt(0);return"b"===r?{type:"message",data:f(t.substring(1),n)}:e[r]?t.length>1?{type:e[r],data:t.substring(1)}:{type:e[r]}:s},f=(e,t)=>{if(l){const n=(e=>{let t,n,r,i,s,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const u=new ArrayBuffer(o),l=new Uint8Array(u);for(t=0;t<a;t+=4)n=p[e.charCodeAt(t)],r=p[e.charCodeAt(t+1)],i=p[e.charCodeAt(t+2)],s=p[e.charCodeAt(t+3)],l[c++]=n<<2|r>>4,l[c++]=(15&r)<<4|i>>2,l[c++]=(3&i)<<6|63&s;return u})(e);return y(n,t)}return{base64:!0,data:e}},y=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,g=String.fromCharCode(30);function m(){return new TransformStream({transform(e,t){!function(e,t){n&&e.data instanceof Blob?e.data.arrayBuffer().then(h).then(t):i&&(e.data instanceof ArrayBuffer||r(e.data))?t(h(e.data)):o(e,!1,e=>{c||(c=new TextEncoder),t(c.encode(e))})}(e,n=>{const r=n.length;let i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);const e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{i=new Uint8Array(9);const e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&"string"!=typeof e.data&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}})}let b;function v(e){return e.reduce((e,t)=>e+t.length,0)}function w(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let i=0;i<t;i++)n[i]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function k(e){if(e)return function(e){for(var t in k.prototype)e[t]=k.prototype[t];return e}(e)}k.prototype.on=k.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},k.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},k.prototype.off=k.prototype.removeListener=k.prototype.removeAllListeners=k.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<r.length;i++)if((n=r[i])===t||n.fn===t){r.splice(i,1);break}return 0===r.length&&delete this._callbacks["$"+e],this},k.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){r=0;for(var i=(n=n.slice(0)).length;r<i;++r)n[r].apply(this,t)}return this},k.prototype.emitReserved=k.prototype.emit,k.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},k.prototype.hasListeners=function(e){return!!this.listeners(e).length};const _="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function E(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const A=_.setTimeout,O=_.clearTimeout;function T(e,t){t.useNativeTimers?(e.setTimeoutFn=A.bind(_),e.clearTimeoutFn=O.bind(_)):(e.setTimeoutFn=_.setTimeout.bind(_),e.clearTimeoutFn=_.clearTimeout.bind(_))}class R extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}let C$1=class extends k{constructor(e){super(),this.writable=!1,T(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,n){return super.emitReserved("error",new R(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=d(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}(e);return t.length?"?"+t:""}};const B="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),N=64,S={};let x,L=0,q=0;function P(e){let t="";do{t=B[e%N]+t,e=Math.floor(e/N)}while(e>0);return t}function j(){const e=P(+new Date);return e!==x?(L=0,x=e):e+"."+P(L++)}for(;q<N;q++)S[B[q]]=q;let U=!1;try{U="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const D=U;function I(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||D))return new XMLHttpRequest}catch(e){}if(!t)try{return new(_[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function F(){}const M=null!=new I({xdomain:!1}).responseType;class V extends k{constructor(e,t){super(),T(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.data=void 0!==t.data?t.data:null,this.create()}create(){var e;const t=E(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd;const n=this.xhr=new I(t);try{n.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{n.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.opts.cookieJar)||void 0===e||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(n.timeout=this.opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(n)),4===n.readyState&&(200===n.status||1223===n.status?this.onLoad():this.setTimeoutFn(()=>{this.onError("number"==typeof n.status?n.status:0)},0))},n.send(this.data)}catch(e){return void this.setTimeoutFn(()=>{this.onError(e)},0)}"undefined"!=typeof document&&(this.index=V.requestsCount++,V.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=F,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete V.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}function H(){for(let e in V.requests)V.requests.hasOwnProperty(e)&&V.requests[e].abort()}V.requestsCount=0,V.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",H):"function"==typeof addEventListener&&addEventListener("onpagehide"in _?"pagehide":"unload",H,!1));const K="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Y=_.WebSocket||_.MozWebSocket,W="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),z$1={websocket:class extends C$1{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,n=W?{}:E(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=W?new Y(e,t,n):t?new Y(e,t):new Y(e)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;o(n,this.supportsBinary,e=>{try{this.ws.send(e)}catch(e){}r&&K(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=j()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!Y}},webtransport:class extends C$1{get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(e=>{const t=function(e,t){b||(b=new TextDecoder);const n=[];let r=0,i=-1,o=!1;return new TransformStream({transform(a,c){for(n.push(a);;){if(0===r){if(v(n)<1)break;const e=w(n,1);o=!(128&~e[0]),i=127&e[0],r=i<126?3:126===i?1:2}else if(1===r){if(v(n)<2)break;const e=w(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(2===r){if(v(n)<8)break;const e=w(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),o=t.getUint32(0);if(o>Math.pow(2,21)-1){c.enqueue(s);break}i=o*Math.pow(2,32)+t.getUint32(4),r=3}else{if(v(n)<i)break;const e=w(n,i);c.enqueue(d(o?e:b.decode(e),t)),r=0}if(0===i||i>e){c.enqueue(s);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=m();r.readable.pipeTo(e.writable),this.writer=r.writable.getWriter();const i=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this.writer.write(o).then(()=>this.onOpen())})}))}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;this.writer.write(n).then(()=>{r&&K(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}},polling:class extends C$1{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let n=location.port;n||(n=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||n!==e.port}const t=e&&e.forceBase64;this.supportsBinary=M&&!t,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const n=e.split(g),r=[];for(let e=0;e<n.length;e++){const i=d(n[e],t);if(r.push(i),"error"===i.type)break}return r})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const n=e.length,r=new Array(n);let i=0;e.forEach((e,s)=>{o(e,!1,e=>{r[s]=e,++i===n&&t(r.join(g))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=j()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new V(this.uri(),e)}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}},J=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,$=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Q(e){const t=e,n=e.indexOf("["),r=e.indexOf("]");-1!=n&&-1!=r&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let i=J.exec(e||""),s={},o=14;for(;o--;)s[$[o]]=i[o]||"";return-1!=n&&-1!=r&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=function(e,t){const n=t.replace(/\/{2,9}/g,"/").split("/");return"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1),"/"==t.slice(-1)&&n.splice(n.length-1,1),n}(0,s.path),s.queryKey=function(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}(0,s.query),s}class X extends k{constructor(e,t={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=Q(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=Q(t.host).host),T(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},n=e.split("&");for(let e=0,r=n.length;e<r;e++){let r=n[e].split("=");t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new z$1[e](n)}open(){let e;if(this.opts.rememberUpgrade&&X.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",e=>this.onClose("transport close",e))}probe(e){let t=this.createTransport(e),n=!1;X.priorWebsocketSuccess=!1;const r=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!n)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;X.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(u(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function i(){n||(n=!0,u(),t.close(),t=null)}const s=e=>{const n=new Error("probe error: "+e);n.transport=t.name,i(),this.emitReserved("upgradeError",n)};function o(){s("transport closed")}function a(){s("socket closed")}function c(e){t&&e.name!==t.name&&i()}const u=()=>{t.removeListener("open",r),t.removeListener("error",s),t.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};t.once("open",r),t.once("error",s),t.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onOpen(){if(this.readyState="open",X.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn(()=>{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let n=0;n<this.writeBuffer.length;n++){const r=this.writeBuffer[n].data;if(r&&(e+="string"==typeof(t=r)?function(e){let t=0,n=0;for(let r=0,i=e.length;r<i;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}(t):Math.ceil(1.33*(t.byteLength||t.size))),n>0&&e>this.maxPayload)return this.writeBuffer.slice(0,n);e+=2}var t;return this.writeBuffer}write(e,t,n){return this.sendPacket("message",e,t,n),this}send(e,t,n){return this.sendPacket("message",e,t,n),this}sendPacket(e,t,n,r){if("function"==typeof t&&(r=t,t=void 0),"function"==typeof n&&(r=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const i={type:e,data:t,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}onError(e){X.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let n=0;const r=e.length;for(;n<r;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}X.protocol=4;const G="function"==typeof ArrayBuffer,Z=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,tt=Object.prototype.toString,et="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===tt.call(Blob),st="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===tt.call(File);function nt(e){return G&&(e instanceof ArrayBuffer||Z(e))||et&&e instanceof Blob||st&&e instanceof File}function it(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(it(e[t]))return!0;return!1}if(nt(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return it(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&it(e[t]))return!0;return!1}function rt(e){const t=[],n=e.data,r=e;return r.data=ot(n,t),r.attachments=t.length,{packet:r,buffers:t}}function ot(e,t){if(!e)return e;if(nt(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){const n=new Array(e.length);for(let r=0;r<e.length;r++)n[r]=ot(e[r],t);return n}if("object"==typeof e&&!(e instanceof Date)){const n={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=ot(e[r],t));return n}return e}function at(e,t){return e.data=ht(e.data,t),delete e.attachments,e}function ht(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=ht(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=ht(e[n],t));return e}const ct=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var pt;function lt(e){return"[object Object]"===Object.prototype.toString.call(e)}!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(pt||(pt={}));class dt extends k{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===pt.BINARY_EVENT;n||t.type===pt.BINARY_ACK?(t.type=n?pt.EVENT:pt.ACK,this.reconstructor=new ft(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!nt(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(void 0===pt[n.type])throw new Error("unknown packet type "+n.type);if(n.type===pt.BINARY_EVENT||n.type===pt.BINARY_ACK){const r=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const i=e.substring(r,t);if(i!=Number(i)||"-"!==e.charAt(t))throw new Error("Illegal attachments");n.attachments=Number(i)}if("/"===e.charAt(t+1)){const r=t+1;for(;++t&&","!==e.charAt(t)&&t!==e.length;);n.nsp=e.substring(r,t)}else n.nsp="/";const r=e.charAt(t+1);if(""!==r&&Number(r)==r){const r=t+1;for(;++t;){const n=e.charAt(t);if(null==n||Number(n)!=n){--t;break}if(t===e.length)break}n.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(!dt.isPayloadValid(n.type,r))throw new Error("invalid payload");n.data=r}return n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case pt.CONNECT:return lt(t);case pt.DISCONNECT:return void 0===t;case pt.CONNECT_ERROR:return"string"==typeof t||lt(t);case pt.EVENT:case pt.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===ct.indexOf(t[0]));case pt.ACK:case pt.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ft{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=at(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var yt=Object.freeze({__proto__:null,protocol:5,get PacketType(){return pt},Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==pt.EVENT&&e.type!==pt.ACK||!it(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===pt.EVENT?pt.BINARY_EVENT:pt.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==pt.BINARY_EVENT&&e.type!==pt.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=rt(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},Decoder:dt});function gt(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const mt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class bt extends k{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[gt(e,"open",this.onopen.bind(this)),gt(e,"packet",this.onpacket.bind(this)),gt(e,"error",this.onerror.bind(this)),gt(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(mt.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const n={type:pt.EVENT,data:t,options:{}};if(n.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,r=t.pop();this._registerAckCallback(e,r),n.id=e}const r=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!r||!this.connected)||(this.connected?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){var n;const r=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===r)return void(this.acks[e]=t);const i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},r);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(i),t.apply(this,[null,...e])}}emitWithAck(e,...t){const n=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise((r,i)=>{t.push((e,t)=>n?e?i(e):r(t):r(e)),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>{if(n===this._queue[0])return null!==e?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...r)),n.pending=!1,this._drainQueue()}),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:pt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case pt.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case pt.EVENT:case pt.BINARY_EVENT:this.onevent(e);break;case pt.ACK:case pt.BINARY_ACK:this.onack(e);break;case pt.DISCONNECT:this.ondisconnect();break;case pt.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...r){n||(n=!0,t.packet({type:pt.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:pt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function vt(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}vt.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+n:e-n}return 0|Math.min(e,this.max)},vt.prototype.reset=function(){this.attempts=0},vt.prototype.setMin=function(e){this.ms=e},vt.prototype.setMax=function(e){this.max=e},vt.prototype.setJitter=function(e){this.jitter=e};class wt extends k{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,T(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=t.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new vt({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||yt;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new X(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=gt(t,"open",function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},s=gt(t,"error",i);if(!1!==this._timeout){const e=this._timeout,n=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(s),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(gt(e,"ping",this.onping.bind(this)),gt(e,"data",this.ondata.bind(this)),gt(e,"error",this.onerror.bind(this)),gt(e,"close",this.onclose.bind(this)),gt(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){K(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new bt(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const e of t)if(this.nsps[e].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const kt={};function _t(e,t){"object"==typeof e&&(t=e,e=void 0);const n=function(e,t="",n){let r=e;n=n||"undefined"!=typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==n?n.protocol+"//"+e:"https://"+e),r=Q(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const i=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+t,r.href=r.protocol+"://"+i+(n&&n.port===r.port?"":":"+r.port),r}(e,(t=t||{}).path||"/socket.io"),r=n.source,i=n.id,s=n.path,o=kt[i]&&s in kt[i].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new wt(r,t):(kt[i]||(kt[i]=new wt(r,t)),a=kt[i]),n.query&&!t.query&&(t.query=n.queryKey),a.socket(n.path,t)}Object.assign(_t,{Manager:wt,Socket:bt,io:_t,connect:_t});var NOT_OPEN_AUDIO={notOpenAudioMsg:"麦克风没有开启",notOpenAudioCode:403,notOpenAudioMsgEn:"Permission dismissed"},AUDIO_FORBIDDEN={forbiddenAudioMsg:"请先检查您的麦克风是否开启",forbiddenAudioCode:0,forbiddenAudioMsgEn:"Permission denied"},LIBRARY_VERSION="0.20.0",Parameters=function(){function e(e){for(var t in this.parameters={},e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}return e.prototype.setParam=function(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())},e.prototype.getParam=function(e){if(e)return this.parameters[e.toLowerCase()]},e.prototype.hasParam=function(e){return!(!e||void 0===this.parameters[e.toLowerCase()])},e.prototype.deleteParam=function(e){if(e=e.toLowerCase(),this.hasParam(e)){var t=this.parameters[e];return delete this.parameters[e],t}},e.prototype.clearParams=function(){this.parameters={}},e}(),NameAddrHeader=function(e){function t(t,n,r){var i=e.call(this,r)||this;return i.uri=t,i._displayName=n,i}return __extends$1(t,e),Object.defineProperty(t.prototype,"friendlyName",{get:function(){return this.displayName||this.uri.aor},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"displayName",{get:function(){return this._displayName},set:function(e){this._displayName=e},enumerable:!1,configurable:!0}),t.prototype.clone=function(){return new t(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))},t.prototype.toString=function(){var e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";for(var t in e+="<"+this.uri.toString()+">",this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e},t}(Parameters),URI=function(e){function t(t,n,r,i,s,o){void 0===t&&(t="sip");var a=e.call(this,s||{})||this;if(a.headers={},!r)throw new TypeError('missing or invalid "host" parameter');for(var c in o)o.hasOwnProperty(c)&&a.setHeader(c,o[c]);return a.raw={scheme:t,user:n,host:r,port:i},a.normal={scheme:t.toLowerCase(),user:n,host:r.toLowerCase(),port:i},a}return __extends$1(t,e),Object.defineProperty(t.prototype,"scheme",{get:function(){return this.normal.scheme},set:function(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"user",{get:function(){return this.normal.user},set:function(e){this.normal.user=this.raw.user=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"host",{get:function(){return this.normal.host},set:function(e){this.raw.host=e,this.normal.host=e.toLowerCase()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"aor",{get:function(){return this.normal.user+"@"+this.normal.host},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"port",{get:function(){return this.normal.port},set:function(e){this.normal.port=this.raw.port=e},enumerable:!1,configurable:!0}),t.prototype.setHeader=function(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]},t.prototype.getHeader=function(e){if(e)return this.headers[this.headerize(e)]},t.prototype.hasHeader=function(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))},t.prototype.deleteHeader=function(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){var t=this.headers[e];return delete this.headers[e],t}},t.prototype.clearHeaders=function(){this.headers={}},t.prototype.clone=function(){return new t(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))},t.prototype.toRaw=function(){return this._toString(this._raw)},t.prototype.toString=function(){return this._toString(this._normal)},Object.defineProperty(t.prototype,"_normal",{get:function(){return this.normal},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_raw",{get:function(){return this.raw},enumerable:!1,configurable:!0}),t.prototype._toString=function(e){var t=e.scheme+":";for(var n in e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port),this.parameters)this.parameters.hasOwnProperty(n)&&(t+=";"+n,null!==this.parameters[n]&&(t+="="+this.parameters[n]));var r=[];for(var i in this.headers)if(this.headers.hasOwnProperty(i))for(var s in this.headers[i])this.headers[i].hasOwnProperty(s)&&r.push(i+"="+this.headers[i][s]);return r.length>0&&(t+="?"+r.join("&")),t},t.prototype.escapeUser=function(e){var t;try{t=decodeURIComponent(e)}catch(e){throw e}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")},t.prototype.headerize=function(e){for(var t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},n=e.toLowerCase().replace(/_/g,"-").split("-"),r=n.length,i="",s=0;s<r;s++)0!==s&&(i+="-"),i+=n[s].charAt(0).toUpperCase()+n[s].substring(1);return t[i]&&(i=t[i]),i},t}(Parameters);function equivalentURI(e,t){if(e.scheme!==t.scheme)return!1;if(e.user!==t.user||e.host!==t.host||e.port!==t.port)return!1;if(!function(e,t){var n=Object.keys(e.parameters),r=Object.keys(t.parameters),i=n.filter(function(e){return r.includes(e)});return!!i.every(function(n){return e.parameters[n]===t.parameters[n]})&&(!!["user","ttl","method","transport"].every(function(n){return e.hasParam(n)&&t.hasParam(n)||!e.hasParam(n)&&!t.hasParam(n)})&&!!["maddr"].every(function(n){return e.hasParam(n)&&t.hasParam(n)||!e.hasParam(n)&&!t.hasParam(n)}))}(e,t))return!1;var n=Object.keys(e.headers),r=Object.keys(t.headers);if(0!==n.length||0!==r.length){if(n.length!==r.length)return!1;var i=n.filter(function(e){return r.includes(e)});if(i.length!==r.length)return!1;if(!i.every(function(n){return e.headers[n].length&&t.headers[n].length&&e.headers[n][0]===t.headers[n][0]}))return!1}return!0}var SyntaxError=function(e){function t(n,r,i,s){var o=e.call(this)||this;return o.message=n,o.expected=r,o.found=i,o.location=s,o.name="SyntaxError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(o,t),o}return __extends$1(t,e),t.buildMessage=function(e,t){function n(e){return e.charCodeAt(0).toString(16).toUpperCase()}function r(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(e){return"\\x0"+n(e)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(e){return"\\x"+n(e)})}function i(e){return e.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(e){return"\\x0"+n(e)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(e){return"\\x"+n(e)})}function s(e){switch(e.type){case"literal":return'"'+r(e.text)+'"';case"class":var t=e.parts.map(function(e){return Array.isArray(e)?i(e[0])+"-"+i(e[1]):i(e)});return"["+(e.inverted?"^":"")+t+"]";case"any":return"any character";case"end":return"end of input";case"other":return e.description}}return"Expected "+function(e){var t,n,r=e.map(s);if(r.sort(),r.length>0){for(t=1,n=1;t<r.length;t++)r[t-1]!==r[t]&&(r[n]=r[t],n++);r.length=n}switch(r.length){case 1:return r[0];case 2:return r[0]+" or "+r[1];default:return r.slice(0,-1).join(", ")+", or "+r[r.length-1]}}(e)+" but "+(((o=t)?'"'+r(o)+'"':"end of input")+" found.");var o},t}(Error);function peg$parse(e,t){t=void 0!==t?t:{};var n,r,i,s,o={},a={Contact:119,Name_Addr_Header:156,Record_Route:176,Request_Response:81,SIP_URI:45,Subscription_State:186,Supported:191,Require:182,Via:194,absoluteURI:84,Call_ID:118,Content_Disposition:130,Content_Length:135,Content_Type:136,CSeq:146,displayName:122,Event:149,From:151,host:52,Max_Forwards:154,Min_SE:213,Proxy_Authenticate:157,quoted_string:40,Refer_To:178,Replaces:179,Session_Expires:210,stun_URI:217,To:192,turn_URI:223,uuid:226,WWW_Authenticate:209,challenge:158,sipfrag:230,Referred_By:231},c=119,u=["\r\n",b("\r\n",!1),/^[0-9]/,S([["0","9"]],!1,!1),/^[a-zA-Z]/,S([["a","z"],["A","Z"]],!1,!1),/^[0-9a-fA-F]/,S([["0","9"],["a","f"],["A","F"]],!1,!1),/^[\0-\xFF]/,S([["\0","ÿ"]],!1,!1),/^["]/,S(['"'],!1,!1)," ",b(" ",!1),"\t",b("\t",!1),/^[a-zA-Z0-9]/,S([["a","z"],["A","Z"],["0","9"]],!1,!1),";",b(";",!1),"/",b("/",!1),"?",b("?",!1),":",b(":",!1),"@",b("@",!1),"&",b("&",!1),"=",b("=",!1),"+",b("+",!1),"$",b("$",!1),",",b(",",!1),"-",b("-",!1),"_",b("_",!1),".",b(".",!1),"!",b("!",!1),"~",b("~",!1),"*",b("*",!1),"'",b("'",!1),"(",b("(",!1),")",b(")",!1),"%",b("%",!1),function(){return" "},function(){return":"},/^[!-~]/,S([["!","~"]],!1,!1),/^[\x80-\uFFFF]/,S([["€","￿"]],!1,!1),/^[\x80-\xBF]/,S([["€","¿"]],!1,!1),/^[a-f]/,S([["a","f"]],!1,!1),"`",b("`",!1),"<",b("<",!1),">",b(">",!1),"\\",b("\\",!1),"[",b("[",!1),"]",b("]",!1),"{",b("{",!1),"}",b("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,S([["!","'"]],!1,!1),/^[*-[]/,S([["*","["]],!1,!1),/^[\]-~]/,S([["]","~"]],!1,!1),function(e){return e},/^[#-[]/,S([["#","["]],!1,!1),/^[\0-\t]/,S([["\0","\t"]],!1,!1),/^[\x0B-\f]/,S([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,S([["",""]],!1,!1),function(){(t=t||{data:{}}).data.uri=new URI(t.data.scheme,t.data.user,t.data.host,t.data.port),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port},function(){(t=t||{data:{}}).data.uri=new URI(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params,"SIP_URI"===t.startRule&&(t.data=t.data.uri)},"sips",b("sips",!0),"sip",b("sip",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(){(t=t||{data:{}}).data.user=decodeURIComponent(v().slice(0,-1))},function(){(t=t||{data:{}}).data.password=v()},function(){return(t=t||{data:{}}).data.host=v(),t.data.host},function(){return(t=t||{data:{}}).data.host_type="domain",v()},/^[a-zA-Z0-9_\-]/,S([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,S([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",v()},"::",b("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",v()},function(){return(t=t||{data:{}}).data.host_type="IPv4",v()},"25",b("25",!1),/^[0-5]/,S([["0","5"]],!1,!1),"2",b("2",!1),/^[0-4]/,S([["0","4"]],!1,!1),"1",b("1",!1),/^[1-9]/,S([["1","9"]],!1,!1),function(e){return t=t||{data:{}},e=parseInt(e.join("")),t.data.port=e,e},"transport=",b("transport=",!0),"udp",b("udp",!0),"tcp",b("tcp",!0),"sctp",b("sctp",!0),"tls",b("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",b("user=",!0),"phone",b("phone",!0),"ip",b("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",b("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",b("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",b("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",b("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,n){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),n=null===n?void 0:n[1],t.data.uri_params[e.toLowerCase()]=n},function(e,n){e=e.join("").toLowerCase(),n=n.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(n):t.data.uri_headers[e]=[n]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new URI(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params)},"//",b("//",!1),function(){(t=t||{data:{}}).data.scheme=v()},b("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=v()},"INVITE",b("INVITE",!1),"ACK",b("ACK",!1),"VXACH",b("VXACH",!1),"OPTIONS",b("OPTIONS",!1),"BYE",b("BYE",!1),"CANCEL",b("CANCEL",!1),"REGISTER",b("REGISTER",!1),"SUBSCRIBE",b("SUBSCRIBE",!1),"NOTIFY",b("NOTIFY",!1),"REFER",b("REFER",!1),"PUBLISH",b("PUBLISH",!1),function(){return(t=t||{data:{}}).data.method=v(),t.data.method},function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},function(){(t=t||{data:{}}).data.reason_phrase=v()},function(){(t=t||{data:{}}).data=v()},function(){var e,n;for(n=(t=t||{data:{}}).data.multi_header.length,e=0;e<n;e++)if(null===t.data.multi_header[e].parsed){t.data=null;break}null!==t.data?t.data=t.data.multi_header:t.data=-1},function(){var e;(t=t||{data:{}}).data.multi_header||(t.data.multi_header=[]);try{e=new NameAddrHeader(t.data.uri,t.data.displayName,t.data.params),delete t.data.uri,delete t.data.displayName,delete t.data.params}catch(t){e=null}t.data.multi_header.push({position:h,offset:y().start.offset,parsed:e})},function(e){'"'===(e=v().trim())[0]&&(e=e.substring(1,e.length-1)),(t=t||{data:{}}).data.displayName=e},"q",b("q",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.q=e},"expires",b("expires",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.expires=e},function(e){return parseInt(e.join(""))},"0",b("0",!1),function(){return parseFloat(v())},function(e,n){(t=t||{data:{}}).data.params||(t.data.params={}),n=null===n?void 0:n[1],t.data.params[e.toLowerCase()]=n},"render",b("render",!0),"session",b("session",!0),"icon",b("icon",!0),"alert",b("alert",!0),function(){"Content_Disposition"===(t=t||{data:{}}).startRule&&(t.data.type=v().toLowerCase())},"handling",b("handling",!0),"optional",b("optional",!0),"required",b("required",!0),function(e){(t=t||{data:{}}).data=parseInt(e.join(""))},function(){(t=t||{data:{}}).data=v()},"text",b("text",!0),"image",b("image",!0),"audio",b("audio",!0),"video",b("video",!0),"application",b("application",!0),"message",b("message",!0),"multipart",b("multipart",!0),"x-",b("x-",!0),function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},function(e){(t=t||{data:{}}).data=e},function(e){(t=t||{data:{}}).data.event=e.toLowerCase()},function(){var e=(t=t||{data:{}}).data.tag;t.data=new NameAddrHeader(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"tag",b("tag",!0),function(e){(t=t||{data:{}}).data.tag=e},function(e){(t=t||{data:{}}).data=parseInt(e.join(""))},function(e){(t=t||{data:{}}).data=e},function(){(t=t||{data:{}}).data=new NameAddrHeader(t.data.uri,t.data.displayName,t.data.params)},"digest",b("Digest",!0),"realm",b("realm",!0),function(e){(t=t||{data:{}}).data.realm=e},"domain",b("domain",!0),"nonce",b("nonce",!0),function(e){(t=t||{data:{}}).data.nonce=e},"opaque",b("opaque",!0),function(e){(t=t||{data:{}}).data.opaque=e},"stale",b("stale",!0),"true",b("true",!0),function(){(t=t||{data:{}}).data.stale=!0},"false",b("false",!0),function(){(t=t||{data:{}}).data.stale=!1},"algorithm",b("algorithm",!0),"md5",b("MD5",!0),"md5-sess",b("MD5-sess",!0),function(e){(t=t||{data:{}}).data.algorithm=e.toUpperCase()},"qop",b("qop",!0),"auth-int",b("auth-int",!0),"auth",b("auth",!0),function(e){(t=t||{data:{}}).data.qop||(t.data.qop=[]),t.data.qop.push(e.toLowerCase())},function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},function(){var e,n;for(n=(t=t||{data:{}}).data.multi_header.length,e=0;e<n;e++)if(null===t.data.multi_header[e].parsed){t.data=null;break}null!==t.data?t.data=t.data.multi_header:t.data=-1},function(){var e;(t=t||{data:{}}).data.multi_header||(t.data.multi_header=[]);try{e=new NameAddrHeader(t.data.uri,t.data.displayName,t.data.params),delete t.data.uri,delete t.data.displayName,delete t.data.params}catch(t){e=null}t.data.multi_header.push({position:h,offset:y().start.offset,parsed:e})},function(){(t=t||{data:{}}).data=new NameAddrHeader(t.data.uri,t.data.displayName,t.data.params)},function(){(t=t||{data:{}}).data.replaces_from_tag&&t.data.replaces_to_tag||(t.data=-1)},function(){(t=t||{data:{}}).data={call_id:t.data}},"from-tag",b("from-tag",!0),function(e){(t=t||{data:{}}).data.replaces_from_tag=e},"to-tag",b("to-tag",!0),function(e){(t=t||{data:{}}).data.replaces_to_tag=e},"early-only",b("early-only",!0),function(){(t=t||{data:{}}).data.early_only=!0},function(e,t){return t},function(e,t){return function(e,t){return[e].concat(t)}(e,t)},function(e){"Require"===(t=t||{data:{}}).startRule&&(t.data=e||[])},function(e){(t=t||{data:{}}).data.value=parseInt(e.join(""))},"active",b("active",!0),"pending",b("pending",!0),"terminated",b("terminated",!0),function(){(t=t||{data:{}}).data.state=v()},"reason",b("reason",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.reason=e)},function(e){t=t||{data:{}},void 0!==e&&(t.data.expires=e)},"retry_after",b("retry_after",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.retry_after=e)},"deactivated",b("deactivated",!0),"probation",b("probation",!0),"rejected",b("rejected",!0),"timeout",b("timeout",!0),"giveup",b("giveup",!0),"noresource",b("noresource",!0),"invariant",b("invariant",!0),function(e){"Supported"===(t=t||{data:{}}).startRule&&(t.data=e||[])},function(){var e=(t=t||{data:{}}).data.tag;t.data=new NameAddrHeader(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"ttl",b("ttl",!0),function(e){(t=t||{data:{}}).data.ttl=e},"maddr",b("maddr",!0),function(e){(t=t||{data:{}}).data.maddr=e},"received",b("received",!0),function(e){(t=t||{data:{}}).data.received=e},"branch",b("branch",!0),function(e){(t=t||{data:{}}).data.branch=e},"rport",b("rport",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.rport=e.join(""))},function(e){(t=t||{data:{}}).data.protocol=e},b("UDP",!0),b("TCP",!0),b("TLS",!0),b("SCTP",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data.host=v()},function(e){(t=t||{data:{}}).data.port=parseInt(e.join(""))},function(e){return parseInt(e.join(""))},function(e){"Session_Expires"===(t=t||{data:{}}).startRule&&(t.data.deltaSeconds=e)},"refresher",b("refresher",!1),"uas",b("uas",!1),"uac",b("uac",!1),function(e){"Session_Expires"===(t=t||{data:{}}).startRule&&(t.data.refresher=e)},function(e){"Min_SE"===(t=t||{data:{}}).startRule&&(t.data=e)},"stuns",b("stuns",!0),"stun",b("stun",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(e){(t=t||{data:{}}).data.host=e},"?transport=",b("?transport=",!1),"turns",b("turns",!0),"turn",b("turn",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data=v()},"Referred-By",b("Referred-By",!1),"b",b("b",!1),"cid",b("cid",!1)],l=[E('2 ""6 7!'),E('4"""5!7#'),E('4$""5!7%'),E('4&""5!7\''),E(";'.# &;("),E('4(""5!7)'),E('4*""5!7+'),E('2,""6,7-'),E('2.""6.7/'),E('40""5!71'),E('22""6273.‰ &24""6475.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),E(";).# &;,"),E('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),E('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),E('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/&#0#*;$&&&#/\'$8":Z" )("\'#&\'#'),E(';.." &"'),E("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),E('%%$;2/&#0#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),E('4\\""5!7].# &;3'),E('4^""5!7_'),E('4`""5!7a'),E(';!.) &4b""5!7c'),E('%$;).• &2F""6F7G.‰ &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/ž#0›*;).• &2F""6F7G.‰ &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),E('%$;).‰ &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/’#0*;).‰ &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),E('2T""6T7U.ã &2V""6V7W.× &2f""6f7g.Ë &2h""6h7i.¿ &2:""6:7;.³ &2D""6D7E.§ &22""6273.› &28""6879. &2j""6j7k.ƒ &;&.} &24""6475.q &2l""6l7m.e &2n""6n7o.Y &26""6677.M &2>""6>7?.A &2p""6p7q.5 &2r""6r7s.) &;\'.# &;('),E('%$;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W.› &2f""6f7g. &2h""6h7i.ƒ &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s/Ĵ#0ı*;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W.› &2f""6f7g. &2h""6h7i.ƒ &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s&&&#/"!&,)'),E("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),E("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),E("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),E("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),E("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),E('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),E('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),E("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),E("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),E("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),E("%;//0#;&/'$8\":~\" )(\"'#&'#"),E("%;&/0#;//'$8\":~\" )(\"'#&'#"),E("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),E('4""5!7€.A &4""5!7‚.5 &4ƒ""5!7„.) &;3.# &;.'),E("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),E("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:…$!!)($'#(#'#(\"'#&'#"),E(';..G &2L""6L7M.; &4†""5!7‡./ &4ƒ""5!7„.# &;3'),E('%2j""6j7k/J#4ˆ""5!7‰.5 &4Š""5!7‹.) &4Œ""5!7/#$+")("\'#&\'#'),E("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:Ž$ )($'#(#'#(\"'#&'#"),E("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:& )(&'#(%'#($'#(#'#(\"'#&'#"),E('%3""5$7‘.) &3’""5#7“/\' 8!:”!! )'),E('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:•# )(#\'#("\'#&\'#'),E("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),E('2<""6<7=.q &2>""6>7?.e &2@""6@7A.Y &2B""6B7C.M &2D""6D7E.A &22""6273.5 &26""6677.) &24""6475'),E('%$;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E0e*;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E&/& 8!:–! )'),E('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),E("%;U.) &;\\.# &;X/& 8!:—! )"),E('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:˜# )(#\'#("\'#&\'#'),E('$4™""5!7š/,#0)*4™""5!7š&&&#'),E('%4$""5!7%/?#$4›""5!7œ0)*4›""5!7œ&/#$+")("\'#&\'#'),E('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:# )(#\'#("\'#&\'#'),E('%%;Z/³#28""6879/¤$;Z/›$28""6879/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ސ &%2ž""6ž7Ÿ/¤#;Z/›$28""6879/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.۹ &%2ž""6ž7Ÿ/Œ#;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ٺ &%2ž""6ž7Ÿ/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ؓ &%2ž""6ž7Ÿ/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.ׄ &%2ž""6ž7Ÿ/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.֍ &%2ž""6ž7Ÿ/,#;[/#$+")("\'#&\'#.ծ &%2ž""6ž7Ÿ/,#;Z/#$+")("\'#&\'#.Տ &%;Z/›#2ž""6ž7Ÿ/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ӈ &%;Z/ª#%28""6879/,#;Z/#$+")("\'#&\'#." &"/ƒ$2ž""6ž7Ÿ/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.а &%;Z/¹#%28""6879/,#;Z/#$+")("\'#&\'#." &"/’$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2ž""6ž7Ÿ/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ί &%;Z/È#%28""6879/,#;Z/#$+")("\'#&\'#." &"/¡$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2ž""6ž7Ÿ/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.˕ &%;Z/×#%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/‰$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2ž""6ž7Ÿ/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ȑ &%;Z/þ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/×$%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/‰$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2ž""6ž7Ÿ/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ħ &%;Z/Ĝ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/õ$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Î$%28""6879/,#;Z/#$+")("\'#&\'#." &"/§$%28""6879/,#;Z/#$+")("\'#&\'#." &"/€$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2ž""6ž7Ÿ/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!: ! )'),E('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),E("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),E("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),E('%2¢""6¢7£/2#4¤""5!7¥/#$+")("\'#&\'#.˜ &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#\'#("\'#&\'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4¬""5!7­/,#;!/#$+")("\'#&\'#.# &;!'),E('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:®!! )'),E('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),E(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),E('%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("\'#&\'#'),E('%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("\'#&\'#'),E('%3Á""5\'7Â/1#;/($8":Ã"! )("\'#&\'#'),E('%3Ä""5$7Å/1#;ð/($8":Æ"! )("\'#&\'#'),E('%3Ç""5&7È/1#;T/($8":É"! )("\'#&\'#'),E('%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":Ì" )("\'#&\'#'),E('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":Í""! )("\'#&\'#'),E('%$;j/&#0#*;j&&&#/"!&,)'),E('%$;j/&#0#*;j&&&#/"!&,)'),E(";k.) &;+.# &;-"),E('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),E('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),E('%;n/A#2>""6>7?/2$;o/)$8#:Î#"" )(#\'#("\'#&\'#'),E("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),E("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),E('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),E(";‘.# &;r"),E("%;/G#;'/>$;s/5$;'/,$;„/#$+%)(%'#($'#(#'#(\"'#&'#"),E(";M.# &;t"),E("%;/E#28\"\"6879/6$;u.# &;x/'$8#:Ï# )(#'#(\"'#&'#"),E('%;v.# &;w/J#%26""6677/,#;ƒ/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),E('%2Ð""6Ð7Ñ/:#;€/1$;w." &"/#$+#)(#\'#("\'#&\'#'),E('%24""6475/,#;{/#$+")("\'#&\'#'),E("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),E(";*.) &;+.# &;-"),E(';+. &;-.‰ &22""6273.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),E('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),E('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),E("$;~0#*;~&"),E(';+.w &;-.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),E('%%;"/‡#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:Ò! )'),E(";.# &;‚"),E('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),E('$;+.ƒ &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A/Œ#0‰*;+.ƒ &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A&&&#'),E("$;y0#*;y&"),E('%3’""5#7Ó/q#24""6475/b$$;!/&#0#*;!&&&#/L$2J""6J7K/=$$;!/&#0#*;!&&&#/\'$8%:Ô% )(%\'#($\'#(#\'#("\'#&\'#'),E('2Õ""6Õ7Ö'),E('2×""6×7Ø'),E('2Ù""6Ù7Ú'),E('2Û""6Û7Ü'),E('2Ý""6Ý7Þ'),E('2ß""6ß7à'),E('2á""6á7â'),E('2ã""6ã7ä'),E('2å""6å7æ'),E('2ç""6ç7è'),E('2é""6é7ê'),E("%;….Y &;†.S &;ˆ.M &;‰.G &;Š.A &;‹.; &;Œ.5 &;./ &;.) &;Ž.# &;6/& 8!:ë! )"),E("%;„/G#;'/>$;’/5$;'/,$;”/#$+%)(%'#($'#(#'#(\"'#&'#"),E("%;“/' 8!:ì!! )"),E("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),E("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),E("%;¶/Y#$%;A/,#;¶/#$+\")(\"'#&'#06*%;A/,#;¶/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":î" )("\'#&\'#'),E("%;:.c &%;˜/Y#$%;A/,#;˜/#$+\")(\"'#&'#06*%;A/,#;˜/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:ï! )"),E("%;L.# &;™/]#$%;B/,#;›/#$+\")(\"'#&'#06*%;B/,#;›/#$+\")(\"'#&'#&/'$8\":ð\" )(\"'#&'#"),E("%;š.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),E("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:ñ!! )"),E(";œ.) &;.# &; "),E("%3ò\"\"5!7ó/:#;</1$;Ÿ/($8#:ô#! )(#'#(\"'#&'#"),E("%3õ\"\"5'7ö/:#;</1$;ž/($8#:÷#! )(#'#(\"'#&'#"),E("%$;!/&#0#*;!&&&#/' 8!:ø!! )"),E('%2ù""6ù7ú/o#%2J""6J7K/M#;!." &"/?$;!." &"/1$;!." &"/#$+$)($\'#(#\'#("\'#&\'#." &"/\'$8":û" )("\'#&\'#'),E('%;6/J#%;</,#;¡/#$+")("\'#&\'#." &"/)$8":ü""! )("\'#&\'#'),E(";6.) &;T.# &;H"),E("%;£/Y#$%;B/,#;¤/#$+\")(\"'#&'#06*%;B/,#;¤/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E('%3ý""5&7þ.G &3ÿ""5\'7Ā.; &3ā""5$7Ă./ &3ă""5%7Ą.# &;6/& 8!:ą! )'),E(";¥.# &; "),E('%3Ć""5(7ć/M#;</D$3Ĉ""5(7ĉ./ &3Ċ""5(7ċ.# &;6/#$+#)(#\'#("\'#&\'#'),E("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%$;!/&#0#*;!&&&#/' 8!:Č!! )"),E("%;©/& 8!:č! )"),E("%;ª/k#;;/b$;¯/Y$$%;B/,#;°/#$+\")(\"'#&'#06*%;B/,#;°/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),E(";«.# &;¬"),E('3Ď""5$7ď.S &3Đ""5%7đ.G &3Ē""5%7ē.; &3Ĕ""5%7ĕ./ &3Ė""5+7ė.# &;­'),E('3Ę""5\'7ę./ &3Ě""5)7ě.# &;­'),E(";6.# &;®"),E('%3Ĝ""5"7ĝ/,#;6/#$+")("\'#&\'#'),E(";­.# &;6"),E("%;6/5#;</,$;±/#$+#)(#'#(\"'#&'#"),E(";6.# &;H"),E("%;³/5#;./,$;/#$+#)(#'#(\"'#&'#"),E("%$;!/&#0#*;!&&&#/' 8!:Ğ!! )"),E("%;ž/' 8!:ğ!! )"),E('%;¶/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ġ"!!)("\'#&\'#'),E('%%;7/e#$%2J""6J7K/,#;7/#$+")("\'#&\'#0<*%2J""6J7K/,#;7/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),E("%;L.# &;™/]#$%;B/,#;¸/#$+\")(\"'#&'#06*%;B/,#;¸/#$+\")(\"'#&'#&/'$8\":ġ\" )(\"'#&'#"),E(";¹.# &; "),E("%3Ģ\"\"5#7ģ/:#;</1$;6/($8#:Ĥ#! )(#'#(\"'#&'#"),E("%$;!/&#0#*;!&&&#/' 8!:ĥ!! )"),E("%;ž/' 8!:Ħ!! )"),E("%$;š0#*;š&/x#;@/o$;M/f$;?/]$$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8%:ħ% )(%'#($'#(#'#(\"'#&'#"),E(";¾"),E("%3Ĩ\"\"5&7ĩ/k#;./b$;Á/Y$$%;A/,#;Á/#$+\")(\"'#&'#06*%;A/,#;Á/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#.# &;¿"),E("%;6/k#;./b$;À/Y$$%;A/,#;À/#$+\")(\"'#&'#06*%;A/,#;À/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),E("%;6/;#;</2$;6.# &;H/#$+#)(#'#(\"'#&'#"),E(";Â.G &;Ä.A &;Æ.; &;È.5 &;É./ &;Ê.) &;Ë.# &;À"),E("%3Ī\"\"5%7ī/5#;</,$;Ã/#$+#)(#'#(\"'#&'#"),E("%;I/' 8!:Ĭ!! )"),E("%3ĭ\"\"5&7Į/—#;</Ž$;D/…$;Å/|$$%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#0C*%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#&/,$;E/#$+&)(&'#(%'#($'#(#'#(\"'#&'#"),E(";t.# &;w"),E("%3į\"\"5%7İ/5#;</,$;Ç/#$+#)(#'#(\"'#&'#"),E("%;I/' 8!:ı!! )"),E("%3IJ\"\"5&7ij/:#;</1$;I/($8#:Ĵ#! )(#'#(\"'#&'#"),E('%3ĵ""5%7Ķ/]#;</T$%3ķ""5$7ĸ/& 8!:Ĺ! ).4 &%3ĺ""5%7Ļ/& 8!:ļ! )/#$+#)(#\'#("\'#&\'#'),E('%3Ľ""5)7ľ/R#;</I$3Ŀ""5#7ŀ./ &3Ł""5(7ł.# &;6/($8#:Ń#! )(#\'#("\'#&\'#'),E('%3ń""5#7Ņ/“#;</Š$;D/$%;Ì/e#$%2D""6D7E/,#;Ì/#$+")("\'#&\'#0<*%2D""6D7E/,#;Ì/#$+")("\'#&\'#&/#$+")("\'#&\'#/,$;E/#$+%)(%\'#($\'#(#\'#("\'#&\'#'),E('%3ņ""5(7Ň./ &3ň""5$7ʼn.# &;6/\' 8!:Ŋ!! )'),E("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%;Ï/G#;./>$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),E("%$;!/&#0#*;!&&&#/' 8!:ŋ!! )"),E("%;Ñ/]#$%;A/,#;Ñ/#$+\")(\"'#&'#06*%;A/,#;Ñ/#$+\")(\"'#&'#&/'$8\":Ō\" )(\"'#&'#"),E("%;™/]#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8\":ō\" )(\"'#&'#"),E('%;L.O &;™.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/\'$8":Ŏ" )("\'#&\'#'),E("%;Ô/]#$%;B/,#;Õ/#$+\")(\"'#&'#06*%;B/,#;Õ/#$+\")(\"'#&'#&/'$8\":ŏ\" )(\"'#&'#"),E("%;–/& 8!:Ő! )"),E('%3ő""5(7Œ/:#;</1$;6/($8#:œ#! )(#\'#("\'#&\'#.g &%3Ŕ""5&7ŕ/:#;</1$;6/($8#:Ŗ#! )(#\'#("\'#&\'#.: &%3ŗ""5*7Ř/& 8!:ř! ).# &; '),E('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:Ŝ!! )'),E("%;Ø/Y#$%;A/,#;Ø/#$+\")(\"'#&'#06*%;A/,#;Ø/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%;™/Y#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%$;!/&#0#*;!&&&#/' 8!:ŝ!! )"),E("%;Û/Y#$%;B/,#;Ü/#$+\")(\"'#&'#06*%;B/,#;Ü/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E('%3Ş""5&7ş.; &3Š""5\'7š./ &3Ţ""5*7ţ.# &;6/& 8!:Ť! )'),E("%3ť\"\"5&7Ŧ/:#;</1$;Ý/($8#:ŧ#! )(#'#(\"'#&'#.} &%3õ\"\"5'7ö/:#;</1$;ž/($8#:Ũ#! )(#'#(\"'#&'#.P &%3ũ\"\"5+7Ū/:#;</1$;ž/($8#:ū#! )(#'#(\"'#&'#.# &; "),E('3Ŭ""5+7ŭ.k &3Ů""5)7ů._ &3Ű""5(7ű.S &3Ų""5\'7ų.G &3Ŵ""5&7ŵ.; &3Ŷ""5*7ŷ./ &3Ÿ""5)7Ź.# &;6'),E(';1." &"'),E('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:ź!! )'),E("%;L.# &;™/]#$%;B/,#;á/#$+\")(\"'#&'#06*%;B/,#;á/#$+\")(\"'#&'#&/'$8\":Ż\" )(\"'#&'#"),E(";¹.# &; "),E("%;ã/Y#$%;A/,#;ã/#$+\")(\"'#&'#06*%;A/,#;ã/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),E("%;ê/k#;./b$;í/Y$$%;B/,#;ä/#$+\")(\"'#&'#06*%;B/,#;ä/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),E(";å.; &;æ.5 &;ç./ &;è.) &;é.# &; "),E("%3ż\"\"5#7Ž/:#;</1$;ð/($8#:ž#! )(#'#(\"'#&'#"),E("%3ſ\"\"5%7ƀ/:#;</1$;T/($8#:Ɓ#! )(#'#(\"'#&'#"),E("%3Ƃ\"\"5(7ƃ/F#;</=$;\\.) &;Y.# &;X/($8#:Ƅ#! )(#'#(\"'#&'#"),E("%3ƅ\"\"5&7Ɔ/:#;</1$;6/($8#:Ƈ#! )(#'#(\"'#&'#"),E("%3ƈ\"\"5%7Ɖ/A#;</8$$;!0#*;!&/($8#:Ɗ#! )(#'#(\"'#&'#"),E("%;ë/G#;;/>$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#(\"'#&'#"),E('%3’""5#7Ó.# &;6/\' 8!:Ƌ!! )'),E('%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/\' 8!:Ɛ!! )'),E('%;î/D#%;C/,#;ï/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),E("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),E('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:ƒ!! )'),E('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:Ɠ!! )'),E(";¾"),E('%;ž/^#$%;B/,#;ó/#$+")("\'#&\'#06*%;B/,#;ó/#$+")("\'#&\'#&/($8":Ɣ"!!)("\'#&\'#'),E(";ô.# &; "),E('%2ƕ""6ƕ7Ɩ/L#;</C$2Ɨ""6Ɨ7Ƙ.) &2ƙ""6ƙ7ƚ/($8#:ƛ#! )(#\'#("\'#&\'#'),E('%;ž/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ɯ"!!)("\'#&\'#'),E("%;6/5#;0/,$;÷/#$+#)(#'#(\"'#&'#"),E("$;2.) &;4.# &;.0/*;2.) &;4.# &;.&"),E("$;%0#*;%&"),E("%;ú/;#28\"\"6879/,$;û/#$+#)(#'#(\"'#&'#"),E('%3Ɲ""5%7ƞ.) &3Ɵ""5$7Ơ/\' 8!:ơ!! )'),E('%;ü/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),E("%;\\.) &;X.# &;‚/' 8!:Ƣ!! )"),E(';".S &;!.M &2F""6F7G.A &2J""6J7K.5 &2H""6H7I.) &2N""6N7O'),E('2L""6L7M.• &2B""6B7C.‰ &2<""6<7=.} &2R""6R7S.q &2T""6T7U.e &2V""6V7W.Y &2P""6P7Q.M &2@""6@7A.A &2D""6D7E.5 &22""6273.) &2>""6>7?'),E('%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),E('%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/\' 8!:ơ!! )'),E('%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/\' 8!:Ʃ!! )'),E("%;Ą/‡#2F\"\"6F7G/x$;ă/o$2F\"\"6F7G/`$;ă/W$2F\"\"6F7G/H$;ă/?$2F\"\"6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),E("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),E("%;ă/,#;ă/#$+\")(\"'#&'#"),E("%;ă/5#;ă/,$;ă/#$+#)(#'#(\"'#&'#"),E("%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),E('%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("\'#&\'#0<*%;B/2#;ĉ.# &; /#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),E(";™.# &;L"),E("%2Ư\"\"6Ư7ư/5#;</,$;Ċ/#$+#)(#'#(\"'#&'#"),E("%;D/S#;,/J$2:\"\"6:7;/;$;,.# &;T/,$;E/#$+%)(%'#($'#(#'#(\"'#&'#")],h=0,d=0,p=[{line:1,column:1}],g=0,f=[],m=0;if(void 0!==t.startRule){if(!(t.startRule in a))throw new Error("Can't start parsing from rule \""+t.startRule+'".');c=a[t.startRule]}function v(){return e.substring(d,h)}function y(){return w(d,h)}function b(e,t){return{type:"literal",text:e,ignoreCase:t}}function S(e,t,n){return{type:"class",parts:e,inverted:t,ignoreCase:n}}function T(t){var n,r=p[t];if(r)return r;for(n=t-1;!p[n];)n--;for(r={line:(r=p[n]).line,column:r.column};n<t;)10===e.charCodeAt(n)?(r.line++,r.column=1):r.column++,n++;return p[t]=r,r}function w(e,t){var n=T(e),r=T(t);return{start:{offset:e,line:n.line,column:n.column},end:{offset:t,line:r.line,column:r.column}}}function R(e){h<g||(h>g&&(g=h,f=[]),f.push(e))}function E(e){return e.split("").map(function(e){return e.charCodeAt(0)-32})}if(t.data={},n=function t(n){for(var r,i=l[n],s=0,a=[],c=i.length,p=[],g=[];;){for(;s<c;)switch(i[s]){case 0:g.push(u[i[s+1]]),s+=2;break;case 1:g.push(void 0),s++;break;case 2:g.push(null),s++;break;case 3:g.push(o),s++;break;case 4:g.push([]),s++;break;case 5:g.push(h),s++;break;case 6:g.pop(),s++;break;case 7:h=g.pop(),s++;break;case 8:g.length-=i[s+1],s+=2;break;case 9:g.splice(-2,1),s++;break;case 10:g[g.length-2].push(g.pop()),s++;break;case 11:g.push(g.splice(g.length-i[s+1],i[s+1])),s+=2;break;case 12:g.push(e.substring(g.pop(),h)),s++;break;case 13:p.push(c),a.push(s+3+i[s+1]+i[s+2]),g[g.length-1]?(c=s+3+i[s+1],s+=3):(c=s+3+i[s+1]+i[s+2],s+=3+i[s+1]);break;case 14:p.push(c),a.push(s+3+i[s+1]+i[s+2]),g[g.length-1]===o?(c=s+3+i[s+1],s+=3):(c=s+3+i[s+1]+i[s+2],s+=3+i[s+1]);break;case 15:p.push(c),a.push(s+3+i[s+1]+i[s+2]),g[g.length-1]!==o?(c=s+3+i[s+1],s+=3):(c=s+3+i[s+1]+i[s+2],s+=3+i[s+1]);break;case 16:g[g.length-1]!==o?(p.push(c),a.push(s),c=s+2+i[s+1],s+=2):s+=2+i[s+1];break;case 17:p.push(c),a.push(s+3+i[s+1]+i[s+2]),e.length>h?(c=s+3+i[s+1],s+=3):(c=s+3+i[s+1]+i[s+2],s+=3+i[s+1]);break;case 18:p.push(c),a.push(s+4+i[s+2]+i[s+3]),e.substr(h,u[i[s+1]].length)===u[i[s+1]]?(c=s+4+i[s+2],s+=4):(c=s+4+i[s+2]+i[s+3],s+=4+i[s+2]);break;case 19:p.push(c),a.push(s+4+i[s+2]+i[s+3]),e.substr(h,u[i[s+1]].length).toLowerCase()===u[i[s+1]]?(c=s+4+i[s+2],s+=4):(c=s+4+i[s+2]+i[s+3],s+=4+i[s+2]);break;case 20:p.push(c),a.push(s+4+i[s+2]+i[s+3]),u[i[s+1]].test(e.charAt(h))?(c=s+4+i[s+2],s+=4):(c=s+4+i[s+2]+i[s+3],s+=4+i[s+2]);break;case 21:g.push(e.substr(h,i[s+1])),h+=i[s+1],s+=2;break;case 22:g.push(u[i[s+1]]),h+=u[i[s+1]].length,s+=2;break;case 23:g.push(o),0===m&&R(u[i[s+1]]),s+=2;break;case 24:d=g[g.length-1-i[s+1]],s+=2;break;case 25:d=h,s++;break;case 26:r=i.slice(s+4,s+4+i[s+3]).map(function(e){return g[g.length-1-e]}),g.splice(g.length-i[s+2],i[s+2],u[i[s+1]].apply(null,r)),s+=4+i[s+3];break;case 27:g.push(t(i[s+1])),s+=2;break;case 28:m++,s++;break;case 29:m--,s++;break;default:throw new Error("Invalid opcode: "+i[s]+".")}if(!(p.length>0))break;c=p.pop(),s=a.pop()}return g[0]}(c),n!==o&&h===e.length)return n;throw n!==o&&h<e.length&&R({type:"end"}),r=f,i=g<e.length?e.charAt(g):null,s=g<e.length?w(g,g+1):w(g,g),new SyntaxError(SyntaxError.buildMessage(r,i),r,i,s)}var parse=peg$parse,Grammar,C;!function(e){e.parse=function(e,t){var n={startRule:t};try{parse(e,n)}catch(e){n.data=-1}return n.data},e.nameAddrHeaderParse=function(t){var n=e.parse(t,"Name_Addr_Header");return-1!==n?n:void 0},e.URIParse=function(t){var n=e.parse(t,"SIP_URI");return-1!==n?n:void 0}}(Grammar||(Grammar={})),function(e){e.ACK="ACK",e.BYE="BYE",e.CANCEL="CANCEL",e.INFO="INFO",e.INVITE="INVITE",e.MESSAGE="MESSAGE",e.NOTIFY="NOTIFY",e.OPTIONS="OPTIONS",e.REGISTER="REGISTER",e.UPDATE="UPDATE",e.SUBSCRIBE="SUBSCRIBE",e.PUBLISH="PUBLISH",e.REFER="REFER",e.PRACK="PRACK"}(C||(C={}));var REASON_PHRASE={100:"Trying",180:"Ringing",181:"Call Is Being Forwarded",182:"Queued",183:"Session Progress",199:"Early Dialog Terminated",200:"OK",202:"Accepted",204:"No Notification",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",305:"Use Proxy",380:"Alternative Service",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",410:"Gone",412:"Conditional Request Failed",413:"Request Entity Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Unsupported URI Scheme",417:"Unknown Resource-Priority",420:"Bad Extension",421:"Extension Required",422:"Session Interval Too Small",423:"Interval Too Brief",428:"Use Identity Header",429:"Provide Referrer Identity",430:"Flow Failed",433:"Anonymity Disallowed",436:"Bad Identity-Info",437:"Unsupported Certificate",438:"Invalid Identity Header",439:"First Hop Lacks Outbound Support",440:"Max-Breadth Exceeded",469:"Bad Info Package",470:"Consent Needed",478:"Unresolvable Destination",480:"Temporarily Unavailable",481:"Call/Transaction Does Not Exist",482:"Loop Detected",483:"Too Many Hops",484:"Address Incomplete",485:"Ambiguous",486:"Busy Here",487:"Request Terminated",488:"Not Acceptable Here",489:"Bad Event",491:"Request Pending",493:"Undecipherable",494:"Security Agreement Required",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Server Time-out",505:"Version Not Supported",513:"Message Too Large",580:"Precondition Failure",600:"Busy Everywhere",603:"Decline",604:"Does Not Exist Anywhere",606:"Not Acceptable"};function createRandomToken(e,t){void 0===t&&(t=32);for(var n="",r=0;r<e;r++){n+=Math.floor(Math.random()*t).toString(t)}return n}function getReasonPhrase(e){return REASON_PHRASE[e]||""}function newTag(){return createRandomToken(10)}function headerize(e){for(var t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},n=e.toLowerCase().replace(/_/g,"-").split("-"),r=n.length,i="",s=0;s<r;s++)0!==s&&(i+="-"),i+=n[s].charAt(0).toUpperCase()+n[s].substring(1);return t[i]&&(i=t[i]),i}function utf8Length(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length}var IncomingMessage=function(){function e(){this.headers={}}return e.prototype.addHeader=function(e,t){var n={raw:t};e=headerize(e),this.headers[e]?this.headers[e].push(n):this.headers[e]=[n]},e.prototype.getHeader=function(e){var t=this.headers[headerize(e)];if(t)return t[0]?t[0].raw:void 0},e.prototype.getHeaders=function(e){var t=this.headers[headerize(e)],n=[];if(!t)return[];for(var r=0,i=t;r<i.length;r++){var s=i[r];n.push(s.raw)}return n},e.prototype.hasHeader=function(e){return!!this.headers[headerize(e)]},e.prototype.parseHeader=function(e,t){if(void 0===t&&(t=0),e=headerize(e),this.headers[e]&&!(t>=this.headers[e].length)){var n=this.headers[e][t],r=n.raw;if(n.parsed)return n.parsed;var i=Grammar.parse(r,e.replace(/-/g,"_"));return-1===i?void this.headers[e].splice(t,1):(n.parsed=i,i)}},e.prototype.s=function(e,t){return void 0===t&&(t=0),this.parseHeader(e,t)},e.prototype.setHeader=function(e,t){this.headers[headerize(e)]=[{raw:t}]},e.prototype.toString=function(){return this.data},e}(),IncomingRequestMessage=function(e){function t(){return e.call(this)||this}return __extends$1(t,e),t}(IncomingMessage),IncomingResponseMessage=function(e){function t(){return e.call(this)||this}return __extends$1(t,e),t}(IncomingMessage),OutgoingRequestMessage=function(){function e(t,n,r,i,s,o,a){this.headers={},this.extraHeaders=[],this.options=e.getDefaultOptions(),s&&(this.options=__assign(__assign({},this.options),s),this.options.optionTags&&this.options.optionTags.length&&(this.options.optionTags=this.options.optionTags.slice()),this.options.routeSet&&this.options.routeSet.length&&(this.options.routeSet=this.options.routeSet.slice())),o&&o.length&&(this.extraHeaders=o.slice()),a&&(this.body={body:a.content,contentType:a.contentType}),this.method=t,this.ruri=n.clone(),this.fromURI=r.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:newTag(),this.from=e.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=i.clone(),this.toTag=this.options.toTag,this.to=e.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+createRandomToken(15),this.cseq=this.options.cseq,this.setHeader("route",this.options.routeSet),this.setHeader("via",""),this.setHeader("to",this.to.toString()),this.setHeader("from",this.from.toString()),this.setHeader("cseq",this.cseq+" "+this.method),this.setHeader("call-id",this.callId),this.setHeader("max-forwards","70")}return e.getDefaultOptions=function(){return{callId:"",callIdPrefix:"",cseq:1,toDisplayName:"",toTag:"",fromDisplayName:"",fromTag:"",forceRport:!1,hackViaTcp:!1,optionTags:["outbound"],routeSet:[],userAgentString:"sip.js",viaHost:""}},e.makeNameAddrHeader=function(e,t,n){var r={};return n&&(r.tag=n),new NameAddrHeader(e,t,r)},e.prototype.getHeader=function(e){var t=this.headers[headerize(e)];if(t){if(t[0])return t[0]}else for(var n=new RegExp("^\\s*"+e+"\\s*:","i"),r=0,i=this.extraHeaders;r<i.length;r++){var s=i[r];if(n.test(s))return s.substring(s.indexOf(":")+1).trim()}},e.prototype.getHeaders=function(e){var t=[],n=this.headers[headerize(e)];if(n)for(var r=0,i=n;r<i.length;r++){var s=i[r];t.push(s)}else for(var o=new RegExp("^\\s*"+e+"\\s*:","i"),a=0,c=this.extraHeaders;a<c.length;a++){var u=c[a];o.test(u)&&t.push(u.substring(u.indexOf(":")+1).trim())}return t},e.prototype.hasHeader=function(e){if(this.headers[headerize(e)])return!0;for(var t=new RegExp("^\\s*"+e+"\\s*:","i"),n=0,r=this.extraHeaders;n<r.length;n++){var i=r[n];if(t.test(i))return!0}return!1},e.prototype.setHeader=function(e,t){this.headers[headerize(e)]=t instanceof Array?t:[t]},e.prototype.setViaHeader=function(e,t){this.options.hackViaTcp&&(t="TCP");var n="SIP/2.0/"+t;n+=" "+this.options.viaHost+";branch="+e,this.options.forceRport&&(n+=";rport"),this.setHeader("via",n),this.branch=e},e.prototype.toString=function(){var e="";for(var t in e+=this.method+" "+this.ruri.toRaw()+" SIP/2.0\r\n",this.headers)if(this.headers[t])for(var n=0,r=this.headers[t];n<r.length;n++){e+=t+": "+r[n]+"\r\n"}for(var i=0,s=this.extraHeaders;i<s.length;i++){e+=(t=s[i]).trim()+"\r\n"}return e+="Supported: "+this.options.optionTags.join(", ")+"\r\n",e+="User-Agent: "+this.options.userAgentString+"\r\n",this.body?"string"==typeof this.body?(e+="Content-Length: "+utf8Length(this.body)+"\r\n\r\n",e+=this.body):this.body.body&&this.body.contentType?(e+="Content-Type: "+this.body.contentType+"\r\n",e+="Content-Length: "+utf8Length(this.body.body)+"\r\n\r\n",e+=this.body.body):e+="Content-Length: 0\r\n\r\n":e+="Content-Length: 0\r\n\r\n",e},e}();function contentTypeToContentDisposition(e){return"application/sdp"===e?"session":"render"}function fromBodyLegacy(e){var t="string"==typeof e?e:e.body,n="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:contentTypeToContentDisposition(n),contentType:n,content:t}}function isBody(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function getBody(e){var t,n,r,i;e instanceof IncomingRequestMessage&&(e.body&&(t=(i=e.parseHeader("Content-Disposition"))?i.type:void 0,n=e.parseHeader("Content-Type"),r=e.body));e instanceof IncomingResponseMessage&&(e.body&&(t=(i=e.parseHeader("Content-Disposition"))?i.type:void 0,n=e.parseHeader("Content-Type"),r=e.body));if(e instanceof OutgoingRequestMessage&&e.body)if(t=e.getHeader("Content-Disposition"),n=e.getHeader("Content-Type"),"string"==typeof e.body){if(!n)throw new Error("Header content type header does not equal body content type.");r=e.body}else{if(n&&n!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");n=e.body.contentType,r=e.body.body}if(isBody(e)&&(t=e.contentDisposition,n=e.contentType,r=e.content),r){if(n&&!t&&(t=contentTypeToContentDisposition(n)),!t)throw new Error("Content disposition undefined.");if(!n)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:n,content:r}}}var Md5=function(){function e(){this._dataLength=0,this._bufferLength=0,this._state=new Int32Array(4),this._buffer=new ArrayBuffer(68),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}return e.hashStr=function(e,t){return void 0===t&&(t=!1),this.onePassHasher.start().appendStr(e).end(t)},e.hashAsciiStr=function(e,t){return void 0===t&&(t=!1),this.onePassHasher.start().appendAsciiStr(e).end(t)},e._hex=function(t){var n,r,i,s,o=e.hexChars,a=e.hexOut;for(s=0;s<4;s+=1)for(r=8*s,n=t[s],i=0;i<8;i+=2)a[r+1+i]=o.charAt(15&n),n>>>=4,a[r+0+i]=o.charAt(15&n),n>>>=4;return a.join("")},e._md5cycle=function(e,t){var n=e[0],r=e[1],i=e[2],s=e[3];r=((r+=((i=((i+=((s=((s+=((n=((n+=(r&i|~r&s)+t[0]-680876936|0)<<7|n>>>25)+r|0)&r|~n&i)+t[1]-389564586|0)<<12|s>>>20)+n|0)&n|~s&r)+t[2]+606105819|0)<<17|i>>>15)+s|0)&s|~i&n)+t[3]-1044525330|0)<<22|r>>>10)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r&i|~r&s)+t[4]-176418897|0)<<7|n>>>25)+r|0)&r|~n&i)+t[5]+1200080426|0)<<12|s>>>20)+n|0)&n|~s&r)+t[6]-1473231341|0)<<17|i>>>15)+s|0)&s|~i&n)+t[7]-45705983|0)<<22|r>>>10)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r&i|~r&s)+t[8]+1770035416|0)<<7|n>>>25)+r|0)&r|~n&i)+t[9]-1958414417|0)<<12|s>>>20)+n|0)&n|~s&r)+t[10]-42063|0)<<17|i>>>15)+s|0)&s|~i&n)+t[11]-1990404162|0)<<22|r>>>10)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r&i|~r&s)+t[12]+1804603682|0)<<7|n>>>25)+r|0)&r|~n&i)+t[13]-40341101|0)<<12|s>>>20)+n|0)&n|~s&r)+t[14]-1502002290|0)<<17|i>>>15)+s|0)&s|~i&n)+t[15]+1236535329|0)<<22|r>>>10)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r&s|i&~s)+t[1]-165796510|0)<<5|n>>>27)+r|0)&i|r&~i)+t[6]-1069501632|0)<<9|s>>>23)+n|0)&r|n&~r)+t[11]+643717713|0)<<14|i>>>18)+s|0)&n|s&~n)+t[0]-373897302|0)<<20|r>>>12)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r&s|i&~s)+t[5]-701558691|0)<<5|n>>>27)+r|0)&i|r&~i)+t[10]+38016083|0)<<9|s>>>23)+n|0)&r|n&~r)+t[15]-660478335|0)<<14|i>>>18)+s|0)&n|s&~n)+t[4]-405537848|0)<<20|r>>>12)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r&s|i&~s)+t[9]+568446438|0)<<5|n>>>27)+r|0)&i|r&~i)+t[14]-1019803690|0)<<9|s>>>23)+n|0)&r|n&~r)+t[3]-187363961|0)<<14|i>>>18)+s|0)&n|s&~n)+t[8]+1163531501|0)<<20|r>>>12)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r&s|i&~s)+t[13]-1444681467|0)<<5|n>>>27)+r|0)&i|r&~i)+t[2]-51403784|0)<<9|s>>>23)+n|0)&r|n&~r)+t[7]+1735328473|0)<<14|i>>>18)+s|0)&n|s&~n)+t[12]-1926607734|0)<<20|r>>>12)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r^i^s)+t[5]-378558|0)<<4|n>>>28)+r|0)^r^i)+t[8]-2022574463|0)<<11|s>>>21)+n|0)^n^r)+t[11]+1839030562|0)<<16|i>>>16)+s|0)^s^n)+t[14]-35309556|0)<<23|r>>>9)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r^i^s)+t[1]-1530992060|0)<<4|n>>>28)+r|0)^r^i)+t[4]+1272893353|0)<<11|s>>>21)+n|0)^n^r)+t[7]-155497632|0)<<16|i>>>16)+s|0)^s^n)+t[10]-1094730640|0)<<23|r>>>9)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r^i^s)+t[13]+681279174|0)<<4|n>>>28)+r|0)^r^i)+t[0]-358537222|0)<<11|s>>>21)+n|0)^n^r)+t[3]-722521979|0)<<16|i>>>16)+s|0)^s^n)+t[6]+76029189|0)<<23|r>>>9)+i|0,r=((r+=((i=((i+=((s=((s+=((n=((n+=(r^i^s)+t[9]-640364487|0)<<4|n>>>28)+r|0)^r^i)+t[12]-421815835|0)<<11|s>>>21)+n|0)^n^r)+t[15]+530742520|0)<<16|i>>>16)+s|0)^s^n)+t[2]-995338651|0)<<23|r>>>9)+i|0,r=((r+=((s=((s+=(r^((n=((n+=(i^(r|~s))+t[0]-198630844|0)<<6|n>>>26)+r|0)|~i))+t[7]+1126891415|0)<<10|s>>>22)+n|0)^((i=((i+=(n^(s|~r))+t[14]-1416354905|0)<<15|i>>>17)+s|0)|~n))+t[5]-57434055|0)<<21|r>>>11)+i|0,r=((r+=((s=((s+=(r^((n=((n+=(i^(r|~s))+t[12]+1700485571|0)<<6|n>>>26)+r|0)|~i))+t[3]-1894986606|0)<<10|s>>>22)+n|0)^((i=((i+=(n^(s|~r))+t[10]-1051523|0)<<15|i>>>17)+s|0)|~n))+t[1]-2054922799|0)<<21|r>>>11)+i|0,r=((r+=((s=((s+=(r^((n=((n+=(i^(r|~s))+t[8]+1873313359|0)<<6|n>>>26)+r|0)|~i))+t[15]-30611744|0)<<10|s>>>22)+n|0)^((i=((i+=(n^(s|~r))+t[6]-1560198380|0)<<15|i>>>17)+s|0)|~n))+t[13]+1309151649|0)<<21|r>>>11)+i|0,r=((r+=((s=((s+=(r^((n=((n+=(i^(r|~s))+t[4]-145523070|0)<<6|n>>>26)+r|0)|~i))+t[11]-1120210379|0)<<10|s>>>22)+n|0)^((i=((i+=(n^(s|~r))+t[2]+718787259|0)<<15|i>>>17)+s|0)|~n))+t[9]-343485551|0)<<21|r>>>11)+i|0,e[0]=n+e[0]|0,e[1]=r+e[1]|0,e[2]=i+e[2]|0,e[3]=s+e[3]|0},e.prototype.start=function(){return this._dataLength=0,this._bufferLength=0,this._state.set(e.stateIdentity),this},e.prototype.appendStr=function(t){var n,r,i=this._buffer8,s=this._buffer32,o=this._bufferLength;for(r=0;r<t.length;r+=1){if((n=t.charCodeAt(r))<128)i[o++]=n;else if(n<2048)i[o++]=(n>>>6)+192,i[o++]=63&n|128;else if(n<55296||n>56319)i[o++]=(n>>>12)+224,i[o++]=n>>>6&63|128,i[o++]=63&n|128;else{if((n=1024*(n-55296)+(t.charCodeAt(++r)-56320)+65536)>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");i[o++]=(n>>>18)+240,i[o++]=n>>>12&63|128,i[o++]=n>>>6&63|128,i[o++]=63&n|128}o>=64&&(this._dataLength+=64,e._md5cycle(this._state,s),o-=64,s[0]=s[16])}return this._bufferLength=o,this},e.prototype.appendAsciiStr=function(t){for(var n,r=this._buffer8,i=this._buffer32,s=this._bufferLength,o=0;;){for(n=Math.min(t.length-o,64-s);n--;)r[s++]=t.charCodeAt(o++);if(s<64)break;this._dataLength+=64,e._md5cycle(this._state,i),s=0}return this._bufferLength=s,this},e.prototype.appendByteArray=function(t){for(var n,r=this._buffer8,i=this._buffer32,s=this._bufferLength,o=0;;){for(n=Math.min(t.length-o,64-s);n--;)r[s++]=t[o++];if(s<64)break;this._dataLength+=64,e._md5cycle(this._state,i),s=0}return this._bufferLength=s,this},e.prototype.getState=function(){var e=this,t=e._state;return{buffer:String.fromCharCode.apply(null,e._buffer8),buflen:e._bufferLength,length:e._dataLength,state:[t[0],t[1],t[2],t[3]]}},e.prototype.setState=function(e){var t,n=e.buffer,r=e.state,i=this._state;for(this._dataLength=e.length,this._bufferLength=e.buflen,i[0]=r[0],i[1]=r[1],i[2]=r[2],i[3]=r[3],t=0;t<n.length;t+=1)this._buffer8[t]=n.charCodeAt(t)},e.prototype.end=function(t){void 0===t&&(t=!1);var n,r=this._bufferLength,i=this._buffer8,s=this._buffer32,o=1+(r>>2);if(this._dataLength+=r,i[r]=128,i[r+1]=i[r+2]=i[r+3]=0,s.set(e.buffer32Identity.subarray(o),o),r>55&&(e._md5cycle(this._state,s),s.set(e.buffer32Identity)),(n=8*this._dataLength)<=4294967295)s[14]=n;else{var a=n.toString(16).match(/(.*?)(.{0,8})$/);if(null===a)return;var c=parseInt(a[2],16),u=parseInt(a[1],16)||0;s[14]=c,s[15]=u}return e._md5cycle(this._state,s),t?this._state:e._hex(this._state)},e.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),e.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),e.hexChars="0123456789abcdef",e.hexOut=[],e.onePassHasher=new e,e}();function MD5(e){return Md5.hashStr(e)}"5d41402abc4b2a76b9719d911017c592"!==Md5.hashStr("hello")&&console.error("Md5 self test failed.");var DigestAuthentication=function(){function e(e,t,n,r){this.logger=e.getLogger("sipjs.digestauthentication"),this.username=n,this.password=r,this.ha1=t,this.nc=0,this.ncHex="00000000"}return e.prototype.authenticate=function(e,t,n){if(this.algorithm=t.algorithm,this.realm=t.realm,this.nonce=t.nonce,this.opaque=t.opaque,this.stale=t.stale,this.algorithm){if("MD5"!==this.algorithm)return this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"),!1}else this.algorithm="MD5";if(!this.realm)return this.logger.warn("challenge without Digest realm, authentication aborted"),!1;if(!this.nonce)return this.logger.warn("challenge without Digest nonce, authentication aborted"),!1;if(t.qop)if(t.qop.indexOf("auth")>-1)this.qop="auth";else{if(!(t.qop.indexOf("auth-int")>-1))return this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"),!1;this.qop="auth-int"}else this.qop=void 0;return this.method=e.method,this.uri=e.ruri,this.cnonce=createRandomToken(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(n),!0},e.prototype.toString=function(){var e=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return e.push("algorithm="+this.algorithm),e.push('username="'+this.username+'"'),e.push('realm="'+this.realm+'"'),e.push('nonce="'+this.nonce+'"'),e.push('uri="'+this.uri+'"'),e.push('response="'+this.response+'"'),this.opaque&&e.push('opaque="'+this.opaque+'"'),this.qop&&(e.push("qop="+this.qop),e.push('cnonce="'+this.cnonce+'"'),e.push("nc="+this.ncHex)),"Digest "+e.join(", ")},e.prototype.updateNcHex=function(){var e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e},e.prototype.calculateResponse=function(e){var t,n;""!==(t=this.ha1)&&void 0!==t||(t=MD5(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(n=MD5(this.method+":"+this.uri),this.response=MD5(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+n)):"auth-int"===this.qop?(n=MD5(this.method+":"+this.uri+":"+MD5(e||"")),this.response=MD5(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+n)):void 0===this.qop&&(n=MD5(this.method+":"+this.uri),this.response=MD5(t+":"+this.nonce+":"+n))},e}(),Parser;function constructOutgoingResponse(e,t){var n="\r\n";if(t.statusCode<100||t.statusCode>699)throw new TypeError("Invalid statusCode: "+t.statusCode);var r=t.reasonPhrase?t.reasonPhrase:getReasonPhrase(t.statusCode),i="SIP/2.0 "+t.statusCode+" "+r+n;t.statusCode>=100&&t.statusCode,t.statusCode;var s="From: "+e.getHeader("From")+n,o="Call-ID: "+e.callId+n,a="CSeq: "+e.cseq+" "+e.method+n,c=e.getHeaders("via").reduce(function(e,t){return e+"Via: "+t+n},""),u="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){var l=t.toTag;l||(l=newTag()),u+=";tag="+l}u+=n;var h="";t.supported&&(h="Supported: "+t.supported.join(", ")+n);var d="";t.userAgent&&(d="User-Agent: "+t.userAgent+n);var p="";return t.extraHeaders&&(p=t.extraHeaders.reduce(function(e,t){return e+t.trim()+n},"")),i+=c,i+=s,i+=u,i+=a,i+=o,i+=h,i+=d,i+=p,t.body?(i+="Content-Type: "+t.body.contentType+n,i+="Content-Length: "+utf8Length(t.body.content)+n+n,i+=t.body.content):i+="Content-Length: 0\r\n\r\n",{message:i}}!function(e){function t(e,t){var n=t,r=0,i=0;if(e.substring(n,n+2).match(/(^\r\n)/))return-2;for(;0===r;){if(-1===(i=e.indexOf("\r\n",n)))return i;!e.substring(i+2,i+4).match(/(^\r\n)/)&&e.charAt(i+2).match(/(^\s+)/)?n=i+2:r=i}return r}function n(e,t,n,r){var i,s=t.indexOf(":",n),o=t.substring(n,s).trim(),a=t.substring(s+1,r).trim();switch(o.toLowerCase()){case"via":case"v":e.addHeader("via",a),1===e.getHeaders("via").length?(i=e.parseHeader("Via"))&&(e.via=i,e.viaBranch=i.branch):i=0;break;case"from":case"f":e.setHeader("from",a),(i=e.parseHeader("from"))&&(e.from=i,e.fromTag=i.getParam("tag"));break;case"to":case"t":e.setHeader("to",a),(i=e.parseHeader("to"))&&(e.to=i,e.toTag=i.getParam("tag"));break;case"record-route":if(-1===(i=Grammar.parse(a,"Record_Route"))){i=void 0;break}if(!(i instanceof Array)){i=void 0;break}i.forEach(function(t){e.addHeader("record-route",a.substring(t.position,t.offset)),e.headers["Record-Route"][e.getHeaders("record-route").length-1].parsed=t.parsed});break;case"call-id":case"i":e.setHeader("call-id",a),(i=e.parseHeader("call-id"))&&(e.callId=a);break;case"contact":case"m":if(-1===(i=Grammar.parse(a,"Contact"))){i=void 0;break}if(!(i instanceof Array)){i=void 0;break}i.forEach(function(t){e.addHeader("contact",a.substring(t.position,t.offset)),e.headers.Contact[e.getHeaders("contact").length-1].parsed=t.parsed});break;case"content-length":case"l":e.setHeader("content-length",a),i=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",a),i=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",a),(i=e.parseHeader("cseq"))&&(e.cseq=i.value),e instanceof IncomingResponseMessage&&(e.method=i.method);break;case"max-forwards":e.setHeader("max-forwards",a),i=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",a),i=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",a),i=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",a),(i=e.parseHeader("refer-to"))&&(e.referTo=i);break;default:e.addHeader(o.toLowerCase(),a),i=0}return void 0!==i||{error:"error parsing header '"+o+"'"}}e.getHeader=t,e.parseHeader=n,e.parseMessage=function(e,r){var i=0,s=e.indexOf("\r\n");if(-1!==s){var o,a=e.substring(0,s),c=Grammar.parse(a,"Request_Response");if(-1!==c){var u;for(c.status_code?((o=new IncomingResponseMessage).statusCode=c.status_code,o.reasonPhrase=c.reason_phrase):((o=new IncomingRequestMessage).method=c.method,o.ruri=c.uri),o.data=e,i=s+2;;){if(-2===(s=t(e,i))){u=i+2;break}if(-1===s)return void r.error("malformed message");var l=n(o,e,i,s);if(l&&!0!==l)return void r.error(l.error);i=s+2}return o.hasHeader("content-length")?o.body=e.substr(u,Number(o.getHeader("content-length"))):o.body=e.substring(u),o}r.warn('error parsing first line of SIP message: "'+a+'"')}else r.warn("no CRLF found, not a SIP message, discarded")}}(Parser||(Parser={}));var Dialog=function(){function e(e,t){this.core=e,this.dialogState=t,this.core.dialogs.set(this.id,this)}return e.initialDialogStateForUserAgentClient=function(e,t){var n=t.getHeaders("record-route").reverse(),r=t.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");var i=r.uri,s=e.cseq,o=e.callId,a=e.fromTag,c=t.toTag;if(!o)throw new Error("Call id undefined.");if(!a)throw new Error("From tag undefined.");if(!c)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");var u=e.from.uri,l=e.to.uri;if(!t.statusCode)throw new Error("Incoming response status code undefined.");return{id:o+a+c,early:t.statusCode<200,callId:o,localTag:a,remoteTag:c,localSequenceNumber:s,remoteSequenceNumber:undefined,localURI:u,remoteURI:l,remoteTarget:i,routeSet:n,secure:!1}},e.initialDialogStateForUserAgentServer=function(e,t,n){void 0===n&&(n=!1);var r=e.getHeaders("record-route"),i=e.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");var s=i.uri,o=e.cseq,a=e.callId,c=t,u=e.fromTag,l=e.from.uri;return{id:a+c+u,early:n,callId:a,localTag:c,remoteTag:u,localSequenceNumber:undefined,remoteSequenceNumber:o,localURI:e.to.uri,remoteURI:l,remoteTarget:s,routeSet:r,secure:!1}},e.prototype.dispose=function(){this.core.dialogs.delete(this.id)},Object.defineProperty(e.prototype,"id",{get:function(){return this.dialogState.id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"early",{get:function(){return this.dialogState.early},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"callId",{get:function(){return this.dialogState.callId},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localTag",{get:function(){return this.dialogState.localTag},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteTag",{get:function(){return this.dialogState.remoteTag},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localSequenceNumber",{get:function(){return this.dialogState.localSequenceNumber},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteSequenceNumber",{get:function(){return this.dialogState.remoteSequenceNumber},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localURI",{get:function(){return this.dialogState.localURI},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteURI",{get:function(){return this.dialogState.remoteURI},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteTarget",{get:function(){return this.dialogState.remoteTarget},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"routeSet",{get:function(){return this.dialogState.routeSet},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"secure",{get:function(){return this.dialogState.secure},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"userAgentCore",{get:function(){return this.core},enumerable:!1,configurable:!0}),e.prototype.confirm=function(){this.dialogState.early=!1},e.prototype.receiveRequest=function(e){if(e.method!==C.ACK){if(this.remoteSequenceNumber){if(e.cseq<=this.remoteSequenceNumber)throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?");this.dialogState.remoteSequenceNumber=e.cseq}this.remoteSequenceNumber||(this.dialogState.remoteSequenceNumber=e.cseq)}},e.prototype.recomputeRouteSet=function(e){this.dialogState.routeSet=e.getHeaders("record-route").reverse()},e.prototype.createOutgoingRequestMessage=function(e,t){var n,r=this.remoteURI,i=this.remoteTag,s=this.localURI,o=this.localTag,a=this.callId;n=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;var c=this.remoteTarget,u=this.routeSet,l=t&&t.extraHeaders,h=t&&t.body;return this.userAgentCore.makeOutgoingRequestMessage(e,c,s,r,{callId:a,cseq:n,fromTag:o,toTag:i,routeSet:u},l,h)},e.prototype.incrementLocalSequenceNumber=function(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1},e.prototype.sequenceGuard=function(e){return e.method===C.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))},e}(),SessionState$1,SignalingState;!function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(SessionState$1||(SessionState$1={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(SignalingState||(SignalingState={}));var T1=500,T2=4e3,T4=5e3,Timers={T1:T1,T2:T2,T4:T4,TIMER_B:64*T1,TIMER_D:0*T1,TIMER_F:6*T1,TIMER_H:64*T1,TIMER_I:0*T4,TIMER_J:0*T1,TIMER_K:0*T4,TIMER_L:64*T1,TIMER_M:64*T1,TIMER_N:64*T1,PROVISIONAL_RESPONSE_INTERVAL:6e4},Exception=function(e){function t(t){var n=this.constructor,r=e.call(this,t)||this;return Object.setPrototypeOf(r,n.prototype),r}return __extends$1(t,e),t}(Error),TransactionStateError=function(e){function t(t){return e.call(this,t||"Transaction state error.")||this}return __extends$1(t,e),t}(Exception),TransportError=function(e){function t(t){return e.call(this,t||"Unspecified transport error.")||this}return __extends$1(t,e),t}(Exception),Transaction=function(){function e(e,t,n,r,i){this._transport=e,this._user=t,this._id=n,this._state=r,this.listeners=new Array,this.logger=t.loggerFactory.getLogger(i,n),this.logger.debug("Constructing ".concat(this.typeToString()," with id ").concat(this.id,"."))}return e.prototype.dispose=function(){this.logger.debug("Destroyed ".concat(this.typeToString()," with id ").concat(this.id,"."))},Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"kind",{get:function(){throw new Error("Invalid kind.")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transport",{get:function(){return this._transport},enumerable:!1,configurable:!0}),e.prototype.addStateChangeListener=function(e,t){var n=this,r=function(){n.removeStateChangeListener(r),e()};!0===(null==t?void 0:t.once)?this.listeners.push(r):this.listeners.push(e)},e.prototype.notifyStateChangeListeners=function(){this.listeners.slice().forEach(function(e){return e()})},e.prototype.removeStateChangeListener=function(e){this.listeners=this.listeners.filter(function(t){return t!==e})},e.prototype.logTransportError=function(e,t){this.logger.error(e.message),this.logger.error("Transport error occurred in ".concat(this.typeToString()," with id ").concat(this.id,".")),this.logger.error(t)},e.prototype.send=function(e){var t=this;return this.transport.send(e).catch(function(e){if(e instanceof TransportError)throw t.onTransportError(e),e;var n;throw n=e&&"string"==typeof e.message?new TransportError(e.message):new TransportError,t.onTransportError(n),n})},e.prototype.setState=function(e){this.logger.debug('State change to "'.concat(e,'" on ').concat(this.typeToString()," with id ").concat(this.id,".")),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.notifyStateChangeListeners()},e.prototype.typeToString=function(){return"UnknownType"},e}(),ClientTransaction=function(e){function t(n,r,i,s,o){var a=e.call(this,r,i,t.makeId(n),s,o)||this;return a._request=n,a.user=i,n.setViaHeader(a.id,r.protocol),a}return __extends$1(t,e),t.makeId=function(e){if("CANCEL"===e.method){if(!e.branch)throw new Error("Outgoing CANCEL request without a branch.");return e.branch}return"z9hG4bK"+Math.floor(1e7*Math.random())},Object.defineProperty(t.prototype,"request",{get:function(){return this._request},enumerable:!1,configurable:!0}),t.prototype.onRequestTimeout=function(){this.user.onRequestTimeout&&this.user.onRequestTimeout()},t}(Transaction),TransactionState;!function(e){e.Accepted="Accepted",e.Calling="Calling",e.Completed="Completed",e.Confirmed="Confirmed",e.Proceeding="Proceeding",e.Terminated="Terminated",e.Trying="Trying"}(TransactionState||(TransactionState={}));var InviteClientTransaction=function(e){function t(t,n,r){var i=e.call(this,t,n,r,TransactionState.Calling,"sip.transaction.ict")||this;return i.ackRetransmissionCache=new Map,i.B=setTimeout(function(){return i.timerB()},Timers.TIMER_B),i.send(t.toString()).catch(function(e){i.logTransportError(e,"Failed to send initial outgoing request.")}),i}return __extends$1(t,e),t.prototype.dispose=function(){this.B&&(clearTimeout(this.B),this.B=void 0),this.D&&(clearTimeout(this.D),this.D=void 0),this.M&&(clearTimeout(this.M),this.M=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"ict"},enumerable:!1,configurable:!0}),t.prototype.ackResponse=function(e){var t=this,n=e.toTag;if(!n)throw new Error("To tag undefined.");var r="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(r,this.transport.protocol),this.ackRetransmissionCache.set(n,e),this.send(e.toString()).catch(function(e){t.logTransportError(e,"Failed to send ACK to 2xx response.")})},t.prototype.receiveResponse=function(e){var t=this,n=e.statusCode;if(!n||n<100||n>699)throw new Error("Invalid status code ".concat(n));switch(this.state){case TransactionState.Calling:if(n>=100&&n<=199)return this.stateTransition(TransactionState.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(n>=200&&n<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(TransactionState.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(n>=300&&n<=699)return this.stateTransition(TransactionState.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case TransactionState.Proceeding:if(n>=100&&n<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(n>=200&&n<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(TransactionState.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(n>=300&&n<=699)return this.stateTransition(TransactionState.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case TransactionState.Accepted:if(n>=200&&n<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));var r=this.ackRetransmissionCache.get(e.toTag);return r?void this.send(r.toString()).catch(function(e){t.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")}):void 0}break;case TransactionState.Completed:if(n>=300&&n<=699)return void this.ack(e);break;case TransactionState.Terminated:break;default:throw new Error("Invalid state ".concat(this.state))}var i="Received unexpected ".concat(n," response while in state ").concat(this.state,".");this.logger.warn(i)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"INVITE client transaction"},t.prototype.ack=function(e){var t=this,n=this.request.ruri,r=this.request.callId,i=this.request.cseq,s=this.request.getHeader("from"),o=e.getHeader("to"),a=this.request.getHeader("via"),c=this.request.getHeader("route");if(!s)throw new Error("From undefined.");if(!o)throw new Error("To undefined.");if(!a)throw new Error("Via undefined.");var u="ACK ".concat(n," SIP/2.0\r\n");c&&(u+="Route: ".concat(c,"\r\n")),u+="Via: ".concat(a,"\r\n"),u+="To: ".concat(o,"\r\n"),u+="From: ".concat(s,"\r\n"),u+="Call-ID: ".concat(r,"\r\n"),u+="CSeq: ".concat(i," ACK\r\n"),u+="Max-Forwards: 70\r\n",u+="Content-Length: 0\r\n\r\n",this.send(u).catch(function(e){t.logTransportError(e,"Failed to send ACK to non-2xx response.")})},t.prototype.stateTransition=function(e,t){var n=this;void 0===t&&(t=!1);var r=function(){throw new Error("Invalid state transition from ".concat(n.state," to ").concat(e))};switch(e){case TransactionState.Calling:r();break;case TransactionState.Proceeding:this.state!==TransactionState.Calling&&r();break;case TransactionState.Accepted:case TransactionState.Completed:this.state!==TransactionState.Calling&&this.state!==TransactionState.Proceeding&&r();break;case TransactionState.Terminated:this.state!==TransactionState.Calling&&this.state!==TransactionState.Accepted&&this.state!==TransactionState.Completed&&(t||r());break;default:r()}this.B&&(clearTimeout(this.B),this.B=void 0),TransactionState.Proceeding,e===TransactionState.Completed&&(this.D=setTimeout(function(){return n.timerD()},Timers.TIMER_D)),e===TransactionState.Accepted&&(this.M=setTimeout(function(){return n.timerM()},Timers.TIMER_M)),e===TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timerA=function(){},t.prototype.timerB=function(){this.logger.debug("Timer B expired for INVITE client transaction ".concat(this.id,".")),this.state===TransactionState.Calling&&(this.onRequestTimeout(),this.stateTransition(TransactionState.Terminated))},t.prototype.timerD=function(){this.logger.debug("Timer D expired for INVITE client transaction ".concat(this.id,".")),this.state===TransactionState.Completed&&this.stateTransition(TransactionState.Terminated)},t.prototype.timerM=function(){this.logger.debug("Timer M expired for INVITE client transaction ".concat(this.id,".")),this.state===TransactionState.Accepted&&this.stateTransition(TransactionState.Terminated)},t}(ClientTransaction),ServerTransaction=function(e){function t(t,n,r,i,s){var o=e.call(this,n,r,t.viaBranch,i,s)||this;return o._request=t,o.user=r,o}return __extends$1(t,e),Object.defineProperty(t.prototype,"request",{get:function(){return this._request},enumerable:!1,configurable:!0}),t}(Transaction),InviteServerTransaction=function(e){function t(t,n,r){return e.call(this,t,n,r,TransactionState.Proceeding,"sip.transaction.ist")||this}return __extends$1(t,e),t.prototype.dispose=function(){this.stopProgressExtensionTimer(),this.H&&(clearTimeout(this.H),this.H=void 0),this.I&&(clearTimeout(this.I),this.I=void 0),this.L&&(clearTimeout(this.L),this.L=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"ist"},enumerable:!1,configurable:!0}),t.prototype.receiveRequest=function(e){var t=this;switch(this.state){case TransactionState.Proceeding:if(e.method===C.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(function(e){t.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case TransactionState.Accepted:if(e.method===C.INVITE)return;break;case TransactionState.Completed:if(e.method===C.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch(function(e){t.logTransportError(e,"Failed to send retransmission of final response.")})}if(e.method===C.ACK)return void this.stateTransition(TransactionState.Confirmed);break;case TransactionState.Confirmed:case TransactionState.Terminated:if(e.method===C.INVITE||e.method===C.ACK)return;break;default:throw new Error("Invalid state ".concat(this.state))}var n="INVITE server transaction received unexpected ".concat(e.method," request while in state ").concat(this.state,".");this.logger.warn(n)},t.prototype.receiveResponse=function(e,t){var n=this;if(e<100||e>699)throw new Error("Invalid status code ".concat(e));switch(this.state){case TransactionState.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch(function(e){n.logTransportError(e,"Failed to send 1xx response.")});if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(TransactionState.Accepted),void this.send(t).catch(function(e){n.logTransportError(e,"Failed to send 2xx response.")});if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(TransactionState.Completed),void this.send(t).catch(function(e){n.logTransportError(e,"Failed to send non-2xx final response.")});break;case TransactionState.Accepted:if(e>=200&&e<=299)return void this.send(t).catch(function(e){n.logTransportError(e,"Failed to send 2xx response.")});break;case TransactionState.Completed:case TransactionState.Confirmed:case TransactionState.Terminated:break;default:throw new Error("Invalid state ".concat(this.state))}var r="INVITE server transaction received unexpected ".concat(e," response from TU while in state ").concat(this.state,".");throw this.logger.error(r),new Error(r)},t.prototype.retransmitAcceptedResponse=function(){var e=this;this.state===TransactionState.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch(function(t){e.logTransportError(t,"Failed to send 2xx response.")})},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e)},t.prototype.typeToString=function(){return"INVITE server transaction"},t.prototype.stateTransition=function(e){var t=this,n=function(){throw new Error("Invalid state transition from ".concat(t.state," to ").concat(e))};switch(e){case TransactionState.Proceeding:n();break;case TransactionState.Accepted:case TransactionState.Completed:this.state!==TransactionState.Proceeding&&n();break;case TransactionState.Confirmed:this.state!==TransactionState.Completed&&n();break;case TransactionState.Terminated:this.state!==TransactionState.Accepted&&this.state!==TransactionState.Completed&&this.state!==TransactionState.Confirmed&&n();break;default:n()}this.stopProgressExtensionTimer(),e===TransactionState.Accepted&&(this.L=setTimeout(function(){return t.timerL()},Timers.TIMER_L)),e===TransactionState.Completed&&(this.H=setTimeout(function(){return t.timerH()},Timers.TIMER_H)),e===TransactionState.Confirmed&&(this.I=setTimeout(function(){return t.timerI()},Timers.TIMER_I)),e===TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.startProgressExtensionTimer=function(){var e=this;void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval(function(){if(e.logger.debug("Progress extension timer expired for INVITE server transaction ".concat(e.id,".")),!e.lastProvisionalResponse)throw new Error("Last provisional response undefined.");e.send(e.lastProvisionalResponse).catch(function(t){e.logTransportError(t,"Failed to send retransmission of provisional response.")})},Timers.PROVISIONAL_RESPONSE_INTERVAL))},t.prototype.stopProgressExtensionTimer=function(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)},t.prototype.timerG=function(){},t.prototype.timerH=function(){this.logger.debug("Timer H expired for INVITE server transaction ".concat(this.id,".")),this.state===TransactionState.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(TransactionState.Terminated))},t.prototype.timerI=function(){this.logger.debug("Timer I expired for INVITE server transaction ".concat(this.id,".")),this.stateTransition(TransactionState.Terminated)},t.prototype.timerL=function(){this.logger.debug("Timer L expired for INVITE server transaction ".concat(this.id,".")),this.state===TransactionState.Accepted&&this.stateTransition(TransactionState.Terminated)},t}(ServerTransaction),NonInviteClientTransaction=function(e){function t(t,n,r){var i=e.call(this,t,n,r,TransactionState.Trying,"sip.transaction.nict")||this;return i.F=setTimeout(function(){return i.timerF()},Timers.TIMER_F),i.send(t.toString()).catch(function(e){i.logTransportError(e,"Failed to send initial outgoing request.")}),i}return __extends$1(t,e),t.prototype.dispose=function(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"nict"},enumerable:!1,configurable:!0}),t.prototype.receiveResponse=function(e){var t=e.statusCode;if(!t||t<100||t>699)throw new Error("Invalid status code ".concat(t));switch(this.state){case TransactionState.Trying:if(t>=100&&t<=199)return this.stateTransition(TransactionState.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(TransactionState.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case TransactionState.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(TransactionState.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case TransactionState.Completed:case TransactionState.Terminated:return;default:throw new Error("Invalid state ".concat(this.state))}var n="Non-INVITE client transaction received unexpected ".concat(t," response while in state ").concat(this.state,".");this.logger.warn(n)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"non-INVITE client transaction"},t.prototype.stateTransition=function(e,t){var n=this;void 0===t&&(t=!1);var r=function(){throw new Error("Invalid state transition from ".concat(n.state," to ").concat(e))};switch(e){case TransactionState.Trying:r();break;case TransactionState.Proceeding:this.state!==TransactionState.Trying&&r();break;case TransactionState.Completed:this.state!==TransactionState.Trying&&this.state!==TransactionState.Proceeding&&r();break;case TransactionState.Terminated:this.state!==TransactionState.Trying&&this.state!==TransactionState.Proceeding&&this.state!==TransactionState.Completed&&(t||r());break;default:r()}e===TransactionState.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(function(){return n.timerK()},Timers.TIMER_K)),e===TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timerF=function(){this.logger.debug("Timer F expired for non-INVITE client transaction ".concat(this.id,".")),this.state!==TransactionState.Trying&&this.state!==TransactionState.Proceeding||(this.onRequestTimeout(),this.stateTransition(TransactionState.Terminated))},t.prototype.timerK=function(){this.state===TransactionState.Completed&&this.stateTransition(TransactionState.Terminated)},t}(ClientTransaction),NonInviteServerTransaction=function(e){function t(t,n,r){return e.call(this,t,n,r,TransactionState.Trying,"sip.transaction.nist")||this}return __extends$1(t,e),t.prototype.dispose=function(){this.J&&(clearTimeout(this.J),this.J=void 0),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"kind",{get:function(){return"nist"},enumerable:!1,configurable:!0}),t.prototype.receiveRequest=function(e){var t=this;switch(this.state){case TransactionState.Trying:break;case TransactionState.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(function(e){t.logTransportError(e,"Failed to send retransmission of provisional response.")});break;case TransactionState.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(function(e){t.logTransportError(e,"Failed to send retransmission of final response.")});break;case TransactionState.Terminated:break;default:throw new Error("Invalid state ".concat(this.state))}},t.prototype.receiveResponse=function(e,t){var n=this;if(e<100||e>699)throw new Error("Invalid status code ".concat(e));if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case TransactionState.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(TransactionState.Proceeding),void this.send(t).catch(function(e){n.logTransportError(e,"Failed to send provisional response.")});if(e>=200&&e<=699)return this.stateTransition(TransactionState.Completed),void this.send(t).catch(function(e){n.logTransportError(e,"Failed to send final response.")});break;case TransactionState.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(TransactionState.Completed),void this.send(t).catch(function(e){n.logTransportError(e,"Failed to send final response.")});break;case TransactionState.Completed:return;case TransactionState.Terminated:break;default:throw new Error("Invalid state ".concat(this.state))}var r="Non-INVITE server transaction received unexpected ".concat(e," response from TU while in state ").concat(this.state,".");throw this.logger.error(r),new Error(r)},t.prototype.onTransportError=function(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(TransactionState.Terminated,!0)},t.prototype.typeToString=function(){return"non-INVITE server transaction"},t.prototype.stateTransition=function(e,t){var n=this;void 0===t&&(t=!1);var r=function(){throw new Error("Invalid state transition from ".concat(n.state," to ").concat(e))};switch(e){case TransactionState.Trying:r();break;case TransactionState.Proceeding:this.state!==TransactionState.Trying&&r();break;case TransactionState.Completed:this.state!==TransactionState.Trying&&this.state!==TransactionState.Proceeding&&r();break;case TransactionState.Terminated:this.state!==TransactionState.Proceeding&&this.state!==TransactionState.Completed&&(t||r());break;default:r()}e===TransactionState.Completed&&(this.J=setTimeout(function(){return n.timerJ()},Timers.TIMER_J)),e===TransactionState.Terminated&&this.dispose(),this.setState(e)},t.prototype.timerJ=function(){this.logger.debug("Timer J expired for NON-INVITE server transaction ".concat(this.id,".")),this.state===TransactionState.Completed&&this.stateTransition(TransactionState.Terminated)},t}(ServerTransaction),UserAgentClient=function(){function e(e,t,n,r){this.transactionConstructor=e,this.core=t,this.message=n,this.delegate=r,this.challenged=!1,this.stale=!1,this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}return e.prototype.dispose=function(){this.transaction.dispose()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.core.loggerFactory},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transaction",{get:function(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction},enumerable:!1,configurable:!0}),e.prototype.cancel=function(t,n){var r=this;if(void 0===n&&(n={}),!this.transaction)throw new Error("Transaction undefined.");if(!this.message.to)throw new Error("To undefined.");if(!this.message.from)throw new Error("From undefined.");var i=this.core.makeOutgoingRequestMessage(C.CANCEL,this.message.ruri,this.message.from.uri,this.message.to.uri,{toTag:this.message.toTag,fromTag:this.message.fromTag,callId:this.message.callId,cseq:this.message.cseq},n.extraHeaders);return i.branch=this.message.branch,this.message.headers.Route&&(i.headers.Route=this.message.headers.Route),t&&i.setHeader("Reason",t),this.transaction.state===TransactionState.Proceeding?new e(NonInviteClientTransaction,this.core,i):this.transaction.addStateChangeListener(function(){r.transaction&&r.transaction.state===TransactionState.Proceeding&&new e(NonInviteClientTransaction,r.core,i)},{once:!0}),i},e.prototype.authenticationGuard=function(e,t){var n,r,i=e.statusCode;if(!i)throw new Error("Response status code undefined.");if(401!==i&&407!==i)return!0;if(401===i?(n=e.parseHeader("www-authenticate"),r="authorization"):(n=e.parseHeader("proxy-authenticate"),r="proxy-authorization"),!n)return this.logger.warn(i+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==n.stale))return this.logger.warn(i+" apparently in authentication loop, cannot authenticate"),!0;if(!this.credentials&&(this.credentials=this.core.configuration.authenticationFactory(),!this.credentials))return this.logger.warn("Unable to obtain credentials, cannot authenticate"),!0;if(!this.credentials.authenticate(this.message,n))return!0;this.challenged=!0,n.stale&&(this.stale=!0);var s=this.message.cseq+=1;return t&&t.localSequenceNumber&&(t.incrementLocalSequenceNumber(),s=this.message.cseq=t.localSequenceNumber),this.message.setHeader("cseq",s+" "+this.message.method),this.message.setHeader(r,this.credentials.toString()),this.init(),!1},e.prototype.onRequestTimeout=function(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");var e=new IncomingResponseMessage;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)},e.prototype.onTransportError=function(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");var t=new IncomingResponseMessage;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)},e.prototype.receiveResponse=function(e){if(this.authenticationGuard(e)){var t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e});break;case/^2[0-9]{2}$/.test(t):this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e});break;case/^3[0-9]{2}$/.test(t):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error("Invalid status code ".concat(t))}}},e.prototype.init=function(){var e=this,t={loggerFactory:this.loggerFactory,onRequestTimeout:function(){return e.onRequestTimeout()},onStateChange:function(t){t===TransactionState.Terminated&&(e.core.userAgentClients.delete(r),n===e._transaction&&e.dispose())},onTransportError:function(t){return e.onTransportError(t)},receiveResponse:function(t){return e.receiveResponse(t)}},n=new this.transactionConstructor(this.message,this.core.transport,t);this._transaction=n;var r=n.id+n.request.method;this.core.userAgentClients.set(r,this)},e}(),ByeUserAgentClient=function(e){function t(t,n,r){var i,s=t.createOutgoingRequestMessage(C.BYE,r);return i=e.call(this,NonInviteClientTransaction,t.userAgentCore,s,n)||this,t.dispose(),i}return __extends$1(t,e),t}(UserAgentClient),UserAgentServer=function(){function e(e,t,n,r){this.transactionConstructor=e,this.core=t,this.message=n,this.delegate=r,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=n.toTag?n.toTag:newTag(),this.init()}return e.prototype.dispose=function(){this.transaction.dispose()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.core.loggerFactory},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transaction",{get:function(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){if(void 0===e&&(e={statusCode:200}),!this.acceptable)throw new TransactionStateError("".concat(this.message.method," not acceptable in state ").concat(this.transaction.state,"."));var t=e.statusCode;if(t<200||t>299)throw new TypeError("Invalid statusCode: ".concat(t));return this.reply(e)},e.prototype.progress=function(e){if(void 0===e&&(e={statusCode:180}),!this.progressable)throw new TransactionStateError("".concat(this.message.method," not progressable in state ").concat(this.transaction.state,"."));var t=e.statusCode;if(t<101||t>199)throw new TypeError("Invalid statusCode: ".concat(t));return this.reply(e)},e.prototype.redirect=function(e,t){if(void 0===t&&(t={statusCode:302}),!this.redirectable)throw new TransactionStateError("".concat(this.message.method," not redirectable in state ").concat(this.transaction.state,"."));var n=t.statusCode;if(n<300||n>399)throw new TypeError("Invalid statusCode: ".concat(n));var r=new Array;return e.forEach(function(e){return r.push("Contact: ".concat(e.toString()))}),t.extraHeaders=(t.extraHeaders||[]).concat(r),this.reply(t)},e.prototype.reject=function(e){if(void 0===e&&(e={statusCode:480}),!this.rejectable)throw new TransactionStateError("".concat(this.message.method," not rejectable in state ").concat(this.transaction.state,"."));var t=e.statusCode;if(t<400||t>699)throw new TypeError("Invalid statusCode: ".concat(t));return this.reply(e)},e.prototype.trying=function(e){if(!this.tryingable)throw new TransactionStateError("".concat(this.message.method," not tryingable in state ").concat(this.transaction.state,"."));return this.reply({statusCode:100})},e.prototype.receiveCancel=function(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)},Object.defineProperty(e.prototype,"acceptable",{get:function(){if(this.transaction instanceof InviteServerTransaction)return this.transaction.state===TransactionState.Proceeding||this.transaction.state===TransactionState.Accepted;if(this.transaction instanceof NonInviteServerTransaction)return this.transaction.state===TransactionState.Trying||this.transaction.state===TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"progressable",{get:function(){if(this.transaction instanceof InviteServerTransaction)return this.transaction.state===TransactionState.Proceeding;if(this.transaction instanceof NonInviteServerTransaction)return!1;throw new Error("Unknown transaction type.")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"redirectable",{get:function(){if(this.transaction instanceof InviteServerTransaction)return this.transaction.state===TransactionState.Proceeding;if(this.transaction instanceof NonInviteServerTransaction)return this.transaction.state===TransactionState.Trying||this.transaction.state===TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"rejectable",{get:function(){if(this.transaction instanceof InviteServerTransaction)return this.transaction.state===TransactionState.Proceeding;if(this.transaction instanceof NonInviteServerTransaction)return this.transaction.state===TransactionState.Trying||this.transaction.state===TransactionState.Proceeding;throw new Error("Unknown transaction type.")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"tryingable",{get:function(){if(this.transaction instanceof InviteServerTransaction)return this.transaction.state===TransactionState.Proceeding;if(this.transaction instanceof NonInviteServerTransaction)return this.transaction.state===TransactionState.Trying;throw new Error("Unknown transaction type.")},enumerable:!1,configurable:!0}),e.prototype.reply=function(e){e.toTag||100===e.statusCode||(e.toTag=this.toTag),e.userAgent=e.userAgent||this.core.configuration.userAgentHeaderFieldValue,e.supported=e.supported||this.core.configuration.supportedOptionTagsResponse;var t=constructOutgoingResponse(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t},e.prototype.init=function(){var e=this,t={loggerFactory:this.loggerFactory,onStateChange:function(t){t===TransactionState.Terminated&&(e.core.userAgentServers.delete(r),e.dispose())},onTransportError:function(t){e.logger.error(t.message),e.delegate&&e.delegate.onTransportError?e.delegate.onTransportError(t):e.logger.error("User agent server response transport error.")}},n=new this.transactionConstructor(this.message,this.core.transport,t);this._transaction=n;var r=n.id;this.core.userAgentServers.set(n.id,this)},e}(),ByeUserAgentServer=function(e){function t(t,n,r){return e.call(this,NonInviteServerTransaction,t.userAgentCore,n,r)||this}return __extends$1(t,e),t}(UserAgentServer),InfoUserAgentClient=function(e){function t(t,n,r){var i=t.createOutgoingRequestMessage(C.INFO,r);return e.call(this,NonInviteClientTransaction,t.userAgentCore,i,n)||this}return __extends$1(t,e),t}(UserAgentClient),InfoUserAgentServer=function(e){function t(t,n,r){return e.call(this,NonInviteServerTransaction,t.userAgentCore,n,r)||this}return __extends$1(t,e),t}(UserAgentServer),MessageUserAgentClient=function(e){function t(t,n,r){return e.call(this,NonInviteClientTransaction,t,n,r)||this}return __extends$1(t,e),t}(UserAgentClient),MessageUserAgentServer=function(e){function t(t,n,r){return e.call(this,NonInviteServerTransaction,t,n,r)||this}return __extends$1(t,e),t}(UserAgentServer),NotifyUserAgentClient=function(e){function t(t,n,r){var i=t.createOutgoingRequestMessage(C.NOTIFY,r);return e.call(this,NonInviteClientTransaction,t.userAgentCore,i,n)||this}return __extends$1(t,e),t}(UserAgentClient);function instanceOfDialog(e){return void 0!==e.userAgentCore}var NotifyUserAgentServer=function(e){function t(t,n,r){var i=instanceOfDialog(t)?t.userAgentCore:t;return e.call(this,NonInviteServerTransaction,i,n,r)||this}return __extends$1(t,e),t}(UserAgentServer),PrackUserAgentClient=function(e){function t(t,n,r){var i,s=t.createOutgoingRequestMessage(C.PRACK,r);return i=e.call(this,NonInviteClientTransaction,t.userAgentCore,s,n)||this,t.signalingStateTransition(s),i}return __extends$1(t,e),t}(UserAgentClient),PrackUserAgentServer=function(e){function t(t,n,r){var i=e.call(this,NonInviteServerTransaction,t.userAgentCore,n,r)||this;return t.signalingStateTransition(n),i.dialog=t,i}return __extends$1(t,e),t.prototype.accept=function(t){return void 0===t&&(t={statusCode:200}),t.body&&this.dialog.signalingStateTransition(t.body),e.prototype.accept.call(this,t)},t}(UserAgentServer),ReInviteUserAgentClient=function(e){function t(t,n,r){var i=this,s=t.createOutgoingRequestMessage(C.INVITE,r);return(i=e.call(this,InviteClientTransaction,t.userAgentCore,s,n)||this).delegate=n,t.signalingStateTransition(s),t.reinviteUserAgentClient=i,i.dialog=t,i}return __extends$1(t,e),t.prototype.receiveResponse=function(e){var t=this;if(this.authenticationGuard(e,this.dialog)){var n=e.statusCode?e.statusCode.toString():"";if(!n)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(n):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(n):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:this.dialog,prack:function(e){throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(n):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:function(e){return t.dialog.ack(e)}});break;case/^3[0-9]{2}$/.test(n):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(n):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error("Invalid status code ".concat(n))}}},t}(UserAgentClient),ReInviteUserAgentServer=function(e){function t(t,n,r){var i=e.call(this,InviteServerTransaction,t.userAgentCore,n,r)||this;return t.reinviteUserAgentServer=i,i.dialog=t,i}return __extends$1(t,e),t.prototype.accept=function(t){void 0===t&&(t={statusCode:200}),t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(this.dialog.routeSet.map(function(e){return"Record-Route: ".concat(e)}));var n=e.prototype.accept.call(this,t),r=this.dialog,i=__assign(__assign({},n),{session:r});return t.body&&this.dialog.signalingStateTransition(t.body),this.dialog.reConfirm(),i},t.prototype.progress=function(t){void 0===t&&(t={statusCode:180});var n=e.prototype.progress.call(this,t),r=this.dialog,i=__assign(__assign({},n),{session:r});return t.body&&this.dialog.signalingStateTransition(t.body),i},t.prototype.redirect=function(e,t){throw this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")},t.prototype.reject=function(t){return void 0===t&&(t={statusCode:488}),this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,e.prototype.reject.call(this,t)},t}(UserAgentServer),ReferUserAgentClient=function(e){function t(t,n,r){var i=t.createOutgoingRequestMessage(C.REFER,r);return e.call(this,NonInviteClientTransaction,t.userAgentCore,i,n)||this}return __extends$1(t,e),t}(UserAgentClient);function instanceOfSessionDialog(e){return void 0!==e.userAgentCore}var ReferUserAgentServer=function(e){function t(t,n,r){var i=instanceOfSessionDialog(t)?t.userAgentCore:t;return e.call(this,NonInviteServerTransaction,i,n,r)||this}return __extends$1(t,e),t}(UserAgentServer),SessionDialog=function(e){function t(t,n,r,i){var s=e.call(this,n,r)||this;return s.initialTransaction=t,s._signalingState=SignalingState.Initial,s.ackWait=!1,s.ackProcessing=!1,s.delegate=i,t instanceof InviteServerTransaction&&(s.ackWait=!0),s.early||s.start2xxRetransmissionTimer(),s.signalingStateTransition(t.request),s.logger=n.loggerFactory.getLogger("sip.invite-dialog"),s.logger.log("INVITE dialog ".concat(s.id," constructed")),s}return __extends$1(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._signalingState=SignalingState.Closed,this._offer=void 0,this._answer=void 0,this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.logger.log("INVITE dialog ".concat(this.id," destroyed"))},Object.defineProperty(t.prototype,"sessionState",{get:function(){return this.early?SessionState$1.Early:this.ackWait?SessionState$1.AckWait:this._signalingState===SignalingState.Closed?SessionState$1.Terminated:SessionState$1.Confirmed},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"signalingState",{get:function(){return this._signalingState},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"offer",{get:function(){return this._offer},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"answer",{get:function(){return this._answer},enumerable:!1,configurable:!0}),t.prototype.confirm=function(){this.early&&this.start2xxRetransmissionTimer(),e.prototype.confirm.call(this)},t.prototype.reConfirm=function(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()},t.prototype.ack=function(e){var t;if(void 0===e&&(e={}),this.logger.log("INVITE dialog ".concat(this.id," sending ACK request")),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof InviteClientTransaction))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}var n=this.createOutgoingRequestMessage(C.ACK,{cseq:t.request.cseq,extraHeaders:e.extraHeaders,body:e.body});return t.ackResponse(n),this.signalingStateTransition(n),{message:n}},t.prototype.bye=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending BYE request")),this.initialTransaction instanceof InviteServerTransaction){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==TransactionState.Terminated)throw new Error("UAS MUST NOT send a BYE on a confirmed dialog until it has received an ACK for its 2xx response or until the server transaction times out.")}return new ByeUserAgentClient(this,e,t)},t.prototype.info=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending INFO request")),this.early)throw new Error("Dialog not confirmed.");return new InfoUserAgentClient(this,e,t)},t.prototype.invite=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending INVITE request")),this.early)throw new Error("Dialog not confirmed.");if(this.reinviteUserAgentClient)throw new Error("There is an ongoing re-INVITE client transaction.");if(this.reinviteUserAgentServer)throw new Error("There is an ongoing re-INVITE server transaction.");return new ReInviteUserAgentClient(this,e,t)},t.prototype.message=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending MESSAGE request")),this.early)throw new Error("Dialog not confirmed.");var n=this.createOutgoingRequestMessage(C.MESSAGE,t);return new MessageUserAgentClient(this.core,n,e)},t.prototype.notify=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending NOTIFY request")),this.early)throw new Error("Dialog not confirmed.");return new NotifyUserAgentClient(this,e,t)},t.prototype.prack=function(e,t){return this.logger.log("INVITE dialog ".concat(this.id," sending PRACK request")),new PrackUserAgentClient(this,e,t)},t.prototype.refer=function(e,t){if(this.logger.log("INVITE dialog ".concat(this.id," sending REFER request")),this.early)throw new Error("Dialog not confirmed.");return new ReferUserAgentClient(this,e,t)},t.prototype.receiveRequest=function(t){var n=this;if(this.logger.log("INVITE dialog ".concat(this.id," received ").concat(t.method," request")),t.method!==C.ACK)if(this.sequenceGuard(t)){if(e.prototype.receiveRequest.call(this,t),t.method===C.INVITE){var r=function(){var e=n.ackWait?"waiting for initial ACK":"processing initial ACK";n.logger.warn("INVITE dialog ".concat(n.id," received re-INVITE while ").concat(e));n.logger.warn("RFC 5407 suggests the following to avoid this race condition... Note: Implementation issues are outside the scope of this document, but the following tip is provided for avoiding race conditions of this type. The caller can delay sending re-INVITE F6 for some period of time (2 seconds, perhaps), after which the caller can reasonably assume that its ACK has been received. Implementors can decouple the actions of the user (e.g., pressing the hold button) from the actions of the protocol (the sending of re-INVITE F6), so that the UA can behave like this. In this case, it is the implementor's choice as to how long to wait. In most cases, such an implementation may be useful to prevent the type of race condition shown in this section. This document expresses no preference about whether or not they should wait for an ACK to be delivered. After considering the impact on user experience, implementors should decide whether or not to wait for a while, because the user experience depends on the implementation and has no direct bearing on protocol behavior.")},i=Math.floor(10*Math.random())+1,s=["Retry-After: ".concat(i)];if(this.ackProcessing)return this.core.replyStateless(t,{statusCode:500,extraHeaders:s}),void r();if(this.ackWait&&this.signalingState!==SignalingState.Stable)return this.core.replyStateless(t,{statusCode:500,extraHeaders:s}),void r();if(this.reinviteUserAgentServer)return void this.core.replyStateless(t,{statusCode:500,extraHeaders:s});if(this.reinviteUserAgentClient)return void this.core.replyStateless(t,{statusCode:491})}if(t.method===C.INVITE){var o=t.parseHeader("contact");if(!o)throw new Error("Contact undefined.");if(!(o instanceof NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=o.uri}switch(t.method){case C.BYE:var a=new ByeUserAgentServer(this,t);this.delegate&&this.delegate.onBye?this.delegate.onBye(a):a.accept(),this.dispose();break;case C.INFO:a=new InfoUserAgentServer(this,t);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(a):a.reject({statusCode:469,extraHeaders:["Recv-Info:"]});break;case C.INVITE:a=new ReInviteUserAgentServer(this,t);this.signalingStateTransition(t),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(a):a.reject({statusCode:488});break;case C.MESSAGE:a=new MessageUserAgentServer(this.core,t);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(a):a.accept();break;case C.NOTIFY:a=new NotifyUserAgentServer(this,t);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(a):a.accept();break;case C.PRACK:a=new PrackUserAgentServer(this,t);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(a):a.accept();break;case C.REFER:a=new ReferUserAgentServer(this,t);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(a):a.reject();break;default:this.logger.log("INVITE dialog ".concat(this.id," received unimplemented ").concat(t.method," request")),this.core.replyStateless(t,{statusCode:501})}}else this.logger.log("INVITE dialog ".concat(this.id," rejected out of order ").concat(t.method," request."));else{if(this.ackWait){if(this.initialTransaction instanceof InviteClientTransaction)return void this.logger.warn("INVITE dialog ".concat(this.id," received unexpected ").concat(t.method," request, dropping."));if(this.initialTransaction.request.cseq!==t.cseq)return void this.logger.warn("INVITE dialog ".concat(this.id," received unexpected ").concat(t.method," request, dropping."));this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn("INVITE dialog ".concat(this.id," received unexpected ").concat(t.method," request, dropping."));if(this.reinviteUserAgentServer.transaction.request.cseq!==t.cseq)return void this.logger.warn("INVITE dialog ".concat(this.id," received unexpected ").concat(t.method," request, dropping."));this.reinviteUserAgentServer=void 0}if(this.signalingStateTransition(t),this.delegate&&this.delegate.onAck){var c=this.delegate.onAck({message:t});c instanceof Promise&&(this.ackProcessing=!0,c.then(function(){return n.ackProcessing=!1}).catch(function(){return n.ackProcessing=!1}))}}},t.prototype.reliableSequenceGuard=function(e){var t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){var n=e.getHeader("require"),r=e.getHeader("rseq"),i=n&&n.includes("100rel")&&r?Number(r):void 0;if(i){if(this.rseq&&this.rseq+1!==i)return!1;this.rseq=this.rseq?this.rseq+1:i}}return!0},t.prototype.signalingStateRollback=function(){this._signalingState!==SignalingState.HaveLocalOffer&&this.signalingState!==SignalingState.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=SignalingState.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)},t.prototype.signalingStateTransition=function(e){var t=getBody(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===SignalingState.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof IncomingRequestMessage)switch(this._signalingState){case SignalingState.Initial:case SignalingState.Stable:this._signalingState=SignalingState.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case SignalingState.HaveLocalOffer:this._signalingState=SignalingState.Stable,this._answer=t;break;case SignalingState.HaveRemoteOffer:case SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof IncomingResponseMessage)switch(this._signalingState){case SignalingState.Initial:case SignalingState.Stable:this._signalingState=SignalingState.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case SignalingState.HaveLocalOffer:this._signalingState=SignalingState.Stable,this._answer=t;break;case SignalingState.HaveRemoteOffer:case SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof OutgoingRequestMessage)switch(this._signalingState){case SignalingState.Initial:case SignalingState.Stable:this._signalingState=SignalingState.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case SignalingState.HaveLocalOffer:break;case SignalingState.HaveRemoteOffer:this._signalingState=SignalingState.Stable,this._answer=t;break;case SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}if(isBody(e))switch(this._signalingState){case SignalingState.Initial:case SignalingState.Stable:this._signalingState=SignalingState.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case SignalingState.HaveLocalOffer:break;case SignalingState.HaveRemoteOffer:this._signalingState=SignalingState.Stable,this._answer=t;break;case SignalingState.Closed:break;default:throw new Error("Unexpected signaling state.")}}},t.prototype.start2xxRetransmissionTimer=function(){var e=this;if(this.initialTransaction instanceof InviteServerTransaction){var t=this.initialTransaction,n=Timers.T1,r=function(){e.ackWait?(e.logger.log("No ACK for 2xx response received, attempting retransmission"),t.retransmitAcceptedResponse(),n=Math.min(2*n,Timers.T2),e.invite2xxTimer=setTimeout(r,n)):e.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(r,n);var i=function(){t.state===TransactionState.Terminated&&(t.removeStateChangeListener(i),e.invite2xxTimer&&(clearTimeout(e.invite2xxTimer),e.invite2xxTimer=void 0),e.ackWait&&(e.delegate&&e.delegate.onAckTimeout?e.delegate.onAckTimeout():e.bye()))};t.addStateChangeListener(i)}},t.prototype.startReInvite2xxRetransmissionTimer=function(){var e=this;if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof InviteServerTransaction){var t=this.reinviteUserAgentServer.transaction,n=Timers.T1,r=function(){e.reinviteUserAgentServer?(e.logger.log("No ACK for 2xx response received, attempting retransmission"),t.retransmitAcceptedResponse(),n=Math.min(2*n,Timers.T2),e.invite2xxTimer=setTimeout(r,n)):e.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(r,n);var i=function(){t.state===TransactionState.Terminated&&(t.removeStateChangeListener(i),e.invite2xxTimer&&(clearTimeout(e.invite2xxTimer),e.invite2xxTimer=void 0),e.reinviteUserAgentServer)};t.addStateChangeListener(i)}},t}(Dialog),SubscriptionState$1;!function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(SubscriptionState$1||(SubscriptionState$1={}));var AllowedMethods=[C.ACK,C.BYE,C.CANCEL,C.INFO,C.INVITE,C.MESSAGE,C.NOTIFY,C.OPTIONS,C.PRACK,C.REFER,C.REGISTER,C.SUBSCRIBE],ReSubscribeUserAgentClient=function(e){function t(t,n,r){var i=this,s=t.createOutgoingRequestMessage(C.SUBSCRIBE,r);return(i=e.call(this,NonInviteClientTransaction,t.userAgentCore,s,n)||this).dialog=t,i}return __extends$1(t,e),t.prototype.waitNotifyStop=function(){},t.prototype.receiveResponse=function(t){if(t.statusCode&&t.statusCode>=200&&t.statusCode<300){var n=t.getHeader("Expires");if(n){var r=Number(n);this.dialog.subscriptionExpires>r&&(this.dialog.subscriptionExpires=r)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(t.statusCode&&t.statusCode>=400&&t.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(t.statusCode)&&this.dialog.terminate()}e.prototype.receiveResponse.call(this,t)},t}(UserAgentClient),SubscriptionDialog=function(e){function t(t,n,r,i,s,o){var a=e.call(this,i,s)||this;return a.delegate=o,a._autoRefresh=!1,a._subscriptionEvent=t,a._subscriptionExpires=n,a._subscriptionExpiresInitial=n,a._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),a._subscriptionRefresh=void 0,a._subscriptionRefreshLastSet=void 0,a._subscriptionState=r,a.logger=i.loggerFactory.getLogger("sip.subscribe-dialog"),a.logger.log("SUBSCRIBE dialog ".concat(a.id," constructed")),a}return __extends$1(t,e),t.initialDialogStateForSubscription=function(e,t){var n=t.getHeaders("record-route"),r=t.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof NameAddrHeader))throw new Error("Contact not instance of NameAddrHeader.");var i=r.uri,s=e.cseq,o=e.callId,a=e.fromTag,c=t.fromTag;if(!o)throw new Error("Call id undefined.");if(!a)throw new Error("From tag undefined.");if(!c)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");return{id:o+a+c,early:!1,callId:o,localTag:a,remoteTag:c,localSequenceNumber:s,remoteSequenceNumber:undefined,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:i,routeSet:n,secure:!1}},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.N&&(clearTimeout(this.N),this.N=void 0),this.refreshTimerClear(),this.logger.log("SUBSCRIBE dialog ".concat(this.id," destroyed"))},Object.defineProperty(t.prototype,"autoRefresh",{get:function(){return this._autoRefresh},set:function(e){this._autoRefresh=!0,this.refreshTimerSet()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionEvent",{get:function(){return this._subscriptionEvent},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionExpires",{get:function(){var e=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,t=this._subscriptionExpires-e;return Math.max(t,0)},set:function(e){if(e<0)throw new Error("Expires must be greater than or equal to zero.");if(this._subscriptionExpires=e,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this.autoRefresh){var t=this.subscriptionRefresh;(void 0===t||t>=e)&&this.refreshTimerSet()}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionExpiresInitial",{get:function(){return this._subscriptionExpiresInitial},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionRefresh",{get:function(){if(void 0!==this._subscriptionRefresh&&void 0!==this._subscriptionRefreshLastSet){var e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subscriptionState",{get:function(){return this._subscriptionState},enumerable:!1,configurable:!0}),t.prototype.receiveRequest=function(t){if(this.logger.log("SUBSCRIBE dialog ".concat(this.id," received ").concat(t.method," request")),this.sequenceGuard(t))if(e.prototype.receiveRequest.call(this,t),t.method===C.NOTIFY)this.onNotify(t);else this.logger.log("SUBSCRIBE dialog ".concat(this.id," received unimplemented ").concat(t.method," request")),this.core.replyStateless(t,{statusCode:501});else this.logger.log("SUBSCRIBE dialog ".concat(this.id," rejected out of order ").concat(t.method," request."))},t.prototype.refresh=function(){var e="Allow: "+AllowedMethods.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: "+this.subscriptionExpiresInitial),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)},t.prototype.subscribe=function(e,t){var n=this;if(void 0===t&&(t={}),this.subscriptionState!==SubscriptionState$1.Pending&&this.subscriptionState!==SubscriptionState$1.Active)throw new Error("Invalid state ".concat(this.subscriptionState,'. May only re-subscribe while in state "pending" or "active".'));this.logger.log("SUBSCRIBE dialog ".concat(this.id," sending SUBSCRIBE request"));var r=new ReSubscribeUserAgentClient(this,e,t);return this.N&&(clearTimeout(this.N),this.N=void 0),this.N=setTimeout(function(){return n.timerN()},Timers.TIMER_N),r},t.prototype.terminate=function(){this.stateTransition(SubscriptionState$1.Terminated),this.onTerminated()},t.prototype.unsubscribe=function(){var e="Allow: "+AllowedMethods.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: 0"),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)},t.prototype.onNotify=function(e){var t=e.parseHeader("Event").event;if(t&&t===this.subscriptionEvent){this.N&&(clearTimeout(this.N),this.N=void 0);var n=e.parseHeader("Subscription-State");if(n&&n.state){var r=n.state,i=n.expires?Math.max(n.expires,0):void 0;switch(r){case"pending":this.stateTransition(SubscriptionState$1.Pending,i);break;case"active":this.stateTransition(SubscriptionState$1.Active,i);break;case"terminated":this.stateTransition(SubscriptionState$1.Terminated,i);break;default:this.logger.warn("Unrecognized subscription state.")}var s=new NotifyUserAgentServer(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(s):s.accept()}else this.core.replyStateless(e,{statusCode:489})}else this.core.replyStateless(e,{statusCode:489})},t.prototype.onRefresh=function(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)},t.prototype.onTerminated=function(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()},t.prototype.refreshTimerClear=function(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)},t.prototype.refreshTimerSet=function(){var e=this;if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){var t=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(t/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout(function(){e.refreshTimer=void 0,e._subscriptionRefresh=void 0,e._subscriptionRefreshLastSet=void 0,e.onRefresh(e.refresh())},t)}},t.prototype.stateTransition=function(e,t){var n=this,r=function(){n.logger.warn("Invalid subscription state transition from ".concat(n.subscriptionState," to ").concat(e))};switch(e){case SubscriptionState$1.Initial:case SubscriptionState$1.NotifyWait:return void r();case SubscriptionState$1.Pending:if(this.subscriptionState!==SubscriptionState$1.NotifyWait&&this.subscriptionState!==SubscriptionState$1.Pending)return void r();break;case SubscriptionState$1.Active:case SubscriptionState$1.Terminated:if(this.subscriptionState!==SubscriptionState$1.NotifyWait&&this.subscriptionState!==SubscriptionState$1.Pending&&this.subscriptionState!==SubscriptionState$1.Active)return void r();break;default:return void r()}e===SubscriptionState$1.Pending&&t&&(this.subscriptionExpires=t),e===SubscriptionState$1.Active&&t&&(this.subscriptionExpires=t),e===SubscriptionState$1.Terminated&&this.dispose(),this._subscriptionState=e},t.prototype.timerN=function(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==SubscriptionState$1.Terminated&&(this.stateTransition(SubscriptionState$1.Terminated),this.onTerminated())},t}(Dialog),Levels;!function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(Levels||(Levels={}));var Logger=function(){function e(e,t,n){this.logger=e,this.category=t,this.label=n}return e.prototype.error=function(e){this.genericLog(Levels.error,e)},e.prototype.warn=function(e){this.genericLog(Levels.warn,e)},e.prototype.log=function(e){this.genericLog(Levels.log,e)},e.prototype.debug=function(e){this.genericLog(Levels.debug,e)},e.prototype.genericLog=function(e,t){this.logger.genericLog(e,this.category,this.label,t)},Object.defineProperty(e.prototype,"level",{get:function(){return this.logger.level},set:function(e){this.logger.level=e},enumerable:!1,configurable:!0}),e}(),LoggerFactory=function(){function e(){this.builtinEnabled=!0,this._level=Levels.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}return Object.defineProperty(e.prototype,"level",{get:function(){return this._level},set:function(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:Levels.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connector",{get:function(){return this._connector},set:function(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0},enumerable:!1,configurable:!0}),e.prototype.getLogger=function(e,t){if(t&&3===this.level)return new Logger(this,e,t);if(this.loggers[e])return this.loggers[e];var n=new Logger(this,e);return this.loggers[e]=n,n},e.prototype.genericLog=function(e,t,n,r){this.level>=e&&this.builtinEnabled&&this.print(e,t,n,r),this.connector&&this.connector(Levels[e],t,n,r)},e.prototype.print=function(e,t,n,r){if("string"==typeof r){var i=[new Date,t];n&&i.push(n),r=i.concat(r).join(" | ")}switch(e){case Levels.error:console.error(r);break;case Levels.warn:console.warn(r);break;case Levels.log:console.log(r);break;case Levels.debug:console.debug(r)}},e}();!function(e){function t(t,n,r){return e.call(this,NonInviteClientTransaction,t,n,r)||this}__extends$1(t,e)}(UserAgentClient);var InviteUserAgentClient=function(e){function t(t,n,r){var i=e.call(this,InviteClientTransaction,t,n,r)||this;return i.confirmedDialogAcks=new Map,i.confirmedDialogs=new Map,i.earlyDialogs=new Map,i.delegate=r,i}return __extends$1(t,e),t.prototype.dispose=function(){this.earlyDialogs.forEach(function(e){return e.dispose()}),this.earlyDialogs.clear(),e.prototype.dispose.call(this)},t.prototype.onTransportError=function(t){if(this.transaction.state===TransactionState.Calling)return e.prototype.onTransportError.call(this,t);this.logger.error(t.message),this.logger.error("User agent client request transport error while sending ACK.")},t.prototype.receiveResponse=function(e){var t=this;if(this.authenticationGuard(e)){var n=e.statusCode?e.statusCode.toString():"";if(!n)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(n):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(n):if(!e.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping.");var r=Dialog.initialDialogStateForUserAgentClient(this.message,e),i=this.earlyDialogs.get(r.id);if(!i){if(!((a=this.transaction)instanceof InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");i=new SessionDialog(a,this.core,r),this.earlyDialogs.set(i.id,i)}if(!i.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping.");i.signalingState!==SignalingState.Initial&&i.signalingState!==SignalingState.HaveLocalOffer||i.signalingStateTransition(e);var s=i;return void(this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:s,prack:function(e){return s.prack(void 0,e)}}));case/^2[0-9]{2}$/.test(n):if(!e.toTag)return void this.logger.error("2xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("2xx INVITE response received without a Contact header field, dropping.");r=Dialog.initialDialogStateForUserAgentClient(this.message,e);var o=this.confirmedDialogs.get(r.id);if(o){if(u=this.confirmedDialogAcks.get(r.id)){if(!((a=this.transaction)instanceof InviteClientTransaction))throw new Error("Client transaction not instance of InviteClientTransaction.");a.ackResponse(u.message)}return}if(o=this.earlyDialogs.get(r.id))o.confirm(),o.recomputeRouteSet(e),this.earlyDialogs.delete(o.id),this.confirmedDialogs.set(o.id,o);else{var a;if(!((a=this.transaction)instanceof InviteClientTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");o=new SessionDialog(a,this.core,r),this.confirmedDialogs.set(o.id,o)}o.signalingState!==SignalingState.Initial&&o.signalingState!==SignalingState.HaveLocalOffer||o.signalingStateTransition(e);var c=o;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:c,ack:function(e){var n=c.ack(e);return t.confirmedDialogAcks.set(c.id,n),n}});else{var u=c.ack();this.confirmedDialogAcks.set(c.id,u)}return;case/^3[0-9]{2}$/.test(n):return this.earlyDialogs.forEach(function(e){return e.dispose()}),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(n):return this.earlyDialogs.forEach(function(e){return e.dispose()}),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error("Invalid status code ".concat(n))}}},t}(UserAgentClient),InviteUserAgentServer=function(e){function t(t,n,r){var i=e.call(this,InviteServerTransaction,t,n,r)||this;return i.core=t,i}return __extends$1(t,e),t.prototype.dispose=function(){this.earlyDialog&&this.earlyDialog.dispose(),e.prototype.dispose.call(this)},t.prototype.accept=function(t){if(void 0===t&&(t={statusCode:200}),!this.acceptable)throw new TransactionStateError("".concat(this.message.method," not acceptable in state ").concat(this.transaction.state,"."));if(!this.confirmedDialog)if(this.earlyDialog)this.earlyDialog.confirm(),this.confirmedDialog=this.earlyDialog,this.earlyDialog=void 0;else{var n=this.transaction;if(!(n instanceof InviteServerTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");var r=Dialog.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new SessionDialog(n,this.core,r)}var i=this.message.getHeaders("record-route").map(function(e){return"Record-Route: ".concat(e)}),s="Contact: ".concat(this.core.configuration.contact.toString()),o="Allow: "+AllowedMethods.toString();if(!t.body)if(this.confirmedDialog.signalingState===SignalingState.Stable)t.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===SignalingState.Initial||this.confirmedDialog.signalingState===SignalingState.HaveRemoteOffer)throw new Error("Response must have a body.");t.statusCode=t.statusCode||200,t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(i),t.extraHeaders.push(o),t.extraHeaders.push(s);var a=e.prototype.accept.call(this,t),c=this.confirmedDialog,u=__assign(__assign({},a),{session:c});return t.body&&this.confirmedDialog.signalingState!==SignalingState.Stable&&this.confirmedDialog.signalingStateTransition(t.body),u},t.prototype.progress=function(t){if(void 0===t&&(t={statusCode:180}),!this.progressable)throw new TransactionStateError("".concat(this.message.method," not progressable in state ").concat(this.transaction.state,"."));if(!this.earlyDialog){var n=this.transaction;if(!(n instanceof InviteServerTransaction))throw new Error("Transaction not instance of InviteClientTransaction.");var r=Dialog.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new SessionDialog(n,this.core,r)}var i=this.message.getHeaders("record-route").map(function(e){return"Record-Route: ".concat(e)}),s="Contact: ".concat(this.core.configuration.contact);t.extraHeaders=t.extraHeaders||[],t.extraHeaders=t.extraHeaders.concat(i),t.extraHeaders.push(s);var o=e.prototype.progress.call(this,t),a=this.earlyDialog,c=__assign(__assign({},o),{session:a});return t.body&&this.earlyDialog.signalingState!==SignalingState.Stable&&this.earlyDialog.signalingStateTransition(t.body),c},t.prototype.redirect=function(t,n){return void 0===n&&(n={statusCode:302}),e.prototype.redirect.call(this,t,n)},t.prototype.reject=function(t){return void 0===t&&(t={statusCode:486}),e.prototype.reject.call(this,t)},t}(UserAgentServer),PublishUserAgentClient=function(e){function t(t,n,r){return e.call(this,NonInviteClientTransaction,t,n,r)||this}return __extends$1(t,e),t}(UserAgentClient);!function(e){function t(t,n,r){return e.call(this,NonInviteServerTransaction,t.userAgentCore,n,r)||this}__extends$1(t,e)}(UserAgentServer);var RegisterUserAgentClient=function(e){function t(t,n,r){return e.call(this,NonInviteClientTransaction,t,n,r)||this}return __extends$1(t,e),t}(UserAgentClient),RegisterUserAgentServer=function(e){function t(t,n,r){var i=e.call(this,NonInviteServerTransaction,t,n,r)||this;return i.core=t,i}return __extends$1(t,e),t}(UserAgentServer),SubscribeUserAgentClient=function(e){function t(t,n,r){var i=this,s=n.getHeader("Event");if(!s)throw new Error("Event undefined");var o=n.getHeader("Expires");if(!o)throw new Error("Expires undefined");return(i=e.call(this,NonInviteClientTransaction,t,n,r)||this).delegate=r,i.subscriberId=n.callId+n.fromTag+s,i.subscriptionExpiresRequested=i.subscriptionExpires=Number(o),i.subscriptionEvent=s,i.subscriptionState=SubscriptionState$1.NotifyWait,i.waitNotifyStart(),i}return __extends$1(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype.onNotify=function(e){var t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});var n=e.message.parseHeader("Subscription-State");if(!n||!n.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});var r=n.state;switch(r){case"pending":case"active":case"terminated":break;default:return this.logger.warn("Invalid subscription state ".concat(r)),void e.reject({statusCode:489})}if("terminated"!==r&&!e.message.parseHeader("contact"))return this.logger.warn("Failed to parse contact."),void e.reject({statusCode:489});if(this.dialog)throw new Error("Dialog already created. This implementation only supports install of single subscriptions.");switch(this.waitNotifyStop(),this.subscriptionExpires=n.expires?Math.min(this.subscriptionExpires,Math.max(n.expires,0)):this.subscriptionExpires,r){case"pending":this.subscriptionState=SubscriptionState$1.Pending;break;case"active":this.subscriptionState=SubscriptionState$1.Active;break;case"terminated":this.subscriptionState=SubscriptionState$1.Terminated;break;default:throw new Error("Unrecognized state ".concat(r,"."))}if(this.subscriptionState!==SubscriptionState$1.Terminated){var i=SubscriptionDialog.initialDialogStateForSubscription(this.message,e.message);this.dialog=new SubscriptionDialog(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,i)}if(this.delegate&&this.delegate.onNotify){var s=e,o=this.dialog;this.delegate.onNotify({request:s,subscription:o})}else e.accept()},t.prototype.waitNotifyStart=function(){var e=this;this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout(function(){return e.timerN()},Timers.TIMER_N))},t.prototype.waitNotifyStop=function(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)},t.prototype.receiveResponse=function(t){if(this.authenticationGuard(t)){if(t.statusCode&&t.statusCode>=200&&t.statusCode<300){var n=t.getHeader("Expires");if(n){var r=Number(n);r>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),r<this.subscriptionExpires&&(this.subscriptionExpires=r)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE");this.dialog&&this.dialog.subscriptionExpires>this.subscriptionExpires&&(this.dialog.subscriptionExpires=this.subscriptionExpires)}t.statusCode&&t.statusCode>=300&&t.statusCode<700&&this.waitNotifyStop(),e.prototype.receiveResponse.call(this,t)}},t.prototype.timerN=function(){this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."),this.waitNotifyStop(),this.delegate&&this.delegate.onNotifyTimeout&&this.delegate.onNotifyTimeout()},t}(UserAgentClient),SubscribeUserAgentServer=function(e){function t(t,n,r){var i=e.call(this,NonInviteServerTransaction,t,n,r)||this;return i.core=t,i}return __extends$1(t,e),t}(UserAgentServer),acceptedBodyTypes=["application/sdp","application/dtmf-relay"],UserAgentCore=function(){function e(e,t){void 0===t&&(t={}),this.userAgentClients=new Map,this.userAgentServers=new Map,this.configuration=e,this.delegate=t,this.dialogs=new Map,this.subscribers=new Map,this.logger=e.loggerFactory.getLogger("sip.user-agent-core")}return e.prototype.dispose=function(){this.reset()},e.prototype.reset=function(){this.dialogs.forEach(function(e){return e.dispose()}),this.dialogs.clear(),this.subscribers.forEach(function(e){return e.dispose()}),this.subscribers.clear(),this.userAgentClients.forEach(function(e){return e.dispose()}),this.userAgentClients.clear(),this.userAgentServers.forEach(function(e){return e.dispose()}),this.userAgentServers.clear()},Object.defineProperty(e.prototype,"loggerFactory",{get:function(){return this.configuration.loggerFactory},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transport",{get:function(){var e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e},enumerable:!1,configurable:!0}),e.prototype.invite=function(e,t){return new InviteUserAgentClient(this,e,t)},e.prototype.message=function(e,t){return new MessageUserAgentClient(this,e,t)},e.prototype.publish=function(e,t){return new PublishUserAgentClient(this,e,t)},e.prototype.register=function(e,t){return new RegisterUserAgentClient(this,e,t)},e.prototype.subscribe=function(e,t){return new SubscribeUserAgentClient(this,e,t)},e.prototype.request=function(e,t){return new UserAgentClient(NonInviteClientTransaction,this,e,t)},e.prototype.makeOutgoingRequestMessage=function(e,t,n,r,i,s,o){var a=this.configuration.sipjsId,c=this.configuration.displayName,u=this.configuration.viaForceRport,l=this.configuration.hackViaTcp,h=this.configuration.supportedOptionTags.slice();e===C.REGISTER&&h.push("path","gruu"),e===C.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&h.push("gruu");var d=this.configuration.routeSet,p=this.configuration.userAgentHeaderFieldValue,g=this.configuration.viaHost,f=__assign(__assign({},{callIdPrefix:a,forceRport:u,fromDisplayName:c,hackViaTcp:l,optionTags:h,routeSet:d,userAgentString:p,viaHost:g}),i);return new OutgoingRequestMessage(e,t,n,r,f,s,o)},e.prototype.receiveIncomingRequestFromTransport=function(e){this.receiveRequestFromTransport(e)},e.prototype.receiveIncomingResponseFromTransport=function(e){this.receiveResponseFromTransport(e)},e.prototype.replyStateless=function(e,t){var n=this,r=this.configuration.userAgentHeaderFieldValue,i=this.configuration.supportedOptionTagsResponse;t=__assign(__assign({},t),{userAgent:r,supported:i});var s=constructOutgoingResponse(e,t);return this.transport.send(s.message).catch(function(t){t instanceof Error&&n.logger.error(t.message),n.logger.error("Transport error occurred sending stateless reply to ".concat(e.method," request."))}),s},e.prototype.receiveRequestFromTransport=function(e){var t=e.viaBranch,n=this.userAgentServers.get(t);e.method===C.ACK&&n&&n.transaction.state===TransactionState.Accepted&&n instanceof InviteUserAgentServer?this.logger.warn("Discarding out of dialog ACK after 2xx response sent on transaction ".concat(t,".")):e.method!==C.CANCEL?n?n.transaction.receiveRequest(e):this.receiveRequest(e):n?(this.replyStateless(e,{statusCode:200}),n.transaction instanceof InviteServerTransaction&&n.transaction.state===TransactionState.Proceeding&&n instanceof InviteUserAgentServer&&n.receiveCancel(e)):this.replyStateless(e,{statusCode:481})},e.prototype.receiveRequest=function(e){if(AllowedMethods.includes(e.method)){if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"===e.ruri.scheme){var t=e.ruri,n=function(e){return!!e&&e.user===t.user};if(!n(this.configuration.aor)&&!(n(this.configuration.contact.uri)||n(this.configuration.contact.pubGruu)||n(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==C.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==C.INVITE||e.hasHeader("Contact")){if(!e.toTag){var r=e.viaBranch;if(!this.userAgentServers.has(r))if(Array.from(this.userAgentServers.values()).some(function(t){return t.transaction.request.fromTag===e.fromTag&&t.transaction.request.callId===e.callId&&t.transaction.request.cseq===e.cseq}))return void this.replyStateless(e,{statusCode:482})}e.toTag?this.receiveInsideDialogRequest(e):this.receiveOutsideDialogRequest(e)}else this.replyStateless(e,{statusCode:400,reasonPhrase:"Missing Contact Header"})}else this.replyStateless(e,{statusCode:416})}else{var i="Allow: "+AllowedMethods.toString();this.replyStateless(e,{statusCode:405,extraHeaders:[i]})}},e.prototype.receiveInsideDialogRequest=function(e){if(e.method===C.NOTIFY){var t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});var n=e.callId+e.toTag+t.event,r=this.subscribers.get(n);if(r){var i=new NotifyUserAgentServer(this,e);return void r.onNotify(i)}}var s=e.callId+e.toTag+e.fromTag,o=this.dialogs.get(s);if(o){if(e.method===C.OPTIONS){var a="Allow: "+AllowedMethods.toString(),c="Accept: "+acceptedBodyTypes.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[a,c]})}o.receiveRequest(e)}else e.method!==C.ACK&&this.replyStateless(e,{statusCode:481})},e.prototype.receiveOutsideDialogRequest=function(e){switch(e.method){case C.ACK:break;case C.BYE:this.replyStateless(e,{statusCode:481});break;case C.CANCEL:throw new Error("Unexpected out of dialog request method ".concat(e.method,"."));case C.INFO:this.replyStateless(e,{statusCode:405});break;case C.INVITE:var t=new InviteUserAgentServer(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject();break;case C.MESSAGE:t=new MessageUserAgentServer(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept();break;case C.NOTIFY:t=new NotifyUserAgentServer(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405});break;case C.OPTIONS:var n="Allow: "+AllowedMethods.toString(),r="Accept: "+acceptedBodyTypes.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[n,r]});break;case C.REFER:t=new ReferUserAgentServer(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405});break;case C.REGISTER:t=new RegisterUserAgentServer(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405});break;case C.SUBSCRIBE:t=new SubscribeUserAgentServer(this,e);this.delegate.onSubscribe?this.delegate.onSubscribe(t):t.reject({statusCode:480});break;default:throw new Error("Unexpected out of dialog request method ".concat(e.method,"."))}},e.prototype.receiveResponseFromTransport=function(e){if(e.getHeaders("via").length>1)this.logger.warn("More than one Via header field present in the response, dropping");else{var t=e.viaBranch+e.method,n=this.userAgentClients.get(t);n?n.transaction.receiveResponse(e):this.logger.warn("Discarding unmatched ".concat(e.statusCode," response to ").concat(e.method," ").concat(t,"."))}},e}(),ContentTypeUnsupportedError=function(e){function t(t){return e.call(this,t||"Unsupported content type.")||this}return __extends$1(t,e),t}(Exception),RequestPendingError=function(e){function t(t){return e.call(this,t||"Request pending.")||this}return __extends$1(t,e),t}(Exception),SessionDescriptionHandlerError=function(e){function t(t){return e.call(this,t||"Unspecified session description handler error.")||this}return __extends$1(t,e),t}(Exception),SessionTerminatedError=function(e){function t(){return e.call(this,"The session has terminated.")||this}return __extends$1(t,e),t}(Exception),StateTransitionError=function(e){function t(t){return e.call(this,t||"An error occurred during state transition.")||this}return __extends$1(t,e),t}(Exception),Ack=function(){function e(e){this.incomingAckRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingAckRequest.message},enumerable:!1,configurable:!0}),e}(),Bye=function(){function e(e){this.incomingByeRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingByeRequest.message},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){return this.incomingByeRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingByeRequest.reject(e),Promise.resolve()},e}(),EmitterImpl=function(){function e(){this.listeners=new Array}return e.prototype.addListener=function(e,t){var n=this,r=function(t){n.removeListener(r),e(t)};!0===(null==t?void 0:t.once)?this.listeners.push(r):this.listeners.push(e)},e.prototype.emit=function(e){this.listeners.slice().forEach(function(t){return t(e)})},e.prototype.removeAllListeners=function(){this.listeners=[]},e.prototype.removeListener=function(e){this.listeners=this.listeners.filter(function(t){return t!==e})},e.prototype.on=function(e){return this.addListener(e)},e.prototype.off=function(e){return this.removeListener(e)},e.prototype.once=function(e){return this.addListener(e,{once:!0})},e}(),Info=function(){function e(e){this.incomingInfoRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingInfoRequest.message},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){return this.incomingInfoRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingInfoRequest.reject(e),Promise.resolve()},e}(),Message=function(){function e(e){this.incomingMessageRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingMessageRequest.message},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){return this.incomingMessageRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingMessageRequest.reject(e),Promise.resolve()},e}(),Notification=function(){function e(e){this.incomingNotifyRequest=e}return Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingNotifyRequest.message},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){return this.incomingNotifyRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingNotifyRequest.reject(e),Promise.resolve()},e}(),Referral=function(){function e(e,t){this.incomingReferRequest=e,this.session=t}return Object.defineProperty(e.prototype,"referTo",{get:function(){var e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof NameAddrHeader))throw new Error("Failed to parse Refer-To header.");return e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"referredBy",{get:function(){return this.incomingReferRequest.message.getHeader("referred-by")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"replaces",{get:function(){var e=this.referTo.uri.getHeader("replaces");return e instanceof Array?e[0]:e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"request",{get:function(){return this.incomingReferRequest.message},enumerable:!1,configurable:!0}),e.prototype.accept=function(e){return void 0===e&&(e={statusCode:202}),this.incomingReferRequest.accept(e),Promise.resolve()},e.prototype.reject=function(e){return this.incomingReferRequest.reject(e),Promise.resolve()},e.prototype.makeInviter=function(e){if(this.inviter)return this.inviter;var t=this.referTo.uri.clone();t.clearHeaders();var n=((e=e||{}).extraHeaders||[]).slice(),r=this.replaces;r&&n.push("Replaces: "+decodeURIComponent(r));var i=this.referredBy;return i&&n.push("Referred-By: "+i),e.extraHeaders=n,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter},e}(),SessionState;!function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(SessionState||(SessionState={}));var Session=function(){function e(e,t){void 0===t&&(t={}),this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=SessionState.Initial,this.delegate=t.delegate,this._stateEventEmitter=new EmitterImpl,this._userAgent=e}return e.prototype.dispose=function(){var e=this;switch(this.logger.log("Session ".concat(this.id," in state ").concat(this._state," is being disposed")),delete this.userAgent._sessions[this.id],this._sessionDescriptionHandler&&this._sessionDescriptionHandler.close(),this.state){case SessionState.Initial:case SessionState.Establishing:break;case SessionState.Established:return new Promise(function(t){e._bye({onAccept:function(){return t()},onRedirect:function(){return t()},onReject:function(){return t()}})});case SessionState.Terminating:case SessionState.Terminated:break;default:throw new Error("Unknown state.")}return Promise.resolve()},Object.defineProperty(e.prototype,"assertedIdentity",{get:function(){return this._assertedIdentity},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dialog",{get:function(){return this._dialog},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"replacee",{get:function(){return this._replacee},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandler",{get:function(){return this._sessionDescriptionHandler},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandlerFactory",{get:function(){return this.userAgent.configuration.sessionDescriptionHandlerFactory},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandlerModifiers",{get:function(){return this._sessionDescriptionHandlerModifiers||[]},set:function(e){this._sessionDescriptionHandlerModifiers=e.slice()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandlerOptions",{get:function(){return this._sessionDescriptionHandlerOptions||{}},set:function(e){this._sessionDescriptionHandlerOptions=__assign({},e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandlerModifiersReInvite",{get:function(){return this._sessionDescriptionHandlerModifiersReInvite||[]},set:function(e){this._sessionDescriptionHandlerModifiersReInvite=e.slice()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionDescriptionHandlerOptionsReInvite",{get:function(){return this._sessionDescriptionHandlerOptionsReInvite||{}},set:function(e){this._sessionDescriptionHandlerOptionsReInvite=__assign({},e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"userAgent",{get:function(){return this._userAgent},enumerable:!1,configurable:!0}),e.prototype.bye=function(e){void 0===e&&(e={});var t="Session.bye() may only be called if established session.";switch(this.state){case SessionState.Initial:"function"==typeof this.cancel?(t+=" However Inviter.invite() has not yet been called.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called.",t+=" Perhaps you should have called Invitation.reject()?");break;case SessionState.Establishing:"function"==typeof this.cancel?(t+=" However a dialog does not yet exist.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called (or not yet resolved).",t+=" Perhaps you should have called Invitation.reject()?");break;case SessionState.Established:var n=e.requestDelegate,r=this.copyRequestOptions(e.requestOptions);return this._bye(n,r);case SessionState.Terminating:t+=" However this session is already terminating.","function"==typeof this.cancel?t+=" Perhaps you have already called Inviter.cancel()?":"function"==typeof this.reject&&(t+=" Perhaps you have already called Session.bye()?");break;case SessionState.Terminated:t+=" However this session is already terminated.";break;default:throw new Error("Unknown state")}return this.logger.error(t),Promise.reject(new Error("Invalid session state ".concat(this.state)))},e.prototype.info=function(e){if(void 0===e&&(e={}),this.state!==SessionState.Established){return this.logger.error("Session.info() may only be called if established session."),Promise.reject(new Error("Invalid session state ".concat(this.state)))}var t=e.requestDelegate,n=this.copyRequestOptions(e.requestOptions);return this._info(t,n)},e.prototype.invite=function(e){var t=this;if(void 0===e&&(e={}),this.logger.log("Session.invite"),this.state!==SessionState.Established)return Promise.reject(new Error("Invalid session state ".concat(this.state)));if(this.pendingReinvite)return Promise.reject(new RequestPendingError("Reinvite in progress. Please wait until complete, then try again."));this.pendingReinvite=!0,e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiersReInvite=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptionsReInvite=e.sessionDescriptionHandlerOptions);var n={onAccept:function(n){var r=getBody(n.message);if(!r)return t.logger.error("Received 2xx response to re-INVITE without a session description"),t.ackAndBye(n,400,"Missing session description"),t.stateTransition(SessionState.Terminated),void(t.pendingReinvite=!1);if(e.withoutSdp){var i={sessionDescriptionHandlerOptions:t.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:t.sessionDescriptionHandlerModifiersReInvite};t.setOfferAndGetAnswer(r,i).then(function(e){n.ack({body:e})}).catch(function(e){t.logger.error("Failed to handle offer in 2xx response to re-INVITE"),t.logger.error(e.message),t.state===SessionState.Terminated?n.ack():(t.ackAndBye(n,488,"Bad Media Description"),t.stateTransition(SessionState.Terminated))}).then(function(){t.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(n)})}else{i={sessionDescriptionHandlerOptions:t.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:t.sessionDescriptionHandlerModifiersReInvite};t.setAnswer(r,i).then(function(){n.ack()}).catch(function(e){t.logger.error("Failed to handle answer in 2xx response to re-INVITE"),t.logger.error(e.message),t.state!==SessionState.Terminated?(t.ackAndBye(n,488,"Bad Media Description"),t.stateTransition(SessionState.Terminated)):n.ack()}).then(function(){t.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(n)})}},onProgress:function(e){},onRedirect:function(e){},onReject:function(n){t.logger.warn("Received a non-2xx response to re-INVITE"),t.pendingReinvite=!1,e.withoutSdp?e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(n):t.rollbackOffer().catch(function(e){if(t.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),t.logger.error(e.message),t.state!==SessionState.Terminated){if(!t.dialog)throw new Error("Dialog undefined.");var n=[];n.push("Reason: "+t.getReasonHeaderValue(500,"Internal Server Error")),t.dialog.bye(void 0,{extraHeaders:n}),t.stateTransition(SessionState.Terminated)}}).then(function(){e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(n)})},onTrying:function(e){}},r=e.requestOptions||{};if(r.extraHeaders=(r.extraHeaders||[]).slice(),r.extraHeaders.push("Allow: "+AllowedMethods.toString()),r.extraHeaders.push("Contact: "+this._contact),e.withoutSdp){if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return Promise.resolve(this.dialog.invite(n,r))}var i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(i).then(function(e){if(!t.dialog)throw t.pendingReinvite=!1,new Error("Dialog undefined.");return r.body=e,t.dialog.invite(n,r)}).catch(function(e){throw t.logger.error(e.message),t.logger.error("Failed to send re-INVITE"),t.pendingReinvite=!1,e})},e.prototype.message=function(e){if(void 0===e&&(e={}),this.state!==SessionState.Established){return this.logger.error("Session.message() may only be called if established session."),Promise.reject(new Error("Invalid session state ".concat(this.state)))}var t=e.requestDelegate,n=this.copyRequestOptions(e.requestOptions);return this._message(t,n)},e.prototype.refer=function(e,t){if(void 0===t&&(t={}),this.state!==SessionState.Established){return this.logger.error("Session.refer() may only be called if established session."),Promise.reject(new Error("Invalid session state ".concat(this.state)))}var n=t.requestDelegate,r=this.copyRequestOptions(t.requestOptions);return r.extraHeaders=r.extraHeaders?r.extraHeaders.concat(this.referExtraHeaders(this.referToString(e))):this.referExtraHeaders(this.referToString(e)),this._refer(t.onNotify,n,r)},e.prototype._bye=function(e,t){var n=this;if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));var r=this.dialog;switch(r.sessionState){case SessionState$1.Initial:case SessionState$1.Early:throw new Error("Invalid dialog state ".concat(r.sessionState));case SessionState$1.AckWait:return this.stateTransition(SessionState.Terminating),new Promise(function(i){r.delegate={onAck:function(){var s=r.bye(e,t);return n.stateTransition(SessionState.Terminated),i(s),Promise.resolve()},onAckTimeout:function(){var s=r.bye(e,t);n.stateTransition(SessionState.Terminated),i(s)}}});case SessionState$1.Confirmed:var i=r.bye(e,t);return this.stateTransition(SessionState.Terminated),Promise.resolve(i);case SessionState$1.Terminated:throw new Error("Invalid dialog state ".concat(r.sessionState));default:throw new Error("Unrecognized state.")}},e.prototype._info=function(e,t){return this.dialog?Promise.resolve(this.dialog.info(e,t)):Promise.reject(new Error("Session dialog undefined."))},e.prototype._message=function(e,t){return this.dialog?Promise.resolve(this.dialog.message(e,t)):Promise.reject(new Error("Session dialog undefined."))},e.prototype._refer=function(e,t,n){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,n))):Promise.reject(new Error("Session dialog undefined."))},e.prototype.ackAndBye=function(e,t,n){e.ack();var r=[];t&&r.push("Reason: "+this.getReasonHeaderValue(t,n)),e.session.bye(void 0,{extraHeaders:r})},e.prototype.onAckRequest=function(e){var t=this;if(this.logger.log("Session.onAckRequest"),this.state!==SessionState.Established&&this.state!==SessionState.Terminating)return this.logger.error("ACK received while in state ".concat(this.state,", dropping request")),Promise.resolve();var n=this.dialog;if(!n)throw new Error("Dialog undefined.");var r={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};if(this.delegate&&this.delegate.onAck){var i=new Ack(e);this.delegate.onAck(i)}switch(this.pendingReinviteAck=!1,n.signalingState){case SignalingState.Initial:this.logger.error("Invalid signaling state ".concat(n.signalingState,"."));var s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return n.bye(void 0,{extraHeaders:s}),this.stateTransition(SessionState.Terminated),Promise.resolve();case SignalingState.Stable:var o=getBody(e.message);return o?"render"===o.contentDisposition?(this._renderbody=o.content,this._rendertype=o.contentType,Promise.resolve()):"session"!==o.contentDisposition?Promise.resolve():this.setAnswer(o,r).catch(function(e){t.logger.error(e.message);var r=["Reason: "+t.getReasonHeaderValue(488,"Bad Media Description")];n.bye(void 0,{extraHeaders:r}),t.stateTransition(SessionState.Terminated)}):Promise.resolve();case SignalingState.HaveLocalOffer:this.logger.error("Invalid signaling state ".concat(n.signalingState,"."));s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return n.bye(void 0,{extraHeaders:s}),this.stateTransition(SessionState.Terminated),Promise.resolve();case SignalingState.HaveRemoteOffer:this.logger.error("Invalid signaling state ".concat(n.signalingState,"."));s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return n.bye(void 0,{extraHeaders:s}),this.stateTransition(SessionState.Terminated),Promise.resolve();case SignalingState.Closed:default:throw new Error("Invalid signaling state ".concat(n.signalingState,"."))}},e.prototype.onByeRequest=function(e){if(this.logger.log("Session.onByeRequest"),this.state===SessionState.Established){if(this.delegate&&this.delegate.onBye){var t=new Bye(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(SessionState.Terminated)}else this.logger.error("BYE received while in state ".concat(this.state,", dropping request"))},e.prototype.onInfoRequest=function(e){if(this.logger.log("Session.onInfoRequest"),this.state===SessionState.Established)if(this.delegate&&this.delegate.onInfo){var t=new Info(e);this.delegate.onInfo(t)}else e.accept();else this.logger.error("INFO received while in state ".concat(this.state,", dropping request"))},e.prototype.onInviteRequest=function(e){var t=this;if(this.logger.log("Session.onInviteRequest"),this.state===SessionState.Established){this.pendingReinviteAck=!0;var n=["Contact: "+this._contact];if(e.message.hasHeader("P-Asserted-Identity")){var r=e.message.getHeader("P-Asserted-Identity");if(!r)throw new Error("Header undefined.");this._assertedIdentity=Grammar.nameAddrHeaderParse(r)}var i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(i).then(function(r){var i=e.accept({statusCode:200,extraHeaders:n,body:r});t.delegate&&t.delegate.onInvite&&t.delegate.onInvite(e.message,i.message,200)}).catch(function(r){if(t.logger.error(r.message),t.logger.error("Failed to handle to re-INVITE request"),!t.dialog)throw new Error("Dialog undefined.");if(t.logger.error(t.dialog.signalingState),t.dialog.signalingState!==SignalingState.Stable)t.rollbackOffer().then(function(){var n=e.reject({statusCode:488});t.delegate&&t.delegate.onInvite&&t.delegate.onInvite(e.message,n.message,488)}).catch(function(r){t.logger.error(r.message),t.logger.error("Failed to rollback offer on re-INVITE request");var i=e.reject({statusCode:488});if(t.state!==SessionState.Terminated){if(!t.dialog)throw new Error("Dialog undefined.");[].push("Reason: "+t.getReasonHeaderValue(500,"Internal Server Error")),t.dialog.bye(void 0,{extraHeaders:n}),t.stateTransition(SessionState.Terminated)}t.delegate&&t.delegate.onInvite&&t.delegate.onInvite(e.message,i.message,488)});else{var i=e.reject({statusCode:488});t.delegate&&t.delegate.onInvite&&t.delegate.onInvite(e.message,i.message,488)}})}else this.logger.error("INVITE received while in state ".concat(this.state,", dropping request"))},e.prototype.onMessageRequest=function(e){if(this.logger.log("Session.onMessageRequest"),this.state===SessionState.Established)if(this.delegate&&this.delegate.onMessage){var t=new Message(e);this.delegate.onMessage(t)}else e.accept();else this.logger.error("MESSAGE received while in state ".concat(this.state,", dropping request"))},e.prototype.onNotifyRequest=function(e){if(this.logger.log("Session.onNotifyRequest"),this.state===SessionState.Established)if(this.onNotify){var t=new Notification(e);this.onNotify(t)}else if(this.delegate&&this.delegate.onNotify){t=new Notification(e);this.delegate.onNotify(t)}else e.accept();else this.logger.error("NOTIFY received while in state ".concat(this.state,", dropping request"))},e.prototype.onPrackRequest=function(e){if(this.logger.log("Session.onPrackRequest"),this.state===SessionState.Established)throw new Error("Unimplemented.");this.logger.error("PRACK received while in state ".concat(this.state,", dropping request"))},e.prototype.onReferRequest=function(e){var t=this;if(this.logger.log("Session.onReferRequest"),this.state===SessionState.Established){if(!e.message.hasHeader("refer-to"))return this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),void e.reject();var n=new Referral(e,this);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(n):(this.logger.log("No delegate available to handle REFER, automatically accepting and following."),n.accept().then(function(){return n.makeInviter(t._referralInviterOptions).invite()}).catch(function(e){t.logger.error(e.message)}))}else this.logger.error("REFER received while in state ".concat(this.state,", dropping request"))},e.prototype.generateResponseOfferAnswer=function(e,t){if(this.dialog)return this.generateResponseOfferAnswerInDialog(t);var n=getBody(e.message);return n&&"session"===n.contentDisposition?this.setOfferAndGetAnswer(n,t):this.getOffer(t)},e.prototype.generateResponseOfferAnswerInDialog=function(e){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case SignalingState.Initial:return this.getOffer(e);case SignalingState.HaveLocalOffer:return Promise.resolve(void 0);case SignalingState.HaveRemoteOffer:if(!this.dialog.offer)throw new Error("Session offer undefined in signaling state ".concat(this.dialog.signalingState,"."));return this.setOfferAndGetAnswer(this.dialog.offer,e);case SignalingState.Stable:return this.state!==SessionState.Established?Promise.resolve(void 0):this.getOffer(e);case SignalingState.Closed:default:throw new Error("Invalid signaling state ".concat(this.dialog.signalingState,"."))}},e.prototype.getOffer=function(e){var t=this,n=this.setupSessionDescriptionHandler(),r=e.sessionDescriptionHandlerOptions,i=e.sessionDescriptionHandlerModifiers;try{return n.getDescription(r,i).then(function(e){return fromBodyLegacy(e)}).catch(function(e){t.logger.error("Session.getOffer: SDH getDescription rejected...");var n=e instanceof Error?e:new Error("Session.getOffer unknown error.");throw t.logger.error(n.message),n})}catch(e){this.logger.error("Session.getOffer: SDH getDescription threw...");var s=e instanceof Error?e:new Error(e);return this.logger.error(s.message),Promise.reject(s)}},e.prototype.rollbackOffer=function(){var e=this,t=this.setupSessionDescriptionHandler();if(void 0===t.rollbackDescription)return Promise.resolve();try{return t.rollbackDescription().catch(function(t){e.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");var n=t instanceof Error?t:new Error("Session.rollbackOffer unknown error.");throw e.logger.error(n.message),n})}catch(e){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");var n=e instanceof Error?e:new Error(e);return this.logger.error(n.message),Promise.reject(n)}},e.prototype.setAnswer=function(e,t){var n=this,r=this.setupSessionDescriptionHandler(),i=t.sessionDescriptionHandlerOptions,s=t.sessionDescriptionHandlerModifiers;try{if(!r.hasDescription(e.contentType))return Promise.reject(new ContentTypeUnsupportedError)}catch(e){this.logger.error("Session.setAnswer: SDH hasDescription threw...");var o=e instanceof Error?e:new Error(e);return this.logger.error(o.message),Promise.reject(o)}try{return r.setDescription(e.content,i,s).catch(function(e){n.logger.error("Session.setAnswer: SDH setDescription rejected...");var t=e instanceof Error?e:new Error("Session.setAnswer unknown error.");throw n.logger.error(t.message),t})}catch(e){this.logger.error("Session.setAnswer: SDH setDescription threw...");o=e instanceof Error?e:new Error(e);return this.logger.error(o.message),Promise.reject(o)}},e.prototype.setOfferAndGetAnswer=function(e,t){var n=this,r=this.setupSessionDescriptionHandler(),i=t.sessionDescriptionHandlerOptions,s=t.sessionDescriptionHandlerModifiers;try{if(!r.hasDescription(e.contentType))return Promise.reject(new ContentTypeUnsupportedError)}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");var o=e instanceof Error?e:new Error(e);return this.logger.error(o.message),Promise.reject(o)}try{return r.setDescription(e.content,i,s).then(function(){return r.getDescription(i,s)}).then(function(e){return fromBodyLegacy(e)}).catch(function(e){n.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");var t=e instanceof Error?e:new Error("Session.setOfferAndGetAnswer unknown error.");throw n.logger.error(t.message),t})}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");o=e instanceof Error?e:new Error(e);return this.logger.error(o.message),Promise.reject(o)}},e.prototype.setSessionDescriptionHandler=function(e){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=e},e.prototype.setupSessionDescriptionHandler=function(){var e;return this._sessionDescriptionHandler||(this._sessionDescriptionHandler=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions),(null===(e=this.delegate)||void 0===e?void 0:e.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler,!1)),this._sessionDescriptionHandler},e.prototype.stateTransition=function(e){var t=this,n=function(){throw new Error("Invalid state transition from ".concat(t._state," to ").concat(e))};switch(this._state){case SessionState.Initial:e!==SessionState.Establishing&&e!==SessionState.Established&&e!==SessionState.Terminating&&e!==SessionState.Terminated&&n();break;case SessionState.Establishing:e!==SessionState.Established&&e!==SessionState.Terminating&&e!==SessionState.Terminated&&n();break;case SessionState.Established:e!==SessionState.Terminating&&e!==SessionState.Terminated&&n();break;case SessionState.Terminating:e!==SessionState.Terminated&&n();break;case SessionState.Terminated:n();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log("Session ".concat(this.id," transitioned to state ").concat(this._state)),this._stateEventEmitter.emit(this._state),e===SessionState.Terminated&&this.dispose()},e.prototype.copyRequestOptions=function(e){return void 0===e&&(e={}),{extraHeaders:e.extraHeaders?e.extraHeaders.slice():void 0,body:e.body?{contentDisposition:e.body.contentDisposition||"render",contentType:e.body.contentType||"text/plain",content:e.body.content||""}:void 0}},e.prototype.getReasonHeaderValue=function(e,t){var n=e,r=getReasonPhrase(e);return!r&&t&&(r=t),"SIP;cause="+n+';text="'+r+'"'},e.prototype.referExtraHeaders=function(e){var t=[];return t.push("Referred-By: <"+this.userAgent.configuration.uri+">"),t.push("Contact: "+this._contact),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.push("Refer-To: "+e),t},e.prototype.referToString=function(e){var t;if(e instanceof URI)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");var n=e.remoteIdentity.friendlyName,r=e.dialog.remoteTarget.toString(),i=e.dialog.callId,s=e.dialog.remoteTag,o=e.dialog.localTag,a=encodeURIComponent("".concat(i,";to-tag=").concat(s,";from-tag=").concat(o));t='"'.concat(n,'" <').concat(r,"?Replaces=").concat(a,">")}return t},e}(),SIPExtension;!function(e){e.Required="Required",e.Supported="Supported",e.Unsupported="Unsupported"}(SIPExtension||(SIPExtension={}));var UserAgentRegisteredOptionTags={"100rel":!0,199:!0,answermode:!0,"early-session":!0,eventlist:!0,explicitsub:!0,"from-change":!0,"geolocation-http":!0,"geolocation-sip":!0,gin:!0,gruu:!0,histinfo:!0,ice:!0,join:!0,"multiple-refer":!0,norefersub:!0,nosub:!0,outbound:!0,path:!0,policy:!0,precondition:!0,pref:!0,privacy:!0,"recipient-list-invite":!0,"recipient-list-message":!0,"recipient-list-subscribe":!0,replaces:!0,"resource-priority":!0,"sdp-anat":!0,"sec-agree":!0,tdialog:!0,timer:!0,uui:!0},Invitation=function(e){function t(t,n){var r=e.call(this,t)||this;r.incomingInviteRequest=n,r.disposed=!1,r.expiresTimer=void 0,r.isCanceled=!1,r.rel100="none",r.rseq=Math.floor(1e4*Math.random()),r.userNoAnswerTimer=void 0,r.waitingForPrack=!1,r.logger=t.getLogger("sip.Invitation");var i=r.incomingInviteRequest.message,s=i.getHeader("require");s&&s.toLowerCase().includes("100rel")&&(r.rel100="required");var o=i.getHeader("supported");if(o&&o.toLowerCase().includes("100rel")&&(r.rel100="supported"),i.toTag=n.toTag,"string"!=typeof i.toTag)throw new TypeError("toTag should have been a string.");if(r.userNoAnswerTimer=setTimeout(function(){n.reject({statusCode:480}),r.stateTransition(SessionState.Terminated)},r.userAgent.configuration.noAnswerTimeout?1e3*r.userAgent.configuration.noAnswerTimeout:6e4),i.hasHeader("expires")){var a=1e3*Number(i.getHeader("expires")||0);r.expiresTimer=setTimeout(function(){r.state===SessionState.Initial&&(n.reject({statusCode:487}),r.stateTransition(SessionState.Terminated))},a)}var c=r.request.getHeader("P-Asserted-Identity");c&&(r._assertedIdentity=Grammar.nameAddrHeaderParse(c)),r._contact=r.userAgent.contact.toString();var u=i.parseHeader("Content-Disposition");return u&&"render"===u.type&&(r._renderbody=i.body,r._rendertype=i.getHeader("Content-Type")),r._id=i.callId+i.fromTag,r.userAgent._sessions[r._id]=r,r}return __extends$1(t,e),t.prototype.dispose=function(){var t=this;if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.expiresTimer&&(clearTimeout(this.expiresTimer),this.expiresTimer=void 0),this.userNoAnswerTimer&&(clearTimeout(this.userNoAnswerTimer),this.userNoAnswerTimer=void 0),this.prackNeverArrived(),this.state){case SessionState.Initial:case SessionState.Establishing:return this.reject().then(function(){return e.prototype.dispose.call(t)});case SessionState.Established:case SessionState.Terminating:case SessionState.Terminated:return e.prototype.dispose.call(this);default:throw new Error("Unknown state.")}},Object.defineProperty(t.prototype,"autoSendAnInitialProvisionalResponse",{get:function(){return"required"!==this.rel100&&this.userAgent.configuration.sendInitialProvisionalResponse},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"body",{get:function(){return this.incomingInviteRequest.message.body},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"localIdentity",{get:function(){return this.request.to},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"remoteIdentity",{get:function(){return this.request.from},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"request",{get:function(){return this.incomingInviteRequest.message},enumerable:!1,configurable:!0}),t.prototype.accept=function(e){var t=this;if(void 0===e&&(e={}),this.logger.log("Invitation.accept"),this.state!==SessionState.Initial){var n=new Error("Invalid session state ".concat(this.state));return this.logger.error(n.message),Promise.reject(n)}return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.stateTransition(SessionState.Establishing),this.sendAccept(e).then(function(e){e.message;var n=e.session;n.delegate={onAck:function(e){return t.onAckRequest(e)},onAckTimeout:function(){return t.onAckTimeout()},onBye:function(e){return t.onByeRequest(e)},onInfo:function(e){return t.onInfoRequest(e)},onInvite:function(e){return t.onInviteRequest(e)},onMessage:function(e){return t.onMessageRequest(e)},onNotify:function(e){return t.onNotifyRequest(e)},onPrack:function(e){return t.onPrackRequest(e)},onRefer:function(e){return t.onReferRequest(e)}},t._dialog=n,t.stateTransition(SessionState.Established),t._replacee&&t._replacee._bye()}).catch(function(e){return t.handleResponseError(e)})},t.prototype.progress=function(e){var t=this;if(void 0===e&&(e={}),this.logger.log("Invitation.progress"),this.state!==SessionState.Initial){var n=new Error("Invalid session state ".concat(this.state));return this.logger.error(n.message),Promise.reject(n)}var r=e.statusCode||180;if(r<100||r>199)throw new TypeError("Invalid statusCode: "+r);return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.waitingForPrack?(this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),Promise.resolve()):100===e.statusCode?this.sendProgressTrying().then(function(){}).catch(function(e){return t.handleResponseError(e)}):"required"===this.rel100||"supported"===this.rel100&&e.rel100||"supported"===this.rel100&&this.userAgent.configuration.sipExtension100rel===SIPExtension.Required?this.sendProgressReliableWaitForPrack(e).then(function(){}).catch(function(e){return t.handleResponseError(e)}):this.sendProgress(e).then(function(){}).catch(function(e){return t.handleResponseError(e)})},t.prototype.reject=function(e){if(void 0===e&&(e={}),this.logger.log("Invitation.reject"),this.state!==SessionState.Initial&&this.state!==SessionState.Establishing){var t=new Error("Invalid session state ".concat(this.state));return this.logger.error(t.message),Promise.reject(t)}var n=e.statusCode||480,r=e.reasonPhrase?e.reasonPhrase:getReasonPhrase(n),i=e.extraHeaders||[];if(n<300||n>699)throw new TypeError("Invalid statusCode: "+n);var s=e.body?fromBodyLegacy(e.body):void 0;return n<400?this.incomingInviteRequest.redirect([],{statusCode:n,reasonPhrase:r,extraHeaders:i,body:s}):this.incomingInviteRequest.reject({statusCode:n,reasonPhrase:r,extraHeaders:i,body:s}),this.stateTransition(SessionState.Terminated),Promise.resolve()},t.prototype._onCancel=function(e){this.logger.log("Invitation._onCancel"),this.state===SessionState.Initial||this.state===SessionState.Establishing?(this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(SessionState.Terminated)):this.logger.error("CANCEL received while in state ".concat(this.state,", dropping request"))},t.prototype.handlePrackOfferAnswer=function(e){if(!this.dialog)throw new Error("Dialog undefined.");var t=getBody(e.message);if(!t||"session"!==t.contentDisposition)return Promise.resolve(void 0);var n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case SignalingState.Initial:throw new Error("Invalid signaling state ".concat(this.dialog.signalingState,"."));case SignalingState.Stable:return this.setAnswer(t,n).then(function(){});case SignalingState.HaveLocalOffer:throw new Error("Invalid signaling state ".concat(this.dialog.signalingState,"."));case SignalingState.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,n);case SignalingState.Closed:default:throw new Error("Invalid signaling state ".concat(this.dialog.signalingState,"."))}},t.prototype.handleResponseError=function(e){var t=480;if(e instanceof Error?this.logger.error(e.message):this.logger.error(e),e instanceof ContentTypeUnsupportedError?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof SessionDescriptionHandlerError?this.logger.error("A session description handler occurred while sending response"):e instanceof SessionTerminatedError?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof TransactionStateError&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===SessionState.Initial||this.state===SessionState.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(SessionState.Terminated)}catch(e){throw this.logger.error("An error occurred attempting to reject the request while handling another error"),e}if(!this.isCanceled)throw e;this.logger.warn("An error occurred while attempting to formulate and send a response to an incoming INVITE. However a CANCEL was received and processed while doing so which can (and often does) result in errors occurring as the session terminates in the meantime. Said error is being ignored.")},t.prototype.onAckTimeout=function(){if(this.logger.log("Invitation.onAckTimeout"),!this.dialog)throw new Error("Dialog undefined.");this.logger.log("No ACK received for an extended period of time, terminating session"),this.dialog.bye(),this.stateTransition(SessionState.Terminated)},t.prototype.sendAccept=function(e){var t=this;void 0===e&&(e={});var n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},r=e.extraHeaders||[];return this.waitingForPrack?this.waitForArrivalOfPrack().then(function(){return clearTimeout(t.userNoAnswerTimer)}).then(function(){return t.generateResponseOfferAnswer(t.incomingInviteRequest,n)}).then(function(e){return t.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:r})}):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,n).then(function(e){return t.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:r})}))},t.prototype.sendProgress=function(e){void 0===e&&(e={});var t=e.statusCode||180,n=e.reasonPhrase,r=(e.extraHeaders||[]).slice(),i=e.body?fromBodyLegacy(e.body):void 0;if(183===t&&!i)return this.sendProgressWithSDP(e);try{var s=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:n,extraHeaders:r,body:i});return this._dialog=s.session,Promise.resolve(s)}catch(e){return Promise.reject(e)}},t.prototype.sendProgressWithSDP=function(e){var t=this;void 0===e&&(e={});var n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},r=e.statusCode||183,i=e.reasonPhrase,s=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,n).then(function(e){return t.incomingInviteRequest.progress({statusCode:r,reasonPhrase:i,extraHeaders:s,body:e})}).then(function(e){return t._dialog=e.session,e})},t.prototype.sendProgressReliable=function(e){return void 0===e&&(e={}),e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this.sendProgressWithSDP(e)},t.prototype.sendProgressReliableWaitForPrack=function(e){var t=this;void 0===e&&(e={});var n,r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.statusCode||183,s=e.reasonPhrase,o=(e.extraHeaders||[]).slice();return o.push("Require: 100rel"),o.push("RSeq: "+this.rseq++),new Promise(function(e,a){t.waitingForPrack=!0,t.generateResponseOfferAnswer(t.incomingInviteRequest,r).then(function(e){return n=e,t.incomingInviteRequest.progress({statusCode:i,reasonPhrase:s,extraHeaders:o,body:n})}).then(function(r){var c,u;t._dialog=r.session,r.session.delegate={onPrack:function(n){c=n,clearTimeout(l),clearTimeout(p),t.waitingForPrack&&(t.waitingForPrack=!1,t.handlePrackOfferAnswer(c).then(function(n){try{u=c.accept({statusCode:200,body:n}),t.prackArrived(),e({prackRequest:c,prackResponse:u,progressResponse:r})}catch(e){a(e)}}).catch(function(e){return a(e)}))}};var l=setTimeout(function(){t.waitingForPrack&&(t.waitingForPrack=!1,t.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(p),t.reject({statusCode:504}).then(function(){return a(new SessionTerminatedError)}).catch(function(e){return a(e)}))},64*Timers.T1),h=function(){try{t.incomingInviteRequest.progress({statusCode:i,reasonPhrase:s,extraHeaders:o,body:n})}catch(e){return t.waitingForPrack=!1,void a(e)}p=setTimeout(h,d*=2)},d=Timers.T1,p=setTimeout(h,d)}).catch(function(e){t.waitingForPrack=!1,a(e)})})},t.prototype.sendProgressTrying=function(){try{var e=this.incomingInviteRequest.trying();return Promise.resolve(e)}catch(e){return Promise.reject(e)}},t.prototype.waitForArrivalOfPrack=function(){var e=this;if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise(function(t,n){e.waitingForPrackResolve=t,e.waitingForPrackReject=n}),this.waitingForPrackPromise},t.prototype.prackArrived=function(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0},t.prototype.prackNeverArrived=function(){this.waitingForPrackReject&&this.waitingForPrackReject(new SessionTerminatedError),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0},t}(Session),Inviter=function(e){function t(t,n,r){void 0===r&&(r={});var i=e.call(this,t,r)||this;i.disposed=!1,i.earlyMedia=!1,i.earlyMediaSessionDescriptionHandlers=new Map,i.isCanceled=!1,i.inviteWithoutSdp=!1,i.logger=t.getLogger("sip.Inviter"),i.earlyMedia=void 0!==r.earlyMedia?r.earlyMedia:i.earlyMedia,i.fromTag=newTag(),i.inviteWithoutSdp=void 0!==r.inviteWithoutSdp?r.inviteWithoutSdp:i.inviteWithoutSdp;var s=__assign({},r);s.params=__assign({},r.params);var o=r.anonymous||!1,a=t.contact.toString({anonymous:o,outbound:o?!t.contact.tempGruu:!t.contact.pubGruu});o&&t.configuration.uri&&(s.params.fromDisplayName="Anonymous",s.params.fromUri="sip:anonymous@anonymous.invalid");var c=t.userAgentCore.configuration.aor;if(s.params.fromUri&&(c="string"==typeof s.params.fromUri?Grammar.URIParse(s.params.fromUri):s.params.fromUri),!c)throw new TypeError("Invalid from URI: "+s.params.fromUri);var u=n;if(s.params.toUri&&(u="string"==typeof s.params.toUri?Grammar.URIParse(s.params.toUri):s.params.toUri),!u)throw new TypeError("Invalid to URI: "+s.params.toUri);var l=__assign({},s.params);l.fromTag=i.fromTag;var h=(s.extraHeaders||[]).slice();o&&t.configuration.uri&&(h.push("P-Preferred-Identity: "+t.configuration.uri.toString()),h.push("Privacy: id")),h.push("Contact: "+a),h.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.configuration.sipExtension100rel===SIPExtension.Required&&h.push("Require: 100rel"),t.configuration.sipExtensionReplaces===SIPExtension.Required&&h.push("Require: replaces"),s.extraHeaders=h;return i.outgoingRequestMessage=t.userAgentCore.makeOutgoingRequestMessage(C.INVITE,n,c,u,l,h,undefined),i._contact=a,i._referralInviterOptions=s,i._renderbody=r.renderbody,i._rendertype=r.rendertype,r.sessionDescriptionHandlerModifiers&&(i.sessionDescriptionHandlerModifiers=r.sessionDescriptionHandlerModifiers),r.sessionDescriptionHandlerOptions&&(i.sessionDescriptionHandlerOptions=r.sessionDescriptionHandlerOptions),r.sessionDescriptionHandlerModifiersReInvite&&(i.sessionDescriptionHandlerModifiersReInvite=r.sessionDescriptionHandlerModifiersReInvite),r.sessionDescriptionHandlerOptionsReInvite&&(i.sessionDescriptionHandlerOptionsReInvite=r.sessionDescriptionHandlerOptionsReInvite),i._id=i.outgoingRequestMessage.callId+i.fromTag,i.userAgent._sessions[i._id]=i,i}return __extends$1(t,e),t.prototype.dispose=function(){var t=this;if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.disposeEarlyMedia(),this.state){case SessionState.Initial:case SessionState.Establishing:return this.cancel().then(function(){return e.prototype.dispose.call(t)});case SessionState.Established:case SessionState.Terminating:case SessionState.Terminated:return e.prototype.dispose.call(this);default:throw new Error("Unknown state.")}},Object.defineProperty(t.prototype,"body",{get:function(){return this.outgoingRequestMessage.body},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"localIdentity",{get:function(){return this.outgoingRequestMessage.from},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"remoteIdentity",{get:function(){return this.outgoingRequestMessage.to},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"request",{get:function(){return this.outgoingRequestMessage},enumerable:!1,configurable:!0}),t.prototype.cancel=function(e){if(void 0===e&&(e={}),this.logger.log("Inviter.cancel"),this.state!==SessionState.Initial&&this.state!==SessionState.Establishing){var t=new Error("Invalid session state ".concat(this.state));return this.logger.error(t.message),Promise.reject(t)}if(this.isCanceled=!0,this.stateTransition(SessionState.Terminating),this.outgoingInviteRequest){var n=void 0;e.statusCode&&e.reasonPhrase&&(n=function(e,t){if(e&&e<200||e>699)throw new TypeError("Invalid statusCode: "+e);if(e)return"SIP;cause="+e+';text="'+(getReasonPhrase(e)||t)+'"'}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(n,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(SessionState.Terminated);return Promise.resolve()},t.prototype.invite=function(t){var n=this;if(void 0===t&&(t={}),this.logger.log("Inviter.invite"),this.state!==SessionState.Initial)return e.prototype.invite.call(this,t);if(t.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=t.sessionDescriptionHandlerModifiers),t.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=t.sessionDescriptionHandlerOptions),t.withoutSdp||this.inviteWithoutSdp)return this._renderbody&&this._rendertype&&(this.outgoingRequestMessage.body={contentType:this._rendertype,body:this._renderbody}),this.stateTransition(SessionState.Establishing),Promise.resolve(this.sendInvite(t));var r={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(r).then(function(e){return n.outgoingRequestMessage.body={body:e.content,contentType:e.contentType},n.stateTransition(SessionState.Establishing),n.sendInvite(t)}).catch(function(e){throw n.logger.log(e.message),n.stateTransition(SessionState.Terminated),e})},t.prototype.sendInvite=function(e){var t=this;return void 0===e&&(e={}),this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:function(n){return t.dialog?(t.logger.log("Additional confirmed dialog, sending ACK and BYE"),void t.ackAndBye(n)):t.isCanceled?(t.logger.log("Canceled session accepted, sending ACK and BYE"),t.ackAndBye(n),void t.stateTransition(SessionState.Terminated)):(t.notifyReferer(n),void t.onAccept(n).then(function(){t.disposeEarlyMedia()}).catch(function(){t.disposeEarlyMedia()}).then(function(){e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(n)}))},onProgress:function(n){t.isCanceled||(t.notifyReferer(n),t.onProgress(n).catch(function(){t.disposeEarlyMedia()}).then(function(){e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(n)}))},onRedirect:function(n){t.notifyReferer(n),t.onRedirect(n),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(n)},onReject:function(n){t.notifyReferer(n),t.onReject(n),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(n)},onTrying:function(n){t.notifyReferer(n),t.onTrying(n),e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(n)}}),this.outgoingInviteRequest},t.prototype.disposeEarlyMedia=function(){this.earlyMediaSessionDescriptionHandlers.forEach(function(e){e.close()}),this.earlyMediaSessionDescriptionHandlers.clear()},t.prototype.notifyReferer=function(e){var t=this;if(this._referred){if(!(this._referred instanceof Session))throw new Error("Referred session not instance of session");if(this._referred.dialog){if(!e.message.statusCode)throw new Error("Status code undefined.");if(!e.message.reasonPhrase)throw new Error("Reason phrase undefined.");var n=e.message.statusCode,r=e.message.reasonPhrase,i="SIP/2.0 ".concat(n," ").concat(r).trim();this._referred.dialog.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:i}}).delegate={onReject:function(){t._referred=void 0}}}}},t.prototype.onAccept=function(e){var t=this;if(this.logger.log("Inviter.onAccept"),this.state!==SessionState.Establishing)return this.logger.error("Accept received while in state ".concat(this.state,", dropping response")),Promise.reject(new Error("Invalid session state ".concat(this.state)));var n=e.message,r=e.session;switch(n.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=Grammar.nameAddrHeaderParse(n.getHeader("P-Asserted-Identity"))),r.delegate={onAck:function(e){return t.onAckRequest(e)},onBye:function(e){return t.onByeRequest(e)},onInfo:function(e){return t.onInfoRequest(e)},onInvite:function(e){return t.onInviteRequest(e)},onMessage:function(e){return t.onMessageRequest(e)},onNotify:function(e){return t.onNotifyRequest(e)},onPrack:function(e){return t.onPrackRequest(e)},onRefer:function(e){return t.onReferRequest(e)}},this._dialog=r,r.signalingState){case SignalingState.Initial:case SignalingState.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(SessionState.Terminated),Promise.reject(new Error("Bad Media Description"));case SignalingState.HaveRemoteOffer:if(!this._dialog.offer)throw new Error("Session offer undefined in signaling state ".concat(this._dialog.signalingState,"."));var i={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,i).then(function(n){e.ack({body:n}),t.stateTransition(SessionState.Established)}).catch(function(n){throw t.ackAndBye(e,488,"Invalid session description"),t.stateTransition(SessionState.Terminated),n});case SignalingState.Stable:if(this.earlyMediaSessionDescriptionHandlers.size>0){var s=this.earlyMediaSessionDescriptionHandlers.get(r.id);if(!s)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(s),this.earlyMediaSessionDescriptionHandlers.delete(r.id),e.ack(),this.stateTransition(SessionState.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==r){if(this.earlyMedia){this.logger.error("You have set the 'earlyMedia' option to 'true' which requires that your INVITE requests do not fork and yet this INVITE request did in fact fork. Consequentially and not surprisingly the end point which accepted the INVITE (confirmed dialog) does not match the end point with which early media has been setup (early dialog) and thus this session is unable to proceed. In accordance with the SIP specifications, the SIP servers your end point is connected to determine if an INVITE forks and the forking behavior of those servers cannot be controlled by this library. If you wish to use early media with this library you must configure those servers accordingly. Alternatively you may set the 'earlyMedia' to 'false' which will allow this library to function with any INVITE requests which do fork.")}var o=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(o.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(SessionState.Terminated),Promise.reject(o)}return e.ack(),this.stateTransition(SessionState.Established),Promise.resolve()}var a=r.answer;if(!a)throw new Error("Answer is undefined.");i={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(a,i).then(function(){var n;t._renderbody&&t._rendertype&&(n={body:{contentDisposition:"render",contentType:t._rendertype,content:t._renderbody}}),e.ack(n),t.stateTransition(SessionState.Established)}).catch(function(n){throw t.logger.error(n.message),t.ackAndBye(e,488,"Not Acceptable Here"),t.stateTransition(SessionState.Terminated),n});case SignalingState.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}},t.prototype.onProgress=function(e){var t,n=this;if(this.logger.log("Inviter.onProgress"),this.state!==SessionState.Establishing)return this.logger.error("Progress received while in state ".concat(this.state,", dropping response")),Promise.reject(new Error("Invalid session state ".concat(this.state)));if(!this.outgoingInviteRequest)throw new Error("Outgoing INVITE request undefined.");var r=e.message,i=e.session;r.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=Grammar.nameAddrHeaderParse(r.getHeader("P-Asserted-Identity")));var s=r.getHeader("require"),o=r.getHeader("rseq"),a=!!(s&&s.includes("100rel")&&o?Number(o):void 0),c=[];switch(a&&c.push("RAck: "+r.getHeader("rseq")+" "+r.getHeader("cseq")),i.signalingState){case SignalingState.Initial:return a&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:c})),Promise.resolve();case SignalingState.HaveLocalOffer:return a&&e.prack({extraHeaders:c}),Promise.resolve();case SignalingState.HaveRemoteOffer:if(!a)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();var u=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(t=this.delegate)||void 0===t?void 0:t.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(u,!0),this.earlyMediaSessionDescriptionHandlers.set(i.id,u),u.setDescription(r.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then(function(){return u.getDescription(n.sessionDescriptionHandlerOptions,n.sessionDescriptionHandlerModifiers)}).then(function(t){var n={contentDisposition:"session",contentType:t.contentType,content:t.body};e.prack({extraHeaders:c,body:n})}).catch(function(e){throw n.stateTransition(SessionState.Terminated),e});case SignalingState.Stable:if(a&&e.prack({extraHeaders:c}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=i;var l=i.answer;if(!l)throw new Error("Answer is undefined.");var h={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(l,h).catch(function(e){throw n.stateTransition(SessionState.Terminated),e})}return Promise.resolve();case SignalingState.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}},t.prototype.onRedirect=function(e){this.logger.log("Inviter.onRedirect"),this.state===SessionState.Establishing||this.state===SessionState.Terminating?this.stateTransition(SessionState.Terminated):this.logger.error("Redirect received while in state ".concat(this.state,", dropping response"))},t.prototype.onReject=function(e){this.logger.log("Inviter.onReject"),this.state===SessionState.Establishing||this.state===SessionState.Terminating?this.stateTransition(SessionState.Terminated):this.logger.error("Reject received while in state ".concat(this.state,", dropping response"))},t.prototype.onTrying=function(e){this.logger.log("Inviter.onTrying"),this.state===SessionState.Establishing||this.logger.error("Trying received while in state ".concat(this.state,", dropping response"))},t}(Session),Messager=function(){function e(e,t,n,r,i){void 0===r&&(r="text/plain"),void 0===i&&(i={}),this.logger=e.getLogger("sip.Messager"),i.params=i.params||{};var s=e.userAgentCore.configuration.aor;if(i.params.fromUri&&(s="string"==typeof i.params.fromUri?Grammar.URIParse(i.params.fromUri):i.params.fromUri),!s)throw new TypeError("Invalid from URI: "+i.params.fromUri);var o=t;if(i.params.toUri&&(o="string"==typeof i.params.toUri?Grammar.URIParse(i.params.toUri):i.params.toUri),!o)throw new TypeError("Invalid to URI: "+i.params.toUri);var a=i.params?__assign({},i.params):{},c=(i.extraHeaders||[]).slice(),u={contentDisposition:"render",contentType:r,content:n};this.request=e.userAgentCore.makeOutgoingRequestMessage(C.MESSAGE,t,s,o,a,c,u),this.userAgent=e}return e.prototype.message=function(e){return void 0===e&&(e={}),this.userAgent.userAgentCore.request(this.request,e.requestDelegate),Promise.resolve()},e}(),PublisherState,RegistererState;!function(e){e.Initial="Initial",e.Published="Published",e.Unpublished="Unpublished",e.Terminated="Terminated"}(PublisherState||(PublisherState={})),function(){function e(e,t,n,r){void 0===r&&(r={}),this.disposed=!1,this._state=PublisherState.Initial,this._stateEventEmitter=new EmitterImpl,this.userAgent=e,r.extraHeaders=(r.extraHeaders||[]).slice(),r.contentType=r.contentType||"text/plain","number"!=typeof r.expires||r.expires%1!=0?r.expires=3600:r.expires=Number(r.expires),"boolean"!=typeof r.unpublishOnClose&&(r.unpublishOnClose=!0),this.target=t,this.event=n,this.options=r,this.pubRequestExpires=r.expires,this.logger=e.getLogger("sip.Publisher");var i,s=r.params||{},o=s.fromUri?s.fromUri:e.userAgentCore.configuration.aor,a=s.toUri?s.toUri:t;if(r.body&&r.contentType){i={contentDisposition:"render",contentType:r.contentType,content:r.body}}var c=(r.extraHeaders||[]).slice();this.request=e.userAgentCore.makeOutgoingRequestMessage(C.PUBLISH,t,o,a,s,c,i),this.id=this.target.toString()+":"+this.event,this.userAgent._publishers[this.id]=this}e.prototype.dispose=function(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log("Publisher ".concat(this.id," in state ").concat(this.state," is being disposed")),delete this.userAgent._publishers[this.id],this.options.unpublishOnClose&&this.state===PublisherState.Published?this.unpublish():(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,this.pubRequestEtag=void 0,Promise.resolve()))},Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),e.prototype.publish=function(e,t){if(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.options.body=e,this.pubRequestBody=this.options.body,0===this.pubRequestExpires){if(void 0===this.options.expires)throw new Error("Expires undefined.");this.pubRequestExpires=this.options.expires,this.pubRequestEtag=void 0}return this.sendPublishRequest(),Promise.resolve()},e.prototype.unpublish=function(e){return this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestExpires=0,void 0!==this.pubRequestEtag&&this.sendPublishRequest(),Promise.resolve()},e.prototype.receiveResponse=function(e){var t=this,n=e.statusCode||0;switch(!0){case/^1[0-9]{2}$/.test(n.toString()):break;case/^2[0-9]{2}$/.test(n.toString()):if(e.hasHeader("SIP-ETag")?this.pubRequestEtag=e.getHeader("SIP-ETag"):this.logger.warn("SIP-ETag header missing in a 200-class response to PUBLISH"),e.hasHeader("Expires")){var r=Number(e.getHeader("Expires"));"number"==typeof r&&r>=0&&r<=this.pubRequestExpires?this.pubRequestExpires=r:this.logger.warn("Bad Expires header in a 200-class response to PUBLISH")}else this.logger.warn("Expires header missing in a 200-class response to PUBLISH");0!==this.pubRequestExpires?(this.publishRefreshTimer=setTimeout(function(){return t.refreshRequest()},900*this.pubRequestExpires),this._state!==PublisherState.Published&&this.stateTransition(PublisherState.Published)):this.stateTransition(PublisherState.Unpublished);break;case/^412$/.test(n.toString()):if(void 0!==this.pubRequestEtag&&0!==this.pubRequestExpires){if(this.logger.warn("412 response to PUBLISH, recovering"),this.pubRequestEtag=void 0,void 0===this.options.body)throw new Error("Body undefined.");this.publish(this.options.body)}else this.logger.warn("412 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.stateTransition(PublisherState.Unpublished),this.stateTransition(PublisherState.Terminated);break;case/^423$/.test(n.toString()):if(0!==this.pubRequestExpires&&e.hasHeader("Min-Expires")){var i=Number(e.getHeader("Min-Expires"));if("number"==typeof i||i>this.pubRequestExpires){if(this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"),this.pubRequestExpires=i,void 0===this.options.body)throw new Error("Body undefined.");this.publish(this.options.body)}else this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"),this.pubRequestExpires=0,this.stateTransition(PublisherState.Unpublished),this.stateTransition(PublisherState.Terminated)}else this.logger.warn("423 response to PUBLISH, recovery failed"),this.pubRequestExpires=0,this.stateTransition(PublisherState.Unpublished),this.stateTransition(PublisherState.Terminated);break;default:this.pubRequestExpires=0,this.stateTransition(PublisherState.Unpublished),this.stateTransition(PublisherState.Terminated)}0===this.pubRequestExpires&&(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,this.pubRequestEtag=void 0)},e.prototype.send=function(){var e=this;return this.userAgent.userAgentCore.publish(this.request,{onAccept:function(t){return e.receiveResponse(t.message)},onProgress:function(t){return e.receiveResponse(t.message)},onRedirect:function(t){return e.receiveResponse(t.message)},onReject:function(t){return e.receiveResponse(t.message)},onTrying:function(t){return e.receiveResponse(t.message)}})},e.prototype.refreshRequest=function(){if(this.publishRefreshTimer&&(clearTimeout(this.publishRefreshTimer),this.publishRefreshTimer=void 0),this.pubRequestBody=void 0,void 0===this.pubRequestEtag)throw new Error("Etag undefined");if(0===this.pubRequestExpires)throw new Error("Expires zero");this.sendPublishRequest()},e.prototype.sendPublishRequest=function(){var e=__assign({},this.options);e.extraHeaders=(this.options.extraHeaders||[]).slice(),e.extraHeaders.push("Event: "+this.event),e.extraHeaders.push("Expires: "+this.pubRequestExpires),void 0!==this.pubRequestEtag&&e.extraHeaders.push("SIP-If-Match: "+this.pubRequestEtag);var t,n,r=this.target,i=this.options.params||{};if(void 0!==this.pubRequestBody){if(void 0===this.options.contentType)throw new Error("Content type undefined.");t={body:this.pubRequestBody,contentType:this.options.contentType}}return t&&(n=fromBodyLegacy(t)),this.request=this.userAgent.userAgentCore.makeOutgoingRequestMessage(C.PUBLISH,r,i.fromUri?i.fromUri:this.userAgent.userAgentCore.configuration.aor,i.toUri?i.toUri:this.target,i,e.extraHeaders,n),this.send()},e.prototype.stateTransition=function(e){var t=this,n=function(){throw new Error("Invalid state transition from ".concat(t._state," to ").concat(e))};switch(this._state){case PublisherState.Initial:e!==PublisherState.Published&&e!==PublisherState.Unpublished&&e!==PublisherState.Terminated&&n();break;case PublisherState.Published:e!==PublisherState.Unpublished&&e!==PublisherState.Terminated&&n();break;case PublisherState.Unpublished:e!==PublisherState.Published&&e!==PublisherState.Terminated&&n();break;case PublisherState.Terminated:n();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log("Publication transitioned to state ".concat(this._state)),this._stateEventEmitter.emit(this._state),e===PublisherState.Terminated&&this.dispose()}}(),function(e){e.Initial="Initial",e.Registered="Registered",e.Unregistered="Unregistered",e.Terminated="Terminated"}(RegistererState||(RegistererState={}));var Registerer=function(){function e(t,n){void 0===n&&(n={});var r=this;this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=RegistererState.Initial,this._waiting=!1,this._stateEventEmitter=new EmitterImpl,this._waitingEventEmitter=new EmitterImpl,this.userAgent=t;var i=t.configuration.uri.clone();if(i.user=void 0,this.options=__assign(__assign(__assign({},e.defaultOptions()),{registrar:i}),e.stripUndefinedProperties(n)),this.options.extraContactHeaderParams=(this.options.extraContactHeaderParams||[]).slice(),this.options.extraHeaders=(this.options.extraHeaders||[]).slice(),!this.options.registrar)throw new Error("Registrar undefined.");if(this.options.registrar=this.options.registrar.clone(),this.options.regId&&!this.options.instanceId?this.options.instanceId=e.newUUID():!this.options.regId&&this.options.instanceId&&(this.options.regId=1),this.options.instanceId&&-1===Grammar.parse(this.options.instanceId,"uuid"))throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");var s=this.options.registrar,o=this.options.params&&this.options.params.fromUri||t.userAgentCore.configuration.aor,a=this.options.params&&this.options.params.toUri||t.configuration.uri,c=this.options.params||{},u=(n.extraHeaders||[]).slice();if(this.request=t.userAgentCore.makeOutgoingRequestMessage(C.REGISTER,s,o,a,c,u,void 0),this.expires=this.options.expires||e.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||e.defaultRefreshFrequency,this.refreshFrequency<50||this.refreshFrequency>99)throw new Error("Invalid refresh frequency. The value represents a percentage of the expiration time and should be between 50 and 99.");this.logger=t.getLogger("sip.Registerer"),this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(function(e){var t=r.options[e];if("registrar"===e)r.logger.log("· "+e+": "+t);else r.logger.log("· "+e+": "+JSON.stringify(t))})),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}return e.defaultOptions=function(){return{expires:e.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new URI("sip","anonymous","anonymous.invalid"),refreshFrequency:e.defaultRefreshFrequency}},e.newUUID=function(){var e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=Math.floor(16*Math.random());return("x"===e?t:t%4+8).toString(16)});return e},e.stripUndefinedProperties=function(e){return Object.keys(e).reduce(function(t,n){return void 0!==e[n]&&(t[n]=e[n]),t},{})},Object.defineProperty(e.prototype,"contacts",{get:function(){return this._contacts.slice()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"retryAfter",{get:function(){return this._retryAfter},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){var e=this;return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log("Registerer ".concat(this.id," in state ").concat(this.state," is being disposed")),delete this.userAgent._registerers[this.id],new Promise(function(t){var n=function(){if(!e.waiting&&e._state===RegistererState.Registered)return e.stateChange.addListener(function(){e.terminated(),t()},{once:!0}),void e.unregister();e.terminated(),t()};e.waiting?e.waitingChange.addListener(function(){n()},{once:!0}):n()}))},e.prototype.register=function(e){var t=this;if(void 0===e&&(e={}),this.state===RegistererState.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();var n=new RequestPendingError("REGISTER request already in progress, waiting for final response");return Promise.reject(n)}e.requestOptions&&(this.options=__assign(__assign({},this.options),e.requestOptions));var r=(this.options.extraHeaders||[]).slice();r.push("Contact: "+this.generateContactHeader(this.expires)),r.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),this.request.extraHeaders=r,this.waitingToggle(!0);var i=this.userAgent.userAgentCore.register(this.request,{onAccept:function(n){var r;n.message.hasHeader("expires")&&(r=Number(n.message.getHeader("expires"))),t._contacts=n.message.getHeaders("contact");var i,s,o=t._contacts.length;if(!o)return t.logger.error("No Contact header in response to REGISTER, dropping response."),void t.unregistered();for(;o--;){if(!(i=n.message.parseHeader("contact",o)))throw new Error("Contact undefined");if(t.userAgent.contact.pubGruu&&equivalentURI(i.uri,t.userAgent.contact.pubGruu)){r=Number(i.getParam("expires"));break}if(""===t.userAgent.configuration.contactName){if(i.uri.user===t.userAgent.contact.uri.user){r=Number(i.getParam("expires"));break}}else if(equivalentURI(i.uri,t.userAgent.contact.uri)){r=Number(i.getParam("expires"));break}i=void 0}if(void 0===i)return t.logger.error("No Contact header pointing to us, dropping response"),t.unregistered(),void t.waitingToggle(!1);if(void 0===r)return t.logger.error("Contact pointing to us is missing expires parameter, dropping response"),t.unregistered(),void t.waitingToggle(!1);i.hasParam("temp-gruu")&&((s=i.getParam("temp-gruu"))&&(t.userAgent.contact.tempGruu=Grammar.URIParse(s.replace(/"/g,""))));i.hasParam("pub-gruu")&&((s=i.getParam("pub-gruu"))&&(t.userAgent.contact.pubGruu=Grammar.URIParse(s.replace(/"/g,""))));t.registered(r),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(n),t.waitingToggle(!1)},onProgress:function(t){e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:function(n){t.logger.error("Redirect received. Not supported."),t.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(n),t.waitingToggle(!1)},onReject:function(n){if(423===n.message.statusCode)return n.message.hasHeader("min-expires")?(t.expires=Number(n.message.getHeader("min-expires")),t.waitingToggle(!1),void t.register()):(t.logger.error("423 response received for REGISTER without Min-Expires, dropping response"),t.unregistered(),void t.waitingToggle(!1));t.logger.warn("Failed to register, status code ".concat(n.message.statusCode));var r=NaN;if(500===n.message.statusCode||503===n.message.statusCode){var i=n.message.getHeader("retry-after");i&&(r=Number.parseInt(i,void 0))}t._retryAfter=isNaN(r)?void 0:r,t.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(n),t._retryAfter=void 0,t.waitingToggle(!1)},onTrying:function(t){e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(i)},e.prototype.unregister=function(e){var t=this;if(void 0===e&&(e={}),this.state===RegistererState.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==RegistererState.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();var n=new RequestPendingError("REGISTER request already in progress, waiting for final response");return Promise.reject(n)}this._state===RegistererState.Registered||e.all||this.logger.warn("Not currently registered, but sending an unregister anyway.");var r=(e.requestOptions&&e.requestOptions.extraHeaders||[]).slice();this.request.extraHeaders=r,e.all?(r.push("Contact: *"),r.push("Expires: 0")):r.push("Contact: "+this.generateContactHeader(0)),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),this.waitingToggle(!0);var i=this.userAgent.userAgentCore.register(this.request,{onAccept:function(n){t._contacts=n.message.getHeaders("contact"),t.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(n),t.waitingToggle(!1)},onProgress:function(t){e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:function(n){t.logger.error("Unregister redirected. Not currently supported."),t.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(n),t.waitingToggle(!1)},onReject:function(n){t.logger.error("Unregister rejected with status code ".concat(n.message.statusCode)),t.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(n),t.waitingToggle(!1)},onTrying:function(t){e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(i)},e.prototype.clearTimers=function(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)},e.prototype.generateContactHeader=function(e){var t=this.userAgent.contact.toString();return this.options.regId&&this.options.instanceId&&(t+=";reg-id="+this.options.regId,t+=';+sip.instance="<urn:uuid:'+this.options.instanceId+'>"'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach(function(e){t+=";"+e}),t+=";expires="+e},e.prototype.registered=function(e){var t=this;this.clearTimers(),this.registrationTimer=setTimeout(function(){t.registrationTimer=void 0,t.register()},this.refreshFrequency/100*e*1e3),this.registrationExpiredTimer=setTimeout(function(){t.logger.warn("Registration expired"),t.unregistered()},1e3*e),this._state!==RegistererState.Registered&&this.stateTransition(RegistererState.Registered)},e.prototype.unregistered=function(){this.clearTimers(),this._state!==RegistererState.Unregistered&&this.stateTransition(RegistererState.Unregistered)},e.prototype.terminated=function(){this.clearTimers(),this._state!==RegistererState.Terminated&&this.stateTransition(RegistererState.Terminated)},e.prototype.stateTransition=function(e){var t=this,n=function(){throw new Error("Invalid state transition from ".concat(t._state," to ").concat(e))};switch(this._state){case RegistererState.Initial:e!==RegistererState.Registered&&e!==RegistererState.Unregistered&&e!==RegistererState.Terminated&&n();break;case RegistererState.Registered:e!==RegistererState.Unregistered&&e!==RegistererState.Terminated&&n();break;case RegistererState.Unregistered:e!==RegistererState.Registered&&e!==RegistererState.Terminated&&n();break;case RegistererState.Terminated:n();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log("Registration transitioned to state ".concat(this._state)),this._stateEventEmitter.emit(this._state),e===RegistererState.Terminated&&this.dispose()},Object.defineProperty(e.prototype,"waiting",{get:function(){return this._waiting},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"waitingChange",{get:function(){return this._waitingEventEmitter},enumerable:!1,configurable:!0}),e.prototype.waitingToggle=function(e){if(this._waiting===e)throw new Error("Invalid waiting transition from ".concat(this._waiting," to ").concat(e));this._waiting=e,this.logger.log("Waiting toggled to ".concat(this._waiting)),this._waitingEventEmitter.emit(this._waiting)},e.prototype.waitingWarning=function(){this.logger.warn("An attempt was made to send a REGISTER request while a prior one was still in progress. RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response from the registrar for the previous one or the previous REGISTER request has timed out. Note that if the transport disconnects, you still must wait for the prior request to time out before sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.")},e.prototype.stateError=function(){var e=this.state===RegistererState.Terminated?"is in 'Terminated' state":"has been disposed",t="An attempt was made to send a REGISTER request when the Registerer ".concat(e,".");t+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",t+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(t)},e.defaultExpires=600,e.defaultRefreshFrequency=99,e}(),SubscriptionState;!function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Subscribed="Subscribed",e.Terminated="Terminated"}(SubscriptionState||(SubscriptionState={}));var Subscription=function(){function e(e,t){void 0===t&&(t={}),this._disposed=!1,this._state=SubscriptionState.Initial,this._logger=e.getLogger("sip.Subscription"),this._stateEventEmitter=new EmitterImpl,this._userAgent=e,this.delegate=t.delegate}return e.prototype.dispose=function(){return this._disposed||(this._disposed=!0,this._stateEventEmitter.removeAllListeners()),Promise.resolve()},Object.defineProperty(e.prototype,"dialog",{get:function(){return this._dialog},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"disposed",{get:function(){return this._disposed},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),e.prototype.stateTransition=function(e){var t=this,n=function(){throw new Error("Invalid state transition from ".concat(t._state," to ").concat(e))};switch(this._state){case SubscriptionState.Initial:e!==SubscriptionState.NotifyWait&&e!==SubscriptionState.Terminated&&n();break;case SubscriptionState.NotifyWait:e!==SubscriptionState.Subscribed&&e!==SubscriptionState.Terminated&&n();break;case SubscriptionState.Subscribed:e!==SubscriptionState.Terminated&&n();break;case SubscriptionState.Terminated:n();break;default:throw new Error("Unrecognized state.")}this._state!==e&&(this._state=e,this._logger.log("Subscription ".concat(this._dialog?this._dialog.id:void 0," transitioned to ").concat(this._state)),this._stateEventEmitter.emit(this._state),e===SubscriptionState.Terminated&&this.dispose())},e}();!function(e){function t(t,n,r,i){void 0===i&&(i={});var s=e.call(this,t,i)||this;return s.body=void 0,s.logger=t.getLogger("sip.Subscriber"),i.body&&(s.body={body:i.body,contentType:i.contentType?i.contentType:"application/sdp"}),s.targetURI=n,s.event=r,void 0===i.expires?s.expires=3600:"number"!=typeof i.expires?(s.logger.warn('Option "expires" must be a number. Using default of 3600.'),s.expires=3600):s.expires=i.expires,s.extraHeaders=(i.extraHeaders||[]).slice(),s.subscriberRequest=s.initSubscriberRequest(),s.outgoingRequestMessage=s.subscriberRequest.message,s.id=s.outgoingRequestMessage.callId+s.outgoingRequestMessage.from.parameters.tag+s.event,s._userAgent._subscriptions[s.id]=s,s}__extends$1(t,e),t.prototype.dispose=function(){var t=this;return this.disposed?Promise.resolve():(this.logger.log("Subscription ".concat(this.id," in state ").concat(this.state," is being disposed")),delete this._userAgent._subscriptions[this.id],this.retryAfterTimer&&(clearTimeout(this.retryAfterTimer),this.retryAfterTimer=void 0),this.subscriberRequest.dispose(),e.prototype.dispose.call(this).then(function(){if(t.state===SubscriptionState.Subscribed){if(!t._dialog)throw new Error("Dialog undefined.");if(t._dialog.subscriptionState===SubscriptionState$1.Pending||t._dialog.subscriptionState===SubscriptionState$1.Active){var e=t._dialog;return new Promise(function(t,n){e.delegate={onTerminated:function(){return t()}},e.unsubscribe()})}}}))},t.prototype.subscribe=function(e){var t=this;switch(this.subscriberRequest.state){case SubscriptionState$1.Initial:this.state===SubscriptionState.Initial&&this.stateTransition(SubscriptionState.NotifyWait),this.subscriberRequest.subscribe().then(function(e){e.success?(e.success.subscription&&(t._dialog=e.success.subscription,t._dialog.delegate={onNotify:function(e){return t.onNotify(e)},onRefresh:function(e){return t.onRefresh(e)},onTerminated:function(){t.state!==SubscriptionState.Terminated&&t.stateTransition(SubscriptionState.Terminated)}}),t.onNotify(e.success.request)):e.failure&&t.unsubscribe()});break;case SubscriptionState$1.NotifyWait:case SubscriptionState$1.Pending:break;case SubscriptionState$1.Active:if(this._dialog)this._dialog.refresh().delegate={onAccept:function(e){return t.onAccepted(e)},onRedirect:function(e){return t.unsubscribe()},onReject:function(e){return t.unsubscribe()}};case SubscriptionState$1.Terminated:}return Promise.resolve()},t.prototype.unsubscribe=function(e){if(this.disposed)return Promise.resolve();switch(this.subscriberRequest.state){case SubscriptionState$1.Initial:case SubscriptionState$1.NotifyWait:break;case SubscriptionState$1.Pending:case SubscriptionState$1.Active:this._dialog&&this._dialog.unsubscribe();break;case SubscriptionState$1.Terminated:break;default:throw new Error("Unknown state.")}return this.stateTransition(SubscriptionState.Terminated),Promise.resolve()},t.prototype._refresh=function(){return this.subscriberRequest.state===SubscriptionState$1.Active?this.subscribe():Promise.resolve()},t.prototype.onAccepted=function(e){},t.prototype.onNotify=function(e){var t=this;if(this.disposed)e.accept();else{if(this.state!==SubscriptionState.Subscribed&&this.stateTransition(SubscriptionState.Subscribed),this.delegate&&this.delegate.onNotify){var n=new Notification(e);this.delegate.onNotify(n)}else e.accept();var r=e.message.parseHeader("Subscription-State");if(r&&r.state&&"terminated"===r.state){if(r.reason)switch(this.logger.log("Terminated subscription with reason ".concat(r.reason)),r.reason){case"deactivated":case"timeout":return this.initSubscriberRequest(),void this.subscribe();case"probation":case"giveup":return this.initSubscriberRequest(),void(r.params&&r.params["retry-after"]?this.retryAfterTimer=setTimeout(function(){t.subscribe()},r.params["retry-after"]):this.subscribe())}this.unsubscribe()}}},t.prototype.onRefresh=function(e){var t=this;e.delegate={onAccept:function(e){return t.onAccepted(e)}}},t.prototype.initSubscriberRequest=function(){var e=this,t={extraHeaders:this.extraHeaders,body:this.body?fromBodyLegacy(this.body):void 0};return this.subscriberRequest=new SubscriberRequest(this._userAgent.userAgentCore,this.targetURI,this.event,this.expires,t),this.subscriberRequest.delegate={onAccept:function(t){return e.onAccepted(t)}},this.subscriberRequest}}(Subscription);var SubscriberRequest=function(){function e(e,t,n,r,i,s){this.core=e,this.target=t,this.event=n,this.expires=r,this.subscribed=!1,this.logger=e.loggerFactory.getLogger("sip.Subscriber"),this.delegate=s;var o="Allow: "+AllowedMethods.toString(),a=(i&&i.extraHeaders||[]).slice();a.push(o),a.push("Event: "+this.event),a.push("Expires: "+this.expires),a.push("Contact: "+this.core.configuration.contact.toString());var c=i&&i.body;this.message=e.makeOutgoingRequestMessage(C.SUBSCRIBE,this.target,this.core.configuration.aor,this.target,{},a,c)}return e.prototype.dispose=function(){this.request&&(this.request.waitNotifyStop(),this.request.dispose(),this.request=void 0)},Object.defineProperty(e.prototype,"state",{get:function(){return this.subscription?this.subscription.subscriptionState:this.subscribed?SubscriptionState$1.NotifyWait:SubscriptionState$1.Initial},enumerable:!1,configurable:!0}),e.prototype.subscribe=function(){var e=this;return this.subscribed?Promise.reject(new Error("Not in initial state. Did you call subscribe more than once?")):(this.subscribed=!0,new Promise(function(t){if(!e.message)throw new Error("Message undefined.");e.request=e.core.subscribe(e.message,{onAccept:function(t){e.delegate&&e.delegate.onAccept&&e.delegate.onAccept(t)},onNotify:function(n){e.subscription=n.subscription,e.subscription&&(e.subscription.autoRefresh=!0),t({success:n})},onNotifyTimeout:function(){t({failure:{}})},onRedirect:function(e){t({failure:{response:e}})},onReject:function(e){t({failure:{response:e}})}})}))},e}(),TransportState,UserAgentState;function defaultMediaStreamFactory(){return function(e){return e.audio||e.video?void 0===navigator.mediaDevices?Promise.reject(new Error("Media devices not available in insecure contexts.")):navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices,e):Promise.resolve(new MediaStream)}}function defaultPeerConnectionConfiguration(){return{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",peerIdentity:void 0,rtcpMuxPolicy:"require"}}!function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(TransportState||(TransportState={})),function(e){e.Started="Started",e.Stopped="Stopped"}(UserAgentState||(UserAgentState={}));var SessionDescriptionHandler=function(){function e(e,t,n){e.debug("SessionDescriptionHandler.constructor"),this.logger=e,this.mediaStreamFactory=t,this.sessionDescriptionHandlerConfiguration=n,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==n?void 0:n.peerConnectionConfiguration),this.initPeerConnectionEventHandlers()}return Object.defineProperty(e.prototype,"localMediaStream",{get:function(){return this._localMediaStream},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteMediaStream",{get:function(){return this._remoteMediaStream},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dataChannel",{get:function(){return this._dataChannel},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"peerConnection",{get:function(){return this._peerConnection},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"peerConnectionDelegate",{get:function(){return this._peerConnectionDelegate},set:function(e){this._peerConnectionDelegate=e},enumerable:!1,configurable:!0}),e.dispatchAddTrackEvent=function(e,t){e.dispatchEvent(new MediaStreamTrackEvent("addtrack",{track:t}))},e.dispatchRemoveTrackEvent=function(e,t){e.dispatchEvent(new MediaStreamTrackEvent("removetrack",{track:t}))},e.prototype.close=function(){this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this._peerConnection.getReceivers().forEach(function(e){e.track&&e.track.stop()}),this._peerConnection.getSenders().forEach(function(e){e.track&&e.track.stop()}),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)},e.prototype.getDescription=function(e,t){var n,r,i=this;if(this.logger.debug("SessionDescriptionHandler.getDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==e?void 0:e.onDataChannel;var s=null===(n=null==e?void 0:e.offerOptions)||void 0===n?void 0:n.iceRestart,o=void 0===(null==e?void 0:e.iceGatheringTimeout)?null===(r=this.sessionDescriptionHandlerConfiguration)||void 0===r?void 0:r.iceGatheringTimeout:null==e?void 0:e.iceGatheringTimeout;return this.getLocalMediaStream(e).then(function(){return i.updateDirection(e)}).then(function(){return i.createDataChannel(e)}).then(function(){return i.createLocalOfferOrAnswer(e)}).then(function(e){return i.applyModifiers(e,t)}).then(function(e){return i.setLocalSessionDescription(e)}).then(function(){return i.waitForIceGatheringComplete(s,o)}).then(function(){return i.getLocalSessionDescription()}).then(function(e){return{body:e.sdp,contentType:"application/sdp"}}).catch(function(e){throw i.logger.error("SessionDescriptionHandler.getDescription failed - "+e),e})},e.prototype.hasDescription=function(e){return this.logger.debug("SessionDescriptionHandler.hasDescription"),"application/sdp"===e},e.prototype.sendDtmf=function(e,t){if(this.logger.debug("SessionDescriptionHandler.sendDtmf"),void 0===this._peerConnection)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"),!1;var n=this._peerConnection.getSenders();if(0===n.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;var r=n[0].dtmf;if(!r)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;var i=null==t?void 0:t.duration,s=null==t?void 0:t.interToneGap;try{r.insertDTMF(e,i,s)}catch(e){return this.logger.error(e),!1}return this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: "+e.toString()),!0},e.prototype.setDescription=function(e,t,n){var r=this;if(this.logger.debug("SessionDescriptionHandler.setDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==t?void 0:t.onDataChannel;var i="have-local-offer"===this._peerConnection.signalingState?"answer":"offer";return this.getLocalMediaStream(t).then(function(){return r.applyModifiers({sdp:e,type:i},n)}).then(function(e){return r.setRemoteSessionDescription(e)}).catch(function(e){throw r.logger.error("SessionDescriptionHandler.setDescription failed - "+e),e})},e.prototype.applyModifiers=function(e,t){var n=this;return this.logger.debug("SessionDescriptionHandler.applyModifiers"),t&&0!==t.length?t.reduce(function(e,t){return e.then(t)},Promise.resolve(e)).then(function(e){if(n.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"),!e.sdp||!e.type)throw new Error("Invalid SDP.");return{sdp:e.sdp,type:e.type}}):Promise.resolve(e)},e.prototype.createDataChannel=function(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));if(!0!==(null==e?void 0:e.dataChannel))return Promise.resolve();if(this._dataChannel)return Promise.resolve();switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.createDataChannel - creating data channel");try{return this._dataChannel=this._peerConnection.createDataChannel((null==e?void 0:e.dataChannelLabel)||"",null==e?void 0:e.dataChannelOptions),this.onDataChannel&&this.onDataChannel(this._dataChannel),Promise.resolve()}catch(e){return Promise.reject(e)}case"have-remote-offer":return Promise.resolve();default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}},e.prototype.createLocalOfferOrAnswer=function(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP offer"),this._peerConnection.createOffer(null==e?void 0:e.offerOptions);case"have-remote-offer":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"),this._peerConnection.createAnswer(null==e?void 0:e.answerOptions);default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}},e.prototype.getLocalMediaStream=function(e){var t=this;if(this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));var n=__assign({},null==e?void 0:e.constraints);if(this.localMediaStreamConstraints){if(n.audio=n.audio||this.localMediaStreamConstraints.audio,n.video=n.video||this.localMediaStreamConstraints.video,JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(n.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(n.video))return Promise.resolve()}else void 0===n.audio&&void 0===n.video&&(n={audio:!0});return this.localMediaStreamConstraints=n,this.mediaStreamFactory(n,this).then(function(e){return t.setLocalMediaStream(e)})},e.prototype.setLocalMediaStream=function(t){var n=this;if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");var r=this._peerConnection,i=this._localMediaStream,s=[],o=function(t){var o=t.kind;if("audio"!==o&&"video"!==o)throw new Error("Unknown new track kind ".concat(o,"."));var a=r.getSenders().find(function(e){return e.track&&e.track.kind===o});a?s.push(new Promise(function(e){n.logger.debug("SessionDescriptionHandler.setLocalMediaStream - replacing sender ".concat(o," track")),e()}).then(function(){return a.replaceTrack(t).then(function(){var n=i.getTracks().find(function(e){return e.kind===o});n&&(n.stop(),i.removeTrack(n),e.dispatchRemoveTrackEvent(i,n)),i.addTrack(t),e.dispatchAddTrackEvent(i,t)}).catch(function(e){throw n.logger.error("SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ".concat(o," track")),e})})):s.push(new Promise(function(e){n.logger.debug("SessionDescriptionHandler.setLocalMediaStream - adding sender ".concat(o," track")),e()}).then(function(){try{r.addTrack(t,i)}catch(e){throw n.logger.error("SessionDescriptionHandler.setLocalMediaStream - failed to add sender ".concat(o," track")),e}i.addTrack(t),e.dispatchAddTrackEvent(i,t)}))},a=t.getAudioTracks();a.length&&o(a[0]);var c=t.getVideoTracks();return c.length&&o(c[0]),s.reduce(function(e,t){return e.then(function(){return t})},Promise.resolve())},e.prototype.getLocalSessionDescription=function(){if(this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));var e=this._peerConnection.localDescription;return e?Promise.resolve(e):Promise.reject(new Error("Failed to get local session description"))},e.prototype.setLocalSessionDescription=function(e){return this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"),void 0===this._peerConnection?Promise.reject(new Error("Peer connection closed.")):this._peerConnection.setLocalDescription(e)},e.prototype.setRemoteSessionDescription=function(e){if(this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));var t,n=e.sdp;switch(this._peerConnection.signalingState){case"stable":t="offer";break;case"have-local-offer":t="answer";break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return n?this._peerConnection.setRemoteDescription({sdp:n,type:t}):(this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"),Promise.reject(new Error("SDP is undefined")))},e.prototype.setRemoteTrack=function(t){this.logger.debug("SessionDescriptionHandler.setRemoteTrack");var n=this._remoteMediaStream;n.getTrackById(t.id)?this.logger.debug("SessionDescriptionHandler.setRemoteTrack - have remote ".concat(t.kind," track")):"audio"===t.kind?(this.logger.debug("SessionDescriptionHandler.setRemoteTrack - adding remote ".concat(t.kind," track")),n.getAudioTracks().forEach(function(t){t.stop(),n.removeTrack(t),e.dispatchRemoveTrackEvent(n,t)}),n.addTrack(t),e.dispatchAddTrackEvent(n,t)):"video"===t.kind&&(this.logger.debug("SessionDescriptionHandler.setRemoteTrack - adding remote ".concat(t.kind," track")),n.getVideoTracks().forEach(function(t){t.stop(),n.removeTrack(t),e.dispatchRemoveTrackEvent(n,t)}),n.addTrack(t),e.dispatchAddTrackEvent(n,t))},e.prototype.updateDirection=function(e){var t=this;if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.updateDirection - setting offer direction");this._peerConnection.getTransceivers().forEach(function(t){if(t.direction){var n=function(t){switch(t){case"inactive":case"recvonly":return(null==e?void 0:e.hold)?"inactive":"recvonly";case"sendonly":case"sendrecv":return(null==e?void 0:e.hold)?"sendonly":"sendrecv";case"stopped":return"stopped";default:throw new Error("Should never happen")}}(t.direction);t.direction!==n&&(t.direction=n)}});break;case"have-remote-offer":this.logger.debug("SessionDescriptionHandler.updateDirection - setting answer direction");var n=function(){var e=t._peerConnection.remoteDescription;if(!e)throw new Error("Failed to read remote offer");var n=/a=sendrecv\r\n|a=sendonly\r\n|a=recvonly\r\n|a=inactive\r\n/.exec(e.sdp);if(n)switch(n[0]){case"a=inactive\r\n":return"inactive";case"a=recvonly\r\n":return"recvonly";case"a=sendonly\r\n":return"sendonly";case"a=sendrecv\r\n":return"sendrecv";default:throw new Error("Should never happen")}return"sendrecv"}(),r=function(){switch(n){case"inactive":return"inactive";case"recvonly":return"sendonly";case"sendonly":return(null==e?void 0:e.hold)?"inactive":"recvonly";case"sendrecv":return(null==e?void 0:e.hold)?"sendonly":"sendrecv";default:throw new Error("Should never happen")}}();this._peerConnection.getTransceivers().forEach(function(e){e.direction&&"stopped"!==e.direction&&e.direction!==r&&(e.direction=r)});break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return Promise.resolve()},e.prototype.iceGatheringComplete=function(){this.logger.debug("SessionDescriptionHandler.iceGatheringComplete"),void 0!==this.iceGatheringCompleteTimeoutId&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - clearing timeout"),clearTimeout(this.iceGatheringCompleteTimeoutId),this.iceGatheringCompleteTimeoutId=void 0),void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - resolving promise"),this.iceGatheringCompleteResolve&&this.iceGatheringCompleteResolve(),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0)},e.prototype.waitForIceGatheringComplete=function(e,t){var n=this;return void 0===e&&(e=!1),void 0===t&&(t=0),this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"),void 0===this._peerConnection?Promise.reject("Peer connection closed."):e||"complete"!==this._peerConnection.iceGatheringState?(void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - rejecting prior waiting promise"),this.iceGatheringCompleteReject&&this.iceGatheringCompleteReject(new Error("Promise superseded.")),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0),this.iceGatheringCompletePromise=new Promise(function(e,r){n.iceGatheringCompleteResolve=e,n.iceGatheringCompleteReject=r,t>0&&(n.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in "+t),n.iceGatheringCompleteTimeoutId=setTimeout(function(){n.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"),n.iceGatheringComplete()},t))}),this.iceGatheringCompletePromise):(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"),Promise.resolve())},e.prototype.initPeerConnectionEventHandlers=function(){var e=this;if(this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"),!this._peerConnection)throw new Error("Peer connection undefined.");var t=this._peerConnection;t.onconnectionstatechange=function(n){var r,i=t.connectionState;e.logger.debug("SessionDescriptionHandler.onconnectionstatechange ".concat(i)),(null===(r=e._peerConnectionDelegate)||void 0===r?void 0:r.onconnectionstatechange)&&e._peerConnectionDelegate.onconnectionstatechange(n)},t.ondatachannel=function(t){var n;e.logger.debug("SessionDescriptionHandler.ondatachannel"),e._dataChannel=t.channel,e.onDataChannel&&e.onDataChannel(e._dataChannel),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.ondatachannel)&&e._peerConnectionDelegate.ondatachannel(t)},t.onicecandidate=function(t){var n;e.logger.debug("SessionDescriptionHandler.onicecandidate"),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.onicecandidate)&&e._peerConnectionDelegate.onicecandidate(t)},t.onicecandidateerror=function(t){var n;e.logger.debug("SessionDescriptionHandler.onicecandidateerror"),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.onicecandidateerror)&&e._peerConnectionDelegate.onicecandidateerror(t)},t.oniceconnectionstatechange=function(n){var r,i=t.iceConnectionState;e.logger.debug("SessionDescriptionHandler.oniceconnectionstatechange ".concat(i)),(null===(r=e._peerConnectionDelegate)||void 0===r?void 0:r.oniceconnectionstatechange)&&e._peerConnectionDelegate.oniceconnectionstatechange(n)},t.onicegatheringstatechange=function(n){var r,i=t.iceGatheringState;e.logger.debug("SessionDescriptionHandler.onicegatheringstatechange ".concat(i)),"complete"===i&&e.iceGatheringComplete(),(null===(r=e._peerConnectionDelegate)||void 0===r?void 0:r.onicegatheringstatechange)&&e._peerConnectionDelegate.onicegatheringstatechange(n)},t.onnegotiationneeded=function(t){var n;e.logger.debug("SessionDescriptionHandler.onnegotiationneeded"),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.onnegotiationneeded)&&e._peerConnectionDelegate.onnegotiationneeded(t)},t.onsignalingstatechange=function(n){var r,i=t.signalingState;e.logger.debug("SessionDescriptionHandler.onsignalingstatechange ".concat(i)),(null===(r=e._peerConnectionDelegate)||void 0===r?void 0:r.onsignalingstatechange)&&e._peerConnectionDelegate.onsignalingstatechange(n)},t.onstatsended=function(t){var n;e.logger.debug("SessionDescriptionHandler.onstatsended"),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.onstatsended)&&e._peerConnectionDelegate.onstatsended(t)},t.ontrack=function(t){var n,r=t.track.kind,i=t.track.enabled?"enabled":"disabled";e.logger.debug("SessionDescriptionHandler.ontrack ".concat(r," ").concat(i)),e.setRemoteTrack(t.track),(null===(n=e._peerConnectionDelegate)||void 0===n?void 0:n.ontrack)&&e._peerConnectionDelegate.ontrack(t)}},e}();function defaultSessionDescriptionHandlerFactory(e){return function(t,n){void 0===e&&(e=defaultMediaStreamFactory());var r={iceGatheringTimeout:void 0!==(null==n?void 0:n.iceGatheringTimeout)?null==n?void 0:n.iceGatheringTimeout:5e3,peerConnectionConfiguration:__assign(__assign({},defaultPeerConnectionConfiguration()),null==n?void 0:n.peerConnectionConfiguration)},i=t.userAgent.getLogger("sip.SessionDescriptionHandler");return new SessionDescriptionHandler(i,e,r)}}var Transport=function(){function e(t,n){if(this._state=TransportState.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new EmitterImpl,this.logger=t,n){var r=n,i=null==r?void 0:r.wsServers,s=null==r?void 0:r.maxReconnectionAttempts;if(void 0!==i){var o='The transport option "wsServers" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(o)}if(void 0!==s){o='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(o)}i&&!n.server&&("string"==typeof i&&(n.server=i),i instanceof Array&&(n.server=i[0]))}this.configuration=__assign(__assign({},e.defaultOptions),n);var a=this.configuration.server,c=Grammar.parse(a,"absoluteURI");if(-1===c)throw this.logger.error('Invalid WebSocket Server URL "'.concat(a,'"')),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(c.scheme))throw this.logger.error('Invalid scheme in WebSocket Server URL "'.concat(a,'"')),new Error("Invalid scheme in WebSocket Server URL");this._protocol=c.scheme.toUpperCase()}return e.prototype.dispose=function(){return this.disconnect()},Object.defineProperty(e.prototype,"protocol",{get:function(){return this._protocol},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"server",{get:function(){return this.configuration.server},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"ws",{get:function(){return this._ws},enumerable:!1,configurable:!0}),e.prototype.connect=function(){return this._connect()},e.prototype.disconnect=function(){return this._disconnect()},e.prototype.isConnected=function(){return this.state===TransportState.Connected},e.prototype.send=function(e){return this._send(e)},e.prototype._connect=function(){var e,t=this;switch(this.logger.log("Connecting ".concat(this.server)),this.state){case TransportState.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(TransportState.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case TransportState.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(TransportState.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case TransportState.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(TransportState.Connecting)}catch(e){if(e instanceof StateTransitionError)return Promise.reject(e);throw e}break;case TransportState.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(TransportState.Connecting)}catch(e){if(e instanceof StateTransitionError)return Promise.reject(e);throw e}break;default:throw new Error("Unknown state")}try{(e=new WebSocket(this.server,"sip")).binaryType="arraybuffer",e.addEventListener("close",function(n){return t.onWebSocketClose(n,e)}),e.addEventListener("error",function(n){return t.onWebSocketError(n,e)}),e.addEventListener("open",function(n){return t.onWebSocketOpen(n,e)}),e.addEventListener("message",function(n){return t.onWebSocketMessage(n,e)}),this._ws=e}catch(e){return this._ws=void 0,this.logger.error("WebSocket construction failed."),this.logger.error(e),new Promise(function(n,r){t.connectResolve=n,t.connectReject=r,t.transitionState(TransportState.Disconnected,e)})}return this.connectPromise=new Promise(function(n,r){t.connectResolve=n,t.connectReject=r,t.connectTimeout=setTimeout(function(){t.logger.warn("Connect timed out. Exceeded time set in configuration.connectionTimeout: "+t.configuration.connectionTimeout+"s."),e.close(1e3)},1e3*t.configuration.connectionTimeout)}),this.connectPromise},e.prototype._disconnect=function(){var e=this;switch(this.logger.log("Disconnecting ".concat(this.server)),this.state){case TransportState.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(TransportState.Disconnecting)}catch(e){if(e instanceof StateTransitionError)return Promise.reject(e);throw e}break;case TransportState.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(TransportState.Disconnecting)}catch(e){if(e instanceof StateTransitionError)return Promise.reject(e);throw e}break;case TransportState.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(TransportState.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case TransportState.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(TransportState.Disconnecting));if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");return Promise.resolve();default:throw new Error("Unknown state")}if(!this._ws)throw new Error("WebSocket must be defined.");var t=this._ws;return this.disconnectPromise=new Promise(function(n,r){e.disconnectResolve=n,e.disconnectReject=r;try{t.close(1e3)}catch(t){throw e.logger.error("WebSocket close failed."),e.logger.error(t),t}}),this.disconnectPromise},e.prototype._send=function(e){if(!0===this.configuration.traceSip&&this.logger.log("Sending WebSocket message:\n\n"+e+"\n"),this._state!==TransportState.Connected)return Promise.reject(new Error("Not connected."));if(!this._ws)throw new Error("WebSocket undefined.");try{this._ws.send(e)}catch(e){return e instanceof Error?Promise.reject(e):Promise.reject(new Error("WebSocket send failed."))}return Promise.resolve()},e.prototype.onWebSocketClose=function(e,t){if(t===this._ws){var n="WebSocket closed ".concat(this.server," (code: ").concat(e.code,")"),r=this.disconnectPromise?void 0:new Error(n);r&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(n),this._ws=void 0,this.transitionState(TransportState.Disconnected,r)}},e.prototype.onWebSocketError=function(e,t){t===this._ws&&this.logger.error("WebSocket error occurred.")},e.prototype.onWebSocketMessage=function(e,t){if(t===this._ws){var n,r=e.data;if(/^(\r\n)+$/.test(r))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(r){if("string"!=typeof r){try{n=(new TextDecoder).decode(new Uint8Array(r))}catch(e){return this.logger.error(e),void this.logger.error("Received WebSocket binary message failed to be converted into string, message discarded")}!0===this.configuration.traceSip&&this.logger.log("Received WebSocket binary message:\n\n"+n+"\n")}else n=r,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+n+"\n");if(this.state===TransportState.Connected){if(this.onMessage)try{this.onMessage(n)}catch(e){throw this.logger.error(e),this.logger.error("Exception thrown by onMessage callback"),e}}else this.logger.warn("Received message while not connected, discarding...")}else this.logger.warn("Received empty message, discarding...")}},e.prototype.onWebSocketOpen=function(e,t){t===this._ws&&this._state===TransportState.Connecting&&(this.logger.log("WebSocket opened ".concat(this.server)),this.transitionState(TransportState.Connected))},e.prototype.transitionLoopDetectedError=function(e){var t="A state transition loop has been detected.";return t+=" An attempt to transition from ".concat(this._state," to ").concat(e," before the prior transition completed."),t+=" Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?",this.logger.error(t),new StateTransitionError("Loop detected.")},e.prototype.transitionState=function(e,t){var n=this,r=function(){throw new Error("Invalid state transition from ".concat(n._state," to ").concat(e))};if(this.transitioningState)throw this.transitionLoopDetectedError(e);switch(this.transitioningState=!0,this._state){case TransportState.Connecting:e!==TransportState.Connected&&e!==TransportState.Disconnecting&&e!==TransportState.Disconnected&&r();break;case TransportState.Connected:e!==TransportState.Disconnecting&&e!==TransportState.Disconnected&&r();break;case TransportState.Disconnecting:e!==TransportState.Connecting&&e!==TransportState.Disconnected&&r();break;case TransportState.Disconnected:e!==TransportState.Connecting&&r();break;default:throw new Error("Unknown state.")}var i=this._state;this._state=e;var s=this.connectResolve,o=this.connectReject;i===TransportState.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);var a=this.disconnectResolve,c=this.disconnectReject;if(i===TransportState.Disconnecting&&(this.disconnectPromise=void 0,this.disconnectResolve=void 0,this.disconnectReject=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),this.logger.log("Transitioned from ".concat(i," to ").concat(this._state)),this._stateEventEmitter.emit(this._state),e===TransportState.Connected&&(this.startSendingKeepAlives(),this.onConnect))try{this.onConnect()}catch(e){throw this.logger.error(e),this.logger.error("Exception thrown by onConnect callback"),e}if(i===TransportState.Connected&&(this.stopSendingKeepAlives(),this.onDisconnect))try{t?this.onDisconnect(t):this.onDisconnect()}catch(e){throw this.logger.error(e),this.logger.error("Exception thrown by onDisconnect callback"),e}if(i===TransportState.Connecting){if(!s)throw new Error("Connect resolve undefined.");if(!o)throw new Error("Connect reject undefined.");e===TransportState.Connected?s():o(t||new Error("Connect aborted."))}if(i===TransportState.Disconnecting){if(!a)throw new Error("Disconnect resolve undefined.");if(!c)throw new Error("Disconnect reject undefined.");e===TransportState.Disconnected?a():c(t||new Error("Disconnect aborted."))}this.transitioningState=!1},e.prototype.clearKeepAliveTimeout=function(){this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveDebounceTimeout=void 0},e.prototype.sendKeepAlive=function(){var e=this;return this.keepAliveDebounceTimeout?Promise.resolve():(this.keepAliveDebounceTimeout=setTimeout(function(){e.clearKeepAliveTimeout()},1e3*this.configuration.keepAliveDebounce),this.send("\r\n\r\n"))},e.prototype.startSendingKeepAlives=function(){var e,t,n=this;this.configuration.keepAliveInterval&&!this.keepAliveInterval&&(this.keepAliveInterval=setInterval(function(){n.sendKeepAlive(),n.startSendingKeepAlives()},(e=this.configuration.keepAliveInterval,t=.8*e,1e3*(Math.random()*(e-t)+t))))},e.prototype.stopSendingKeepAlives=function(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0},e.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0},e}(),UserAgent=function(){function e(t){void 0===t&&(t={});var n=this;if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=UserAgentState.Stopped,this.unloadListener=function(){n.stop()},this._stateEventEmitter=new EmitterImpl,this.delegate=t.delegate,this.options=__assign(__assign(__assign(__assign(__assign({},e.defaultOptions()),{sipjsId:createRandomToken(5)}),{uri:new URI("sip","anonymous."+createRandomToken(6),"anonymous.invalid")}),{viaHost:createRandomToken(12)+".invalid"}),e.stripUndefinedProperties(t)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){var r=Math.floor(254*Math.random()+1);this.options.viaHost="192.0.2."+r}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new LoggerFactory,this.logger=this.loggerFactory.getLogger("sip.UserAgent"),this.loggerFactory.builtinEnabled=this.options.logBuiltinEnabled,this.loggerFactory.connector=this.options.logConnector,this.options.logLevel){case"error":this.loggerFactory.level=Levels.error;break;case"warn":this.loggerFactory.level=Levels.warn;break;case"log":this.loggerFactory.level=Levels.log;break;case"debug":this.loggerFactory.level=Levels.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(function(e){var t=n.options[e];switch(e){case"uri":case"sessionDescriptionHandlerFactory":n.logger.log("· "+e+": "+t);break;case"authorizationPassword":n.logger.log("· "+e+": NOT SHOWN");break;case"transportConstructor":n.logger.log("· "+e+": "+t.name);break;default:n.logger.log("· "+e+": "+JSON.stringify(t))}})),this.options.transportOptions){var i=this.options.transportOptions,s=i.maxReconnectionAttempts,o=i.reconnectionTimeout;if(void 0!==s){var a='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(a)}if(void 0!==o){a='The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(a)}void 0===t.reconnectionDelay&&void 0!==o&&(this.options.reconnectionDelay=o),void 0===t.reconnectionAttempts&&void 0!==s&&(this.options.reconnectionAttempts=s)}if(void 0!==t.reconnectionDelay){a='The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(a)}if(void 0!==t.reconnectionAttempts){a='The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(a)}this._transport=new this.options.transportConstructor(this.getLogger("sip.Transport"),this.options.transportOptions),this.initTransportCallbacks(),this._contact=this.initContact(),this._userAgentCore=this.initCore(),this.options.autoStart&&this.start()}return e.makeURI=function(e){return Grammar.URIParse(e)},e.defaultOptions=function(){return{allowLegacyNotifications:!1,authorizationHa1:"",authorizationPassword:"",authorizationUsername:"",autoStart:!1,autoStop:!0,delegate:{},contactName:"",contactParams:{transport:"ws"},displayName:"",forceRport:!1,hackAllowUnregisteredOptionTags:!1,hackIpInContact:!1,hackViaTcp:!1,logBuiltinEnabled:!0,logConfiguration:!0,logConnector:function(){},logLevel:"log",noAnswerTimeout:60,preloadedRouteSet:[],reconnectionAttempts:0,reconnectionDelay:4,sendInitialProvisionalResponse:!0,sessionDescriptionHandlerFactory:defaultSessionDescriptionHandlerFactory(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:SIPExtension.Unsupported,sipExtensionReplaces:SIPExtension.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:Transport,transportOptions:{},uri:new URI("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/"+LIBRARY_VERSION,viaHost:""}},e.stripUndefinedProperties=function(e){return Object.keys(e).reduce(function(t,n){return void 0!==e[n]&&(t[n]=e[n]),t},{})},Object.defineProperty(e.prototype,"configuration",{get:function(){return this.options},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"contact",{get:function(){return this._contact},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stateChange",{get:function(){return this._stateEventEmitter},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transport",{get:function(){return this._transport},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"userAgentCore",{get:function(){return this._userAgentCore},enumerable:!1,configurable:!0}),e.prototype.getLogger=function(e,t){return this.loggerFactory.getLogger(e,t)},e.prototype.getLoggerFactory=function(){return this.loggerFactory},e.prototype.isConnected=function(){return this.transport.isConnected()},e.prototype.reconnect=function(){var e=this;return this.state===UserAgentState.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(function(){return e.transport.connect()})},e.prototype.start=function(){if(this.state===UserAgentState.Started)return this.logger.warn("User agent already started"),Promise.resolve();if(this.logger.log("Starting ".concat(this.configuration.uri)),this.transitionState(UserAgentState.Started),this.options.autoStop){var e=!("undefined"==typeof chrome||!chrome.app||!chrome.app.runtime);"undefined"==typeof window||"function"!=typeof window.addEventListener||e||window.addEventListener("unload",this.unloadListener)}return this.transport.connect()},e.prototype.stop=function(){return __awaiter(this,void 0,void 0,function(){var e,t,n,r,i,s,o,a,c,u,l,h,d,p,g,f,m,v,y,b,S,T,w,R,E,I,_,A=this;return __generator(this,function(C){switch(C.label){case 0:if(this.state===UserAgentState.Stopped)return this.logger.warn("User agent already stopped"),[2,Promise.resolve()];for(l in this.logger.log("Stopping ".concat(this.configuration.uri)),this.transitionState(UserAgentState.Stopped),this.options.autoStop&&(e=!("undefined"==typeof chrome||!chrome.app||!chrome.app.runtime),"undefined"!=typeof window&&window.removeEventListener&&!e&&window.removeEventListener("unload",this.unloadListener)),t=__assign({},this._publishers),n=__assign({},this._registerers),r=__assign({},this._sessions),i=__assign({},this._subscriptions),s=this.transport,o=this.userAgentCore,this.logger.log("Dispose of registerers"),a=function(e){return __generator(this,function(t){switch(t.label){case 0:return n[e]?[4,n[e].dispose().catch(function(t){throw A.logger.error(t.message),delete A._registerers[e],t})]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})},u=[],c=n)u.push(l);h=0,C.label=1;case 1:return h<u.length?(l=u[h])in c?[5,a(l)]:[3,3]:[3,4];case 2:C.sent(),C.label=3;case 3:return h++,[3,1];case 4:for(f in this.logger.log("Dispose of sessions"),d=function(e){return __generator(this,function(t){switch(t.label){case 0:return r[e]?[4,r[e].dispose().catch(function(t){throw A.logger.error(t.message),delete A._sessions[e],t})]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})},g=[],p=r)g.push(f);m=0,C.label=5;case 5:return m<g.length?(f=g[m])in p?[5,d(f)]:[3,7]:[3,8];case 6:C.sent(),C.label=7;case 7:return m++,[3,5];case 8:for(S in this.logger.log("Dispose of subscriptions"),v=function(e){return __generator(this,function(t){switch(t.label){case 0:return i[e]?[4,i[e].dispose().catch(function(t){throw A.logger.error(t.message),delete A._subscriptions[e],t})]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}})},b=[],y=i)b.push(S);T=0,C.label=9;case 9:return T<b.length?(S=b[T])in y?[5,v(S)]:[3,11]:[3,12];case 10:C.sent(),C.label=11;case 11:return T++,[3,9];case 12:for(I in this.logger.log("Dispose of publishers"),w=function(e){return __generator(this,function(n){switch(n.label){case 0:return t[e]?[4,t[e].dispose().catch(function(t){throw A.logger.error(t.message),delete A._publishers[e],t})]:[3,2];case 1:n.sent(),n.label=2;case 2:return[2]}})},E=[],R=t)E.push(I);_=0,C.label=13;case 13:return _<E.length?(I=E[_])in R?[5,w(I)]:[3,15]:[3,16];case 14:C.sent(),C.label=15;case 15:return _++,[3,13];case 16:return this.logger.log("Dispose of transport"),[4,s.dispose().catch(function(e){throw A.logger.error(e.message),e})];case 17:return C.sent(),this.logger.log("Dispose of core"),o.dispose(),[2]}})})},e.prototype._makeInviter=function(e,t){return new Inviter(this,e,t)},e.prototype.attemptReconnection=function(e){var t=this;void 0===e&&(e=1);var n=this.options.reconnectionAttempts,r=this.options.reconnectionDelay;e>n?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log("Reconnection attempt ".concat(e," of ").concat(n," - trying")),setTimeout(function(){t.reconnect().then(function(){t.logger.log("Reconnection attempt ".concat(e," of ").concat(n," - succeeded"))}).catch(function(r){t.logger.error(r.message),t.logger.log("Reconnection attempt ".concat(e," of ").concat(n," - failed")),t.attemptReconnection(++e)})},1===e?0:1e3*r))},e.prototype.initContact=function(){var e=this,t=""!==this.options.contactName?this.options.contactName:createRandomToken(8),n=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new URI("sip",t,this.options.viaHost,void 0,n),toString:function(t){void 0===t&&(t={});var r=t.anonymous||!1,i=t.outbound||!1,s="<";return s+=r?e.contact.tempGruu||"sip:anonymous@anonymous.invalid;transport=".concat(n.transport?n.transport:"ws"):e.contact.pubGruu||e.contact.uri,i&&(s+=";ob"),s+=">"}}},e.prototype.initCore=function(){var e=this,t=[];t.push("outbound"),this.options.sipExtension100rel===SIPExtension.Supported&&t.push("100rel"),this.options.sipExtensionReplaces===SIPExtension.Supported&&t.push("replaces"),this.options.sipExtensionExtraSupported&&t.push.apply(t,this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(t=t.filter(function(e){return UserAgentRegisteredOptionTags[e]}));var n=(t=Array.from(new Set(t))).slice();(this.contact.pubGruu||this.contact.tempGruu)&&n.push("gruu");var r={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:t,supportedOptionTagsResponse:n,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:function(){var t=e.options.authorizationUsername?e.options.authorizationUsername:e.options.uri.user,n=e.options.authorizationPassword?e.options.authorizationPassword:void 0,r=e.options.authorizationHa1?e.options.authorizationHa1:void 0;return new DigestAuthentication(e.getLoggerFactory(),r,t,n)},transportAccessor:function(){return e.transport}},i={onInvite:function(t){var n,r=new Invitation(e,t);if(t.delegate={onCancel:function(e){r._onCancel(e)},onTransportError:function(t){e.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},t.trying(),e.options.sipExtensionReplaces!==SIPExtension.Unsupported){var i=t.message.parseHeader("replaces");if(i){var s=i.call_id;if("string"!=typeof s)throw new Error("Type of call id is not string");var o=i.replaces_to_tag;if("string"!=typeof o)throw new Error("Type of to tag is not string");var a=i.replaces_from_tag;if("string"!=typeof a)throw new Error("type of from tag is not string");var c=s+o+a,u=e.userAgentCore.dialogs.get(c);if(!u)return void r.reject({statusCode:481});if(!u.early&&!0===i.early_only)return void r.reject({statusCode:486});var l=e._sessions[s+a]||e._sessions[s+o]||void 0;if(!l)throw new Error("Session does not exist.");r._replacee=l}}if(null===(n=e.delegate)||void 0===n?void 0:n.onInvite)return r.autoSendAnInitialProvisionalResponse?void r.progress().then(function(){var t;if(void 0===(null===(t=e.delegate)||void 0===t?void 0:t.onInvite))throw new Error("onInvite undefined.");e.delegate.onInvite(r)}):void e.delegate.onInvite(r);r.reject({statusCode:486})},onMessage:function(t){if(e.delegate&&e.delegate.onMessage){var n=new Message(t);e.delegate.onMessage(n)}else t.accept()},onNotify:function(t){if(e.delegate&&e.delegate.onNotify){var n=new Notification(t);e.delegate.onNotify(n)}else e.options.allowLegacyNotifications?t.accept():t.reject({statusCode:481})},onRefer:function(t){e.logger.warn("Received an out of dialog REFER request"),e.delegate&&e.delegate.onReferRequest?e.delegate.onReferRequest(t):t.reject({statusCode:405})},onRegister:function(t){e.logger.warn("Received an out of dialog REGISTER request"),e.delegate&&e.delegate.onRegisterRequest?e.delegate.onRegisterRequest(t):t.reject({statusCode:405})},onSubscribe:function(t){e.logger.warn("Received an out of dialog SUBSCRIBE request"),e.delegate&&e.delegate.onSubscribeRequest?e.delegate.onSubscribeRequest(t):t.reject({statusCode:405})}};return new UserAgentCore(r,i)},e.prototype.initTransportCallbacks=function(){var e=this;this.transport.onConnect=function(){return e.onTransportConnect()},this.transport.onDisconnect=function(t){return e.onTransportDisconnect(t)},this.transport.onMessage=function(t){return e.onTransportMessage(t)}},e.prototype.onTransportConnect=function(){this.state!==UserAgentState.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()},e.prototype.onTransportDisconnect=function(e){this.state!==UserAgentState.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())},e.prototype.onTransportMessage=function(e){var t=this,n=Parser.parseMessage(e,this.getLogger("sip.Parser"));if(n)if(this.state===UserAgentState.Stopped&&n instanceof IncomingRequestMessage)this.logger.warn("Received ".concat(n.method," request while stopped. Dropping."));else{var r=function(){for(var e=0,r=["from","to","call_id","cseq","via"];e<r.length;e++){var i=r[e];if(!n.hasHeader(i))return t.logger.warn("Missing mandatory header field : ".concat(i,".")),!1}return!0};if(n instanceof IncomingRequestMessage){if(!r())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!n.toTag&&n.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(n,{statusCode:482});var i=utf8Length(n.body);if((s=n.getHeader("content-length"))&&i<Number(s))return void this.userAgentCore.replyStateless(n,{statusCode:400})}if(n instanceof IncomingResponseMessage){if(!r())return void this.logger.warn("Response missing mandatory header field. Dropping.");if(n.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(n.via.host!==this.options.viaHost||void 0!==n.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");var s;i=utf8Length(n.body);if((s=n.getHeader("content-length"))&&i<Number(s))return void this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping.")}if(n instanceof IncomingRequestMessage)this.userAgentCore.receiveIncomingRequestFromTransport(n);else{if(!(n instanceof IncomingResponseMessage))throw new Error("Invalid message type.");this.userAgentCore.receiveIncomingResponseFromTransport(n)}}else this.logger.warn("Failed to parse incoming message. Dropping.")},e.prototype.transitionState=function(e,t){var n=this,r=function(){throw new Error("Invalid state transition from ".concat(n._state," to ").concat(e))};switch(this._state){case UserAgentState.Started:e!==UserAgentState.Stopped&&r();break;case UserAgentState.Stopped:e!==UserAgentState.Started&&r();break;default:throw new Error("Unknown state.")}this.logger.log("Transitioned from ".concat(this._state," to ").concat(e)),this._state=e,this._stateEventEmitter.emit(this._state)},e}();function getAudio(e){var t=document.getElementById(e);if(t instanceof HTMLAudioElement)return t;var n=new Audio;return n.controls=!0,n.autoplay=!0,n.id="ueRemoteAudio",n.style.display="none",document.body.appendChild(n),document.getElementById(e)}function assignStream(e,t){t.autoplay=!0,t.srcObject=e,t.play().catch(function(e){}),e.onaddtrack=function(){t.load(),t.play().catch(function(e){})},e.onremovetrack=function(){t.load(),t.play().catch(function(e){})}}!function(){function e(e,t){void 0===t&&(t={});var n=this;this.attemptingReconnection=!1,this.connectRequested=!1,this.held=!1,this.muted=!1,this.registerer=void 0,this.registerRequested=!1,this.session=void 0,this.delegate=t.delegate,this.options=__assign({},t);var r=__assign({},t.userAgentOptions);if(r.transportConstructor||(r.transportConstructor=Transport),r.transportOptions||(r.transportOptions={server:e}),!r.uri&&t.aor){var i=UserAgent.makeURI(t.aor);if(!i)throw new Error("Failed to create valid URI from ".concat(t.aor));r.uri=i}this.userAgent=new UserAgent(r),this.userAgent.delegate={onConnect:function(){n.logger.log("[".concat(n.id,"] Connected")),n.delegate&&n.delegate.onServerConnect&&n.delegate.onServerConnect(),n.registerer&&n.registerRequested&&(n.logger.log("[".concat(n.id,"] Registering...")),n.registerer.register().catch(function(e){n.logger.error("[".concat(n.id,"] Error occurred registering after connection with server was obtained.")),n.logger.error(e.toString())}))},onDisconnect:function(e){n.logger.log("[".concat(n.id,"] Disconnected")),n.delegate&&n.delegate.onServerDisconnect&&n.delegate.onServerDisconnect(e),n.session&&(n.logger.log("[".concat(n.id,"] Hanging up...")),n.hangup().catch(function(e){n.logger.error("[".concat(n.id,"] Error occurred hanging up call after connection with server was lost.")),n.logger.error(e.toString())})),n.registerer&&(n.logger.log("[".concat(n.id,"] Unregistering...")),n.registerer.unregister().catch(function(e){n.logger.error("[".concat(n.id,"] Error occurred unregistering after connection with server was lost.")),n.logger.error(e.toString())})),e&&n.attemptReconnection()},onInvite:function(e){if(n.logger.log("[".concat(n.id,"] Received INVITE")),n.session)return n.logger.warn("[".concat(n.id,"] Session already in progress, rejecting INVITE...")),void e.reject().then(function(){n.logger.log("[".concat(n.id,"] Rejected INVITE"))}).catch(function(e){n.logger.error("[".concat(n.id,"] Failed to reject INVITE")),n.logger.error(e.toString())});var t={sessionDescriptionHandlerOptions:{constraints:n.constraints}};n.initSession(e,t),n.delegate&&n.delegate.onCallReceived?n.delegate.onCallReceived():(n.logger.warn("[".concat(n.id,"] No handler available, rejecting INVITE...")),e.reject().then(function(){n.logger.log("[".concat(n.id,"] Rejected INVITE"))}).catch(function(e){n.logger.error("[".concat(n.id,"] Failed to reject INVITE")),n.logger.error(e.toString())}))},onMessage:function(e){e.accept().then(function(){n.delegate&&n.delegate.onMessageReceived&&n.delegate.onMessageReceived(e.request.body)})}},this.logger=this.userAgent.getLogger("sip.SimpleUser"),window.addEventListener("online",function(){n.logger.log("[".concat(n.id,"] Online")),n.attemptReconnection()})}Object.defineProperty(e.prototype,"id",{get:function(){return this.options.userAgentOptions&&this.options.userAgentOptions.displayName||"Anonymous"},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localMediaStream",{get:function(){var e,t=null===(e=this.session)||void 0===e?void 0:e.sessionDescriptionHandler;if(t){if(!(t instanceof SessionDescriptionHandler))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.localMediaStream}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteMediaStream",{get:function(){var e,t=null===(e=this.session)||void 0===e?void 0:e.sessionDescriptionHandler;if(t){if(!(t instanceof SessionDescriptionHandler))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.remoteMediaStream}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localAudioTrack",{get:function(){var e;return null===(e=this.localMediaStream)||void 0===e?void 0:e.getTracks().find(function(e){return"audio"===e.kind})},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localVideoTrack",{get:function(){var e;return null===(e=this.localMediaStream)||void 0===e?void 0:e.getTracks().find(function(e){return"video"===e.kind})},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteAudioTrack",{get:function(){var e;return null===(e=this.remoteMediaStream)||void 0===e?void 0:e.getTracks().find(function(e){return"audio"===e.kind})},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteVideoTrack",{get:function(){var e;return null===(e=this.remoteMediaStream)||void 0===e?void 0:e.getTracks().find(function(e){return"video"===e.kind})},enumerable:!1,configurable:!0}),e.prototype.connect=function(){return this.logger.log("[".concat(this.id,"] Connecting UserAgent...")),this.connectRequested=!0,this.userAgent.state!==UserAgentState.Started?this.userAgent.start():this.userAgent.reconnect()},e.prototype.disconnect=function(){return this.logger.log("[".concat(this.id,"] Disconnecting UserAgent...")),this.connectRequested=!1,this.userAgent.stop()},e.prototype.isConnected=function(){return this.userAgent.isConnected()},e.prototype.register=function(e,t){var n=this;return this.logger.log("[".concat(this.id,"] Registering UserAgent...")),this.registerRequested=!0,this.registerer||(this.registerer=new Registerer(this.userAgent,e),this.registerer.stateChange.addListener(function(e){switch(e){case RegistererState.Initial:break;case RegistererState.Registered:n.delegate&&n.delegate.onRegistered&&n.delegate.onRegistered();break;case RegistererState.Unregistered:n.delegate&&n.delegate.onUnregistered&&n.delegate.onUnregistered();break;case RegistererState.Terminated:n.registerer=void 0;break;default:throw new Error("Unknown registerer state.")}})),this.registerer.register(t).then(function(){})},e.prototype.unregister=function(e){return this.logger.log("[".concat(this.id,"] Unregistering UserAgent...")),this.registerRequested=!1,this.registerer?this.registerer.unregister(e).then(function(){}):Promise.resolve()},e.prototype.call=function(e,t,n){if(this.logger.log("[".concat(this.id,"] Beginning Session...")),this.session)return Promise.reject(new Error("Session already exists."));var r=UserAgent.makeURI(e);if(!r)return Promise.reject(new Error('Failed to create a valid URI from "'.concat(e,'"')));t||(t={}),t.sessionDescriptionHandlerOptions||(t.sessionDescriptionHandlerOptions={}),t.sessionDescriptionHandlerOptions.constraints||(t.sessionDescriptionHandlerOptions.constraints=this.constraints);var i=new Inviter(this.userAgent,r,t);return this.sendInvite(i,t,n).then(function(){})},e.prototype.hangup=function(){return this.logger.log("[".concat(this.id,"] Hangup...")),this.terminate()},e.prototype.answer=function(e){return this.logger.log("[".concat(this.id,"] Accepting Invitation...")),this.session?this.session instanceof Invitation?(e||(e={}),e.sessionDescriptionHandlerOptions||(e.sessionDescriptionHandlerOptions={}),e.sessionDescriptionHandlerOptions.constraints||(e.sessionDescriptionHandlerOptions.constraints=this.constraints),this.session.accept(e)):Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))},e.prototype.decline=function(){return this.logger.log("[".concat(this.id,"] rejecting Invitation...")),this.session?this.session instanceof Invitation?this.session.reject():Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))},e.prototype.hold=function(){return this.logger.log("[".concat(this.id,"] holding session...")),this.setHold(!0)},e.prototype.unhold=function(){return this.logger.log("[".concat(this.id,"] unholding session...")),this.setHold(!1)},e.prototype.isHeld=function(){return this.held},e.prototype.mute=function(){this.logger.log("[".concat(this.id,"] disabling media tracks...")),this.setMute(!0)},e.prototype.unmute=function(){this.logger.log("[".concat(this.id,"] enabling media tracks...")),this.setMute(!1)},e.prototype.isMuted=function(){return this.muted},e.prototype.sendDTMF=function(e){if(this.logger.log("[".concat(this.id,"] sending DTMF...")),!/^[0-9A-D#*,]$/.exec(e))return Promise.reject(new Error("Invalid DTMF tone."));if(!this.session)return Promise.reject(new Error("Session does not exist."));this.logger.log("[".concat(this.id,"] Sending DTMF tone: ").concat(e));var t={body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:"Signal="+e+"\r\nDuration=2000"}};return this.session.info({requestOptions:t}).then(function(){})},e.prototype.message=function(e,t){this.logger.log("[".concat(this.id,"] sending message..."));var n=UserAgent.makeURI(e);return n?new Messager(this.userAgent,n,t).message():Promise.reject(new Error('Failed to create a valid URI from "'.concat(e,'"')))},Object.defineProperty(e.prototype,"constraints",{get:function(){var e,t={audio:!0,video:!1};return(null===(e=this.options.media)||void 0===e?void 0:e.constraints)&&(t=__assign({},this.options.media.constraints)),t},enumerable:!1,configurable:!0}),e.prototype.attemptReconnection=function(e){var t=this;void 0===e&&(e=1);var n=this.options.reconnectionAttempts||3,r=this.options.reconnectionDelay||4;this.connectRequested?(this.attemptingReconnection&&this.logger.log("[".concat(this.id,"] Reconnection attempt already in progress")),e>n?this.logger.log("[".concat(this.id,"] Reconnection maximum attempts reached")):(1===e?this.logger.log("[".concat(this.id,"] Reconnection attempt ").concat(e," of ").concat(n," - trying")):this.logger.log("[".concat(this.id,"] Reconnection attempt ").concat(e," of ").concat(n," - trying in ").concat(r," seconds")),this.attemptingReconnection=!0,setTimeout(function(){if(!t.connectRequested)return t.logger.log("[".concat(t.id,"] Reconnection attempt ").concat(e," of ").concat(n," - aborted")),void(t.attemptingReconnection=!1);t.userAgent.reconnect().then(function(){t.logger.log("[".concat(t.id,"] Reconnection attempt ").concat(e," of ").concat(n," - succeeded")),t.attemptingReconnection=!1}).catch(function(r){t.logger.log("[".concat(t.id,"] Reconnection attempt ").concat(e," of ").concat(n," - failed")),t.logger.error(r.message),t.attemptingReconnection=!1,t.attemptReconnection(++e)})},1===e?0:1e3*r))):this.logger.log("[".concat(this.id,"] Reconnection not currently desired"))},e.prototype.cleanupMedia=function(){this.options.media&&(this.options.media.local&&this.options.media.local.video&&(this.options.media.local.video.srcObject=null,this.options.media.local.video.pause()),this.options.media.remote&&(this.options.media.remote.audio&&(this.options.media.remote.audio.srcObject=null,this.options.media.remote.audio.pause()),this.options.media.remote.video&&(this.options.media.remote.video.srcObject=null,this.options.media.remote.video.pause())))},e.prototype.enableReceiverTracks=function(e){if(!this.session)throw new Error("Session does not exist.");var t=this.session.sessionDescriptionHandler;if(!(t instanceof SessionDescriptionHandler))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");var n=t.peerConnection;if(!n)throw new Error("Peer connection closed.");n.getReceivers().forEach(function(t){t.track&&(t.track.enabled=e)})},e.prototype.enableSenderTracks=function(e){if(!this.session)throw new Error("Session does not exist.");var t=this.session.sessionDescriptionHandler;if(!(t instanceof SessionDescriptionHandler))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");var n=t.peerConnection;if(!n)throw new Error("Peer connection closed.");n.getSenders().forEach(function(t){t.track&&(t.track.enabled=e)})},e.prototype.initSession=function(e,t){var n=this;this.session=e,this.delegate&&this.delegate.onCallCreated&&this.delegate.onCallCreated(),this.session.stateChange.addListener(function(t){if(n.session===e)switch(n.logger.log("[".concat(n.id,"] session state changed to ").concat(t)),t){case SessionState.Initial:case SessionState.Establishing:break;case SessionState.Established:n.setupLocalMedia(),n.setupRemoteMedia(),n.delegate&&n.delegate.onCallAnswered&&n.delegate.onCallAnswered();break;case SessionState.Terminating:case SessionState.Terminated:n.session=void 0,n.cleanupMedia(),n.delegate&&n.delegate.onCallHangup&&n.delegate.onCallHangup();break;default:throw new Error("Unknown session state.")}}),this.session.delegate={onInfo:function(e){var t;if(void 0!==(null===(t=n.delegate)||void 0===t?void 0:t.onCallDTMFReceived)){var r=e.request.getHeader("content-type");if(r&&/^application\/dtmf-relay/i.exec(r)){var i=e.request.body.split("\r\n",2);if(2===i.length){var s,o=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;if(o.test(i[0])&&(s=i[0].replace(o,"$2")),s){var a,c=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;c.test(i[1])&&(a=parseInt(i[1].replace(c,"$2"),10)),a?e.accept().then(function(){if(n.delegate&&n.delegate.onCallDTMFReceived){if(!s||!a)throw new Error("Tone or duration undefined.");n.delegate.onCallDTMFReceived(s,a)}}).catch(function(e){n.logger.error(e.message)}):e.reject()}else e.reject()}else e.reject()}else e.reject()}else e.reject()},onRefer:function(e){e.accept().then(function(){return n.sendInvite(e.makeInviter(t),t)}).catch(function(e){n.logger.error(e.message)})}}},e.prototype.sendInvite=function(e,t,n){var r=this;return this.initSession(e,t),e.invite(n).then(function(){r.logger.log("[".concat(r.id,"] sent INVITE"))})},e.prototype.setHold=function(e){var t=this;if(!this.session)return Promise.reject(new Error("Session does not exist."));var n=this.session;if(this.held===e)return Promise.resolve();if(!(this.session.sessionDescriptionHandler instanceof SessionDescriptionHandler))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");var r={requestDelegate:{onAccept:function(){t.held=e,t.enableReceiverTracks(!t.held),t.enableSenderTracks(!t.held&&!t.muted),t.delegate&&t.delegate.onCallHold&&t.delegate.onCallHold(t.held)},onReject:function(){t.logger.warn("[".concat(t.id,"] re-invite request was rejected")),t.enableReceiverTracks(!t.held),t.enableSenderTracks(!t.held&&!t.muted),t.delegate&&t.delegate.onCallHold&&t.delegate.onCallHold(t.held)}}},i=n.sessionDescriptionHandlerOptionsReInvite;return i.hold=e,n.sessionDescriptionHandlerOptionsReInvite=i,this.session.invite(r).then(function(){t.enableReceiverTracks(!e),t.enableSenderTracks(!e&&!t.muted)}).catch(function(e){throw e instanceof RequestPendingError&&t.logger.error("[".concat(t.id,"] A hold request is already in progress.")),e})},e.prototype.setMute=function(e){this.session?this.session.state===SessionState.Established?(this.muted=e,this.enableSenderTracks(!this.held&&!this.muted)):this.logger.warn("[".concat(this.id,"] An established session is required to enable/disable media tracks")):this.logger.warn("[".concat(this.id,"] A session is required to enabled/disable media tracks"))},e.prototype.setupLocalMedia=function(){var e,t,n=this;if(!this.session)throw new Error("Session does not exist.");var r=null===(t=null===(e=this.options.media)||void 0===e?void 0:e.local)||void 0===t?void 0:t.video;if(r){var i=this.localMediaStream;if(!i)throw new Error("Local media stream undefiend.");r.srcObject=i,r.volume=0,r.play().catch(function(e){n.logger.error("[".concat(n.id,"] Failed to play local media")),n.logger.error(e.message)})}},e.prototype.setupRemoteMedia=function(){var e,t,n,r,i=this;if(!this.session)throw new Error("Session does not exist.");var s=(null===(t=null===(e=this.options.media)||void 0===e?void 0:e.remote)||void 0===t?void 0:t.video)||(null===(r=null===(n=this.options.media)||void 0===n?void 0:n.remote)||void 0===r?void 0:r.audio);if(s){var o=this.remoteMediaStream;if(!o)throw new Error("Remote media stream undefiend.");s.autoplay=!0,s.srcObject=o,s.play().catch(function(e){i.logger.error("[".concat(i.id,"] Failed to play remote media")),i.logger.error(e.message)}),o.onaddtrack=function(){i.logger.log("[".concat(i.id,"] Remote media onaddtrack")),s.load(),s.play().catch(function(e){i.logger.error("[".concat(i.id,"] Failed to play remote media")),i.logger.error(e.message)})}}},e.prototype.terminate=function(){var e=this;if(this.logger.log("[".concat(this.id,"] Terminating...")),!this.session)return Promise.reject(new Error("Session does not exist."));switch(this.session.state){case SessionState.Initial:if(this.session instanceof Inviter)return this.session.cancel().then(function(){e.logger.log("[".concat(e.id,"] Inviter never sent INVITE (canceled)"))});if(this.session instanceof Invitation)return this.session.reject().then(function(){e.logger.log("[".concat(e.id,"] Invitation rejected (sent 480)"))});throw new Error("Unknown session type.");case SessionState.Establishing:if(this.session instanceof Inviter)return this.session.cancel().then(function(){e.logger.log("[".concat(e.id,"] Inviter canceled (sent CANCEL)"))});if(this.session instanceof Invitation)return this.session.reject().then(function(){e.logger.log("[".concat(e.id,"] Invitation rejected (sent 480)"))});throw new Error("Unknown session type.");case SessionState.Established:return this.session.bye().then(function(){e.logger.log("[".concat(e.id,"] Session ended (sent BYE)"))});case SessionState.Terminating:case SessionState.Terminated:break;default:throw new Error("Unknown state")}return this.logger.log("[".concat(this.id,"] Terminating in state ").concat(this.session.state,", no action taken")),Promise.resolve()}}();var audioElement=getAudio("ueRemoteAudio"),UeWebrtc=function(){function e(e){var t=this;this.registerRequested=!1,this.attemptingReconnection=!1,this.connectRequested=!1,this.requestDelegate={onAccept:function(e){},onProgress:function(e){},onRedirect:function(e){},onReject:function(e){return __awaiter(t,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,this.disconnect()];case 1:return e.sent(),[4,this.connect()];case 2:return e.sent(),this.register(),[2]}})})},onTrying:function(e){}},this.accept=function(){return __awaiter(t,void 0,void 0,function(){var e;return __generator(this,function(t){return e={sessionDescriptionHandlerOptions:{constraints:{audio:!0,video:!1}}},[2,this.Ginvitation.accept(e)]})})},this.ueUnregisterWebrtc=function(){return __awaiter(t,void 0,void 0,function(){return __generator(this,function(e){return this.registerer?[2,this.registerer.unregister({all:!0}).then(function(e){}).catch(function(e){})]:[2,!1]})})};var n=UserAgent.makeURI("sip:"+e.sip+"@"+e.server);if(!n)throw new Error("Failed to create URI");var r={onConnect:function(e){return __awaiter(t,void 0,void 0,function(){return __generator(this,function(e){return this.registerer&&this.registerRequested&&this.registerer.register().catch(function(e){}),[2]})})},onDisconnect:function(e){t.registerer&&t.registerer.unregister().catch(function(e){}),e&&t.attemptReconnection()},onInvite:function(e){t.Ginvitation=e;var n=e;n.delegate={onRefer:function(e){}},n.stateChange.addListener(function(e){switch(e){case SessionState.Initial:case SessionState.Establishing:break;case SessionState.Established:var t=n.sessionDescriptionHandler;if(!(t&&t instanceof SessionDescriptionHandler))throw new Error("Invalid session description handler.");audioElement&&assignStream(t.remoteMediaStream,audioElement);break;case SessionState.Terminating:case SessionState.Terminated:break;default:throw new Error("Unknown session state.")}});var r={sessionDescriptionHandlerOptions:{constraints:{audio:!0,video:!1}}},i=t.Ginvitation.incomingInviteRequest.message.headers["X-Calltype"][0].raw;"callout"!==i&&"callTask"!==i||e.accept(r).then(function(){}).catch(function(e){})}},i={logBuiltinEnabled:!1,delegate:r,displayName:"WEBRTC",uri:n,transportOptions:{server:"wss://"+e.server},authorizationUsername:e.sip,authorizationHa1:e.secret,reconnectionDelay:0};this.userAgent=new UserAgent(i),window.addEventListener("online",function(){return __awaiter(t,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return window.sessionStorage.getItem("kickoff")?[2]:[4,this.attemptReconnection()];case 1:return e.sent(),this.register(),[2]}})})})}return e.prototype.register=function(){var e=this;return this.registerRequested=!0,this.registerer||(this.registerer=new Registerer(this.userAgent,{expires:10}),this.registerer.stateChange.addListener(function(t){switch(t){case RegistererState.Initial:case RegistererState.Registered:case RegistererState.Unregistered:break;case RegistererState.Terminated:e.registerer=void 0;break;default:throw new Error("Unknown registerer state.")}})),this.registerer.register({requestDelegate:this.requestDelegate}).then(function(){})},e.prototype.unregister=function(e){return this.registerRequested=!1,this.registerer?this.registerer.unregister(e).then(function(){}):Promise.resolve()},e.prototype.attemptReconnection=function(e){var t=this;void 0===e&&(e=1);this.connectRequested&&(e>1||(this.attemptingReconnection=!0,setTimeout(function(){t.connectRequested?t.userAgent.reconnect().then(function(){t.attemptingReconnection=!1}).catch(function(n){t.attemptingReconnection=!1,t.attemptReconnection(++e)}):t.attemptingReconnection=!1},0)))},e.prototype.sendDTMF=function(e){if(!/^[0-9A-D#*,]$/.exec(e))return Promise.reject(new Error("Invalid DTMF tone."));if(!this.Ginvitation)return Promise.reject(new Error("Session does not exist."));var t={body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:"Signal="+e+"\r\nDuration=2000"}};return this.Ginvitation.info({requestOptions:t}).then(function(){})},e.prototype.disconnect=function(){return this.connectRequested=!1,this.userAgent.stop()},e.prototype.connect=function(){return this.connectRequested=!0,this.userAgent.state!==UserAgentState.Started?this.userAgent.start():this.userAgent.reconnect()},e.prototype.isConnected=function(){return this.userAgent.isConnected()},e}();const version$2="3.7.7",VERSION=version$2,_hasBuffer="function"==typeof Buffer,_TD="function"==typeof TextDecoder?new TextDecoder:void 0,_TE="function"==typeof TextEncoder?new TextEncoder:void 0,b64ch="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",b64chs=Array.prototype.slice.call(b64ch),b64tab=(e=>{let t={};return e.forEach((e,n)=>t[e]=n),t})(b64chs),b64re=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,_fromCC=String.fromCharCode.bind(String),_U8Afrom="function"==typeof Uint8Array.from?Uint8Array.from.bind(Uint8Array):e=>new Uint8Array(Array.prototype.slice.call(e,0)),_mkUriSafe=e=>e.replace(/=/g,"").replace(/[+\/]/g,e=>"+"==e?"-":"_"),_tidyB64=e=>e.replace(/[^A-Za-z0-9\+\/]/g,""),btoaPolyfill=e=>{let t,n,r,i,s="";const o=e.length%3;for(let o=0;o<e.length;){if((n=e.charCodeAt(o++))>255||(r=e.charCodeAt(o++))>255||(i=e.charCodeAt(o++))>255)throw new TypeError("invalid character found");t=n<<16|r<<8|i,s+=b64chs[t>>18&63]+b64chs[t>>12&63]+b64chs[t>>6&63]+b64chs[63&t]}return o?s.slice(0,o-3)+"===".substring(o):s},_btoa="function"==typeof btoa?e=>btoa(e):_hasBuffer?e=>Buffer.from(e,"binary").toString("base64"):btoaPolyfill,_fromUint8Array=_hasBuffer?e=>Buffer.from(e).toString("base64"):e=>{let t=[];for(let n=0,r=e.length;n<r;n+=4096)t.push(_fromCC.apply(null,e.subarray(n,n+4096)));return _btoa(t.join(""))},fromUint8Array=(e,t=!1)=>t?_mkUriSafe(_fromUint8Array(e)):_fromUint8Array(e),cb_utob=e=>{if(e.length<2)return(t=e.charCodeAt(0))<128?e:t<2048?_fromCC(192|t>>>6)+_fromCC(128|63&t):_fromCC(224|t>>>12&15)+_fromCC(128|t>>>6&63)+_fromCC(128|63&t);var t=65536+1024*(e.charCodeAt(0)-55296)+(e.charCodeAt(1)-56320);return _fromCC(240|t>>>18&7)+_fromCC(128|t>>>12&63)+_fromCC(128|t>>>6&63)+_fromCC(128|63&t)},re_utob=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,utob=e=>e.replace(re_utob,cb_utob),_encode=_hasBuffer?e=>Buffer.from(e,"utf8").toString("base64"):_TE?e=>_fromUint8Array(_TE.encode(e)):e=>_btoa(utob(e)),encode=(e,t=!1)=>t?_mkUriSafe(_encode(e)):_encode(e),encodeURI=e=>encode(e,!0),re_btou=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,cb_btou=e=>{switch(e.length){case 4:var t=((7&e.charCodeAt(0))<<18|(63&e.charCodeAt(1))<<12|(63&e.charCodeAt(2))<<6|63&e.charCodeAt(3))-65536;return _fromCC((t>>>10)+55296)+_fromCC(56320+(1023&t));case 3:return _fromCC((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return _fromCC((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},btou=e=>e.replace(re_btou,cb_btou),atobPolyfill=e=>{if(e=e.replace(/\s+/g,""),!b64re.test(e))throw new TypeError("malformed base64.");e+="==".slice(2-(3&e.length));let t,n,r,i="";for(let s=0;s<e.length;)t=b64tab[e.charAt(s++)]<<18|b64tab[e.charAt(s++)]<<12|(n=b64tab[e.charAt(s++)])<<6|(r=b64tab[e.charAt(s++)]),i+=64===n?_fromCC(t>>16&255):64===r?_fromCC(t>>16&255,t>>8&255):_fromCC(t>>16&255,t>>8&255,255&t);return i},_atob="function"==typeof atob?e=>atob(_tidyB64(e)):_hasBuffer?e=>Buffer.from(e,"base64").toString("binary"):atobPolyfill,_toUint8Array=_hasBuffer?e=>_U8Afrom(Buffer.from(e,"base64")):e=>_U8Afrom(_atob(e).split("").map(e=>e.charCodeAt(0))),toUint8Array=e=>_toUint8Array(_unURI(e)),_decode=_hasBuffer?e=>Buffer.from(e,"base64").toString("utf8"):_TD?e=>_TD.decode(_toUint8Array(e)):e=>btou(_atob(e)),_unURI=e=>_tidyB64(e.replace(/[-_]/g,e=>"-"==e?"+":"/")),decode=e=>_decode(_unURI(e)),isValid=e=>{if("string"!=typeof e)return!1;const t=e.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(t)||!/[^\s0-9a-zA-Z\-_]/.test(t)},_noEnum=e=>({value:e,enumerable:!1,writable:!0,configurable:!0}),extendString=function(){const e=(e,t)=>Object.defineProperty(String.prototype,e,_noEnum(t));e("fromBase64",function(){return decode(this)}),e("toBase64",function(e){return encode(this,e)}),e("toBase64URI",function(){return encode(this,!0)}),e("toBase64URL",function(){return encode(this,!0)}),e("toUint8Array",function(){return toUint8Array(this)})},extendUint8Array=function(){const e=(e,t)=>Object.defineProperty(Uint8Array.prototype,e,_noEnum(t));e("toBase64",function(e){return fromUint8Array(this,e)}),e("toBase64URI",function(){return fromUint8Array(this,!0)}),e("toBase64URL",function(){return fromUint8Array(this,!0)})},extendBuiltins=()=>{extendString(),extendUint8Array()},gBase64={version:version$2,VERSION:VERSION,atob:_atob,atobPolyfill:atobPolyfill,btoa:_btoa,btoaPolyfill:btoaPolyfill,fromBase64:decode,toBase64:encode,encode:encode,encodeURI:encodeURI,encodeURL:encodeURI,utob:utob,btou:btou,decode:decode,isValid:isValid,fromUint8Array:fromUint8Array,toUint8Array:toUint8Array,extendString:extendString,extendUint8Array:extendUint8Array,extendBuiltins:extendBuiltins};var global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch(t){try{return cachedSetTimeout.call(null,e,0)}catch(t){return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch(t){try{return cachedClearTimeout.call(null,e)}catch(t){return cachedClearTimeout.call(this,e)}}}"function"==typeof global$1.setTimeout&&(cachedSetTimeout=setTimeout),"function"==typeof global$1.clearTimeout&&(cachedClearTimeout=clearTimeout);var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&&currentQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex<t;)currentQueue&&currentQueue[queueIndex].run();queueIndex=-1,t=queue.length}currentQueue=null,draining=!1,runClearTimeout(e)}}function nextTick(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];queue.push(new Item(e,t)),1!==queue.length||draining||runTimeout(drainQueue)}function Item(e,t){this.fun=e,this.array=t}Item.prototype.run=function(){this.fun.apply(null,this.array)};var title="browser",platform="browser",browser=!0,env={},argv=[],version$1="",versions={},release={},config={};function noop(){}var on=noop,addListener=noop,once=noop,off=noop,removeListener=noop,removeAllListeners=noop,emit=noop;function binding(e){throw new Error("process.binding is not supported")}function cwd(){return"/"}function chdir(e){throw new Error("process.chdir is not supported")}function umask(){return 0}var performance=global$1.performance||{},performanceNow=performance.now||performance.mozNow||performance.msNow||performance.oNow||performance.webkitNow||function(){return(new Date).getTime()};function hrtime(e){var t=.001*performanceNow.call(performance),n=Math.floor(t),r=Math.floor(t%1*1e9);return e&&(n-=e[0],(r-=e[1])<0&&(n--,r+=1e9)),[n,r]}var startTime=new Date;function uptime(){return(new Date-startTime)/1e3}var browser$1={nextTick:nextTick,title:title,browser:browser,env:env,argv:argv,version:version$1,versions:versions,on:on,addListener:addListener,once:once,off:off,removeListener:removeListener,removeAllListeners:removeAllListeners,emit:emit,binding:binding,cwd:cwd,chdir:chdir,umask:umask,hrtime:hrtime,platform:platform,release:release,config:config,uptime:uptime},commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var md5$1={exports:{}};(function(module){(function(){var ERROR="input is invalid type",WINDOW="object"==typeof window,root=WINDOW?window:{};root.JS_MD5_NO_WINDOW&&(WINDOW=!1);var WEB_WORKER=!WINDOW&&"object"==typeof self,NODE_JS=!root.JS_MD5_NO_NODE_JS&&"object"==typeof browser$1&&browser$1.versions&&browser$1.versions.node;NODE_JS?root=commonjsGlobal:WEB_WORKER&&(root=self);var COMMON_JS=!root.JS_MD5_NO_COMMON_JS&&module.exports,ARRAY_BUFFER=!root.JS_MD5_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,HEX_CHARS="0123456789abcdef".split(""),EXTRA=[128,32768,8388608,-2147483648],SHIFT=[0,8,16,24],OUTPUT_TYPES=["hex","array","digest","buffer","arrayBuffer","base64"],BASE64_ENCODE_CHAR="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),blocks=[],buffer8;if(ARRAY_BUFFER){var buffer=new ArrayBuffer(68);buffer8=new Uint8Array(buffer),blocks=new Uint32Array(buffer)}!root.JS_MD5_NO_NODE_JS&&Array.isArray||(Array.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),!ARRAY_BUFFER||!root.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});var createOutputMethod=function(e){return function(t){return new Md5(!0).update(t)[e]()}},createMethod=function(){var e=createOutputMethod("hex");NODE_JS&&(e=nodeWrap(e)),e.create=function(){return new Md5},e.update=function(t){return e.create().update(t)};for(var t=0;t<OUTPUT_TYPES.length;++t){var n=OUTPUT_TYPES[t];e[n]=createOutputMethod(n)}return e},nodeWrap=function(method){var crypto=eval("require('crypto')"),Buffer=eval("require('buffer').Buffer"),nodeMethod=function(e){if("string"==typeof e)return crypto.createHash("md5").update(e,"utf8").digest("hex");if(null==e)throw ERROR;return e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),Array.isArray(e)||ArrayBuffer.isView(e)||e.constructor===Buffer?crypto.createHash("md5").update(new Buffer(e)).digest("hex"):method(e)};return nodeMethod};function Md5(e){if(e)blocks[0]=blocks[16]=blocks[1]=blocks[2]=blocks[3]=blocks[4]=blocks[5]=blocks[6]=blocks[7]=blocks[8]=blocks[9]=blocks[10]=blocks[11]=blocks[12]=blocks[13]=blocks[14]=blocks[15]=0,this.blocks=blocks,this.buffer8=buffer8;else if(ARRAY_BUFFER){var t=new ArrayBuffer(68);this.buffer8=new Uint8Array(t),this.blocks=new Uint32Array(t)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}Md5.prototype.update=function(e){if(!this.finalized){var t,n=typeof e;if("string"!==n){if("object"!==n)throw ERROR;if(null===e)throw ERROR;if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!(Array.isArray(e)||ARRAY_BUFFER&&ArrayBuffer.isView(e)))throw ERROR;t=!0}for(var r,i,s=0,o=e.length,a=this.blocks,c=this.buffer8;s<o;){if(this.hashed&&(this.hashed=!1,a[0]=a[16],a[16]=a[1]=a[2]=a[3]=a[4]=a[5]=a[6]=a[7]=a[8]=a[9]=a[10]=a[11]=a[12]=a[13]=a[14]=a[15]=0),t)if(ARRAY_BUFFER)for(i=this.start;s<o&&i<64;++s)c[i++]=e[s];else for(i=this.start;s<o&&i<64;++s)a[i>>2]|=e[s]<<SHIFT[3&i++];else if(ARRAY_BUFFER)for(i=this.start;s<o&&i<64;++s)(r=e.charCodeAt(s))<128?c[i++]=r:r<2048?(c[i++]=192|r>>6,c[i++]=128|63&r):r<55296||r>=57344?(c[i++]=224|r>>12,c[i++]=128|r>>6&63,c[i++]=128|63&r):(r=65536+((1023&r)<<10|1023&e.charCodeAt(++s)),c[i++]=240|r>>18,c[i++]=128|r>>12&63,c[i++]=128|r>>6&63,c[i++]=128|63&r);else for(i=this.start;s<o&&i<64;++s)(r=e.charCodeAt(s))<128?a[i>>2]|=r<<SHIFT[3&i++]:r<2048?(a[i>>2]|=(192|r>>6)<<SHIFT[3&i++],a[i>>2]|=(128|63&r)<<SHIFT[3&i++]):r<55296||r>=57344?(a[i>>2]|=(224|r>>12)<<SHIFT[3&i++],a[i>>2]|=(128|r>>6&63)<<SHIFT[3&i++],a[i>>2]|=(128|63&r)<<SHIFT[3&i++]):(r=65536+((1023&r)<<10|1023&e.charCodeAt(++s)),a[i>>2]|=(240|r>>18)<<SHIFT[3&i++],a[i>>2]|=(128|r>>12&63)<<SHIFT[3&i++],a[i>>2]|=(128|r>>6&63)<<SHIFT[3&i++],a[i>>2]|=(128|63&r)<<SHIFT[3&i++]);this.lastByteIndex=i,this.bytes+=i-this.start,i>=64?(this.start=i-64,this.hash(),this.hashed=!0):this.start=i}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this}},Md5.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[t>>2]|=EXTRA[3&t],t>=56&&(this.hashed||this.hash(),e[0]=e[16],e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.bytes<<3,e[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},Md5.prototype.hash=function(){var e,t,n,r,i,s,o=this.blocks;this.first?t=((t=((e=((e=o[0]-680876937)<<7|e>>>25)-271733879|0)^(n=((n=(-271733879^(r=((r=(-1732584194^2004318071&e)+o[1]-117830708)<<12|r>>>20)+e|0)&(-271733879^e))+o[2]-1126478375)<<17|n>>>15)+r|0)&(r^e))+o[3]-1316259209)<<22|t>>>10)+n|0:(e=this.h0,t=this.h1,n=this.h2,t=((t+=((e=((e+=((r=this.h3)^t&(n^r))+o[0]-680876936)<<7|e>>>25)+t|0)^(n=((n+=(t^(r=((r+=(n^e&(t^n))+o[1]-389564586)<<12|r>>>20)+e|0)&(e^t))+o[2]+606105819)<<17|n>>>15)+r|0)&(r^e))+o[3]-1044525330)<<22|t>>>10)+n|0),t=((t+=((e=((e+=(r^t&(n^r))+o[4]-176418897)<<7|e>>>25)+t|0)^(n=((n+=(t^(r=((r+=(n^e&(t^n))+o[5]+1200080426)<<12|r>>>20)+e|0)&(e^t))+o[6]-1473231341)<<17|n>>>15)+r|0)&(r^e))+o[7]-45705983)<<22|t>>>10)+n|0,t=((t+=((e=((e+=(r^t&(n^r))+o[8]+1770035416)<<7|e>>>25)+t|0)^(n=((n+=(t^(r=((r+=(n^e&(t^n))+o[9]-1958414417)<<12|r>>>20)+e|0)&(e^t))+o[10]-42063)<<17|n>>>15)+r|0)&(r^e))+o[11]-1990404162)<<22|t>>>10)+n|0,t=((t+=((e=((e+=(r^t&(n^r))+o[12]+1804603682)<<7|e>>>25)+t|0)^(n=((n+=(t^(r=((r+=(n^e&(t^n))+o[13]-40341101)<<12|r>>>20)+e|0)&(e^t))+o[14]-1502002290)<<17|n>>>15)+r|0)&(r^e))+o[15]+1236535329)<<22|t>>>10)+n|0,t=((t+=((r=((r+=(t^n&((e=((e+=(n^r&(t^n))+o[1]-165796510)<<5|e>>>27)+t|0)^t))+o[6]-1069501632)<<9|r>>>23)+e|0)^e&((n=((n+=(e^t&(r^e))+o[11]+643717713)<<14|n>>>18)+r|0)^r))+o[0]-373897302)<<20|t>>>12)+n|0,t=((t+=((r=((r+=(t^n&((e=((e+=(n^r&(t^n))+o[5]-701558691)<<5|e>>>27)+t|0)^t))+o[10]+38016083)<<9|r>>>23)+e|0)^e&((n=((n+=(e^t&(r^e))+o[15]-660478335)<<14|n>>>18)+r|0)^r))+o[4]-405537848)<<20|t>>>12)+n|0,t=((t+=((r=((r+=(t^n&((e=((e+=(n^r&(t^n))+o[9]+568446438)<<5|e>>>27)+t|0)^t))+o[14]-1019803690)<<9|r>>>23)+e|0)^e&((n=((n+=(e^t&(r^e))+o[3]-187363961)<<14|n>>>18)+r|0)^r))+o[8]+1163531501)<<20|t>>>12)+n|0,t=((t+=((r=((r+=(t^n&((e=((e+=(n^r&(t^n))+o[13]-1444681467)<<5|e>>>27)+t|0)^t))+o[2]-51403784)<<9|r>>>23)+e|0)^e&((n=((n+=(e^t&(r^e))+o[7]+1735328473)<<14|n>>>18)+r|0)^r))+o[12]-1926607734)<<20|t>>>12)+n|0,t=((t+=((s=(r=((r+=((i=t^n)^(e=((e+=(i^r)+o[5]-378558)<<4|e>>>28)+t|0))+o[8]-2022574463)<<11|r>>>21)+e|0)^e)^(n=((n+=(s^t)+o[11]+1839030562)<<16|n>>>16)+r|0))+o[14]-35309556)<<23|t>>>9)+n|0,t=((t+=((s=(r=((r+=((i=t^n)^(e=((e+=(i^r)+o[1]-1530992060)<<4|e>>>28)+t|0))+o[4]+1272893353)<<11|r>>>21)+e|0)^e)^(n=((n+=(s^t)+o[7]-155497632)<<16|n>>>16)+r|0))+o[10]-1094730640)<<23|t>>>9)+n|0,t=((t+=((s=(r=((r+=((i=t^n)^(e=((e+=(i^r)+o[13]+681279174)<<4|e>>>28)+t|0))+o[0]-358537222)<<11|r>>>21)+e|0)^e)^(n=((n+=(s^t)+o[3]-722521979)<<16|n>>>16)+r|0))+o[6]+76029189)<<23|t>>>9)+n|0,t=((t+=((s=(r=((r+=((i=t^n)^(e=((e+=(i^r)+o[9]-640364487)<<4|e>>>28)+t|0))+o[12]-421815835)<<11|r>>>21)+e|0)^e)^(n=((n+=(s^t)+o[15]+530742520)<<16|n>>>16)+r|0))+o[2]-995338651)<<23|t>>>9)+n|0,t=((t+=((r=((r+=(t^((e=((e+=(n^(t|~r))+o[0]-198630844)<<6|e>>>26)+t|0)|~n))+o[7]+1126891415)<<10|r>>>22)+e|0)^((n=((n+=(e^(r|~t))+o[14]-1416354905)<<15|n>>>17)+r|0)|~e))+o[5]-57434055)<<21|t>>>11)+n|0,t=((t+=((r=((r+=(t^((e=((e+=(n^(t|~r))+o[12]+1700485571)<<6|e>>>26)+t|0)|~n))+o[3]-1894986606)<<10|r>>>22)+e|0)^((n=((n+=(e^(r|~t))+o[10]-1051523)<<15|n>>>17)+r|0)|~e))+o[1]-2054922799)<<21|t>>>11)+n|0,t=((t+=((r=((r+=(t^((e=((e+=(n^(t|~r))+o[8]+1873313359)<<6|e>>>26)+t|0)|~n))+o[15]-30611744)<<10|r>>>22)+e|0)^((n=((n+=(e^(r|~t))+o[6]-1560198380)<<15|n>>>17)+r|0)|~e))+o[13]+1309151649)<<21|t>>>11)+n|0,t=((t+=((r=((r+=(t^((e=((e+=(n^(t|~r))+o[4]-145523070)<<6|e>>>26)+t|0)|~n))+o[11]-1120210379)<<10|r>>>22)+e|0)^((n=((n+=(e^(r|~t))+o[2]+718787259)<<15|n>>>17)+r|0)|~e))+o[9]-343485551)<<21|t>>>11)+n|0,this.first?(this.h0=e+1732584193|0,this.h1=t-271733879|0,this.h2=n-1732584194|0,this.h3=r+271733878|0,this.first=!1):(this.h0=this.h0+e|0,this.h1=this.h1+t|0,this.h2=this.h2+n|0,this.h3=this.h3+r|0)},Md5.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3;return HEX_CHARS[e>>4&15]+HEX_CHARS[15&e]+HEX_CHARS[e>>12&15]+HEX_CHARS[e>>8&15]+HEX_CHARS[e>>20&15]+HEX_CHARS[e>>16&15]+HEX_CHARS[e>>28&15]+HEX_CHARS[e>>24&15]+HEX_CHARS[t>>4&15]+HEX_CHARS[15&t]+HEX_CHARS[t>>12&15]+HEX_CHARS[t>>8&15]+HEX_CHARS[t>>20&15]+HEX_CHARS[t>>16&15]+HEX_CHARS[t>>28&15]+HEX_CHARS[t>>24&15]+HEX_CHARS[n>>4&15]+HEX_CHARS[15&n]+HEX_CHARS[n>>12&15]+HEX_CHARS[n>>8&15]+HEX_CHARS[n>>20&15]+HEX_CHARS[n>>16&15]+HEX_CHARS[n>>28&15]+HEX_CHARS[n>>24&15]+HEX_CHARS[r>>4&15]+HEX_CHARS[15&r]+HEX_CHARS[r>>12&15]+HEX_CHARS[r>>8&15]+HEX_CHARS[r>>20&15]+HEX_CHARS[r>>16&15]+HEX_CHARS[r>>28&15]+HEX_CHARS[r>>24&15]},Md5.prototype.toString=Md5.prototype.hex,Md5.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3;return[255&e,e>>8&255,e>>16&255,e>>24&255,255&t,t>>8&255,t>>16&255,t>>24&255,255&n,n>>8&255,n>>16&255,n>>24&255,255&r,r>>8&255,r>>16&255,r>>24&255]},Md5.prototype.array=Md5.prototype.digest,Md5.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(16),t=new Uint32Array(e);return t[0]=this.h0,t[1]=this.h1,t[2]=this.h2,t[3]=this.h3,e},Md5.prototype.buffer=Md5.prototype.arrayBuffer,Md5.prototype.base64=function(){for(var e,t,n,r="",i=this.array(),s=0;s<15;)e=i[s++],t=i[s++],n=i[s++],r+=BASE64_ENCODE_CHAR[e>>>2]+BASE64_ENCODE_CHAR[63&(e<<4|t>>>4)]+BASE64_ENCODE_CHAR[63&(t<<2|n>>>6)]+BASE64_ENCODE_CHAR[63&n];return e=i[s],r+=BASE64_ENCODE_CHAR[e>>>2]+BASE64_ENCODE_CHAR[e<<4&63]+"=="};var exports=createMethod();COMMON_JS?module.exports=exports:root.md5=exports})()})(md5$1);var md5Exports=md5$1.exports,md5=getDefaultExportFromCjs(md5Exports),BI_RM="0123456789abcdefghijklmnopqrstuvwxyz";function int2char(e){return BI_RM.charAt(e)}function op_and(e,t){return e&t}function op_or(e,t){return e|t}function op_xor(e,t){return e^t}function op_andnot(e,t){return e&~t}function lbit(e){if(0==e)return-1;var t=0;return 65535&e||(e>>=16,t+=16),255&e||(e>>=8,t+=8),15&e||(e>>=4,t+=4),3&e||(e>>=2,t+=2),1&e||++t,t}function cbit(e){for(var t=0;0!=e;)e&=e-1,++t;return t}var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",b64pad="=",decoder$1;function hex2b64(e){var t,n,r="";for(t=0;t+3<=e.length;t+=3)n=parseInt(e.substring(t,t+3),16),r+=b64map.charAt(n>>6)+b64map.charAt(63&n);for(t+1==e.length?(n=parseInt(e.substring(t,t+1),16),r+=b64map.charAt(n<<2)):t+2==e.length&&(n=parseInt(e.substring(t,t+2),16),r+=b64map.charAt(n>>2)+b64map.charAt((3&n)<<4));(3&r.length)>0;)r+=b64pad;return r}function b64tohex(e){var t,n="",r=0,i=0;for(t=0;t<e.length&&e.charAt(t)!=b64pad;++t){var s=b64map.indexOf(e.charAt(t));s<0||(0==r?(n+=int2char(s>>2),i=3&s,r=1):1==r?(n+=int2char(i<<2|s>>4),i=15&s,r=2):2==r?(n+=int2char(i),n+=int2char(s>>2),i=3&s,r=3):(n+=int2char(i<<2|s>>4),n+=int2char(15&s),r=0))}return 1==r&&(n+=int2char(i<<2)),n}var Hex={decode:function(e){var t;if(void 0===decoder$1){var n="0123456789ABCDEF",r=" \f\n\r\t \u2028\u2029";for(decoder$1={},t=0;t<16;++t)decoder$1[n.charAt(t)]=t;for(n=n.toLowerCase(),t=10;t<16;++t)decoder$1[n.charAt(t)]=t;for(t=0;t<8;++t)decoder$1[r.charAt(t)]=-1}var i=[],s=0,o=0;for(t=0;t<e.length;++t){var a=e.charAt(t);if("="==a)break;if(-1!=(a=decoder$1[a])){if(void 0===a)throw new Error("Illegal character at offset "+t);s|=a,++o>=2?(i[i.length]=s,s=0,o=0):s<<=4}}if(o)throw new Error("Hex encoding incomplete: 4 bits missing");return i}},decoder,Base64={decode:function(e){var t;if(void 0===decoder){var n="= \f\n\r\t \u2028\u2029";for(decoder=Object.create(null),t=0;t<64;++t)decoder["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(t)]=t;for(decoder["-"]=62,decoder._=63,t=0;t<9;++t)decoder[n.charAt(t)]=-1}var r=[],i=0,s=0;for(t=0;t<e.length;++t){var o=e.charAt(t);if("="==o)break;if(-1!=(o=decoder[o])){if(void 0===o)throw new Error("Illegal character at offset "+t);i|=o,++s>=4?(r[r.length]=i>>16,r[r.length]=i>>8&255,r[r.length]=255&i,i=0,s=0):i<<=6}}switch(s){case 1:throw new Error("Base64 encoding incomplete: at least 2 bits missing");case 2:r[r.length]=i>>10;break;case 3:r[r.length]=i>>16,r[r.length]=i>>8&255}return r},re:/-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/,unarmor:function(e){var t=Base64.re.exec(e);if(t)if(t[1])e=t[1];else{if(!t[2])throw new Error("RegExp out of sync");e=t[2]}return Base64.decode(e)}},max=1e13,Int10=function(){function e(e){this.buf=[+e||0]}return e.prototype.mulAdd=function(e,t){var n,r,i=this.buf,s=i.length;for(n=0;n<s;++n)(r=i[n]*e+t)<max?t=0:r-=(t=0|r/max)*max,i[n]=r;t>0&&(i[n]=t)},e.prototype.sub=function(e){var t,n,r=this.buf,i=r.length;for(t=0;t<i;++t)(n=r[t]-e)<0?(n+=max,e=1):e=0,r[t]=n;for(;0===r[r.length-1];)r.pop()},e.prototype.toString=function(e){if(10!=(e||10))throw new Error("only base 10 is supported");for(var t=this.buf,n=t[t.length-1].toString(),r=t.length-2;r>=0;--r)n+=(max+t[r]).toString().substring(1);return n},e.prototype.valueOf=function(){for(var e=this.buf,t=0,n=e.length-1;n>=0;--n)t=t*max+e[n];return t},e.prototype.simplify=function(){var e=this.buf;return 1==e.length?e[0]:this},e}(),ellipsis="…",reTimeS=/^(\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/,reTimeL=/^(\d\d\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/;function stringCut(e,t){return e.length>t&&(e=e.substring(0,t)+ellipsis),e}var Stream=function(){function e(t,n){this.hexDigits="0123456789ABCDEF",t instanceof e?(this.enc=t.enc,this.pos=t.pos):(this.enc=t,this.pos=n)}return e.prototype.get=function(e){if(void 0===e&&(e=this.pos++),e>=this.enc.length)throw new Error("Requesting byte offset ".concat(e," on a stream of length ").concat(this.enc.length));return"string"==typeof this.enc?this.enc.charCodeAt(e):this.enc[e]},e.prototype.hexByte=function(e){return this.hexDigits.charAt(e>>4&15)+this.hexDigits.charAt(15&e)},e.prototype.hexDump=function(e,t,n){for(var r="",i=e;i<t;++i)if(r+=this.hexByte(this.get(i)),!0!==n)switch(15&i){case 7:r+=" ";break;case 15:r+="\n";break;default:r+=" "}return r},e.prototype.isASCII=function(e,t){for(var n=e;n<t;++n){var r=this.get(n);if(r<32||r>176)return!1}return!0},e.prototype.parseStringISO=function(e,t){for(var n="",r=e;r<t;++r)n+=String.fromCharCode(this.get(r));return n},e.prototype.parseStringUTF=function(e,t){for(var n="",r=e;r<t;){var i=this.get(r++);n+=i<128?String.fromCharCode(i):i>191&&i<224?String.fromCharCode((31&i)<<6|63&this.get(r++)):String.fromCharCode((15&i)<<12|(63&this.get(r++))<<6|63&this.get(r++))}return n},e.prototype.parseStringBMP=function(e,t){for(var n,r,i="",s=e;s<t;)n=this.get(s++),r=this.get(s++),i+=String.fromCharCode(n<<8|r);return i},e.prototype.parseTime=function(e,t,n){var r=this.parseStringISO(e,t),i=(n?reTimeS:reTimeL).exec(r);return i?(n&&(i[1]=+i[1],i[1]+=+i[1]<70?2e3:1900),r=i[1]+"-"+i[2]+"-"+i[3]+" "+i[4],i[5]&&(r+=":"+i[5],i[6]&&(r+=":"+i[6],i[7]&&(r+="."+i[7]))),i[8]&&(r+=" UTC","Z"!=i[8]&&(r+=i[8],i[9]&&(r+=":"+i[9]))),r):"Unrecognized time: "+r},e.prototype.parseInteger=function(e,t){for(var n,r=this.get(e),i=r>127,s=i?255:0,o="";r==s&&++e<t;)r=this.get(e);if(0===(n=t-e))return i?-1:0;if(n>4){for(o=r,n<<=3;!(128&(+o^s));)o=+o<<1,--n;o="("+n+" bit)\n"}i&&(r-=256);for(var a=new Int10(r),c=e+1;c<t;++c)a.mulAdd(256,this.get(c));return o+a.toString()},e.prototype.parseBitString=function(e,t,n){for(var r=this.get(e),i="("+((t-e-1<<3)-r)+" bit)\n",s="",o=e+1;o<t;++o){for(var a=this.get(o),c=o==t-1?r:0,u=7;u>=c;--u)s+=a>>u&1?"1":"0";if(s.length>n)return i+stringCut(s,n)}return i+s},e.prototype.parseOctetString=function(e,t,n){if(this.isASCII(e,t))return stringCut(this.parseStringISO(e,t),n);var r=t-e,i="("+r+" byte)\n";r>(n/=2)&&(t=e+n);for(var s=e;s<t;++s)i+=this.hexByte(this.get(s));return r>n&&(i+=ellipsis),i},e.prototype.parseOID=function(e,t,n){for(var r="",i=new Int10,s=0,o=e;o<t;++o){var a=this.get(o);if(i.mulAdd(128,127&a),s+=7,!(128&a)){if(""===r)if((i=i.simplify())instanceof Int10)i.sub(80),r="2."+i.toString();else{var c=i<80?i<40?0:1:2;r=c+"."+(i-40*c)}else r+="."+i.toString();if(r.length>n)return stringCut(r,n);i=new Int10,s=0}}return s>0&&(r+=".incomplete"),r},e}(),ASN1=function(){function e(e,t,n,r,i){if(!(r instanceof ASN1Tag))throw new Error("Invalid tag value.");this.stream=e,this.header=t,this.length=n,this.tag=r,this.sub=i}return e.prototype.typeName=function(){switch(this.tag.tagClass){case 0:switch(this.tag.tagNumber){case 0:return"EOC";case 1:return"BOOLEAN";case 2:return"INTEGER";case 3:return"BIT_STRING";case 4:return"OCTET_STRING";case 5:return"NULL";case 6:return"OBJECT_IDENTIFIER";case 7:return"ObjectDescriptor";case 8:return"EXTERNAL";case 9:return"REAL";case 10:return"ENUMERATED";case 11:return"EMBEDDED_PDV";case 12:return"UTF8String";case 16:return"SEQUENCE";case 17:return"SET";case 18:return"NumericString";case 19:return"PrintableString";case 20:return"TeletexString";case 21:return"VideotexString";case 22:return"IA5String";case 23:return"UTCTime";case 24:return"GeneralizedTime";case 25:return"GraphicString";case 26:return"VisibleString";case 27:return"GeneralString";case 28:return"UniversalString";case 30:return"BMPString"}return"Universal_"+this.tag.tagNumber.toString();case 1:return"Application_"+this.tag.tagNumber.toString();case 2:return"["+this.tag.tagNumber.toString()+"]";case 3:return"Private_"+this.tag.tagNumber.toString()}},e.prototype.content=function(e){if(void 0===this.tag)return null;void 0===e&&(e=1/0);var t=this.posContent(),n=Math.abs(this.length);if(!this.tag.isUniversal())return null!==this.sub?"("+this.sub.length+" elem)":this.stream.parseOctetString(t,t+n,e);switch(this.tag.tagNumber){case 1:return 0===this.stream.get(t)?"false":"true";case 2:return this.stream.parseInteger(t,t+n);case 3:return this.sub?"("+this.sub.length+" elem)":this.stream.parseBitString(t,t+n,e);case 4:return this.sub?"("+this.sub.length+" elem)":this.stream.parseOctetString(t,t+n,e);case 6:return this.stream.parseOID(t,t+n,e);case 16:case 17:return null!==this.sub?"("+this.sub.length+" elem)":"(no elem)";case 12:return stringCut(this.stream.parseStringUTF(t,t+n),e);case 18:case 19:case 20:case 21:case 22:case 26:return stringCut(this.stream.parseStringISO(t,t+n),e);case 30:return stringCut(this.stream.parseStringBMP(t,t+n),e);case 23:case 24:return this.stream.parseTime(t,t+n,23==this.tag.tagNumber)}return null},e.prototype.toString=function(){return this.typeName()+"@"+this.stream.pos+"[header:"+this.header+",length:"+this.length+",sub:"+(null===this.sub?"null":this.sub.length)+"]"},e.prototype.toPrettyString=function(e){void 0===e&&(e="");var t=e+this.typeName()+" @"+this.stream.pos;if(this.length>=0&&(t+="+"),t+=this.length,this.tag.tagConstructed?t+=" (constructed)":!this.tag.isUniversal()||3!=this.tag.tagNumber&&4!=this.tag.tagNumber||null===this.sub||(t+=" (encapsulates)"),t+="\n",null!==this.sub){e+=" ";for(var n=0,r=this.sub.length;n<r;++n)t+=this.sub[n].toPrettyString(e)}return t},e.prototype.posStart=function(){return this.stream.pos},e.prototype.posContent=function(){return this.stream.pos+this.header},e.prototype.posEnd=function(){return this.stream.pos+this.header+Math.abs(this.length)},e.prototype.toHexString=function(){return this.stream.hexDump(this.posStart(),this.posEnd(),!0)},e.decodeLength=function(e){var t=e.get(),n=127&t;if(n==t)return n;if(n>6)throw new Error("Length over 48 bits not supported at position "+(e.pos-1));if(0===n)return null;t=0;for(var r=0;r<n;++r)t=256*t+e.get();return t},e.prototype.getHexStringValue=function(){var e=this.toHexString(),t=2*this.header,n=2*this.length;return e.substr(t,n)},e.decode=function(t){var n;n=t instanceof Stream?t:new Stream(t,0);var r=new Stream(n),i=new ASN1Tag(n),s=e.decodeLength(n),o=n.pos,a=o-r.pos,c=null,u=function(){var t=[];if(null!==s){for(var r=o+s;n.pos<r;)t[t.length]=e.decode(n);if(n.pos!=r)throw new Error("Content size is not correct for container starting at offset "+o)}else try{for(;;){var i=e.decode(n);if(i.tag.isEOC())break;t[t.length]=i}s=o-n.pos}catch(e){throw new Error("Exception while decoding undefined length content: "+e)}return t};if(i.tagConstructed)c=u();else if(i.isUniversal()&&(3==i.tagNumber||4==i.tagNumber))try{if(3==i.tagNumber&&0!=n.get())throw new Error("BIT STRINGs with unused bits cannot encapsulate.");c=u();for(var l=0;l<c.length;++l)if(c[l].tag.isEOC())throw new Error("EOC is not supposed to be actual content.")}catch(e){c=null}if(null===c){if(null===s)throw new Error("We can't skip over an invalid tag with undefined length at offset "+o);n.pos=o+Math.abs(s)}return new e(r,a,s,i,c)},e}(),ASN1Tag=function(){function e(e){var t=e.get();if(this.tagClass=t>>6,this.tagConstructed=!!(32&t),this.tagNumber=31&t,31==this.tagNumber){var n=new Int10;do{t=e.get(),n.mulAdd(128,127&t)}while(128&t);this.tagNumber=n.simplify()}}return e.prototype.isUniversal=function(){return 0===this.tagClass},e.prototype.isEOC=function(){return 0===this.tagClass&&0===this.tagNumber},e}(),dbits,canary=0xdeadbeefcafe,j_lm=15715070==(16777215&canary),lowprimes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],lplim=(1<<26)/lowprimes[lowprimes.length-1],BigInteger=function(){function e(e,t,n){null!=e&&("number"==typeof e?this.fromNumber(e,t,n):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}return e.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var n,r=(1<<t)-1,i=!1,s="",o=this.t,a=this.DB-o*this.DB%t;if(o-- >0)for(a<this.DB&&(n=this[o]>>a)>0&&(i=!0,s=int2char(n));o>=0;)a<t?(n=(this[o]&(1<<a)-1)<<t-a,n|=this[--o]>>(a+=this.DB-t)):(n=this[o]>>(a-=t)&r,a<=0&&(a+=this.DB,--o)),n>0&&(i=!0),i&&(s+=int2char(n));return i?s:"0"},e.prototype.negate=function(){var t=nbi();return e.ZERO.subTo(this,t),t},e.prototype.abs=function(){return this.s<0?this.negate():this},e.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var n=this.t;if(0!=(t=n-e.t))return this.s<0?-t:t;for(;--n>=0;)if(0!=(t=this[n]-e[n]))return t;return 0},e.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+nbits(this[this.t-1]^this.s&this.DM)},e.prototype.mod=function(t){var n=nbi();return this.abs().divRemTo(t,null,n),this.s<0&&n.compareTo(e.ZERO)>0&&t.subTo(n,n),n},e.prototype.modPowInt=function(e,t){var n;return n=e<256||t.isEven()?new Classic(t):new Montgomery(t),this.exp(e,n)},e.prototype.clone=function(){var e=nbi();return this.copyTo(e),e},e.prototype.intValue=function(){if(this.s<0){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<<this.DB|this[0]},e.prototype.byteValue=function(){return 0==this.t?this.s:this[0]<<24>>24},e.prototype.shortValue=function(){return 0==this.t?this.s:this[0]<<16>>16},e.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1},e.prototype.toByteArray=function(){var e=this.t,t=[];t[0]=this.s;var n,r=this.DB-e*this.DB%8,i=0;if(e-- >0)for(r<this.DB&&(n=this[e]>>r)!=(this.s&this.DM)>>r&&(t[i++]=n|this.s<<this.DB-r);e>=0;)r<8?(n=(this[e]&(1<<r)-1)<<8-r,n|=this[--e]>>(r+=this.DB-8)):(n=this[e]>>(r-=8)&255,r<=0&&(r+=this.DB,--e)),128&n&&(n|=-256),0==i&&(128&this.s)!=(128&n)&&++i,(i>0||n!=this.s)&&(t[i++]=n);return t},e.prototype.equals=function(e){return 0==this.compareTo(e)},e.prototype.min=function(e){return this.compareTo(e)<0?this:e},e.prototype.max=function(e){return this.compareTo(e)>0?this:e},e.prototype.and=function(e){var t=nbi();return this.bitwiseTo(e,op_and,t),t},e.prototype.or=function(e){var t=nbi();return this.bitwiseTo(e,op_or,t),t},e.prototype.xor=function(e){var t=nbi();return this.bitwiseTo(e,op_xor,t),t},e.prototype.andNot=function(e){var t=nbi();return this.bitwiseTo(e,op_andnot,t),t},e.prototype.not=function(){for(var e=nbi(),t=0;t<this.t;++t)e[t]=this.DM&~this[t];return e.t=this.t,e.s=~this.s,e},e.prototype.shiftLeft=function(e){var t=nbi();return e<0?this.rShiftTo(-e,t):this.lShiftTo(e,t),t},e.prototype.shiftRight=function(e){var t=nbi();return e<0?this.lShiftTo(-e,t):this.rShiftTo(e,t),t},e.prototype.getLowestSetBit=function(){for(var e=0;e<this.t;++e)if(0!=this[e])return e*this.DB+lbit(this[e]);return this.s<0?this.t*this.DB:-1},e.prototype.bitCount=function(){for(var e=0,t=this.s&this.DM,n=0;n<this.t;++n)e+=cbit(this[n]^t);return e},e.prototype.testBit=function(e){var t=Math.floor(e/this.DB);return t>=this.t?0!=this.s:!!(this[t]&1<<e%this.DB)},e.prototype.setBit=function(e){return this.changeBit(e,op_or)},e.prototype.clearBit=function(e){return this.changeBit(e,op_andnot)},e.prototype.flipBit=function(e){return this.changeBit(e,op_xor)},e.prototype.add=function(e){var t=nbi();return this.addTo(e,t),t},e.prototype.subtract=function(e){var t=nbi();return this.subTo(e,t),t},e.prototype.multiply=function(e){var t=nbi();return this.multiplyTo(e,t),t},e.prototype.divide=function(e){var t=nbi();return this.divRemTo(e,t,null),t},e.prototype.remainder=function(e){var t=nbi();return this.divRemTo(e,null,t),t},e.prototype.divideAndRemainder=function(e){var t=nbi(),n=nbi();return this.divRemTo(e,t,n),[t,n]},e.prototype.modPow=function(e,t){var n,r,i=e.bitLength(),s=nbv(1);if(i<=0)return s;n=i<18?1:i<48?3:i<144?4:i<768?5:6,r=i<8?new Classic(t):t.isEven()?new Barrett(t):new Montgomery(t);var o=[],a=3,c=n-1,u=(1<<n)-1;if(o[1]=r.convert(this),n>1){var l=nbi();for(r.sqrTo(o[1],l);a<=u;)o[a]=nbi(),r.mulTo(l,o[a-2],o[a]),a+=2}var h,d,p=e.t-1,g=!0,f=nbi();for(i=nbits(e[p])-1;p>=0;){for(i>=c?h=e[p]>>i-c&u:(h=(e[p]&(1<<i+1)-1)<<c-i,p>0&&(h|=e[p-1]>>this.DB+i-c)),a=n;!(1&h);)h>>=1,--a;if((i-=a)<0&&(i+=this.DB,--p),g)o[h].copyTo(s),g=!1;else{for(;a>1;)r.sqrTo(s,f),r.sqrTo(f,s),a-=2;a>0?r.sqrTo(s,f):(d=s,s=f,f=d),r.mulTo(f,o[h],s)}for(;p>=0&&!(e[p]&1<<i);)r.sqrTo(s,f),d=s,s=f,f=d,--i<0&&(i=this.DB-1,--p)}return r.revert(s)},e.prototype.modInverse=function(t){var n=t.isEven();if(this.isEven()&&n||0==t.signum())return e.ZERO;for(var r=t.clone(),i=this.clone(),s=nbv(1),o=nbv(0),a=nbv(0),c=nbv(1);0!=r.signum();){for(;r.isEven();)r.rShiftTo(1,r),n?(s.isEven()&&o.isEven()||(s.addTo(this,s),o.subTo(t,o)),s.rShiftTo(1,s)):o.isEven()||o.subTo(t,o),o.rShiftTo(1,o);for(;i.isEven();)i.rShiftTo(1,i),n?(a.isEven()&&c.isEven()||(a.addTo(this,a),c.subTo(t,c)),a.rShiftTo(1,a)):c.isEven()||c.subTo(t,c),c.rShiftTo(1,c);r.compareTo(i)>=0?(r.subTo(i,r),n&&s.subTo(a,s),o.subTo(c,o)):(i.subTo(r,i),n&&a.subTo(s,a),c.subTo(o,c))}return 0!=i.compareTo(e.ONE)?e.ZERO:c.compareTo(t)>=0?c.subtract(t):c.signum()<0?(c.addTo(t,c),c.signum()<0?c.add(t):c):c},e.prototype.pow=function(e){return this.exp(e,new NullExp)},e.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),n=e.s<0?e.negate():e.clone();if(t.compareTo(n)<0){var r=t;t=n,n=r}var i=t.getLowestSetBit(),s=n.getLowestSetBit();if(s<0)return t;for(i<s&&(s=i),s>0&&(t.rShiftTo(s,t),n.rShiftTo(s,n));t.signum()>0;)(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),(i=n.getLowestSetBit())>0&&n.rShiftTo(i,n),t.compareTo(n)>=0?(t.subTo(n,t),t.rShiftTo(1,t)):(n.subTo(t,n),n.rShiftTo(1,n));return s>0&&n.lShiftTo(s,n),n},e.prototype.isProbablePrime=function(e){var t,n=this.abs();if(1==n.t&&n[0]<=lowprimes[lowprimes.length-1]){for(t=0;t<lowprimes.length;++t)if(n[0]==lowprimes[t])return!0;return!1}if(n.isEven())return!1;for(t=1;t<lowprimes.length;){for(var r=lowprimes[t],i=t+1;i<lowprimes.length&&r<lplim;)r*=lowprimes[i++];for(r=n.modInt(r);t<i;)if(r%lowprimes[t++]==0)return!1}return n.millerRabin(e)},e.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e[t]=this[t];e.t=this.t,e.s=this.s},e.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this[0]=e:e<-1?this[0]=e+this.DV:this.t=0},e.prototype.fromString=function(t,n){var r;if(16==n)r=4;else if(8==n)r=3;else if(256==n)r=8;else if(2==n)r=1;else if(32==n)r=5;else{if(4!=n)return void this.fromRadix(t,n);r=2}this.t=0,this.s=0;for(var i=t.length,s=!1,o=0;--i>=0;){var a=8==r?255&+t[i]:intAt(t,i);a<0?"-"==t.charAt(i)&&(s=!0):(s=!1,0==o?this[this.t++]=a:o+r>this.DB?(this[this.t-1]|=(a&(1<<this.DB-o)-1)<<o,this[this.t++]=a>>this.DB-o):this[this.t-1]|=a<<o,(o+=r)>=this.DB&&(o-=this.DB))}8==r&&128&+t[0]&&(this.s=-1,o>0&&(this[this.t-1]|=(1<<this.DB-o)-1<<o)),this.clamp(),s&&e.ZERO.subTo(this,this)},e.prototype.clamp=function(){for(var e=this.s&this.DM;this.t>0&&this[this.t-1]==e;)--this.t},e.prototype.dlShiftTo=function(e,t){var n;for(n=this.t-1;n>=0;--n)t[n+e]=this[n];for(n=e-1;n>=0;--n)t[n]=0;t.t=this.t+e,t.s=this.s},e.prototype.drShiftTo=function(e,t){for(var n=e;n<this.t;++n)t[n-e]=this[n];t.t=Math.max(this.t-e,0),t.s=this.s},e.prototype.lShiftTo=function(e,t){for(var n=e%this.DB,r=this.DB-n,i=(1<<r)-1,s=Math.floor(e/this.DB),o=this.s<<n&this.DM,a=this.t-1;a>=0;--a)t[a+s+1]=this[a]>>r|o,o=(this[a]&i)<<n;for(a=s-1;a>=0;--a)t[a]=0;t[s]=o,t.t=this.t+s+1,t.s=this.s,t.clamp()},e.prototype.rShiftTo=function(e,t){t.s=this.s;var n=Math.floor(e/this.DB);if(n>=this.t)t.t=0;else{var r=e%this.DB,i=this.DB-r,s=(1<<r)-1;t[0]=this[n]>>r;for(var o=n+1;o<this.t;++o)t[o-n-1]|=(this[o]&s)<<i,t[o-n]=this[o]>>r;r>0&&(t[this.t-n-1]|=(this.s&s)<<i),t.t=this.t-n,t.clamp()}},e.prototype.subTo=function(e,t){for(var n=0,r=0,i=Math.min(e.t,this.t);n<i;)r+=this[n]-e[n],t[n++]=r&this.DM,r>>=this.DB;if(e.t<this.t){for(r-=e.s;n<this.t;)r+=this[n],t[n++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;n<e.t;)r-=e[n],t[n++]=r&this.DM,r>>=this.DB;r-=e.s}t.s=r<0?-1:0,r<-1?t[n++]=this.DV+r:r>0&&(t[n++]=r),t.t=n,t.clamp()},e.prototype.multiplyTo=function(t,n){var r=this.abs(),i=t.abs(),s=r.t;for(n.t=s+i.t;--s>=0;)n[s]=0;for(s=0;s<i.t;++s)n[s+r.t]=r.am(0,i[s],n,s,0,r.t);n.s=0,n.clamp(),this.s!=t.s&&e.ZERO.subTo(n,n)},e.prototype.squareTo=function(e){for(var t=this.abs(),n=e.t=2*t.t;--n>=0;)e[n]=0;for(n=0;n<t.t-1;++n){var r=t.am(n,t[n],e,2*n,0,1);(e[n+t.t]+=t.am(n+1,2*t[n],e,2*n+1,r,t.t-n-1))>=t.DV&&(e[n+t.t]-=t.DV,e[n+t.t+1]=1)}e.t>0&&(e[e.t-1]+=t.am(n,t[n],e,2*n,0,1)),e.s=0,e.clamp()},e.prototype.divRemTo=function(t,n,r){var i=t.abs();if(!(i.t<=0)){var s=this.abs();if(s.t<i.t)return null!=n&&n.fromInt(0),void(null!=r&&this.copyTo(r));null==r&&(r=nbi());var o=nbi(),a=this.s,c=t.s,u=this.DB-nbits(i[i.t-1]);u>0?(i.lShiftTo(u,o),s.lShiftTo(u,r)):(i.copyTo(o),s.copyTo(r));var l=o.t,h=o[l-1];if(0!=h){var d=h*(1<<this.F1)+(l>1?o[l-2]>>this.F2:0),p=this.FV/d,g=(1<<this.F1)/d,f=1<<this.F2,m=r.t,v=m-l,y=null==n?nbi():n;for(o.dlShiftTo(v,y),r.compareTo(y)>=0&&(r[r.t++]=1,r.subTo(y,r)),e.ONE.dlShiftTo(l,y),y.subTo(o,o);o.t<l;)o[o.t++]=0;for(;--v>=0;){var b=r[--m]==h?this.DM:Math.floor(r[m]*p+(r[m-1]+f)*g);if((r[m]+=o.am(0,b,r,v,0,l))<b)for(o.dlShiftTo(v,y),r.subTo(y,r);r[m]<--b;)r.subTo(y,r)}null!=n&&(r.drShiftTo(l,n),a!=c&&e.ZERO.subTo(n,n)),r.t=l,r.clamp(),u>0&&r.rShiftTo(u,r),a<0&&e.ZERO.subTo(r,r)}}},e.prototype.invDigit=function(){if(this.t<1)return 0;var e=this[0];if(!(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},e.prototype.isEven=function(){return 0==(this.t>0?1&this[0]:this.s)},e.prototype.exp=function(t,n){if(t>4294967295||t<1)return e.ONE;var r=nbi(),i=nbi(),s=n.convert(this),o=nbits(t)-1;for(s.copyTo(r);--o>=0;)if(n.sqrTo(r,i),(t&1<<o)>0)n.mulTo(i,s,r);else{var a=r;r=i,i=a}return n.revert(r)},e.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},e.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),n=Math.pow(e,t),r=nbv(n),i=nbi(),s=nbi(),o="";for(this.divRemTo(r,i,s);i.signum()>0;)o=(n+s.intValue()).toString(e).substr(1)+o,i.divRemTo(r,i,s);return s.intValue().toString(e)+o},e.prototype.fromRadix=function(t,n){this.fromInt(0),null==n&&(n=10);for(var r=this.chunkSize(n),i=Math.pow(n,r),s=!1,o=0,a=0,c=0;c<t.length;++c){var u=intAt(t,c);u<0?"-"==t.charAt(c)&&0==this.signum()&&(s=!0):(a=n*a+u,++o>=r&&(this.dMultiply(i),this.dAddOffset(a,0),o=0,a=0))}o>0&&(this.dMultiply(Math.pow(n,o)),this.dAddOffset(a,0)),s&&e.ZERO.subTo(this,this)},e.prototype.fromNumber=function(t,n,r){if("number"==typeof n)if(t<2)this.fromInt(1);else for(this.fromNumber(t,r),this.testBit(t-1)||this.bitwiseTo(e.ONE.shiftLeft(t-1),op_or,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(n);)this.dAddOffset(2,0),this.bitLength()>t&&this.subTo(e.ONE.shiftLeft(t-1),this);else{var i=[],s=7&t;i.length=1+(t>>3),n.nextBytes(i),s>0?i[0]&=(1<<s)-1:i[0]=0,this.fromString(i,256)}},e.prototype.bitwiseTo=function(e,t,n){var r,i,s=Math.min(e.t,this.t);for(r=0;r<s;++r)n[r]=t(this[r],e[r]);if(e.t<this.t){for(i=e.s&this.DM,r=s;r<this.t;++r)n[r]=t(this[r],i);n.t=this.t}else{for(i=this.s&this.DM,r=s;r<e.t;++r)n[r]=t(i,e[r]);n.t=e.t}n.s=t(this.s,e.s),n.clamp()},e.prototype.changeBit=function(t,n){var r=e.ONE.shiftLeft(t);return this.bitwiseTo(r,n,r),r},e.prototype.addTo=function(e,t){for(var n=0,r=0,i=Math.min(e.t,this.t);n<i;)r+=this[n]+e[n],t[n++]=r&this.DM,r>>=this.DB;if(e.t<this.t){for(r+=e.s;n<this.t;)r+=this[n],t[n++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;n<e.t;)r+=e[n],t[n++]=r&this.DM,r>>=this.DB;r+=e.s}t.s=r<0?-1:0,r>0?t[n++]=r:r<-1&&(t[n++]=this.DV+r),t.t=n,t.clamp()},e.prototype.dMultiply=function(e){this[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},e.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this[this.t++]=0;for(this[t]+=e;this[t]>=this.DV;)this[t]-=this.DV,++t>=this.t&&(this[this.t++]=0),++this[t]}},e.prototype.multiplyLowerTo=function(e,t,n){var r=Math.min(this.t+e.t,t);for(n.s=0,n.t=r;r>0;)n[--r]=0;for(var i=n.t-this.t;r<i;++r)n[r+this.t]=this.am(0,e[r],n,r,0,this.t);for(i=Math.min(e.t,t);r<i;++r)this.am(0,e[r],n,r,0,t-r);n.clamp()},e.prototype.multiplyUpperTo=function(e,t,n){--t;var r=n.t=this.t+e.t-t;for(n.s=0;--r>=0;)n[r]=0;for(r=Math.max(t-this.t,0);r<e.t;++r)n[this.t+r-t]=this.am(t-r,e[r],n,0,0,this.t+r-t);n.clamp(),n.drShiftTo(1,n)},e.prototype.modInt=function(e){if(e<=0)return 0;var t=this.DV%e,n=this.s<0?e-1:0;if(this.t>0)if(0==t)n=this[0]%e;else for(var r=this.t-1;r>=0;--r)n=(t*n+this[r])%e;return n},e.prototype.millerRabin=function(t){var n=this.subtract(e.ONE),r=n.getLowestSetBit();if(r<=0)return!1;var i=n.shiftRight(r);(t=t+1>>1)>lowprimes.length&&(t=lowprimes.length);for(var s=nbi(),o=0;o<t;++o){s.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]);var a=s.modPow(i,this);if(0!=a.compareTo(e.ONE)&&0!=a.compareTo(n)){for(var c=1;c++<r&&0!=a.compareTo(n);)if(0==(a=a.modPowInt(2,this)).compareTo(e.ONE))return!1;if(0!=a.compareTo(n))return!1}}return!0},e.prototype.square=function(){var e=nbi();return this.squareTo(e),e},e.prototype.gcda=function(e,t){var n=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(n.compareTo(r)<0){var i=n;n=r,r=i}var s=n.getLowestSetBit(),o=r.getLowestSetBit();if(o<0)t(n);else{s<o&&(o=s),o>0&&(n.rShiftTo(o,n),r.rShiftTo(o,r));var a=function(){(s=n.getLowestSetBit())>0&&n.rShiftTo(s,n),(s=r.getLowestSetBit())>0&&r.rShiftTo(s,r),n.compareTo(r)>=0?(n.subTo(r,n),n.rShiftTo(1,n)):(r.subTo(n,r),r.rShiftTo(1,r)),n.signum()>0?setTimeout(a,0):(o>0&&r.lShiftTo(o,r),setTimeout(function(){t(r)},0))};setTimeout(a,10)}},e.prototype.fromNumberAsync=function(t,n,r,i){if("number"==typeof n)if(t<2)this.fromInt(1);else{this.fromNumber(t,r),this.testBit(t-1)||this.bitwiseTo(e.ONE.shiftLeft(t-1),op_or,this),this.isEven()&&this.dAddOffset(1,0);var s=this,o=function(){s.dAddOffset(2,0),s.bitLength()>t&&s.subTo(e.ONE.shiftLeft(t-1),s),s.isProbablePrime(n)?setTimeout(function(){i()},0):setTimeout(o,0)};setTimeout(o,0)}else{var a=[],c=7&t;a.length=1+(t>>3),n.nextBytes(a),c>0?a[0]&=(1<<c)-1:a[0]=0,this.fromString(a,256)}},e}(),NullExp=function(){function e(){}return e.prototype.convert=function(e){return e},e.prototype.revert=function(e){return e},e.prototype.mulTo=function(e,t,n){e.multiplyTo(t,n)},e.prototype.sqrTo=function(e,t){e.squareTo(t)},e}(),Classic=function(){function e(e){this.m=e}return e.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},e.prototype.revert=function(e){return e},e.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},e.prototype.mulTo=function(e,t,n){e.multiplyTo(t,n),this.reduce(n)},e.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},e}(),Montgomery=function(){function e(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}return e.prototype.convert=function(e){var t=nbi();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(BigInteger.ZERO)>0&&this.m.subTo(t,t),t},e.prototype.revert=function(e){var t=nbi();return e.copyTo(t),this.reduce(t),t},e.prototype.reduce=function(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(var t=0;t<this.m.t;++t){var n=32767&e[t],r=n*this.mpl+((n*this.mph+(e[t]>>15)*this.mpl&this.um)<<15)&e.DM;for(e[n=t+this.m.t]+=this.m.am(0,r,e,t,0,this.m.t);e[n]>=e.DV;)e[n]-=e.DV,e[++n]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},e.prototype.mulTo=function(e,t,n){e.multiplyTo(t,n),this.reduce(n)},e.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},e}(),Barrett=function(){function e(e){this.m=e,this.r2=nbi(),this.q3=nbi(),BigInteger.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e)}return e.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=nbi();return e.copyTo(t),this.reduce(t),t},e.prototype.revert=function(e){return e},e.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},e.prototype.mulTo=function(e,t,n){e.multiplyTo(t,n),this.reduce(n)},e.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},e}();function nbi(){return new BigInteger(null)}function parseBigInt(e,t){return new BigInteger(e,t)}var inBrowser="undefined"!=typeof navigator;inBrowser&&j_lm&&"Microsoft Internet Explorer"==navigator.appName?(BigInteger.prototype.am=function(e,t,n,r,i,s){for(var o=32767&t,a=t>>15;--s>=0;){var c=32767&this[e],u=this[e++]>>15,l=a*c+u*o;i=((c=o*c+((32767&l)<<15)+n[r]+(1073741823&i))>>>30)+(l>>>15)+a*u+(i>>>30),n[r++]=1073741823&c}return i},dbits=30):inBrowser&&j_lm&&"Netscape"!=navigator.appName?(BigInteger.prototype.am=function(e,t,n,r,i,s){for(;--s>=0;){var o=t*this[e++]+n[r]+i;i=Math.floor(o/67108864),n[r++]=67108863&o}return i},dbits=26):(BigInteger.prototype.am=function(e,t,n,r,i,s){for(var o=16383&t,a=t>>14;--s>=0;){var c=16383&this[e],u=this[e++]>>14,l=a*c+u*o;i=((c=o*c+((16383&l)<<14)+n[r]+i)>>28)+(l>>14)+a*u,n[r++]=268435455&c}return i},dbits=28),BigInteger.prototype.DB=dbits,BigInteger.prototype.DM=(1<<dbits)-1,BigInteger.prototype.DV=1<<dbits;var BI_FP=52;BigInteger.prototype.FV=Math.pow(2,BI_FP),BigInteger.prototype.F1=BI_FP-dbits,BigInteger.prototype.F2=2*dbits-BI_FP;var BI_RC=[],rr,vv;for(rr="0".charCodeAt(0),vv=0;vv<=9;++vv)BI_RC[rr++]=vv;for(rr="a".charCodeAt(0),vv=10;vv<36;++vv)BI_RC[rr++]=vv;for(rr="A".charCodeAt(0),vv=10;vv<36;++vv)BI_RC[rr++]=vv;function intAt(e,t){var n=BI_RC[e.charCodeAt(t)];return null==n?-1:n}function nbv(e){var t=nbi();return t.fromInt(e),t}function nbits(e){var t,n=1;return 0!=(t=e>>>16)&&(e=t,n+=16),0!=(t=e>>8)&&(e=t,n+=8),0!=(t=e>>4)&&(e=t,n+=4),0!=(t=e>>2)&&(e=t,n+=2),0!=(t=e>>1)&&(e=t,n+=1),n}BigInteger.ZERO=nbv(0),BigInteger.ONE=nbv(1);var Arcfour=function(){function e(){this.i=0,this.j=0,this.S=[]}return e.prototype.init=function(e){var t,n,r;for(t=0;t<256;++t)this.S[t]=t;for(n=0,t=0;t<256;++t)n=n+this.S[t]+e[t%e.length]&255,r=this.S[t],this.S[t]=this.S[n],this.S[n]=r;this.i=0,this.j=0},e.prototype.next=function(){var e;return this.i=this.i+1&255,this.j=this.j+this.S[this.i]&255,e=this.S[this.i],this.S[this.i]=this.S[this.j],this.S[this.j]=e,this.S[e+this.S[this.i]&255]},e}();function prng_newstate(){return new Arcfour}var rng_psize=256,rng_state,rng_pool=null,rng_pptr;if(null==rng_pool){rng_pool=[],rng_pptr=0;var t=void 0;if("undefined"!=typeof window&&window.crypto&&window.crypto.getRandomValues){var z=new Uint32Array(256);for(window.crypto.getRandomValues(z),t=0;t<z.length;++t)rng_pool[rng_pptr++]=255&z[t]}var count=0,onMouseMoveListener_1=function(e){if((count=count||0)>=256||rng_pptr>=rng_psize)window.removeEventListener?window.removeEventListener("mousemove",onMouseMoveListener_1,!1):window.detachEvent&&window.detachEvent("onmousemove",onMouseMoveListener_1);else try{var t=e.x+e.y;rng_pool[rng_pptr++]=255&t,count+=1}catch(e){}};"undefined"!=typeof window&&(window.addEventListener?window.addEventListener("mousemove",onMouseMoveListener_1,!1):window.attachEvent&&window.attachEvent("onmousemove",onMouseMoveListener_1))}function rng_get_byte(){if(null==rng_state){for(rng_state=prng_newstate();rng_pptr<rng_psize;){var e=Math.floor(65536*Math.random());rng_pool[rng_pptr++]=255&e}for(rng_state.init(rng_pool),rng_pptr=0;rng_pptr<rng_pool.length;++rng_pptr)rng_pool[rng_pptr]=0;rng_pptr=0}return rng_state.next()}var SecureRandom=function(){function e(){}return e.prototype.nextBytes=function(e){for(var t=0;t<e.length;++t)e[t]=rng_get_byte()},e}();function pkcs1pad1(e,t){if(t<e.length+22)return console.error("Message too long for RSA"),null;for(var n=t-e.length-6,r="",i=0;i<n;i+=2)r+="ff";return parseBigInt("0001"+r+"00"+e,16)}function pkcs1pad2(e,t){if(t<e.length+11)return console.error("Message too long for RSA"),null;for(var n=[],r=e.length-1;r>=0&&t>0;){var i=e.charCodeAt(r--);i<128?n[--t]=i:i>127&&i<2048?(n[--t]=63&i|128,n[--t]=i>>6|192):(n[--t]=63&i|128,n[--t]=i>>6&63|128,n[--t]=i>>12|224)}n[--t]=0;for(var s=new SecureRandom,o=[];t>2;){for(o[0]=0;0==o[0];)s.nextBytes(o);n[--t]=o[0]}return n[--t]=2,n[--t]=0,new BigInteger(n)}var RSAKey=function(){function e(){this.n=null,this.e=0,this.d=null,this.p=null,this.q=null,this.dmp1=null,this.dmq1=null,this.coeff=null}return e.prototype.doPublic=function(e){return e.modPowInt(this.e,this.n)},e.prototype.doPrivate=function(e){if(null==this.p||null==this.q)return e.modPow(this.d,this.n);for(var t=e.mod(this.p).modPow(this.dmp1,this.p),n=e.mod(this.q).modPow(this.dmq1,this.q);t.compareTo(n)<0;)t=t.add(this.p);return t.subtract(n).multiply(this.coeff).mod(this.p).multiply(this.q).add(n)},e.prototype.setPublic=function(e,t){null!=e&&null!=t&&e.length>0&&t.length>0?(this.n=parseBigInt(e,16),this.e=parseInt(t,16)):console.error("Invalid RSA public key")},e.prototype.encrypt=function(e){var t=this.n.bitLength()+7>>3,n=pkcs1pad2(e,t);if(null==n)return null;var r=this.doPublic(n);if(null==r)return null;for(var i=r.toString(16),s=i.length,o=0;o<2*t-s;o++)i="0"+i;return i},e.prototype.setPrivate=function(e,t,n){null!=e&&null!=t&&e.length>0&&t.length>0?(this.n=parseBigInt(e,16),this.e=parseInt(t,16),this.d=parseBigInt(n,16)):console.error("Invalid RSA private key")},e.prototype.setPrivateEx=function(e,t,n,r,i,s,o,a){null!=e&&null!=t&&e.length>0&&t.length>0?(this.n=parseBigInt(e,16),this.e=parseInt(t,16),this.d=parseBigInt(n,16),this.p=parseBigInt(r,16),this.q=parseBigInt(i,16),this.dmp1=parseBigInt(s,16),this.dmq1=parseBigInt(o,16),this.coeff=parseBigInt(a,16)):console.error("Invalid RSA private key")},e.prototype.generate=function(e,t){var n=new SecureRandom,r=e>>1;this.e=parseInt(t,16);for(var i=new BigInteger(t,16);;){for(;this.p=new BigInteger(e-r,1,n),0!=this.p.subtract(BigInteger.ONE).gcd(i).compareTo(BigInteger.ONE)||!this.p.isProbablePrime(10););for(;this.q=new BigInteger(r,1,n),0!=this.q.subtract(BigInteger.ONE).gcd(i).compareTo(BigInteger.ONE)||!this.q.isProbablePrime(10););if(this.p.compareTo(this.q)<=0){var s=this.p;this.p=this.q,this.q=s}var o=this.p.subtract(BigInteger.ONE),a=this.q.subtract(BigInteger.ONE),c=o.multiply(a);if(0==c.gcd(i).compareTo(BigInteger.ONE)){this.n=this.p.multiply(this.q),this.d=i.modInverse(c),this.dmp1=this.d.mod(o),this.dmq1=this.d.mod(a),this.coeff=this.q.modInverse(this.p);break}}},e.prototype.decrypt=function(e){var t=parseBigInt(e,16),n=this.doPrivate(t);return null==n?null:pkcs1unpad2(n,this.n.bitLength()+7>>3)},e.prototype.generateAsync=function(e,t,n){var r=new SecureRandom,i=e>>1;this.e=parseInt(t,16);var s=new BigInteger(t,16),o=this,a=function(){var t=function(){if(o.p.compareTo(o.q)<=0){var e=o.p;o.p=o.q,o.q=e}var t=o.p.subtract(BigInteger.ONE),r=o.q.subtract(BigInteger.ONE),i=t.multiply(r);0==i.gcd(s).compareTo(BigInteger.ONE)?(o.n=o.p.multiply(o.q),o.d=s.modInverse(i),o.dmp1=o.d.mod(t),o.dmq1=o.d.mod(r),o.coeff=o.q.modInverse(o.p),setTimeout(function(){n()},0)):setTimeout(a,0)},c=function(){o.q=nbi(),o.q.fromNumberAsync(i,1,r,function(){o.q.subtract(BigInteger.ONE).gcda(s,function(e){0==e.compareTo(BigInteger.ONE)&&o.q.isProbablePrime(10)?setTimeout(t,0):setTimeout(c,0)})})},u=function(){o.p=nbi(),o.p.fromNumberAsync(e-i,1,r,function(){o.p.subtract(BigInteger.ONE).gcda(s,function(e){0==e.compareTo(BigInteger.ONE)&&o.p.isProbablePrime(10)?setTimeout(c,0):setTimeout(u,0)})})};setTimeout(u,0)};setTimeout(a,0)},e.prototype.sign=function(e,t,n){var r=pkcs1pad1(getDigestHeader(n)+t(e).toString(),this.n.bitLength()/4);if(null==r)return null;var i=this.doPrivate(r);if(null==i)return null;var s=i.toString(16);return 1&s.length?"0"+s:s},e.prototype.verify=function(e,t,n){var r=parseBigInt(t,16),i=this.doPublic(r);return null==i?null:removeDigestHeader(i.toString(16).replace(/^1f+00/,""))==n(e).toString()},e}();function pkcs1unpad2(e,t){for(var n=e.toByteArray(),r=0;r<n.length&&0==n[r];)++r;if(n.length-r!=t-1||2!=n[r])return null;for(++r;0!=n[r];)if(++r>=n.length)return null;for(var i="";++r<n.length;){var s=255&n[r];s<128?i+=String.fromCharCode(s):s>191&&s<224?(i+=String.fromCharCode((31&s)<<6|63&n[r+1]),++r):(i+=String.fromCharCode((15&s)<<12|(63&n[r+1])<<6|63&n[r+2]),r+=2)}return i}var DIGEST_HEADERS={md2:"3020300c06082a864886f70d020205000410",md5:"3020300c06082a864886f70d020505000410",sha1:"3021300906052b0e03021a05000414",sha224:"302d300d06096086480165030402040500041c",sha256:"3031300d060960864801650304020105000420",sha384:"3041300d060960864801650304020205000430",sha512:"3051300d060960864801650304020305000440",ripemd160:"3021300906052b2403020105000414"};function getDigestHeader(e){return DIGEST_HEADERS[e]||""}function removeDigestHeader(e){for(var t in DIGEST_HEADERS)if(DIGEST_HEADERS.hasOwnProperty(t)){var n=DIGEST_HEADERS[t],r=n.length;if(e.substr(0,r)==n)return e.substr(r)}return e}var YAHOO={};YAHOO.lang={extend:function(e,t,n){if(!t||!e)throw new Error("YAHOO.lang.extend failed, please check that all dependencies are included.");var r=function(){};if(r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e,e.superclass=t.prototype,t.prototype.constructor==Object.prototype.constructor&&(t.prototype.constructor=t),n){var i;for(i in n)e.prototype[i]=n[i];var s=function(){},o=["toString","valueOf"];try{/MSIE/.test(navigator.userAgent)&&(s=function(e,t){for(i=0;i<o.length;i+=1){var n=o[i],r=t[n];"function"==typeof r&&r!=Object.prototype[n]&&(e[n]=r)}})}catch(e){}s(e.prototype,n)}}};var KJUR={};void 0!==KJUR.asn1&&KJUR.asn1||(KJUR.asn1={}),KJUR.asn1.ASN1Util=new function(){this.integerToByteHex=function(e){var t=e.toString(16);return t.length%2==1&&(t="0"+t),t},this.bigIntToMinTwosComplementsHex=function(e){var t=e.toString(16);if("-"!=t.substr(0,1))t.length%2==1?t="0"+t:t.match(/^[0-7]/)||(t="00"+t);else{var n=t.substr(1).length;n%2==1?n+=1:t.match(/^[0-7]/)||(n+=2);for(var r="",i=0;i<n;i++)r+="f";t=new BigInteger(r,16).xor(e).add(BigInteger.ONE).toString(16).replace(/^-/,"")}return t},this.getPEMStringFromHex=function(e,t){return hextopem(e,t)},this.newObject=function(e){var t=KJUR.asn1,n=t.DERBoolean,r=t.DERInteger,i=t.DERBitString,s=t.DEROctetString,o=t.DERNull,a=t.DERObjectIdentifier,c=t.DEREnumerated,u=t.DERUTF8String,l=t.DERNumericString,h=t.DERPrintableString,d=t.DERTeletexString,p=t.DERIA5String,g=t.DERUTCTime,f=t.DERGeneralizedTime,m=t.DERSequence,v=t.DERSet,y=t.DERTaggedObject,b=t.ASN1Util.newObject,S=Object.keys(e);if(1!=S.length)throw"key of param shall be only one.";var T=S[0];if(-1==":bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:".indexOf(":"+T+":"))throw"undefined key: "+T;if("bool"==T)return new n(e[T]);if("int"==T)return new r(e[T]);if("bitstr"==T)return new i(e[T]);if("octstr"==T)return new s(e[T]);if("null"==T)return new o(e[T]);if("oid"==T)return new a(e[T]);if("enum"==T)return new c(e[T]);if("utf8str"==T)return new u(e[T]);if("numstr"==T)return new l(e[T]);if("prnstr"==T)return new h(e[T]);if("telstr"==T)return new d(e[T]);if("ia5str"==T)return new p(e[T]);if("utctime"==T)return new g(e[T]);if("gentime"==T)return new f(e[T]);if("seq"==T){for(var w=e[T],R=[],E=0;E<w.length;E++){var I=b(w[E]);R.push(I)}return new m({array:R})}if("set"==T){for(w=e[T],R=[],E=0;E<w.length;E++){I=b(w[E]);R.push(I)}return new v({array:R})}if("tag"==T){var _=e[T];if("[object Array]"===Object.prototype.toString.call(_)&&3==_.length){var A=b(_[2]);return new y({tag:_[0],explicit:_[1],obj:A})}var C={};if(void 0!==_.explicit&&(C.explicit=_.explicit),void 0!==_.tag&&(C.tag=_.tag),void 0===_.obj)throw"obj shall be specified for 'tag'.";return C.obj=b(_.obj),new y(C)}},this.jsonToASN1HEX=function(e){return this.newObject(e).getEncodedHex()}},KJUR.asn1.ASN1Util.oidHexToInt=function(e){for(var t="",n=parseInt(e.substr(0,2),16),r=(t=Math.floor(n/40)+"."+n%40,""),i=2;i<e.length;i+=2){var s=("00000000"+parseInt(e.substr(i,2),16).toString(2)).slice(-8);if(r+=s.substr(1,7),"0"==s.substr(0,1))t=t+"."+new BigInteger(r,2).toString(10),r=""}return t},KJUR.asn1.ASN1Util.oidIntToHex=function(e){var t=function(e){var t=e.toString(16);return 1==t.length&&(t="0"+t),t},n=function(e){var n="",r=new BigInteger(e,10).toString(2),i=7-r.length%7;7==i&&(i=0);for(var s="",o=0;o<i;o++)s+="0";r=s+r;for(o=0;o<r.length-1;o+=7){var a=r.substr(o,7);o!=r.length-7&&(a="1"+a),n+=t(parseInt(a,2))}return n};if(!e.match(/^[0-9.]+$/))throw"malformed oid string: "+e;var r="",i=e.split("."),s=40*parseInt(i[0])+parseInt(i[1]);r+=t(s),i.splice(0,2);for(var o=0;o<i.length;o++)r+=n(i[o]);return r},KJUR.asn1.ASN1Object=function(){this.getLengthHexFromValue=function(){if(void 0===this.hV||null==this.hV)throw"this.hV is null or undefined.";if(this.hV.length%2==1)throw"value hex must be even length: n=0,v="+this.hV;var e=this.hV.length/2,t=e.toString(16);if(t.length%2==1&&(t="0"+t),e<128)return t;var n=t.length/2;if(n>15)throw"ASN.1 length too long to represent by 8x: n = "+e.toString(16);return(128+n).toString(16)+t},this.getEncodedHex=function(){return(null==this.hTLV||this.isModified)&&(this.hV=this.getFreshValueHex(),this.hL=this.getLengthHexFromValue(),this.hTLV=this.hT+this.hL+this.hV,this.isModified=!1),this.hTLV},this.getValueHex=function(){return this.getEncodedHex(),this.hV},this.getFreshValueHex=function(){return""}},KJUR.asn1.DERAbstractString=function(e){KJUR.asn1.DERAbstractString.superclass.constructor.call(this),this.getString=function(){return this.s},this.setString=function(e){this.hTLV=null,this.isModified=!0,this.s=e,this.hV=stohex(this.s)},this.setStringHex=function(e){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=e},this.getFreshValueHex=function(){return this.hV},void 0!==e&&("string"==typeof e?this.setString(e):void 0!==e.str?this.setString(e.str):void 0!==e.hex&&this.setStringHex(e.hex))},YAHOO.lang.extend(KJUR.asn1.DERAbstractString,KJUR.asn1.ASN1Object),KJUR.asn1.DERAbstractTime=function(e){KJUR.asn1.DERAbstractTime.superclass.constructor.call(this),this.localDateToUTC=function(e){return utc=e.getTime()+6e4*e.getTimezoneOffset(),new Date(utc)},this.formatDate=function(e,t,n){var r=this.zeroPadding,i=this.localDateToUTC(e),s=String(i.getFullYear());"utc"==t&&(s=s.substr(2,2));var o=s+r(String(i.getMonth()+1),2)+r(String(i.getDate()),2)+r(String(i.getHours()),2)+r(String(i.getMinutes()),2)+r(String(i.getSeconds()),2);if(!0===n){var a=i.getMilliseconds();if(0!=a){var c=r(String(a),3);o=o+"."+(c=c.replace(/[0]+$/,""))}}return o+"Z"},this.zeroPadding=function(e,t){return e.length>=t?e:new Array(t-e.length+1).join("0")+e},this.getString=function(){return this.s},this.setString=function(e){this.hTLV=null,this.isModified=!0,this.s=e,this.hV=stohex(e)},this.setByDateValue=function(e,t,n,r,i,s){var o=new Date(Date.UTC(e,t-1,n,r,i,s,0));this.setByDate(o)},this.getFreshValueHex=function(){return this.hV}},YAHOO.lang.extend(KJUR.asn1.DERAbstractTime,KJUR.asn1.ASN1Object),KJUR.asn1.DERAbstractStructured=function(e){KJUR.asn1.DERAbstractString.superclass.constructor.call(this),this.setByASN1ObjectArray=function(e){this.hTLV=null,this.isModified=!0,this.asn1Array=e},this.appendASN1Object=function(e){this.hTLV=null,this.isModified=!0,this.asn1Array.push(e)},this.asn1Array=new Array,void 0!==e&&void 0!==e.array&&(this.asn1Array=e.array)},YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured,KJUR.asn1.ASN1Object),KJUR.asn1.DERBoolean=function(){KJUR.asn1.DERBoolean.superclass.constructor.call(this),this.hT="01",this.hTLV="0101ff"},YAHOO.lang.extend(KJUR.asn1.DERBoolean,KJUR.asn1.ASN1Object),KJUR.asn1.DERInteger=function(e){KJUR.asn1.DERInteger.superclass.constructor.call(this),this.hT="02",this.setByBigInteger=function(e){this.hTLV=null,this.isModified=!0,this.hV=KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(e)},this.setByInteger=function(e){var t=new BigInteger(String(e),10);this.setByBigInteger(t)},this.setValueHex=function(e){this.hV=e},this.getFreshValueHex=function(){return this.hV},void 0!==e&&(void 0!==e.bigint?this.setByBigInteger(e.bigint):void 0!==e.int?this.setByInteger(e.int):"number"==typeof e?this.setByInteger(e):void 0!==e.hex&&this.setValueHex(e.hex))},YAHOO.lang.extend(KJUR.asn1.DERInteger,KJUR.asn1.ASN1Object),KJUR.asn1.DERBitString=function(e){if(void 0!==e&&void 0!==e.obj){var t=KJUR.asn1.ASN1Util.newObject(e.obj);e.hex="00"+t.getEncodedHex()}KJUR.asn1.DERBitString.superclass.constructor.call(this),this.hT="03",this.setHexValueIncludingUnusedBits=function(e){this.hTLV=null,this.isModified=!0,this.hV=e},this.setUnusedBitsAndHexValue=function(e,t){if(e<0||7<e)throw"unused bits shall be from 0 to 7: u = "+e;var n="0"+e;this.hTLV=null,this.isModified=!0,this.hV=n+t},this.setByBinaryString=function(e){var t=8-(e=e.replace(/0+$/,"")).length%8;8==t&&(t=0);for(var n=0;n<=t;n++)e+="0";var r="";for(n=0;n<e.length-1;n+=8){var i=e.substr(n,8),s=parseInt(i,2).toString(16);1==s.length&&(s="0"+s),r+=s}this.hTLV=null,this.isModified=!0,this.hV="0"+t+r},this.setByBooleanArray=function(e){for(var t="",n=0;n<e.length;n++)1==e[n]?t+="1":t+="0";this.setByBinaryString(t)},this.newFalseArray=function(e){for(var t=new Array(e),n=0;n<e;n++)t[n]=!1;return t},this.getFreshValueHex=function(){return this.hV},void 0!==e&&("string"==typeof e&&e.toLowerCase().match(/^[0-9a-f]+$/)?this.setHexValueIncludingUnusedBits(e):void 0!==e.hex?this.setHexValueIncludingUnusedBits(e.hex):void 0!==e.bin?this.setByBinaryString(e.bin):void 0!==e.array&&this.setByBooleanArray(e.array))},YAHOO.lang.extend(KJUR.asn1.DERBitString,KJUR.asn1.ASN1Object),KJUR.asn1.DEROctetString=function(e){if(void 0!==e&&void 0!==e.obj){var t=KJUR.asn1.ASN1Util.newObject(e.obj);e.hex=t.getEncodedHex()}KJUR.asn1.DEROctetString.superclass.constructor.call(this,e),this.hT="04"},YAHOO.lang.extend(KJUR.asn1.DEROctetString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERNull=function(){KJUR.asn1.DERNull.superclass.constructor.call(this),this.hT="05",this.hTLV="0500"},YAHOO.lang.extend(KJUR.asn1.DERNull,KJUR.asn1.ASN1Object),KJUR.asn1.DERObjectIdentifier=function(e){var t=function(e){var t=e.toString(16);return 1==t.length&&(t="0"+t),t},n=function(e){var n="",r=new BigInteger(e,10).toString(2),i=7-r.length%7;7==i&&(i=0);for(var s="",o=0;o<i;o++)s+="0";r=s+r;for(o=0;o<r.length-1;o+=7){var a=r.substr(o,7);o!=r.length-7&&(a="1"+a),n+=t(parseInt(a,2))}return n};KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this),this.hT="06",this.setValueHex=function(e){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=e},this.setValueOidString=function(e){if(!e.match(/^[0-9.]+$/))throw"malformed oid string: "+e;var r="",i=e.split("."),s=40*parseInt(i[0])+parseInt(i[1]);r+=t(s),i.splice(0,2);for(var o=0;o<i.length;o++)r+=n(i[o]);this.hTLV=null,this.isModified=!0,this.s=null,this.hV=r},this.setValueName=function(e){var t=KJUR.asn1.x509.OID.name2oid(e);if(""===t)throw"DERObjectIdentifier oidName undefined: "+e;this.setValueOidString(t)},this.getFreshValueHex=function(){return this.hV},void 0!==e&&("string"==typeof e?e.match(/^[0-2].[0-9.]+$/)?this.setValueOidString(e):this.setValueName(e):void 0!==e.oid?this.setValueOidString(e.oid):void 0!==e.hex?this.setValueHex(e.hex):void 0!==e.name&&this.setValueName(e.name))},YAHOO.lang.extend(KJUR.asn1.DERObjectIdentifier,KJUR.asn1.ASN1Object),KJUR.asn1.DEREnumerated=function(e){KJUR.asn1.DEREnumerated.superclass.constructor.call(this),this.hT="0a",this.setByBigInteger=function(e){this.hTLV=null,this.isModified=!0,this.hV=KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(e)},this.setByInteger=function(e){var t=new BigInteger(String(e),10);this.setByBigInteger(t)},this.setValueHex=function(e){this.hV=e},this.getFreshValueHex=function(){return this.hV},void 0!==e&&(void 0!==e.int?this.setByInteger(e.int):"number"==typeof e?this.setByInteger(e):void 0!==e.hex&&this.setValueHex(e.hex))},YAHOO.lang.extend(KJUR.asn1.DEREnumerated,KJUR.asn1.ASN1Object),KJUR.asn1.DERUTF8String=function(e){KJUR.asn1.DERUTF8String.superclass.constructor.call(this,e),this.hT="0c"},YAHOO.lang.extend(KJUR.asn1.DERUTF8String,KJUR.asn1.DERAbstractString),KJUR.asn1.DERNumericString=function(e){KJUR.asn1.DERNumericString.superclass.constructor.call(this,e),this.hT="12"},YAHOO.lang.extend(KJUR.asn1.DERNumericString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERPrintableString=function(e){KJUR.asn1.DERPrintableString.superclass.constructor.call(this,e),this.hT="13"},YAHOO.lang.extend(KJUR.asn1.DERPrintableString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERTeletexString=function(e){KJUR.asn1.DERTeletexString.superclass.constructor.call(this,e),this.hT="14"},YAHOO.lang.extend(KJUR.asn1.DERTeletexString,KJUR.asn1.DERAbstractString),KJUR.asn1.DERIA5String=function(e){KJUR.asn1.DERIA5String.superclass.constructor.call(this,e),this.hT="16"},YAHOO.lang.extend(KJUR.asn1.DERIA5String,KJUR.asn1.DERAbstractString),KJUR.asn1.DERUTCTime=function(e){KJUR.asn1.DERUTCTime.superclass.constructor.call(this,e),this.hT="17",this.setByDate=function(e){this.hTLV=null,this.isModified=!0,this.date=e,this.s=this.formatDate(this.date,"utc"),this.hV=stohex(this.s)},this.getFreshValueHex=function(){return void 0===this.date&&void 0===this.s&&(this.date=new Date,this.s=this.formatDate(this.date,"utc"),this.hV=stohex(this.s)),this.hV},void 0!==e&&(void 0!==e.str?this.setString(e.str):"string"==typeof e&&e.match(/^[0-9]{12}Z$/)?this.setString(e):void 0!==e.hex?this.setStringHex(e.hex):void 0!==e.date&&this.setByDate(e.date))},YAHOO.lang.extend(KJUR.asn1.DERUTCTime,KJUR.asn1.DERAbstractTime),KJUR.asn1.DERGeneralizedTime=function(e){KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this,e),this.hT="18",this.withMillis=!1,this.setByDate=function(e){this.hTLV=null,this.isModified=!0,this.date=e,this.s=this.formatDate(this.date,"gen",this.withMillis),this.hV=stohex(this.s)},this.getFreshValueHex=function(){return void 0===this.date&&void 0===this.s&&(this.date=new Date,this.s=this.formatDate(this.date,"gen",this.withMillis),this.hV=stohex(this.s)),this.hV},void 0!==e&&(void 0!==e.str?this.setString(e.str):"string"==typeof e&&e.match(/^[0-9]{14}Z$/)?this.setString(e):void 0!==e.hex?this.setStringHex(e.hex):void 0!==e.date&&this.setByDate(e.date),!0===e.millis&&(this.withMillis=!0))},YAHOO.lang.extend(KJUR.asn1.DERGeneralizedTime,KJUR.asn1.DERAbstractTime),KJUR.asn1.DERSequence=function(e){KJUR.asn1.DERSequence.superclass.constructor.call(this,e),this.hT="30",this.getFreshValueHex=function(){for(var e="",t=0;t<this.asn1Array.length;t++){e+=this.asn1Array[t].getEncodedHex()}return this.hV=e,this.hV}},YAHOO.lang.extend(KJUR.asn1.DERSequence,KJUR.asn1.DERAbstractStructured),KJUR.asn1.DERSet=function(e){KJUR.asn1.DERSet.superclass.constructor.call(this,e),this.hT="31",this.sortFlag=!0,this.getFreshValueHex=function(){for(var e=new Array,t=0;t<this.asn1Array.length;t++){var n=this.asn1Array[t];e.push(n.getEncodedHex())}return 1==this.sortFlag&&e.sort(),this.hV=e.join(""),this.hV},void 0!==e&&void 0!==e.sortflag&&0==e.sortflag&&(this.sortFlag=!1)},YAHOO.lang.extend(KJUR.asn1.DERSet,KJUR.asn1.DERAbstractStructured),KJUR.asn1.DERTaggedObject=function(e){KJUR.asn1.DERTaggedObject.superclass.constructor.call(this),this.hT="a0",this.hV="",this.isExplicit=!0,this.asn1Object=null,this.setASN1Object=function(e,t,n){this.hT=t,this.isExplicit=e,this.asn1Object=n,this.isExplicit?(this.hV=this.asn1Object.getEncodedHex(),this.hTLV=null,this.isModified=!0):(this.hV=null,this.hTLV=n.getEncodedHex(),this.hTLV=this.hTLV.replace(/^../,t),this.isModified=!1)},this.getFreshValueHex=function(){return this.hV},void 0!==e&&(void 0!==e.tag&&(this.hT=e.tag),void 0!==e.explicit&&(this.isExplicit=e.explicit),void 0!==e.obj&&(this.asn1Object=e.obj,this.setASN1Object(this.isExplicit,this.hT,this.asn1Object)))},YAHOO.lang.extend(KJUR.asn1.DERTaggedObject,KJUR.asn1.ASN1Object);var __extends=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},e(t,n)};return function(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),JSEncryptRSAKey=function(e){function t(n){var r=e.call(this)||this;return n&&("string"==typeof n?r.parseKey(n):(t.hasPrivateKeyProperty(n)||t.hasPublicKeyProperty(n))&&r.parsePropertiesFrom(n)),r}return __extends(t,e),t.prototype.parseKey=function(e){try{var t=0,n=0,r=/^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/.test(e)?Hex.decode(e):Base64.unarmor(e),i=ASN1.decode(r);if(3===i.sub.length&&(i=i.sub[2].sub[0]),9===i.sub.length){t=i.sub[1].getHexStringValue(),this.n=parseBigInt(t,16),n=i.sub[2].getHexStringValue(),this.e=parseInt(n,16);var s=i.sub[3].getHexStringValue();this.d=parseBigInt(s,16);var o=i.sub[4].getHexStringValue();this.p=parseBigInt(o,16);var a=i.sub[5].getHexStringValue();this.q=parseBigInt(a,16);var c=i.sub[6].getHexStringValue();this.dmp1=parseBigInt(c,16);var u=i.sub[7].getHexStringValue();this.dmq1=parseBigInt(u,16);var l=i.sub[8].getHexStringValue();this.coeff=parseBigInt(l,16)}else{if(2!==i.sub.length)return!1;if(i.sub[0].sub){var h=i.sub[1].sub[0];t=h.sub[0].getHexStringValue(),this.n=parseBigInt(t,16),n=h.sub[1].getHexStringValue(),this.e=parseInt(n,16)}else t=i.sub[0].getHexStringValue(),this.n=parseBigInt(t,16),n=i.sub[1].getHexStringValue(),this.e=parseInt(n,16)}return!0}catch(e){return!1}},t.prototype.getPrivateBaseKey=function(){var e={array:[new KJUR.asn1.DERInteger({int:0}),new KJUR.asn1.DERInteger({bigint:this.n}),new KJUR.asn1.DERInteger({int:this.e}),new KJUR.asn1.DERInteger({bigint:this.d}),new KJUR.asn1.DERInteger({bigint:this.p}),new KJUR.asn1.DERInteger({bigint:this.q}),new KJUR.asn1.DERInteger({bigint:this.dmp1}),new KJUR.asn1.DERInteger({bigint:this.dmq1}),new KJUR.asn1.DERInteger({bigint:this.coeff})]};return new KJUR.asn1.DERSequence(e).getEncodedHex()},t.prototype.getPrivateBaseKeyB64=function(){return hex2b64(this.getPrivateBaseKey())},t.prototype.getPublicBaseKey=function(){var e=new KJUR.asn1.DERSequence({array:[new KJUR.asn1.DERObjectIdentifier({oid:"1.2.840.113549.1.1.1"}),new KJUR.asn1.DERNull]}),t=new KJUR.asn1.DERSequence({array:[new KJUR.asn1.DERInteger({bigint:this.n}),new KJUR.asn1.DERInteger({int:this.e})]}),n=new KJUR.asn1.DERBitString({hex:"00"+t.getEncodedHex()});return new KJUR.asn1.DERSequence({array:[e,n]}).getEncodedHex()},t.prototype.getPublicBaseKeyB64=function(){return hex2b64(this.getPublicBaseKey())},t.wordwrap=function(e,t){if(!e)return e;var n="(.{1,"+(t=t||64)+"})( +|$\n?)|(.{1,"+t+"})";return e.match(RegExp(n,"g")).join("\n")},t.prototype.getPrivateKey=function(){var e="-----BEGIN RSA PRIVATE KEY-----\n";return e+=t.wordwrap(this.getPrivateBaseKeyB64())+"\n",e+="-----END RSA PRIVATE KEY-----"},t.prototype.getPublicKey=function(){var e="-----BEGIN PUBLIC KEY-----\n";return e+=t.wordwrap(this.getPublicBaseKeyB64())+"\n",e+="-----END PUBLIC KEY-----"},t.hasPublicKeyProperty=function(e){return(e=e||{}).hasOwnProperty("n")&&e.hasOwnProperty("e")},t.hasPrivateKeyProperty=function(e){return(e=e||{}).hasOwnProperty("n")&&e.hasOwnProperty("e")&&e.hasOwnProperty("d")&&e.hasOwnProperty("p")&&e.hasOwnProperty("q")&&e.hasOwnProperty("dmp1")&&e.hasOwnProperty("dmq1")&&e.hasOwnProperty("coeff")},t.prototype.parsePropertiesFrom=function(e){this.n=e.n,this.e=e.e,e.hasOwnProperty("d")&&(this.d=e.d,this.p=e.p,this.q=e.q,this.dmp1=e.dmp1,this.dmq1=e.dmq1,this.coeff=e.coeff)},t}(RSAKey),_a,version=void 0!==browser$1?null===(_a=browser$1.env)||void 0===_a?void 0:_a.npm_package_version:void 0,JSEncrypt=function(){function e(e){void 0===e&&(e={}),e=e||{},this.default_key_size=e.default_key_size?parseInt(e.default_key_size,10):1024,this.default_public_exponent=e.default_public_exponent||"010001",this.log=e.log||!1,this.key=null}return e.prototype.setKey=function(e){this.log&&this.key&&console.warn("A key was already set, overriding existing."),this.key=new JSEncryptRSAKey(e)},e.prototype.setPrivateKey=function(e){this.setKey(e)},e.prototype.setPublicKey=function(e){this.setKey(e)},e.prototype.decrypt=function(e){try{return this.getKey().decrypt(b64tohex(e))}catch(e){return!1}},e.prototype.encrypt=function(e){try{return hex2b64(this.getKey().encrypt(e))}catch(e){return!1}},e.prototype.sign=function(e,t,n){try{return hex2b64(this.getKey().sign(e,t,n))}catch(e){return!1}},e.prototype.verify=function(e,t,n){try{return this.getKey().verify(e,b64tohex(t),n)}catch(e){return!1}},e.prototype.getKey=function(e){if(!this.key){if(this.key=new JSEncryptRSAKey,e&&"[object Function]"==={}.toString.call(e))return void this.key.generateAsync(this.default_key_size,this.default_public_exponent,e);this.key.generate(this.default_key_size,this.default_public_exponent)}return this.key},e.prototype.getPrivateKey=function(){return this.getKey().getPrivateKey()},e.prototype.getPrivateKeyB64=function(){return this.getKey().getPrivateBaseKeyB64()},e.prototype.getPublicKey=function(){return this.getKey().getPublicKey()},e.prototype.getPublicKeyB64=function(){return this.getKey().getPublicBaseKeyB64()},e.version=version,e}(),networkMonitoringConfig={requestState:!1,delay:0},hangupWav="https://softphone.useasy.cn/hangup.wav",ringingWav="https://softphone.useasy.cn/ring.wav",ueSoftphone=function(){function e(e){void 0===e&&(e={});var n=this;this.getWebrtcInfo=function(e,n,r){t.request(e+"/call/api/sip/webrtc/config/query",{verb:"GET",loginToken:t.loginToken,sessionId:t.agentInfo._id,success:function(e){e.success&&e.data?(t.agentextras=e.data,"WEBRTC"===r&&t.initWebrtcEvent(e.data)):n.error(__assign({},e))},error:function(e){n.error({error:e})}})},this.initAttachEvent=function(e,r,i,s){t.request(e+"/platform/action/refreshWsToken",{verb:"GET",loginToken:t.loginToken,sessionId:t.agentInfo._id,success:function(e){if(e&&e.data){var o="";i.forEach(function(e){"KF"===e.id&&(o=e.url)});var a={query:{accountId:s.accountId,agentNumber:s.agentNumber,agentId:s._id,token:e.data.wsToken,wsExtra:JSON.stringify({loginType:r,channelType:"SDK",ability:["call"]}),timestamp:e.data.timestamp,clientType:1,pushHangupStatistics:t.initOptions.pushHangupStatistics||!1,pushCallinRingStatistics:t.initOptions.pushCallinRingStatistics||!1},reconnectionDelay:3e3,"force new connection":!0,transports:["websocket"],timeout:5e3};n.attachEventCallbacks?(n.attachEventCallbacks.serve=o,n.attachEventCallbacks.SocketOptions=a,t.createEventHandle(n.attachEventCallbacks)):t.createEventHandle({serve:o,SocketOptions:a})}},error:function(e){i.error({error:e})}})},this.attachNetworkCallbacks={message:t.noop,error:t.noop,success:t.noop},this.initnNetworkMonitoring=function(e,r){var i="";e.forEach(function(e){"MONITOR"===e.id&&(i="https://"+e.url)}),n.attachNetworkCallbacks.success(),n.attachNetworkCallbacks.message({delay:100}),setInterval(function(){var e=(new Date).getTime();networkMonitoringConfig.requestState=!0,t.request(i+"/ready",{method:"GET",success:function(t){if(t.success){var r=(new Date).getTime();networkMonitoringConfig.delay=(r-e)/2,n.attachNetworkCallbacks.message({delay:networkMonitoringConfig.delay})}else n.attachNetworkCallbacks.error(),networkMonitoringConfig.delay=500,networkMonitoringConfig.requestState=!1},error:function(e){n.attachNetworkCallbacks.error(),networkMonitoringConfig.delay=500,networkMonitoringConfig.requestState=!1}})},1e4)},this.listenCallNetork=function(e){e&&(n.attachNetworkCallbacks.message=e.message&&"function"==typeof e.message?e.message:t.noop,n.attachNetworkCallbacks.success=e.success&&"function"==typeof e.success?e.success:t.noop,n.attachNetworkCallbacks.error=e.error&&"function"==typeof e.error?e.error:t.noop)},this.volumeCallbacks={message:t.noop,error:t.noop,success:t.noop},this.stopVolumeCallbacks={error:t.noop,success:t.noop},this.audioContext=null,this.analyser=null,this.dataArray=null,this.stream=null,this.volumeIntervalId=null,this.getMicrophoneVolume=function(){if(!n.analyser||!n.dataArray)return 0;n.analyser.getByteFrequencyData(n.dataArray);for(var e=0,t=0;t<n.dataArray.length;t++)e+=n.dataArray[t];return e/n.dataArray.length},this.initAudioDetection=function(){return __awaiter(n,void 0,void 0,function(){var e,t,n;return __generator(this,function(r){switch(r.label){case 0:if(this.audioContext)return[2];r.label=1;case 1:return r.trys.push([1,3,,4]),e=this,[4,navigator.mediaDevices.getUserMedia({audio:!0})];case 2:return e.stream=r.sent(),this.audioContext=new AudioContext,t=this.audioContext.createMediaStreamSource(this.stream),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=256,this.dataArray=new Uint8Array(this.analyser.frequencyBinCount),t.connect(this.analyser),[3,4];case 3:return n=r.sent(),this.volumeCallbacks.error(n),[3,4];case 4:return[2]}})})},this.startVolumeDetection=function(e,t){return __awaiter(n,void 0,void 0,function(){var t,n=this;return __generator(this,function(r){switch(r.label){case 0:return"WEBRTC"!==e.loginType?(this.volumeCallbacks.error("只有webrtc支持音量检测"),[2]):(this.clearVolumeDetection(),[4,this.initAudioDetection()]);case 1:return r.sent(),this.volumeCallbacks.success({code:"200",msg:"音频检测已初始化"}),e.interval||(e.interval=500),e.interval<100&&(e.interval=100),e.interval>5e3&&(e.interval=5e3),t=this.getMicrophoneVolume(),this.volumeCallbacks.message({volume:Math.round(t/255*100)}),this.volumeIntervalId=setInterval(function(){var e=n.getMicrophoneVolume();n.volumeCallbacks.message({volume:Math.round(e/255*100)})},e.interval),[2]}})})},this.clearVolumeDetection=function(){n.volumeIntervalId&&(clearInterval(n.volumeIntervalId),n.volumeIntervalId=null),n.stream&&(n.stream.getTracks().forEach(function(e){return e.stop()}),n.stream=null),n.audioContext&&(n.audioContext.close(),n.audioContext=null),n.analyser=null,n.dataArray=null},this.stopVolumeDetection=function(){try{n.clearVolumeDetection(),n.stopVolumeCallbacks.success({code:"200",msg:"音频检测关闭成功"})}catch(e){n.stopVolumeCallbacks.error(e)}},this.listenCallVolume=function(e){e&&(n.volumeCallbacks.message=e.message&&"function"==typeof e.message?e.message:t.noop,n.volumeCallbacks.success=e.success&&"function"==typeof e.success?e.success:t.noop,n.volumeCallbacks.error=e.error&&"function"==typeof e.error?e.error:t.noop),t.initOptions.volume||(t.initOptions.volume={open:!0,interval:500}),n.startVolumeDetection(__assign(__assign({},t.initOptions.volume),{loginType:t.initOptions.loginType}),"")},this.stopListenVolume=function(e){e&&(n.stopVolumeCallbacks.success=e.success&&"function"==typeof e.success?e.success:t.noop,n.stopVolumeCallbacks.error=e.error&&"function"==typeof e.error?e.error:t.noop),n.stopVolumeDetection()},this.turnOffRingCallbacks={error:t.noop,success:t.noop},this.muteRing=function(e){e&&(n.turnOffRingCallbacks.success=e.success&&"function"==typeof e.success?e.success:t.noop,n.turnOffRingCallbacks.error=e.error&&"function"==typeof e.error?e.error:t.noop);try{t.isCanRing=!1,AudioTaskInstance.ringAudioPause(),n.turnOffRingCallbacks.success({code:"200",msg:"关闭铃声成功"})}catch(e){n.turnOffRingCallbacks.error(e)}},this.sdkMonitorMsg=function(e){if(e.success=e&&"function"==typeof e.success?e.success:t.noop,e.error=e&&"function"==typeof e.error?e.error:t.noop,null!==e.type&&void 0!==e.type&&""!==e.type)if(null!==e.requestMsg&&void 0!==e.requestMsg&&""!==e.requestMsg&&"{}"!==JSON.stringify(e.requestMsg))if(t.initOptions.monitor)try{t.changeMonitorEventHandle(n.allMonitorEventCallbacks,e),e.success({code:"200",msg:"成功"})}catch(t){e.error(t)}else e.error({success:!1,message:"The monitor is not turned on when initializing!"});else e.error({success:!1,message:"Parameter requestMsg is required!"});else e.error({success:!1,message:"Parameter type is required!"})},this.closeSdkMonitor=function(e){if(e.success=e&&"function"==typeof e.success?e.success:t.noop,e.error=e&&"function"==typeof e.error?e.error:t.noop,null!==e.type&&void 0!==e.type&&""!==e.type&&0!==e.type.length)if(t.initOptions.monitor)try{e.type.forEach(function(e){switch(e){case"summary":clearInterval(t.summaryUeTimer);break;case"agent":clearInterval(t.agentUeTimer);break;case"queue":clearInterval(t.queueUeTimer)}}),e.success({code:"200",msg:"success"})}catch(t){e.error(t)}else e.error({success:!1,message:"The monitor is not turned on when initializing!"});else e.error({success:!1,message:"Parameter type is required!"})},this.initAgentQueue=function(e,r,i,s){(n.attachMonitorEventCallbacks||n.attachNlsTranslationEventCallbacks||n.allMonitorEventCallbacks)&&t.request(e+"/platform/action/refreshWsToken",{verb:"GET",loginToken:t.loginToken,sessionId:t.agentInfo._id,success:function(e){if(e&&e.data){var o="";i.forEach(function(e){"MONITOR"===e.id&&(o=e.url)});var a={query:{accountId:s.accountId,agentNumber:s.agentNumber,agentId:s._id,token:e.data.wsToken,wsExtra:JSON.stringify({loginType:r,channelType:"SDK",ability:["call"]}),timestamp:e.data.timestamp,clientType:3},reconnectionDelay:3e3,"force new connection":!0,transports:["websocket"],timeout:5e3};n.attachMonitorEventCallbacks&&t.UserConfig.isOpenCallQueue&&(n.attachMonitorEventCallbacks.serve=o,n.attachMonitorEventCallbacks.SocketOptions=a,t.createQueueMonitorEventHandle(n.attachMonitorEventCallbacks)),n.attachNlsTranslationEventCallbacks&&t.UserConfig.openNlsTranslation&&(n.attachNlsTranslationEventCallbacks.serve=o,n.attachNlsTranslationEventCallbacks.SocketOptions=a,t.createopenNlsTransEventHandle(n.attachNlsTranslationEventCallbacks)),n.allMonitorEventCallbacks&&t.UserConfig.monitor&&(n.allMonitorEventCallbacks.serve=o,n.allMonitorEventCallbacks.SocketOptions=a,t.createopenAllMonitorEventHandle(n.allMonitorEventCallbacks))}},error:function(e){t.log("失败"),i.error({error:e})}})},this.initQueue=function(e){t.request(e+"/call/monitor/agent/queue/query",{verb:"POST",body:{accountId:t.agentInfo.accountId,agentId:t.agentInfo._id},success:function(e){e&&e.data?n.attachMonitorEventCallbacks.message(e):n.attachMonitorEventCallbacks.error(e)},error:function(e){n.attachMonitorEventCallbacks.error(e)}})},this.listenCallQueueEvent=function(e){n.attachMonitorEventCallbacks=e},this.listenTranslationEvent=function(e){n.attachNlsTranslationEventCallbacks=e},this.listenMonitor=function(e){n.allMonitorEventCallbacks=e},this.openMediaAudio=function(e,t){var r,i=navigator,s=i.mediaDevices,o=i.getUserMedia,a=i.webkitGetUserMedia,c=i.mozGetUserMedia,u=i.msGetUserMedia,l=null===(r=s&&s.getUserMedia||o||a||c||u)||void 0===r?void 0:r.bind(navigator);return s&&s.getUserMedia?s.getUserMedia({audio:!0}).then(function(e){return __awaiter(n,void 0,void 0,function(){return __generator(this,function(t){return h(e),[2,!0]})})}).catch(function(n){var r=n.message.includes("Permission denied")||"NotAllowedError"===n.name;return t?(r?alert(AUDIO_FORBIDDEN.forbiddenAudioMsg):e&&alert(e),r?AUDIO_FORBIDDEN:NOT_OPEN_AUDIO):r?AUDIO_FORBIDDEN:NOT_OPEN_AUDIO}):new Promise(function(n,r){l?l({audio:!0},function(e){h(e),n(!0)},function(n){t&&e&&alert(e),r(NOT_OPEN_AUDIO)}):r(NOT_OPEN_AUDIO)});function h(e){e&&"function"==typeof e.getTracks&&e.getTracks().forEach(function(e){e.stop()})}},this.listenCallEvent=function(e){n.attachEventCallbacks=e,e&&null!=t.Socketinstance&&t.createEventHandle(n.attachEventCallbacks)},this.switchOutDevices=function(e){return __awaiter(n,void 0,void 0,function(){var n,r,i,s;return __generator(this,function(o){switch(o.label){case 0:if(e.success=e&&"function"==typeof e.success?e.success:t.noop,e.fail=e&&"function"==typeof e.fail?e.fail:t.noop,!e.deviceId||"string"!=typeof e.deviceId)return e.fail({success:!1,message:"Passing in an illegal deviceId!"}),[2];n=document.getElementById("ueRemoteAudio"),o.label=1;case 1:return o.trys.push([1,4,,5]),[4,navigator.mediaDevices.enumerateDevices()];case 2:return r=o.sent(),i=r.filter(function(e){return"audiooutput"===e.kind}),i.some(function(t){return t.deviceId===e.deviceId})?[4,n.setSinkId(e.deviceId)]:(e.fail({success:!1,message:"The deviceId is not in the output device list!"}),[2]);case 3:return o.sent(),[3,5];case 4:return s=o.sent(),e.fail(s),[3,5];case 5:return e.success({code:"200",msg:"切换音频输出设备成功"}),[2]}})})},this._callApi=function(){var e,r,i=n;return{callout:function(n){return __awaiter(this,void 0,void 0,function(){var s,o,a,c,u,l;return __generator(this,function(h){switch(h.label){case 0:if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null===t.loginToken||void 0===t.loginToken)return n.fail({success:!1,message:"initialization not complete!"}),[2];if("KICK_OFF"===t.loginToken)return n.fail({success:!1,message:"您的座席账号正在别处登录,当前页面电话条已退出。"}),[2];if(null===t.agentInfo||void 0===t.agentInfo)return n.fail({success:!1,message:"initialization not complete!"}),[2];if(null===n.customerNumber||void 0===n.customerNumber)return n.fail({success:!1,message:"Parameter customerNumber is required!"}),[2];if(s=t.initOptions.server||t.callApiUrl,o={customerNumber:n.customerNumber,agentNumber:t.agentInfo.agentNumber,accountId:t.agentInfo.accountId,agentId:t.agentInfo._id,loginType:n.loginType||t.agentInfo.loginType||t.initOptions.loginType},n.agentTimeout&&(o.agentTimeout=n.agentTimeout),n.customerTimeout&&(o.customerTimeout=n.customerTimeout),n.agentDisNumber&&(o.agentDisNumber=n.agentDisNumber),n.customerDisNumber&&(o.customerDisNumber=n.customerDisNumber),n.extras&&(o.extras=n.extras),n.numberGroupId&&(o.numberGroupId=n.numberGroupId),n.numberGroupName&&(o.numberGroupName=n.numberGroupName),a=t.initOptions,c=!0,"WEBRTC"!==a.loginType)return[3,4];h.label=1;case 1:return h.trys.push([1,3,,4]),[4,i.openMediaAudio("请打开麦克风权限!",c)];case 2:return u=h.sent()||{},t.log(u),!0!==u?(n.fail({success:!1,message:"无麦克风权限!"}),[2]):[3,4];case 3:return l=h.sent(),t.log(l),n.fail({success:!1,message:"无麦克风权限!"}),[2];case 4:return t.request(s+"/call/api/call/call/out",{verb:"POST",body:o,loginToken:t.loginToken,sessionId:t.agentInfo._id,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success(__assign(__assign({success:!0,message:"callout success"},u),e.data)):n.fail(__assign({success:!1,message:e.message,code:e.code},u))}}),[2]}})})},hangup:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/call/hangup",{verb:"POST",body:{},loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?(n.success({success:!0,message:"hangup success",data:e}),AudioTaskInstance.InvalidateHangup()):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},holdOrUnHold:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.type&&void 0!==n.type){var i=t.initOptions.server||t.callApiUrl,s={type:n.type};t.request(i+"/call/api/call/hold",{verb:"POST",body:s,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"holdOrUnHold success"}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"Parameter type is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},muteOrUnMute:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.type&&void 0!==n.type){var i=t.initOptions.server||t.callApiUrl,s="1"===n.type?"in":"all",o={type:n.type,direction:s};t.request(i+"/call/api/call/mute",{verb:"POST",body:o,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"muteOrUnMute success"}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"Parameter type is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},transfer:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.type&&void 0!==n.type)if(null!==n.number&&void 0!==n.number){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/call/transfer",{verb:"POST",body:n,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"transfer success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"Parameter number is required!"});else n.fail({success:!1,message:"Parameter type is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},consult:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.mode&&void 0!==n.mode)if(null!==n.number&&void 0!==n.number){n.agentNumber=t.agentInfo.agentNumber;var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/call/consult",{verb:"POST",body:n,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"consult success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"Parameter number is required!"});else n.fail({success:!1,message:"Parameter mode is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},cancelconsult:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/call/consult/cancel",{verb:"POST",body:n,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"cancelconsult success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},endConsult:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/call/consult/stop",{verb:"POST",body:n,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"endConsult success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},callbackConsult:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/call/consult/resume",{verb:"POST",body:n,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"resumeConsult success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},consultTransfer:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/call/consult/transfer",{verb:"POST",body:n,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"consultTransfer success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},threeWayCall:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/call/threeway",{verb:"POST",body:n,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"threeWayCall success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},evaluate:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.type&&void 0!==n.type){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/call/evaluate",{verb:"POST",body:n,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"evaluate success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"Parameter type is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},meeting:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.number&&void 0!==n.number){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/call/meeting",{verb:"POST",body:{meetingType:"phone",number:n.number},loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"meeting success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"Parameter number is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},listen:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.agentNumber&&void 0!==n.agentNumber)if(n.agentNumber!==t.agentInfo.agentNumber&&"0000"!==t.agentInfo.agentNumber){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/monitor/listen",{verb:"POST",body:{agentNumber:n.agentNumber,listenAgent:t.agentInfo.agentNumber},loginToken:t.loginToken,sessionId:t.agentInfo._id,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"listen success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"agentNumber is not allowed to be the same as the current login account!"});else n.fail({success:!1,message:"Parameter agentNumber is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},loot:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.agentNumber&&void 0!==n.agentNumber)if(n.agentNumber!==t.agentInfo.agentNumber&&"0000"!==t.agentInfo.agentNumber){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/monitor/lootCall",{verb:"POST",body:{agentNumber:n.agentNumber,lootAgent:t.agentInfo.agentNumber},loginToken:t.loginToken,sessionId:t.agentInfo._id,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"loot success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"agentNumber is not allowed to be the same as the current login account!"});else n.fail({success:!1,message:"Parameter agentNumber is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},forcedHangup:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.agentNumber&&void 0!==n.agentNumber)if(n.agentNumber!==t.agentInfo.agentNumber&&"0000"!==t.agentInfo.agentNumber){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/monitor/hangupChannel",{verb:"POST",body:{agentNumber:n.agentNumber,hangupAgent:t.agentInfo.agentNumber},loginToken:t.loginToken,sessionId:t.agentInfo._id,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"forcedHangup success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"agentNumber is not allowed to be the same as the current login account!"});else n.fail({success:!1,message:"Parameter agentNumber is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},breakIn:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.agentNumber&&void 0!==n.agentNumber)if(n.agentNumber!==t.agentInfo.agentNumber&&"0000"!==t.agentInfo.agentNumber){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/monitor/breakIn",{verb:"POST",body:{agentNumber:n.agentNumber,breakInAgent:t.agentInfo.agentNumber},loginToken:t.loginToken,sessionId:t.agentInfo._id,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"breakIn success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"agentNumber is not allowed to be the same as the current login account!"});else n.fail({success:!1,message:"Parameter agentNumber is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})},whisper:function(n){if(n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null!==t.loginToken&&void 0!==t.loginToken)if(null!==t.agentInfo&&void 0!==t.agentInfo)if(null!==n.agentNumber&&void 0!==n.agentNumber)if(n.agentNumber!==t.agentInfo.agentNumber&&"0000"!==t.agentInfo.agentNumber){var i=t.initOptions.server||t.callApiUrl;t.request(i+"/call/api/monitor/whisper",{verb:"POST",body:{agentNumber:n.agentNumber,whisperAgent:t.agentInfo.agentNumber},loginToken:t.loginToken,sessionId:t.agentInfo._id,encryptionAlgorithm:e,encryptionFields:r,success:function(e){e.success?n.success({success:!0,message:"whisper success",data:e.data}):n.fail({success:!1,message:e.message,code:e.code})}})}else n.fail({success:!1,message:"agentNumber is not allowed to be the same as the current login account!"});else n.fail({success:!1,message:"Parameter agentNumber is required!"});else n.fail({success:!1,message:"initialization not complete!"});else n.fail({success:!1,message:"initialization not complete!"})}}},this._agentApi=function(){var e=n;return{switchLoginType:function(n){return __awaiter(this,void 0,void 0,function(){var r,i,s,o,a=this;return __generator(this,function(c){return r=null,n.success=n&&"function"==typeof n.success?n.success:t.noop,n.fail=n&&"function"==typeof n.fail?n.fail:t.noop,null===n.loginType||void 0===n.loginType?(n.fail({success:!1,message:"Parameter loginType is required!"}),[2]):null===t.agentInfo||void 0===t.agentInfo?(n.fail({success:!1,message:"initialization not complete!"}),[2]):(null!==n.loginNumber&&void 0!==n.loginNumber&&(r=n.loginNumber),"PSTN"!==n.loginType||(r=r||t.agentInfo.mobile)?("SIP"===n.loginType&&(r=r||t.agentInfo.sipNumber),"WEBRTC"===n.loginType&&(r=t.agentInfo.webrtcSipNumber),i=t.initOptions.server||t.callApiUrl,s={loginType:n.loginType,loginNumber:r},t.request(i+"/call/api/agent/v1/login-type/change",{verb:"POST",body:s,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,success:function(r){return __awaiter(a,void 0,void 0,function(){return __generator(this,function(s){switch(s.label){case 0:return r.success?(n.success(__assign({success:!0,message:"updateLoginType success"},o)),t.agentInfo.loginType=n.loginType,t.initOptions.loginType=n.loginType,"WEBRTC"!==n.loginType?[3,1]:(e._webPhoneApi().connect(),[3,4])):[3,5];case 1:return"PSTN"!==n.loginType?[3,3]:[4,t.request(i+"/platform/action/updateCallConfig",{verb:"POST",body:{agentCallConfig:{},mobile:n.loginNumber},loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId})];case 2:return s.sent(),e._webPhoneApi().disconnect(),[3,4];case 3:e._webPhoneApi().disconnect(),s.label=4;case 4:return[3,6];case 5:n.fail(__assign({success:!1,message:r.message,code:r.code},o)),s.label=6;case 6:return[2]}})})}}),[2]):(alert("请给座席绑定手机号,或者传入号码参数!"),n.fail({success:!1,message:"Please bind your mobile number"}),[2]))})})},findPhoneBarList:function(e){if(e.success=e&&"function"==typeof e.success?e.success:t.noop,e.fail=e&&"function"==typeof e.fail?e.fail:t.noop,null!==t.agentInfo&&void 0!==t.agentInfo){var n=t.initOptions.server||t.callApiUrl;t.request(n+"/call/api/phone/bar/all",{verb:"GET",loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,success:function(t){if(t.success){var n=[];t.data.forEach(function(e){var t={name:e.name,number:e.number};n.push(t)}),e.success({success:!0,data:n})}else e.fail({success:!1,message:t.message,code:t.code})}})}else e.fail({success:!1,message:"initialization not complete!"})},switchPhoneBar:function(e){if(e.success=e&&"function"==typeof e.success?e.success:t.noop,e.fail=e&&"function"==typeof e.fail?e.fail:t.noop,null!==e.stateNumber&&void 0!==e.stateNumber)if(null!==t.agentInfo&&void 0!==t.agentInfo){var n=t.initOptions.server||t.callApiUrl,r={stateNumber:e.stateNumber,accountId:t.agentInfo.accountId,agentNumber:t.agentInfo.agentNumber};t.request(n+"/call/api/agent/status/switch",{verb:"POST",body:r,loginToken:t.loginToken,sessionId:t.agentInfo._id,success:function(t){t.success?e.success({success:!0}):e.fail({success:!1,message:t.message,code:t.code})}})}else e.fail({success:!1,message:"initialization not complete!"});else e.fail({success:!1,message:"Parameter stateNumber is required!"})},logout:function(e){if(e.success=e&&"function"==typeof e.success?e.success:t.noop,e.fail=e&&"function"==typeof e.fail?e.fail:t.noop,null!==t.agentInfo&&void 0!==t.agentInfo){null!==e.toAnswerOffline&&void 0!==e.toAnswerOffline||(e.toAnswerOffline="0");var n=t.initOptions.server||t.callApiUrl,r={toAnswerOffline:e.toAnswerOffline};t.request(n+"/call/api/sdk/agent/logout",{verb:"POST",body:r,loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,success:function(n){n.success?e&&(t.Socketinstance&&(t.Socketinstance.disconnect(),t.Socketinstance=null),t.MonitorSocketinstance&&(t.MonitorSocketinstance.disconnect(),t.MonitorSocketinstance=null),"WEBRTC"===t.UserConfig.loginType&&t.webPhone&&(window.sessionStorage.setItem("kickoff","true"),t.webPhone.disconnect(),t.webPhone=null),e.success({success:!0})):e&&e.fail({success:!1,message:n.message,code:n.code})}})}else e.fail({success:!1,message:"initialization not complete!"})},findIdleAgentsForQueue:function(e){if(e.success=e&&"function"==typeof e.success?e.success:t.noop,e.fail=e&&"function"==typeof e.fail?e.fail:t.noop,null!==t.agentInfo&&void 0!==t.agentInfo){var n=t.initOptions.server||t.callApiUrl;t.request(n+"/call/api/queue/acountFreeAgent/find",{verb:"POST",body:{},loginToken:t.loginToken,sessionId:t.agentInfo._id,accountId:t.agentInfo.accountId,success:function(t){t.success?e&&e.success({success:!0,dataList:t.data||[]}):e&&e.fail({success:!1,message:t.message,code:t.code})}})}else e.fail({success:!1,message:"initialization not complete!"})},getAvailableSipNumberList:function(e){if(e.success=e&&"function"==typeof e.success?e.success:t.noop,e.fail=e&&"function"==typeof e.fail?e.fail:t.noop,null!==t.agentInfo&&void 0!==t.agentInfo){var n=t.initOptions.server||t.callApiUrl;t.request(n+"/call/api/sip/avaliable/query",{verb:"POST",body:{},loginToken:t.loginToken,sessionId:t.agentInfo._id,success:function(t){if(t.success&&t.data){var n=[];t.data.forEach(function(e){var t={number:e.id,numberName:e.number};n.push(t)}),e.success({success:!0,data:n})}else e.fail({success:!1,message:t.message,code:t.code})}})}else e.fail({success:!1,message:"initialization not complete!"})}}},this._webPhoneApi=function(){return{accept:function(){t.webPhone.accept()},connect:function(){t.webPhone&&this.isConnected()||t.initWebrtcEvent(t.agentextras)},disconnect:function(){t.webPhone&&this.isConnected()&&t.webPhone.disconnect()},isConnected:function(){return t.webPhone.isConnected()},sendDTMF:function(e){t.webPhone.sendDTMF(e)}}},e.error="function"==typeof e.error?e.error:t.noop,e.success="function"==typeof e.success?e.success:t.noop,null!==e.accountName&&void 0!==e.accountName&&""!==e.accountName||null!==e.accountId&&void 0!==e.accountId&&""!==e.accountId?null!==e.accountName&&void 0!==e.accountName&&""!==e.accountName||null!==e.agentNumber&&void 0!==e.agentNumber&&""!==e.accountId?null!==e.password&&void 0!==e.password||null!==e.passwordPk&&void 0!==e.passwordPk?e.password&&e.passwordPk?e.error({message:"Invalid password, please use one of them"}):(null!==e.loginType&&void 0!==e.loginType||(e.loginType="PSTN"),null!==e.pushHangupStatistics&&void 0!==e.pushHangupStatistics||(e.pushHangupStatistics=!1),null!==e.pushCallinRingStatistics&&void 0!==e.pushCallinRingStatistics||(e.pushCallinRingStatistics=!1),this.init(e)):e.error({message:"Invalid password"}):e.error({message:"Invalid agentNumber or Invalid accountName"}):e.error({message:"Invalid accountId or Invalid accountName"})}var t;return e.noop=function(){},e.prototype.init=function(e){if(void 0===e&&(e={}),t.trace=t.noop,t.debug=t.noop,t.log=t.noop,t.warn=t.noop,t.error=t.noop,!0===e.debug||"all"===e.debug)t.trace=console.trace.bind(console),t.debug=console.debug.bind(console),t.log=console.log.bind(console),t.warn=console.warn.bind(console),t.error=console.error.bind(console);else if(Array.isArray(e.debug))for(var n in e.debug){var r=e.debug[n];switch(r){case"trace":t.trace=console.trace.bind(console);break;case"debug":t.debug=console.debug.bind(console);break;case"log":t.log=console.log.bind(console);break;case"warn":t.warn=console.warn.bind(console);break;case"error":t.error=console.error.bind(console);break;default:console.error("Unknown debugging option '"+r+"' (supported: 'trace', 'debug', 'log', warn', 'error')")}}t.log("Initializing library");var i=t.useDefaultDependencies({WebSocket:ueWebsocket});t.newWebSocket=i.newWebSocket,t.request=i.request,this.getDomain(e)},e.prototype.getDomain=function(e){return __awaiter(this,void 0,void 0,function(){var n,r,i,s=this;return __generator(this,function(o){return n=(null===(i=e.accountName)||void 0===i?void 0:i.split("@")[1])||e.accountId,r=e.server||t.callApiUrl,t.request(r+"/platform/public/cloudConfig?accountName="+n,{verb:"GET",success:function(n){n.success?(e.server="https://"+n.data.baseURL+"/api",t.callApiUrl="https://"+n.data.baseURL+"/api",s.login(e)):e.error({res:n})},error:function(t){e.error({error:t})}}),[2]})})},e.prototype.login=function(e){return __awaiter(this,void 0,void 0,function(){var n,r,i,s,o,a,c,u,l,h=this;return __generator(this,function(d){return t.log(e),t.UserConfig=e,n=e.server||t.callApiUrl,r=e.accountName?e.accountName:e.agentNumber+"@"+e.accountId,i=e.loginType,s=e.isOpenNetwork||!1,o=e.isOpenCallQueue||!1,a=e.openNlsTranslation||!1,c=e.monitor||!1,u={loginName:r,loginType:i,loginChannel:"SDK",password:"",clientType:1},e.password&&(u.password=e.password,t.request(n+"/platform/public/loginPre",{verb:"GET",success:function(r){if(r&&r.success&&r.data){var d=decodeURIComponent(gBase64.decode(r.data.pk)),p=new JSEncrypt;p.setPublicKey(d);var g=md5(u.password),f=p.encrypt(g);u.password=f,t.request(n+"/platform/public/login",{verb:"POST",body:u,success:function(r){r.success?t.request(n+"/platform/action/loginInfo",{verb:"GET",loginToken:r.data.loginToken,sessionId:r.data.sessionId,success:function(r){r.success?(r.data.agent&&(t.agentInfo=r.data.agent,t.loginToken=r.data.loginToken,t.initOptions=__assign(__assign({},e),{audioInfo:l}),e.success(__assign(__assign({},r),{msg:"登录成功"}))),h.initAttachEvent(n,i,r.data.pushServer,r.data.agent),s&&h.initnNetworkMonitoring(r.data.pushServer,""),(o||a||c)&&h.initAgentQueue(n,i,r.data.pushServer,r.data.agent),o&&h.initQueue(n),h.getWebrtcInfo(n,e,i),window.sessionStorage.removeItem("kickoff")):e.error(__assign(__assign({},r),l))},error:function(t){e.error(__assign({error:t},l))}}):e.error(__assign(__assign({},r),l))},error:function(t){e.error(__assign({error:t},l))}})}else e.error(__assign(__assign({},r),l))},error:function(t){e.error(__assign({error:t},l))}})),e.passwordPk&&(u.password=e.passwordPk,t.request(n+"/platform/public/login",{verb:"POST",body:u,success:function(r){r.success?t.request(n+"/platform/action/loginInfo",{verb:"GET",loginToken:r.data.loginToken,sessionId:r.data.sessionId,success:function(r){r.success?(r.data.agent&&(t.agentInfo=r.data.agent,t.loginToken=r.data.loginToken,t.initOptions=__assign(__assign({},e),{audioInfo:l}),e.success(__assign(__assign({},r),{msg:"登录成功"}))),h.initAttachEvent(n,i,r.data.pushServer,r.data.agent),s&&h.initnNetworkMonitoring(r.data.pushServer,""),(o||a||c)&&h.initAgentQueue(n,i,r.data.pushServer,r.data.agent),o&&h.initQueue(n),h.getWebrtcInfo(n,e,i),window.sessionStorage.removeItem("kickoff")):e.error(__assign(__assign({},r),l))},error:function(t){e.error(__assign({error:t},l))}}):e.error(__assign(__assign({},r),l))},error:function(t){e.error(__assign({error:t},l))}})),[2]})})},e.createEventHandle=function(e){void 0===e&&(e={}),e.success="function"==typeof e.success?e.success:t.noop,e.error="function"==typeof e.error?e.error:t.noop,e.message="function"==typeof e.message?e.message:t.noop,e.event="function"==typeof e.event?e.event:t.noop,e.server=null===e.serve||void 0===e.serve?"ws://152.136.72.209:3201/phoneBarGateway":e.serve,null!==e.SocketOptions&&void 0!==e.SocketOptions||(e.SocketOptions={},t.error({message:"login response error!"})),this.Socketinstance||(this.Socketinstance=t.newWebSocket(e.server,e.SocketOptions)),this.Socketinstance.on("connect",function(){e.success("connect event serve success!")}),this.Socketinstance.on("error",function(t,n){e.error({type:"socketError",error:t}),n&&"function"==typeof n&&n("error")}),this.Socketinstance.on("message",function(n,r){e.message({subtype:n.subType,data:n.data}),"WEBRTC"===t.initOptions.loginType&&judgementWebRtcSHandOrRing("WEBRTC",n.data),r&&"function"==typeof r&&r("success")}),this.Socketinstance.on("event",function(n){if("KICK_OFF"===n.subType&&(window.sessionStorage.setItem("kickoff","true"),!0===n.data.kickoff)){try{t.kickOffEvent()}catch(e){}e.event({message:"坐席账户在其他地方登录",data:n})}})},e.createQueueMonitorEventHandle=function(e){void 0===e&&(e={}),e.success="function"==typeof e.success?e.success:t.noop,e.error="function"==typeof e.error?e.error:t.noop,e.message="function"==typeof e.message?e.message:t.noop,e.server=null===e.serve||void 0===e.serve?"ue-dev1.useasy.cn":e.serve,null!==e.SocketOptions&&void 0!==e.SocketOptions||(e.SocketOptions={},t.error({message:"login response error!"})),null===this.MonitorSocketinstance&&(this.MonitorSocketinstance=t.newWebSocket(e.server,e.SocketOptions)),this.MonitorSocketinstance.on("connect",function(){e.success("connect event serve success!"),t.log("监控connect========")}),this.MonitorSocketinstance.on("error",function(t,n){e.error({type:"socketError",error:t}),n&&"function"==typeof n&&n("error")}),this.MonitorSocketinstance.on("event",function(n,r){if("KICK_OFF"===n.subType&&(window.sessionStorage.setItem("kickoff","true"),!0===n.data.kickoff)){try{t.kickOffEvent()}catch(e){}e.message({message:"坐席账户在其他地方登录",data:n})}e.message(n)}),this.MonitorSocketinstance.on("call",function(n,r){"queue"==n.subType&&t.UserConfig.isOpenCallQueue&&e.message({subtype:n.subType,data:n.data})})},e.createopenNlsTransEventHandle=function(e){void 0===e&&(e={}),e.success="function"==typeof e.success?e.success:t.noop,e.error="function"==typeof e.error?e.error:t.noop,e.message="function"==typeof e.message?e.message:t.noop,e.server=null===e.serve||void 0===e.serve?"ue-dev1.useasy.cn":e.serve,null!==e.SocketOptions&&void 0!==e.SocketOptions||(e.SocketOptions={},t.error({message:"login response error!"})),null===this.MonitorSocketinstance&&(this.MonitorSocketinstance=t.newWebSocket(e.server,e.SocketOptions)),this.MonitorSocketinstance.on("connect",function(){e.success("转译connect event serve success!"),t.log("转译监控connect========")}),this.MonitorSocketinstance.on("error",function(t,n){e.error({type:"socketError",error:t}),n&&"function"==typeof n&&n("error")}),this.MonitorSocketinstance.on("event",function(n,r){if("KICK_OFF"===n.subType&&(window.sessionStorage.setItem("kickoff","true"),!0===n.data.kickoff)){try{t.kickOffEvent()}catch(e){}e.message({message:"坐席账户在其他地方登录",data:n})}e.message(n)}),this.MonitorSocketinstance.on("call",function(n,r){"translation"==n.subType&&t.UserConfig.openNlsTranslation&&e.message({subtype:n.subType,data:n.data})})},e.createopenAllMonitorEventHandle=function(e){void 0===e&&(e={}),e.success="function"==typeof e.success?e.success:t.noop,e.error="function"==typeof e.error?e.error:t.noop,e.message="function"==typeof e.message?e.message:t.noop,e.server=null===e.serve||void 0===e.serve?"ue-dev1.useasy.cn":e.serve,null!==e.SocketOptions&&void 0!==e.SocketOptions||(e.SocketOptions={},t.error({message:"login response error!"})),null===this.MonitorSocketinstance&&(this.MonitorSocketinstance=t.newWebSocket(e.server,e.SocketOptions)),this.MonitorSocketinstance.on("connect",function(){e.success("转译connect event serve success!"),t.log("转译监控connect========")}),this.MonitorSocketinstance.on("error",function(t,n){e.error({type:"socketError",error:t}),n&&"function"==typeof n&&n("error")}),this.MonitorSocketinstance.on("event",function(n,r){if("KICK_OFF"===n.subType&&(window.sessionStorage.setItem("kickoff","true"),!0===n.data.kickoff)){try{t.kickOffEvent()}catch(e){}e.message({message:"坐席账户在其他地方登录",data:n})}e.message(n)}),t.UserConfig.monitor&&this.MonitorSocketinstance.on("monitor",function(n){t.UserConfig.monitor&&e.message({type:"agent",data:n})})},e.changeMonitorEventHandle=function(e,n){var r=this;void 0===e&&(e={}),e.success="function"==typeof e.success?e.success:t.noop,e.error="function"==typeof e.error?e.error:t.noop,e.message="function"==typeof e.message?e.message:t.noop,e.server=null===e.serve||void 0===e.serve?"ue-dev1.useasy.cn":e.serve,null!==e.SocketOptions&&void 0!==e.SocketOptions||(e.SocketOptions={},t.error({message:"login response error!"})),null===this.MonitorSocketinstance&&(this.MonitorSocketinstance=t.newWebSocket(e.server,e.SocketOptions)),t.UserConfig.monitor&&n&&(t.agentUeTimer&&clearInterval(t.agentUeTimer),t.queueUeTimer&&clearInterval(t.queueUeTimer),t.summaryUeTimer&&clearInterval(t.summaryUeTimer),n.type.forEach(function(i){var s;switch(i){case"agent":null!==r.MonitorSocketinstance&&(null===(s=r.MonitorSocketinstance)||void 0===s||s.emit("monitor","agent",JSON.stringify(__assign(__assign({},n.requestMsg),{monitorQueryAgent:t.agentInfo._id,accountId:t.agentInfo.accountId})))),t.agentUeTimer=window.setInterval(function(){var e;null===(e=r.MonitorSocketinstance)||void 0===e||e.emit("monitor","agent",JSON.stringify(__assign(__assign({},n.requestMsg),{monitorQueryAgent:t.agentInfo._id,accountId:t.agentInfo.accountId})))},3e3);break;case"queue":null!==r.MonitorSocketinstance&&r.handleHttpMonitor({type:"queue",url:"/call/monitor/detail/queue",data:{accountId:t.agentInfo.accountId,date:new Date}},e),t.queueUeTimer=window.setInterval(function(){r.handleHttpMonitor({type:"queue",url:"/call/monitor/detail/queue",data:{accountId:t.agentInfo.accountId,date:new Date}},e)},3e3);break;case"summary":null!==r.MonitorSocketinstance&&r.handleHttpMonitor({type:"summary",url:"/call/monitor/overview",data:{accountId:t.agentInfo.accountId,date:new Date}},e),t.summaryUeTimer=window.setInterval(function(){r.handleHttpMonitor({type:"summary",url:"/call/monitor/overview",data:{accountId:t.agentInfo.accountId,date:new Date}},e)},3e3)}}))},e.handleHttpMonitor=function(e,n){t.request(t.callApiUrl+e.url,{verb:"POST",body:e.data,success:function(r){r.success&&t.UserConfig.monitor?n.message({type:e.type,data:r.data}):n.error({type:e.type,data:r})}})},e.useDefaultDependencies=function(e){var n=e&&e.fetch||fetch,r=e&&e.Promise||Promise,i=e&&e.WebSocket||WebSocket;return{newWebSocket:function(e,t){return new i(e,t)},request:function(e,i){var s={method:i.verb,cache:"no-cache",headers:{"Content-Type":"application/json",loginToken:i.loginToken||"",sessionId:i.sessionId||"",clienttype:0}};i.encryptionFields&&(s.headers["ue-encryption-algorithm"]=i.encryptionAlgorithm||"aes",s.headers["ue-encryption-fields"]=i.encryptionFields),void 0!==i.withCredentials&&(s.credentials=!0===i.withCredentials?"include":i.withCredentials?i.withCredentials:"omit"),void 0!==i.body&&(s.body=JSON.stringify(i.body));var o=n(e,s).catch(function(e){return r.reject({message:"Probably a network error, is the gateway down?",error:e})});if(void 0!==i.timeout){var a=new r(function(e,t){var n=window.setTimeout(function(){return clearTimeout(n),i.error({message:"Request timed out",timeout:i.timeout}),t({message:"Request timed out",timeout:i.timeout})},i.timeout)});o=r.race([o,a])}return o.then(function(e){return e.ok?typeof i.success==typeof t.noop?e.json().then(function(e){i.success(e)}).catch(function(t){return i.error({message:"Failed to parse response body",error:t,response:e}),r.reject({message:"Failed to parse response body",error:t,response:e})}):void 0:(i.error({message:"API call failed",response:e}),r.reject({message:"API call failed",response:e}))}).catch(function(e){typeof i.error==typeof t.noop&&i.error(e.message||"<< internal error >>",e)}),o}}},Object.defineProperty(e.prototype,"agent",{get:function(){return this._agentApi()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"webrtc",{get:function(){return this._webPhoneApi()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"call",{get:function(){return this._callApi()},enumerable:!1,configurable:!0}),t=e,e.callApiUrl="https://app.useasy.cn/api",e.Socketinstance=null,e.AudioTask=null,e.MonitorSocketinstance=null,e.UserConfig=null,e.isCanRing=!0,e.kickOffEvent=function(){t.Socketinstance&&(t.Socketinstance.disconnect(),t.Socketinstance=null),t.MonitorSocketinstance&&(t.MonitorSocketinstance.disconnect(),t.MonitorSocketinstance=null),"WEBRTC"===t.UserConfig.loginType&&t.webPhone&&(window.sessionStorage.setItem("kickoff","true"),t.webPhone.disconnect(),t.webPhone=null)},e.initWebrtcEvent=function(e){return __awaiter(void 0,void 0,void 0,function(){return __generator(t,function(n){switch(n.label){case 0:return t.webPhone=new UeWebrtc({server:e.wssUrl,sip:e.sip,secret:e.password}),[4,this.webPhone.connect()];case 1:return n.sent(),this.webPhone.register(),[2]}})})},e}(),ueWebsocket=function(){function e(e,t){delete t.path,delete t.hostname,delete t.port,this.ws=_t.connect("wss://".concat(e),t)}return e.prototype.on=function(e,t){"connect"===e&&this.ws.on(e,t),"error"===e&&(this.ws.on("connect_error",t),this.ws.on("error",t),this.ws.on("disconnect",t),this.ws.on("reconnect_failed",t)),"message"===e&&this.ws.on("call",t),"event"===e&&this.ws.on("event",t),"call"===e&&this.ws.on("call",t),"monitor"===e&&this.ws.on("monitor",t)},e.prototype.emit=function(e,t,n){this.ws.emit(e,t,n)},e.prototype.disconnect=function(){this.ws.disconnect()},e}(),AudioTask=function(){function e(){var e=this;fetch(ringingWav).then(function(e){return e.blob()}).then(function(t){var n=URL.createObjectURL(t);e.ringAudio=new Audio(n),e.ringAudio.loop=!0,e.ringAudioRunning=!1}),fetch(hangupWav).then(function(e){return e.blob()}).then(function(t){var n=URL.createObjectURL(t);e.handupAudio=new Audio(n),e.hangupAllow=!0})}return e.prototype.ringAudioPlay=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,this.ringAudio.play()];case 1:return e.sent(),this.ringAudioRunning=!0,[2]}})})},e.prototype.ringAudioPause=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return this.ringAudio.paused?[3,2]:[4,this.ringAudio.pause()];case 1:e.sent(),this.ringAudioRunning=!1,e.label=2;case 2:return[2]}})})},e.prototype.activeHangup=function(){this.hangupAllow=!0},e.prototype.InvalidateHangup=function(){this.hangupAllow=!1},e.prototype.triggerTask=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return this.hangupAllow?this.handupAudio.play():this.activeHangup(),[2]})})},e}(),AudioTaskInstance=new AudioTask,CALL_METHOD="WEBRTC",CALLEVENT_RING="ring",CALLEVENT_HANGUP="hangup",CALL_FROM_INCOMING="callin",CALL_FROM_INTERCOM="inner",CALL_FROM_TWOWAYCALL="twoWayCall",CALL_FROM_TRANSFER="transfer",CALL_FROM_AUTODIALOUT="autoCallout",judgementWebRtcSHandOrRing=function(e,t){e===CALL_METHOD&&(t.eventType!==CALLEVENT_RING||t.callType!==CALL_FROM_INCOMING&&t.callType!==CALL_FROM_INTERCOM&&t.callType!==CALL_FROM_TWOWAYCALL&&t.callType!==CALL_FROM_TRANSFER&&t.callType!==CALL_FROM_AUTODIALOUT||!ueSoftphone.isCanRing?AudioTaskInstance.ringAudioRunning&&AudioTaskInstance.ringAudioPause():AudioTaskInstance.ringAudioPlay(),t.eventType===CALLEVENT_HANGUP&&(ueSoftphone.isCanRing&&AudioTaskInstance.triggerTask(),ueSoftphone.isCanRing=!0))};return ueSoftphone}();