@94ai/softphone 6.0.9 → 6.0.11

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,2 +1,2 @@
1
- /** 6.0.9 */
2
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("crypto-js"),require("@fingerprintjs/fingerprintjs")):"function"==typeof define&&define.amd?define(["exports","crypto-js","@fingerprintjs/fingerprintjs"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).softphone={},e.CryptoJS,e.FingerprintJS)}(this,function(e,t,i){"use strict";function r(e,t,i,r){return new(i||(i=Promise))(function(s,n){function o(e){try{c(r.next(e))}catch(e){n(e)}}function a(e){try{c(r.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(o,a)}c((r=r.apply(e,t||[])).next())})}function s(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)}function n(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i}"function"==typeof SuppressedError&&SuppressedError;class o extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class a extends o{constructor(e){super(e||"Unsupported content type.")}}class c extends o{constructor(e){super(e||"Request pending.")}}class l extends o{constructor(e){super(e||"Unspecified session description handler error.")}}class h extends o{constructor(){super("The session has terminated.")}}class d extends o{constructor(e){super(e||"An error occurred during state transition.")}}class u{constructor(e){Object.defineProperty(this,"incomingAckRequest",{enumerable:!0,configurable:!0,writable:!0,value:e})}get request(){return this.incomingAckRequest.message}}class g{constructor(e){Object.defineProperty(this,"incomingByeRequest",{enumerable:!0,configurable:!0,writable:!0,value:e})}get request(){return this.incomingByeRequest.message}accept(e){return this.incomingByeRequest.accept(e),Promise.resolve()}reject(e){return this.incomingByeRequest.reject(e),Promise.resolve()}}class f{constructor(e){Object.defineProperty(this,"incomingCancelRequest",{enumerable:!0,configurable:!0,writable:!0,value:e})}get request(){return this.incomingCancelRequest}}class p{constructor(){Object.defineProperty(this,"listeners",{enumerable:!0,configurable:!0,writable:!0,value:new Array})}addListener(e,t){const i=t=>{this.removeListener(i),e(t)};!0===(null==t?void 0:t.once)?this.listeners.push(i):this.listeners.push(e)}emit(e){this.listeners.slice().forEach(t=>t(e))}removeAllListeners(){this.listeners=[]}removeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}on(e){return this.addListener(e)}off(e){return this.removeListener(e)}once(e){return this.addListener(e,{once:!0})}}class v{constructor(e){Object.defineProperty(this,"incomingInfoRequest",{enumerable:!0,configurable:!0,writable:!0,value:e})}get request(){return this.incomingInfoRequest.message}accept(e){return this.incomingInfoRequest.accept(e),Promise.resolve()}reject(e){return this.incomingInfoRequest.reject(e),Promise.resolve()}}class m{constructor(e){Object.defineProperty(this,"parameters",{enumerable:!0,configurable:!0,writable:!0,value:{}});for(const t in e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}setParam(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())}getParam(e){if(e)return this.parameters[e.toLowerCase()]}hasParam(e){return!(!e||void 0===this.parameters[e.toLowerCase()])}deleteParam(e){if(e=e.toLowerCase(),this.hasParam(e)){const t=this.parameters[e];return delete this.parameters[e],t}}clearParams(){this.parameters={}}}class b extends m{constructor(e,t,i){super(i),Object.defineProperty(this,"uri",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_displayName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.uri=e,this._displayName=t}get friendlyName(){return this.displayName||this.uri.aor}get displayName(){return this._displayName}set displayName(e){this._displayName=e}clone(){return new b(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))}toString(){let e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";e+="<"+this.uri.toString()+">";for(const t in this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e}}class y extends m{constructor(e="sip",t,i,r,s,n){if(super(s||{}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"normal",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"raw",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!i)throw new TypeError('missing or invalid "host" parameter');for(const e in n)n.hasOwnProperty(e)&&this.setHeader(e,n[e]);this.raw={scheme:e,user:t,host:i,port:r},this.normal={scheme:e.toLowerCase(),user:t,host:i.toLowerCase(),port:r}}get scheme(){return this.normal.scheme}set scheme(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()}get user(){return this.normal.user}set user(e){this.normal.user=this.raw.user=e}get host(){return this.normal.host}set host(e){this.raw.host=e,this.normal.host=e.toLowerCase()}get aor(){return this.normal.user+"@"+this.normal.host}get port(){return this.normal.port}set port(e){this.normal.port=this.raw.port=e}setHeader(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]}getHeader(e){if(e)return this.headers[this.headerize(e)]}hasHeader(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))}deleteHeader(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){const t=this.headers[e];return delete this.headers[e],t}}clearHeaders(){this.headers={}}clone(){return new y(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))}toRaw(){return this._toString(this._raw)}toString(){return this._toString(this._normal)}get _normal(){return this.normal}get _raw(){return this.raw}_toString(e){let t=e.scheme+":";e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port);for(const e in this.parameters)this.parameters.hasOwnProperty(e)&&(t+=";"+e,null!==this.parameters[e]&&(t+="="+this.parameters[e]));const i=[];for(const e in this.headers)if(this.headers.hasOwnProperty(e))for(const t in this.headers[e])this.headers[e].hasOwnProperty(t)&&i.push(e+"="+this.headers[e][t]);return i.length>0&&(t+="?"+i.join("&")),t}escapeUser(e){let t;try{t=decodeURIComponent(e)}catch(e){throw e}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")}headerize(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},i=e.toLowerCase().replace(/_/g,"-").split("-"),r=i.length;let s="";for(let e=0;e<r;e++)0!==e&&(s+="-"),s+=i[e].charAt(0).toUpperCase()+i[e].substring(1);return t[s]&&(s=t[s]),s}}function w(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){const i=Object.keys(e.parameters),r=Object.keys(t.parameters);return!!i.filter(e=>r.includes(e)).every(i=>e.parameters[i]===t.parameters[i])&&(!!["user","ttl","method","transport"].every(i=>e.hasParam(i)&&t.hasParam(i)||!e.hasParam(i)&&!t.hasParam(i))&&!!["maddr"].every(i=>e.hasParam(i)&&t.hasParam(i)||!e.hasParam(i)&&!t.hasParam(i)))}(e,t))return!1;const i=Object.keys(e.headers),r=Object.keys(t.headers);if(0!==i.length||0!==r.length){if(i.length!==r.length)return!1;const s=i.filter(e=>r.includes(e));if(s.length!==r.length)return!1;if(!s.every(i=>e.headers[i].length&&t.headers[i].length&&e.headers[i][0]===t.headers[i][0]))return!1}return!0}function S(e,t,i){return i=i||" ",e.length>t?e:(t-=e.length,e+(i+=i.repeat(t)).slice(0,t))}class T extends Error{static buildMessage(e,t){function i(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,e=>"\\x0"+i(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+i(e))}function s(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,e=>"\\x0"+i(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+i(e))}function n(e){switch(e.type){case"literal":return'"'+r(e.text)+'"';case"class":const t=e.parts.map(e=>Array.isArray(e)?s(e[0])+"-"+s(e[1]):s(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){const t=e.map(n);let i,r;if(t.sort(),t.length>0){for(i=1,r=1;i<t.length;i++)t[i-1]!==t[i]&&(t[r]=t[i],r++);t.length=r}switch(t.length){case 1:return t[0];case 2:return t[0]+" or "+t[1];default:return t.slice(0,-1).join(", ")+", or "+t[t.length-1]}}(e)+" but "+(((o=t)?'"'+r(o)+'"':"end of input")+" found.");var o}constructor(e,t,i,r){super(),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"expected",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"found",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"location",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.message=e,this.expected=t,this.found=i,this.location=r,this.name="SyntaxError","function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(this,T.prototype):this.__proto__=T.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,T)}format(e){let t="Error: "+this.message;if(this.location){let i,r=null;for(i=0;i<e.length;i++)if(e[i].source===this.location.source){r=e[i].text.split(/\r\n|\n|\r/g);break}let s=this.location.start,n=this.location.source+":"+s.line+":"+s.column;if(r){let e=this.location.end,i=S("",s.line.toString().length," "),o=r[s.line-1],a=s.line===e.line?e.column:o.length+1;t+="\n --\x3e "+n+"\n"+i+" |\n"+s.line+" | "+o+"\n"+i+" | "+S("",s.column-1," ")+S("",a-s.column,"^")}else t+="\n at "+n}return t}}const R=function(e,t){const i={},r=(t=void 0!==t?t:{}).grammarSource,s={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};let n=119;const o=["\r\n",m("\r\n",!1),/^[0-9]/,w([["0","9"]],!1,!1),/^[a-zA-Z]/,w([["a","z"],["A","Z"]],!1,!1),/^[0-9a-fA-F]/,w([["0","9"],["a","f"],["A","F"]],!1,!1),/^[\0-\xFF]/,w([["\0","ÿ"]],!1,!1),/^["]/,w(['"'],!1,!1)," ",m(" ",!1),"\t",m("\t",!1),/^[a-zA-Z0-9]/,w([["a","z"],["A","Z"],["0","9"]],!1,!1),";",m(";",!1),"/",m("/",!1),"?",m("?",!1),":",m(":",!1),"@",m("@",!1),"&",m("&",!1),"=",m("=",!1),"+",m("+",!1),"$",m("$",!1),",",m(",",!1),"-",m("-",!1),"_",m("_",!1),".",m(".",!1),"!",m("!",!1),"~",m("~",!1),"*",m("*",!1),"'",m("'",!1),"(",m("(",!1),")",m(")",!1),"%",m("%",!1),function(){return" "},function(){return":"},/^[!-~]/,w([["!","~"]],!1,!1),/^[\x80-\uFFFF]/,w([["€","￿"]],!1,!1),/^[\x80-\xBF]/,w([["€","¿"]],!1,!1),/^[a-f]/,w([["a","f"]],!1,!1),"`",m("`",!1),"<",m("<",!1),">",m(">",!1),"\\",m("\\",!1),"[",m("[",!1),"]",m("]",!1),"{",m("{",!1),"}",m("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,w([["!","'"]],!1,!1),/^[*-[]/,w([["*","["]],!1,!1),/^[\]-~]/,w([["]","~"]],!1,!1),function(e){return e},/^[#-[]/,w([["#","["]],!1,!1),/^[\0-\t]/,w([["\0","\t"]],!1,!1),/^[\v-\f]/,w([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,w([["",""]],!1,!1),function(){(t=t||{data:{}}).data.uri=new y(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 y(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",m("sips",!0),"sip",m("sip",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(){(t=t||{data:{}}).data.user=decodeURIComponent(p().slice(0,-1))},function(){(t=t||{data:{}}).data.password=p()},function(){return(t=t||{data:{}}).data.host=p(),t.data.host},function(){return(t=t||{data:{}}).data.host_type="domain",p()},/^[a-zA-Z0-9_\-]/,w([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,w([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",p()},"::",m("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",p()},function(){return(t=t||{data:{}}).data.host_type="IPv4",p()},"25",m("25",!1),/^[0-5]/,w([["0","5"]],!1,!1),"2",m("2",!1),/^[0-4]/,w([["0","4"]],!1,!1),"1",m("1",!1),/^[1-9]/,w([["1","9"]],!1,!1),function(e){return t=t||{data:{}},e=parseInt(e.join("")),t.data.port=e,e},"transport=",m("transport=",!0),"udp",m("udp",!0),"tcp",m("tcp",!0),"sctp",m("sctp",!0),"tls",m("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",m("user=",!0),"phone",m("phone",!0),"ip",m("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",m("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",m("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",m("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",m("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,i){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),i=null===i?void 0:i[1],t.data.uri_params[e.toLowerCase()]=i},function(e,i){e=e.join("").toLowerCase(),i=i.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(i):t.data.uri_headers[e]=[i]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new y(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)},"//",m("//",!1),function(){(t=t||{data:{}}).data.scheme=p()},m("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=p()},"INVITE",m("INVITE",!1),"ACK",m("ACK",!1),"VXACH",m("VXACH",!1),"OPTIONS",m("OPTIONS",!1),"BYE",m("BYE",!1),"CANCEL",m("CANCEL",!1),"REGISTER",m("REGISTER",!1),"SUBSCRIBE",m("SUBSCRIBE",!1),"NOTIFY",m("NOTIFY",!1),"REFER",m("REFER",!1),"PUBLISH",m("PUBLISH",!1),function(){return(t=t||{data:{}}).data.method=p(),t.data.method},function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},function(){(t=t||{data:{}}).data.reason_phrase=p()},function(){(t=t||{data:{}}).data=p()},function(){var e,i;for(i=(t=t||{data:{}}).data.multi_header.length,e=0;e<i;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 b(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:c,offset:v().start.offset,parsed:e})},function(e){'"'===(e=p().trim())[0]&&(e=e.substring(1,e.length-1)),(t=t||{data:{}}).data.displayName=e},"q",m("q",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.q=e},"expires",m("expires",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.expires=e},function(e){return parseInt(e.join(""))},"0",m("0",!1),function(){return parseFloat(p())},function(e,i){(t=t||{data:{}}).data.params||(t.data.params={}),i=null===i?void 0:i[1],t.data.params[e.toLowerCase()]=i},"render",m("render",!0),"session",m("session",!0),"icon",m("icon",!0),"alert",m("alert",!0),function(){"Content_Disposition"===(t=t||{data:{}}).startRule&&(t.data.type=p().toLowerCase())},"handling",m("handling",!0),"optional",m("optional",!0),"required",m("required",!0),function(e){(t=t||{data:{}}).data=parseInt(e.join(""))},function(){(t=t||{data:{}}).data=p()},"text",m("text",!0),"image",m("image",!0),"audio",m("audio",!0),"video",m("video",!0),"application",m("application",!0),"message",m("message",!0),"multipart",m("multipart",!0),"x-",m("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 b(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"tag",m("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 b(t.data.uri,t.data.displayName,t.data.params)},"digest",m("Digest",!0),"realm",m("realm",!0),function(e){(t=t||{data:{}}).data.realm=e},"domain",m("domain",!0),"nonce",m("nonce",!0),function(e){(t=t||{data:{}}).data.nonce=e},"opaque",m("opaque",!0),function(e){(t=t||{data:{}}).data.opaque=e},"stale",m("stale",!0),"true",m("true",!0),function(){(t=t||{data:{}}).data.stale=!0},"false",m("false",!0),function(){(t=t||{data:{}}).data.stale=!1},"algorithm",m("algorithm",!0),"md5",m("MD5",!0),"md5-sess",m("MD5-sess",!0),function(e){(t=t||{data:{}}).data.algorithm=e.toUpperCase()},"qop",m("qop",!0),"auth-int",m("auth-int",!0),"auth",m("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,i;for(i=(t=t||{data:{}}).data.multi_header.length,e=0;e<i;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 b(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:c,offset:v().start.offset,parsed:e})},function(){(t=t||{data:{}}).data=new b(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",m("from-tag",!0),function(e){(t=t||{data:{}}).data.replaces_from_tag=e},"to-tag",m("to-tag",!0),function(e){(t=t||{data:{}}).data.replaces_to_tag=e},"early-only",m("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",m("active",!0),"pending",m("pending",!0),"terminated",m("terminated",!0),function(){(t=t||{data:{}}).data.state=p()},"reason",m("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",m("retry_after",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.retry_after=e)},"deactivated",m("deactivated",!0),"probation",m("probation",!0),"rejected",m("rejected",!0),"timeout",m("timeout",!0),"giveup",m("giveup",!0),"noresource",m("noresource",!0),"invariant",m("invariant",!0),function(e){"Supported"===(t=t||{data:{}}).startRule&&(t.data=e||[])},function(){var e=(t=t||{data:{}}).data.tag;t.data=new b(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"ttl",m("ttl",!0),function(e){(t=t||{data:{}}).data.ttl=e},"maddr",m("maddr",!0),function(e){(t=t||{data:{}}).data.maddr=e},"received",m("received",!0),function(e){(t=t||{data:{}}).data.received=e},"branch",m("branch",!0),function(e){(t=t||{data:{}}).data.branch=e},"rport",m("rport",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.rport=e.join(""))},function(e){(t=t||{data:{}}).data.protocol=e},m("UDP",!0),m("TCP",!0),m("TLS",!0),m("SCTP",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data.host=p()},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",m("refresher",!1),"uas",m("uas",!1),"uac",m("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",m("stuns",!0),"stun",m("stun",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(e){(t=t||{data:{}}).data.host=e},"?transport=",m("?transport=",!1),"turns",m("turns",!0),"turn",m("turn",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data=p()},"Referred-By",m("Referred-By",!1),"b",m("b",!1),"cid",m("cid",!1)],a=[I('2 ""6 7!'),I('4"""5!7#'),I('4$""5!7%'),I('4&""5!7\''),I(";'.# &;("),I('4(""5!7)'),I('4*""5!7+'),I('2,""6,7-'),I('2.""6.7/'),I('40""5!71'),I('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'),I(";).# &;,"),I('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),I('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),I('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/&#0#*;$&&&#/\'$8":Z" )("\'#&\'#'),I(';.." &"'),I("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),I('%%$;2/&#0#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),I('4\\""5!7].# &;3'),I('4^""5!7_'),I('4`""5!7a'),I(';!.) &4b""5!7c'),I('%$;).• &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&&&#/"!&,)'),I('%$;).‰ &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&&&#/"!&,)'),I('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.) &;\'.# &;('),I('%$;).ī &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&&&#/"!&,)'),I("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),I("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),I("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),I("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),I("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),I('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),I('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),I("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),I("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),I("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),I("%;//0#;&/'$8\":~\" )(\"'#&'#"),I("%;&/0#;//'$8\":~\" )(\"'#&'#"),I("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),I('4""5!7€.A &4""5!7‚.5 &4ƒ""5!7„.) &;3.# &;.'),I("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),I("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:…$!!)($'#(#'#(\"'#&'#"),I(';..G &2L""6L7M.; &4†""5!7‡./ &4ƒ""5!7„.# &;3'),I('%2j""6j7k/J#4ˆ""5!7‰.5 &4Š""5!7‹.) &4Œ""5!7/#$+")("\'#&\'#'),I("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:Ž$ )($'#(#'#(\"'#&'#"),I("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:& )(&'#(%'#($'#(#'#(\"'#&'#"),I('%3""5$7‘.) &3’""5#7“/\' 8!:”!! )'),I('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:•# )(#\'#("\'#&\'#'),I("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),I('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'),I('%$;+._ &;-.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!:–! )'),I('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),I("%;U.) &;\\.# &;X/& 8!:—! )"),I('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:˜# )(#\'#("\'#&\'#'),I('$4™""5!7š/,#0)*4™""5!7š&&&#'),I('%4$""5!7%/?#$4›""5!7œ0)*4›""5!7œ&/#$+")("\'#&\'#'),I('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:# )(#\'#("\'#&\'#'),I('%%;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!: ! )'),I('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),I("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),I("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),I('%2¢""6¢7£/2#4¤""5!7¥/#$+")("\'#&\'#.˜ &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#\'#("\'#&\'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4¬""5!7­/,#;!/#$+")("\'#&\'#.# &;!'),I('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:®!! )'),I('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),I(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),I('%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("\'#&\'#'),I('%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("\'#&\'#'),I('%3Á""5\'7Â/1#;/($8":Ã"! )("\'#&\'#'),I('%3Ä""5$7Å/1#;ð/($8":Æ"! )("\'#&\'#'),I('%3Ç""5&7È/1#;T/($8":É"! )("\'#&\'#'),I('%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":Ì" )("\'#&\'#'),I('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":Í""! )("\'#&\'#'),I('%$;j/&#0#*;j&&&#/"!&,)'),I('%$;j/&#0#*;j&&&#/"!&,)'),I(";k.) &;+.# &;-"),I('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),I('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),I('%;n/A#2>""6>7?/2$;o/)$8#:Î#"" )(#\'#("\'#&\'#'),I("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),I("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),I('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),I(";‘.# &;r"),I("%;/G#;'/>$;s/5$;'/,$;„/#$+%)(%'#($'#(#'#(\"'#&'#"),I(";M.# &;t"),I("%;/E#28\"\"6879/6$;u.# &;x/'$8#:Ï# )(#'#(\"'#&'#"),I('%;v.# &;w/J#%26""6677/,#;ƒ/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),I('%2Ð""6Ð7Ñ/:#;€/1$;w." &"/#$+#)(#\'#("\'#&\'#'),I('%24""6475/,#;{/#$+")("\'#&\'#'),I("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),I(";*.) &;+.# &;-"),I(';+. &;-.‰ &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'),I('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),I('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),I("$;~0#*;~&"),I(';+.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'),I('%%;"/‡#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:Ò! )'),I(";.# &;‚"),I('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),I('$;+.ƒ &;-.} &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&&&#'),I("$;y0#*;y&"),I('%3’""5#7Ó/q#24""6475/b$$;!/&#0#*;!&&&#/L$2J""6J7K/=$$;!/&#0#*;!&&&#/\'$8%:Ô% )(%\'#($\'#(#\'#("\'#&\'#'),I('2Õ""6Õ7Ö'),I('2×""6×7Ø'),I('2Ù""6Ù7Ú'),I('2Û""6Û7Ü'),I('2Ý""6Ý7Þ'),I('2ß""6ß7à'),I('2á""6á7â'),I('2ã""6ã7ä'),I('2å""6å7æ'),I('2ç""6ç7è'),I('2é""6é7ê'),I("%;….Y &;†.S &;ˆ.M &;‰.G &;Š.A &;‹.; &;Œ.5 &;./ &;.) &;Ž.# &;6/& 8!:ë! )"),I("%;„/G#;'/>$;’/5$;'/,$;”/#$+%)(%'#($'#(#'#(\"'#&'#"),I("%;“/' 8!:ì!! )"),I("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),I("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),I("%;¶/Y#$%;A/,#;¶/#$+\")(\"'#&'#06*%;A/,#;¶/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":î" )("\'#&\'#'),I("%;:.c &%;˜/Y#$%;A/,#;˜/#$+\")(\"'#&'#06*%;A/,#;˜/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:ï! )"),I("%;L.# &;™/]#$%;B/,#;›/#$+\")(\"'#&'#06*%;B/,#;›/#$+\")(\"'#&'#&/'$8\":ð\" )(\"'#&'#"),I("%;š.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),I("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:ñ!! )"),I(";œ.) &;.# &; "),I("%3ò\"\"5!7ó/:#;</1$;Ÿ/($8#:ô#! )(#'#(\"'#&'#"),I("%3õ\"\"5'7ö/:#;</1$;ž/($8#:÷#! )(#'#(\"'#&'#"),I("%$;!/&#0#*;!&&&#/' 8!:ø!! )"),I('%2ù""6ù7ú/o#%2J""6J7K/M#;!." &"/?$;!." &"/1$;!." &"/#$+$)($\'#(#\'#("\'#&\'#." &"/\'$8":û" )("\'#&\'#'),I('%;6/J#%;</,#;¡/#$+")("\'#&\'#." &"/)$8":ü""! )("\'#&\'#'),I(";6.) &;T.# &;H"),I("%;£/Y#$%;B/,#;¤/#$+\")(\"'#&'#06*%;B/,#;¤/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I('%3ý""5&7þ.G &3ÿ""5\'7Ā.; &3ā""5$7Ă./ &3ă""5%7Ą.# &;6/& 8!:ą! )'),I(";¥.# &; "),I('%3Ć""5(7ć/M#;</D$3Ĉ""5(7ĉ./ &3Ċ""5(7ċ.# &;6/#$+#)(#\'#("\'#&\'#'),I("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I("%$;!/&#0#*;!&&&#/' 8!:Č!! )"),I("%;©/& 8!:č! )"),I("%;ª/k#;;/b$;¯/Y$$%;B/,#;°/#$+\")(\"'#&'#06*%;B/,#;°/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),I(";«.# &;¬"),I('3Ď""5$7ď.S &3Đ""5%7đ.G &3Ē""5%7ē.; &3Ĕ""5%7ĕ./ &3Ė""5+7ė.# &;­'),I('3Ę""5\'7ę./ &3Ě""5)7ě.# &;­'),I(";6.# &;®"),I('%3Ĝ""5"7ĝ/,#;6/#$+")("\'#&\'#'),I(";­.# &;6"),I("%;6/5#;</,$;±/#$+#)(#'#(\"'#&'#"),I(";6.# &;H"),I("%;³/5#;./,$;/#$+#)(#'#(\"'#&'#"),I("%$;!/&#0#*;!&&&#/' 8!:Ğ!! )"),I("%;ž/' 8!:ğ!! )"),I('%;¶/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ġ"!!)("\'#&\'#'),I('%%;7/e#$%2J""6J7K/,#;7/#$+")("\'#&\'#0<*%2J""6J7K/,#;7/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),I("%;L.# &;™/]#$%;B/,#;¸/#$+\")(\"'#&'#06*%;B/,#;¸/#$+\")(\"'#&'#&/'$8\":ġ\" )(\"'#&'#"),I(";¹.# &; "),I("%3Ģ\"\"5#7ģ/:#;</1$;6/($8#:Ĥ#! )(#'#(\"'#&'#"),I("%$;!/&#0#*;!&&&#/' 8!:ĥ!! )"),I("%;ž/' 8!:Ħ!! )"),I("%$;š0#*;š&/x#;@/o$;M/f$;?/]$$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8%:ħ% )(%'#($'#(#'#(\"'#&'#"),I(";¾"),I("%3Ĩ\"\"5&7ĩ/k#;./b$;Á/Y$$%;A/,#;Á/#$+\")(\"'#&'#06*%;A/,#;Á/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#.# &;¿"),I("%;6/k#;./b$;À/Y$$%;A/,#;À/#$+\")(\"'#&'#06*%;A/,#;À/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),I("%;6/;#;</2$;6.# &;H/#$+#)(#'#(\"'#&'#"),I(";Â.G &;Ä.A &;Æ.; &;È.5 &;É./ &;Ê.) &;Ë.# &;À"),I("%3Ī\"\"5%7ī/5#;</,$;Ã/#$+#)(#'#(\"'#&'#"),I("%;I/' 8!:Ĭ!! )"),I("%3ĭ\"\"5&7Į/—#;</Ž$;D/…$;Å/|$$%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#0C*%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#&/,$;E/#$+&)(&'#(%'#($'#(#'#(\"'#&'#"),I(";t.# &;w"),I("%3į\"\"5%7İ/5#;</,$;Ç/#$+#)(#'#(\"'#&'#"),I("%;I/' 8!:ı!! )"),I("%3IJ\"\"5&7ij/:#;</1$;I/($8#:Ĵ#! )(#'#(\"'#&'#"),I('%3ĵ""5%7Ķ/]#;</T$%3ķ""5$7ĸ/& 8!:Ĺ! ).4 &%3ĺ""5%7Ļ/& 8!:ļ! )/#$+#)(#\'#("\'#&\'#'),I('%3Ľ""5)7ľ/R#;</I$3Ŀ""5#7ŀ./ &3Ł""5(7ł.# &;6/($8#:Ń#! )(#\'#("\'#&\'#'),I('%3ń""5#7Ņ/“#;</Š$;D/$%;Ì/e#$%2D""6D7E/,#;Ì/#$+")("\'#&\'#0<*%2D""6D7E/,#;Ì/#$+")("\'#&\'#&/#$+")("\'#&\'#/,$;E/#$+%)(%\'#($\'#(#\'#("\'#&\'#'),I('%3ņ""5(7Ň./ &3ň""5$7ʼn.# &;6/\' 8!:Ŋ!! )'),I("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I("%;Ï/G#;./>$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),I("%$;!/&#0#*;!&&&#/' 8!:ŋ!! )"),I("%;Ñ/]#$%;A/,#;Ñ/#$+\")(\"'#&'#06*%;A/,#;Ñ/#$+\")(\"'#&'#&/'$8\":Ō\" )(\"'#&'#"),I("%;™/]#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8\":ō\" )(\"'#&'#"),I('%;L.O &;™.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/\'$8":Ŏ" )("\'#&\'#'),I("%;Ô/]#$%;B/,#;Õ/#$+\")(\"'#&'#06*%;B/,#;Õ/#$+\")(\"'#&'#&/'$8\":ŏ\" )(\"'#&'#"),I("%;–/& 8!:Ő! )"),I('%3ő""5(7Œ/:#;</1$;6/($8#:œ#! )(#\'#("\'#&\'#.g &%3Ŕ""5&7ŕ/:#;</1$;6/($8#:Ŗ#! )(#\'#("\'#&\'#.: &%3ŗ""5*7Ř/& 8!:ř! ).# &; '),I('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:Ŝ!! )'),I("%;Ø/Y#$%;A/,#;Ø/#$+\")(\"'#&'#06*%;A/,#;Ø/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I("%;™/Y#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I("%$;!/&#0#*;!&&&#/' 8!:ŝ!! )"),I("%;Û/Y#$%;B/,#;Ü/#$+\")(\"'#&'#06*%;B/,#;Ü/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I('%3Ş""5&7ş.; &3Š""5\'7š./ &3Ţ""5*7ţ.# &;6/& 8!:Ť! )'),I("%3ť\"\"5&7Ŧ/:#;</1$;Ý/($8#:ŧ#! )(#'#(\"'#&'#.} &%3õ\"\"5'7ö/:#;</1$;ž/($8#:Ũ#! )(#'#(\"'#&'#.P &%3ũ\"\"5+7Ū/:#;</1$;ž/($8#:ū#! )(#'#(\"'#&'#.# &; "),I('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'),I(';1." &"'),I('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:ź!! )'),I("%;L.# &;™/]#$%;B/,#;á/#$+\")(\"'#&'#06*%;B/,#;á/#$+\")(\"'#&'#&/'$8\":Ż\" )(\"'#&'#"),I(";¹.# &; "),I("%;ã/Y#$%;A/,#;ã/#$+\")(\"'#&'#06*%;A/,#;ã/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I("%;ê/k#;./b$;í/Y$$%;B/,#;ä/#$+\")(\"'#&'#06*%;B/,#;ä/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),I(";å.; &;æ.5 &;ç./ &;è.) &;é.# &; "),I("%3ż\"\"5#7Ž/:#;</1$;ð/($8#:ž#! )(#'#(\"'#&'#"),I("%3ſ\"\"5%7ƀ/:#;</1$;T/($8#:Ɓ#! )(#'#(\"'#&'#"),I("%3Ƃ\"\"5(7ƃ/F#;</=$;\\.) &;Y.# &;X/($8#:Ƅ#! )(#'#(\"'#&'#"),I("%3ƅ\"\"5&7Ɔ/:#;</1$;6/($8#:Ƈ#! )(#'#(\"'#&'#"),I("%3ƈ\"\"5%7Ɖ/A#;</8$$;!0#*;!&/($8#:Ɗ#! )(#'#(\"'#&'#"),I("%;ë/G#;;/>$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#(\"'#&'#"),I('%3’""5#7Ó.# &;6/\' 8!:Ƌ!! )'),I('%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/\' 8!:Ɛ!! )'),I('%;î/D#%;C/,#;ï/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),I("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),I('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:ƒ!! )'),I('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:Ɠ!! )'),I(";¾"),I('%;ž/^#$%;B/,#;ó/#$+")("\'#&\'#06*%;B/,#;ó/#$+")("\'#&\'#&/($8":Ɣ"!!)("\'#&\'#'),I(";ô.# &; "),I('%2ƕ""6ƕ7Ɩ/L#;</C$2Ɨ""6Ɨ7Ƙ.) &2ƙ""6ƙ7ƚ/($8#:ƛ#! )(#\'#("\'#&\'#'),I('%;ž/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ɯ"!!)("\'#&\'#'),I("%;6/5#;0/,$;÷/#$+#)(#'#(\"'#&'#"),I("$;2.) &;4.# &;.0/*;2.) &;4.# &;.&"),I("$;%0#*;%&"),I("%;ú/;#28\"\"6879/,$;û/#$+#)(#'#(\"'#&'#"),I('%3Ɲ""5%7ƞ.) &3Ɵ""5$7Ơ/\' 8!:ơ!! )'),I('%;ü/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),I("%;\\.) &;X.# &;‚/' 8!:Ƣ!! )"),I(';".S &;!.M &2F""6F7G.A &2J""6J7K.5 &2H""6H7I.) &2N""6N7O'),I('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?'),I('%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),I('%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/\' 8!:ơ!! )'),I('%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/\' 8!:Ʃ!! )'),I("%;Ą/‡#2F\"\"6F7G/x$;ă/o$2F\"\"6F7G/`$;ă/W$2F\"\"6F7G/H$;ă/?$2F\"\"6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),I("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),I("%;ă/,#;ă/#$+\")(\"'#&'#"),I("%;ă/5#;ă/,$;ă/#$+#)(#'#(\"'#&'#"),I("%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),I('%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("\'#&\'#0<*%;B/2#;ĉ.# &; /#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),I(";™.# &;L"),I("%2Ư\"\"6Ư7ư/5#;</,$;Ċ/#$+#)(#'#(\"'#&'#"),I("%;D/S#;,/J$2:\"\"6:7;/;$;,.# &;T/,$;E/#$+%)(%'#($'#(#'#(\"'#&'#")];let c=0,l=0;const h=[{line:1,column:1}];let d,u=0,g=[],f=0;if(void 0!==t.startRule){if(!(t.startRule in s))throw new Error("Can't start parsing from rule \""+t.startRule+'".');n=s[t.startRule]}function p(){return e.substring(l,c)}function v(){return R(l,c)}function m(e,t){return{type:"literal",text:e,ignoreCase:t}}function w(e,t,i){return{type:"class",parts:e,inverted:t,ignoreCase:i}}function S(t){let i,r=h[t];if(r)return r;for(i=t-1;!h[i];)i--;for(r=h[i],r={line:r.line,column:r.column};i<t;)10===e.charCodeAt(i)?(r.line++,r.column=1):r.column++,i++;return h[t]=r,r}function R(e,t){const i=S(e),s=S(t);return{source:r,start:{offset:e,line:i.line,column:i.column},end:{offset:t,line:s.line,column:s.column}}}function E(e){c<u||(c>u&&(u=c,g=[]),g.push(e))}function I(e){return e.split("").map(e=>e.charCodeAt(0)-32)}if(t.data={},d=function t(r){const s=a[r];let n=0;const h=[];let d=s.length;const u=[],g=[];let p;for(;;){for(;n<d;)switch(s[n]){case 0:g.push(o[s[n+1]]),n+=2;break;case 1:g.push(void 0),n++;break;case 2:g.push(null),n++;break;case 3:g.push(i),n++;break;case 4:g.push([]),n++;break;case 5:g.push(c),n++;break;case 6:g.pop(),n++;break;case 7:c=g.pop(),n++;break;case 8:g.length-=s[n+1],n+=2;break;case 9:g.splice(-2,1),n++;break;case 10:g[g.length-2].push(g.pop()),n++;break;case 11:g.push(g.splice(g.length-s[n+1],s[n+1])),n+=2;break;case 12:g.push(e.substring(g.pop(),c)),n++;break;case 13:u.push(d),h.push(n+3+s[n+1]+s[n+2]),g[g.length-1]?(d=n+3+s[n+1],n+=3):(d=n+3+s[n+1]+s[n+2],n+=3+s[n+1]);break;case 14:u.push(d),h.push(n+3+s[n+1]+s[n+2]),g[g.length-1]===i?(d=n+3+s[n+1],n+=3):(d=n+3+s[n+1]+s[n+2],n+=3+s[n+1]);break;case 15:u.push(d),h.push(n+3+s[n+1]+s[n+2]),g[g.length-1]!==i?(d=n+3+s[n+1],n+=3):(d=n+3+s[n+1]+s[n+2],n+=3+s[n+1]);break;case 16:g[g.length-1]!==i?(u.push(d),h.push(n),d=n+2+s[n+1],n+=2):n+=2+s[n+1];break;case 17:u.push(d),h.push(n+3+s[n+1]+s[n+2]),e.length>c?(d=n+3+s[n+1],n+=3):(d=n+3+s[n+1]+s[n+2],n+=3+s[n+1]);break;case 18:u.push(d),h.push(n+4+s[n+2]+s[n+3]),e.substr(c,o[s[n+1]].length)===o[s[n+1]]?(d=n+4+s[n+2],n+=4):(d=n+4+s[n+2]+s[n+3],n+=4+s[n+2]);break;case 19:u.push(d),h.push(n+4+s[n+2]+s[n+3]),e.substr(c,o[s[n+1]].length).toLowerCase()===o[s[n+1]]?(d=n+4+s[n+2],n+=4):(d=n+4+s[n+2]+s[n+3],n+=4+s[n+2]);break;case 20:u.push(d),h.push(n+4+s[n+2]+s[n+3]),o[s[n+1]].test(e.charAt(c))?(d=n+4+s[n+2],n+=4):(d=n+4+s[n+2]+s[n+3],n+=4+s[n+2]);break;case 21:g.push(e.substr(c,s[n+1])),c+=s[n+1],n+=2;break;case 22:g.push(o[s[n+1]]),c+=o[s[n+1]].length,n+=2;break;case 23:g.push(i),0===f&&E(o[s[n+1]]),n+=2;break;case 24:l=g[g.length-1-s[n+1]],n+=2;break;case 25:l=c,n++;break;case 26:p=s.slice(n+4,n+4+s[n+3]).map(function(e){return g[g.length-1-e]}),g.splice(g.length-s[n+2],s[n+2],o[s[n+1]].apply(null,p)),n+=4+s[n+3];break;case 27:g.push(t(s[n+1])),n+=2;break;case 28:f++,n++;break;case 29:f--,n++;break;default:throw new Error("Invalid opcode: "+s[n]+".")}if(!(u.length>0))break;d=u.pop(),n=h.pop()}return g[0]}(n),d!==i&&c===e.length)return d;throw d!==i&&c<e.length&&E({type:"end"}),C=g,P=u<e.length?e.charAt(u):null,A=u<e.length?R(u,u+1):R(u,u),new T(T.buildMessage(C,P),C,P,A);var C,P,A};var E;!function(e){e.parse=function(e,t){const i={startRule:t};try{R(e,i)}catch(e){i.data=-1}return i.data},e.nameAddrHeaderParse=function(t){const i=e.parse(t,"Name_Addr_Header");return-1!==i?i:void 0},e.URIParse=function(t){const i=e.parse(t,"SIP_URI");return-1!==i?i:void 0}}(E||(E={}));const I={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 C(e,t=32){let i="";for(let r=0;r<e;r++){i+=Math.floor(Math.random()*t).toString(t)}return i}function P(e){return I[e]||""}function A(){return C(10)}function O(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},i=e.toLowerCase().replace(/_/g,"-").split("-"),r=i.length;let s="";for(let e=0;e<r;e++)0!==e&&(s+="-"),s+=i[e].charAt(0).toUpperCase()+i[e].substring(1);return t[s]&&(s=t[s]),s}function k(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length}class D{constructor(){Object.defineProperty(this,"viaBranch",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"method",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"toTag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"to",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fromTag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"from",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cseq",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"via",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"referTo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}addHeader(e,t){const i={raw:t};e=O(e),this.headers[e]?this.headers[e].push(i):this.headers[e]=[i]}getHeader(e){const t=this.headers[O(e)];if(t)return t[0]?t[0].raw:void 0}getHeaders(e){const t=this.headers[O(e)],i=[];if(!t)return[];for(const e of t)i.push(e.raw);return i}hasHeader(e){return!!this.headers[O(e)]}parseHeader(e,t=0){if(e=O(e),!this.headers[e])return;if(t>=this.headers[e].length)return;const i=this.headers[e][t],r=i.raw;if(i.parsed)return i.parsed;const s=E.parse(r,e.replace(/-/g,"_"));return-1===s?void this.headers[e].splice(t,1):(i.parsed=s,s)}s(e,t=0){return this.parseHeader(e,t)}setHeader(e,t){this.headers[O(e)]=[{raw:t}]}toString(){return this.data}}class $ extends D{constructor(){super(),Object.defineProperty(this,"ruri",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}}class j extends D{constructor(){super(),Object.defineProperty(this,"statusCode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reasonPhrase",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}}class _{constructor(e,t,i,r,s,n,o){Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"method",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ruri",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"from",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fromTag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fromURI",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"to",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"toTag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"toURI",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"branch",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cseq",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extraHeaders",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.options=_.getDefaultOptions(),s&&(this.options=Object.assign(Object.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())),n&&n.length&&(this.extraHeaders=n.slice()),o&&(this.body={body:o.content,contentType:o.contentType}),this.method=e,this.ruri=t.clone(),this.fromURI=i.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:A(),this.from=_.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=r.clone(),this.toTag=this.options.toTag,this.to=_.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+C(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")}static getDefaultOptions(){return{callId:"",callIdPrefix:"",cseq:1,toDisplayName:"",toTag:"",fromDisplayName:"",fromTag:"",forceRport:!1,hackViaTcp:!1,optionTags:["outbound"],routeSet:[],userAgentString:"sip.js",viaHost:""}}static makeNameAddrHeader(e,t,i){const r={};return i&&(r.tag=i),new b(e,t,r)}getHeader(e){const t=this.headers[O(e)];if(t){if(t[0])return t[0]}else{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return e.substring(e.indexOf(":")+1).trim()}}getHeaders(e){const t=[],i=this.headers[O(e)];if(i)for(const e of i)t.push(e);else{const i=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)i.test(e)&&t.push(e.substring(e.indexOf(":")+1).trim())}return t}hasHeader(e){if(this.headers[O(e)])return!0;{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return!0}return!1}setHeader(e,t){this.headers[O(e)]=t instanceof Array?t:[t]}setViaHeader(e,t){this.options.hackViaTcp&&(t="TCP");let i="SIP/2.0/"+t;i+=" "+this.options.viaHost+";branch="+e,this.options.forceRport&&(i+=";rport"),this.setHeader("via",i),this.branch=e}toString(){let e="";e+=this.method+" "+this.ruri.toRaw()+" SIP/2.0\r\n";for(const t in this.headers)if(this.headers[t])for(const i of this.headers[t])e+=t+": "+i+"\r\n";for(const t of this.extraHeaders)e+=t.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: "+k(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: "+k(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}}function H(e){return"application/sdp"===e?"session":"render"}function M(e){const t="string"==typeof e?e:e.body,i="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:H(i),contentType:i,content:t}}function x(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function q(e){let t,i,r;if(e instanceof $&&e.body){const s=e.parseHeader("Content-Disposition");t=s?s.type:void 0,i=e.parseHeader("Content-Type"),r=e.body}if(e instanceof j&&e.body){const s=e.parseHeader("Content-Disposition");t=s?s.type:void 0,i=e.parseHeader("Content-Type"),r=e.body}if(e instanceof _&&e.body)if(t=e.getHeader("Content-Disposition"),i=e.getHeader("Content-Type"),"string"==typeof e.body){if(!i)throw new Error("Header content type header does not equal body content type.");r=e.body}else{if(i&&i!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");i=e.body.contentType,r=e.body.body}if(x(e)&&(t=e.contentDisposition,i=e.contentType,r=e.content),r){if(i&&!t&&(t=H(i)),!t)throw new Error("Content disposition undefined.");if(!i)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:i,content:r}}}var N,F;!function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(N||(N={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(F||(F={}));const U=500,L=5e3,B={T1:U,T2:4e3,T4:L,TIMER_B:32e3,TIMER_D:0,TIMER_F:32e3,TIMER_H:32e3,TIMER_I:0,TIMER_J:0,TIMER_K:0,TIMER_L:32e3,TIMER_M:32e3,TIMER_N:32e3,PROVISIONAL_RESPONSE_INTERVAL:6e4};class W extends o{constructor(e){super(e||"Transaction state error.")}}var G;!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"}(G||(G={}));const V=[G.ACK,G.BYE,G.CANCEL,G.INFO,G.INVITE,G.MESSAGE,G.NOTIFY,G.OPTIONS,G.PRACK,G.REFER,G.REGISTER,G.SUBSCRIBE];class K{constructor(e){Object.defineProperty(this,"incomingMessageRequest",{enumerable:!0,configurable:!0,writable:!0,value:e})}get request(){return this.incomingMessageRequest.message}accept(e){return this.incomingMessageRequest.accept(e),Promise.resolve()}reject(e){return this.incomingMessageRequest.reject(e),Promise.resolve()}}class z{constructor(e){Object.defineProperty(this,"incomingNotifyRequest",{enumerable:!0,configurable:!0,writable:!0,value:e})}get request(){return this.incomingNotifyRequest.message}accept(e){return this.incomingNotifyRequest.accept(e),Promise.resolve()}reject(e){return this.incomingNotifyRequest.reject(e),Promise.resolve()}}class Y{constructor(e,t){Object.defineProperty(this,"incomingReferRequest",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"session",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"inviter",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof b))throw new Error("Failed to parse Refer-To header.");return e}get referredBy(){return this.incomingReferRequest.message.getHeader("referred-by")}get replaces(){const e=this.referTo.uri.getHeader("replaces");return e instanceof Array?e[0]:e}get request(){return this.incomingReferRequest.message}accept(e={statusCode:202}){return this.incomingReferRequest.accept(e),Promise.resolve()}reject(e){return this.incomingReferRequest.reject(e),Promise.resolve()}makeInviter(e){if(this.inviter)return this.inviter;const t=this.referTo.uri.clone();t.clearHeaders();const i=((e=e||{}).extraHeaders||[]).slice(),r=this.replaces;r&&i.push("Replaces: "+decodeURIComponent(r));const s=this.referredBy;return s&&i.push("Referred-By: "+s),e.extraHeaders=i,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter}}function J(){const e=new Date,t=e.getFullYear(),i=e.getMonth()+1,r=e.getDate(),s=e.getHours(),n=e.getMinutes(),o=e.getSeconds();return t+"-"+Z(i)+"-"+Z(r)+" "+Z(s)+":"+Z(n)+":"+Z(o)}function Z(e){return e<10?"0"+e:e}e.SessionState=void 0,function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(e.SessionState||(e.SessionState={}));class X{constructor(t,i={}){Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_contact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_referral",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_replacee",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_assertedIdentity",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_dialog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_referralInviterOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_renderbody",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_rendertype",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onNotify",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingReinvite",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"pendingReinviteAck",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_sessionDescriptionHandler",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sessionDescriptionHandlerModifiers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sessionDescriptionHandlerOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sessionDescriptionHandlerModifiersReInvite",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sessionDescriptionHandlerOptionsReInvite",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_state",{enumerable:!0,configurable:!0,writable:!0,value:e.SessionState.Initial}),Object.defineProperty(this,"_stateEventEmitter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_userAgent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.delegate=i.delegate,this._stateEventEmitter=new p,this._userAgent=t}dispose(){switch(this.logger.log(`Session ${this.id} in state ${this._state} is being disposed`),delete this.userAgent._sessions[this.id],this._sessionDescriptionHandler&&this._sessionDescriptionHandler.close(),this.state){case e.SessionState.Initial:case e.SessionState.Establishing:break;case e.SessionState.Established:return new Promise(e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})});case e.SessionState.Terminating:case e.SessionState.Terminated:break;default:throw new Error("Unknown state.")}return Promise.resolve()}get assertedIdentity(){return this._assertedIdentity}get dialog(){return this._dialog}get id(){return this._id}get replacee(){return this._replacee}get sessionDescriptionHandler(){return this._sessionDescriptionHandler}get sessionDescriptionHandlerFactory(){return this.userAgent.configuration.sessionDescriptionHandlerFactory}get sessionDescriptionHandlerModifiers(){return this._sessionDescriptionHandlerModifiers||[]}set sessionDescriptionHandlerModifiers(e){this._sessionDescriptionHandlerModifiers=e.slice()}get sessionDescriptionHandlerOptions(){return this._sessionDescriptionHandlerOptions||{}}set sessionDescriptionHandlerOptions(e){this._sessionDescriptionHandlerOptions=Object.assign({},e)}get sessionDescriptionHandlerModifiersReInvite(){return this._sessionDescriptionHandlerModifiersReInvite||[]}set sessionDescriptionHandlerModifiersReInvite(e){this._sessionDescriptionHandlerModifiersReInvite=e.slice()}get sessionDescriptionHandlerOptionsReInvite(){return this._sessionDescriptionHandlerOptionsReInvite||{}}set sessionDescriptionHandlerOptionsReInvite(e){this._sessionDescriptionHandlerOptionsReInvite=Object.assign({},e)}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get userAgent(){return this._userAgent}bye(t={}){let i="Session.bye() may only be called if established session.";switch(this.state){case e.SessionState.Initial:"function"==typeof this.cancel?(i+=" However Inviter.invite() has not yet been called.",i+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(i+=" However Invitation.accept() has not yet been called.",i+=" Perhaps you should have called Invitation.reject()?");break;case e.SessionState.Establishing:"function"==typeof this.cancel?(i+=" However a dialog does not yet exist.",i+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(i+=" However Invitation.accept() has not yet been called (or not yet resolved).",i+=" Perhaps you should have called Invitation.reject()?");break;case e.SessionState.Established:{const e=t.requestDelegate,i=this.copyRequestOptions(t.requestOptions);return this._bye(e,i)}case e.SessionState.Terminating:i+=" However this session is already terminating.","function"==typeof this.cancel?i+=" Perhaps you have already called Inviter.cancel()?":"function"==typeof this.reject&&(i+=" Perhaps you have already called Session.bye()?");break;case e.SessionState.Terminated:i+=" However this session is already terminated.";break;default:throw new Error("Unknown state")}return this.logger.error(i),Promise.reject(new Error(`Invalid session state ${this.state}`))}info(t={}){if(this.state!==e.SessionState.Established){const e="Session.info() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const i=t.requestDelegate,r=this.copyRequestOptions(t.requestOptions);return this._info(i,r)}invite(t={}){if(this.logger.log("Session.invite"),this.state!==e.SessionState.Established)return Promise.reject(new Error(`Invalid session state ${this.state}`));if(this.pendingReinvite)return Promise.reject(new c("Reinvite in progress. Please wait until complete, then try again."));this.pendingReinvite=!0,t.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiersReInvite=t.sessionDescriptionHandlerModifiers),t.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptionsReInvite=t.sessionDescriptionHandlerOptions);const i={onAccept:i=>{const r=q(i.message);if(!r)return this.logger.error("Received 2xx response to re-INVITE without a session description"),this.ackAndBye(i,400,"Missing session description"),this.stateTransition(e.SessionState.Terminated),void(this.pendingReinvite=!1);if(t.withoutSdp){const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setOfferAndGetAnswer(r,s).then(e=>{i.ack({body:e})}).catch(t=>{this.logger.error("Failed to handle offer in 2xx response to re-INVITE"),this.logger.error(t.message),this.state===e.SessionState.Terminated?i.ack():(this.ackAndBye(i,488,"Bad Media Description"),this.stateTransition(e.SessionState.Terminated))}).then(()=>{this.pendingReinvite=!1,t.requestDelegate&&t.requestDelegate.onAccept&&t.requestDelegate.onAccept(i)})}else{const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setAnswer(r,s).then(()=>{i.ack()}).catch(t=>{this.logger.error("Failed to handle answer in 2xx response to re-INVITE"),this.logger.error(t.message),this.state!==e.SessionState.Terminated?(this.ackAndBye(i,488,"Bad Media Description"),this.stateTransition(e.SessionState.Terminated)):i.ack()}).then(()=>{this.pendingReinvite=!1,t.requestDelegate&&t.requestDelegate.onAccept&&t.requestDelegate.onAccept(i)})}},onProgress:e=>{},onRedirect:e=>{},onReject:i=>{this.logger.warn("Received a non-2xx response to re-INVITE"),this.pendingReinvite=!1,t.withoutSdp?t.requestDelegate&&t.requestDelegate.onReject&&t.requestDelegate.onReject(i):this.rollbackOffer().catch(t=>{if(this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),this.logger.error(t.message),this.state!==e.SessionState.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const t=[];t.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:t}),this.stateTransition(e.SessionState.Terminated)}}).then(()=>{t.requestDelegate&&t.requestDelegate.onReject&&t.requestDelegate.onReject(i)})},onTrying:e=>{}},r=t.requestOptions||{};if(r.extraHeaders=(r.extraHeaders||[]).slice(),r.extraHeaders.push("Allow: "+V.toString()),r.extraHeaders.push("Contact: "+this._contact),t.withoutSdp){if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return Promise.resolve(this.dialog.invite(i,r))}const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(s).then(e=>{if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return r.body=e,this.dialog.invite(i,r)}).catch(e=>{throw this.logger.error(e.message),this.logger.error("Failed to send re-INVITE"),this.pendingReinvite=!1,e})}message(t={}){if(this.state!==e.SessionState.Established){const e="Session.message() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const i=t.requestDelegate,r=this.copyRequestOptions(t.requestOptions);return this._message(i,r)}refer(t,i={}){if(this.state!==e.SessionState.Established){const e="Session.refer() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}if(t instanceof X&&!t.dialog){const e="Session.refer() may only be called with session which is established. You are perhaps attempting to attended transfer to a target for which there is not dialog yet established. Perhaps you are attempting a 'semi-attended' tansfer? Regardless, this is not supported. The recommended approached is to check to see if the target Session is in the Established state before calling refer(); if the state is not Established you may proceed by falling back using a URI as the target (blind transfer).";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const r=i.requestDelegate,s=this.copyRequestOptions(i.requestOptions);return s.extraHeaders=s.extraHeaders?s.extraHeaders.concat(this.referExtraHeaders(this.referToString(t))):this.referExtraHeaders(this.referToString(t)),this._refer(i.onNotify,r,s)}_bye(t,i){if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));const r=this.dialog;switch(r.sessionState){case N.Initial:case N.Early:throw new Error(`Invalid dialog state ${r.sessionState}`);case N.AckWait:return this.stateTransition(e.SessionState.Terminating),new Promise(s=>{r.delegate={onAck:()=>{const n=r.bye(t,i);return this.stateTransition(e.SessionState.Terminated),s(n),Promise.resolve()},onAckTimeout:()=>{const n=r.bye(t,i);this.stateTransition(e.SessionState.Terminated),s(n)}}});case N.Confirmed:{const s=r.bye(t,i);return this.stateTransition(e.SessionState.Terminated),Promise.resolve(s)}case N.Terminated:throw new Error(`Invalid dialog state ${r.sessionState}`);default:throw new Error("Unrecognized state.")}}_info(e,t){return this.dialog?Promise.resolve(this.dialog.info(e,t)):Promise.reject(new Error("Session dialog undefined."))}_message(e,t){return this.dialog?Promise.resolve(this.dialog.message(e,t)):Promise.reject(new Error("Session dialog undefined."))}_refer(e,t,i){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,i))):Promise.reject(new Error("Session dialog undefined."))}ackAndBye(e,t,i){e.ack();const r=[];t&&r.push("Reason: "+this.getReasonHeaderValue(t,i)),e.session.bye(void 0,{extraHeaders:r})}onAckRequest(t){if(this.logger.log("Session.onAckRequest"),this.state!==e.SessionState.Established&&this.state!==e.SessionState.Terminating)return this.logger.error(`ACK received while in state ${this.state}, dropping request`),Promise.resolve();const i=this.dialog;if(!i)throw new Error("Dialog undefined.");const r={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};if(this.delegate&&this.delegate.onAck){const e=new u(t);this.delegate.onAck(e)}switch(this.pendingReinviteAck=!1,i.signalingState){case F.Initial:{this.logger.error(`Invalid signaling state ${i.signalingState}.`);const t=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return i.bye(void 0,{extraHeaders:t}),this.stateTransition(e.SessionState.Terminated),Promise.resolve()}case F.Stable:{const s=q(t.message);return s?"render"===s.contentDisposition?(this._renderbody=s.content,this._rendertype=s.contentType,Promise.resolve()):"session"!==s.contentDisposition?Promise.resolve():this.setAnswer(s,r).catch(t=>{this.logger.error(t.message);const r=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];i.bye(void 0,{extraHeaders:r}),this.stateTransition(e.SessionState.Terminated)}):Promise.resolve()}case F.HaveLocalOffer:{this.logger.error(`Invalid signaling state ${i.signalingState}.`);const t=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return i.bye(void 0,{extraHeaders:t}),this.stateTransition(e.SessionState.Terminated),Promise.resolve()}case F.HaveRemoteOffer:{this.logger.error(`Invalid signaling state ${i.signalingState}.`);const t=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return i.bye(void 0,{extraHeaders:t}),this.stateTransition(e.SessionState.Terminated),Promise.resolve()}case F.Closed:default:throw new Error(`Invalid signaling state ${i.signalingState}.`)}}onByeRequest(t){if(this.logger.log("Session.onByeRequest"),this.state===e.SessionState.Established){if(this.delegate&&this.delegate.onBye){const e=new g(t);this.delegate.onBye(e)}else t.accept();this.stateTransition(e.SessionState.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(t){if(this.logger.log("Session.onInfoRequest"),this.state===e.SessionState.Established)if(this.delegate&&this.delegate.onInfo){const e=new v(t);this.delegate.onInfo(e)}else t.accept();else this.logger.error(`INFO received while in state ${this.state}, dropping request`)}onInviteRequest(t){if(this.logger.log("Session.onInviteRequest"),this.state!==e.SessionState.Established)return void this.logger.error(`INVITE received while in state ${this.state}, dropping request`);this.pendingReinviteAck=!0;const i=["Contact: "+this._contact];if(t.message.hasHeader("P-Asserted-Identity")){const e=t.message.getHeader("P-Asserted-Identity");if(!e)throw new Error("Header undefined.");this._assertedIdentity=E.nameAddrHeaderParse(e)}const r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(r,t).then(e=>{const r=t.accept({statusCode:200,extraHeaders:i,body:e});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(t.message,r.message,200)}).catch(i=>{if(this.logger.error(i.message),this.logger.error("Failed to handle to re-INVITE request"),!this.dialog)throw new Error("Dialog undefined.");if(this.logger.error(this.dialog.signalingState),this.dialog.signalingState===F.Stable){const e=t.reject({statusCode:488});return void(this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(t.message,e.message,488))}this.rollbackOffer().then(()=>{const e=t.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(t.message,e.message,488)}).catch(i=>{this.logger.error(i.message),this.logger.error("Failed to rollback offer on re-INVITE request");const r=t.reject({statusCode:488});if(this.state!==e.SessionState.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const t=[];t.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:t}),this.stateTransition(e.SessionState.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(t.message,r.message,488)})})}onMessageRequest(t){if(this.logger.log("Session.onMessageRequest"),this.state===e.SessionState.Established)if(this.delegate&&this.delegate.onMessage){const e=new K(t);this.delegate.onMessage(e)}else t.accept();else this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`)}onNotifyRequest(t){if(this.logger.log("Session.onNotifyRequest"),this.state===e.SessionState.Established){if(this.onNotify){const e=new z(t);return void this.onNotify(e)}if(this.delegate&&this.delegate.onNotify){const e=new z(t);this.delegate.onNotify(e)}else t.accept()}else this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`)}onPrackRequest(t){if(this.logger.log("Session.onPrackRequest"),this.state===e.SessionState.Established)throw new Error("Unimplemented.");this.logger.error(`PRACK received while in state ${this.state}, dropping request`)}onReferRequest(t){if(this.logger.log("Session.onReferRequest"),this.state!==e.SessionState.Established)return void this.logger.error(`REFER received while in state ${this.state}, dropping request`);if(!t.message.hasHeader("refer-to"))return this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),void t.reject();const i=new Y(t,this);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(i):(this.logger.log("No delegate available to handle REFER, automatically accepting and following."),i.accept().then(()=>i.makeInviter(this._referralInviterOptions).invite()).catch(e=>{this.logger.error(e.message)}))}generateResponseOfferAnswer(e,t){if(this.dialog)return this.generateResponseOfferAnswerInDialog(t,e).catch(t=>{var i;throw null===(i=this.userAgent.configuration)||void 0===i||i.errorCallback({ERR_MESSAGE:t.message,CODE:"480",TIMESTAMP:J(),CALLID:e.message.callId,INVITE:e.message.toString(),ENTRY:"session: generateResponseOfferAnswer generateResponseOfferAnswerInDialog catch"}),t});const i=q(e.message);return i&&"session"===i.contentDisposition?this.setOfferAndGetAnswer(i,t,e).catch(t=>{var i;throw null===(i=this.userAgent.configuration)||void 0===i||i.errorCallback({ERR_MESSAGE:t.message,CODE:"480",TIMESTAMP:J(),CALLID:e.message.callId,INVITE:e.message.toString(),ENTRY:"session: generateResponseOfferAnswer setOfferAndGetAnswer catch"}),t}):this.getOffer(t,e).catch(t=>{var i;throw null===(i=this.userAgent.configuration)||void 0===i||i.errorCallback({ERR_MESSAGE:t.message,CODE:"480",TIMESTAMP:J(),CALLID:e.message.callId,INVITE:e.message.toString(),ENTRY:"session: generateResponseOfferAnswer getOffer catch"}),t})}generateResponseOfferAnswerInDialog(t,i){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case F.Initial:return this.getOffer(t,i).catch(e=>{var t;throw null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:(null==i?void 0:i.message.callId)||"",INVITE:(null==i?void 0:i.message.toString())||"",ENTRY:"session: generateResponseOfferAnswerInDialog SignalingState.Initial getOffer catch"}),e});case F.HaveLocalOffer:return Promise.resolve(void 0);case F.HaveRemoteOffer:if(!this.dialog.offer)throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`);return this.setOfferAndGetAnswer(this.dialog.offer,t,i).catch(e=>{var t;throw null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:(null==i?void 0:i.message.callId)||"",INVITE:(null==i?void 0:i.message.toString())||"",ENTRY:"session: generateResponseOfferAnswerInDialog setOfferAndGetAnswer catch"}),e});case F.Stable:return this.state!==e.SessionState.Established?Promise.resolve(void 0):this.getOffer(t,i).catch(e=>{var t;throw null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:(null==i?void 0:i.message.callId)||"",INVITE:(null==i?void 0:i.message.toString())||"",ENTRY:"session: generateResponseOfferAnswerInDialog SignalingState.Stable getOffer catch"}),e});case F.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}getOffer(e,t){var i;try{const i=this.setupSessionDescriptionHandler(),r=e.sessionDescriptionHandlerOptions,s=e.sessionDescriptionHandlerModifiers;return i.getDescription(r,s).catch(e=>{var i;throw null===(i=this.userAgent.configuration)||void 0===i||i.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:(null==t?void 0:t.message.callId)||"",INVITE:(null==t?void 0:t.message.toString())||"",ENTRY:"session: getOffer sdh.getDescription catch"}),e}).then(e=>M(e)).catch(e=>{this.logger.error("Session.getOffer: SDH getDescription rejected...");const t=e instanceof Error?e:new Error("Session.getOffer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.getOffer: SDH getDescription threw...");const r=e instanceof Error?e:new Error(e);return this.logger.error(r.message),null===(i=this.userAgent.configuration)||void 0===i||i.errorCallback({ERR_MESSAGE:r.message,CODE:"480",TIMESTAMP:J(),CALLID:(null==t?void 0:t.message.callId)||"",INVITE:(null==t?void 0:t.message.toString())||"",ENTRY:"session: getOffer setupSessionDescriptionHandler catch"}),Promise.reject(r)}}rollbackOffer(){try{const e=this.setupSessionDescriptionHandler();return void 0===e.rollbackDescription?Promise.resolve():e.rollbackDescription().catch(e=>{this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");const t=e instanceof Error?e:new Error("Session.rollbackOffer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setAnswer(e,t){let i,r,s;try{if(i=this.setupSessionDescriptionHandler(),r=t.sessionDescriptionHandlerOptions,s=t.sessionDescriptionHandlerModifiers,!i.hasDescription(e.contentType))return Promise.reject(new a)}catch(e){this.logger.error("Session.setAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return i.setDescription(e.content,r,s).catch(e=>{this.logger.error("Session.setAnswer: SDH setDescription rejected...");const t=e instanceof Error?e:new Error("Session.setAnswer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.setAnswer: SDH setDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setOfferAndGetAnswer(e,t,i){var r;let s,n,o;try{if(s=this.setupSessionDescriptionHandler(),n=t.sessionDescriptionHandlerOptions,o=t.sessionDescriptionHandlerModifiers,!s.hasDescription(e.contentType))return Promise.reject(new a)}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),null===(r=this.userAgent.configuration)||void 0===r||r.errorCallback({ERR_MESSAGE:t.message,CODE:"480",TIMESTAMP:J(),CALLID:(null==i?void 0:i.message.callId)||"",INVITE:(null==i?void 0:i.message.toString())||"",ENTRY:"session: setOfferAndGetAnswer setupSessionDescriptionHandler catch"}),Promise.reject(t)}try{return s.setDescription(e.content,n,o).catch(e=>{var t;throw null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:(null==i?void 0:i.message.callId)||"",INVITE:(null==i?void 0:i.message.toString())||"",ENTRY:"session: setOfferAndGetAnswer sdh.setDescription catch"}),e}).then(()=>s.getDescription(n,o)).catch(e=>{var t;throw null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:(null==i?void 0:i.message.callId)||"",INVITE:(null==i?void 0:i.message.toString())||"",ENTRY:"session: setOfferAndGetAnswer sdh.getDescription catch"}),e}).then(e=>M(e)).catch(e=>{this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");const t=e instanceof Error?e:new Error("Session.setOfferAndGetAnswer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setSessionDescriptionHandler(e){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=e}setupSessionDescriptionHandler(){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}stateTransition(t){const i=()=>{throw new Error(`Invalid state transition from ${this._state} to ${t}`)};switch(this._state){case e.SessionState.Initial:t!==e.SessionState.Establishing&&t!==e.SessionState.Established&&t!==e.SessionState.Terminating&&t!==e.SessionState.Terminated&&i();break;case e.SessionState.Establishing:t!==e.SessionState.Established&&t!==e.SessionState.Terminating&&t!==e.SessionState.Terminated&&i();break;case e.SessionState.Established:t!==e.SessionState.Terminating&&t!==e.SessionState.Terminated&&i();break;case e.SessionState.Terminating:t!==e.SessionState.Terminated&&i();break;case e.SessionState.Terminated:i();break;default:throw new Error("Unrecognized state.")}this._state=t,this.logger.log(`Session ${this.id} transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),t===e.SessionState.Terminated&&this.dispose()}copyRequestOptions(e={}){return{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}}getReasonHeaderValue(e,t){const i=e;let r=P(e);return!r&&t&&(r=t),"SIP;cause="+i+';text="'+r+'"'}referExtraHeaders(e){const 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}referToString(e){let t;if(e instanceof y)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");const i=e.remoteIdentity.friendlyName,r=e.dialog.remoteTarget.toString(),s=e.dialog.callId,n=e.dialog.remoteTag,o=e.dialog.localTag;t=`"${i}" <${r}?Replaces=${encodeURIComponent(`${s};to-tag=${n};from-tag=${o}`)}>`}return t}}var Q;!function(e){e.Required="Required",e.Supported="Supported",e.Unsupported="Unsupported"}(Q||(Q={}));const ee={"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};class te extends X{constructor(t,i){super(t),Object.defineProperty(this,"incomingInviteRequest",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"disposed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"expiresTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isCanceled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"rel100",{enumerable:!0,configurable:!0,writable:!0,value:"none"}),Object.defineProperty(this,"rseq",{enumerable:!0,configurable:!0,writable:!0,value:Math.floor(1e4*Math.random())}),Object.defineProperty(this,"userNoAnswerTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"waitingForPrack",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"waitingForPrackPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"waitingForPrackResolve",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"waitingForPrackReject",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logger=t.getLogger("sip.Invitation");const r=this.incomingInviteRequest.message,s=r.getHeader("require");s&&s.toLowerCase().includes("100rel")&&(this.rel100="required");const n=r.getHeader("supported");if(n&&n.toLowerCase().includes("100rel")&&(this.rel100="supported"),r.toTag=i.toTag,"string"!=typeof r.toTag)throw new TypeError("toTag should have been a string.");if(this.userNoAnswerTimer=setTimeout(()=>{var t;null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:"NOT ERROR",CODE:"480",TIMESTAMP:J(),CALLID:this.incomingInviteRequest.message.callId,INVITE:this.incomingInviteRequest.message.toString(),ENTRY:"invitation: constructor userNoAnswerTimer "+(this.userAgent.configuration.noAnswerTimeout?1e3*this.userAgent.configuration.noAnswerTimeout:6e4)}),i.reject({statusCode:480}),this.stateTransition(e.SessionState.Terminated)},this.userAgent.configuration.noAnswerTimeout?1e3*this.userAgent.configuration.noAnswerTimeout:6e4),r.hasHeader("expires")){const t=1e3*Number(r.getHeader("expires")||0);this.expiresTimer=setTimeout(()=>{this.state===e.SessionState.Initial&&(i.reject({statusCode:487}),this.stateTransition(e.SessionState.Terminated))},t)}const o=this.request.getHeader("P-Asserted-Identity");o&&(this._assertedIdentity=E.nameAddrHeaderParse(o)),this._contact=this.userAgent.contact.toString();const a=r.parseHeader("Content-Disposition");a&&"render"===a.type&&(this._renderbody=r.body,this._rendertype=r.getHeader("Content-Type")),this._id=r.callId+r.fromTag,this.userAgent._sessions[this._id]=this}dispose(){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 e.SessionState.Initial:case e.SessionState.Establishing:return this.reject().then(()=>super.dispose());case e.SessionState.Established:case e.SessionState.Terminating:case e.SessionState.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get autoSendAnInitialProvisionalResponse(){return"required"!==this.rel100&&this.userAgent.configuration.sendInitialProvisionalResponse}get body(){return this.incomingInviteRequest.message.body}get localIdentity(){return this.request.to}get remoteIdentity(){return this.request.from}get request(){return this.incomingInviteRequest.message}accept(t={}){if(this.logger.log("Invitation.accept"),this.state!==e.SessionState.Initial){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}return t.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=t.sessionDescriptionHandlerModifiers),t.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=t.sessionDescriptionHandlerOptions),this.stateTransition(e.SessionState.Establishing),this.sendAccept(t).then(({message:i,session:r})=>{r.delegate={onAck:e=>{const i=this.onAckRequest(e);return t.onAck&&t.onAck(e),i},onAckTimeout:()=>{this.onAckTimeout(),t.onAckTimeout&&t.onAckTimeout()},onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=r,this.stateTransition(e.SessionState.Established),this._replacee&&this._replacee._bye()}).catch(e=>{var t;return null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:this.incomingInviteRequest.message.callId,INVITE:this.incomingInviteRequest.message.toString(),ENTRY:"invitation: accept sendAccept catch"}),this.handleResponseError(e)})}progress(t={}){if(this.logger.log("Invitation.progress"),this.state!==e.SessionState.Initial){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const i=t.statusCode||180;if(i<100||i>199)throw new TypeError("Invalid statusCode: "+i);return t.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=t.sessionDescriptionHandlerModifiers),t.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=t.sessionDescriptionHandlerOptions),this.waitingForPrack?(this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),Promise.resolve()):100===t.statusCode?this.sendProgressTrying().then(()=>{}).catch(e=>{var t;return null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:this.incomingInviteRequest.message.callId,INVITE:this.incomingInviteRequest.message.toString(),ENTRY:"invitation: progress sendProgressTrying catch"}),this.handleResponseError(e)}):"required"===this.rel100||"supported"===this.rel100&&t.rel100||"supported"===this.rel100&&this.userAgent.configuration.sipExtension100rel===Q.Required?this.sendProgressReliableWaitForPrack(t).then(()=>{}).catch(e=>{var t;return null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:this.incomingInviteRequest.message.callId,INVITE:this.incomingInviteRequest.message.toString(),ENTRY:"invitation: progress sendProgressReliableWaitForPrack catch"}),this.handleResponseError(e)}):this.sendProgress(t).then(()=>{}).catch(e=>{var t;return null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:this.incomingInviteRequest.message.callId,INVITE:this.incomingInviteRequest.message.toString(),ENTRY:"invitation: progress rel100 sendProgress catch"}),this.handleResponseError(e)})}reject(t={}){if(this.logger.log("Invitation.reject"),this.state!==e.SessionState.Initial&&this.state!==e.SessionState.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const i=t.statusCode||480,r=t.reasonPhrase?t.reasonPhrase:P(i),s=t.extraHeaders||[];if(i<300||i>699)throw new TypeError("Invalid statusCode: "+i);const n=t.body?M(t.body):void 0;return i<400?this.incomingInviteRequest.redirect([],{statusCode:i,reasonPhrase:r,extraHeaders:s,body:n}):this.incomingInviteRequest.reject({statusCode:i,reasonPhrase:r,extraHeaders:s,body:n}),this.stateTransition(e.SessionState.Terminated),Promise.resolve()}_onCancel(t){if(this.logger.log("Invitation._onCancel"),this.state===e.SessionState.Initial||this.state===e.SessionState.Establishing){if(this.delegate&&this.delegate.onCancel){const e=new f(t);this.delegate.onCancel(e)}this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(e.SessionState.Terminated)}else this.logger.error(`CANCEL received while in state ${this.state}, dropping request`)}handlePrackOfferAnswer(e){if(!this.dialog)throw new Error("Dialog undefined.");const t=q(e.message);if(!t||"session"!==t.contentDisposition)return Promise.resolve(void 0);const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case F.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case F.Stable:return this.setAnswer(t,i).then(()=>{});case F.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case F.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,i);case F.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}handleResponseError(t){let i=480;if(t instanceof Error?this.logger.error(t.message):this.logger.error(t),t instanceof a?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),i=415):t instanceof l?this.logger.error("A session description handler occurred while sending response"):t instanceof h?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):t instanceof W&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===e.SessionState.Initial||this.state===e.SessionState.Establishing)try{this.incomingInviteRequest.reject({statusCode:i}),this.stateTransition(e.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 t;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.")}onAckTimeout(){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(e.SessionState.Terminated)}sendAccept(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.extraHeaders||[];return this.waitingForPrack?this.waitForArrivalOfPrack().then(()=>clearTimeout(this.userNoAnswerTimer)).then(()=>this.generateResponseOfferAnswer(this.incomingInviteRequest,t)).catch(e=>{var t;throw null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:this.incomingInviteRequest.message.callId,INVITE:this.incomingInviteRequest.message.toString(),ENTRY:"invitation: sendAccept waitForArrivalOfPrack generateResponseOfferAnswer catch"}),e}).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:i})):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,t).catch(e=>{var t;throw null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:this.incomingInviteRequest.message.callId,INVITE:this.incomingInviteRequest.message.toString(),ENTRY:"invitation: sendAccept generateResponseOfferAnswer catch"}),e}).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:i})))}sendProgress(e={}){const t=e.statusCode||180,i=e.reasonPhrase,r=(e.extraHeaders||[]).slice(),s=e.body?M(e.body):void 0;if(183===t&&!s)return this.sendProgressWithSDP(e);try{const e=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:i,extraHeaders:r,body:s});return this._dialog=e.session,Promise.resolve(e)}catch(e){return Promise.reject(e)}}sendProgressWithSDP(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.statusCode||183,r=e.reasonPhrase,s=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>this.incomingInviteRequest.progress({statusCode:i,reasonPhrase:r,extraHeaders:s,body:e})).then(e=>(this._dialog=e.session,e))}sendProgressReliable(e={}){return e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this.sendProgressWithSDP(e)}sendProgressReliableWaitForPrack(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.statusCode||183,r=e.reasonPhrase,s=(e.extraHeaders||[]).slice();let n;return s.push("Require: 100rel"),s.push("RSeq: "+this.rseq++),new Promise((e,o)=>{this.waitingForPrack=!0,this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>(n=e,this.incomingInviteRequest.progress({statusCode:i,reasonPhrase:r,extraHeaders:s,body:n}))).then(t=>{let a,c;this._dialog=t.session,t.session.delegate={onPrack:i=>{a=i,clearTimeout(l),clearTimeout(g),this.waitingForPrack&&(this.waitingForPrack=!1,this.handlePrackOfferAnswer(a).then(i=>{try{c=a.accept({statusCode:200,body:i}),this.prackArrived(),e({prackRequest:a,prackResponse:c,progressResponse:t})}catch(e){o(e)}}).catch(e=>o(e)))}};const l=setTimeout(()=>{this.waitingForPrack&&(this.waitingForPrack=!1,this.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(g),this.reject({statusCode:504}).then(()=>o(new h)).catch(e=>o(e)))},64*B.T1),d=()=>{try{this.incomingInviteRequest.progress({statusCode:i,reasonPhrase:r,extraHeaders:s,body:n})}catch(e){return this.waitingForPrack=!1,void o(e)}g=setTimeout(d,u*=2)};let u=B.T1,g=setTimeout(d,u)}).catch(e=>{this.waitingForPrack=!1,o(e)})})}sendProgressTrying(){try{const e=this.incomingInviteRequest.trying();return Promise.resolve(e)}catch(e){return Promise.reject(e)}}waitForArrivalOfPrack(){if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise((e,t)=>{this.waitingForPrackResolve=e,this.waitingForPrackReject=t}),this.waitingForPrackPromise}prackArrived(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}prackNeverArrived(){this.waitingForPrackReject&&this.waitingForPrackReject(new h),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}class ie extends X{constructor(e,t,i={}){super(e,i),Object.defineProperty(this,"_referred",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"disposed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"earlyMedia",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"earlyMediaDialog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"earlyMediaSessionDescriptionHandlers",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"fromTag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isCanceled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"inviteWithoutSdp",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"outgoingInviteRequest",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outgoingRequestMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logger=e.getLogger("sip.Inviter"),this.earlyMedia=void 0!==i.earlyMedia?i.earlyMedia:this.earlyMedia,this.fromTag=A(),this.inviteWithoutSdp=void 0!==i.inviteWithoutSdp?i.inviteWithoutSdp:this.inviteWithoutSdp;const r=Object.assign({},i);r.params=Object.assign({},i.params);const s=i.anonymous||!1,n=e.contact.toString({anonymous:s,outbound:s?!e.contact.tempGruu:!e.contact.pubGruu});s&&e.configuration.uri&&(r.params.fromDisplayName="Anonymous",r.params.fromUri="sip:anonymous@anonymous.invalid");let o=e.userAgentCore.configuration.aor;if(r.params.fromUri&&(o="string"==typeof r.params.fromUri?E.URIParse(r.params.fromUri):r.params.fromUri),!o)throw new TypeError("Invalid from URI: "+r.params.fromUri);let a=t;if(r.params.toUri&&(a="string"==typeof r.params.toUri?E.URIParse(r.params.toUri):r.params.toUri),!a)throw new TypeError("Invalid to URI: "+r.params.toUri);const c=Object.assign({},r.params);c.fromTag=this.fromTag;const l=(r.extraHeaders||[]).slice();s&&e.configuration.uri&&(l.push("P-Preferred-Identity: "+e.configuration.uri.toString()),l.push("Privacy: id")),l.push("Contact: "+n),l.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),e.configuration.sipExtension100rel===Q.Required&&l.push("Require: 100rel"),e.configuration.sipExtensionReplaces===Q.Required&&l.push("Require: replaces"),r.extraHeaders=l;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(G.INVITE,t,o,a,c,l,undefined),this._contact=n,this._referralInviterOptions=r,this._renderbody=i.renderbody,this._rendertype=i.rendertype,i.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=i.sessionDescriptionHandlerModifiers),i.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=i.sessionDescriptionHandlerOptions),i.sessionDescriptionHandlerModifiersReInvite&&(this.sessionDescriptionHandlerModifiersReInvite=i.sessionDescriptionHandlerModifiersReInvite),i.sessionDescriptionHandlerOptionsReInvite&&(this.sessionDescriptionHandlerOptionsReInvite=i.sessionDescriptionHandlerOptionsReInvite),this._id=this.outgoingRequestMessage.callId+this.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.disposeEarlyMedia(),this.state){case e.SessionState.Initial:case e.SessionState.Establishing:return this.cancel().then(()=>super.dispose());case e.SessionState.Established:case e.SessionState.Terminating:case e.SessionState.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get body(){return this.outgoingRequestMessage.body}get localIdentity(){return this.outgoingRequestMessage.from}get remoteIdentity(){return this.outgoingRequestMessage.to}get request(){return this.outgoingRequestMessage}cancel(t={}){if(this.logger.log("Inviter.cancel"),this.state!==e.SessionState.Initial&&this.state!==e.SessionState.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}if(this.isCanceled=!0,this.stateTransition(e.SessionState.Terminating),this.outgoingInviteRequest){let e;t.statusCode&&t.reasonPhrase&&(e=function(e,t){if(e&&e<200||e>699)throw new TypeError("Invalid statusCode: "+e);if(e)return"SIP;cause="+e+';text="'+(P(e)||t)+'"'}(t.statusCode,t.reasonPhrase)),this.outgoingInviteRequest.cancel(e,t)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(e.SessionState.Terminated);return Promise.resolve()}invite(t={}){if(this.logger.log("Inviter.invite"),this.state!==e.SessionState.Initial)return super.invite(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(e.SessionState.Establishing),Promise.resolve(this.sendInvite(t));const i={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(i).then(i=>(this.outgoingRequestMessage.body={body:i.content,contentType:i.contentType},this.stateTransition(e.SessionState.Establishing),this.sendInvite(t))).catch(t=>{throw this.logger.log(t.message),this.state!==e.SessionState.Terminated&&this.stateTransition(e.SessionState.Terminated),t})}sendInvite(t={}){return this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:i=>this.dialog?(this.logger.log("Additional confirmed dialog, sending ACK and BYE"),void this.ackAndBye(i)):this.isCanceled?(this.logger.log("Canceled session accepted, sending ACK and BYE"),this.ackAndBye(i),void this.stateTransition(e.SessionState.Terminated)):(this.notifyReferer(i),void this.onAccept(i).then(()=>{this.disposeEarlyMedia()}).catch(()=>{this.disposeEarlyMedia()}).then(()=>{t.requestDelegate&&t.requestDelegate.onAccept&&t.requestDelegate.onAccept(i)})),onProgress:e=>{this.isCanceled||(this.notifyReferer(e),this.onProgress(e).catch(()=>{this.disposeEarlyMedia()}).then(()=>{t.requestDelegate&&t.requestDelegate.onProgress&&t.requestDelegate.onProgress(e)}))},onRedirect:e=>{this.notifyReferer(e),this.onRedirect(e),t.requestDelegate&&t.requestDelegate.onRedirect&&t.requestDelegate.onRedirect(e)},onReject:e=>{this.notifyReferer(e),this.onReject(e),t.requestDelegate&&t.requestDelegate.onReject&&t.requestDelegate.onReject(e)},onTrying:e=>{this.notifyReferer(e),this.onTrying(e),t.requestDelegate&&t.requestDelegate.onTrying&&t.requestDelegate.onTrying(e)}}),this.outgoingInviteRequest}disposeEarlyMedia(){this.earlyMediaSessionDescriptionHandlers.forEach(e=>{e.close()}),this.earlyMediaSessionDescriptionHandlers.clear()}notifyReferer(e){if(!this._referred)return;if(!(this._referred instanceof X))throw new Error("Referred session not instance of session");if(!this._referred.dialog)return;if(!e.message.statusCode)throw new Error("Status code undefined.");if(!e.message.reasonPhrase)throw new Error("Reason phrase undefined.");const t=`SIP/2.0 ${e.message.statusCode} ${e.message.reasonPhrase}`.trim();this._referred.dialog.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:t}}).delegate={onReject:()=>{this._referred=void 0}}}onAccept(t){if(this.logger.log("Inviter.onAccept"),this.state!==e.SessionState.Establishing)return this.logger.error(`Accept received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));const i=t.message,r=t.session;switch(i.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=E.nameAddrHeaderParse(i.getHeader("P-Asserted-Identity"))),r.delegate={onAck:e=>this.onAckRequest(e),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=r,r.signalingState){case F.Initial:case F.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(t,400,"Missing session description"),this.stateTransition(e.SessionState.Terminated),Promise.reject(new Error("Bad Media Description"));case F.HaveRemoteOffer:{if(!this._dialog.offer)throw new Error(`Session offer undefined in signaling state ${this._dialog.signalingState}.`);const i={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,i).then(i=>{t.ack({body:i}),this.stateTransition(e.SessionState.Established)}).catch(i=>{throw this.ackAndBye(t,488,"Invalid session description"),this.stateTransition(e.SessionState.Terminated),i})}case F.Stable:{if(this.earlyMediaSessionDescriptionHandlers.size>0){const i=this.earlyMediaSessionDescriptionHandlers.get(r.id);if(!i)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(i),this.earlyMediaSessionDescriptionHandlers.delete(r.id),t.ack(),this.stateTransition(e.SessionState.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==r){if(this.earlyMedia){const e="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.";this.logger.error(e)}const i=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(i.message),this.ackAndBye(t,488,"Not Acceptable Here"),this.stateTransition(e.SessionState.Terminated),Promise.reject(i)}return t.ack(),this.stateTransition(e.SessionState.Established),Promise.resolve()}const i=r.answer;if(!i)throw new Error("Answer is undefined.");const s={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(i,s).then(()=>{let i;this._renderbody&&this._rendertype&&(i={body:{contentDisposition:"render",contentType:this._rendertype,content:this._renderbody}}),t.ack(i),this.stateTransition(e.SessionState.Established)}).catch(i=>{throw this.logger.error(i.message),this.ackAndBye(t,488,"Not Acceptable Here"),this.stateTransition(e.SessionState.Terminated),i})}case F.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onProgress(t){var i;if(this.logger.log("Inviter.onProgress"),this.state!==e.SessionState.Establishing)return this.logger.error(`Progress received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));if(!this.outgoingInviteRequest)throw new Error("Outgoing INVITE request undefined.");const r=t.message,s=t.session;r.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=E.nameAddrHeaderParse(r.getHeader("P-Asserted-Identity")));const n=r.getHeader("require"),o=r.getHeader("rseq"),a=!!(n&&n.includes("100rel")&&o?Number(o):void 0),c=[];switch(a&&c.push("RAck: "+r.getHeader("rseq")+" "+r.getHeader("cseq")),s.signalingState){case F.Initial:return a&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),t.prack({extraHeaders:c})),Promise.resolve();case F.HaveLocalOffer:return a&&t.prack({extraHeaders:c}),Promise.resolve();case F.HaveRemoteOffer:if(!a)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();{const n=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(i=this.delegate)||void 0===i?void 0:i.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(n,!0),this.earlyMediaSessionDescriptionHandlers.set(s.id,n),n.setDescription(r.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then(()=>n.getDescription(this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers)).then(e=>{const i={contentDisposition:"session",contentType:e.contentType,content:e.body};t.prack({extraHeaders:c,body:i})}).catch(t=>{throw this.stateTransition(e.SessionState.Terminated),t})}case F.Stable:if(a&&t.prack({extraHeaders:c}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=s;const t=s.answer;if(!t)throw new Error("Answer is undefined.");const i={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(t,i).catch(t=>{throw this.stateTransition(e.SessionState.Terminated),t})}return Promise.resolve();case F.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(t){this.logger.log("Inviter.onRedirect"),this.state===e.SessionState.Establishing||this.state===e.SessionState.Terminating?this.stateTransition(e.SessionState.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(t){this.logger.log("Inviter.onReject"),this.state===e.SessionState.Establishing||this.state===e.SessionState.Terminating?this.stateTransition(e.SessionState.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(t){this.logger.log("Inviter.onTrying"),this.state===e.SessionState.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}class re{constructor(e,t,i,r="text/plain",s={}){Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"userAgent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logger=e.getLogger("sip.Messager"),s.params=s.params||{};let n=e.userAgentCore.configuration.aor;if(s.params.fromUri&&(n="string"==typeof s.params.fromUri?E.URIParse(s.params.fromUri):s.params.fromUri),!n)throw new TypeError("Invalid from URI: "+s.params.fromUri);let o=t;if(s.params.toUri&&(o="string"==typeof s.params.toUri?E.URIParse(s.params.toUri):s.params.toUri),!o)throw new TypeError("Invalid to URI: "+s.params.toUri);const a=s.params?Object.assign({},s.params):{},c=(s.extraHeaders||[]).slice(),l={contentDisposition:"render",contentType:r,content:i};this.request=e.userAgentCore.makeOutgoingRequestMessage(G.MESSAGE,t,n,o,a,c,l),this.userAgent=e}message(e={}){return this.userAgent.userAgentCore.request(this.request,e.requestDelegate),Promise.resolve()}}var se,ne,oe,ae,ce,le,he,de,ue;!function(e){e.Initial="Initial",e.Published="Published",e.Unpublished="Unpublished",e.Terminated="Terminated"}(se||(se={})),function(e){e.Initial="Initial",e.Registered="Registered",e.Unregistered="Unregistered",e.Terminated="Terminated"}(ne||(ne={}));class ge{constructor(e,t={}){Object.defineProperty(this,"disposed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"expires",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshFrequency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"userAgent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"registrationExpiredTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"registrationTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_contacts",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_retryAfter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_state",{enumerable:!0,configurable:!0,writable:!0,value:ne.Initial}),Object.defineProperty(this,"_stateEventEmitter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_waiting",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_waitingEventEmitter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._stateEventEmitter=new p,this._waitingEventEmitter=new p,this.userAgent=e;const i=e.configuration.uri.clone();if(i.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},ge.defaultOptions()),{registrar:i}),ge.stripUndefinedProperties(t)),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=this.userAgent.instanceId:!this.options.regId&&this.options.instanceId&&(this.options.regId=1),this.options.instanceId&&-1===E.parse(this.options.instanceId,"uuid"))throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");const r=this.options.registrar,s=this.options.params&&this.options.params.fromUri||e.userAgentCore.configuration.aor,n=this.options.params&&this.options.params.toUri||e.configuration.uri,o=this.options.params||{},a=(t.extraHeaders||[]).slice();if(this.request=e.userAgentCore.makeOutgoingRequestMessage(G.REGISTER,r,s,n,o,a,void 0),this.expires=this.options.expires||ge.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||ge.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=e.getLogger("sip.Registerer"),this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];if("registrar"===e)this.logger.log("· "+e+": "+t);else this.logger.log("· "+e+": "+JSON.stringify(t))})),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}static defaultOptions(){return{expires:ge.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new y("sip","anonymous","anonymous.invalid"),refreshFrequency:ge.defaultRefreshFrequency}}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,i)=>(void 0!==e[i]&&(t[i]=e[i]),t),{})}get contacts(){return this._contacts.slice()}get retryAfter(){return this._retryAfter}get state(){return this._state}get stateChange(){return this._stateEventEmitter}dispose(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log(`Registerer ${this.id} in state ${this.state} is being disposed`),delete this.userAgent._registerers[this.id],new Promise(e=>{const t=()=>{if(!this.waiting&&this._state===ne.Registered)return this.stateChange.addListener(()=>{this.terminated(),e()},{once:!0}),void this.unregister();this.terminated(),e()};this.waiting?this.waitingChange.addListener(()=>{t()},{once:!0}):t()}))}register(e={}){if(this.state===ne.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();const e=new c("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}e.requestOptions&&(this.options=Object.assign(Object.assign({},this.options),e.requestOptions));const t=(this.options.extraHeaders||[]).slice();t.push("Contact: "+this.generateContactHeader(this.expires)),t.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=t,this.waitingToggle(!0);const i=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{let i;t.message.hasHeader("expires")&&(i=Number(t.message.getHeader("expires"))),this._contacts=t.message.getHeaders("contact");let r,s=this._contacts.length;if(!s)return this.logger.error("No Contact header in response to REGISTER, dropping response."),void this.unregistered();for(;s--;){if(r=t.message.parseHeader("contact",s),!r)throw new Error("Contact undefined");if(this.userAgent.contact.pubGruu&&w(r.uri,this.userAgent.contact.pubGruu)){i=Number(r.getParam("expires"));break}if(""===this.userAgent.configuration.contactName){if(r.uri.user===this.userAgent.contact.uri.user){i=Number(r.getParam("expires"));break}}else if(w(r.uri,this.userAgent.contact.uri)){i=Number(r.getParam("expires"));break}r=void 0}if(void 0===r)return this.logger.error("No Contact header pointing to us, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(void 0===i)return this.logger.error("Contact pointing to us is missing expires parameter, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(r.hasParam("temp-gruu")){const e=r.getParam("temp-gruu");e&&(this.userAgent.contact.tempGruu=E.URIParse(e.replace(/"/g,"")))}if(r.hasParam("pub-gruu")){const e=r.getParam("pub-gruu");e&&(this.userAgent.contact.pubGruu=E.URIParse(e.replace(/"/g,"")))}this.registered(i),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Redirect received. Not supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{if(423===t.message.statusCode)return t.message.hasHeader("min-expires")?(this.expires=Number(t.message.getHeader("min-expires")),this.waitingToggle(!1),void this.register()):(this.logger.error("423 response received for REGISTER without Min-Expires, dropping response"),this.unregistered(),void this.waitingToggle(!1));this.logger.warn(`Failed to register, status code ${t.message.statusCode}`);let i=NaN;if(500===t.message.statusCode||503===t.message.statusCode){const e=t.message.getHeader("retry-after");e&&(i=Number.parseInt(e,void 0))}this._retryAfter=isNaN(i)?void 0:i,this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this._retryAfter=void 0,this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(i)}unregister(e={}){if(this.state===ne.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==ne.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new c("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}this._state===ne.Registered||e.all||this.logger.warn("Not currently registered, but sending an unregister anyway.");const t=(e.requestOptions&&e.requestOptions.extraHeaders||[]).slice();this.request.extraHeaders=t,e.all?(t.push("Contact: *"),t.push("Expires: 0")):t.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);const i=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{this._contacts=t.message.getHeaders("contact"),this.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Unregister redirected. Not currently supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{this.logger.error(`Unregister rejected with status code ${t.message.statusCode}`),this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(i)}clearTimers(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)}generateContactHeader(e){let t=this.userAgent.contact.toString({register:!0});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(e=>{t+=";"+e}),t+=";expires="+e,t}registered(e){this.clearTimers(),this.registrationTimer=setTimeout(()=>{this.registrationTimer=void 0,this.register()},this.refreshFrequency/100*e*1e3),this.registrationExpiredTimer=setTimeout(()=>{this.logger.warn("Registration expired"),this.unregistered()},1e3*e),this._state!==ne.Registered&&this.stateTransition(ne.Registered)}unregistered(){this.clearTimers(),this._state!==ne.Unregistered&&this.stateTransition(ne.Unregistered)}terminated(){this.clearTimers(),this._state!==ne.Terminated&&this.stateTransition(ne.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case ne.Initial:e!==ne.Registered&&e!==ne.Unregistered&&e!==ne.Terminated&&t();break;case ne.Registered:e!==ne.Unregistered&&e!==ne.Terminated&&t();break;case ne.Unregistered:e!==ne.Registered&&e!==ne.Terminated&&t();break;case ne.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Registration transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===ne.Terminated&&this.dispose()}get waiting(){return this._waiting}get waitingChange(){return this._waitingEventEmitter}waitingToggle(e){if(this._waiting===e)throw new Error(`Invalid waiting transition from ${this._waiting} to ${e}`);this._waiting=e,this.logger.log(`Waiting toggled to ${this._waiting}`),this._waitingEventEmitter.emit(this._waiting)}waitingWarning(){let e="An attempt was made to send a REGISTER request while a prior one was still in progress.";e+=" RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response",e+=" from the registrar for the previous one or the previous REGISTER request has timed out.",e+=" Note that if the transport disconnects, you still must wait for the prior request to time out before",e+=" sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.",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.")}stateError(){let e=`An attempt was made to send a REGISTER request when the Registerer ${this.state===ne.Terminated?"is in 'Terminated' state":"has been disposed"}.`;e+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",e+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(e)}}Object.defineProperty(ge,"defaultExpires",{enumerable:!0,configurable:!0,writable:!0,value:600}),Object.defineProperty(ge,"defaultRefreshFrequency",{enumerable:!0,configurable:!0,writable:!0,value:99}),function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(oe||(oe={})),function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Subscribed="Subscribed",e.Terminated="Terminated"}(ae||(ae={})),function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(ce||(ce={})),function(e){e.Started="Started",e.Stopped="Stopped"}(le||(le={}));class fe{static hashStr(e,t=!1){return this.onePassHasher.start().appendStr(e).end(t)}static hashAsciiStr(e,t=!1){return this.onePassHasher.start().appendAsciiStr(e).end(t)}static _hex(e){const t=fe.hexChars,i=fe.hexOut;let r,s,n,o;for(o=0;o<4;o+=1)for(s=8*o,r=e[o],n=0;n<8;n+=2)i[s+1+n]=t.charAt(15&r),r>>>=4,i[s+0+n]=t.charAt(15&r),r>>>=4;return i.join("")}static _md5cycle(e,t){let i=e[0],r=e[1],s=e[2],n=e[3];i+=(r&s|~r&n)+t[0]-680876936|0,i=(i<<7|i>>>25)+r|0,n+=(i&r|~i&s)+t[1]-389564586|0,n=(n<<12|n>>>20)+i|0,s+=(n&i|~n&r)+t[2]+606105819|0,s=(s<<17|s>>>15)+n|0,r+=(s&n|~s&i)+t[3]-1044525330|0,r=(r<<22|r>>>10)+s|0,i+=(r&s|~r&n)+t[4]-176418897|0,i=(i<<7|i>>>25)+r|0,n+=(i&r|~i&s)+t[5]+1200080426|0,n=(n<<12|n>>>20)+i|0,s+=(n&i|~n&r)+t[6]-1473231341|0,s=(s<<17|s>>>15)+n|0,r+=(s&n|~s&i)+t[7]-45705983|0,r=(r<<22|r>>>10)+s|0,i+=(r&s|~r&n)+t[8]+1770035416|0,i=(i<<7|i>>>25)+r|0,n+=(i&r|~i&s)+t[9]-1958414417|0,n=(n<<12|n>>>20)+i|0,s+=(n&i|~n&r)+t[10]-42063|0,s=(s<<17|s>>>15)+n|0,r+=(s&n|~s&i)+t[11]-1990404162|0,r=(r<<22|r>>>10)+s|0,i+=(r&s|~r&n)+t[12]+1804603682|0,i=(i<<7|i>>>25)+r|0,n+=(i&r|~i&s)+t[13]-40341101|0,n=(n<<12|n>>>20)+i|0,s+=(n&i|~n&r)+t[14]-1502002290|0,s=(s<<17|s>>>15)+n|0,r+=(s&n|~s&i)+t[15]+1236535329|0,r=(r<<22|r>>>10)+s|0,i+=(r&n|s&~n)+t[1]-165796510|0,i=(i<<5|i>>>27)+r|0,n+=(i&s|r&~s)+t[6]-1069501632|0,n=(n<<9|n>>>23)+i|0,s+=(n&r|i&~r)+t[11]+643717713|0,s=(s<<14|s>>>18)+n|0,r+=(s&i|n&~i)+t[0]-373897302|0,r=(r<<20|r>>>12)+s|0,i+=(r&n|s&~n)+t[5]-701558691|0,i=(i<<5|i>>>27)+r|0,n+=(i&s|r&~s)+t[10]+38016083|0,n=(n<<9|n>>>23)+i|0,s+=(n&r|i&~r)+t[15]-660478335|0,s=(s<<14|s>>>18)+n|0,r+=(s&i|n&~i)+t[4]-405537848|0,r=(r<<20|r>>>12)+s|0,i+=(r&n|s&~n)+t[9]+568446438|0,i=(i<<5|i>>>27)+r|0,n+=(i&s|r&~s)+t[14]-1019803690|0,n=(n<<9|n>>>23)+i|0,s+=(n&r|i&~r)+t[3]-187363961|0,s=(s<<14|s>>>18)+n|0,r+=(s&i|n&~i)+t[8]+1163531501|0,r=(r<<20|r>>>12)+s|0,i+=(r&n|s&~n)+t[13]-1444681467|0,i=(i<<5|i>>>27)+r|0,n+=(i&s|r&~s)+t[2]-51403784|0,n=(n<<9|n>>>23)+i|0,s+=(n&r|i&~r)+t[7]+1735328473|0,s=(s<<14|s>>>18)+n|0,r+=(s&i|n&~i)+t[12]-1926607734|0,r=(r<<20|r>>>12)+s|0,i+=(r^s^n)+t[5]-378558|0,i=(i<<4|i>>>28)+r|0,n+=(i^r^s)+t[8]-2022574463|0,n=(n<<11|n>>>21)+i|0,s+=(n^i^r)+t[11]+1839030562|0,s=(s<<16|s>>>16)+n|0,r+=(s^n^i)+t[14]-35309556|0,r=(r<<23|r>>>9)+s|0,i+=(r^s^n)+t[1]-1530992060|0,i=(i<<4|i>>>28)+r|0,n+=(i^r^s)+t[4]+1272893353|0,n=(n<<11|n>>>21)+i|0,s+=(n^i^r)+t[7]-155497632|0,s=(s<<16|s>>>16)+n|0,r+=(s^n^i)+t[10]-1094730640|0,r=(r<<23|r>>>9)+s|0,i+=(r^s^n)+t[13]+681279174|0,i=(i<<4|i>>>28)+r|0,n+=(i^r^s)+t[0]-358537222|0,n=(n<<11|n>>>21)+i|0,s+=(n^i^r)+t[3]-722521979|0,s=(s<<16|s>>>16)+n|0,r+=(s^n^i)+t[6]+76029189|0,r=(r<<23|r>>>9)+s|0,i+=(r^s^n)+t[9]-640364487|0,i=(i<<4|i>>>28)+r|0,n+=(i^r^s)+t[12]-421815835|0,n=(n<<11|n>>>21)+i|0,s+=(n^i^r)+t[15]+530742520|0,s=(s<<16|s>>>16)+n|0,r+=(s^n^i)+t[2]-995338651|0,r=(r<<23|r>>>9)+s|0,i+=(s^(r|~n))+t[0]-198630844|0,i=(i<<6|i>>>26)+r|0,n+=(r^(i|~s))+t[7]+1126891415|0,n=(n<<10|n>>>22)+i|0,s+=(i^(n|~r))+t[14]-1416354905|0,s=(s<<15|s>>>17)+n|0,r+=(n^(s|~i))+t[5]-57434055|0,r=(r<<21|r>>>11)+s|0,i+=(s^(r|~n))+t[12]+1700485571|0,i=(i<<6|i>>>26)+r|0,n+=(r^(i|~s))+t[3]-1894986606|0,n=(n<<10|n>>>22)+i|0,s+=(i^(n|~r))+t[10]-1051523|0,s=(s<<15|s>>>17)+n|0,r+=(n^(s|~i))+t[1]-2054922799|0,r=(r<<21|r>>>11)+s|0,i+=(s^(r|~n))+t[8]+1873313359|0,i=(i<<6|i>>>26)+r|0,n+=(r^(i|~s))+t[15]-30611744|0,n=(n<<10|n>>>22)+i|0,s+=(i^(n|~r))+t[6]-1560198380|0,s=(s<<15|s>>>17)+n|0,r+=(n^(s|~i))+t[13]+1309151649|0,r=(r<<21|r>>>11)+s|0,i+=(s^(r|~n))+t[4]-145523070|0,i=(i<<6|i>>>26)+r|0,n+=(r^(i|~s))+t[11]-1120210379|0,n=(n<<10|n>>>22)+i|0,s+=(i^(n|~r))+t[2]+718787259|0,s=(s<<15|s>>>17)+n|0,r+=(n^(s|~i))+t[9]-343485551|0,r=(r<<21|r>>>11)+s|0,e[0]=i+e[0]|0,e[1]=r+e[1]|0,e[2]=s+e[2]|0,e[3]=n+e[3]|0}constructor(){Object.defineProperty(this,"_dataLength",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_bufferLength",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_state",{enumerable:!0,configurable:!0,writable:!0,value:new Int32Array(4)}),Object.defineProperty(this,"_buffer",{enumerable:!0,configurable:!0,writable:!0,value:new ArrayBuffer(68)}),Object.defineProperty(this,"_buffer8",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_buffer32",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(fe.stateIdentity),this}appendStr(e){const t=this._buffer8,i=this._buffer32;let r,s,n=this._bufferLength;for(s=0;s<e.length;s+=1){if(r=e.charCodeAt(s),r<128)t[n++]=r;else if(r<2048)t[n++]=(r>>>6)+192,t[n++]=63&r|128;else if(r<55296||r>56319)t[n++]=(r>>>12)+224,t[n++]=r>>>6&63|128,t[n++]=63&r|128;else{if(r=1024*(r-55296)+(e.charCodeAt(++s)-56320)+65536,r>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");t[n++]=(r>>>18)+240,t[n++]=r>>>12&63|128,t[n++]=r>>>6&63|128,t[n++]=63&r|128}n>=64&&(this._dataLength+=64,fe._md5cycle(this._state,i),n-=64,i[0]=i[16])}return this._bufferLength=n,this}appendAsciiStr(e){const t=this._buffer8,i=this._buffer32;let r,s=this._bufferLength,n=0;for(;;){for(r=Math.min(e.length-n,64-s);r--;)t[s++]=e.charCodeAt(n++);if(s<64)break;this._dataLength+=64,fe._md5cycle(this._state,i),s=0}return this._bufferLength=s,this}appendByteArray(e){const t=this._buffer8,i=this._buffer32;let r,s=this._bufferLength,n=0;for(;;){for(r=Math.min(e.length-n,64-s);r--;)t[s++]=e[n++];if(s<64)break;this._dataLength+=64,fe._md5cycle(this._state,i),s=0}return this._bufferLength=s,this}getState(){const 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]]}}setState(e){const t=e.buffer,i=e.state,r=this._state;let s;for(this._dataLength=e.length,this._bufferLength=e.buflen,r[0]=i[0],r[1]=i[1],r[2]=i[2],r[3]=i[3],s=0;s<t.length;s+=1)this._buffer8[s]=t.charCodeAt(s)}end(e=!1){const t=this._bufferLength,i=this._buffer8,r=this._buffer32,s=1+(t>>2);let n;if(this._dataLength+=t,i[t]=128,i[t+1]=i[t+2]=i[t+3]=0,r.set(fe.buffer32Identity.subarray(s),s),t>55&&(fe._md5cycle(this._state,r),r.set(fe.buffer32Identity)),n=8*this._dataLength,n<=4294967295)r[14]=n;else{const e=n.toString(16).match(/(.*?)(.{0,8})$/);if(null===e)return;const t=parseInt(e[2],16),i=parseInt(e[1],16)||0;r[14]=t,r[15]=i}return fe._md5cycle(this._state,r),e?this._state:fe._hex(this._state)}}function pe(e){return fe.hashStr(e)}Object.defineProperty(fe,"stateIdentity",{enumerable:!0,configurable:!0,writable:!0,value:new Int32Array([1732584193,-271733879,-1732584194,271733878])}),Object.defineProperty(fe,"buffer32Identity",{enumerable:!0,configurable:!0,writable:!0,value:new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])}),Object.defineProperty(fe,"hexChars",{enumerable:!0,configurable:!0,writable:!0,value:"0123456789abcdef"}),Object.defineProperty(fe,"hexOut",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(fe,"onePassHasher",{enumerable:!0,configurable:!0,writable:!0,value:new fe}),"5d41402abc4b2a76b9719d911017c592"!==fe.hashStr("hello")&&console.error("Md5 self test failed.");class ve{constructor(e,t,i,r){Object.defineProperty(this,"stale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ha1",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"username",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"password",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cnonce",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"nc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ncHex",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"algorithm",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"realm",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"nonce",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"opaque",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"qop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"method",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"uri",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logger=e.getLogger("sipjs.digestauthentication"),this.username=i,this.password=r,this.ha1=t,this.nc=0,this.ncHex="00000000"}authenticate(e,t,i){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=C(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(i),!0}toString(){const 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(", ")}updateNcHex(){const e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e}calculateResponse(e){let t,i;t=this.ha1,""!==t&&void 0!==t||(t=pe(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(i=pe(this.method+":"+this.uri),this.response=pe(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+i)):"auth-int"===this.qop?(i=pe(this.method+":"+this.uri+":"+pe(e||"")),this.response=pe(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+i)):void 0===this.qop&&(i=pe(this.method+":"+this.uri),this.response=pe(t+":"+this.nonce+":"+i))}}!function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(he||(he={}));class me{constructor(e,t,i){Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"category",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"label",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logger=e,this.category=t,this.label=i}error(e){this.genericLog(he.error,e)}warn(e){this.genericLog(he.warn,e)}log(e){this.genericLog(he.log,e)}debug(e){this.genericLog(he.debug,e)}genericLog(e,t){this.logger.genericLog(e,this.category,this.label,t)}get level(){return this.logger.level}set level(e){this.logger.level=e}}class be{constructor(){Object.defineProperty(this,"builtinEnabled",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"_level",{enumerable:!0,configurable:!0,writable:!0,value:he.log}),Object.defineProperty(this,"_connector",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"loggers",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logger=this.getLogger("sip:loggerfactory")}get level(){return this._level}set level(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:he.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))}get connector(){return this._connector}set connector(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0}getLogger(e,t){if(t&&3===this.level)return new me(this,e,t);if(this.loggers[e])return this.loggers[e];{const t=new me(this,e);return this.loggers[e]=t,t}}genericLog(e,t,i,r){this.level>=e&&this.builtinEnabled&&this.print(e,t,i,r),this.connector&&this.connector(he[e],t,i,r)}print(e,t,i,r){if("string"==typeof r){const e=[new Date,t];i&&e.push(i),r=e.concat(r).join(" | ")}switch(e){case he.error:console.error(r);break;case he.warn:console.warn(r);break;case he.log:console.log(r);break;case he.debug:console.debug(r)}}}function ye(e,t){const i="\r\n";if(t.statusCode<100||t.statusCode>699)throw new TypeError("Invalid statusCode: "+t.statusCode);const r=t.reasonPhrase?t.reasonPhrase:P(t.statusCode);let s="SIP/2.0 "+t.statusCode+" "+r+i;t.statusCode>=100&&t.statusCode,t.statusCode;const n="From: "+e.getHeader("From")+i,o="Call-ID: "+e.callId+i,a="CSeq: "+e.cseq+" "+e.method+i,c=e.getHeaders("via").reduce((e,t)=>e+"Via: "+t+i,"");let l="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){let e=t.toTag;e||(e=A()),l+=";tag="+e}l+=i;let h="";t.supported&&(h="Supported: "+t.supported.join(", ")+i);let d="";t.userAgent&&(d="User-Agent: "+t.userAgent+i);let u="";return t.extraHeaders&&(u=t.extraHeaders.reduce((e,t)=>e+t.trim()+i,"")),s+=c,s+=n,s+=l,s+=a,s+=o,s+=h,s+=d,s+=u,t.body?(s+="Content-Type: "+t.body.contentType+i,s+="Content-Length: "+k(t.body.content)+i+i,s+=t.body.content):s+="Content-Length: 0\r\n\r\n",{message:s}}!function(e){function t(e,t){let i=t,r=0,s=0;if(e.substring(i,i+2).match(/(^\r\n)/))return-2;for(;0===r;){if(s=e.indexOf("\r\n",i),-1===s)return s;!e.substring(s+2,s+4).match(/(^\r\n)/)&&e.charAt(s+2).match(/(^\s+)/)?i=s+2:r=s}return r}function i(e,t,i,r){const s=t.indexOf(":",i),n=t.substring(i,s).trim(),o=t.substring(s+1,r).trim();let a;switch(n.toLowerCase()){case"via":case"v":e.addHeader("via",o),1===e.getHeaders("via").length?(a=e.parseHeader("Via"),a&&(e.via=a,e.viaBranch=a.branch)):a=0;break;case"from":case"f":e.setHeader("from",o),a=e.parseHeader("from"),a&&(e.from=a,e.fromTag=a.getParam("tag"));break;case"to":case"t":e.setHeader("to",o),a=e.parseHeader("to"),a&&(e.to=a,e.toTag=a.getParam("tag"));break;case"record-route":if(a=E.parse(o,"Record_Route"),-1===a){a=void 0;break}if(!(a instanceof Array)){a=void 0;break}a.forEach(t=>{e.addHeader("record-route",o.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",o),a=e.parseHeader("call-id"),a&&(e.callId=o);break;case"contact":case"m":if(a=E.parse(o,"Contact"),-1===a){a=void 0;break}if(!(a instanceof Array)){a=void 0;break}a.forEach(t=>{e.addHeader("contact",o.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",o),a=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",o),a=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",o),a=e.parseHeader("cseq"),a&&(e.cseq=a.value),e instanceof j&&(e.method=a.method);break;case"max-forwards":e.setHeader("max-forwards",o),a=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",o),a=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",o),a=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",o),a=e.parseHeader("refer-to"),a&&(e.referTo=a);break;default:e.addHeader(n.toLowerCase(),o),a=0}return void 0!==a||{error:"error parsing header '"+n+"'"}}e.getHeader=t,e.parseHeader=i,e.parseMessage=function(e,r){let s=0,n=e.indexOf("\r\n");if(-1===n)return void r.warn("no CRLF found, not a SIP message, discarded");const o=e.substring(0,n),a=E.parse(o,"Request_Response");let c,l;if(-1!==a){for(a.status_code?(c=new j,c.statusCode=a.status_code,c.reasonPhrase=a.reason_phrase):(c=new $,c.method=a.method,c.ruri=a.uri),c.data=e,s=n+2;;){if(n=t(e,s),-2===n){l=s+2;break}if(-1===n)return void r.error("malformed message");const o=i(c,e,s,n);if(o&&!0!==o)return void r.error(o.error);s=n+2}return c.hasHeader("content-length")?c.body=e.substr(l,Number(c.getHeader("content-length"))):c.body=e.substring(l),c}r.warn('error parsing first line of SIP message: "'+o+'"')}}(de||(de={}));class we extends o{constructor(e){super(e||"Unspecified transport error.")}}class Se{constructor(e,t,i,r,s){Object.defineProperty(this,"_transport",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"_user",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"_id",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"_state",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"listeners",{enumerable:!0,configurable:!0,writable:!0,value:new Array}),this.logger=t.loggerFactory.getLogger(s,i),this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`)}dispose(){this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`)}get id(){return this._id}get kind(){throw new Error("Invalid kind.")}get state(){return this._state}get transport(){return this._transport}addStateChangeListener(e,t){const i=()=>{this.removeStateChangeListener(i),e()};!0===(null==t?void 0:t.once)?this.listeners.push(i):this.listeners.push(e)}notifyStateChangeListeners(){this.listeners.slice().forEach(e=>e())}removeStateChangeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}logTransportError(e,t){this.logger.error(e.message),this.logger.error(`Transport error occurred in ${this.typeToString()} with id ${this.id}.`),this.logger.error(t)}send(e){return this.transport.send(e).catch(e=>{if(e instanceof we)throw this.onTransportError(e),e;let t;throw t=e&&"string"==typeof e.message?new we(e.message):new we,this.onTransportError(t),t})}setState(e){this.logger.debug(`State change to "${e}" on ${this.typeToString()} with id ${this.id}.`),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.notifyStateChangeListeners()}typeToString(){return"UnknownType"}}class Te extends Se{constructor(e,t,i,r,s){super(t,i,e.viaBranch,r,s),Object.defineProperty(this,"_request",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:i})}get request(){return this._request}}!function(e){e.Accepted="Accepted",e.Calling="Calling",e.Completed="Completed",e.Confirmed="Confirmed",e.Proceeding="Proceeding",e.Terminated="Terminated",e.Trying="Trying"}(ue||(ue={}));class Re extends Te{constructor(e,t,i){super(e,t,i,ue.Proceeding,"sip.transaction.ist"),Object.defineProperty(this,"lastFinalResponse",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lastProvisionalResponse",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"H",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"I",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"L",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"progressExtensionTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}dispose(){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),super.dispose()}get kind(){return"ist"}receiveRequest(e){switch(this.state){case ue.Proceeding:if(e.method===G.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case ue.Accepted:if(e.method===G.INVITE)return;break;case ue.Completed:if(e.method===G.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")})}if(e.method===G.ACK)return void this.stateTransition(ue.Confirmed);break;case ue.Confirmed:case ue.Terminated:if(e.method===G.INVITE||e.method===G.ACK)return;break;default:throw new Error(`Invalid state ${this.state}`)}const t=`INVITE server transaction received unexpected ${e.method} request while in state ${this.state}.`;this.logger.warn(t)}receiveResponse(e,t){if(e<100||e>699)throw new Error(`Invalid status code ${e}`);switch(this.state){case ue.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 1xx response.")});if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(ue.Accepted),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(ue.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send non-2xx final response.")});break;case ue.Accepted:if(e>=200&&e<=299)return void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});break;case ue.Completed:case ue.Confirmed:case ue.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const i=`INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(i),new Error(i)}retransmitAcceptedResponse(){this.state===ue.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")})}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e)}typeToString(){return"INVITE server transaction"}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case ue.Proceeding:t();break;case ue.Accepted:case ue.Completed:this.state!==ue.Proceeding&&t();break;case ue.Confirmed:this.state!==ue.Completed&&t();break;case ue.Terminated:this.state!==ue.Accepted&&this.state!==ue.Completed&&this.state!==ue.Confirmed&&t();break;default:t()}this.stopProgressExtensionTimer(),e===ue.Accepted&&(this.L=setTimeout(()=>this.timerL(),B.TIMER_L)),e===ue.Completed&&(this.H=setTimeout(()=>this.timerH(),B.TIMER_H)),e===ue.Confirmed&&(this.I=setTimeout(()=>this.timerI(),B.TIMER_I)),e===ue.Terminated&&this.dispose(),this.setState(e)}startProgressExtensionTimer(){void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval(()=>{if(this.logger.debug(`Progress extension timer expired for INVITE server transaction ${this.id}.`),!this.lastProvisionalResponse)throw new Error("Last provisional response undefined.");this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")})},B.PROVISIONAL_RESPONSE_INTERVAL))}stopProgressExtensionTimer(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)}timerG(){}timerH(){this.logger.debug(`Timer H expired for INVITE server transaction ${this.id}.`),this.state===ue.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(ue.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(ue.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===ue.Accepted&&this.stateTransition(ue.Terminated)}}class Ee extends Se{constructor(e,t,i,r,s){super(t,i,Ee.makeId(e),r,s),Object.defineProperty(this,"_request",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:i}),e.setViaHeader(this.id,t.protocol)}static makeId(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())}get request(){return this._request}onRequestTimeout(){this.user.onRequestTimeout&&this.user.onRequestTimeout()}}class Ie extends Ee{constructor(e,t,i){super(e,t,i,ue.Trying,"sip.transaction.nict"),Object.defineProperty(this,"F",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"K",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.F=setTimeout(()=>this.timerF(),B.TIMER_F),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),super.dispose()}get kind(){return"nict"}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error(`Invalid status code ${t}`);switch(this.state){case ue.Trying:if(t>=100&&t<=199)return this.stateTransition(ue.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(ue.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case ue.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(ue.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case ue.Completed:case ue.Terminated:return;default:throw new Error(`Invalid state ${this.state}`)}const i=`Non-INVITE client transaction received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(i)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(ue.Terminated,!0)}typeToString(){return"non-INVITE client transaction"}stateTransition(e,t=!1){const i=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case ue.Trying:i();break;case ue.Proceeding:this.state!==ue.Trying&&i();break;case ue.Completed:this.state!==ue.Trying&&this.state!==ue.Proceeding&&i();break;case ue.Terminated:this.state!==ue.Trying&&this.state!==ue.Proceeding&&this.state!==ue.Completed&&(t||i());break;default:i()}e===ue.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(()=>this.timerK(),B.TIMER_K)),e===ue.Terminated&&this.dispose(),this.setState(e)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==ue.Trying&&this.state!==ue.Proceeding||(this.onRequestTimeout(),this.stateTransition(ue.Terminated))}timerK(){this.state===ue.Completed&&this.stateTransition(ue.Terminated)}}class Ce{constructor(e,t){Object.defineProperty(this,"core",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"dialogState",{enumerable:!0,configurable:!0,writable:!0,value:t}),this.core.dialogs.set(this.id,this)}static initialDialogStateForUserAgentClient(e,t){const i=t.getHeaders("record-route").reverse(),r=t.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof b))throw new Error("Contact not instance of NameAddrHeader.");const s=r.uri,n=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.");const l=e.from.uri,h=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:n,remoteSequenceNumber:undefined,localURI:l,remoteURI:h,remoteTarget:s,routeSet:i,secure:!1}}static initialDialogStateForUserAgentServer(e,t,i=!1){const r=e.getHeaders("record-route"),s=e.parseHeader("contact");if(!s)throw new Error("Contact undefined.");if(!(s instanceof b))throw new Error("Contact not instance of NameAddrHeader.");const n=s.uri,o=e.cseq,a=e.callId,c=t,l=e.fromTag,h=e.from.uri;return{id:a+c+l,early:i,callId:a,localTag:c,remoteTag:l,localSequenceNumber:undefined,remoteSequenceNumber:o,localURI:e.to.uri,remoteURI:h,remoteTarget:n,routeSet:r,secure:!1}}dispose(){this.core.dialogs.delete(this.id)}get id(){return this.dialogState.id}get early(){return this.dialogState.early}get callId(){return this.dialogState.callId}get localTag(){return this.dialogState.localTag}get remoteTag(){return this.dialogState.remoteTag}get localSequenceNumber(){return this.dialogState.localSequenceNumber}get remoteSequenceNumber(){return this.dialogState.remoteSequenceNumber}get localURI(){return this.dialogState.localURI}get remoteURI(){return this.dialogState.remoteURI}get remoteTarget(){return this.dialogState.remoteTarget}get routeSet(){return this.dialogState.routeSet}get secure(){return this.dialogState.secure}get userAgentCore(){return this.core}confirm(){this.dialogState.early=!1}receiveRequest(e){if(e.method!==G.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)}}recomputeRouteSet(e){this.dialogState.routeSet=e.getHeaders("record-route").reverse()}createOutgoingRequestMessage(e,t){const i=this.remoteURI,r=this.remoteTag,s=this.localURI,n=this.localTag,o=this.callId;let a;a=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;const c=this.remoteTarget,l=this.routeSet,h=t&&t.extraHeaders,d=t&&t.body;return this.userAgentCore.makeOutgoingRequestMessage(e,c,s,i,{callId:o,cseq:a,fromTag:n,toTag:r,routeSet:l},h,d)}incrementLocalSequenceNumber(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1}sequenceGuard(e){return e.method===G.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))}}class Pe extends Ee{constructor(e,t,i){super(e,t,i,ue.Calling,"sip.transaction.ict"),Object.defineProperty(this,"B",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"D",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"M",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ackRetransmissionCache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),this.B=setTimeout(()=>this.timerB(),B.TIMER_B),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){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),super.dispose()}get kind(){return"ict"}ackResponse(e){const t=e.toTag;if(!t)throw new Error("To tag undefined.");const i="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(i,this.transport.protocol),this.ackRetransmissionCache.set(t,e),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send ACK to 2xx response.")})}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error(`Invalid status code ${t}`);switch(this.state){case ue.Calling:if(t>=100&&t<=199)return this.stateTransition(ue.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(ue.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(ue.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case ue.Proceeding:if(t>=100&&t<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(ue.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(ue.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case ue.Accepted:if(t>=200&&t<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));const t=this.ackRetransmissionCache.get(e.toTag);return t?void this.send(t.toString()).catch(e=>{this.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")}):void 0}break;case ue.Completed:if(t>=300&&t<=699)return void this.ack(e);break;case ue.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const i=`Received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(i)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(ue.Terminated,!0)}typeToString(){return"INVITE client transaction"}ack(e){const t=this.request.ruri,i=this.request.callId,r=this.request.cseq,s=this.request.getHeader("from"),n=e.getHeader("to"),o=this.request.getHeader("via"),a=this.request.getHeader("route");if(!s)throw new Error("From undefined.");if(!n)throw new Error("To undefined.");if(!o)throw new Error("Via undefined.");let c=`ACK ${t} SIP/2.0\r\n`;a&&(c+=`Route: ${a}\r\n`),c+=`Via: ${o}\r\n`,c+=`To: ${n}\r\n`,c+=`From: ${s}\r\n`,c+=`Call-ID: ${i}\r\n`,c+=`CSeq: ${r} ACK\r\n`,c+="Max-Forwards: 70\r\n",c+="Content-Length: 0\r\n\r\n",this.send(c).catch(e=>{this.logTransportError(e,"Failed to send ACK to non-2xx response.")})}stateTransition(e,t=!1){const i=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case ue.Calling:i();break;case ue.Proceeding:this.state!==ue.Calling&&i();break;case ue.Accepted:case ue.Completed:this.state!==ue.Calling&&this.state!==ue.Proceeding&&i();break;case ue.Terminated:this.state!==ue.Calling&&this.state!==ue.Accepted&&this.state!==ue.Completed&&(t||i());break;default:i()}this.B&&(clearTimeout(this.B),this.B=void 0),ue.Proceeding,e===ue.Completed&&(this.D=setTimeout(()=>this.timerD(),B.TIMER_D)),e===ue.Accepted&&(this.M=setTimeout(()=>this.timerM(),B.TIMER_M)),e===ue.Terminated&&this.dispose(),this.setState(e)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===ue.Calling&&(this.onRequestTimeout(),this.stateTransition(ue.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===ue.Completed&&this.stateTransition(ue.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===ue.Accepted&&this.stateTransition(ue.Terminated)}}class Ae{constructor(e,t,i,r){Object.defineProperty(this,"transactionConstructor",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"core",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_transaction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"credentials",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"challenged",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"stale",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}cancel(e,t={}){if(!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.");const i=this.core.makeOutgoingRequestMessage(G.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},t.extraHeaders);return i.branch=this.message.branch,this.message.headers.Route&&(i.headers.Route=this.message.headers.Route),e&&i.setHeader("Reason",e),this.transaction.state===ue.Proceeding?new Ae(Ie,this.core,i):this.transaction.addStateChangeListener(()=>{this.transaction&&this.transaction.state===ue.Proceeding&&new Ae(Ie,this.core,i)},{once:!0}),i}authenticationGuard(e,t){const i=e.statusCode;if(!i)throw new Error("Response status code undefined.");if(401!==i&&407!==i)return!0;let r,s;if(401===i?(r=e.parseHeader("www-authenticate"),s="authorization"):(r=e.parseHeader("proxy-authenticate"),s="proxy-authorization"),!r)return this.logger.warn(i+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==r.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,r))return!0;this.challenged=!0,r.stale&&(this.stale=!0);let n=this.message.cseq+=1;return t&&t.localSequenceNumber&&(t.incrementLocalSequenceNumber(),n=this.message.cseq=t.localSequenceNumber),this.message.setHeader("cseq",n+" "+this.message.method),this.message.setHeader(s,this.credentials.toString()),this.init(),!1}onRequestTimeout(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");const e=new j;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)}onTransportError(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");const t=new j;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)}receiveResponse(e){if(!this.authenticationGuard(e))return;const 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 ${t}`)}}init(){const e={loggerFactory:this.loggerFactory,onRequestTimeout:()=>this.onRequestTimeout(),onStateChange:e=>{e===ue.Terminated&&(this.core.userAgentClients.delete(i),t===this._transaction&&this.dispose())},onTransportError:e=>this.onTransportError(e),receiveResponse:e=>this.receiveResponse(e)},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const i=t.id+t.request.method;this.core.userAgentClients.set(i,this)}}class Oe extends Ae{constructor(e,t,i){const r=e.createOutgoingRequestMessage(G.BYE,i);super(Ie,e.userAgentCore,r,t),e.dispose()}}class ke extends Te{constructor(e,t,i){super(e,t,i,ue.Trying,"sip.transaction.nist"),Object.defineProperty(this,"lastResponse",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"J",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}dispose(){this.J&&(clearTimeout(this.J),this.J=void 0),super.dispose()}get kind(){return"nist"}receiveRequest(e){switch(this.state){case ue.Trying:break;case ue.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")});break;case ue.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")});break;case ue.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}}receiveResponse(e,t){if(e<100||e>699)throw new Error(`Invalid status code ${e}`);if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case ue.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(ue.Proceeding),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send provisional response.")});if(e>=200&&e<=699)return this.stateTransition(ue.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case ue.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(ue.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case ue.Completed:return;case ue.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const i=`Non-INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(i),new Error(i)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(ue.Terminated,!0)}typeToString(){return"non-INVITE server transaction"}stateTransition(e,t=!1){const i=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case ue.Trying:i();break;case ue.Proceeding:this.state!==ue.Trying&&i();break;case ue.Completed:this.state!==ue.Trying&&this.state!==ue.Proceeding&&i();break;case ue.Terminated:this.state!==ue.Proceeding&&this.state!==ue.Completed&&(t||i());break;default:i()}e===ue.Completed&&(this.J=setTimeout(()=>this.timerJ(),B.TIMER_J)),e===ue.Terminated&&this.dispose(),this.setState(e)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===ue.Completed&&this.stateTransition(ue.Terminated)}}class De{constructor(e,t,i,r){Object.defineProperty(this,"transactionConstructor",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"core",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"toTag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_transaction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=i.toTag?i.toTag:A(),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}accept(e={statusCode:200}){if(!this.acceptable)throw new W(`${this.message.method} not acceptable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<200||t>299)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}progress(e={statusCode:180}){if(!this.progressable)throw new W(`${this.message.method} not progressable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<101||t>199)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}redirect(e,t={statusCode:302}){if(!this.redirectable)throw new W(`${this.message.method} not redirectable in state ${this.transaction.state}.`);const i=t.statusCode;if(i<300||i>399)throw new TypeError(`Invalid statusCode: ${i}`);const r=new Array;e.forEach(e=>r.push(`Contact: ${e.toString()}`)),t.extraHeaders=(t.extraHeaders||[]).concat(r);return this.reply(t)}reject(e={statusCode:480}){if(!this.rejectable)throw new W(`${this.message.method} not rejectable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<400||t>699)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}trying(e){if(!this.tryingable)throw new W(`${this.message.method} not tryingable in state ${this.transaction.state}.`);return this.reply({statusCode:100})}receiveCancel(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)}get acceptable(){if(this.transaction instanceof Re)return this.transaction.state===ue.Proceeding||this.transaction.state===ue.Accepted;if(this.transaction instanceof ke)return this.transaction.state===ue.Trying||this.transaction.state===ue.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof Re)return this.transaction.state===ue.Proceeding;if(this.transaction instanceof ke)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof Re)return this.transaction.state===ue.Proceeding;if(this.transaction instanceof ke)return this.transaction.state===ue.Trying||this.transaction.state===ue.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof Re)return this.transaction.state===ue.Proceeding;if(this.transaction instanceof ke)return this.transaction.state===ue.Trying||this.transaction.state===ue.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof Re)return this.transaction.state===ue.Proceeding;if(this.transaction instanceof ke)return this.transaction.state===ue.Trying;throw new Error("Unknown transaction type.")}reply(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;const t=ye(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t}init(){const e={loggerFactory:this.loggerFactory,onStateChange:e=>{e===ue.Terminated&&(this.core.userAgentServers.delete(i),this.dispose())},onTransportError:e=>{this.logger.error(e.message),this.delegate&&this.delegate.onTransportError?this.delegate.onTransportError(e):this.logger.error("User agent server response transport error.")}},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const i=t.id;this.core.userAgentServers.set(t.id,this)}}class $e extends De{constructor(e,t,i){super(ke,e.userAgentCore,t,i)}}class je extends Ae{constructor(e,t,i){const r=e.createOutgoingRequestMessage(G.INFO,i);super(Ie,e.userAgentCore,r,t)}}class _e extends De{constructor(e,t,i){super(ke,e.userAgentCore,t,i)}}class He extends Ae{constructor(e,t,i){super(Ie,e,t,i)}}class Me extends De{constructor(e,t,i){super(ke,e,t,i)}}class xe extends Ae{constructor(e,t,i){const r=e.createOutgoingRequestMessage(G.NOTIFY,i);super(Ie,e.userAgentCore,r,t)}}class qe extends De{constructor(e,t,i){const r=void 0!==e.userAgentCore?e.userAgentCore:e;super(ke,r,t,i)}}class Ne extends Ae{constructor(e,t,i){const r=e.createOutgoingRequestMessage(G.PRACK,i);super(Ie,e.userAgentCore,r,t),e.signalingStateTransition(r)}}class Fe extends De{constructor(e,t,i){super(ke,e.userAgentCore,t,i),Object.defineProperty(this,"dialog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e.signalingStateTransition(t),this.dialog=e}accept(e={statusCode:200}){return e.body&&this.dialog.signalingStateTransition(e.body),super.accept(e)}}class Ue extends Ae{constructor(e,t,i){const r=e.createOutgoingRequestMessage(G.INVITE,i);super(Pe,e.userAgentCore,r,t),Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dialog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.delegate=t,e.signalingStateTransition(r),e.reinviteUserAgentClient=this,this.dialog=e}receiveResponse(e){if(!this.authenticationGuard(e,this.dialog))return;const 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,session:this.dialog,prack:e=>{throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(t):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:e=>this.dialog.ack(e)});break;case/^3[0-9]{2}$/.test(t):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(t):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 ${t}`)}}}class Le extends De{constructor(e,t,i){super(Re,e.userAgentCore,t,i),Object.defineProperty(this,"dialog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e.reinviteUserAgentServer=this,this.dialog=e}accept(e={statusCode:200}){e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(this.dialog.routeSet.map(e=>`Record-Route: ${e}`));const t=super.accept(e),i=this.dialog,r=Object.assign(Object.assign({},t),{session:i});return e.body&&this.dialog.signalingStateTransition(e.body),this.dialog.reConfirm(),r}progress(e={statusCode:180}){const t=super.progress(e),i=this.dialog,r=Object.assign(Object.assign({},t),{session:i});return e.body&&this.dialog.signalingStateTransition(e.body),r}redirect(e,t={statusCode:302}){throw this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")}reject(e={statusCode:488}){return this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,super.reject(e)}}class Be extends Ae{constructor(e,t,i){const r=e.createOutgoingRequestMessage(G.REFER,i);super(Ie,e.userAgentCore,r,t)}}class We extends De{constructor(e,t,i){const r=void 0!==e.userAgentCore?e.userAgentCore:e;super(ke,r,t,i)}}class Ge extends Ce{constructor(e,t,i,r){super(t,i),Object.defineProperty(this,"initialTransaction",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reinviteUserAgentClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reinviteUserAgentServer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_signalingState",{enumerable:!0,configurable:!0,writable:!0,value:F.Initial}),Object.defineProperty(this,"_offer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_answer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_rollbackOffer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_rollbackAnswer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ackWait",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ackProcessing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"invite2xxTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"rseq",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.delegate=r,e instanceof Re&&(this.ackWait=!0),this.early||this.start2xxRetransmissionTimer(),this.signalingStateTransition(e.request),this.logger=t.loggerFactory.getLogger("sip.invite-dialog"),this.logger.log(`INVITE dialog ${this.id} constructed`)}dispose(){super.dispose(),this._signalingState=F.Closed,this._offer=void 0,this._answer=void 0,this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.logger.log(`INVITE dialog ${this.id} destroyed`)}get sessionState(){return this.early?N.Early:this.ackWait?N.AckWait:this._signalingState===F.Closed?N.Terminated:N.Confirmed}get signalingState(){return this._signalingState}get offer(){return this._offer}get answer(){return this._answer}confirm(){this.early&&this.start2xxRetransmissionTimer(),super.confirm()}reConfirm(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()}ack(e={}){let t;if(this.logger.log(`INVITE dialog ${this.id} sending ACK request`),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof Pe))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof Pe))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}const i=this.createOutgoingRequestMessage(G.ACK,{cseq:t.request.cseq,extraHeaders:e.extraHeaders,body:e.body});return t.ackResponse(i),this.signalingStateTransition(i),{message:i}}bye(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending BYE request`),this.initialTransaction instanceof Re){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==ue.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 Oe(this,e,t)}info(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending INFO request`),this.early)throw new Error("Dialog not confirmed.");return new je(this,e,t)}invite(e,t){if(this.logger.log(`INVITE dialog ${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 Ue(this,e,t)}message(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending MESSAGE request`),this.early)throw new Error("Dialog not confirmed.");const i=this.createOutgoingRequestMessage(G.MESSAGE,t);return new He(this.core,i,e)}notify(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending NOTIFY request`),this.early)throw new Error("Dialog not confirmed.");return new xe(this,e,t)}prack(e,t){return this.logger.log(`INVITE dialog ${this.id} sending PRACK request`),new Ne(this,e,t)}refer(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending REFER request`),this.early)throw new Error("Dialog not confirmed.");return new Be(this,e,t)}receiveRequest(e){if(this.logger.log(`INVITE dialog ${this.id} received ${e.method} request`),e.method!==G.ACK)if(this.sequenceGuard(e)){if(super.receiveRequest(e),e.method===G.INVITE){const t=()=>{const e=this.ackWait?"waiting for initial ACK":"processing initial ACK";this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${e}`);let t="RFC 5407 suggests the following to avoid this race condition... ";t+=" Note: Implementation issues are outside the scope of this document,",t+=" but the following tip is provided for avoiding race conditions of",t+=" this type. The caller can delay sending re-INVITE F6 for some period",t+=" of time (2 seconds, perhaps), after which the caller can reasonably",t+=" assume that its ACK has been received. Implementors can decouple the",t+=" actions of the user (e.g., pressing the hold button) from the actions",t+=" of the protocol (the sending of re-INVITE F6), so that the UA can",t+=" behave like this. In this case, it is the implementor's choice as to",t+=" how long to wait. In most cases, such an implementation may be",t+=" useful to prevent the type of race condition shown in this section.",t+=" This document expresses no preference about whether or not they",t+=" should wait for an ACK to be delivered. After considering the impact",t+=" on user experience, implementors should decide whether or not to wait",t+=" for a while, because the user experience depends on the",t+=" implementation and has no direct bearing on protocol behavior.",this.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=[`Retry-After: ${Math.floor(10*Math.random())+1}`];if(this.ackProcessing)return this.core.replyStateless(e,{statusCode:500,extraHeaders:i}),void t();if(this.ackWait&&this.signalingState!==F.Stable)return this.core.replyStateless(e,{statusCode:500,extraHeaders:i}),void t();if(this.reinviteUserAgentServer)return void this.core.replyStateless(e,{statusCode:500,extraHeaders:i});if(this.reinviteUserAgentClient)return void this.core.replyStateless(e,{statusCode:491})}if(e.method===G.INVITE){const t=e.parseHeader("contact");if(!t)throw new Error("Contact undefined.");if(!(t instanceof b))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=t.uri}switch(e.method){case G.BYE:{const t=new $e(this,e);this.delegate&&this.delegate.onBye?this.delegate.onBye(t):t.accept(),this.dispose()}break;case G.INFO:{const t=new _e(this,e);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(t):t.reject({statusCode:469,extraHeaders:["Recv-Info:"]})}break;case G.INVITE:{const t=new Le(this,e);this.signalingStateTransition(e),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(t):t.reject({statusCode:488})}break;case G.MESSAGE:{const t=new Me(this.core,e);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case G.NOTIFY:{const t=new qe(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(t):t.accept()}break;case G.PRACK:{const t=new Fe(this,e);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(t):t.accept()}break;case G.REFER:{const t=new We(this,e);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):t.reject()}break;default:this.logger.log(`INVITE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501})}}else this.logger.log(`INVITE dialog ${this.id} rejected out of order ${e.method} request.`);else{if(this.ackWait){if(this.initialTransaction instanceof Pe)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.initialTransaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.reinviteUserAgentServer.transaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.reinviteUserAgentServer=void 0}if(this.signalingStateTransition(e),this.delegate&&this.delegate.onAck){const t=this.delegate.onAck({message:e});t instanceof Promise&&(this.ackProcessing=!0,t.then(()=>this.ackProcessing=!1).catch(()=>this.ackProcessing=!1))}}}reliableSequenceGuard(e){const t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){const t=e.getHeader("require"),i=e.getHeader("rseq"),r=t&&t.includes("100rel")&&i?Number(i):void 0;if(r){if(this.rseq&&this.rseq+1!==r)return!1;this.rseq=this.rseq?this.rseq+1:r}}return!0}signalingStateRollback(){this._signalingState!==F.HaveLocalOffer&&this.signalingState!==F.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=F.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(e){const t=q(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===F.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof $)switch(this._signalingState){case F.Initial:case F.Stable:this._signalingState=F.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case F.HaveLocalOffer:this._signalingState=F.Stable,this._answer=t;break;case F.HaveRemoteOffer:case F.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof j)switch(this._signalingState){case F.Initial:case F.Stable:this._signalingState=F.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case F.HaveLocalOffer:this._signalingState=F.Stable,this._answer=t;break;case F.HaveRemoteOffer:case F.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof _)switch(this._signalingState){case F.Initial:case F.Stable:this._signalingState=F.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case F.HaveLocalOffer:break;case F.HaveRemoteOffer:this._signalingState=F.Stable,this._answer=t;break;case F.Closed:break;default:throw new Error("Unexpected signaling state.")}if(x(e))switch(this._signalingState){case F.Initial:case F.Stable:this._signalingState=F.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case F.HaveLocalOffer:break;case F.HaveRemoteOffer:this._signalingState=F.Stable,this._answer=t;break;case F.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof Re){const e=this.initialTransaction;let t=B.T1;const i=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,B.T2),this.invite2xxTimer=setTimeout(i,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(i,t);const r=()=>{e.state===ue.Terminated&&(e.removeStateChangeListener(r),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.ackWait&&(this.delegate&&this.delegate.onAckTimeout?this.delegate.onAckTimeout():this.bye()))};e.addStateChangeListener(r)}}startReInvite2xxRetransmissionTimer(){if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof Re){const e=this.reinviteUserAgentServer.transaction;let t=B.T1;const i=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,B.T2),this.invite2xxTimer=setTimeout(i,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(i,t);const r=()=>{e.state===ue.Terminated&&(e.removeStateChangeListener(r),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};e.addStateChangeListener(r)}}}class Ve extends Ae{constructor(e,t,i){super(Pe,e,t,i),Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"confirmedDialogAcks",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"confirmedDialogs",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"earlyDialogs",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),this.delegate=i}dispose(){this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),super.dispose()}onTransportError(e){if(this.transaction.state===ue.Calling)return super.onTransportError(e);this.logger.error(e.message),this.logger.error("User agent client request transport error while sending ACK.")}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(t):{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.");const t=Ce.initialDialogStateForUserAgentClient(this.message,e);let i=this.earlyDialogs.get(t.id);if(!i){const e=this.transaction;if(!(e instanceof Pe))throw new Error("Transaction not instance of InviteClientTransaction.");i=new Ge(e,this.core,t),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!==F.Initial&&i.signalingState!==F.HaveLocalOffer||i.signalingStateTransition(e);const r=i;this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:r,prack:e=>r.prack(void 0,e)})}return;case/^2[0-9]{2}$/.test(t):{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.");const t=Ce.initialDialogStateForUserAgentClient(this.message,e);let i=this.confirmedDialogs.get(t.id);if(i){const e=this.confirmedDialogAcks.get(t.id);if(e){const t=this.transaction;if(!(t instanceof Pe))throw new Error("Client transaction not instance of InviteClientTransaction.");t.ackResponse(e.message)}return}if(i=this.earlyDialogs.get(t.id),i)i.confirm(),i.recomputeRouteSet(e),this.earlyDialogs.delete(i.id),this.confirmedDialogs.set(i.id,i);else{const e=this.transaction;if(!(e instanceof Pe))throw new Error("Transaction not instance of InviteClientTransaction.");i=new Ge(e,this.core,t),this.confirmedDialogs.set(i.id,i)}i.signalingState!==F.Initial&&i.signalingState!==F.HaveLocalOffer||i.signalingStateTransition(e);const r=i;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:r,ack:e=>{const t=r.ack(e);return this.confirmedDialogAcks.set(r.id,t),t}});else{const e=r.ack();this.confirmedDialogAcks.set(r.id,e)}}return;case/^3[0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error(`Invalid status code ${t}`)}}}class Ke extends De{constructor(e,t,i){super(Re,e,t,i),Object.defineProperty(this,"core",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"confirmedDialog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"earlyDialog",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(e={statusCode:200}){if(!this.acceptable)throw new W(`${this.message.method} not acceptable in state ${this.transaction.state}.`);if(!this.confirmedDialog)if(this.earlyDialog)this.earlyDialog.confirm(),this.confirmedDialog=this.earlyDialog,this.earlyDialog=void 0;else{const e=this.transaction;if(!(e instanceof Re))throw new Error("Transaction not instance of InviteClientTransaction.");const t=Ce.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new Ge(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>`Record-Route: ${e}`),i=`Contact: ${this.core.configuration.contact.toString()}`,r="Allow: "+V.toString();if(!e.body)if(this.confirmedDialog.signalingState===F.Stable)e.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===F.Initial||this.confirmedDialog.signalingState===F.HaveRemoteOffer)throw new Error("Response must have a body.");e.statusCode=e.statusCode||200,e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(r),e.extraHeaders.push(i);const s=super.accept(e),n=this.confirmedDialog,o=Object.assign(Object.assign({},s),{session:n});return e.body&&this.confirmedDialog.signalingState!==F.Stable&&this.confirmedDialog.signalingStateTransition(e.body),o}progress(e={statusCode:180}){if(!this.progressable)throw new W(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const e=this.transaction;if(!(e instanceof Re))throw new Error("Transaction not instance of InviteClientTransaction.");const t=Ce.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new Ge(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>`Record-Route: ${e}`),i=`Contact: ${this.core.configuration.contact}`;e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(i);const r=super.progress(e),s=this.earlyDialog,n=Object.assign(Object.assign({},r),{session:s});return e.body&&this.earlyDialog.signalingState!==F.Stable&&this.earlyDialog.signalingStateTransition(e.body),n}redirect(e,t={statusCode:302}){return super.redirect(e,t)}reject(e={statusCode:486}){return super.reject(e)}}class ze extends Ae{constructor(e,t,i){super(Ie,e,t,i)}}class Ye extends Ae{constructor(e,t,i){super(Ie,e,t,i)}}class Je extends De{constructor(e,t,i){super(ke,e,t,i),Object.defineProperty(this,"core",{enumerable:!0,configurable:!0,writable:!0,value:e})}}class Ze extends Ae{constructor(e,t,i){const r=e.createOutgoingRequestMessage(G.SUBSCRIBE,i);super(Ie,e.userAgentCore,r,t),Object.defineProperty(this,"dialog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.dialog=e}waitNotifyStop(){}receiveResponse(e){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);this.dialog.subscriptionExpires>e&&(this.dialog.subscriptionExpires=e)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(e.statusCode&&e.statusCode>=400&&e.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(e.statusCode)&&this.dialog.terminate()}super.receiveResponse(e)}}class Xe extends Ce{constructor(e,t,i,r,s,n){super(r,s),Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_autoRefresh",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_subscriptionEvent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_subscriptionExpires",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_subscriptionExpiresInitial",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_subscriptionExpiresLastSet",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_subscriptionRefresh",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_subscriptionRefreshLastSet",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_subscriptionState",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"N",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.delegate=n,this._autoRefresh=!1,this._subscriptionEvent=e,this._subscriptionExpires=t,this._subscriptionExpiresInitial=t,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this._subscriptionState=i,this.logger=r.loggerFactory.getLogger("sip.subscribe-dialog"),this.logger.log(`SUBSCRIBE dialog ${this.id} constructed`)}static initialDialogStateForSubscription(e,t){const i=t.getHeaders("record-route"),r=t.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof b))throw new Error("Contact not instance of NameAddrHeader.");const s=r.uri,n=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:n,remoteSequenceNumber:undefined,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:s,routeSet:i,secure:!1}}dispose(){super.dispose(),this.N&&(clearTimeout(this.N),this.N=void 0),this.refreshTimerClear(),this.logger.log(`SUBSCRIBE dialog ${this.id} destroyed`)}get autoRefresh(){return this._autoRefresh}set autoRefresh(e){this._autoRefresh=!0,this.refreshTimerSet()}get subscriptionEvent(){return this._subscriptionEvent}get subscriptionExpires(){const e=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,t=this._subscriptionExpires-e;return Math.max(t,0)}set subscriptionExpires(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){const t=this.subscriptionRefresh;(void 0===t||t>=e)&&this.refreshTimerSet()}}get subscriptionExpiresInitial(){return this._subscriptionExpiresInitial}get subscriptionRefresh(){if(void 0===this._subscriptionRefresh||void 0===this._subscriptionRefreshLastSet)return;const e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}get subscriptionState(){return this._subscriptionState}receiveRequest(e){if(this.logger.log(`SUBSCRIBE dialog ${this.id} received ${e.method} request`),this.sequenceGuard(e))if(super.receiveRequest(e),e.method===G.NOTIFY)this.onNotify(e);else this.logger.log(`SUBSCRIBE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501});else this.logger.log(`SUBSCRIBE dialog ${this.id} rejected out of order ${e.method} request.`)}refresh(){const e="Allow: "+V.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)}subscribe(e,t={}){var i;if(this.subscriptionState!==oe.Pending&&this.subscriptionState!==oe.Active)throw new Error(`Invalid state ${this.subscriptionState}. May only re-subscribe while in state "pending" or "active".`);this.logger.log(`SUBSCRIBE dialog ${this.id} sending SUBSCRIBE request`);const r=new Ze(this,e,t);return this.N&&(clearTimeout(this.N),this.N=void 0),(null===(i=t.extraHeaders)||void 0===i?void 0:i.includes("Expires: 0"))||(this.N=setTimeout(()=>this.timerN(),B.TIMER_N)),r}terminate(){this.stateTransition(oe.Terminated),this.onTerminated()}unsubscribe(){const e="Allow: "+V.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)}onNotify(e){const t=e.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return void this.core.replyStateless(e,{statusCode:489});this.N&&(clearTimeout(this.N),this.N=void 0);const i=e.parseHeader("Subscription-State");if(!i||!i.state)return void this.core.replyStateless(e,{statusCode:489});const r=i.state,s=i.expires?Math.max(i.expires,0):void 0;switch(r){case"pending":this.stateTransition(oe.Pending,s);break;case"active":this.stateTransition(oe.Active,s);break;case"terminated":this.stateTransition(oe.Terminated,s);break;default:this.logger.warn("Unrecognized subscription state.")}const n=new qe(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(n):n.accept()}onRefresh(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)}onTerminated(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()}refreshTimerClear(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}refreshTimerSet(){if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){const e=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(e/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout(()=>{this.refreshTimer=void 0,this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this.onRefresh(this.refresh())},e)}}stateTransition(e,t){const i=()=>{this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${e}`)};switch(e){case oe.Initial:case oe.NotifyWait:return void i();case oe.Pending:if(this.subscriptionState!==oe.NotifyWait&&this.subscriptionState!==oe.Pending)return void i();break;case oe.Active:case oe.Terminated:if(this.subscriptionState!==oe.NotifyWait&&this.subscriptionState!==oe.Pending&&this.subscriptionState!==oe.Active)return void i();break;default:return void i()}e===oe.Pending&&t&&(this.subscriptionExpires=t),e===oe.Active&&t&&(this.subscriptionExpires=t),e===oe.Terminated&&this.dispose(),this._subscriptionState=e}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==oe.Terminated&&(this.stateTransition(oe.Terminated),this.onTerminated())}}class Qe extends Ae{constructor(e,t,i){const r=t.getHeader("Event");if(!r)throw new Error("Event undefined");const s=t.getHeader("Expires");if(!s)throw new Error("Expires undefined");super(Ie,e,t,i),Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dialog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"subscriberId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"subscriptionExpires",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"subscriptionExpiresRequested",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"subscriptionEvent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"subscriptionState",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"N",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.delegate=i,this.subscriberId=t.callId+t.fromTag+r,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(s),this.subscriptionEvent=r,this.subscriptionState=oe.NotifyWait,this.waitNotifyStart()}dispose(){super.dispose()}onNotify(e){const t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});const i=e.message.parseHeader("Subscription-State");if(!i||!i.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});const r=i.state;switch(r){case"pending":case"active":case"terminated":break;default:return this.logger.warn(`Invalid subscription state ${r}`),void e.reject({statusCode:489})}if("terminated"!==r){if(!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=i.expires?Math.min(this.subscriptionExpires,Math.max(i.expires,0)):this.subscriptionExpires,r){case"pending":this.subscriptionState=oe.Pending;break;case"active":this.subscriptionState=oe.Active;break;case"terminated":this.subscriptionState=oe.Terminated;break;default:throw new Error(`Unrecognized state ${r}.`)}if(this.subscriptionState!==oe.Terminated){const t=Xe.initialDialogStateForSubscription(this.message,e.message);this.dialog=new Xe(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,t)}if(this.delegate&&this.delegate.onNotify){const t=e,i=this.dialog;this.delegate.onNotify({request:t,subscription:i})}else e.accept()}waitNotifyStart(){this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout(()=>this.timerN(),B.TIMER_N))}waitNotifyStop(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)}receiveResponse(e){if(this.authenticationGuard(e)){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);e>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),e<this.subscriptionExpires&&(this.subscriptionExpires=e)}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)}e.statusCode&&e.statusCode>=300&&e.statusCode<700&&this.waitNotifyStop(),super.receiveResponse(e)}}timerN(){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()}}class et extends De{constructor(e,t,i){super(ke,e,t,i),Object.defineProperty(this,"core",{enumerable:!0,configurable:!0,writable:!0,value:e})}}const tt=["application/sdp","application/dtmf-relay"];class it{constructor(e,t={}){Object.defineProperty(this,"configuration",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dialogs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"subscribers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"userAgentClients",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"userAgentServers",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.configuration=e,this.delegate=t,this.dialogs=new Map,this.subscribers=new Map,this.logger=e.loggerFactory.getLogger("sip.user-agent-core")}dispose(){this.reset()}reset(){this.dialogs.forEach(e=>e.dispose()),this.dialogs.clear(),this.subscribers.forEach(e=>e.dispose()),this.subscribers.clear(),this.userAgentClients.forEach(e=>e.dispose()),this.userAgentClients.clear(),this.userAgentServers.forEach(e=>e.dispose()),this.userAgentServers.clear()}get loggerFactory(){return this.configuration.loggerFactory}get transport(){const e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e}invite(e,t){return new Ve(this,e,t)}message(e,t){return new He(this,e,t)}publish(e,t){return new ze(this,e,t)}register(e,t){return new Ye(this,e,t)}subscribe(e,t){return new Qe(this,e,t)}request(e,t){return new Ae(Ie,this,e,t)}makeOutgoingRequestMessage(e,t,i,r,s,n,o){const a=this.configuration.sipjsId,c=this.configuration.displayName,l=this.configuration.viaForceRport,h=this.configuration.hackViaTcp,d=this.configuration.supportedOptionTags.slice();e===G.REGISTER&&d.push("path","gruu"),e===G.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&d.push("gruu");const u={callIdPrefix:a,forceRport:l,fromDisplayName:c,hackViaTcp:h,optionTags:d,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},g=Object.assign(Object.assign({},u),s);return new _(e,t,i,r,g,n,o)}receiveIncomingRequestFromTransport(e){this.receiveRequestFromTransport(e)}receiveIncomingResponseFromTransport(e){this.receiveResponseFromTransport(e)}replyStateless(e,t){const i=this.configuration.userAgentHeaderFieldValue,r=this.configuration.supportedOptionTagsResponse;t=Object.assign(Object.assign({},t),{userAgent:i,supported:r});const s=ye(e,t);return this.transport.send(s.message).catch(t=>{t instanceof Error&&this.logger.error(t.message),this.logger.error(`Transport error occurred sending stateless reply to ${e.method} request.`)}),s}receiveRequestFromTransport(e){const t=e.viaBranch,i=this.userAgentServers.get(t);e.method===G.ACK&&i&&i.transaction.state===ue.Accepted&&i instanceof Ke?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${t}.`):e.method!==G.CANCEL?i?i.transaction.receiveRequest(e):this.receiveRequest(e):i?(this.replyStateless(e,{statusCode:200}),i.transaction instanceof Re&&i.transaction.state===ue.Proceeding&&i instanceof Ke&&i.receiveCancel(e)):this.replyStateless(e,{statusCode:481})}receiveRequest(e){if(!V.includes(e.method)){const t="Allow: "+V.toString();return void this.replyStateless(e,{statusCode:405,extraHeaders:[t]})}if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"!==e.ruri.scheme)return void this.replyStateless(e,{statusCode:416});const t=e.ruri,i=e=>!!e&&e.user===t.user;if(!i(this.configuration.aor)&&!(i(this.configuration.contact.uri)||i(this.configuration.contact.pubGruu)||i(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==G.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==G.INVITE||e.hasHeader("Contact")){if(!e.toTag){const t=e.viaBranch;if(!this.userAgentServers.has(t)){if(Array.from(this.userAgentServers.values()).some(t=>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"})}receiveInsideDialogRequest(e){if(e.method===G.NOTIFY){const t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});const i=e.callId+e.toTag+t.event,r=this.subscribers.get(i);if(r){const t=new qe(this,e);return void r.onNotify(t)}}const t=e.callId+e.toTag+e.fromTag,i=this.dialogs.get(t);if(i){if(e.method===G.OPTIONS){const t="Allow: "+V.toString(),i="Accept: "+tt.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[t,i]})}i.receiveRequest(e)}else e.method!==G.ACK&&this.replyStateless(e,{statusCode:481})}receiveOutsideDialogRequest(e){switch(e.method){case G.ACK:break;case G.BYE:this.replyStateless(e,{statusCode:481});break;case G.CANCEL:throw new Error(`Unexpected out of dialog request method ${e.method}.`);case G.INFO:this.replyStateless(e,{statusCode:405});break;case G.INVITE:{const t=new Ke(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject()}break;case G.MESSAGE:{const t=new Me(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case G.NOTIFY:{const t=new qe(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405})}break;case G.OPTIONS:{const t="Allow: "+V.toString(),i="Accept: "+tt.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[t,i]})}break;case G.REFER:{const t=new We(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405})}break;case G.REGISTER:{const t=new Je(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405})}break;case G.SUBSCRIBE:{const t=new et(this,e);this.delegate.onSubscribe?this.delegate.onSubscribe(t):t.reject({statusCode:480})}break;default:throw new Error(`Unexpected out of dialog request method ${e.method}.`)}}receiveResponseFromTransport(e){if(e.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response, dropping");const t=e.viaBranch+e.method,i=this.userAgentClients.get(t);i?i.transaction.receiveResponse(e):this.logger.warn(`Discarding unmatched ${e.statusCode} response to ${e.method} ${t}.`)}}class rt{constructor(e,t,i){Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mediaStreamFactory",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sessionDescriptionHandlerConfiguration",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_localMediaStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_remoteMediaStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_dataChannel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_peerConnection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_peerConnectionDelegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"iceGatheringCompletePromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"iceGatheringCompleteTimeoutId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"iceGatheringCompleteResolve",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"iceGatheringCompleteReject",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"localMediaStreamConstraints",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onDataChannel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e.debug("SessionDescriptionHandler.constructor"),this.logger=e,this.mediaStreamFactory=t,this.sessionDescriptionHandlerConfiguration=i,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==i?void 0:i.peerConnectionConfiguration),this.initPeerConnectionEventHandlers()}get localMediaStream(){return this._localMediaStream}get remoteMediaStream(){return this._remoteMediaStream}get dataChannel(){return this._dataChannel}get peerConnection(){return this._peerConnection}get peerConnectionDelegate(){return this._peerConnectionDelegate}set peerConnectionDelegate(e){this._peerConnectionDelegate=e}static dispatchAddTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("addtrack",{track:t}))}static dispatchRemoveTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("removetrack",{track:t}))}close(){this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this._peerConnection.getReceivers().forEach(e=>{e.track&&e.track.stop()}),this._peerConnection.getSenders().forEach(e=>{e.track&&e.track.stop()}),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)}enableReceiverTracks(e){const t=this.peerConnection;if(!t)throw new Error("Peer connection closed.");t.getReceivers().forEach(t=>{t.track&&(t.track.enabled=e)})}enableSenderTracks(e){const t=this.peerConnection;if(!t)throw new Error("Peer connection closed.");t.getSenders().forEach(t=>{t.track&&(t.track.enabled=e)})}getDescription(e,t){var i,r;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;const s=null===(i=null==e?void 0:e.offerOptions)||void 0===i?void 0:i.iceRestart,n=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(()=>this.updateDirection(e)).then(()=>this.createDataChannel(e)).then(()=>this.createLocalOfferOrAnswer(e)).then(e=>this.applyModifiers(e,t)).then(e=>this.setLocalSessionDescription(e)).then(()=>this.waitForIceGatheringComplete(s,n)).then(()=>this.getLocalSessionDescription()).then(t=>{const i=null==e?void 0:e.finalModifiers;return i&&0!==i.length?(this.logger.debug("SessionDescriptionHandler.getDescription - applying final SDP modifiers"),this.applyFinalModifiers(t,i)):t}).then(e=>{const t=e.sdp||"";return this.logger.log("SessionDescriptionHandler.getDescription - final SDP "+JSON.stringify({hasRecoveryReason:t.includes("a=x-recovery-reason:"),hasReinviteReason:t.includes("a=x-reinvite-reason:")})),{body:t,contentType:"application/sdp"}}).catch(e=>{throw this.logger.error("SessionDescriptionHandler.getDescription failed - "+e),e})}hasDescription(e){return this.logger.debug("SessionDescriptionHandler.hasDescription"),"application/sdp"===e}iceGatheringComplete(){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)}sendDtmf(e,t){if(this.logger.debug("SessionDescriptionHandler.sendDtmf"),void 0===this._peerConnection)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"),!1;const i=this._peerConnection.getSenders();if(0===i.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;const r=i[0].dtmf;if(!r)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;const s=null==t?void 0:t.duration,n=null==t?void 0:t.interToneGap;try{r.insertDTMF(e,s,n)}catch(e){return this.logger.error(e.toString()),!1}return this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: "+e.toString()),!0}setDescription(e,t,i){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;const r="have-local-offer"===this._peerConnection.signalingState?"answer":"offer";return this.getLocalMediaStream(t).then(()=>this.applyModifiers({sdp:e,type:r},i)).then(e=>this.setRemoteSessionDescription(e)).catch(e=>{throw this.logger.error("SessionDescriptionHandler.setDescription failed - "+e),e})}applyFinalModifiers(e,t){return this.logger.debug("SessionDescriptionHandler.applyFinalModifiers"),t&&0!==t.length?t.reduce((e,t)=>e.then(e=>r(this,void 0,void 0,function*(){var i;const r=yield t(e);if(!r||!r.sdp)throw new Error("Invalid final SDP.");return{sdp:r.sdp,type:null!==(i=r.type)&&void 0!==i?i:e.type}})),Promise.resolve({sdp:e.sdp,type:e.type})):Promise.resolve(e)}applyModifiers(e,t){return this.logger.debug("SessionDescriptionHandler.applyModifiers"),t&&0!==t.length?t.reduce((e,t)=>e.then(t),Promise.resolve(e)).then(e=>{if(this.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)}createDataChannel(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))}}createLocalOfferOrAnswer(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))}}getLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));let t=Object.assign({},null==e?void 0:e.constraints);if(this.localMediaStreamConstraints){if(t.audio=t.audio||this.localMediaStreamConstraints.audio,t.video=t.video||this.localMediaStreamConstraints.video,JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(t.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(t.video))return Promise.resolve()}else void 0===t.audio&&void 0===t.video&&(t={audio:!0});return this.localMediaStreamConstraints=t,this.mediaStreamFactory(t,this,e).then(e=>this.setLocalMediaStream(e))}setLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");const t=this._peerConnection,i=this._localMediaStream,r=[],s=e=>{const s=e.kind;if("audio"!==s&&"video"!==s)throw new Error(`Unknown new track kind ${s}.`);const n=t.getSenders().find(e=>e.track&&e.track.kind===s);n?r.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${s} track`),e()}).then(()=>n.replaceTrack(e).then(()=>{const t=i.getTracks().find(e=>e.kind===s);t&&(t.stop(),i.removeTrack(t),rt.dispatchRemoveTrackEvent(i,t)),i.addTrack(e),rt.dispatchAddTrackEvent(i,e)}).catch(e=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${s} track`),e}))):r.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${s} track`),e()}).then(()=>{try{t.addTrack(e,i)}catch(e){throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${s} track`),e}i.addTrack(e),rt.dispatchAddTrackEvent(i,e)}))},n=e.getAudioTracks();n.length&&s(n[0]);const o=e.getVideoTracks();return o.length&&s(o[0]),r.reduce((e,t)=>e.then(()=>t),Promise.resolve())}getLocalSessionDescription(){if(this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const e=this._peerConnection.localDescription;return e?Promise.resolve(e):Promise.reject(new Error("Failed to get local session description"))}setLocalSessionDescription(e){return this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"),void 0===this._peerConnection?Promise.reject(new Error("Peer connection closed.")):this._peerConnection.setLocalDescription(e)}setRemoteSessionDescription(e){if(this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const t=e.sdp;let i;switch(this._peerConnection.signalingState){case"stable":i="offer";break;case"have-local-offer":i="answer";break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return t?this._peerConnection.setRemoteDescription({sdp:t,type:i}):(this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"),Promise.reject(new Error("SDP is undefined")))}setRemoteTrack(e){this.logger.debug("SessionDescriptionHandler.setRemoteTrack");const t=this._remoteMediaStream;t.getTrackById(e.id)?this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${e.kind} track`):"audio"===e.kind?(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getAudioTracks().forEach(e=>{e.stop(),t.removeTrack(e),rt.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),rt.dispatchAddTrackEvent(t,e)):"video"===e.kind&&(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getVideoTracks().forEach(e=>{e.stop(),t.removeTrack(e),rt.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),rt.dispatchAddTrackEvent(t,e))}updateDirection(e){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");{const t=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")}};this._peerConnection.getTransceivers().forEach(e=>{if(e.direction){const i=t(e.direction);e.direction!==i&&(e.direction=i)}})}break;case"have-remote-offer":this.logger.debug("SessionDescriptionHandler.updateDirection - setting answer direction");{const t=(()=>{const e=this._peerConnection.remoteDescription;if(!e)throw new Error("Failed to read remote offer");const t=/a=sendrecv\r\n|a=sendonly\r\n|a=recvonly\r\n|a=inactive\r\n/.exec(e.sdp);if(t)switch(t[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"})(),i=(()=>{switch(t){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(e=>{e.direction&&"stopped"!==e.direction&&e.direction!==i&&(e.direction=i)})}break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return Promise.resolve()}waitForIceGatheringComplete(e=!1,t=0){return 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((e,i)=>{this.iceGatheringCompleteResolve=e,this.iceGatheringCompleteReject=i,t>0&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in "+t),this.iceGatheringCompleteTimeoutId=setTimeout(()=>{this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"),this.iceGatheringComplete()},t))}),this.iceGatheringCompletePromise):(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"),Promise.resolve())}initPeerConnectionEventHandlers(){if(this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"),!this._peerConnection)throw new Error("Peer connection undefined.");const e=this._peerConnection;e.onconnectionstatechange=t=>{var i;const r=e.connectionState;this.logger.debug(`SessionDescriptionHandler.onconnectionstatechange ${r}`),(null===(i=this._peerConnectionDelegate)||void 0===i?void 0:i.onconnectionstatechange)&&this._peerConnectionDelegate.onconnectionstatechange(t)},e.ondatachannel=e=>{var t;this.logger.debug("SessionDescriptionHandler.ondatachannel"),this._dataChannel=e.channel,this.onDataChannel&&this.onDataChannel(this._dataChannel),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ondatachannel)&&this._peerConnectionDelegate.ondatachannel(e)},e.onicecandidate=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidate"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidate)&&this._peerConnectionDelegate.onicecandidate(e)},e.onicecandidateerror=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidateerror"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidateerror)&&this._peerConnectionDelegate.onicecandidateerror(e)},e.oniceconnectionstatechange=t=>{var i;const r=e.iceConnectionState;this.logger.debug(`SessionDescriptionHandler.oniceconnectionstatechange ${r}`),(null===(i=this._peerConnectionDelegate)||void 0===i?void 0:i.oniceconnectionstatechange)&&this._peerConnectionDelegate.oniceconnectionstatechange(t)},e.onicegatheringstatechange=t=>{var i;const r=e.iceGatheringState;this.logger.debug(`SessionDescriptionHandler.onicegatheringstatechange ${r}`),"complete"===r&&this.iceGatheringComplete(),(null===(i=this._peerConnectionDelegate)||void 0===i?void 0:i.onicegatheringstatechange)&&this._peerConnectionDelegate.onicegatheringstatechange(t)},e.onnegotiationneeded=e=>{var t;this.logger.debug("SessionDescriptionHandler.onnegotiationneeded"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onnegotiationneeded)&&this._peerConnectionDelegate.onnegotiationneeded(e)},e.onsignalingstatechange=t=>{var i;const r=e.signalingState;this.logger.debug(`SessionDescriptionHandler.onsignalingstatechange ${r}`),(null===(i=this._peerConnectionDelegate)||void 0===i?void 0:i.onsignalingstatechange)&&this._peerConnectionDelegate.onsignalingstatechange(t)},e.ontrack=e=>{var t;const i=e.track.kind,r=e.track.enabled?"enabled":"disabled";this.logger.debug(`SessionDescriptionHandler.ontrack ${i} ${r}`),this.setRemoteTrack(e.track),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ontrack)&&this._peerConnectionDelegate.ontrack(e)}}}function st(e){return(t,i)=>{void 0===e&&(e=e=>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));const r={iceGatheringTimeout:void 0!==(null==i?void 0:i.iceGatheringTimeout)?null==i?void 0:i.iceGatheringTimeout:5e3,peerConnectionConfiguration:Object.assign(Object.assign({},{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",rtcpMuxPolicy:"require"}),null==i?void 0:i.peerConnectionConfiguration)},s=t.userAgent.getLogger("sip.SessionDescriptionHandler");return new rt(s,e,r)}}class nt{constructor(e,t){if(Object.defineProperty(this,"onConnect",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onDisconnect",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_protocol",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_state",{enumerable:!0,configurable:!0,writable:!0,value:ce.Disconnected}),Object.defineProperty(this,"_stateEventEmitter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ws",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"configuration",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"connectPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"connectResolve",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"connectReject",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"connectTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"disconnectPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"disconnectResolve",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"disconnectReject",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keepAliveInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keepAliveDebounceTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"transitioningState",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this._stateEventEmitter=new p,this.logger=e,t){const e=t,i=null==e?void 0:e.wsServers,r=null==e?void 0:e.maxReconnectionAttempts;if(void 0!==i){const e='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(e)}if(void 0!==r){const e='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(e)}i&&!t.server&&("string"==typeof i&&(t.server=i),i instanceof Array&&(t.server=i[0]))}this.configuration=Object.assign(Object.assign({},nt.defaultOptions),t);const i=this.configuration.server,r=E.parse(i,"absoluteURI");if(-1===r)throw this.logger.error(`Invalid WebSocket Server URL "${i}"`),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(r.scheme))throw this.logger.error(`Invalid scheme in WebSocket Server URL "${i}"`),new Error("Invalid scheme in WebSocket Server URL");this._protocol=r.scheme.toUpperCase()}dispose(){return this.disconnect()}get protocol(){return this._protocol}get server(){return this.configuration.server}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get ws(){return this._ws}connect(){return this._connect()}disconnect(){return this._disconnect()}isConnected(){return this.state===ce.Connected}send(e){return this._send(e)}_connect(){switch(this.logger.log(`Connecting ${this.server}`),this.state){case ce.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ce.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case ce.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ce.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case ce.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(ce.Connecting)}catch(e){if(e instanceof d)return Promise.reject(e);throw e}break;case ce.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(ce.Connecting)}catch(e){if(e instanceof d)return Promise.reject(e);throw e}break;default:throw new Error("Unknown state")}let e;try{e=new WebSocket(this.server,"sip"),e.binaryType="arraybuffer",e.addEventListener("close",t=>this.onWebSocketClose(t,e)),e.addEventListener("error",t=>this.onWebSocketError(t,e)),e.addEventListener("open",t=>this.onWebSocketOpen(t,e)),e.addEventListener("message",t=>this.onWebSocketMessage(t,e)),this._ws=e}catch(e){return this._ws=void 0,this.logger.error("WebSocket construction failed."),this.logger.error(e.toString()),new Promise((t,i)=>{this.connectResolve=t,this.connectReject=i,this.transitionState(ce.Disconnected,e)})}return this.connectPromise=new Promise((t,i)=>{this.connectResolve=t,this.connectReject=i,this.connectTimeout=setTimeout(()=>{this.logger.warn("Connect timed out. Exceeded time set in configuration.connectionTimeout: "+this.configuration.connectionTimeout+"s."),e.close(1e3)},1e3*this.configuration.connectionTimeout)}),this.connectPromise}_disconnect(){switch(this.logger.log(`Disconnecting ${this.server}`),this.state){case ce.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(ce.Disconnecting)}catch(e){if(e instanceof d)return Promise.reject(e);throw e}break;case ce.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(ce.Disconnecting)}catch(e){if(e instanceof d)return Promise.reject(e);throw e}break;case ce.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ce.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case ce.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ce.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.");const e=this._ws;return this.disconnectPromise=new Promise((t,i)=>{this.disconnectResolve=t,this.disconnectReject=i;try{e.close(1e3)}catch(e){throw this.logger.error("WebSocket close failed."),this.logger.error(e.toString()),e}}),this.disconnectPromise}_send(e){if(!0===this.configuration.traceSip&&this.logger.log("Sending WebSocket message:\n\n"+e+"\n"),this._state!==ce.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()}onWebSocketClose(e,t){if(t!==this._ws)return;const i=`WebSocket closed ${this.server} (code: ${e.code})`,r=this.disconnectPromise?void 0:new Error(i);r&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(i),this._ws=void 0,this.transitionState(ce.Disconnected,r)}onWebSocketError(e,t){t===this._ws&&this.logger.error("WebSocket error occurred.")}onWebSocketMessage(e,t){if(t!==this._ws)return;const i=e.data;let r;if(/^(\r\n)+$/.test(i))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(i){if("string"!=typeof i){try{r=(new TextDecoder).decode(new Uint8Array(i))}catch(e){return this.logger.error(e.toString()),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"+r+"\n")}else r=i,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+r+"\n");if(this.state===ce.Connected){if(this.onMessage)try{this.onMessage(r)}catch(e){throw this.logger.error(e.toString()),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...")}onWebSocketOpen(e,t){t===this._ws&&this._state===ce.Connecting&&(this.logger.log(`WebSocket opened ${this.server}`),this.transitionState(ce.Connected))}transitionLoopDetectedError(e){let t="A state transition loop has been detected.";return t+=` An attempt to transition from ${this._state} to ${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 d("Loop detected.")}transitionState(e,t){const i=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};if(this.transitioningState)throw this.transitionLoopDetectedError(e);switch(this.transitioningState=!0,this._state){case ce.Connecting:e!==ce.Connected&&e!==ce.Disconnecting&&e!==ce.Disconnected&&i();break;case ce.Connected:e!==ce.Disconnecting&&e!==ce.Disconnected&&i();break;case ce.Disconnecting:e!==ce.Connecting&&e!==ce.Disconnected&&i();break;case ce.Disconnected:e!==ce.Connecting&&i();break;default:throw new Error("Unknown state.")}const r=this._state;this._state=e;const s=this.connectResolve,n=this.connectReject;r===ce.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const o=this.disconnectResolve,a=this.disconnectReject;if(r===ce.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 ${r} to ${this._state}`),this._stateEventEmitter.emit(this._state),e===ce.Connected&&(this.startSendingKeepAlives(),this.onConnect))try{this.onConnect()}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onConnect callback"),e}if(r===ce.Connected&&(this.stopSendingKeepAlives(),this.onDisconnect))try{t?this.onDisconnect(t):this.onDisconnect()}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onDisconnect callback"),e}if(r===ce.Connecting){if(!s)throw new Error("Connect resolve undefined.");if(!n)throw new Error("Connect reject undefined.");e===ce.Connected?s():n(t||new Error("Connect aborted."))}if(r===ce.Disconnecting){if(!o)throw new Error("Disconnect resolve undefined.");if(!a)throw new Error("Disconnect reject undefined.");e===ce.Disconnected?o():a(t||new Error("Disconnect aborted."))}this.transitioningState=!1}clearKeepAliveTimeout(){this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveDebounceTimeout=void 0}sendKeepAlive(){return this.keepAliveDebounceTimeout?Promise.resolve():(this.keepAliveDebounceTimeout=setTimeout(()=>{this.clearKeepAliveTimeout()},1e3*this.configuration.keepAliveDebounce),this.send("\r\n\r\n"))}startSendingKeepAlives(){this.configuration.keepAliveInterval&&!this.keepAliveInterval&&(this.keepAliveInterval=setInterval(()=>{this.sendKeepAlive(),this.startSendingKeepAlives()},(e=>{const t=.8*e;return 1e3*(Math.random()*(e-t)+t)})(this.configuration.keepAliveInterval)))}stopSendingKeepAlives(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0}}Object.defineProperty(nt,"defaultOptions",{enumerable:!0,configurable:!0,writable:!0,value:{server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0}});class ot{constructor(e={}){if(Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_publishers",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_registerers",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_sessions",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_subscriptions",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_contact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_instanceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_state",{enumerable:!0,configurable:!0,writable:!0,value:le.Stopped}),Object.defineProperty(this,"_stateEventEmitter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_transport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_userAgentCore",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"loggerFactory",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._stateEventEmitter=new p,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},ot.defaultOptions()),{sipjsId:C(5)}),{uri:new y("sip","anonymous."+C(6),"anonymous.invalid")}),{viaHost:C(12)+".invalid"}),ot.stripUndefinedProperties(e)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){const e=1,t=254,i=Math.floor(Math.random()*(t-e+1)+e);this.options.viaHost="192.0.2."+i}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new be,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=he.error;break;case"warn":this.loggerFactory.level=he.warn;break;case"log":this.loggerFactory.level=he.log;break;case"debug":this.loggerFactory.level=he.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];switch(e){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("· "+e+": "+t);break;case"authorizationPassword":this.logger.log("· "+e+": NOT SHOWN");break;case"transportConstructor":this.logger.log("· "+e+": "+t.name);break;default:this.logger.log("· "+e+": "+JSON.stringify(t))}})),this.options.transportOptions){const t=this.options.transportOptions,i=t.maxReconnectionAttempts,r=t.reconnectionTimeout;if(void 0!==i){const e='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(e)}if(void 0!==r){const e='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(e)}void 0===e.reconnectionDelay&&void 0!==r&&(this.options.reconnectionDelay=r),void 0===e.reconnectionAttempts&&void 0!==i&&(this.options.reconnectionAttempts=i)}if(void 0!==e.reconnectionDelay){const e='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(e)}if(void 0!==e.reconnectionAttempts){const e='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(e)}if(this._transport=new this.options.transportConstructor(this.getLogger("sip.Transport"),this.options.transportOptions),this.initTransportCallbacks(),this._contact=this.initContact(),this._instanceId=this.options.instanceId?this.options.instanceId:ot.newUUID(),-1===E.parse(this._instanceId,"uuid"))throw new Error("Invalid instanceId.");this._userAgentCore=this.initCore()}static makeURI(e){return E.URIParse(e)}static defaultOptions(){return{errorCallback:()=>{},allowLegacyNotifications:!1,authorizationHa1:"",authorizationPassword:"",authorizationUsername:"",delegate:{},contactName:"",contactParams:{transport:"ws"},displayName:"",forceRport:!1,gracefulShutdown:!0,hackAllowUnregisteredOptionTags:!1,hackIpInContact:!1,hackViaTcp:!1,instanceId:"",instanceIdAlwaysAdded:!1,logBuiltinEnabled:!0,logConfiguration:!0,logConnector:()=>{},logLevel:"log",noAnswerTimeout:60,preloadedRouteSet:[],reconnectionAttempts:0,reconnectionDelay:4,sendInitialProvisionalResponse:!0,sessionDescriptionHandlerFactory:st(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:Q.Unsupported,sipExtensionReplaces:Q.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:nt,transportOptions:{},uri:new y("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/0.21.17",viaHost:""}}static newUUID(){const e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.floor(16*Math.random());return("x"===e?t:t%4+8).toString(16)});return e}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,i)=>(void 0!==e[i]&&(t[i]=e[i]),t),{})}get configuration(){return this.options}get contact(){return this._contact}get instanceId(){return this._instanceId}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get transport(){return this._transport}get userAgentCore(){return this._userAgentCore}getLogger(e,t){return this.loggerFactory.getLogger(e,t)}getLoggerFactory(){return this.loggerFactory}isConnected(){return this.transport.isConnected()}reconnect(){return this.state===le.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(()=>this.transport.connect())}start(){return this.state===le.Started?(this.logger.warn("User agent already started"),Promise.resolve()):(this.logger.log(`Starting ${this.configuration.uri}`),this.transitionState(le.Started),this.transport.connect())}stop(){return r(this,void 0,void 0,function*(){if(this.state===le.Stopped)return this.logger.warn("User agent already stopped"),Promise.resolve();if(this.logger.log(`Stopping ${this.configuration.uri}`),!this.options.gracefulShutdown)return this.logger.log("Dispose of transport"),this.transport.dispose().catch(e=>{throw this.logger.error(e.message),e}),this.logger.log("Dispose of core"),this.userAgentCore.dispose(),this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this.transitionState(le.Stopped),Promise.resolve();const e=Object.assign({},this._publishers),t=Object.assign({},this._registerers),i=Object.assign({},this._sessions),r=Object.assign({},this._subscriptions),s=this.transport,n=this.userAgentCore;this.logger.log("Dispose of registerers");for(const e in t)t[e]&&(yield t[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._registerers[e],t}));this.logger.log("Dispose of sessions");for(const e in i)i[e]&&(yield i[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._sessions[e],t}));this.logger.log("Dispose of subscriptions");for(const e in r)r[e]&&(yield r[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._subscriptions[e],t}));this.logger.log("Dispose of publishers");for(const t in e)e[t]&&(yield e[t].dispose().catch(e=>{throw this.logger.error(e.message),delete this._publishers[t],e}));this.logger.log("Dispose of transport"),yield s.dispose().catch(e=>{throw this.logger.error(e.message),e}),this.logger.log("Dispose of core"),n.dispose(),this.transitionState(le.Stopped)})}_makeInviter(e,t){return new ie(this,e,t)}attemptReconnection(e=1){const t=this.options.reconnectionAttempts,i=this.options.reconnectionDelay;e>t?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log(`Reconnection attempt ${e} of ${t} - trying`),setTimeout(()=>{this.reconnect().then(()=>{this.logger.log(`Reconnection attempt ${e} of ${t} - succeeded`)}).catch(i=>{this.logger.error(i.message),this.logger.log(`Reconnection attempt ${e} of ${t} - failed`),this.attemptReconnection(++e)})},1===e?0:1e3*i))}initContact(){const e=""!==this.options.contactName?this.options.contactName:C(8),t=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new y("sip",e,this.options.viaHost,void 0,t),toString:(e={})=>{const i=e.anonymous||!1,r=e.outbound||!1,s=e.register||!1;let n="<";return n+=i?this.contact.tempGruu||`sip:anonymous@anonymous.invalid;transport=${t.transport?t.transport:"ws"}`:s?this.contact.uri:this.contact.pubGruu||this.contact.uri,r&&(n+=";ob"),n+=">",this.options.instanceIdAlwaysAdded&&(n+=';+sip.instance="<urn:uuid:'+this._instanceId+'>"'),n}}}initCore(){let e=[];e.push("outbound"),this.options.sipExtension100rel===Q.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===Q.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter(e=>ee[e])),e=Array.from(new Set(e));const t=e.slice();(this.contact.pubGruu||this.contact.tempGruu)&&t.push("gruu");const i={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:e,supportedOptionTagsResponse:t,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:()=>{const e=this.options.authorizationUsername?this.options.authorizationUsername:this.options.uri.user,t=this.options.authorizationPassword?this.options.authorizationPassword:void 0,i=this.options.authorizationHa1?this.options.authorizationHa1:void 0;return new ve(this.getLoggerFactory(),i,e,t)},transportAccessor:()=>this.transport},r={onInvite:e=>{var t;const i=new te(this,e);if(e.delegate={onCancel:e=>{i._onCancel(e)},onTransportError:e=>{this.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},e.trying(),this.options.sipExtensionReplaces!==Q.Unsupported){const t=e.message.parseHeader("replaces");if(t){const e=t.call_id;if("string"!=typeof e)throw new Error("Type of call id is not string");const r=t.replaces_to_tag;if("string"!=typeof r)throw new Error("Type of to tag is not string");const s=t.replaces_from_tag;if("string"!=typeof s)throw new Error("type of from tag is not string");const n=e+r+s,o=this.userAgentCore.dialogs.get(n);if(!o)return void i.reject({statusCode:481});if(!o.early&&!0===t.early_only)return void i.reject({statusCode:486});const a=this._sessions[e+s]||this._sessions[e+r]||void 0;if(!a)throw new Error("Session does not exist.");i._replacee=a}}if(null===(t=this.delegate)||void 0===t?void 0:t.onInvite)return i.autoSendAnInitialProvisionalResponse?void i.progress().then(()=>{var e;if(void 0===(null===(e=this.delegate)||void 0===e?void 0:e.onInvite))throw new Error("onInvite undefined.");this.delegate.onInvite(i)}):void this.delegate.onInvite(i);i.reject({statusCode:486})},onMessage:e=>{if(this.delegate&&this.delegate.onMessage){const t=new K(e);this.delegate.onMessage(t)}else e.accept()},onNotify:e=>{if(this.delegate&&this.delegate.onNotify){const t=new z(e);this.delegate.onNotify(t)}else this.options.allowLegacyNotifications?e.accept():e.reject({statusCode:481})},onRefer:e=>{this.logger.warn("Received an out of dialog REFER request"),this.delegate&&this.delegate.onReferRequest?this.delegate.onReferRequest(e):e.reject({statusCode:405})},onRegister:e=>{this.logger.warn("Received an out of dialog REGISTER request"),this.delegate&&this.delegate.onRegisterRequest?this.delegate.onRegisterRequest(e):e.reject({statusCode:405})},onSubscribe:e=>{this.logger.warn("Received an out of dialog SUBSCRIBE request"),this.delegate&&this.delegate.onSubscribeRequest?this.delegate.onSubscribeRequest(e):e.reject({statusCode:405})}};return new it(i,r)}initTransportCallbacks(){this.transport.onConnect=()=>this.onTransportConnect(),this.transport.onDisconnect=e=>this.onTransportDisconnect(e),this.transport.onMessage=e=>this.onTransportMessage(e)}onTransportConnect(){this.state!==le.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==le.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const t=de.parseMessage(e,this.getLogger("sip.Parser"));if(!t)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===le.Stopped&&t instanceof $)return void this.logger.warn(`Received ${t.method} request while stopped. Dropping.`);const i=()=>{const e=["from","to","call_id","cseq","via"];for(const i of e)if(!t.hasHeader(i))return this.logger.warn(`Missing mandatory header field : ${i}.`),!1;return!0};if(t instanceof $){if(!i())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!t.toTag&&t.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(t,{statusCode:482});const e=k(t.body),r=t.getHeader("content-length");if(r&&e<Number(r))return void this.userAgentCore.replyStateless(t,{statusCode:400})}if(t instanceof j){if(!i())return void this.logger.warn("Response missing mandatory header field. Dropping.");if(t.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(t.via.host!==this.options.viaHost||void 0!==t.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");const e=k(t.body),r=t.getHeader("content-length");if(r&&e<Number(r))return void this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping.")}if(t instanceof $)this.userAgentCore.receiveIncomingRequestFromTransport(t);else{if(!(t instanceof j))throw new Error("Invalid message type.");this.userAgentCore.receiveIncomingResponseFromTransport(t)}}transitionState(e,t){const i=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case le.Started:e!==le.Stopped&&i();break;case le.Stopped:e!==le.Started&&i();break;default:throw new Error("Unknown state.")}this.logger.log(`Transitioned from ${this._state} to ${e}`),this._state=e,this._stateEventEmitter.emit(this._state)}}class at{constructor(e,t={}){Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"managedSessions",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"userAgent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attemptingReconnection",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"optionsPingFailure",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"optionsPingRequest",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"optionsPingRunning",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"optionsPingTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"registrationAttemptTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"registerer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"registererOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"registererRegisterOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shouldBeConnected",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"shouldBeRegistered",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.delegate=t.delegate,this.options=Object.assign({aor:"",autoStop:!0,delegate:{},iceStopWaitingOnServerReflexive:!1,managedSessionFactory:(e,t)=>({session:t,held:!1,muted:!1}),maxSimultaneousSessions:2,media:{},optionsPingInterval:-1,optionsPingRequestURI:"",reconnectionAttempts:3,reconnectionDelay:4,registrationRetry:!1,registrationRetryInterval:3,registerGuard:null,registererOptions:{},registererRegisterOptions:{},sendDTMFUsingSessionDescriptionHandler:!1,userAgentOptions:{}},at.stripUndefinedProperties(t));const i=Object.assign({},t.userAgentOptions);if(i.transportConstructor||(i.transportConstructor=nt),i.transportOptions||(i.transportOptions={server:e}),!i.uri&&t.aor){const e=ot.makeURI(t.aor);if(!e)throw new Error(`Failed to create valid URI from ${t.aor}`);i.uri=e}if(this.userAgent=new ot(i),this.userAgent.delegate={onConnect:()=>{this.logger.log("Connected"),this.delegate&&this.delegate.onServerConnect&&this.delegate.onServerConnect(),this.shouldBeRegistered&&this.register(),this.options.optionsPingInterval>0&&this.optionsPingStart()},onDisconnect:e=>r(this,void 0,void 0,function*(){this.logger.log("Disconnected");let t=!1;this.options.optionsPingInterval>0&&(t=this.optionsPingFailure,this.optionsPingFailure=!1,this.optionsPingStop()),this.delegate&&this.delegate.onServerDisconnect&&this.delegate.onServerDisconnect(e),(e||t)&&(this.registerer&&(this.logger.log("Disposing of registerer..."),this.registerer.dispose().catch(e=>{this.logger.debug("Error occurred disposing of registerer after connection with server was lost."),this.logger.debug(e.toString())}),this.registerer=void 0),this.managedSessions.slice().map(e=>e.session).forEach(e=>r(this,void 0,void 0,function*(){this.logger.log("Disposing of session..."),e.dispose().catch(e=>{this.logger.debug("Error occurred disposing of a session after connection with server was lost."),this.logger.debug(e.toString())})})),this.shouldBeConnected&&this.attemptReconnection())}),onInvite:e=>{this.logger.log(`[${e.id}] Received INVITE`);const t=this.options.maxSimultaneousSessions;if(0!==t&&this.managedSessions.length>t)return this.logger.warn(`[${e.id}] Session already in progress, rejecting INVITE...`),void e.reject().then(()=>{this.logger.log(`[${e.id}] Rejected INVITE`)}).catch(t=>{this.logger.error(`[${e.id}] Failed to reject INVITE`),this.logger.error(t.toString())});const i={sessionDescriptionHandlerOptions:{constraints:this.constraints}};this.initSession(e,i),this.delegate&&this.delegate.onCallReceived?this.delegate.onCallReceived(e):(this.logger.warn(`[${e.id}] No handler available, rejecting INVITE...`),e.reject().then(()=>{this.logger.log(`[${e.id}] Rejected INVITE`)}).catch(t=>{this.logger.error(`[${e.id}] Failed to reject INVITE`),this.logger.error(t.toString())}))},onMessage:e=>{e.accept().then(()=>{this.delegate&&this.delegate.onMessageReceived&&this.delegate.onMessageReceived(e)})},onNotify:e=>{e.accept().then(()=>{this.delegate&&this.delegate.onNotificationReceived&&this.delegate.onNotificationReceived(e)})}},this.registererOptions=Object.assign({},t.registererOptions),this.registererRegisterOptions=Object.assign({},t.registererRegisterOptions),this.options.registrationRetry){this.registererRegisterOptions.requestDelegate=this.registererRegisterOptions.requestDelegate||{};const e=this.registererRegisterOptions.requestDelegate.onReject;this.registererRegisterOptions.requestDelegate.onReject=t=>{e&&e(t),this.attemptRegistration()}}this.logger=this.userAgent.getLogger("sip.SessionManager"),window.addEventListener("online",()=>{this.logger.log("Online"),this.shouldBeConnected&&this.connect()}),this.options.autoStop&&window.addEventListener("beforeunload",()=>r(this,void 0,void 0,function*(){this.shouldBeConnected=!1,this.shouldBeRegistered=!1,this.userAgent.state!==le.Stopped&&(yield this.userAgent.stop())}))}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,i)=>(void 0!==e[i]&&(t[i]=e[i]),t),{})}getLocalMediaStream(e){const t=e.sessionDescriptionHandler;if(t){if(!(t instanceof rt))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.localMediaStream}}getRemoteMediaStream(e){const t=e.sessionDescriptionHandler;if(t){if(!(t instanceof rt))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.remoteMediaStream}}getLocalAudioTrack(e){var t;return null===(t=this.getLocalMediaStream(e))||void 0===t?void 0:t.getTracks().find(e=>"audio"===e.kind)}getLocalVideoTrack(e){var t;return null===(t=this.getLocalMediaStream(e))||void 0===t?void 0:t.getTracks().find(e=>"video"===e.kind)}getRemoteAudioTrack(e){var t;return null===(t=this.getRemoteMediaStream(e))||void 0===t?void 0:t.getTracks().find(e=>"audio"===e.kind)}getRemoteVideoTrack(e){var t;return null===(t=this.getRemoteMediaStream(e))||void 0===t?void 0:t.getTracks().find(e=>"video"===e.kind)}connect(){return r(this,void 0,void 0,function*(){return this.logger.log("Connecting UserAgent..."),this.shouldBeConnected=!0,this.userAgent.state!==le.Started?this.userAgent.start():this.userAgent.reconnect()})}disconnect(){return r(this,void 0,void 0,function*(){return this.logger.log("Disconnecting UserAgent..."),this.userAgent.state===le.Stopped?Promise.resolve():(this.shouldBeConnected=!1,this.shouldBeRegistered=!1,this.registerer=void 0,this.userAgent.stop())})}isConnected(){return this.userAgent.isConnected()}register(e){return r(this,void 0,void 0,function*(){return this.logger.log("Registering UserAgent..."),this.shouldBeRegistered=!0,void 0!==e&&(this.registererRegisterOptions=Object.assign({},e)),this.registerer||(this.registerer=new ge(this.userAgent,this.registererOptions),this.registerer.stateChange.addListener(e=>{switch(e){case ne.Initial:break;case ne.Registered:this.delegate&&this.delegate.onRegistered&&this.delegate.onRegistered();break;case ne.Unregistered:this.delegate&&this.delegate.onUnregistered&&this.delegate.onUnregistered(),this.shouldBeRegistered&&this.attemptRegistration();break;case ne.Terminated:break;default:throw new Error("Unknown registerer state.")}})),this.attemptRegistration(!0)})}unregister(e){return r(this,void 0,void 0,function*(){return this.logger.log("Unregistering UserAgent..."),this.shouldBeRegistered=!1,this.registerer?this.registerer.unregister(e).then(()=>{}):(this.logger.warn("No registerer to unregister."),Promise.resolve())})}call(e,t,i){return r(this,void 0,void 0,function*(){this.logger.log("Beginning Session...");const r=this.options.maxSimultaneousSessions;if(0!==r&&this.managedSessions.length>r)return Promise.reject(new Error("Maximum number of sessions already exists."));const s=ot.makeURI(e);if(!s)return Promise.reject(new Error(`Failed to create a valid URI from "${e}"`));if(t||(t={}),t.sessionDescriptionHandlerOptions||(t.sessionDescriptionHandlerOptions={}),t.sessionDescriptionHandlerOptions.constraints||(t.sessionDescriptionHandlerOptions.constraints=this.constraints),t.earlyMedia){(i=i||{}).requestDelegate=i.requestDelegate||{};const e=i.requestDelegate.onProgress;i.requestDelegate.onProgress=t=>{183===t.message.statusCode&&this.setupRemoteMedia(n),e&&e(t)}}this.options.iceStopWaitingOnServerReflexive&&(t.delegate=t.delegate||{},t.delegate.onSessionDescriptionHandler=e=>{if(!(e instanceof rt))throw new Error("Session description handler not instance of SessionDescriptionHandler");e.peerConnectionDelegate={onicecandidate:t=>{var i;if("srflx"===(null===(i=t.candidate)||void 0===i?void 0:i.type)){this.logger.log(`[${n.id}] Found srflx ICE candidate, stop waiting...`);e.iceGatheringComplete()}}}});const n=new ie(this.userAgent,s,t);return this.sendInvite(n,t,i).then(()=>n)})}hangup(e){return r(this,void 0,void 0,function*(){return this.logger.log(`[${e.id}] Hangup...`),this.sessionExists(e)?this.terminate(e):Promise.reject(new Error("Session does not exist."))})}answer(e,t){return r(this,void 0,void 0,function*(){return this.logger.log(`[${e.id}] Accepting Invitation...`),this.sessionExists(e)?e instanceof te?(t||(t={}),t.sessionDescriptionHandlerOptions||(t.sessionDescriptionHandlerOptions={}),t.sessionDescriptionHandlerOptions.constraints||(t.sessionDescriptionHandlerOptions.constraints=this.constraints),e.accept(t)):Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))})}decline(e){return r(this,void 0,void 0,function*(){return this.logger.log(`[${e.id}] Rejecting Invitation...`),this.sessionExists(e)?e instanceof te?e.reject():Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))})}hold(e){return r(this,void 0,void 0,function*(){return this.logger.log(`[${e.id}] Holding session...`),this.setHold(e,!0)})}unhold(e){return r(this,void 0,void 0,function*(){return this.logger.log(`[${e.id}] Unholding session...`),this.setHold(e,!1)})}isHeld(e){const t=this.sessionManaged(e);return!!t&&t.held}mute(e){this.logger.log(`[${e.id}] Disabling media tracks...`),this.setMute(e,!0)}unmute(e){this.logger.log(`[${e.id}] Enabling media tracks...`),this.setMute(e,!1)}isMuted(e){const t=this.sessionManaged(e);return!!t&&t.muted}sendDTMF(e,t){return r(this,void 0,void 0,function*(){if(this.logger.log(`[${e.id}] Sending DTMF...`),!/^[0-9A-D#*,]$/.exec(t))return Promise.reject(new Error("Invalid DTMF tone."));if(!this.sessionExists(e))return Promise.reject(new Error("Session does not exist."));if(this.logger.log(`[${e.id}] Sending DTMF tone: ${t}`),this.options.sendDTMFUsingSessionDescriptionHandler)return e.sessionDescriptionHandler?e.sessionDescriptionHandler.sendDtmf(t)?Promise.resolve():Promise.reject(new Error("Failed to send DTMF")):Promise.reject(new Error("Session desciption handler undefined."));{const i={body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:"Signal="+t+"\r\nDuration="+2e3}};return e.info({requestOptions:i}).then(()=>{})}})}transfer(e,t,i){return r(this,void 0,void 0,function*(){if(this.logger.log(`[${e.id}] Referring session...`),t instanceof X)return e.refer(t,i).then(()=>{});const r=ot.makeURI(t);return r?e.refer(r,i).then(()=>{}):Promise.reject(new Error(`Failed to create a valid URI from "${t}"`))})}message(e,t){return r(this,void 0,void 0,function*(){this.logger.log("Sending message...");const i=ot.makeURI(e);return i?new re(this.userAgent,i,t).message():Promise.reject(new Error(`Failed to create a valid URI from "${e}"`))})}get constraints(){let e={audio:!0,video:!1};return this.options.media.constraints&&(e=Object.assign({},this.options.media.constraints)),e}attemptReconnection(e=1){const t=this.options.reconnectionAttempts,i=this.options.reconnectionDelay;this.shouldBeConnected?(this.attemptingReconnection&&this.logger.log("Reconnection attempt already in progress"),e>t?this.logger.log("Reconnection maximum attempts reached"):(1===e?this.logger.log(`Reconnection attempt ${e} of ${t} - trying`):this.logger.log(`Reconnection attempt ${e} of ${t} - trying in ${i} seconds`),this.attemptingReconnection=!0,setTimeout(()=>{if(!this.shouldBeConnected)return this.logger.log(`Reconnection attempt ${e} of ${t} - aborted`),void(this.attemptingReconnection=!1);this.userAgent.reconnect().then(()=>{this.logger.log(`Reconnection attempt ${e} of ${t} - succeeded`),this.attemptingReconnection=!1}).catch(i=>{this.logger.log(`Reconnection attempt ${e} of ${t} - failed`),this.logger.error(i.message),this.attemptingReconnection=!1,this.attemptReconnection(++e)})},1===e?0:1e3*i))):this.logger.log("Should not be connected currently")}attemptRegistration(e=!1){if(this.logger.log("Registration attempt "+(e?"without delay":"")),!this.shouldBeRegistered)return this.logger.log("Should not be registered currently"),Promise.resolve();if(void 0!==this.registrationAttemptTimeout)return this.logger.log("Registration attempt already in progress"),Promise.resolve();const t=()=>this.registerer?this.isConnected()?this.userAgent.state===le.Stopped?(this.logger.log("User agent stopped"),Promise.resolve()):this.options.registerGuard?this.options.registerGuard().catch(e=>{throw this.logger.log("Register guard rejected will making registration attempt"),e}).then(e=>e||!this.registerer?Promise.resolve():this.registerer.register(this.registererRegisterOptions).then(()=>{})):this.registerer.register(this.registererRegisterOptions).then(()=>{}):(this.logger.log("User agent not connected"),Promise.resolve()):(this.logger.log("Registerer undefined"),Promise.resolve());return new Promise((i,r)=>{this.registrationAttemptTimeout=setTimeout(()=>{t().then(()=>{this.registrationAttemptTimeout=void 0,i()}).catch(e=>{this.registrationAttemptTimeout=void 0,e instanceof c?i():r(e)})},e?0:(e=>{const t=2*e;return 1e3*(Math.random()*(t-e)+e)})(this.options.registrationRetryInterval))})}cleanupMedia(e){const t=this.sessionManaged(e);if(!t)throw new Error("Managed session does not exist.");t.mediaLocal&&t.mediaLocal.video&&(t.mediaLocal.video.srcObject=null,t.mediaLocal.video.pause()),t.mediaRemote&&(t.mediaRemote.audio&&(t.mediaRemote.audio.srcObject=null,t.mediaRemote.audio.pause()),t.mediaRemote.video&&(t.mediaRemote.video.srcObject=null,t.mediaRemote.video.pause()))}enableReceiverTracks(e,t){if(!this.sessionExists(e))throw new Error("Session does not exist.");const i=e.sessionDescriptionHandler;if(!(i instanceof rt))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");i.enableReceiverTracks(t)}enableSenderTracks(e,t){if(!this.sessionExists(e))throw new Error("Session does not exist.");const i=e.sessionDescriptionHandler;if(!(i instanceof rt))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");i.enableSenderTracks(t)}initSession(t,i){this.sessionAdd(t),this.delegate&&this.delegate.onCallCreated&&this.delegate.onCallCreated(t),t.stateChange.addListener(i=>{switch(this.logger.log(`[${t.id}] Session state changed to ${i}`),i){case e.SessionState.Initial:case e.SessionState.Establishing:break;case e.SessionState.Established:this.setupLocalMedia(t),this.setupRemoteMedia(t),this.delegate&&this.delegate.onCallAnswered&&this.delegate.onCallAnswered(t);break;case e.SessionState.Terminating:case e.SessionState.Terminated:this.sessionExists(t)&&(this.cleanupMedia(t),this.sessionRemove(t),this.delegate&&this.delegate.onCallHangup&&this.delegate.onCallHangup(t));break;default:throw new Error("Unknown session state.")}}),t.delegate=t.delegate||{},t.delegate.onInfo=e=>{var i;if(void 0===(null===(i=this.delegate)||void 0===i?void 0:i.onCallDTMFReceived))return void e.reject();const r=e.request.getHeader("content-type");if(!r||!/^application\/dtmf-relay/i.exec(r))return void e.reject();const s=e.request.body.split("\r\n",2);if(2!==s.length)return void e.reject();let n;const o=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;if(void 0!==s[0]&&o.test(s[0])&&(n=s[0].replace(o,"$2")),!n)return void e.reject();let a;const c=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;void 0!==s[1]&&c.test(s[1])&&(a=parseInt(s[1].replace(c,"$2"),10)),a?e.accept().then(()=>{if(this.delegate&&this.delegate.onCallDTMFReceived){if(!n||!a)throw new Error("Tone or duration undefined.");this.delegate.onCallDTMFReceived(t,n,a)}}).catch(e=>{this.logger.error(e.message)}):e.reject()},t.delegate.onRefer=e=>{e.accept().then(()=>this.sendInvite(e.makeInviter(i),i)).catch(e=>{this.logger.error(e.message)})}}optionsPingRun(e,t,i){if(this.options.optionsPingInterval<1)throw new Error("Invalid options ping interval.");this.optionsPingRunning||(this.optionsPingRunning=!0,this.optionsPingTimeout=setTimeout(()=>{this.optionsPingTimeout=void 0;const r=()=>{this.optionsPingFailure=!1,this.optionsPingRunning&&(this.optionsPingRunning=!1,this.optionsPingRun(e,t,i))},s=()=>{this.logger.error("OPTIONS ping failed"),this.optionsPingFailure=!0,this.optionsPingRunning=!1,this.userAgent.transport.disconnect().catch(e=>this.logger.error(e))},n=this.userAgent.userAgentCore,o=n.makeOutgoingRequestMessage("OPTIONS",e,t,i,{});this.optionsPingRequest=n.request(o,{onAccept:()=>{this.optionsPingRequest=void 0,r()},onReject:e=>{this.optionsPingRequest=void 0,408===e.message.statusCode||503===e.message.statusCode?s():r()}})},1e3*this.options.optionsPingInterval))}optionsPingStart(){let e,t,i;if(this.logger.log("OPTIONS pings started"),this.options.optionsPingRequestURI){if(e=ot.makeURI(this.options.optionsPingRequestURI),!e)throw new Error("Failed to create Request URI.");t=this.userAgent.contact.uri.clone(),i=this.userAgent.contact.uri.clone()}else{if(!this.options.aor)return void this.logger.error("You have enabled sending OPTIONS pings and as such you must provide either a) an AOR to register, or b) an RURI to use for the target of the OPTIONS ping requests. ");{const r=ot.makeURI(this.options.aor);if(!r)throw new Error("Failed to create URI.");e=r.clone(),e.user=void 0,t=r.clone(),i=r.clone()}}this.optionsPingRun(e,t,i)}optionsPingStop(){this.logger.log("OPTIONS pings stopped"),this.optionsPingRunning=!1,this.optionsPingFailure=!1,this.optionsPingRequest&&(this.optionsPingRequest.dispose(),this.optionsPingRequest=void 0),this.optionsPingTimeout&&(clearTimeout(this.optionsPingTimeout),this.optionsPingTimeout=void 0)}sendInvite(e,t,i){return r(this,void 0,void 0,function*(){return this.initSession(e,t),e.invite(i).then(()=>{this.logger.log(`[${e.id}] Sent INVITE`)})})}sessionAdd(e){const t=this.options.managedSessionFactory(this,e);this.managedSessions.push(t)}sessionExists(e){return void 0!==this.sessionManaged(e)}sessionManaged(e){return this.managedSessions.find(t=>t.session.id===e.id)}sessionRemove(e){this.managedSessions=this.managedSessions.filter(t=>t.session.id!==e.id)}setHold(e,t){return r(this,void 0,void 0,function*(){if(!this.sessionExists(e))return Promise.reject(new Error("Session does not exist."));if(this.isHeld(e)===t)return Promise.resolve();if(!(e.sessionDescriptionHandler instanceof rt))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");const i={requestDelegate:{onAccept:()=>{const i=this.sessionManaged(e);void 0!==i&&(i.held=t,this.enableReceiverTracks(e,!i.held),this.enableSenderTracks(e,!i.held&&!i.muted),this.delegate&&this.delegate.onCallHold&&this.delegate.onCallHold(e,i.held))},onReject:()=>{this.logger.warn(`[${e.id}] Re-invite request was rejected`);const i=this.sessionManaged(e);void 0!==i&&(i.held=!t,this.enableReceiverTracks(e,!i.held),this.enableSenderTracks(e,!i.held&&!i.muted),this.delegate&&this.delegate.onCallHold&&this.delegate.onCallHold(e,i.held))}}},r=e.sessionDescriptionHandlerOptionsReInvite;r.hold=t,e.sessionDescriptionHandlerOptionsReInvite=r;const s=this.sessionManaged(e);if(!s)throw new Error("Managed session is undefiend.");return s.held=t,e.invite(i).then(()=>{const t=this.sessionManaged(e);void 0!==t&&(this.enableReceiverTracks(e,!t.held),this.enableSenderTracks(e,!t.held&&!t.muted))}).catch(i=>{throw s.held=!t,i instanceof c&&this.logger.error(`[${e.id}] A hold request is already in progress.`),i})})}setMute(t,i){if(!this.sessionExists(t))return void this.logger.warn(`[${t.id}] A session is required to enabled/disable media tracks`);if(t.state!==e.SessionState.Established)return void this.logger.warn(`[${t.id}] An established session is required to enable/disable media tracks`);const r=this.sessionManaged(t);void 0!==r&&(r.muted=i,this.enableSenderTracks(t,!r.held&&!r.muted))}setupLocalMedia(e){const t=this.sessionManaged(e);if(!t)throw new Error("Managed session does not exist.");const i="function"==typeof this.options.media.local?this.options.media.local(e):this.options.media.local;t.mediaLocal=i;const r=null==i?void 0:i.video;if(r){const t=this.getLocalMediaStream(e);if(!t)throw new Error("Local media stream undefiend.");r.srcObject=t,r.volume=0,r.play().catch(t=>{this.logger.error(`[${e.id}] Failed to play local media`),this.logger.error(t.message)})}}setupRemoteMedia(e){const t=this.sessionManaged(e);if(!t)throw new Error("Managed session does not exist.");const i="function"==typeof this.options.media.remote?this.options.media.remote(e):this.options.media.remote;t.mediaRemote=i;const r=(null==i?void 0:i.video)||(null==i?void 0:i.audio);if(r){const t=this.getRemoteMediaStream(e);if(!t)throw new Error("Remote media stream undefiend.");r.autoplay=!0,r.srcObject=t,r.play().catch(t=>{this.logger.error(`[${e.id}] Failed to play remote media`),this.logger.error(t.message)}),t.onaddtrack=()=>{this.logger.log("Remote media onaddtrack"),r.load(),r.play().catch(t=>{this.logger.error(`[${e.id}] Failed to play remote media`),this.logger.error(t.message)})}}}terminate(t){return r(this,void 0,void 0,function*(){switch(this.logger.log(`[${t.id}] Terminating...`),t.state){case e.SessionState.Initial:if(t instanceof ie)return t.cancel().then(()=>{this.logger.log(`[${t.id}] Inviter never sent INVITE (canceled)`)});if(t instanceof te)return t.reject().then(()=>{this.logger.log(`[${t.id}] Invitation rejected (sent 480)`)});throw new Error("Unknown session type.");case e.SessionState.Establishing:if(t instanceof ie)return t.cancel().then(()=>{this.logger.log(`[${t.id}] Inviter canceled (sent CANCEL)`)});if(t instanceof te)return t.reject().then(()=>{this.logger.log(`[${t.id}] Invitation rejected (sent 480)`)});throw new Error("Unknown session type.");case e.SessionState.Established:return t.bye().then(()=>{this.logger.log(`[${t.id}] Session ended (sent BYE)`)});case e.SessionState.Terminating:case e.SessionState.Terminated:break;default:throw new Error("Unknown state")}return this.logger.log(`[${t.id}] Terminating in state ${t.state}, no action taken`),Promise.resolve()})}}const ct=".",lt=Symbol("target"),ht=Symbol("unsubscribe");function dt(e){return e instanceof Date||e instanceof Set||e instanceof Map||e instanceof WeakSet||e instanceof WeakMap||ArrayBuffer.isView(e)}var ut=Array.isArray;function gt(e){return"symbol"==typeof e}const ft={after:(e,t)=>ut(e)?e.slice(t.length):""===t?e:e.slice(t.length+1),concat:(e,t)=>ut(e)?(e=[...e],t&&e.push(t),e):t&&void 0!==t.toString?(""!==e&&(e+=ct),gt(t)?e+t.toString():e+t):e,initial:e=>{if(ut(e))return e.slice(0,-1);if(""===e)return e;const t=e.lastIndexOf(ct);return-1===t?"":e.slice(0,t)},last:e=>{if(ut(e))return e[e.length-1]||"";if(""===e)return e;const t=e.lastIndexOf(ct);return-1===t?e:e.slice(t+1)},walk:(e,t)=>{if(ut(e))for(const i of e)t(i);else if(""!==e){let i=0,r=e.indexOf(ct);if(-1===r)t(e);else for(;i<e.length;)-1===r&&(r=e.length),t(e.slice(i,r)),i=r+1,r=e.indexOf(ct,i)}},get(e,t){return this.walk(t,t=>{e&&(e=e[t])}),e}};function pt(e,t,i){return e.isUnsubscribed||t.ignoreSymbols&&gt(i)||t.ignoreUnderscores&&"_"===i.charAt(0)||"ignoreKeys"in t&&t.ignoreKeys.includes(i)}class vt{constructor(e){this._equals=e,this._proxyCache=new WeakMap,this._pathCache=new WeakMap,this.isUnsubscribed=!1}_getDescriptorCache(){return void 0===this._descriptorCache&&(this._descriptorCache=new WeakMap),this._descriptorCache}_getProperties(e){const t=this._getDescriptorCache();let i=t.get(e);return void 0===i&&(i={},t.set(e,i)),i}_getOwnPropertyDescriptor(e,t){if(this.isUnsubscribed)return Reflect.getOwnPropertyDescriptor(e,t);const i=this._getProperties(e);let r=i[t];return void 0===r&&(r=Reflect.getOwnPropertyDescriptor(e,t),i[t]=r),r}getProxy(e,t,i,r){if(this.isUnsubscribed)return e;const s=e[r],n=s||e;this._pathCache.set(n,t);let o=this._proxyCache.get(n);return void 0===o&&(o=void 0===s?new Proxy(e,i):e,this._proxyCache.set(n,o)),o}getPath(e){return this.isUnsubscribed?void 0:this._pathCache.get(e)}isDetached(e,t){return!Object.is(e,ft.get(t,this.getPath(e)))}defineProperty(e,t,i){return!!Reflect.defineProperty(e,t,i)&&(this.isUnsubscribed||(this._getProperties(e)[t]=i),!0)}setProperty(e,t,i,r,s){if(!this._equals(s,i)||!(t in e)){const s=this._getOwnPropertyDescriptor(e,t);return void 0!==s&&"set"in s?Reflect.set(e,t,i,r):Reflect.set(e,t,i)}return!0}deleteProperty(e,t,i){if(Reflect.deleteProperty(e,t)){if(!this.isUnsubscribed){const r=this._getDescriptorCache().get(e);r&&(delete r[t],this._pathCache.delete(i))}return!0}return!1}isSameDescriptor(e,t,i){const r=this._getOwnPropertyDescriptor(t,i);return void 0!==e&&void 0!==r&&Object.is(e.value,r.value)&&(e.writable||!1)===(r.writable||!1)&&(e.enumerable||!1)===(r.enumerable||!1)&&(e.configurable||!1)===(r.configurable||!1)&&e.get===r.get&&e.set===r.set}isGetInvariant(e,t){const i=this._getOwnPropertyDescriptor(e,t);return void 0!==i&&!0!==i.configurable&&!0!==i.writable}unsubscribe(){this._descriptorCache=null,this._pathCache=null,this._proxyCache=null,this.isUnsubscribed=!0}}function mt(e){return"[object Object]"===toString.call(e)}function bt(){return!0}function yt(e,t){return e.length!==t.length||e.some((e,i)=>t[i]!==e)}const wt=new Set(["hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]),St=new Set(["concat","includes","indexOf","join","keys","lastIndexOf"]),Tt={push:bt,pop:bt,shift:bt,unshift:bt,copyWithin:yt,reverse:yt,sort:yt,splice:yt,flat:yt,fill:yt},Rt=new Set([...wt,...St,...Object.keys(Tt)]);function Et(e,t){if(e.size!==t.size)return!0;for(const i of e)if(!t.has(i))return!0;return!1}const It=["keys","values","entries"],Ct=new Set(["has","toString"]),Pt={add:Et,clear:Et,delete:Et,forEach:Et},At=new Set([...Ct,...Object.keys(Pt),...It]);function Ot(e,t){if(e.size!==t.size)return!0;let i;for(const[r,s]of e)if(i=t.get(r),i!==s||void 0===i&&!t.has(r))return!0;return!1}const kt=new Set([...Ct,"get"]),Dt={set:Ot,clear:Ot,delete:Ot,forEach:Ot},$t=new Set([...kt,...Object.keys(Dt),...It]);class jt{constructor(e,t,i,r){this._path=t,this._isChanged=!1,this._clonedCache=new Set,this._hasOnValidate=r,this._changes=r?[]:null,this.clone=void 0===t?e:this._shallowClone(e)}static isHandledMethod(e){return wt.has(e)}_shallowClone(e){let t=e;if(mt(e))t={...e};else if(ut(e)||ArrayBuffer.isView(e))t=[...e];else if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set([...e].map(e=>this._shallowClone(e)));else if(e instanceof Map){t=new Map;for(const[i,r]of e.entries())t.set(i,this._shallowClone(r))}return this._clonedCache.add(t),t}preferredThisArg(e,t,i,r){return e?(ut(r)?this._onIsChanged=Tt[t]:r instanceof Set?this._onIsChanged=Pt[t]:r instanceof Map&&(this._onIsChanged=Dt[t]),r):i}update(e,t,i){const r=ft.after(e,this._path);if("length"!==t){let e=this.clone;ft.walk(r,t=>{e&&e[t]&&(this._clonedCache.has(e[t])||(e[t]=this._shallowClone(e[t])),e=e[t])}),this._hasOnValidate&&this._changes.push({path:r,property:t,previous:i}),e&&e[t]&&(e[t]=i)}this._isChanged=!0}undo(e){let t;for(let i=this._changes.length-1;-1!==i;i--)t=this._changes[i],ft.get(e,t.path)[t.property]=t.previous}isChanged(e){return void 0===this._onIsChanged?this._isChanged:this._onIsChanged(this.clone,e)}}class _t extends jt{static isHandledMethod(e){return Rt.has(e)}}class Ht extends jt{undo(e){e.setTime(this.clone.getTime())}isChanged(e,t){return!t(this.clone.valueOf(),e.valueOf())}}class Mt extends jt{static isHandledMethod(e){return At.has(e)}undo(e){for(const t of this.clone)e.add(t);for(const t of e)this.clone.has(t)||e.delete(t)}}class xt extends jt{static isHandledMethod(e){return $t.has(e)}undo(e){for(const[t,i]of this.clone.entries())e.set(t,i);for(const t of e.keys())this.clone.has(t)||e.delete(t)}}class qt extends jt{constructor(e,t,i,r){super(void 0,t,i,r),this._arg1=i[0],this._weakValue=e.has(this._arg1)}isChanged(e){return this._weakValue!==e.has(this._arg1)}undo(e){this._weakValue&&!e.has(this._arg1)?e.add(this._arg1):e.delete(this._arg1)}}class Nt extends jt{constructor(e,t,i,r){super(void 0,t,i,r),this._weakKey=i[0],this._weakHas=e.has(this._weakKey),this._weakValue=e.get(this._weakKey)}isChanged(e){return this._weakValue!==e.get(this._weakKey)}undo(e){const t=e.has(this._weakKey);this._weakHas&&!t?e.set(this._weakKey,this._weakValue):!this._weakHas&&t?e.delete(this._weakKey):this._weakValue!==e.get(this._weakKey)&&e.set(this._weakKey,this._weakValue)}}class Ft{constructor(e){this._stack=[],this._hasOnValidate=e}static isHandledType(e){return mt(e)||ut(e)||dt(e)}static isHandledMethod(e,t){return mt(e)?jt.isHandledMethod(t):ut(e)?_t.isHandledMethod(t):e instanceof Set?Mt.isHandledMethod(t):e instanceof Map?xt.isHandledMethod(t):dt(e)}get isCloning(){return this._stack.length>0}start(e,t,i){let r=jt;ut(e)?r=_t:e instanceof Date?r=Ht:e instanceof Set?r=Mt:e instanceof Map?r=xt:e instanceof WeakSet?r=qt:e instanceof WeakMap&&(r=Nt),this._stack.push(new r(e,t,i,this._hasOnValidate))}update(e,t,i){this._stack[this._stack.length-1].update(e,t,i)}preferredThisArg(e,t,i){const{name:r}=e,s=Ft.isHandledMethod(i,r);return this._stack[this._stack.length-1].preferredThisArg(s,r,t,i)}isChanged(e,t,i){return this._stack[this._stack.length-1].isChanged(e,t,i)}undo(e){void 0!==this._previousClone&&this._previousClone.undo(e)}stop(){return this._previousClone=this._stack.pop(),this._previousClone.clone}}const Ut={equals:Object.is,isShallow:!1,pathAsArray:!1,ignoreSymbols:!1,ignoreUnderscores:!1,ignoreDetached:!1,details:!1},Lt=(e,t,i={})=>{i={...Ut,...i};const r=Symbol("ProxyTarget"),{equals:s,isShallow:n,ignoreDetached:o,details:a}=i,c=new vt(s),l="function"==typeof i.onValidate,h=new Ft(l),d=(e,t,r,s,n)=>!l||h.isCloning||!0===i.onValidate(ft.concat(c.getPath(e),t),r,s,n),u=(t,r,s,n)=>{pt(c,i,r)||o&&c.isDetached(t,e)||g(c.getPath(t),r,s,n)},g=(e,i,r,s,n)=>{h.isCloning?h.update(e,i,s):t(ft.concat(e,i),r,s,n)},f=e=>e&&e[r]||e,p=(t,s,a,l)=>function(e){return("object"==typeof e?null===e:"function"!=typeof e)||e instanceof RegExp}(t)||"constructor"===a||n&&!Ft.isHandledMethod(s,a)||pt(c,i,a)||c.isGetInvariant(s,a)||o&&c.isDetached(s,e)?t:(void 0===l&&(l=c.getPath(s)),c.getProxy(t,ft.concat(l,a),v,r)),v={get(e,t,i){if(gt(t)){if(t===r||t===lt)return e;if(t===ht&&!c.isUnsubscribed&&0===c.getPath(e).length)return c.unsubscribe(),e}const s=dt(e)?Reflect.get(e,t):Reflect.get(e,t,i);return p(s,e,t)},set(e,t,i,n){i=f(i);const o=e[r]||e,a=o[t];if(s(a,i)&&t in e)return!0;const l=d(e,t,i,a);return l&&c.setProperty(o,t,i,n,a)?(u(e,t,e[t],a),!0):!l},defineProperty(e,t,i){if(!c.isSameDescriptor(i,e,t)){const r=e[t];d(e,t,i.value,r)&&c.defineProperty(e,t,i,r)&&u(e,t,i.value,r)}return!0},deleteProperty(e,t){if(!Reflect.has(e,t))return!0;const i=Reflect.get(e,t),r=d(e,t,void 0,i);return r&&c.deleteProperty(e,t,i)?(u(e,t,void 0,i),!0):!r},apply(t,i,n){const o=i[r]||i;if(c.isUnsubscribed)return Reflect.apply(t,o,n);if((!1===a||!0!==a&&!a.includes(t.name))&&Ft.isHandledType(o)){let r=ft.initial(c.getPath(t));const a=Ft.isHandledMethod(o,t.name);h.start(o,r,n);let u=Reflect.apply(t,h.preferredThisArg(t,i,o),a?n.map(e=>f(e)):n);const m=h.isChanged(o,s),b=h.stop();if(Ft.isHandledType(u)&&a&&(i instanceof Map&&"get"===t.name&&(r=ft.concat(r,n[0])),u=c.getProxy(u,r,v)),m){const i={name:t.name,args:n,result:u},s=h.isCloning?ft.initial(r):r,a=h.isCloning?ft.last(r):"";d(ft.get(e,s),a,o,b,i)?g(s,a,o,b,i):h.undo(o)}return(i instanceof Map||i instanceof Set)&&("object"==typeof(l=u)&&"function"==typeof l.next)?function(e,t,i,r,s){const n=e.next;if("entries"===t.name)e.next=function(){const e=n.call(this);return!1===e.done&&(e.value[0]=s(e.value[0],t,e.value[0],r),e.value[1]=s(e.value[1],t,e.value[0],r)),e};else if("values"===t.name){const o=i[lt].keys();e.next=function(){const e=n.call(this);return!1===e.done&&(e.value=s(e.value,t,o.next().value,r)),e}}else e.next=function(){const e=n.call(this);return!1===e.done&&(e.value=s(e.value,t,e.value,r)),e};return e}(u,t,i,r,p):u}var l;return Reflect.apply(t,i,n)}},m=c.getProxy(e,i.pathAsArray?[]:"",v);return t=t.bind(m),l&&(i.onValidate=i.onValidate.bind(m)),m};function Bt(e){return document.getElementById(e)}function Wt(e){if(e&&e.getTracks)try{e.getTracks().forEach(e=>{try{e.stop()}catch(e){}})}catch(e){}}function Gt(e){return navigator.mediaDevices.getUserMedia(e).then(e=>e?(Wt(e),!0):Promise.reject(new Error("EmptyStreamError"))).catch(e=>(!e||"NotAllowedError"!==e.name)&&Promise.reject(e))}Lt.target=e=>e&&e[lt]||e,Lt.unsubscribe=e=>e[ht]||e;const Vt=e=>e.getHours().toString().padStart(2,"0")+":"+e.getMinutes().toString().padStart(2,"0")+":"+e.getSeconds().toString().padStart(2,"0"),Kt=()=>new Date(new Date((new Date).toLocaleDateString()).getTime()),zt=e=>new Date(e.setSeconds(e.getSeconds()+1));function Yt(e,t,i){const r=window.XMLHttpRequest?new window.XMLHttpRequest:window.ActiveXObject?new window.ActiveXObject("Microsoft.XMLHTTP"):void 0;r||t(new Error("Your Browser does not support ajax")),r.onreadystatechange=function(){if(4==r.readyState){const i=r.response||r.responseText;if(200==r.status){const t=r.getResponseHeader("Content-Type");-1!=t.indexOf("json")?e(JSON.parse(r.responseText)):-1!=t.indexOf("xml")?e(r.responseXML):e(r.responseText)}else t(i)}};const{url:s,data:n,type:o,contentType:a}=i,c=o||"POST";let l=s,h=null;return n&&("GET"===c?l=l+"?"+function(e){let t=[];for(let i in e)t.push(i+"="+e[i]);return t.join("&")}(n):"POST"===c&&(h=JSON.stringify(n))),r.open(c,l,!0),{xhr:r,ajaxData:h,contentType:a}}function Jt(){const e=new Date,t=e.getUTCFullYear(),i=e.getUTCMonth()+1,r=e.getUTCDate(),s=e.getUTCHours(),n=e.getUTCMinutes(),o=e.getUTCSeconds(),a=new Date(Date.UTC(t,i-1,r,s+8,n,o)),c=e=>String(e).padStart(2,"0");return`${a.getUTCFullYear()}-${c(a.getUTCMonth()+1)}-${c(a.getUTCDate())} ${c(a.getUTCHours())}:${c(a.getUTCMinutes())}:${c(a.getUTCSeconds())}`}const Zt={authorizationPassword:"",authorizationUsername:"",viaHost:"",uri:ot.makeURI("sip:@"),logLevel:"error",transportOptions:{server:"://"},contactName:""},Xt={connectStatus:!1,registerStatus:!1,invitatingStatus:!1,incomingStatus:!1,answerStatus:!1,reconnectStatus:!1};var Qt,ei,ti,ii;!function(e){e.NO="0",e.YES="1"}(Qt||(Qt={})),function(e){e.NO="0",e.YES="1"}(ei||(ei={})),function(e){e.MULTI_AI="1",e.MULTI_VOICE_NOTIFY="2",e.MULTI_PRETEST="3",e.LABOUR="4",e.AI="5",e.NEW_VOICE_NOTIFY="6"}(ti||(ti={})),function(e){e.DIRECT_ANSWER="1",e.LISTEN_FIRST_AND_THEN_ANSWER_MANUALLY="2"}(ii||(ii={}));var ri="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function si(e,t){return e(t={exports:{}},t.exports),t.exports}var ni,oi,ai=function(e){return e&&e.Math===Math&&e},ci=ai("object"==typeof globalThis&&globalThis)||ai("object"==typeof window&&window)||ai("object"==typeof self&&self)||ai("object"==typeof ri&&ri)||ai("object"==typeof ri&&ri)||function(){return this}()||Function("return this")(),li=function(e){try{return!!e()}catch(e){return!0}},hi=!li(function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")}),di=Function.prototype,ui=di.apply,gi=di.call,fi="object"==typeof Reflect&&Reflect.apply||(hi?gi.bind(ui):function(){return gi.apply(ui,arguments)}),pi=Function.prototype,vi=pi.call,mi=hi&&pi.bind.bind(vi,vi),bi=hi?mi:function(e){return function(){return vi.apply(e,arguments)}},yi=bi({}.toString),wi=bi("".slice),Si=function(e){return wi(yi(e),8,-1)},Ti=function(e){if("Function"===Si(e))return bi(e)},Ri="object"==typeof document&&document.all,Ei=void 0===Ri&&void 0!==Ri?function(e){return"function"==typeof e||e===Ri}:function(e){return"function"==typeof e},Ii=!li(function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]}),Ci=Function.prototype.call,Pi=hi?Ci.bind(Ci):function(){return Ci.apply(Ci,arguments)},Ai={}.propertyIsEnumerable,Oi=Object.getOwnPropertyDescriptor,ki=Oi&&!Ai.call({1:2},1)?function(e){var t=Oi(this,e);return!!t&&t.enumerable}:Ai,Di={f:ki},$i=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},ji=Object,_i=bi("".split),Hi=li(function(){return!ji("z").propertyIsEnumerable(0)})?function(e){return"String"===Si(e)?_i(e,""):ji(e)}:ji,Mi=function(e){return null==e},xi=TypeError,qi=function(e){if(Mi(e))throw new xi("Can't call method on "+e);return e},Ni=function(e){return Hi(qi(e))},Fi=function(e){return"object"==typeof e?null!==e:Ei(e)},Ui={},Li=function(e){return Ei(e)?e:void 0},Bi=function(e,t){return arguments.length<2?Li(Ui[e])||Li(ci[e]):Ui[e]&&Ui[e][t]||ci[e]&&ci[e][t]},Wi=bi({}.isPrototypeOf),Gi=ci.navigator,Vi=Gi&&Gi.userAgent,Ki=Vi?String(Vi):"",zi=ci.process,Yi=ci.Deno,Ji=zi&&zi.versions||Yi&&Yi.version,Zi=Ji&&Ji.v8;Zi&&(oi=(ni=Zi.split("."))[0]>0&&ni[0]<4?1:+(ni[0]+ni[1])),!oi&&Ki&&(!(ni=Ki.match(/Edge\/(\d+)/))||ni[1]>=74)&&(ni=Ki.match(/Chrome\/(\d+)/))&&(oi=+ni[1]);var Xi=oi,Qi=ci.String,er=!!Object.getOwnPropertySymbols&&!li(function(){var e=Symbol("symbol detection");return!Qi(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&Xi&&Xi<41}),tr=er&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,ir=Object,rr=tr?function(e){return"symbol"==typeof e}:function(e){var t=Bi("Symbol");return Ei(t)&&Wi(t.prototype,ir(e))},sr=String,nr=function(e){try{return sr(e)}catch(e){return"Object"}},or=TypeError,ar=function(e){if(Ei(e))return e;throw new or(nr(e)+" is not a function")},cr=function(e,t){var i=e[t];return Mi(i)?void 0:ar(i)},lr=TypeError,hr=!0,dr=Object.defineProperty,ur=si(function(e){var t="__core-js_shared__",i=e.exports=ci[t]||function(e,t){try{dr(ci,e,{value:t,configurable:!0,writable:!0})}catch(i){ci[e]=t}return t}(t,{});(i.versions||(i.versions=[])).push({version:"3.46.0",mode:"pure",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru), 2025 CoreJS Company (core-js.io)",license:"https://github.com/zloirock/core-js/blob/v3.46.0/LICENSE",source:"https://github.com/zloirock/core-js"})}),gr=function(e,t){return ur[e]||(ur[e]=t||{})},fr=Object,pr=function(e){return fr(qi(e))},vr=bi({}.hasOwnProperty),mr=Object.hasOwn||function(e,t){return vr(pr(e),t)},br=0,yr=Math.random(),wr=bi(1.1.toString),Sr=function(e){return"Symbol("+(void 0===e?"":e)+")_"+wr(++br+yr,36)},Tr=ci.Symbol,Rr=gr("wks"),Er=tr?Tr.for||Tr:Tr&&Tr.withoutSetter||Sr,Ir=function(e){return mr(Rr,e)||(Rr[e]=er&&mr(Tr,e)?Tr[e]:Er("Symbol."+e)),Rr[e]},Cr=TypeError,Pr=Ir("toPrimitive"),Ar=function(e,t){if(!Fi(e)||rr(e))return e;var i,r=cr(e,Pr);if(r){if(void 0===t&&(t="default"),i=Pi(r,e,t),!Fi(i)||rr(i))return i;throw new Cr("Can't convert object to primitive value")}return void 0===t&&(t="number"),function(e,t){var i,r;if("string"===t&&Ei(i=e.toString)&&!Fi(r=Pi(i,e)))return r;if(Ei(i=e.valueOf)&&!Fi(r=Pi(i,e)))return r;if("string"!==t&&Ei(i=e.toString)&&!Fi(r=Pi(i,e)))return r;throw new lr("Can't convert object to primitive value")}(e,t)},Or=function(e){var t=Ar(e,"string");return rr(t)?t:t+""},kr=ci.document,Dr=Fi(kr)&&Fi(kr.createElement),$r=function(e){return Dr?kr.createElement(e):{}},jr=!Ii&&!li(function(){return 7!==Object.defineProperty($r("div"),"a",{get:function(){return 7}}).a}),_r=Object.getOwnPropertyDescriptor,Hr={f:Ii?_r:function(e,t){if(e=Ni(e),t=Or(t),jr)try{return _r(e,t)}catch(e){}if(mr(e,t))return $i(!Pi(Di.f,e,t),e[t])}},Mr=/#|\.prototype\./,xr=function(e,t){var i=Nr[qr(e)];return i===Ur||i!==Fr&&(Ei(t)?li(t):!!t)},qr=xr.normalize=function(e){return String(e).replace(Mr,".").toLowerCase()},Nr=xr.data={},Fr=xr.NATIVE="N",Ur=xr.POLYFILL="P",Lr=xr,Br=Ti(Ti.bind),Wr=function(e,t){return ar(e),void 0===t?e:hi?Br(e,t):function(){return e.apply(t,arguments)}},Gr=Ii&&li(function(){return 42!==Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype}),Vr=String,Kr=TypeError,zr=function(e){if(Fi(e))return e;throw new Kr(Vr(e)+" is not an object")},Yr=TypeError,Jr=Object.defineProperty,Zr=Object.getOwnPropertyDescriptor,Xr="enumerable",Qr="configurable",es="writable",ts={f:Ii?Gr?function(e,t,i){if(zr(e),t=Or(t),zr(i),"function"==typeof e&&"prototype"===t&&"value"in i&&es in i&&!i[es]){var r=Zr(e,t);r&&r[es]&&(e[t]=i.value,i={configurable:Qr in i?i[Qr]:r[Qr],enumerable:Xr in i?i[Xr]:r[Xr],writable:!1})}return Jr(e,t,i)}:Jr:function(e,t,i){if(zr(e),t=Or(t),zr(i),jr)try{return Jr(e,t,i)}catch(e){}if("get"in i||"set"in i)throw new Yr("Accessors not supported");return"value"in i&&(e[t]=i.value),e}},is=Ii?function(e,t,i){return ts.f(e,t,$i(1,i))}:function(e,t,i){return e[t]=i,e},rs=Hr.f,ss=function(e){var t=function(i,r,s){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(i);case 2:return new e(i,r)}return new e(i,r,s)}return fi(e,this,arguments)};return t.prototype=e.prototype,t},ns=function(e,t){var i,r,s,n,o,a,c,l,h,d=e.target,u=e.global,g=e.stat,f=e.proto,p=u?ci:g?ci[d]:ci[d]&&ci[d].prototype,v=u?Ui:Ui[d]||is(Ui,d,{})[d],m=v.prototype;for(n in t)r=!(i=Lr(u?n:d+(g?".":"#")+n,e.forced))&&p&&mr(p,n),a=v[n],r&&(c=e.dontCallGetSet?(h=rs(p,n))&&h.value:p[n]),o=r&&c?c:t[n],(i||f||typeof a!=typeof o)&&(l=e.bind&&r?Wr(o,ci):e.wrap&&r?ss(o):f&&Ei(o)?Ti(o):o,(e.sham||o&&o.sham||a&&a.sham)&&is(l,"sham",!0),is(v,n,l),f&&(mr(Ui,s=d+"Prototype")||is(Ui,s,{}),is(Ui[s],n,o),e.real&&m&&(i||!m[n])&&is(m,n,o)))},os=ts.f;ns({target:"Object",stat:!0,forced:Object.defineProperty!==os,sham:!Ii},{defineProperty:os});var as=si(function(e){var t=Ui.Object,i=e.exports=function(e,i,r){return t.defineProperty(e,i,r)};t.defineProperty.sham&&(i.sham=!0)}),cs=as,ls=Array.isArray||function(e){return"Array"===Si(e)},hs=Math.ceil,ds=Math.floor,us=Math.trunc||function(e){var t=+e;return(t>0?ds:hs)(t)},gs=function(e){var t=+e;return t!=t||0===t?0:us(t)},fs=Math.min,ps=function(e){return t=e.length,(i=gs(t))>0?fs(i,9007199254740991):0;var t,i},vs=TypeError,ms=function(e){if(e>9007199254740991)throw vs("Maximum allowed index exceeded");return e},bs=function(e,t,i){Ii?ts.f(e,t,$i(0,i)):e[t]=i},ys={};ys[Ir("toStringTag")]="z";var ws="[object z]"===String(ys),Ss=Ir("toStringTag"),Ts=Object,Rs="Arguments"===Si(function(){return arguments}()),Es=ws?Si:function(e){var t,i,r;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t]}catch(e){}}(t=Ts(e),Ss))?i:Rs?Si(t):"Object"===(r=Si(t))&&Ei(t.callee)?"Arguments":r},Is=bi(Function.toString);Ei(ur.inspectSource)||(ur.inspectSource=function(e){return Is(e)});var Cs=ur.inspectSource,Ps=function(){},As=Bi("Reflect","construct"),Os=/^\s*(?:class|function)\b/,ks=bi(Os.exec),Ds=!Os.test(Ps),$s=function(e){if(!Ei(e))return!1;try{return As(Ps,[],e),!0}catch(e){return!1}},js=function(e){if(!Ei(e))return!1;switch(Es(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Ds||!!ks(Os,Cs(e))}catch(e){return!0}};js.sham=!0;var _s,Hs=!As||li(function(){var e;return $s($s.call)||!$s(Object)||!$s(function(){e=!0})||e})?js:$s,Ms=Ir("species"),xs=Array,qs=function(e,t){return new(function(e){var t;return ls(e)&&(t=e.constructor,(Hs(t)&&(t===xs||ls(t.prototype))||Fi(t)&&null===(t=t[Ms]))&&(t=void 0)),void 0===t?xs:t}(e))(0===t?0:t)},Ns=Ir("species"),Fs=Ir("isConcatSpreadable"),Us=Xi>=51||!li(function(){var e=[];return e[Fs]=!1,e.concat()[0]!==e}),Ls=function(e){if(!Fi(e))return!1;var t=e[Fs];return void 0!==t?!!t:ls(e)},Bs=!(Us&&(_s="concat",Xi>=51||!li(function(){var e=[];return(e.constructor={})[Ns]=function(){return{foo:1}},1!==e[_s](Boolean).foo})));ns({target:"Array",proto:!0,arity:1,forced:Bs},{concat:function(e){var t,i,r,s,n,o=pr(this),a=qs(o,0),c=0;for(t=-1,r=arguments.length;t<r;t++)if(Ls(n=-1===t?o:arguments[t]))for(s=ps(n),ms(c+s),i=0;i<s;i++,c++)i in n&&bs(a,c,n[i]);else ms(c+1),bs(a,c++,n);return a.length=c,a}});var Ws,Gs=String,Vs=function(e){if("Symbol"===Es(e))throw new TypeError("Cannot convert a Symbol value to a string");return Gs(e)},Ks=Math.max,zs=Math.min,Ys=function(e){return function(t,i,r){var s=Ni(t),n=ps(s);if(0===n)return!e&&-1;var o,a=function(e,t){var i=gs(e);return i<0?Ks(i+t,0):zs(i,t)}(r,n);if(e&&i!=i){for(;n>a;)if((o=s[a++])!=o)return!0}else for(;n>a;a++)if((e||a in s)&&s[a]===i)return e||a||0;return!e&&-1}},Js={includes:Ys(!0),indexOf:Ys(!1)},Zs={},Xs=Js.indexOf,Qs=bi([].push),en=function(e,t){var i,r=Ni(e),s=0,n=[];for(i in r)!mr(Zs,i)&&mr(r,i)&&Qs(n,i);for(;t.length>s;)mr(r,i=t[s++])&&(~Xs(n,i)||Qs(n,i));return n},tn=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],rn=Object.keys||function(e){return en(e,tn)},sn=Ii&&!Gr?Object.defineProperties:function(e,t){zr(e);for(var i,r=Ni(t),s=rn(t),n=s.length,o=0;n>o;)ts.f(e,i=s[o++],r[i]);return e},nn={f:sn},on=Bi("document","documentElement"),an=gr("keys"),cn=function(e){return an[e]||(an[e]=Sr(e))},ln="prototype",hn="script",dn=cn("IE_PROTO"),un=function(){},gn=function(e){return"<"+hn+">"+e+"</"+hn+">"},fn=function(e){e.write(gn("")),e.close();var t=e.parentWindow.Object;return e=null,t},pn=function(){try{Ws=new ActiveXObject("htmlfile")}catch(e){}var e,t,i;pn="undefined"!=typeof document?document.domain&&Ws?fn(Ws):(t=$r("iframe"),i="java"+hn+":",t.style.display="none",on.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(gn("document.F=Object")),e.close(),e.F):fn(Ws);for(var r=tn.length;r--;)delete pn[ln][tn[r]];return pn()};Zs[dn]=!0;var vn,mn,bn,yn=Object.create||function(e,t){var i;return null!==e?(un[ln]=zr(e),i=new un,un[ln]=null,i[dn]=e):i=pn(),void 0===t?i:nn.f(i,t)},wn=tn.concat("length","prototype"),Sn={f:Object.getOwnPropertyNames||function(e){return en(e,wn)}},Tn=bi([].slice),Rn=Sn.f,En="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],In={f:function(e){return En&&"Window"===Si(e)?function(e){try{return Rn(e)}catch(e){return Tn(En)}}(e):Rn(Ni(e))}},Cn={f:Object.getOwnPropertySymbols},Pn=function(e,t,i,r){return r&&r.enumerable?e[t]=i:is(e,t,i),e},An={f:Ir},On=ts.f,kn=function(e){var t=Ui.Symbol||(Ui.Symbol={});mr(t,e)||On(t,e,{value:An.f(e)})},Dn=function(){var e=Bi("Symbol"),t=e&&e.prototype,i=t&&t.valueOf,r=Ir("toPrimitive");t&&!t[r]&&Pn(t,r,function(e){return Pi(i,this)},{arity:1})},$n=ws?{}.toString:function(){return"[object "+Es(this)+"]"},jn=ts.f,_n=Ir("toStringTag"),Hn=function(e,t,i,r){var s=i?e:e&&e.prototype;s&&(mr(s,_n)||jn(s,_n,{configurable:!0,value:t}),r&&!ws&&is(s,"toString",$n))},Mn=ci.WeakMap,xn=Ei(Mn)&&/native code/.test(String(Mn)),qn="Object already initialized",Nn=ci.TypeError,Fn=ci.WeakMap;if(xn||ur.state){var Un=ur.state||(ur.state=new Fn);Un.get=Un.get,Un.has=Un.has,Un.set=Un.set,vn=function(e,t){if(Un.has(e))throw new Nn(qn);return t.facade=e,Un.set(e,t),t},mn=function(e){return Un.get(e)||{}},bn=function(e){return Un.has(e)}}else{var Ln=cn("state");Zs[Ln]=!0,vn=function(e,t){if(mr(e,Ln))throw new Nn(qn);return t.facade=e,is(e,Ln,t),t},mn=function(e){return mr(e,Ln)?e[Ln]:{}},bn=function(e){return mr(e,Ln)}}var Bn,Wn,Gn,Vn={set:vn,get:mn,has:bn,enforce:function(e){return bn(e)?mn(e):vn(e,{})},getterFor:function(e){return function(t){var i;if(!Fi(t)||(i=mn(t)).type!==e)throw new Nn("Incompatible receiver, "+e+" required");return i}}},Kn=bi([].push),zn=function(e){var t=1===e,i=2===e,r=3===e,s=4===e,n=6===e,o=7===e,a=5===e||n;return function(c,l,h,d){for(var u,g,f=pr(c),p=Hi(f),v=ps(p),m=Wr(l,h),b=0,y=d||qs,w=t?y(c,v):i||o?y(c,0):void 0;v>b;b++)if((a||b in p)&&(g=m(u=p[b],b,f),e))if(t)w[b]=g;else if(g)switch(e){case 3:return!0;case 5:return u;case 6:return b;case 2:Kn(w,u)}else switch(e){case 4:return!1;case 7:Kn(w,u)}return n?-1:r||s?s:w}},Yn={forEach:zn(0),map:zn(1),filter:zn(2),some:zn(3),every:zn(4),find:zn(5),findIndex:zn(6),filterReject:zn(7)},Jn=Yn.forEach,Zn=cn("hidden"),Xn="Symbol",Qn="prototype",eo=Vn.set,to=Vn.getterFor(Xn),io=Object[Qn],ro=ci.Symbol,so=ro&&ro[Qn],no=ci.RangeError,oo=ci.TypeError,ao=ci.QObject,co=Hr.f,lo=ts.f,ho=In.f,uo=Di.f,go=bi([].push),fo=gr("symbols"),po=gr("op-symbols"),vo=gr("wks"),mo=!ao||!ao[Qn]||!ao[Qn].findChild,bo=function(e,t,i){var r=co(io,t);r&&delete io[t],lo(e,t,i),r&&e!==io&&lo(io,t,r)},yo=Ii&&li(function(){return 7!==yn(lo({},"a",{get:function(){return lo(this,"a",{value:7}).a}})).a})?bo:lo,wo=function(e,t){var i=fo[e]=yn(so);return eo(i,{type:Xn,tag:e,description:t}),Ii||(i.description=t),i},So=function(e,t,i){e===io&&So(po,t,i),zr(e);var r=Or(t);return zr(i),mr(fo,r)?(i.enumerable?(mr(e,Zn)&&e[Zn][r]&&(e[Zn][r]=!1),i=yn(i,{enumerable:$i(0,!1)})):(mr(e,Zn)||lo(e,Zn,$i(1,yn(null))),e[Zn][r]=!0),yo(e,r,i)):lo(e,r,i)},To=function(e,t){zr(e);var i=Ni(t),r=rn(i).concat(Co(i));return Jn(r,function(t){Ii&&!Pi(Ro,i,t)||So(e,t,i[t])}),e},Ro=function(e){var t=Or(e),i=Pi(uo,this,t);return!(this===io&&mr(fo,t)&&!mr(po,t))&&(!(i||!mr(this,t)||!mr(fo,t)||mr(this,Zn)&&this[Zn][t])||i)},Eo=function(e,t){var i=Ni(e),r=Or(t);if(i!==io||!mr(fo,r)||mr(po,r)){var s=co(i,r);return!s||!mr(fo,r)||mr(i,Zn)&&i[Zn][r]||(s.enumerable=!0),s}},Io=function(e){var t=ho(Ni(e)),i=[];return Jn(t,function(e){mr(fo,e)||mr(Zs,e)||go(i,e)}),i},Co=function(e){var t=e===io,i=ho(t?po:Ni(e)),r=[];return Jn(i,function(e){!mr(fo,e)||t&&!mr(io,e)||go(r,fo[e])}),r};er||(ro=function(){if(Wi(so,this))throw new oo("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?Vs(arguments[0]):void 0,t=Sr(e),i=function(e){var r=void 0===this?ci:this;r===io&&Pi(i,po,e),mr(r,Zn)&&mr(r[Zn],t)&&(r[Zn][t]=!1);var s=$i(1,e);try{yo(r,t,s)}catch(e){if(!(e instanceof no))throw e;bo(r,t,s)}};return Ii&&mo&&yo(io,t,{configurable:!0,set:i}),wo(t,e)},so=ro[Qn],Pn(so,"toString",function(){return to(this).tag}),Pn(ro,"withoutSetter",function(e){return wo(Sr(e),e)}),Di.f=Ro,ts.f=So,nn.f=To,Hr.f=Eo,Sn.f=In.f=Io,Cn.f=Co,An.f=function(e){return wo(Ir(e),e)},Ii&&(Bn=so,Wn="description",Gn={configurable:!0,get:function(){return to(this).description}},ts.f(Bn,Wn,Gn))),ns({global:!0,constructor:!0,wrap:!0,forced:!er,sham:!er},{Symbol:ro}),Jn(rn(vo),function(e){kn(e)}),ns({target:Xn,stat:!0,forced:!er},{useSetter:function(){mo=!0},useSimple:function(){mo=!1}}),ns({target:"Object",stat:!0,forced:!er,sham:!Ii},{create:function(e,t){return void 0===t?yn(e):To(yn(e),t)},defineProperty:So,defineProperties:To,getOwnPropertyDescriptor:Eo}),ns({target:"Object",stat:!0,forced:!er},{getOwnPropertyNames:Io}),Dn(),Hn(ro,Xn),Zs[Zn]=!0;var Po=er&&!!Symbol.for&&!!Symbol.keyFor,Ao=gr("string-to-symbol-registry"),Oo=gr("symbol-to-string-registry");ns({target:"Symbol",stat:!0,forced:!Po},{for:function(e){var t=Vs(e);if(mr(Ao,t))return Ao[t];var i=Bi("Symbol")(t);return Ao[t]=i,Oo[i]=t,i}});var ko=gr("symbol-to-string-registry");ns({target:"Symbol",stat:!0,forced:!Po},{keyFor:function(e){if(!rr(e))throw new TypeError(nr(e)+" is not a symbol");if(mr(ko,e))return ko[e]}});var Do=bi([].push),$o=String,jo=Bi("JSON","stringify"),_o=bi(/./.exec),Ho=bi("".charAt),Mo=bi("".charCodeAt),xo=bi("".replace),qo=bi(1.1.toString),No=/[\uD800-\uDFFF]/g,Fo=/^[\uD800-\uDBFF]$/,Uo=/^[\uDC00-\uDFFF]$/,Lo=!er||li(function(){var e=Bi("Symbol")("stringify detection");return"[null]"!==jo([e])||"{}"!==jo({a:e})||"{}"!==jo(Object(e))}),Bo=li(function(){return'"\\udf06\\ud834"'!==jo("\udf06\ud834")||'"\\udead"'!==jo("\udead")}),Wo=function(e,t){var i=Tn(arguments),r=function(e){if(Ei(e))return e;if(ls(e)){for(var t=e.length,i=[],r=0;r<t;r++){var s=e[r];"string"==typeof s?Do(i,s):"number"!=typeof s&&"Number"!==Si(s)&&"String"!==Si(s)||Do(i,Vs(s))}var n=i.length,o=!0;return function(e,t){if(o)return o=!1,t;if(ls(this))return t;for(var r=0;r<n;r++)if(i[r]===e)return t}}}(t);if(Ei(r)||void 0!==e&&!rr(e))return i[1]=function(e,t){if(Ei(r)&&(t=Pi(r,this,$o(e),t)),!rr(t))return t},fi(jo,null,i)},Go=function(e,t,i){var r=Ho(i,t-1),s=Ho(i,t+1);return _o(Fo,e)&&!_o(Uo,s)||_o(Uo,e)&&!_o(Fo,r)?"\\u"+qo(Mo(e,0),16):e};jo&&ns({target:"JSON",stat:!0,arity:3,forced:Lo||Bo},{stringify:function(e,t,i){var r=Tn(arguments),s=fi(Lo?Wo:jo,null,r);return Bo&&"string"==typeof s?xo(s,No,Go):s}});var Vo=!er||li(function(){Cn.f(1)});ns({target:"Object",stat:!0,forced:Vo},{getOwnPropertySymbols:function(e){var t=Cn.f;return t?t(pr(e)):[]}}),kn("asyncDispose"),kn("asyncIterator"),kn("dispose"),kn("hasInstance"),kn("isConcatSpreadable"),kn("iterator"),kn("match"),kn("matchAll"),kn("replace"),kn("search"),kn("species"),kn("split"),kn("toPrimitive"),Dn(),kn("toStringTag"),Hn(Bi("Symbol"),"Symbol"),kn("unscopables"),Hn(ci.JSON,"JSON",!0);var Ko,zo,Yo,Jo=Ui.Symbol,Zo={},Xo=Function.prototype,Qo=Ii&&Object.getOwnPropertyDescriptor,ea=mr(Xo,"name"),ta={EXISTS:ea,PROPER:ea&&"something"===function(){}.name,CONFIGURABLE:ea&&(!Ii||Ii&&Qo(Xo,"name").configurable)},ia=!li(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}),ra=cn("IE_PROTO"),sa=Object,na=sa.prototype,oa=ia?sa.getPrototypeOf:function(e){var t=pr(e);if(mr(t,ra))return t[ra];var i=t.constructor;return Ei(i)&&t instanceof i?i.prototype:t instanceof sa?na:null},aa=Ir("iterator"),ca=!1;[].keys&&("next"in(Yo=[].keys())?(zo=oa(oa(Yo)))!==Object.prototype&&(Ko=zo):ca=!0);var la=!Fi(Ko)||li(function(){var e={};return Ko[aa].call(e)!==e});Ko=la?{}:yn(Ko),Ei(Ko[aa])||Pn(Ko,aa,function(){return this});var ha={IteratorPrototype:Ko,BUGGY_SAFARI_ITERATORS:ca},da=ha.IteratorPrototype,ua=function(){return this},ga=ta.PROPER,fa=ha.BUGGY_SAFARI_ITERATORS,pa=Ir("iterator"),va="keys",ma="values",ba="entries",ya=function(){return this},wa=function(e,t,i,r,s,n,o){!function(e,t,i,r){var s=t+" Iterator";e.prototype=yn(da,{next:$i(+!r,i)}),Hn(e,s,!1,!0),Zo[s]=ua}(i,t,r);var a,c,l,h=function(e){if(e===s&&p)return p;if(!fa&&e&&e in g)return g[e];switch(e){case va:case ma:case ba:return function(){return new i(this,e)}}return function(){return new i(this)}},d=t+" Iterator",u=!1,g=e.prototype,f=g[pa]||g["@@iterator"]||s&&g[s],p=!fa&&f||h(s),v="Array"===t&&g.entries||f;if(v&&(a=oa(v.call(new e)))!==Object.prototype&&a.next&&(Hn(a,d,!0,!0),Zo[d]=ya),ga&&s===ma&&f&&f.name!==ma&&(u=!0,p=function(){return Pi(f,this)}),s)if(c={values:h(ma),keys:n?p:h(va),entries:h(ba)},o)for(l in c)(fa||u||!(l in g))&&Pn(g,l,c[l]);else ns({target:t,proto:!0,forced:fa||u},c);return o&&g[pa]!==p&&Pn(g,pa,p,{name:s}),Zo[t]=p,c},Sa=function(e,t){return{value:e,done:t}};ts.f;var Ta="Array Iterator",Ra=Vn.set,Ea=Vn.getterFor(Ta);wa(Array,"Array",function(e,t){Ra(this,{type:Ta,target:Ni(e),index:0,kind:t})},function(){var e=Ea(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,Sa(void 0,!0);switch(e.kind){case"keys":return Sa(i,!1);case"values":return Sa(t[i],!1)}return Sa([i,t[i]],!1)},"values"),Zo.Arguments=Zo.Array;for(var Ia in{CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0})Hn(ci[Ia],Ia),Zo[Ia]=Zo.Array;var Ca=Jo,Pa=ts.f,Aa=Ir("metadata"),Oa=Function.prototype;void 0===Oa[Aa]&&Pa(Oa,Aa,{value:null}),kn("metadata");var ka=Ca,Da=Bi("Symbol"),$a=Da.keyFor,ja=bi(Da.prototype.valueOf),_a=Da.isRegisteredSymbol||function(e){try{return void 0!==$a(ja(e))}catch(e){return!1}};ns({target:"Symbol",stat:!0},{isRegisteredSymbol:_a});for(var Ha=Bi("Symbol"),Ma=Ha.isWellKnownSymbol,xa=Bi("Object","getOwnPropertyNames"),qa=bi(Ha.prototype.valueOf),Na=gr("wks"),Fa=0,Ua=xa(Ha),La=Ua.length;Fa<La;Fa++)try{var Ba=Ua[Fa];rr(Ha[Ba])&&Ir(Ba)}catch(e){}var Wa=function(e){if(Ma&&Ma(e))return!0;try{for(var t=qa(e),i=0,r=xa(Na),s=r.length;i<s;i++)if(Na[r[i]]==t)return!0}catch(e){}return!1};ns({target:"Symbol",stat:!0,forced:!0},{isWellKnownSymbol:Wa}),kn("customMatcher"),kn("observable"),ns({target:"Symbol",stat:!0,name:"isRegisteredSymbol"},{isRegistered:_a}),ns({target:"Symbol",stat:!0,name:"isWellKnownSymbol",forced:!0},{isWellKnown:Wa}),kn("matcher"),kn("metadataKey"),kn("patternMatch"),kn("replaceAll");var Ga=ka,Va=bi("".charAt),Ka=bi("".charCodeAt),za=bi("".slice),Ya=function(e){return function(t,i){var r,s,n=Vs(qi(t)),o=gs(i),a=n.length;return o<0||o>=a?e?"":void 0:(r=Ka(n,o))<55296||r>56319||o+1===a||(s=Ka(n,o+1))<56320||s>57343?e?Va(n,o):r:e?za(n,o,o+2):s-56320+(r-55296<<10)+65536}},Ja={codeAt:Ya(!1),charAt:Ya(!0)}.charAt,Za="String Iterator",Xa=Vn.set,Qa=Vn.getterFor(Za);wa(String,"String",function(e){Xa(this,{type:Za,string:Vs(e),index:0})},function(){var e,t=Qa(this),i=t.string,r=t.index;return r>=i.length?Sa(void 0,!0):(e=Ja(i,r),t.index+=e.length,Sa(e,!1))});var ec=An.f("iterator");function tc(e){return tc="function"==typeof Ga&&"symbol"==typeof ec?function(e){return typeof e}:function(e){return e&&"function"==typeof Ga&&e.constructor===Ga&&e!==Ga.prototype?"symbol":typeof e},tc(e)}var ic=An.f("toPrimitive");function rc(e){var t=function(e,t){if("object"!=tc(e)||!e)return e;var i=e[ic];if(void 0!==i){var r=i.call(e,t||"default");if("object"!=tc(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==tc(t)?t:t+""}function sc(e,t){for(var i=0;i<t.length;i++){var r=t[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),cs(e,rc(r.key),r)}}var nc=Object.assign,oc=Object.defineProperty,ac=bi([].concat),cc=!nc||li(function(){if(Ii&&1!==nc({b:1},nc(oc({},"a",{enumerable:!0,get:function(){oc(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},i=Symbol("assign detection"),r="abcdefghijklmnopqrst";return e[i]=7,r.split("").forEach(function(e){t[e]=e}),7!==nc({},e)[i]||rn(nc({},t)).join("")!==r})?function(e,t){for(var i=pr(e),r=arguments.length,s=1,n=Cn.f,o=Di.f;r>s;)for(var a,c=Hi(arguments[s++]),l=n?ac(rn(c),n(c)):rn(c),h=l.length,d=0;h>d;)a=l[d++],Ii&&!Pi(o,c,a)||(i[a]=c[a]);return i}:nc;ns({target:"Object",stat:!0,arity:2,forced:Object.assign!==cc},{assign:cc});var lc=Ui.Object.assign,hc=!li(function(){return Object.isExtensible(Object.preventExtensions({}))}),dc=function(e,t,i){for(var r in t)i&&i.unsafe&&e[r]?e[r]=t[r]:Pn(e,r,t[r],i);return e},uc=li(function(){if("function"==typeof ArrayBuffer){var e=new ArrayBuffer(8);Object.isExtensible(e)&&Object.defineProperty(e,"a",{value:8})}}),gc=Object.isExtensible,fc=li(function(){gc(1)})||uc?function(e){return!!Fi(e)&&((!uc||"ArrayBuffer"!==Si(e))&&(!gc||gc(e)))}:gc,pc=si(function(e){var t=ts.f,i=!1,r=Sr("meta"),s=0,n=function(e){t(e,r,{value:{objectID:"O"+s++,weakData:{}}})},o=e.exports={enable:function(){o.enable=function(){},i=!0;var e=Sn.f,t=bi([].splice),s={};s[r]=1,e(s).length&&(Sn.f=function(i){for(var s=e(i),n=0,o=s.length;n<o;n++)if(s[n]===r){t(s,n,1);break}return s},ns({target:"Object",stat:!0,forced:!0},{getOwnPropertyNames:In.f}))},fastKey:function(e,t){if(!Fi(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!mr(e,r)){if(!fc(e))return"F";if(!t)return"E";n(e)}return e[r].objectID},getWeakData:function(e,t){if(!mr(e,r)){if(!fc(e))return!0;if(!t)return!1;n(e)}return e[r].weakData},onFreeze:function(e){return hc&&i&&fc(e)&&!mr(e,r)&&n(e),e}};Zs[r]=!0});pc.enable,pc.fastKey,pc.getWeakData,pc.onFreeze;var vc=Ir("iterator"),mc=Array.prototype,bc=Ir("iterator"),yc=function(e){if(!Mi(e))return cr(e,bc)||cr(e,"@@iterator")||Zo[Es(e)]},wc=TypeError,Sc=function(e,t,i){var r,s;zr(e);try{if(!(r=cr(e,"return"))){if("throw"===t)throw i;return i}r=Pi(r,e)}catch(e){s=!0,r=e}if("throw"===t)throw i;if(s)throw r;return zr(r),i},Tc=TypeError,Rc=function(e,t){this.stopped=e,this.result=t},Ec=Rc.prototype,Ic=function(e,t,i){var r,s,n,o,a,c,l,h,d=i&&i.that,u=!(!i||!i.AS_ENTRIES),g=!(!i||!i.IS_RECORD),f=!(!i||!i.IS_ITERATOR),p=!(!i||!i.INTERRUPTED),v=Wr(t,d),m=function(e){return r&&Sc(r,"normal"),new Rc(!0,e)},b=function(e){return u?(zr(e),p?v(e[0],e[1],m):v(e[0],e[1])):p?v(e,m):v(e)};if(g)r=e.iterator;else if(f)r=e;else{if(!(s=yc(e)))throw new Tc(nr(e)+" is not iterable");if(void 0!==(h=s)&&(Zo.Array===h||mc[vc]===h)){for(n=0,o=ps(e);o>n;n++)if((a=b(e[n]))&&Wi(Ec,a))return a;return new Rc(!1)}r=function(e,t){var i=arguments.length<2?yc(e):t;if(ar(i))return zr(Pi(i,e));throw new wc(nr(e)+" is not iterable")}(e,s)}for(c=g?e.next:r.next;!(l=Pi(c,r)).done;){try{a=b(l.value)}catch(e){Sc(r,"throw",e)}if("object"==typeof a&&a&&Wi(Ec,a))return a}return new Rc(!1)},Cc=TypeError,Pc=function(e,t){if(Wi(t,e))return e;throw new Cc("Incorrect invocation")},Ac=ts.f,Oc=Yn.forEach,kc=Vn.set,Dc=Vn.getterFor,$c=function(e,t,i){var r,s=-1!==e.indexOf("Map"),n=-1!==e.indexOf("Weak"),o=s?"set":"add",a=ci[e],c=a&&a.prototype,l={};if(Ii&&Ei(a)&&(n||c.forEach&&!li(function(){(new a).entries().next()}))){r=t(function(t,i){kc(Pc(t,h),{type:e,collection:new a}),Mi(i)||Ic(i,t[o],{that:t,AS_ENTRIES:s})});var h=r.prototype,d=Dc(e);Oc(["add","clear","delete","forEach","get","has","set","keys","values","entries"],function(e){var t="add"===e||"set"===e;!(e in c)||n&&"clear"===e||is(h,e,function(i,r){var s=d(this).collection;if(!t&&n&&!Fi(i))return"get"===e&&void 0;var o=s[e](0===i?0:i,r);return t?this:o})}),n||Ac(h,"size",{configurable:!0,get:function(){return d(this).collection.size}})}else r=i.getConstructor(t,e,s,o),pc.enable();return Hn(r,e,!1,!0),l[e]=r,ns({global:!0,forced:!0},l),n||i.setStrong(r,e,s),r},jc=pc.getWeakData,_c=Vn.set,Hc=Vn.getterFor,Mc=Yn.find,xc=Yn.findIndex,qc=bi([].splice),Nc=0,Fc=function(e){return e.frozen||(e.frozen=new Uc)},Uc=function(){this.entries=[]},Lc=function(e,t){return Mc(e.entries,function(e){return e[0]===t})};Uc.prototype={get:function(e){var t=Lc(this,e);if(t)return t[1]},has:function(e){return!!Lc(this,e)},set:function(e,t){var i=Lc(this,e);i?i[1]=t:this.entries.push([e,t])},delete:function(e){var t=xc(this.entries,function(t){return t[0]===e});return~t&&qc(this.entries,t,1),!!~t}};var Bc,Wc={getConstructor:function(e,t,i,r){var s=e(function(e,s){Pc(e,n),_c(e,{type:t,id:Nc++,frozen:null}),Mi(s)||Ic(s,e[r],{that:e,AS_ENTRIES:i})}),n=s.prototype,o=Hc(t),a=function(e,t,i){var r=o(e),s=jc(zr(t),!0);return!0===s?Fc(r).set(t,i):s[r.id]=i,e};return dc(n,{delete:function(e){var t=o(this);if(!Fi(e))return!1;var i=jc(e);return!0===i?Fc(t).delete(e):i&&mr(i,t.id)&&delete i[t.id]},has:function(e){var t=o(this);if(!Fi(e))return!1;var i=jc(e);return!0===i?Fc(t).has(e):i&&mr(i,t.id)}}),dc(n,i?{get:function(e){var t=o(this);if(Fi(e)){var i=jc(e);if(!0===i)return Fc(t).get(e);if(i)return i[t.id]}},set:function(e,t){return a(this,e,t)}}:{add:function(e){return a(this,e,!0)}}),s}},Gc=Vn.enforce,Vc=Object,Kc=Array.isArray,zc=Vc.isExtensible,Yc=Vc.isFrozen,Jc=Vc.isSealed,Zc=Vc.freeze,Xc=Vc.seal,Qc=!ci.ActiveXObject&&"ActiveXObject"in ci,el=function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}},tl=$c("WeakMap",el,Wc),il=tl.prototype,rl=bi(il.set);if(xn)if(Qc){Bc=Wc.getConstructor(el,"WeakMap",!0),pc.enable();var sl=bi(il.delete),nl=bi(il.has),ol=bi(il.get);dc(il,{delete:function(e){if(Fi(e)&&!zc(e)){var t=Gc(this);return t.frozen||(t.frozen=new Bc),sl(this,e)||t.frozen.delete(e)}return sl(this,e)},has:function(e){if(Fi(e)&&!zc(e)){var t=Gc(this);return t.frozen||(t.frozen=new Bc),nl(this,e)||t.frozen.has(e)}return nl(this,e)},get:function(e){if(Fi(e)&&!zc(e)){var t=Gc(this);return t.frozen||(t.frozen=new Bc),nl(this,e)?ol(this,e):t.frozen.get(e)}return ol(this,e)},set:function(e,t){if(Fi(e)&&!zc(e)){var i=Gc(this);i.frozen||(i.frozen=new Bc),nl(this,e)?rl(this,e,t):i.frozen.set(e,t)}else rl(this,e,t);return this}})}else hc&&li(function(){var e=Zc([]);return rl(new tl,e,1),!Yc(e)})&&dc(il,{set:function(e,t){var i;return Kc(e)&&(Yc(e)?i=Zc:Jc(e)&&(i=Xc)),rl(this,e,t),i&&i(e),this}});var al=Ui.WeakMap,cl=TypeError,ll=function(e){if("object"==typeof e&&"has"in e&&"get"in e&&"set"in e)return e;throw new cl(nr(e)+" is not a weakmap")},hl=function(e,t){return 1===t?function(t,i){return t[e](i)}:function(t,i,r){return t[e](i,r)}},dl={WeakMap:Bi("WeakMap"),set:hl("set",2),get:hl("get",1),has:hl("has",1),remove:hl("delete",1)},ul=dl.get,gl=dl.has,fl=dl.set;ns({target:"WeakMap",proto:!0,real:!0,forced:hr},{getOrInsert:function(e,t){return gl(ll(this),e)?ul(this,e):(fl(this,e,t),t)}});var pl=new dl.WeakMap,vl=dl.set,ml=dl.remove,bl=dl.get,yl=dl.has,wl=dl.set;ns({target:"WeakMap",proto:!0,real:!0,forced:true},{getOrInsertComputed:function(e,t){if(ll(this),function(e){vl(pl,e,1),ml(pl,e)}(e),ar(t),yl(this,e))return bl(this,e);var i=t(e);return wl(this,e,i),i}});var Sl=al,Tl=function(e,t,i){return function(r){var s=pr(r),n=arguments.length,o=n>1?arguments[1]:void 0,a=void 0!==o,c=a?Wr(o,n>2?arguments[2]:void 0):void 0,l=new e,h=0;return Ic(s,function(e){var r=a?c(e,h++):e;i?t(l,zr(r)[0],r[1]):t(l,r)}),l}};ns({target:"WeakMap",stat:!0,forced:!0},{from:Tl(dl.WeakMap,dl.set,!0)});var Rl=function(e,t,i){return function(){for(var r=new e,s=arguments.length,n=0;n<s;n++){var o=arguments[n];i?t(r,zr(o)[0],o[1]):t(r,o)}return r}};ns({target:"WeakMap",stat:!0,forced:!0},{of:Rl(dl.WeakMap,dl.set,!0)});var El=dl.get,Il=dl.has,Cl=dl.set;ns({target:"WeakMap",proto:!0,real:!0,forced:!0},{emplace:function(e,t){var i,r,s=ll(this);return Il(s,e)?(i=El(s,e),"update"in t&&(i=t.update(i,e,s),Cl(s,e,i)),i):(r=t.insert(e,s),Cl(s,e,r),r)}});var Pl=dl.remove;ns({target:"WeakMap",proto:!0,real:!0,forced:!0},{deleteAll:function(){for(var e,t=ll(this),i=!0,r=0,s=arguments.length;r<s;r++)e=Pl(t,arguments[r]),i=i&&e;return!!i}});var Al=TypeError;ns({target:"WeakMap",proto:!0,real:!0,forced:!0},{upsert:function(e,t){var i,r=zr(this),s=ar(r.get),n=ar(r.has),o=ar(r.set),a=arguments.length>2?arguments[2]:void 0;if(!Ei(t)&&!Ei(a))throw new Al("At least one callback required");return Pi(n,r,e)?(i=Pi(s,r,e),Ei(t)&&(i=t(i),Pi(o,r,e,i))):Ei(a)&&(i=a(),Pi(o,r,e,i)),i}});var Ol=Sl;$c("WeakSet",function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}},Wc);var kl=Ui.WeakSet,Dl=TypeError,$l=function(e){if("object"==typeof e&&"has"in e&&"add"in e&&"delete"in e)return e;throw new Dl(nr(e)+" is not a weakset")},jl={WeakSet:Bi("WeakSet"),add:hl("add",1),has:hl("has",1),remove:hl("delete",1)},_l=jl.add;ns({target:"WeakSet",proto:!0,real:!0,forced:!0},{addAll:function(){for(var e=$l(this),t=0,i=arguments.length;t<i;t++)_l(e,arguments[t]);return e}});var Hl=jl.remove;ns({target:"WeakSet",proto:!0,real:!0,forced:!0},{deleteAll:function(){for(var e,t=$l(this),i=!0,r=0,s=arguments.length;r<s;r++)e=Hl(t,arguments[r]),i=i&&e;return!!i}}),ns({target:"WeakSet",stat:!0,forced:!0},{from:Tl(jl.WeakSet,jl.add,!1)}),ns({target:"WeakSet",stat:!0,forced:!0},{of:Rl(jl.WeakSet,jl.add,!1)});var Ml=kl,xl=si(function(e,t){e.exports=function(){function e(e){return!isNaN(parseFloat(e))&&isFinite(e)}function t(e){return e.charAt(0).toUpperCase()+e.substring(1)}function i(e){return function(){return this[e]}}var r=["isConstructor","isEval","isNative","isToplevel"],s=["columnNumber","lineNumber"],n=["fileName","functionName","source"],o=["args"],a=["evalOrigin"],c=r.concat(s,n,o,a);function l(e){if(e)for(var i=0;i<c.length;i++)void 0!==e[c[i]]&&this["set"+t(c[i])](e[c[i]])}l.prototype={getArgs:function(){return this.args},setArgs:function(e){if("[object Array]"!==Object.prototype.toString.call(e))throw new TypeError("Args must be an Array");this.args=e},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(e){if(e instanceof l)this.evalOrigin=e;else{if(!(e instanceof Object))throw new TypeError("Eval Origin must be an Object or StackFrame");this.evalOrigin=new l(e)}},toString:function(){var e=this.getFileName()||"",t=this.getLineNumber()||"",i=this.getColumnNumber()||"",r=this.getFunctionName()||"";return this.getIsEval()?e?"[eval] ("+e+":"+t+":"+i+")":"[eval]:"+t+":"+i:r?r+" ("+e+":"+t+":"+i+")":e+":"+t+":"+i}},l.fromString=function(e){var t=e.indexOf("("),i=e.lastIndexOf(")"),r=e.substring(0,t),s=e.substring(t+1,i).split(","),n=e.substring(i+1);if(0===n.indexOf("@"))var o=/@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(n,""),a=o[1],c=o[2],h=o[3];return new l({functionName:r,args:s||void 0,fileName:a,lineNumber:c||void 0,columnNumber:h||void 0})};for(var h=0;h<r.length;h++)l.prototype["get"+t(r[h])]=i(r[h]),l.prototype["set"+t(r[h])]=function(e){return function(t){this[e]=Boolean(t)}}(r[h]);for(var d=0;d<s.length;d++)l.prototype["get"+t(s[d])]=i(s[d]),l.prototype["set"+t(s[d])]=function(t){return function(i){if(!e(i))throw new TypeError(t+" must be a Number");this[t]=Number(i)}}(s[d]);for(var u=0;u<n.length;u++)l.prototype["get"+t(n[u])]=i(n[u]),l.prototype["set"+t(n[u])]=function(e){return function(t){this[e]=String(t)}}(n[u]);return l}()}),ql=si(function(e,t){var i,r,s,n;e.exports=(i=xl,r=/(^|@)\S+:\d+/,s=/^\s*at .*(\S+:\d+|\(native\))/m,n=/^(eval@)?(\[native code])?$/,{parse:function(e){if(void 0!==e.stacktrace||void 0!==e["opera#sourceloc"])return this.parseOpera(e);if(e.stack&&e.stack.match(s))return this.parseV8OrIE(e);if(e.stack)return this.parseFFOrSafari(e);throw new Error("Cannot parse given Error object")},extractLocation:function(e){if(-1===e.indexOf(":"))return[e];var t=/(.+?)(?::(\d+))?(?::(\d+))?$/.exec(e.replace(/[()]/g,""));return[t[1],t[2]||void 0,t[3]||void 0]},parseV8OrIE:function(e){return e.stack.split("\n").filter(function(e){return!!e.match(s)},this).map(function(e){e.indexOf("(eval ")>-1&&(e=e.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var t=e.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),r=t.match(/ (\(.+\)$)/);t=r?t.replace(r[0],""):t;var s=this.extractLocation(r?r[1]:t),n=r&&t||void 0,o=["eval","<anonymous>"].indexOf(s[0])>-1?void 0:s[0];return new i({functionName:n,fileName:o,lineNumber:s[1],columnNumber:s[2],source:e})},this)},parseFFOrSafari:function(e){return e.stack.split("\n").filter(function(e){return!e.match(n)},this).map(function(e){if(e.indexOf(" > eval")>-1&&(e=e.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),-1===e.indexOf("@")&&-1===e.indexOf(":"))return new i({functionName:e});var t=/((.*".+"[^@]*)?[^@]*)(?:@)/,r=e.match(t),s=r&&r[1]?r[1]:void 0,n=this.extractLocation(e.replace(t,""));return new i({functionName:s,fileName:n[0],lineNumber:n[1],columnNumber:n[2],source:e})},this)},parseOpera:function(e){return!e.stacktrace||e.message.indexOf("\n")>-1&&e.message.split("\n").length>e.stacktrace.split("\n").length?this.parseOpera9(e):e.stack?this.parseOpera11(e):this.parseOpera10(e)},parseOpera9:function(e){for(var t=/Line (\d+).*script (?:in )?(\S+)/i,r=e.message.split("\n"),s=[],n=2,o=r.length;n<o;n+=2){var a=t.exec(r[n]);a&&s.push(new i({fileName:a[2],lineNumber:a[1],source:r[n]}))}return s},parseOpera10:function(e){for(var t=/Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i,r=e.stacktrace.split("\n"),s=[],n=0,o=r.length;n<o;n+=2){var a=t.exec(r[n]);a&&s.push(new i({functionName:a[3]||void 0,fileName:a[2],lineNumber:a[1],source:r[n]}))}return s},parseOpera11:function(e){return e.stack.split("\n").filter(function(e){return!!e.match(r)&&!e.match(/^Error created at/)},this).map(function(e){var t,r=e.split("@"),s=this.extractLocation(r.pop()),n=r.shift()||"",o=n.replace(/<anonymous function(: (\w+))?>/,"$2").replace(/\([^)]*\)/g,"")||void 0;n.match(/\(([^)]*)\)/)&&(t=n.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var a=void 0===t||"[arguments not available]"===t?void 0:t.split(",");return new i({functionName:o,args:a,fileName:s[0],lineNumber:s[1],columnNumber:s[2],source:e})},this)}})});Date.now=Date.now||function(){return(new Date).getTime()};var Nl=Date.now(),Fl=function(){},Ul={noop:Fl,warn:function(){var e="object"==typeof console?console.warn:Fl;try{var t={warn:e};t.warn.call(t)}catch(e){return Fl}return e}(),key:"__bl",selfErrKey:"ARMS_SDK_ERROR",selfErrPage:"ARMSSDK",win:"object"==typeof window&&window.document?window:void 0,regionMap:{cn:"https://arms-retcode.aliyuncs.com/r.png?",sg:"https://arms-retcode-sg.aliyuncs.com/r.png?",sg_2:"https://retcode-sg-lazada.arms.aliyuncs.com/r.png?",daily:"http://arms-retcode-daily.alibaba.net/r.png?",daily_2:"https://arms-retcode-daily.alibaba.net/r.png?",us:"https://retcode-us-west-1.arms.aliyuncs.com/r.png?",tw:"https://arms-retcode.orientalgame.com.tw/r.png?",tw_sg:"https://arms-retcode-sg.orientalgame.com.tw/r.png?",hz_finance:"https://arms-retcode-hz-finance.aliyuncs.com/r.png?"},defaultImgUrl:"https://arms-retcode.aliyuncs.com/r.png?",createObject:function(e){if(Object.create)return Object.create(e);var t=function(){};return t.prototype=e,new t},each:function(e,t){var i=0,r=e.length;if(this.T(e,"Array"))for(;i<r&&!1!==t.call(e[i],e[i],i);i++);else for(i in e)if(!1===t.call(e[i],e[i],i))break;return e},safetyCall:function(e,t,i){if("function"!=typeof e)return i;try{return e.apply(this,t)}catch(e){return i}},T:function(e,t){var i=Object.prototype.toString.call(e).substring(8).replace("]","");return t?i===t:i},filterByRule:function(e,t){if(!e)return"";if(!t)return e;var i=this,r=i.T(t);return"Function"===r?i.safetyCall(t,[e],e):"Array"===r?(this.each(t,function(t){e=i.filterByRule(e,t)}),e):"Object"===r?e.replace(t.rule,t.target||""):e.replace(t,"")},ignoreByRule:function(e,t){if(!e||!t)return!1;if((this.isString(t)||t.source||"Function"===this.T(t))&&(t=[t]),!this.isArray(t))return this.warn("[arms] invalid rules of ignore config, (list of) String/RegExp/Funcitons are available"),!1;for(var i,r=[],s=0,n=t.length;s<n;s++)if(i=t[s],this.isString(i))r.push(i.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1"));else if(i&&i.source)r.push(i.source);else if(i&&"Function"===this.T(i)&&!0===this.safetyCall(i,[e],!1))return!0;var o=new RegExp(r.join("|"),"i");return!!(r.length&&o.test&&o.test(e))},J:function(e){if(!e||"string"!=typeof e)return e;var t=null;try{t=JSON.parse(e)}catch(e){}return t},pick:function(e){return 1===e||1===Math.ceil(Math.random()*e)},verifyConfig:function(e){if("sample"in e){var t=e.sample,i=t;t&&/^\d+(\.\d+)?%$/.test(t)&&(i=parseInt(100/parseFloat(t))),0<i&&1>i&&(i=parseInt(1/i)),i>=1&&i<=100?e.sample=i:delete e.sample}return e},on:function(e,t,i,r,s){return e.addEventListener?(s=s||!1,e.addEventListener(t,function n(o){r&&e.removeEventListener(t,n,s),i.call(this,o)},s)):e.attachEvent&&e.attachEvent("on"+t,function s(n){r&&e.detachEvent("on"+t,s),i.call(this,n)}),this},off:function(e,t,i){return i?(e.removeEventListener?e.removeEventListener(t,i):e.detachEvent&&e.detachEvent(t,i),this):this},delay:function(e,t){return-1===t?(e(),null):setTimeout(e,t||0)},ext:function(e){for(var t=1,i=arguments.length;t<i;t++){var r=arguments[t];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},sub:function(e,t){var i={};return this.each(e,function(e,r){-1!==t.indexOf(r)&&(i[r]=e)}),i},uu:function(){for(var e,t,i=20,r=new Array(i),s=Date.now().toString(36).split("");i-- >0;)t=(e=36*Math.random()|0).toString(36),r[i]=e%3?t:t.toUpperCase();for(var n=0;n<8;n++)r.splice(3*n+2,0,s[n]);return r.join("")},seq:function(){return(Nl++).toString(36)},decode:function(e){try{e=decodeURIComponent(e)}catch(e){}return e},encode:function(e,t){try{e=t?encodeURIComponent(e).replace(/\(/g,"%28").replace(/\)/g,"%29"):encodeURIComponent(e)}catch(e){}return e},serialize:function(e){e=e||{};var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&void 0!==e[i]&&t.push(i+"="+this.encode(e[i],"msg"===i));return t.join("&")},checkAPI:function(e,t){if(!e||"string"!=typeof e)return!1;var i=/arms-retcode[\w-]*\.aliyuncs/.test(e);return!i&&t&&(i=/(\.png)|(\.gif)|(alicdn\.com)|(mmstat\.com)/.test(e)),!i},checkAutoError:function(e){return!(!e||!e.message||/failed[\w\s]+fetch/i.test(e.message))},cutUrlSearch:function(e){return e&&"string"==typeof e?e.replace(/^(https?:)?\/\//,"").replace(/\?.*$/,""):""},removeUrlSearch:function(e){return e&&"string"==typeof e?e.replace(/\?.*$/,""):""},createFakeToString:function(e){return function(){return e+"() { [native code] }"}},checkSameOrigin:function(e,t){if(!t||!e)return!1;var i="//"+t.split("/")[2];return e===t||e.slice(0,t.length+1)===t+"/"||e===i||e.slice(0,i.length+1)===i+"/"||!/^(\/\/|http:|https:).*/.test(e)},getRandIP:function(){for(var e=[],t=0;t<4;t++){var i=Math.floor(256*Math.random());e[t]=(i>15?"":"0")+i.toString(16)}return e.join("").replace(/^0/,"1")},getSortNum:function(e){return e?(e+=1)>=1e3&&e<=9999?e:e<1e3?e+1e3:e%1e4+1e3:1e3},getRandNum:function(e){return e&&"string"==typeof e?e.length<5?this.getNum(5):e.substring(e.length-5):this.getNum(5)},getNum:function(e){for(var t=[],i=0;i<e;i++){var r=Math.floor(16*Math.random());t[i]=r.toString(16)}return t.join("")},getCurDomain:function(){return location&&location.hostname||""},parseFetchHeaders:function(e){if(!e)return{};var t={};try{if("function"==typeof e.keys)for(var i=e.keys(),r=i.next();!r.done;){var s=r.value;t[s]=e.get(s),r=i.next()}else t=e}catch(e){t={}}return t},parseXhrHeaders:function(e){if(!e&&"string"!=typeof e)return{};var t={};try{t=e.split("\r\n").reduce(function(e,t){var i=t.split(": ");return e[i[0]]=i[1],e},{})}catch(e){t={}}return t},getQuerys:function(e){if(!e)return"";var t={},i=[],r="",s="";try{var n=[];if(e.indexOf("?")>=0&&(n=e.substring(e.indexOf("?")+1,e.length).split("&")),n.length>0)for(var o in n)r=(i=n[o].split("="))[0],s=i[1],t[r]=s}catch(e){t={}}return t},getFetchSnapshot:function(e,t,i){var r,s;try{var n=(e&&"string"!=typeof e[0]?e[0].url:e[0])||"",o=(e&&"string"!=typeof e[0]?e[0]:e[1])||{},a="POST"===o.method.toUpperCase()?o.body:this.getQuerys(n);r={originApi:n,method:o.method||"unknown",params:a,response:t||"",reqHeaders:this.parseFetchHeaders(o.headers||null),resHeaders:this.parseFetchHeaders(i)},s="function"==typeof encodeURIComponent&&JSON&&encodeURIComponent(JSON.stringify(r))||"{}"}catch(e){s="{}"}return s},getXhrSnapshot:function(e,t,i){if(!e||!t||!i)return{};var r,s;try{var n="";""===i.responseType||"text"===i.responseType?n=i.responseText:"document"===i.responseType&&(n=i.responseXML),r={originApi:e,method:t,params:this.getQuerys(e),response:n,reqHeaders:{},resHeaders:this.parseXhrHeaders("function"==typeof i.getAllResponseHeaders&&i.getAllResponseHeaders()||"")},s="function"==typeof encodeURIComponent&&JSON&&encodeURIComponent(JSON.stringify(r))||"{}"}catch(e){s="{}"}return s},isRobot:function(){var e=["nuhk","googlebot/","googlebot-image","yammybot","openbot","slurp","msnbot","ask jeeves/teoma","ia_archiver","baiduspider","bingbot/","adsbot"];if(!navigator||"string"!=typeof navigator.userAgent)return!1;try{for(var t=navigator.userAgent.toLowerCase(),i=0;i<e.length;i++){var r=e[i];if(t.lastIndexOf(r)>=0)return!0}}catch(e){this.warn("[arms] useragent parse error")}return!1},isFunction:function(e){return"function"==typeof e},isPlainObject:function(e){return"[object Object]"===Object.prototype.toString.call(e)},isString:function(e){return"[object String]"===Object.prototype.toString.call(e)},isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},joinRegExp:function(e){for(var t,i=[],r=0,s=e.length;r<s;r++)t=e[r],this.isString(t)?i.push(t.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1")):t&&t.source&&i.push(t.source);return new RegExp(i.join("|"),"i")},reWriteMethod:function(e,t,i){if(null!==e){var r=e[t];e[t]=i(r)}},checkSDKError:function(e,t){return!(!e&&!t)&&(!!new RegExp(this.selfErrKey,"i").test(e)||!!this.ignoreByRule(t,[/retcode.alicdn.com\/retcode\/bl.js/,/g.alicdn.com\/retcode\/cloud-sdk\/bl.js/,/laz-g-cdn.alicdn.com\/retcode\/cloud-sdk\/bl.js/,/local.taobao.com:8880\/build\/bl/]))},sdkError:function(e){return{msg:e,message:this.selfErrKey}},dealParam:function(e,t,i){var r={};try{r=this.isPlainObject(e)?this.ext({key:e.key||"default",val:e.val||e.value||i},e,{begin:Date.now()}):{key:e||"default",val:t||i,begin:Date.now()}}catch(e){this.warn("[retcode] baseLog error: "+e)}return r}},Ll=Ul,Bl=si(function(e){var t="aokcdqn3ly@e629dabd48a9933",i=function(e,t){var i;if("error"!==t.t||!(i=e.requestQueue[0])||"error"!==i.t||t.msg!==i.msg){if("behavior"===t.t){var r=e.requestQueue&&e.requestQueue.length;if(r>0&&"behavior"===e.requestQueue[r-1].t){var s=t.behavior||[];e.requestQueue[r-1].behavior.concat(s)}else e.requestQueue.push(t)}else e.requestQueue.unshift(t);return e.onReady(function(){e.requestTimmer=Ll.delay(function(){e.clear()},e.requestQueue[0]&&"error"===e.requestQueue[0].t?3e3:-1)}),!0}i.times++},r=function(e){return this.ver="1.8.30",this._conf=Ll.ext({},r.dftCon),this.sampleCache={},this.requestQueue=[],this.selfQueue=[],this.sdkFlag=!0,this.hash=Ll.seq(),this.resetPageview(),this.setConfig(e),this.rip=Ll.getRandIP(),this.record=999,this["EagleEye-TraceID"]=this.getTraceId()["EagleEye-TraceID"],this._common={},this};r.dftCon={sample:1,pvSample:1,tag:"",imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",region:null,ignore:{ignoreUrls:[],ignoreApis:[],ignoreErrors:[/^Script error\.?$/],ignoreResErrors:[]},release:void 0,environment:"prod"},r.prototype={constructor:r,onReady:function(e){return e()},getPage:function(){var e=this._conf.page;return Ll.safetyCall(e,[],e+"")},setPage:function(){},setConfig:function(e){e&&"object"==typeof e&&(Ll.verifyConfig(e),e=this.setImgUrl(e),this._conf=Ll.ext({},this._conf,e))},setImgUrl:function(e){var t=e.region,i=e.imgUrl;if(t){var r=Ll.regionMap[t];return e.imgUrl=r||Ll.defaultImgUrl,e}return i&&(e.imgUrl=i),e},checkImgUrl:function(e){if(this.getConfig("debug"))return!0;var t=Ll.regionMap,i=!1;for(var r in t)if(t[r]===e){i=!0;break}return!i&&Ll.warn("[retcode] invalid url: "+e),i},sendRequest:function(){},sendBeacon:function(e){!function(e,t){"object"==typeof e&&(e=Ll.serialize(e));var i=t+e;window&&window.navigator&&"function"==typeof window.navigator.sendBeacon?window.navigator.sendBeacon(i,"&post_res="):Ll.warn("[arms] navigator.sendBeacon not surported")}(e,this.getConfig("imgUrl"))},postData:function(){},commonInfo:function(){return{}},setCommonInfo:function(e){e&&"object"==typeof e&&(this._common=Ll.ext({},this._common,e))},resetPageview:function(){this.pageview=Ll.uu(),this.sBegin=Date.now()},getUsername:function(){if(this.username)return this.username;var e=this._conf,t=e&&e.setUsername;if("function"==typeof t)try{var i=t();"string"==typeof i&&(i=i.substr(0,40),this.username=i)}catch(e){Ll.warn("[arms] setUsername fail",e)}return this.username},getTraceId:function(){var e=this.rip,t=Date.now(),i=Ll.getSortNum(this.record),r=e+t+i+Ll.getRandNum(this._conf.pid);return this["EagleEye-TraceID"]=r,this.record=i,{"EagleEye-TraceID":r}},getUberTraceId:function(e){var t=this.rip,i=Date.now(),r=Ll.getSortNum(this.record),s=Ll.getRandNum(this._conf.pid),n=t+i+r+Ll.getNum(2)+s,o=n.substring(0,16);return{"uber-trace-id":n+":"+o+":0:"+(e=e?"1":"0"),traceId:n}},getPageviewId:function(){return{"EagleEye-SessionID":this.pageview}},getConfig:function(e){return e?this._conf[e]:Ll.ext({},this._conf)},sampling:function(e){return 1===e||("boolean"==typeof this.sampleCache[e]||(this.sampleCache[e]=Ll.pick(e)),this.sampleCache[e])},clear:function(e){var t;clearTimeout(this.requestTimmer),this.requestTimmer=null;for(var i=this._conf&&"function"==typeof this._conf.sendRequest;t=this.requestQueue.pop();)"res"===t.t?this.postData(t,"res"):"error"===t.t?this.postData(t,"err"):"api"===t.t?this.postData(t,"apiSnapshot"):"behavior"===t.t?this.postData(t,"behavior"):"health"===t.t&&!i&&window&&window.navigator&&"function"==typeof window.navigator.sendBeacon?this.sendBeacon(t):this.sendRequest(t);return e&&this.clearSelf(),this},clearSelf:function(){var e;for(clearTimeout(this.Timmer),this.Timmer=null;e=this.selfQueue.pop();)this.postData(e,"err");return this},_lg:function(e,t,r,s){var n=this._conf,o=this.getPage(),a=n.ignore||{},c=a.ignoreErrors,l=a.ignoreResErrors,h=a.ignoreUrls,d=a.ignoreApis;if(this._isRobot)return this;if(Ll.ignoreByRule(o,h)||Ll.ignoreByRule(Ll.decode(o),h))return this;if("error"===e&&(Ll.ignoreByRule(t.msg,c)||Ll.ignoreByRule(Ll.decode(t.msg),c)))return this;if("resourceError"===e&&(Ll.ignoreByRule(t.src,l)||Ll.ignoreByRule(Ll.decode(t.src),l)))return this;if("api"===e&&(Ll.ignoreByRule(t.api,d)||Ll.ignoreByRule(Ll.decode(t.api),d)))return this;if(!this.checkImgUrl(n.imgUrl))return this;if(!t||n.disabled||!n.pid)return this;if(0===s)return this;var u=t.dl;return delete t.dl,t=Ll.ext({t:e,times:1,page:o,tag:n.tag||"",release:n.release||"",environment:n.environment,begin:Date.now(),c1:n.c1,c2:n.c2,c3:n.c3},t,this.commonInfo(),this._common,{pid:n.pid,_v:this.ver,pv_id:this.pageview,username:this.getUsername(),sampling:r||1,dl:u,z:Ll.seq()}),1===s?i(this,t):r&&!this.sampling(r)?this:i(this,t)},_self:function(e,i,r){var s=this,n=s._conf;if("error"!==e)return s;if(!s.checkImgUrl(n.imgUrl))return s;if(!i||n.disabled||!n.pid)return s;if(r&&!s.sampling(r))return s;i=Ll.ext({t:e,times:1,page:Ll.selfErrPage,tag:n.pid,begin:Date.now()},i,{pid:t,_v:s.ver,sampling:r||1,z:Ll.seq()});var o=s.selfQueue[0];if(o){o.times++;try{o.err&&i.err&&o.err.msg_raw&&i.err.msg_raw&&o.err.msg_raw.split("&").indexOf(i.err.msg_raw)<0&&o.err.msg_raw.length<1e3&&(o.err.msg_raw+="&"+i.err.msg_raw)}catch(e){}}else s.selfQueue.unshift(i),s.onReady(function(){s.sdkFlag&&(s.sdkFlag=!1,s.Timmer=Ll.delay(function(){s.clearSelf()},1e4))})},custom:function(e,t){if(!e||"object"!=typeof e)return this;var i=!1,r={begin:Date.now()};return Ll.each(e,function(e,t){return!(i=t&&t.length<=20)&&Ll.warn("[retcode] invalid key: "+t),r["x-"+t]=e,i}),i?this._lg("custom",r,t||1):this}},e.exports=r}),Wl=si(function(e){var t=["api","success","time","code","msg","trace","traceId","begin","pv_id","sid","seq","domain","flag"],i=function(e){var t=(e.key||"default").split("::");return t.length>1?Ll.ext(e,{group:t[0],key:t[1]}):Ll.ext(e,{group:"default_group",key:t[0]})},r=function(e){var t;Bl.call(this,e);try{t="object"==typeof performance?performance.timing.fetchStart:Date.now()}catch(e){t=Date.now()}return this._startTime=t,this};r.prototype=Ll.createObject(Bl.prototype),Ll.ext(Bl.dftCon,{startTime:null}),Ll.ext(r.prototype,{constructor:r,_super:Bl,sum:function(e,t,r){try{var s=Ll.dealParam(e,t,1);return this._lg("sum",i(s),r)}catch(e){Ll.warn("[retcode] can not get parseStatData: "+e)}},avg:function(e,t,r){try{var s=Ll.dealParam(e,t,0);return this._lg("avg",i(s),r)}catch(e){Ll.warn("[retcode] can not get parseStatData: "+e)}},percent:function(e,t,r,s){try{return this._lg("percent",i({key:e,subkey:t,val:r||0,begin:Date.now()}),s)}catch(e){Ll.warn("[retcode] can not get parseStatData: "+e)}},msg:function(e,t){if(e&&!(e.length>180))return this.custom({msg:e},t)},error:function(e,t){if(!e)return Ll.warn("[retcode] invalid param e: "+e),this;1===arguments.length?("string"==typeof e&&(e={message:e},t={}),"object"==typeof e&&(t=e=e.error||e)):("string"==typeof e&&(e={message:e}),"object"!=typeof t&&(t={}));var i=e.name||"CustomError",r=e.message||"",s=e.stack||"";t=t||{};var n="object"==typeof location&&"string"==typeof location.href&&location.href.substring(0,500)||"";if(Ll.checkSDKError(r,t.filename)){var o=/^Script error\.?$/,a=e.msg||e.message;if(Ll.ignoreByRule(a,o)||Ll.ignoreByRule(Ll.decode(a),o))return this;var c={msg:Ll.selfErrKey,err:{msg_raw:Ll.encode(e.msg||e.message)}};return this._self("error",c,1)}for(var l={begin:Date.now(),cate:i,msg:r&&r.substring(0,1e3),stack:s&&s.substring(0,1e3),file:Ll.removeUrlSearch(t.filename||""),line:t.lineno||"",col:t.colno||"",err:{msg_raw:Ll.encode(r),stack_raw:Ll.encode(s)},dl:n},h=["tag","c1","c2","c3"],d=0;d<h.length;d++){var u=h[d];t[u]&&(l[u]=t[u])}var g=(this.getConfig("ignore")||{}).ignoreErrors;return Ll.ignoreByRule(l.msg,g)||Ll.ignoreByRule(Ll.decode(l.msg),g)?this:(this.beforeSend&&this.beforeSend("error",l),this._lg("error",l,1))},behavior:function(e){if(e){var t="object"==typeof e&&e.behavior?e:{behavior:e};return this.beforeSend&&this.beforeSend("behavior",t),this._lg("behavior",t,1)}},api:function(e,i,r,s,n,o,a,c,l,h,d,u){if(!e)return Ll.warn("[retcode] api is null"),this;if(e="string"==typeof e?{api:e,success:i,time:r,code:s,msg:n,begin:o,traceId:a,pv_id:c,apiSnapshot:l,domain:h,flag:u}:Ll.sub(e,t),!Ll.checkAPI(e.api,!0))return this;e.code=e.code||"";var g=e.msg||"";if(g="string"==typeof g?g.substring(0,1e3):g,e.msg=g,e.success=e.success?1:0,e.time=+e.time,e.begin=e.begin,e.traceId=e.traceId||"",e.pv_id=e.pv_id||"",e.domain=e.domain||"",e.flag=e.flag,e.dl="object"==typeof location&&"string"==typeof location.href&&location.href.substring(0,500)||"",e.success?e.apiSnapshot&&delete e.apiSnapshot:e.apiSnapshot=l,d&&(e.traceOrigin=d),!e.api||isNaN(e.time))return Ll.warn("[retcode] invalid time or api"),this;var f=(this.getConfig("ignore")||{}).ignoreApis;return Ll.ignoreByRule(e.api,f)||Ll.ignoreByRule(Ll.decode(e.api),f)?this:(this.beforeSend&&this.beforeSend("api",e),this._lg("api",e,e.success&&this.getConfig("sample"),e.flag))},speed:function(e,t,i){var r=this,s=this.getConfig("startTime")||this._startTime;return/^s(\d|1[0])$/.test(e)?(t="number"!=typeof t?Date.now()-s:t>=s?t-s:t,r.speedCache=r.speedCache||{},r.speedCache[e]=t,r.speedCache.begin=s,clearTimeout(r.speedTimmer),r.speedTimmer=setTimeout(function(){i||(r.speedCache.page=r.getPage(!0)),r._lg("speed",r.speedCache),r.speedCache=null},5e3),r):(Ll.warn("[retcode] invalid point: "+e),r)},performance:function(e){if(e&&"object"==typeof e&&!this.hasSendPerf){var t={},i={},r=this.getConfig("autoSendPerf");if(e.autoSend&&r)return i=Ll.ext(this.perfData||{},e),this.hasSendPerf=!0,this._lg("perf",i,this.getConfig("sample"));if(e.autoSend&&!r)return delete e.autoSend,this.perfData?(i=Ll.ext(this.perfData||{},e),this.hasSendPerf=!0,this._lg("perf",i,this.getConfig("sample"))):void(this.perfData=e);for(var s in e)(/^t([1-9]|1[0])$/.test(s)||"ctti"===s||"cfpt"===s)&&(t[s]=e[s]);if(!0===e.autoSend||!r&&(r||this.perfData))return!0!==e.autoSend&&!1===r&&this.perfData?(t=Ll.ext(this.perfData||{},t),this.hasSendPerf=!0,this._lg("perf",t,this.getConfig("sample"))):void 0;this.perfData=Ll.ext(this.perfData||{},t)}},resource:function(e,t){if(!e||!Ll.isPlainObject(e))return Ll.warn("[arms] invalid param data: "+e),this;var i=Object.keys(e),r=["begin","dom","load","res","dl"],s=!1;for(var n in r)if(i.indexOf(r[n])<0){s=!0;break}if(s)return Ll.warn("[arms] lack param data: "+e),this;var o={begin:e.begin||Date.now(),dom:e.dom||"",load:e.load||"",res:Ll.isArray(e.res)?JSON.stringify(e.res):JSON.stringify([]),dl:e.dl||""};return this._lg("res",o,t)},event:function(e,t){if("object"==typeof e&&e&&e.key){var i={},r=["key","success","time","c1","c2","c3"];for(var s in e)r.indexOf(s)>-1&&(i[s]=e[s]);i.success=!1===e.success?0:1,this._lg("event",i,t)}}}),r._super=Bl,r._root=Bl,Bl.Reporter=r,e.exports=r}),Gl=si(function(e){var t="object"==typeof window?window:{},i=t.__oFetch_||t.fetch;i="function"==typeof i?i:void 0,e.exports=function(e,r){var s=-1;"object"==typeof e&&(s=e.z,e=Ll.serialize(e));var n=r+e;if(i)return i(n,{method:"HEAD",mode:"no-cors"}).catch(Ll.noop);if(t.document&&t.document.createElement){var o="__request_hold_"+s,a=t[o]=new Image;a.onload=a.onerror=function(){t[o]=void 0},a.src=n,a=null}}}),Vl=si(function(e){var t="object"==typeof window?window:{},i=t.__oXMLHttpRequest_||t.XMLHttpRequest;i="function"==typeof i?i:void 0,e.exports=function(e,t){try{var r=new i;r.open("POST",t,!0),r.setRequestHeader("Content-Type","text/plain"),r.send(JSON.stringify(e))}catch(e){Ll.warn("[retcode] Failed to log, exception is :\n"+e)}}}),Kl=function(e,t){var i=[],r=null,s=t&&t.location&&t.location.href,n=0,o=void 0,a=null,c=function(e,t,i){if(null!==e){var r=e[t];e[t]=i(r)}},l=function(e){var t,i,r,s,n,o=[];if(!e||"string"!=typeof e.tagName)return"";if(o.push(e.tagName.toLowerCase()),"string"==typeof e.id&&o.push("#".concat(e.id)),"string"==typeof(t=e.className))for(i=t.split(/\s+/),n=0;n<i.length;n++)o.push(".".concat(i[n]));var a=["type","name","title","alt","data-arms-attr"];for(n=0;n<a.length;n++)r=a[n],"string"==typeof(s=e.getAttribute(r))&&o.push("[".concat(r,'="').concat(s,'"]'));return o.join("")},h=function(e,t){return function(i){if(i&&i!==a){var s;a=i;try{s=i.target}catch(e){s="<unknown>"}if(0!==s.length){var c={type:"ui.".concat(e),data:{message:function(e){if(!e||1!==e.nodeType)return"";for(var t=e||null,i=[],r=0,s=0,n="";t&&r++<5&&!("html"===(n=l(t))||r>1&&s+3*i.length+n.length>=80);)i.push(n),s+=n.length,t=t.parentNode;return i.reverse().join(" > ")}(s)},timestamp:Date.now()};"click"===e?(n&&clearTimeout(n),t?n=setTimeout(function(){r&&r.addBehavior(c)},0):r&&r.addBehavior(c)):"keypress"===e&&(o||r&&r.addBehavior(c),clearTimeout(o),o=setTimeout(function(){o=void 0},100))}}}};Ll.ext(e.prototype,{addBehavior:function(e){if(this.getConfig("behavior")&&e&&"object"==typeof e){var r={},s=e.data||{};if(e.type)r=s;else{if("string"!=typeof s.name||"string"!=typeof s.message)return;r.name=s.name.substr(0,20),r.message=s.message.substr(0,200)}r.message&&(r.message=Ll.encode(r.message));var n={type:e.type||"custom",data:r||{},timestamp:e.timestamp||Date.now(),page:e.page||t&&t.location&&t.location.pathname};return i.push(n),i=i.slice(-100)}},getBehavior:function(){return i||[]},setBehavior:function(e){return e&&(i=e),i},reportBehavior:function(e){var t=this;t.getConfig("behavior")&&(t.sendBhTimer&&(clearTimeout(t.sendBhTimer),t.sendBhTimer=void 0),t.sendBhTimer=setTimeout(function(){i&&i.length>0&&(t.behavior(i),i=[],t.sendBhTimer=void 0,e&&"function"==typeof e&&e())},0))},initBehavior:function(){if(!this.hasInitBehavior&&!r){try{!function(){if(document&&document.referrer&&document.location){var e=document.referrer,t=document.location.href;if(""!==e){var i={type:"navigation",data:{from:e,to:t}};s=t,r&&r.addBehavior(i)}}}(),t&&t.document&&t.document.addEventListener&&(t.document.addEventListener("click",h("click"),!1),t.document.addEventListener("keypress",h("keypress"),!1)),function(){if(function(){var e=t&&t.chrome,i=e&&e.app&&e.app.runtime,r="history"in t&&!!t.history.pushState&&!!t.history.replaceState;return!i&&r}()){var e=function(e,t){var i={type:"navigation",data:{from:e,to:t}};r&&r.addBehavior(i),s=t},i=t.onpopstate;t.onpopstate=function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];var a=t.location.href;if(e(s,a),i)return i.apply(this,n)};var n=function(t){return function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];var o=r.length>2?r[2]:void 0;return o&&e(s,String(o)),t.apply(this,r)}};c(t.history,"pushState",n),c(t.history,"replaceState",n)}}(),this.getConfig("enableConsole")&&function(){if(t&&t.console)for(var e=["debug","info","warn","log","error","assert"],i=0;i<e.length;i++){var s=e[i];t.console[s]&&"function"==typeof t.console[s]&&c(t.console,s,function(e){var i=s;return function(){for(var s=arguments.length,n=new Array(s),o=0;o<s;o++)n[o]=arguments[o];var a={type:"console",data:{level:i,message:n}};if(r&&r.addBehavior(a),"error"===i)for(var c=0;c<n.length;c++){var l=n[c];l&&l.message&&l.stack&&r&&r.errorHandler(new ErrorEvent("error",{error:l,message:l.message}))}e&&Function.prototype.apply.call(e,t.console,n)}})}}()}catch(e){Ll.warn("[arms] error in initBehavior",e)}r=this,this.hasInitBehavior=!0}return this}})},zl=["","fetchStart","domainLookupStart","domainLookupEnd","connectStart","connectEnd","requestStart","responseStart","responseEnd","","domInteractive","","domContentLoadedEventEnd","","loadEventStart","","msFirstPaint","secureConnectionStart"],Yl=zl,Jl=function(){var e=Ll.win||{},t=e.performance;if(!t||"object"!=typeof t||"function"!=typeof t.getEntriesByType)return null;var i={},r=t.timing||{},s=t.getEntriesByType("resource")||[];if(i.begin=r[Yl[1]]||Date.now(),"function"==typeof e.PerformanceNavigationTiming){var n=t.getEntriesByType("navigation")[0];n&&(r=n)}return Ll.each({dom:[10,8],load:[14,1]},function(e,t){var s=r[Yl[e[1]]],n=r[Yl[e[0]]];if(s>0&&n>0){var o=Math.round(n-s);o>=0&&o<6e5&&(i[t]=o)}}),i.res=JSON.stringify(s),i},Zl=zl,Xl=function(){var e=Ll.win||{},t=e.performance;if(!t||"object"!=typeof t)return null;var i={},r=t.timing||{},s=Date.now(),n=1;if("function"==typeof e.PerformanceNavigationTiming){var o=t.getEntriesByType("navigation")[0];o&&(r=o,n=2)}Ll.each({dns:[3,2],tcp:[5,4],ssl:[5,17],ttfb:[7,6],trans:[8,7],dom:[10,8],res:[14,12],firstbyte:[7,2],fpt:[8,1],tti:[10,1],ready:[12,1],load:[14,1]},function(e,t){var s=r[Zl[e[1]]],o=r[Zl[e[0]]];if(2===n||s>0&&o>0){var a=Math.round(o-s);a>=0&&a<6e5&&(i[t]=a)}});var a=e.navigator.connection,c=t.navigation||{};i.ct=a?a.effectiveType||a.type:"";var l=a&&(a.downlink||a.downlinkMax||a.bandwidth)||null;if((l=l>999?999:l)&&(i.bandwidth=l),i.navtype=1===c.type?"Reload":"Other",1===n&&r[Zl[16]]>0&&r[Zl[1]]>0){var h=r[Zl[16]]-r[Zl[1]];h>=0&&h<36e5&&(i.fpt=h)}return 1===n&&r[Zl[1]]>0?i.begin=r[Zl[1]]:2===n&&i.load>0?i.begin=s-i.load:i.begin=s,i},Ql=function(e,t,i){function r(e,t,i){var s=0,o=e.tagName;if("SCRIPT"!==o&&"STYLE"!==o&&"META"!==o&&"HEAD"!==o){var a=e.children?e.children.length:0;if(a>0)for(var c=e.children,l=a-1;l>=0;l--)s+=r(c[l],t+1,s>0);if(s<=0&&!i&&!(e.getBoundingClientRect&&e.getBoundingClientRect().top<n))return 0;s+=1+.5*t}return s}function s(e){for(var t=1;t<e.length;t++)if(e[t].score<e[t-1].score)return e.splice(t,1),s(e);return e}var n=t.innerHeight||0,o=[],a=null,c=0;Ll.ext(e.prototype,{initFmpObserver:function(e){var s=this;if(!s._conf||!s._conf.useFmp)return null;if(!t.MutationObserver)return Ll.warn("[retcode] first meaningful paint can not be retrieved"),s.sendPerformance(),null;Ll.on(t,"beforeunload",function(){s.endObserving(0,!0)});var n=t.MutationObserver;return(a=new n(function(){!function(e){var t=Date.now()-e,s=i.querySelector("body");if(s){var n=0;n+=r(s,1,!1),o.push({score:n,t:t})}else o.push({score:0,t:t})}(s._startTime)})).observe(document,{childList:!0,subtree:!0}),c=1,s.onReady(function(){s.endObserving(e)}),a},endObserving:function(e,t){var i=this;if(a&&c)if(i.fmpTimmer&&(clearTimeout(i.fmpTimmer),i.fmpTimmer=null),t||!function(e,t){var i=Date.now()-e;return!(i>t||i-(o&&o.length&&o[o.length-1].t||0)>1e3)}(i._startTime,e)){a.disconnect(),c=0,o=s(o);for(var r=null,n=1;n<o.length;n++)if(o[n].t>=o[n-1].t){var l=o[n].score-o[n-1].score;(!r||r.rate<=l)&&(r={t:o[n].t,rate:l})}r&&r.t>0&&r.t<36e5?i.sendPerformance({fmp:r.t}):i.sendPerformance()}else i.fmpTimmer=Ll.delay(function(){i.endObserving(e)},500)}})},eh=si(function(e){var t=Ll.win,i=t.document,r=/^(error|api|speed|sum|avg|percent|custom|msg|setPage|setConfig|behavior|performance)$/,s=function(e){var i=this;return Wl.call(i,e),i._initialPage=e.page&&Ll.safetyCall(e.page,[],e.page+"")||null,i._isRobot=Ll.isRobot(),i._health={errcount:0,apisucc:0,apifail:0},i.beforeSend=function(e,t){"error"===e?i._health.errcount++:"api"===e&&i._health[t.success?"apisucc":"apifail"]++},!1!==e.enableInstanceAutoSend&&(i.initHandler(),i.initHook(),i.initFmpObserver(1e4),i._conf&&i._conf.behavior&&"function"==typeof i.initBehavior&&i.initBehavior()),Object.defineProperty&&t.addEventListener&&Object.defineProperty(i,"pipe",{set:i.sendPipe}),i};s.prototype=Ll.createObject(Wl.prototype),Ll.ext(Wl._root.dftCon,{uid:null,setUsername:null,ignoreUrlPath:null,ignoreApiPath:null,urlHelper:[{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},/\/$/],apiHelper:{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},ignoreUrlCase:!0,imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",disableHook:!1,autoSendPv:!0,autoSendPerf:!0,enableSPA:!1,enableLinkTrace:!1,linkType:"arms",enableApiCors:!1,sendResource:!0,behavior:!0,enableConsole:!1,parseHash:function(e){return(e?Ll.cutUrlSearch(e.replace(/^#\/?/,"")):"")||"[index]"},parseResponse:function(e){if(!e||"object"!=typeof e)return{};var t=e.code,i=e.msg||e.message||e.subMsg||e.errorMsg||e.ret||e.errorResponse||"";return"object"==typeof i&&(t=t||i.code,i=i.msg||i.message||i.info||i.ret||JSON.stringify(i)),{msg:i,code:t,success:!0}}}),Ll.ext(s.prototype,{constructor:s,_super:Wl,onReady:function(e){var r=this;if(r.hasReady)return e();"complete"===i.readyState?(r.hasReady=!0,e()):Ll.on(t,"load",function(){r.hasReady=!0,e()},!0)},getPage:function(e){var t=this._conf,i=t.page,r=location,s=r.host+r.pathname;return i&&!e?Ll.safetyCall(i,[],i+""):this._initialPage||Ll.filterByRule(t.ignoreUrlCase?s.toLowerCase():s,t.ignoreUrlPath?t.ignoreUrlPath:t.urlHelper)},setPage:function(e,t){var i=this,r=i.prevPage;if(!1!==t){if(!e||e===r)return i;i.prevPage=e,clearTimeout(i.sendPVTimmer),i.handleUnload(1),i.resetPageview(),i.sendPVTimmer=setTimeout(function(){i.sendPV()},10)}else i.prevPage=e;return i._conf.page=e,i},setConfig:function(e,t){if(e&&"object"==typeof e){Ll.verifyConfig(e),e=this.setImgUrl(e);var i=this._conf;if(this._conf=Ll.ext({},i,e),!t){var r="disableHook";r in e&&i[r]!==e[r]&&(e[r]?this.removeHook():this.addHook()),(r="enableSPA")in e&&i[r]!==e[r]&&this.bindHashChange(e[r])}}},sendRequest:function(e){Gl(e,this.getConfig("imgUrl"))},postData:function(e,t){var i={};i[t]=e[t],delete e[t];var r="";"object"==typeof e&&(r=Ll.serialize(e)),Vl(i,this.getConfig("imgUrl")+r+"&post_res=")},sendPipe:function(e){var t=this;if(!e||!e.length)return t;try{if("Array"===Ll.T(e[0]))return Ll.each(e,function(e){return t.sendPipe(e)});if("Array"!==Ll.T(e))return t;var i=e.shift();if(!r.test(i))return t;t[i].apply(t,e)}catch(e){return Ll.warn("[retcode] error in sendPipe",e),t}},sendHealth:function(){var e=Ll.ext({},this._health);e.healthy=e.errcount>0?0:1,e.begin=Date.now();var t=e.begin-this.sBegin;e.stay=t,this._lg("health",e,1),this._health={errcount:0,apisucc:0,apifail:0}},createInstance:function(e){e=Ll.ext({pid:this._conf.pid},e);var t=this.__proto__.constructor(e);return e.page&&t.sendPV(),t}}),Kl(s,t),function(e,t,i){var r=Ll,s=Jl,n=Xl,o=null,a=i.documentElement,c=t.innerWidth||a.clientWidth||i.body.clientWidth,l=t.innerHeight||a.clientHeight||i.body.clientHeight,h=t.navigator.connection,d={sr:screen.width+"x"+screen.height,vp:c+"x"+l,ct:h?h.effectiveType||h.type:""},u={},g=function(e,t,s,n,o){if(void 0===t){var a,c;if(!u[e]){a=new RegExp(e+"=([^;]+)");try{c=a.exec(i.cookie)}catch(e){return r.warn("[retcode] can not get cookie:",e),null}c&&(u[e]=c[1])}return u[e]}var l=e+"="+t;n&&(l+="; domain="+n),l+="; path="+(o||"/"),s&&(l+="; max-age="+s);try{return i.cookie=l,!!i.cookie}catch(e){return r.warn("[retcode] can not set cookie: ",e),!1}},f=function(e){var t=e._conf.uid||g("_nk_")||g("_bl_uid");return t||(t=r.uu(),g("_bl_uid",t,15552e3))?t:null};r.ext(e.prototype,{activeErrHandler:function(e){return o&&!e||(o=this),this},errorHandler:function(e){if(!e)return this;var t=e.type;if("error"===t){var i=e.target||e.srcElement;!i||!i.tagName||e.message||e.filename||e.lineno||e.colno?this.error(e.error||{message:e.message},e):this.resourceErrorHandler(e)}else"unhandledrejection"===t&&r.T(e.reason,"Error")&&r.checkAutoError(e.reason)&&this.error(e.reason);try{this.getConfig("behavior")&&this.reportBehavior&&this.reportBehavior()}catch(e){}return this},resourceErrorHandler:function(e){var t=this,i=e.target||e.srcElement;try{var s=t.getSrc(i),n="string"==typeof i.tagName?i.tagName.toLowerCase():"",o=t.getXPath(i,5);return t._lg("resourceError",{src:s&&s.substring(0,1e3),node_name:n,xpath:o}),t}catch(e){return r.warn("[ARMS] resourceErrorHandler error :",e),t}},getSrc:function(e){var t=e.src||e.href;try{if(!t){var i="object"===("string"==typeof e.tagName?e.tagName.toLowerCase():""),r=e.getAttribute("classid")&&"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"===e.getAttribute("classid").toLowerCase()||"application/x-shockwave-flash"===e.getAttribute("type");i&&r&&(t=e.getAttribute("data")||e.getAttribute("codebase")),t||(t=e.outerHTML||e.innerHTML)}}catch(e){t=""}return t},getXPath:function(e,t){var i=e.id?"#"+e.id:"",r="string"==typeof e.className?"."+e.className.split(" ").join("."):"",s=("string"==typeof e.tagName?e.tagName.toLowerCase():"")+i+r;return e.parentNode&&e.parentNode.tagName&&t-1!=0?this.getXPath(e.parentNode,t-1)+" > "+s:s},sendPerformance:function(e){var t=this;t.onReady(function(){var i=n();i&&i.load&&i.load>0&&(i.page=t.getPage(!0),e&&(i=r.ext(i,e)),i.autoSend=!0,t.performance(i))})},sendResources:function(e){var t=this;t.onReady(function(){var i=s();i&&i.load&&i.load>0&&(i.load&&i.load<=2e3||i.load&&i.load<=8e3&&Math.random()>.05||(i.page=t.getPage(!0),i.dl=location.href,e&&(i=r.ext(i,e)),t._lg("res",i,t.getConfig("sample"))))})},sendPV:function(){var e=this;e.onReady(function(){var r=function(e){var r=f(e),s=t.devicePixelRatio||1;return{uid:r,dt:i.title,dl:location.href,dr:i.referrer,dpr:s.toFixed(2),de:(i.characterSet||i.defaultCharset||"").toLowerCase(),ul:a.lang,begin:Date.now()}}(e);r&&r.uid&&e._lg("pv",r,e.getConfig("pvSample"))})},commonInfo:function(){return d.uid=f(this),d.sid=function(e){if(e.session)return e.session;var t;try{if("object"==typeof window&&"object"==typeof sessionStorage&&"function"==typeof sessionStorage.getItem)return"string"==typeof(t=sessionStorage.getItem("_bl_sid"))?(e.session=t,t):(t=r.uu(),e.session=t,"function"==typeof sessionStorage.setItem&&sessionStorage.setItem("_bl_sid",t),t)}catch(e){r.warn("[ARMS] getSid error :",e)}return e.session=t=r.uu(),t}(this),d},handleUnload:function(e){var t=Date.now();if(t-this._lastUnload<200)return this;this._lastUnload=t,this.sendHealth(e),this.speedCache&&(this._lg("speed",this.speedCache),this.speedCache=null,clearTimeout(this.speedTimmer)),this.clear(!0)},bindHashChange:function(e){var i=this;if(!e^i.hashChangeHandler)return i;e?(i.hackHistoryState(),i.hashChangeHandler=function(e){var t=i._conf.parseHash(location.hash);t&&i.setPage(t,!1!==e)},i.stateChangeHandler=function(e){var t=i._conf.parseHash(e.detail);t&&i.setPage(t)},r.on(t,"hashchange",i.hashChangeHandler),r.on(t,"historystatechange",i.stateChangeHandler),i.hashChangeHandler(!1)):(r.off(t,"hashchange",i.hashChangeHandler),r.off(t,"historystatechange",i.stateChangeHandler),i.hashChangeHandler=null,i.stateChangeHandler=null)},initHandler:function(){var e=this;if(e.hasInitHandler)return e;var i=e._conf;return r.on(t,"beforeunload",function(){e.handleUnload(0)}),e.bindHashChange(i.enableSPA),e.activeErrHandler(!1),e.hasInitHandler=!0,e}}),r.on(t,"error",function(e){o&&o.errorHandler(e)},!1,!0).on(t,"unhandledrejection",function(e){o&&o.errorHandler(e)})}(s,t,i),Ql(s,t,i),function(e,t){var i=Ll,r=null,s=i.getCurDomain(),n=function(e,t,r,n,o,a,c,l,h,d,u,g,f){var p=i.J(o)||null,v=i.safetyCall(t,[p,n],null);if(!v)return!1;var m=v.code||a,b=!("success"in v)||v.success;e.api(r,b,c,m,v.msg,l,h,d,u,s,g,f)},o="fetch",a="__oFetch_",c="__oXMLHttpRequest_",l="XMLHttpRequest";i.ext(e.prototype,{removeHook:function(e,i){return r&&(i||this===r)?(t[a]&&(t[o]=t[a],delete t[a]),t[c]&&(t[l]=t[c],delete t[c]),r=null,this):this},addHook:function(e){return!e&&r||(r||(function(){if("function"==typeof t[o]){var e=t[o];t[a]=e,t[o]=function(o,a){var c=1===arguments.length?[arguments[0]]:Array.apply(null,arguments),l=r;if(!l||!l.api)return e.apply(t,c);if(a&&("HEAD"===a.method||"no-cors"===a.mode))return e.apply(t,c);var h=Date.now(),d=l._conf,u=(o&&"string"!=typeof o?o.url:o)||"",g=u;u=i.cutUrlSearch(u);var f=(d.ignore||{}).ignoreApis;if(!i.checkAPI(u,!0)||i.ignoreByRule(u,f))return e.apply(t,c);u=i.filterByRule(u,d.ignoreApiPath?d.ignoreApiPath:d.apiHelper);var p=d.enableLinkTrace,v="",m="",b=l.getConfig("pid"),y=null,w=l.getConfig("sample"),S=l.getConfig("linkType"),T=1;if(w&&!l.sampling(w)&&(T=0),p){var R="";try{R=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch(e){R=""}var E=i.checkSameOrigin(g,R);if(l.getConfig("enableApiCors")||E){if(o&&"string"!=typeof o)try{if(c[0].headers&&"function"==typeof c[0].headers.get&&"function"==typeof c[0].headers.append)if("tracing"===S){var I=c[0].headers.get("uber-trace-id");I?v=I.split(":")[0]:(I=l.getUberTraceId(T),c[0].headers.append("uber-trace-id",I["uber-trace-id"]),v=I.traceId),m=l.pageview}else{var C=c[0].headers.get("EagleEye-TraceID"),P=c[0].headers.get("EagleEye-SessionID"),A=c[0].headers.get("EagleEye-pAppName");C?v=C:(v=l.getTraceId()["EagleEye-TraceID"],c[0].headers.append("EagleEye-TraceID",v)),P?m=P:(m=l.getPageviewId()["EagleEye-SessionID"],c[0].headers.append("EagleEye-SessionID",m)),A||c[0].headers.append("EagleEye-pAppName",b)}}catch(e){i.warn("[retcode] fetch failed to set header, exception is :\n"+e)}if(a)if("tracing"===(a.headers=a.headers?a.headers:{},S)){if(a.headers["uber-trace-id"])v=a.headers["uber-trace-id"].split(":")[0];else{var O=l.getUberTraceId(T);a.headers["uber-trace-id"]=O["uber-trace-id"],v=O.traceId}m=l.getPageviewId()["EagleEye-SessionID"]}else a.headers["EagleEye-TraceID"]?v=a.headers["EagleEye-TraceID"]:(v=l.getTraceId()["EagleEye-TraceID"],a.headers["EagleEye-TraceID"]=v),a.headers["EagleEye-SessionID"]?m=a.headers["EagleEye-SessionID"]:(m=l.getPageviewId()["EagleEye-SessionID"],a.headers["EagleEye-SessionID"]=m),a.headers["EagleEye-pAppName"]||(a.headers["EagleEye-pAppName"]=b)}}return e.apply(t,c).then(function(e){if(!l||!l.api)return e;try{if(!e||"function"!=typeof e.clone)return e;var t=e.clone(),r=t.headers;if(r&&"function"==typeof r.get){var o=r.get("content-type");if(o&&!/(text)|(json)/.test(o))return e;if(!v){var a=i.parseFetchHeaders(r);"object"==typeof a&&a["eagleeye-traceid"]&&(v=a["eagleeye-traceid"],y="response")}}var f=Date.now()-h;return t.text().then(function(e){var o=i.getFetchSnapshot(c,e,r);t.ok?n(l,d.parseResponse,u,g,e,t.status||200,f,h,v,m,o,y,T):l.api(u,!1,f,t.status||404,t.statusText,h,v,m,o,s,y,T)}),e}catch(t){return i.warn("[ARMS] fetch response error :",t),e}}).catch(function(e){if(!l||!l.api)throw e;var t=Date.now()-h;throw l.api(u,!1,t,e.name||"Error",e.message,h,v,m,{},s),e})},t[o].toString=i.createFakeToString(o)}}(),function(){if("function"==typeof t[l]){var e,o=t[l];t[c]=o;var a=function(t){var a=new o(t),c=r;if(!c||!c.api||!a.addEventListener)return a;var l,h,d,u=a.send,g=a.open,f=a.setRequestHeader,p=c._conf,v=(p.ignore||{}).ignoreApis,m=c.getConfig("enableLinkTrace"),b="",y="",w="",S=null,T=c.getConfig("sample"),R=c.getConfig("linkType"),E=1;return T&&!c.sampling(T)&&(E=0),a.open=function(t,r){e=t;var s=1===arguments.length?[arguments[0]]:Array.apply(null,arguments);g.apply(a,s),d=r||"",h=i.cutUrlSearch(d);var n=!i.checkAPI(h,!0)||i.ignoreByRule(h,v);if(h=h?i.filterByRule(h,p.ignoreApiPath?p.ignoreApiPath:p.apiHelper):"",!n&&m){var o="";try{o=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch(e){o=""}var l=i.checkSameOrigin(d,o);if((c.getConfig("enableApiCors")||l)&&f&&"function"==typeof f)if("tracing"===R){var u=c.getUberTraceId(E);f.apply(a,["uber-trace-id",u["uber-trace-id"]]),b=u.traceId,y=c.getPageviewId()["EagleEye-SessionID"]}else b=c.getTraceId()["EagleEye-TraceID"],f.apply(a,["EagleEye-TraceID",b]),y=c.getPageviewId()["EagleEye-SessionID"],f.apply(a,["EagleEye-SessionID",y]),w=c.getConfig("pid"),f.apply(a,["EagleEye-pAppName",w])}},a.send=function(){l=Date.now();var e=1===arguments.length?[arguments[0]]:Array.apply(null,arguments);u.apply(a,e)},i.on(a,"readystatechange",function(){if(h&&4===a.readyState){var t=Date.now()-l,r=i.getXhrSnapshot(d,e,a);if(!b){var o=i.parseXhrHeaders("function"==typeof a.getAllResponseHeaders&&a.getAllResponseHeaders()||"");"object"==typeof o&&o["eagleeye-traceid"]&&(b=o["eagleeye-traceid"],S="response")}if(a.status>=200&&a.status<=299){var u=a.status||200;if("function"==typeof a.getResponseHeader){var g=a.getResponseHeader("Content-Type");if(g&&!/(text)|(json)/.test(g))return}a.responseType&&"text"!==a.responseType?c.api(h,!0,t,u,"",l,b,y,{},s,S,E):n(c,p.parseResponse,h,d,a.responseText,u,t,l,b,y,r,S,E)}else c.api(h,!1,t,a.status||"FAILED",a.statusText,l,b,y,r,s,S,E)}}),a};a.prototype=o.prototype,t[l]=a,t[l].toString=i.createFakeToString(l)}}()),r=this),this},initHook:function(){return this.hasInitHook||(this.getConfig("disableHook")||this.addHook(),this.hasInitHook=!0),this}})}(s,t),function(e,t){var i=Ll,r=t.history||{},s=t.document,n=function(e,i){var r;t.CustomEvent?r=new CustomEvent(e,{detail:i}):((r=s.createEvent("HTMLEvents")).initEvent(e,!1,!0),r.detail=i),t.dispatchEvent(r)},o=function(e){var t=r[e];"function"==typeof t&&(r[e]=function(s,o,a){var c=1===arguments.length?[arguments[0]]:Array.apply(null,arguments),l=location.href,h=t.apply(r,c);if(!a||"string"!=typeof a)return h;if(a===l)return h;try{var d=l.split("#"),u=a.split("#"),g=i.cutUrlSearch(d[0]),f=i.cutUrlSearch(u[0]),p=d[1]&&d[1].replace(/^\/?(.*)/,"$1"),v=u[1]&&u[1].replace(/^\/?(.*)/,"$1");g!==f?n("historystatechange",f):p!==v&&n("historystatechange",v)}catch(t){i.warn("[retcode] error in "+e+": "+t)}return h},r[e].toString=i.createFakeToString(e))};i.ext(e.prototype,{hackHistoryState:function(){return this.hasHackedHistoryState||(o("pushState"),o("replaceState"),this.hasHackedHistoryState=!0),this}})}(s,t),s._super=Wl,s._root=Wl._root,Wl.Browser=s,e.exports=s}),th=si(function(e){function t(e,t){var o=i[s]=new r(e);o.sendPipe(t);var a=o._conf;return!1!==a.autoSendPv&&o.sendPV(),a&&a.useFmp||o.sendPerformance(),a&&a.sendResource&&o.sendResources(),i[n]=!0,o}var i=window,r=i.BrowserLogger=eh,s=Ll.key,n="__hasInitBlSdk";r.singleton=function(e,r){return i[n]?i[s]:t(e,r)},r.createExtraInstance=function(e){e&&"object"==typeof e&&!0!==e.enableInstanceAutoSend&&(e.enableInstanceAutoSend=!1);var t=new r(e),i=t._conf;return i.enableInstanceAutoSend&&(!1!==i.autoSendPv&&t.sendPV(),i&&i.useFmp||t.sendPerformance(),i&&i.sendResource&&t.sendResources()),t},"object"==typeof window&&!!window.navigator&&i[s]&&(r.bl=function(){if(i[n])return i[s];var e={},r=[];return s in i&&(e=i[s].config||{},r=i[s].pipe||[]),t(e,r)}()),e.exports=r});function ih(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)}function rh(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i}var sh,nh,oh,ah,ch,lh,hh,dh,uh,gh,fh,ph,vh,mh,bh,yh,wh,Sh,Th,Rh,Eh,Ih,Ch,Ph,Ah,Oh,kh,Dh,$h,jh,_h,Hh,Mh,xh,qh,Nh,Fh,Uh,Lh,Bh,Wh,Gh,Vh,Kh,zh,Yh,Jh,Zh,Xh,Qh,ed,td,id,rd,sd,nd,od,ad,cd,ld,hd,dd,ud,gd,fd,pd,vd,md,bd,yd,wd,Sd,Td,Rd,Ed,Id,Cd,Pd,Ad,Od,kd,Dd,$d,jd,_d,Hd,Md,xd,qd,Nd,Fd,Ud,Ld,Bd,Wd,Gd,Vd,Kd,zd,Yd,Jd,Zd,Xd,Qd,eu,tu,iu,ru,su,nu,ou,au,cu,lu,hu,du,uu,gu,fu,pu,vu,mu,bu,yu,wu,Su,Tu,Ru,Eu,Iu,Cu,Pu,Au,Ou,ku,Du,$u,ju,_u,Hu,Mu,xu,qu,Nu,Fu,Uu,Lu,Bu,Wu,Gu,Vu=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),sh.add(this),nh.set(this,void 0),oh.set(this,void 0),ah.set(this,void 0),ch.set(this,void 0),lh.set(this,void 0),hh.set(this,void 0),dh.set(this,"https://arms-retcode.aliyuncs.com/r.png?"),uh.set(this,!0),gh.set(this,!0),fh.set(this,{});var i=t.release,r=t.environment,s=t.uid,n=t.pid,o=t.appType,a=t.imgUrl,c=t.sendResource,l=t.disableHook,h=function(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(i[r[s]]=e[r[s]])}return i}(t,["release","environment","uid","pid","appType","imgUrl","sendResource","disableHook"]);rh(this,oh,i,"f"),rh(this,ah,r,"f"),rh(this,ch,s,"f"),rh(this,lh,n,"f"),rh(this,hh,o,"f"),rh(this,dh,null!=a?a:ih(this,dh,"f"),"f"),rh(this,uh,null!=c?c:ih(this,uh,"f"),"f"),rh(this,gh,null!=l?l:ih(this,gh,"f"),"f"),rh(this,fh,h,"f"),this.getInstance(),ih(this,sh,"m",ph).call(this)}return t=e,i=[{key:"getInstance",value:function(){return ih(this,nh,"f")||rh(this,nh,th.singleton(lc({uid:ih(this,ch,"f"),pid:ih(this,lh,"f"),appType:ih(this,hh,"f"),imgUrl:ih(this,dh,"f"),sendResource:ih(this,uh,"f"),disableHook:ih(this,gh,"f"),environment:ih(this,ah,"f"),release:ih(this,oh,"f")},ih(this,fh,"f"))),"f"),ih(this,nh,"f")}},{key:"errorParser",value:function(e){return ql.parse(e)}},{key:"errReport",value:function(e){this.getInstance().error(e,{filename:void 0,lineno:void 0,colno:void 0})}}],i&&sc(t.prototype,i),r&&sc(t,r),cs(t,"prototype",{writable:!1}),e;var t,i,r}();nh=new Ol,oh=new Ol,ah=new Ol,ch=new Ol,lh=new Ol,hh=new Ol,dh=new Ol,uh=new Ol,gh=new Ol,fh=new Ol,sh=new Ml,ph=function(){var e=this;window.onerror=function(t,i,r,s,n){e.getInstance().error(n,{filename:i,lineno:r,colno:s})},window.addEventListener("unhandledrejection",function(t){t.promise.catch(function(t){e.errReport(t)})}),window.addEventListener("rejectionhandled",function(t){t.promise.catch(function(t){e.errReport(t)})})};class Ku{static getAliArms(e){const t=e&&e!==s(this,vh,"f",bh);return t&&n(this,vh,e,"f",bh),s(this,vh,"f",mh)&&!t||(n(this,vh,new Vu({uid:s(this,vh,"f",bh),pid:"jjn8k2jk90@aa39edd52601f08",appType:"web",imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",release:"6.0.8",environment:"prod",sendResource:!1,autoSendPerf:!1,useFmp:!1,autoSendPv:!1,enableSPA:!1,jsReport:!1,behavior:!1,enableConsole:!1,disableHook:!0,ignore:{ignoreErrors:[()=>!0],ignoreResErrors:[()=>!0]}}),"f",mh),s(this,vh,"f",yh).push({uid:s(this,vh,"f",bh),aliArms:s(this,vh,"f",mh)})),s(this,vh,"f",mh)}static getAliArmsList(){return s(this,vh,"f",yh)}static errReport(e,t){var i;null===(i=Ku.getAliArms(t))||void 0===i||i.errReport(e)}}vh=Ku,mh={value:void 0},bh={value:void 0},yh={value:[]};class zu{constructor(t,i,s={}){var n,o,a,c,l,h,d,u,g,f,p,v,m,b,y,w,S,T,R,E,I,C,P,A;Object.defineProperty(this,"session",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"userAgentManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:"idle"}),Object.defineProperty(this,"destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"hardFailed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"signalingBusyCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"disconnectedTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"retryTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signalingBusyTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"negotiationTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"iceRecoveryTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"rtpStatsTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onlineTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"transportRecoveryTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"registrationRecoveryTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"transportWaitStartedAt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingTransportRecoveryReason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"registrationWaitStartedAt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingRegistrationRecoveryReason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lastRtpSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lastRtpProgressAt",{enumerable:!0,configurable:!0,writable:!0,value:Date.now()}),Object.defineProperty(this,"lastRtpRecoveryAt",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"recoveryGeneration",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"acceptedRecoveryGeneration",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"recoveryReason",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"reinviteReason",{enumerable:!0,configurable:!0,writable:!0,value:"unknown"}),Object.defineProperty(this,"permanentRecoverySdpModifier",{enumerable:!0,configurable:!0,writable:!0,value:e=>r(this,void 0,void 0,function*(){return this.applyRecoveryReasonToSdp(e)})}),Object.defineProperty(this,"handleSessionStateChange",{enumerable:!0,configurable:!0,writable:!0,value:t=>{switch(this.logInfo("SIP session state:",t),t){case e.SessionState.Established:this.handleEstablished();break;case e.SessionState.Terminating:case e.SessionState.Terminated:this.destroy()}}}),Object.defineProperty(this,"handleOffline",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.destroyed||this.hardFailed||(this.logInfo("browser offline"),this.clearDisconnectedTimer(),this.clearRetryTimer(),this.clearSignalingBusyTimer(),this.clearIceRecoveryTimer(),this.clearTransportRecoveryTimer(),"sending-reinvite"!==this.state&&(this.state="idle"))}}),Object.defineProperty(this,"handleOnline",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.destroyed||this.hardFailed||(this.logInfo("browser online"),this.onlineTimer&&clearTimeout(this.onlineTimer),this.onlineTimer=setTimeout(()=>{if(this.onlineTimer=void 0,this.destroyed||this.hardFailed)return;if(this.session.state!==e.SessionState.Established)return;if(!this.isTransportAvailable())return void this.waitForTransport("network-online");const t=this.getPeerConnection();if(t)if("stable"===t.signalingState)switch(t.iceConnectionState){case"failed":case"disconnected":this.state="idle",this.recover("network-online")}else this.scheduleSignalingBusyRetry(`network-online:${t.signalingState}`)},this.options.onlineRecoveryDelayMs))}}),this.session=t,this.userAgentManager=i,this.options={disconnectedTimeoutMs:null!==(n=s.disconnectedTimeoutMs)&&void 0!==n?n:3e3,negotiationTimeoutMs:null!==(o=s.negotiationTimeoutMs)&&void 0!==o?o:1e4,iceRecoveryTimeoutMs:null!==(a=s.iceRecoveryTimeoutMs)&&void 0!==a?a:1e4,iceGatheringTimeoutMs:null!==(c=s.iceGatheringTimeoutMs)&&void 0!==c?c:5e3,maxRetries:null!==(l=s.maxRetries)&&void 0!==l?l:3,retryBaseDelayMs:null!==(h=s.retryBaseDelayMs)&&void 0!==h?h:1e3,retryMaxDelayMs:null!==(d=s.retryMaxDelayMs)&&void 0!==d?d:1e4,maxSignalingBusyRetries:null!==(u=s.maxSignalingBusyRetries)&&void 0!==u?u:3,signalingBusyRetryDelayMs:null!==(g=s.signalingBusyRetryDelayMs)&&void 0!==g?g:1e3,enableRtpWatchdog:null===(f=s.enableRtpWatchdog)||void 0===f||f,rtpStatsIntervalMs:null!==(p=s.rtpStatsIntervalMs)&&void 0!==p?p:1e3,rtpStallTimeoutMs:null!==(v=s.rtpStallTimeoutMs)&&void 0!==v?v:5e3,recoverOnRtpStallWhenIceConnected:null===(m=s.recoverOnRtpStallWhenIceConnected)||void 0===m||m,rtpRecoveryCooldownMs:null!==(b=s.rtpRecoveryCooldownMs)&&void 0!==b?b:1e4,onlineRecoveryDelayMs:null!==(y=s.onlineRecoveryDelayMs)&&void 0!==y?y:800,transportRecoveryPollMs:null!==(w=s.transportRecoveryPollMs)&&void 0!==w?w:1e3,transportRecoveryTimeoutMs:null!==(S=s.transportRecoveryTimeoutMs)&&void 0!==S?S:6e4,registrationRecoveryPollMs:null!==(T=s.registrationRecoveryPollMs)&&void 0!==T?T:1e3,registrationRecoveryTimeoutMs:null!==(R=s.registrationRecoveryTimeoutMs)&&void 0!==R?R:6e4,debugIceCredentials:null!==(E=s.debugIceCredentials)&&void 0!==E&&E,includeRecoveryReasonInSdp:null===(I=s.includeRecoveryReasonInSdp)||void 0===I||I,recoveryReasonSdpAttribute:null!==(C=s.recoveryReasonSdpAttribute)&&void 0!==C?C:"x-recovery-reason",reinviteReasonSdpAttribute:null!==(P=s.reinviteReasonSdpAttribute)&&void 0!==P?P:"x-reinvite-reason",isSignalingAvailable:s.isSignalingAvailable,isRegistrationAvailable:s.isRegistrationAvailable,logger:null!==(A=s.logger)&&void 0!==A?A:console,onRecoveryStart:s.onRecoveryStart,onRecovered:s.onRecovered,onRecoveryFailed:s.onRecoveryFailed}}start(){this.destroyed||this.hardFailed||(this.logInfo("start"),this.session.stateChange.addListener(this.handleSessionStateChange),"undefined"!=typeof window&&(window.addEventListener("online",this.handleOnline),window.addEventListener("offline",this.handleOffline)),this.session.state===e.SessionState.Established&&this.handleEstablished())}restartNow(e="manual"){return r(this,void 0,void 0,function*(){yield this.recover(e)})}getState(){return this.state}getRetryCount(){return this.retryCount}getIceConnectionState(){var e;return null===(e=this.getPeerConnection())||void 0===e?void 0:e.iceConnectionState}destroy(){if(this.destroyed)return;this.destroyed=!0,this.hardFailed=!0,this.recoveryGeneration++,this.state="terminated",this.clearAllTimers(),this.session.stateChange.removeListener(this.handleSessionStateChange),"undefined"!=typeof window&&(window.removeEventListener("online",this.handleOnline),window.removeEventListener("offline",this.handleOffline));const e=this.getSessionDescriptionHandler();e&&this.bound&&(e.peerConnectionDelegate=void 0),this.bound=!1,this.logInfo("destroy")}handleEstablished(){this.destroyed||this.hardFailed||(this.bindPeerConnectionDelegate(),this.options.enableRtpWatchdog&&this.startRtpWatchdog())}bindPeerConnectionDelegate(){const e=this.getSessionDescriptionHandler(),t=null==e?void 0:e.peerConnection;e&&t?this.bound||(this.bound=!0,this.logInfo("bind PeerConnection",{iceConnectionState:t.iceConnectionState,connectionState:t.connectionState,signalingState:t.signalingState}),e.peerConnectionDelegate={oniceconnectionstatechange:()=>{this.handleIceConnectionStateChange()},onconnectionstatechange:()=>{this.logInfo("connectionState:",t.connectionState),"failed"===t.connectionState&&"stable"!==t.signalingState&&this.logWarn("PeerConnection failed while signaling is busy",{signalingState:t.signalingState,iceConnectionState:t.iceConnectionState})},onicegatheringstatechange:()=>{this.logDebug("iceGatheringState:",t.iceGatheringState)},onsignalingstatechange:()=>{this.logInfo("signalingState:",t.signalingState),"stable"===t.signalingState&&(this.signalingBusyCount=0,"waiting-signaling"!==this.state||this.signalingBusyTimer||(this.state="idle",this.recover("signaling-became-stable"))),"closed"===t.signalingState&&this.destroy()},onicecandidate:e=>{e.candidate?this.logDebug("ICE candidate:",{type:e.candidate.type,protocol:e.candidate.protocol,address:e.candidate.address,port:e.candidate.port}):this.logDebug("ICE candidate gathering complete")}}):this.logWarn("SessionDescriptionHandler / PeerConnection unavailable")}handleIceConnectionStateChange(){if(this.destroyed||this.hardFailed)return;const e=this.getPeerConnection();if(!e)return;const t=e.iceConnectionState;switch(this.logInfo("iceConnectionState:",t,"recoveryState:",this.state),t){case"new":break;case"checking":this.clearDisconnectedTimer(),"sending-reinvite"!==this.state&&"waiting-ice"!==this.state||(this.state="waiting-ice");break;case"connected":case"completed":this.handleIceRecovered();break;case"disconnected":this.handleIceDisconnected();break;case"failed":this.clearDisconnectedTimer(),this.recover("ice-failed");break;case"closed":this.destroy()}}handleIceDisconnected(){this.destroyed||this.hardFailed||"sending-reinvite"!==this.state&&"waiting-ice"!==this.state&&(this.disconnectedTimer||(this.state="waiting-disconnected",this.logInfo(`ICE disconnected, wait ${this.options.disconnectedTimeoutMs}ms`),this.disconnectedTimer=setTimeout(()=>{if(this.disconnectedTimer=void 0,this.destroyed||this.hardFailed)return;const e=this.getPeerConnection();if(e){if("disconnected"===e.iceConnectionState)return this.state="idle",void this.recover("ice-disconnected-timeout");this.logInfo("ICE self recovered:",e.iceConnectionState),this.state="idle"}},this.options.disconnectedTimeoutMs)))}handleIceRecovered(){var e,t;if(this.destroyed||this.hardFailed)return;const i="idle"!==this.state||this.retryCount>0;!i||"sending-reinvite"!==this.state&&"waiting-ice"!==this.state||this.acceptedRecoveryGeneration===this.recoveryGeneration?(this.clearDisconnectedTimer(),this.clearRetryTimer(),this.clearSignalingBusyTimer(),this.clearNegotiationTimer(),this.clearIceRecoveryTimer(),this.clearTransportRecoveryTimer(),this.clearRegistrationRecoveryTimer(),this.transportWaitStartedAt=void 0,this.pendingTransportRecoveryReason=void 0,this.registrationWaitStartedAt=void 0,this.pendingRegistrationRecoveryReason=void 0,this.state="idle",this.retryCount=0,this.signalingBusyCount=0,this.acceptedRecoveryGeneration=void 0,this.recoveryReason="",this.reinviteReason="unknown",this.lastRtpProgressAt=Date.now(),this.lastRtpSnapshot=void 0,this.logInfo("ICE healthy"),i&&(this.logInfo("ICE recovery succeeded"),null===(t=(e=this.options).onRecovered)||void 0===t||t.call(e))):this.logInfo("ICE healthy, waiting for re-INVITE acceptance")}getIceCandidates(){return r(this,void 0,void 0,function*(){const e=this.getPeerConnection();if(!e)return;const t=yield e.getStats(),i=[],r=[];return t.forEach(e=>{if("local-candidate"!==e.type&&"remote-candidate"!==e.type)return;const t={address:e.address,port:e.port,protocol:e.protocol,candidateType:e.candidateType};"local-candidate"===e.type?i.push(t):r.push(t)}),{localCandidates:i,remoteCandidates:r,iceGatheringState:e.iceGatheringState,iceConnectionState:e.iceConnectionState}})}recover(t){var i,s,n,o,a;return r(this,void 0,void 0,function*(){if(this.destroyed||this.hardFailed)return;if(this.session.state!==e.SessionState.Established)return void this.logWarn("skip recovery: session not established",this.session.state);if("undefined"!=typeof navigator&&!1===navigator.onLine)return this.logWarn("skip recovery: browser offline"),void(this.state="idle");if(!this.isTransportAvailable())return void this.waitForTransport(t);if(!this.isRegistrationAvailable())return void this.waitForRegistration(t);if("sending-reinvite"===this.state||"waiting-ice"===this.state)return void this.logDebug("skip recovery: recovery already running");const c=this.getPeerConnection();if(!c)return;if("stable"!==c.signalingState)return this.logWarn("skip recovery: signalingState not stable",c.signalingState),this.state="waiting-signaling",void this.scheduleSignalingBusyRetry(`signaling-busy:${c.signalingState}`);if(this.signalingBusyCount=0,this.clearSignalingBusyTimer(),this.retryCount>=this.options.maxRetries)return void this.failRecovery(`${t}:max-retries`);this.clearDisconnectedTimer(),this.clearRetryTimer(),this.retryCount++;const l=++this.recoveryGeneration;this.state="sending-reinvite";const h=this.readIceCredentials(null===(i=c.localDescription)||void 0===i?void 0:i.sdp);this.recoveryReason||(this.reinviteReason=this.resolveReinviteReason(t),this.recoveryReason=this.normalizeRecoveryReason(t,this.reinviteReason)),this.acceptedRecoveryGeneration=void 0,this.logInfo(`ICE recovery #${this.retryCount}`,{recoveryReason:this.recoveryReason,reinviteReason:this.reinviteReason}),null===(n=(s=this.options).onRecoveryStart)||void 0===n||n.call(s,this.recoveryReason,this.retryCount),this.startNegotiationTimeout(l,t);try{const e={offerOptions:{iceRestart:!0},iceGatheringTimeout:this.options.iceGatheringTimeoutMs,finalModifiers:this.options.includeRecoveryReasonInSdp?[this.permanentRecoverySdpModifier]:[]};this.session.sessionDescriptionHandlerOptionsReInvite=e,this.session.sessionDescriptionHandlerModifiersReInvite=[],this.logDebug("re-INVITE Final SDP configured",{recoveryReason:this.recoveryReason,reinviteReason:this.reinviteReason,includeRecoveryReasonInSdp:this.options.includeRecoveryReasonInSdp,finalModifierCount:null!==(a=null===(o=e.finalModifiers)||void 0===o?void 0:o.length)&&void 0!==a?a:0});const i=Date.now();yield this.session.invite({requestDelegate:{onTrying:()=>{this.isCurrentGeneration(l)&&this.logDebug("ICE re-INVITE trying")},onProgress:e=>{this.isCurrentGeneration(l)&&this.logDebug("ICE re-INVITE progress:",e.message.statusCode)},onAccept:()=>r(this,void 0,void 0,function*(){var e,r,s;if(!this.isCurrentGeneration(l))return;if(this.logInfo("ICE re-INVITE accepted"),this.userAgentManager.armsReportFlag)try{const t=Date.now();null===(r=null===(e=Ku.getAliArms())||void 0===e?void 0:e.getInstance())||void 0===r||r.api({api:`softphone-sdk-re-invite-${this.userAgentManager.appKey}-${this.userAgentManager.agentExtension}`,msg:JSON.stringify(Object.assign(Object.assign({businessAttribute:Object.keys(this.userAgentManager.businessAttribute).length?this.userAgentManager.businessAttribute:void 0,appKey:this.userAgentManager.appKey||void 0,agentId:this.userAgentManager.agentId||void 0,agentTag:this.userAgentManager.agentTag||void 0,agentExtension:this.userAgentManager.agentExtension||void 0,recoveryReason:this.recoveryReason||void 0,reinviteReason:this.reinviteReason||void 0},(yield this.getIceCandidates())||{}),{bjDate:Jt(),timestamp:Date.now()})),traceId:this.userAgentManager.businessAttribute.callId||this.userAgentManager.businessAttribute.cid,code:200,success:!0,time:t-i,begin:i})}catch(e){}this.clearNegotiationTimer(),this.acceptedRecoveryGeneration=l;const n=this.getPeerConnection();if(n&&"stable"!==n.signalingState&&this.logWarn("re-INVITE accepted but signalingState is not stable",n.signalingState),this.state="waiting-ice",this.options.debugIceCredentials){const e=this.readIceCredentials(null===(s=null==n?void 0:n.localDescription)||void 0===s?void 0:s.sdp);this.logInfo("ICE credentials:",{old:h,new:e,changed:this.hasIceCredentialsChanged(h,e)})}this.startIceRecoveryTimeout(l,t)}),onReject:e=>r(this,void 0,void 0,function*(){var r,s;if(this.userAgentManager.armsReportFlag)try{const t=Date.now();null===(s=null===(r=Ku.getAliArms())||void 0===r?void 0:r.getInstance())||void 0===s||s.api({api:`softphone-sdk-re-invite-${this.userAgentManager.appKey}-${this.userAgentManager.agentExtension}`,msg:JSON.stringify(Object.assign(Object.assign({businessAttribute:Object.keys(this.userAgentManager.businessAttribute).length?this.userAgentManager.businessAttribute:void 0,appKey:this.userAgentManager.appKey||void 0,agentId:this.userAgentManager.agentId||void 0,agentTag:this.userAgentManager.agentTag||void 0,agentExtension:this.userAgentManager.agentExtension||void 0,recoveryReason:this.recoveryReason||void 0,reinviteReason:this.reinviteReason||void 0},(yield this.getIceCandidates())||{}),{bjDate:Jt(),reasonPhrase:e.message.reasonPhrase||void 0,timestamp:Date.now()})),traceId:this.userAgentManager.businessAttribute.callId||this.userAgentManager.businessAttribute.cid,code:e.message.statusCode,success:!1,time:t-i,begin:i})}catch(e){}this.handleReinviteRejected(l,t,e.message.statusCode,e.message.reasonPhrase)})}})}catch(e){if(!this.isCurrentGeneration(l))return;this.clearNegotiationTimer(),this.clearIceRecoveryTimer(),this.logWarn("ICE re-INVITE error:",e);const i=yield this.rollbackLocalOffer("invite-exception");if(!this.isCurrentGeneration(l))return;if(!i)return void this.failRecovery(`${t}:rollback-failed:exception`);if(this.state="idle",this.signalingBusyCount=0,!this.isTransportAvailable())return void this.waitForTransport(`${t}:invite-exception`);if(this.isRequestPendingError(e))return void this.scheduleRetry(`${t}:request-pending`,1500);this.scheduleRetry(`${t}:exception`)}})}rollbackLocalOffer(e){return r(this,void 0,void 0,function*(){const t=this.getPeerConnection();if(!t)return!1;if("stable"===t.signalingState)return!0;if("have-local-offer"!==t.signalingState)return this.logWarn("cannot rollback current signaling state",{reason:e,signalingState:t.signalingState}),!1;try{this.logWarn("rollback local offer",{reason:e,signalingState:t.signalingState}),yield t.setLocalDescription({type:"rollback"});const i=t.signalingState,r="stable"===i;return this.logInfo("local offer rollback result",{success:r,signalingState:i}),r}catch(i){return this.logError("local offer rollback failed",{reason:e,error:i,signalingState:t.signalingState}),!1}})}normalizeRecoveryReason(e,t){return e.toLowerCase().includes("transport-restored")?`transport-restored:${t}`:"unknown"!==t?t:"unknown"}resolveReinviteReason(e){const t=e.toLowerCase();return t.includes("rtp-stalled")?"rtp-stalled":t.includes("ice-failed")?"ice-failed":t.includes("ice-disconnected")||t.includes("disconnected-timeout")?"ice-disconnected":t.includes("network-changed")?"network-changed":t.includes("transport-restored")?"transport-restored":t.includes("manual")?"manual":"unknown"}sanitizeSdpReason(e,t=256){return e.replace(/[\r\n]/g,"").replace(/[^a-zA-Z0-9._:-]/g,"_").slice(0,t)}sanitizeSdpAttributeName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"").slice(0,64)||"x-reinvite-reason"}applyRecoveryReasonToSdp(e){return r(this,void 0,void 0,function*(){if(!e.sdp||!this.options.includeRecoveryReasonInSdp)return e;const t=this.sanitizeSdpAttributeName(this.options.recoveryReasonSdpAttribute),i=this.sanitizeSdpAttributeName(this.options.reinviteReasonSdpAttribute),r=this.sanitizeSdpReason(this.recoveryReason||"unknown"),s=this.sanitizeSdpReason(this.reinviteReason||"unknown",64),n=e.sdp.split(/\r?\n/).filter(e=>!e.startsWith(`a=${t}:`)&&!e.startsWith(`a=${i}:`));for(;n.length>0&&""===n[n.length-1];)n.pop();const o=n.findIndex(e=>e.startsWith("m=")),a=o>=0?o:n.length;n.splice(a,0,`a=${t}:${r}`,`a=${i}:${s}`);const c=`${n.join("\r\n")}\r\n`,l=c.includes(`a=${t}:${r}`),h=c.includes(`a=${i}:${s}`);return this.logInfo("SDP modifier RESULT",{recoveryReason:r,reinviteReason:s,containsRecoveryReason:l,containsReinviteReason:h,insertedBeforeFirstMedia:o>=0}),this.logDebug("SDP custom reason lines",{recoveryLine:`a=${t}:${r}`,reinviteLine:`a=${i}:${s}`}),Object.assign(Object.assign({},e),{sdp:c})})}createRecoveryReasonSdpModifier(e,t){return i=>r(this,void 0,void 0,function*(){return this.recoveryReason=e,this.reinviteReason=t,this.applyRecoveryReasonToSdp(i)})}handleReinviteRejected(e,t,i,s){return r(this,void 0,void 0,function*(){if(!this.isCurrentGeneration(e))return;this.clearNegotiationTimer(),this.clearIceRecoveryTimer(),this.logWarn("ICE re-INVITE rejected:",i,s);const r=yield this.rollbackLocalOffer(`sip-${i}`);this.isCurrentGeneration(e)&&(r?(this.state="idle",this.signalingBusyCount=0,481!==i?this.isTransportAvailable()?491!==i?503!==i?this.scheduleRetry(`${t}:sip-${i}`):this.scheduleRetry(`${t}:sip-503`,3e3):this.scheduleRetry(`${t}:sip-491`,1500):this.waitForTransport(`${t}:sip-${i}`):this.failRecovery(`${t}:sip-481`)):this.failRecovery(`${t}:rollback-failed:sip-${i}`))})}startNegotiationTimeout(e,t){this.clearNegotiationTimer(),this.negotiationTimer=setTimeout(()=>{if(this.negotiationTimer=void 0,!this.isCurrentGeneration(e))return;const i=this.getPeerConnection();this.logError("re-INVITE negotiation timeout",{reason:t,signalingState:null==i?void 0:i.signalingState,iceConnectionState:null==i?void 0:i.iceConnectionState,connectionState:null==i?void 0:i.connectionState}),this.failRecovery(`${t}:negotiation-timeout`)},this.options.negotiationTimeoutMs)}startIceRecoveryTimeout(e,t){this.clearIceRecoveryTimer(),this.iceRecoveryTimer=setTimeout(()=>{if(this.iceRecoveryTimer=void 0,!this.isCurrentGeneration(e))return;const i=this.getPeerConnection();i&&("connected"!==i.iceConnectionState&&"completed"!==i.iceConnectionState?(this.logWarn("ICE recovery timeout",{reason:t,iceConnectionState:i.iceConnectionState,connectionState:i.connectionState,signalingState:i.signalingState}),this.state="idle","stable"===i.signalingState?this.scheduleRetry(`${t}:ice-timeout`):this.scheduleSignalingBusyRetry(`ice-timeout:${i.signalingState}`)):this.handleIceRecovered())},this.options.iceRecoveryTimeoutMs)}scheduleRetry(e,t=0){if(this.destroyed||this.hardFailed)return;if(this.retryCount>=this.options.maxRetries)return void this.failRecovery(`${e}:max-retries`);if(this.retryTimer)return;this.state="waiting-retry";const i=this.options.retryBaseDelayMs*Math.pow(2,Math.max(0,this.retryCount-1)),r=Math.min(i,this.options.retryMaxDelayMs),s=Math.floor(500*Math.random()),n=Math.max(r+s,t);this.logInfo(`schedule ICE retry in ${n}ms`,e),this.retryTimer=setTimeout(()=>{if(this.retryTimer=void 0,this.destroyed||this.hardFailed)return;if(!this.isTransportAvailable())return void this.waitForTransport(this.recoveryReason||e);const t=this.getPeerConnection();if(t)if("connected"!==t.iceConnectionState&&"completed"!==t.iceConnectionState){if("stable"!==t.signalingState)return this.state="waiting-signaling",void this.scheduleSignalingBusyRetry(`retry-signaling-busy:${t.signalingState}`);this.state="idle",this.recover(this.recoveryReason||e)}else this.handleIceRecovered()},n)}scheduleSignalingBusyRetry(t){var i;if(this.destroyed||this.hardFailed)return;if(!this.isTransportAvailable())return void this.waitForTransport(t);if(this.signalingBusyTimer)return;this.signalingBusyCount++;const r=this.getPeerConnection();if(this.logWarn("signalingState still busy",{reason:t,signalingState:null==r?void 0:r.signalingState,count:this.signalingBusyCount,max:this.options.maxSignalingBusyRetries}),this.signalingBusyCount>this.options.maxSignalingBusyRetries)return void this.failRecovery(`signaling-stuck:${null!==(i=null==r?void 0:r.signalingState)&&void 0!==i?i:"unknown"}`);this.state="waiting-signaling";const s=Math.floor(500*Math.random()),n=this.options.signalingBusyRetryDelayMs+s;this.logInfo(`schedule signaling retry in ${n}ms`),this.signalingBusyTimer=setTimeout(()=>{if(this.signalingBusyTimer=void 0,this.destroyed||this.hardFailed)return;if(this.session.state!==e.SessionState.Established)return;if(!this.isTransportAvailable())return void this.waitForTransport("signaling-unavailable");const t=this.getPeerConnection();return t?"stable"===t.signalingState?(this.signalingBusyCount=0,this.state="idle","connected"===t.iceConnectionState||"completed"===t.iceConnectionState?void this.handleIceRecovered():void this.recover("signaling-recovered")):void this.scheduleSignalingBusyRetry(`signaling-busy:${t.signalingState}`):void 0},n)}isTransportAvailable(){const e=this.options.isSignalingAvailable;if(!e)return!0;try{return e()}catch(e){return this.logWarn("isSignalingAvailable() threw",e),!1}}isRegistrationAvailable(){const e=this.options.isRegistrationAvailable;if(!e)return!0;try{return e()}catch(e){return this.logWarn("isRegistrationAvailable() threw",e),!1}}waitForRegistration(t){if(this.destroyed||this.hardFailed)return;if(!this.isTransportAvailable())return this.clearRegistrationRecoveryTimer(),this.registrationWaitStartedAt=void 0,this.pendingRegistrationRecoveryReason=void 0,void this.waitForTransport(t);if(this.isRegistrationAvailable()){const e=void 0===this.registrationWaitStartedAt?0:Date.now()-this.registrationWaitStartedAt;return this.clearRegistrationRecoveryTimer(),this.registrationWaitStartedAt=void 0,this.pendingRegistrationRecoveryReason=void 0,this.state="idle",this.logInfo("SIP registration recovered",{waitedMs:e,reason:t}),void this.resumeAfterRegistrationRecovery(t)}if(this.state="waiting-registration",this.pendingRegistrationRecoveryReason=t,void 0===this.registrationWaitStartedAt&&(this.registrationWaitStartedAt=Date.now(),this.logWarn("SIP registration unavailable; pause ICE restart",{reason:t,timeoutMs:this.options.registrationRecoveryTimeoutMs})),this.registrationRecoveryTimer)return;Date.now()-this.registrationWaitStartedAt>=this.options.registrationRecoveryTimeoutMs?this.failRecovery(`registration-recovery-timeout:${t}`):this.registrationRecoveryTimer=setTimeout(()=>{var i;this.registrationRecoveryTimer=void 0,this.destroyed||this.hardFailed||this.session.state===e.SessionState.Established&&this.waitForRegistration(null!==(i=this.pendingRegistrationRecoveryReason)&&void 0!==i?i:t)},this.options.registrationRecoveryPollMs)}resumeAfterRegistrationRecovery(t){return r(this,void 0,void 0,function*(){if(this.destroyed||this.hardFailed||this.session.state!==e.SessionState.Established)return;if(!this.isTransportAvailable())return void this.waitForTransport(t);if(!this.isRegistrationAvailable())return void this.waitForRegistration(t);const i=this.getPeerConnection();if(i)if("connected"!==i.iceConnectionState&&"completed"!==i.iceConnectionState){if("stable"!==i.signalingState)return this.state="waiting-signaling",void this.scheduleSignalingBusyRetry(`registration-restored:${i.signalingState}`);this.state="idle",yield this.recover(`registration-restored:${t}`)}else this.handleIceRecovered()})}waitForTransport(t){if(this.destroyed||this.hardFailed)return;if(this.isTransportAvailable())return this.transportWaitStartedAt=void 0,this.pendingTransportRecoveryReason=void 0,this.clearTransportRecoveryTimer(),this.state="idle",void this.resumeAfterTransportRecovery(t);if(this.state="waiting-transport",void 0===this.transportWaitStartedAt&&(this.transportWaitStartedAt=Date.now(),this.logWarn("SIP Transport unavailable; pause ICE restart",{reason:t,timeoutMs:this.options.transportRecoveryTimeoutMs})),this.pendingTransportRecoveryReason=t,this.transportRecoveryTimer)return;Date.now()-this.transportWaitStartedAt>=this.options.transportRecoveryTimeoutMs?this.failRecovery(`transport-recovery-timeout:${t}`):this.transportRecoveryTimer=setTimeout(()=>{var i,r;if(this.transportRecoveryTimer=void 0,this.destroyed||this.hardFailed)return;if(this.session.state!==e.SessionState.Established)return;if(!this.isTransportAvailable())return void this.waitForTransport(null!==(i=this.pendingTransportRecoveryReason)&&void 0!==i?i:t);const s=null!==(r=this.pendingTransportRecoveryReason)&&void 0!==r?r:t,n=void 0===this.transportWaitStartedAt?0:Date.now()-this.transportWaitStartedAt;this.transportWaitStartedAt=void 0,this.pendingTransportRecoveryReason=void 0,this.logInfo("SIP Transport recovered",{waitedMs:n,reason:s}),this.state="idle",this.resumeAfterTransportRecovery(s)},this.options.transportRecoveryPollMs)}resumeAfterTransportRecovery(t){return r(this,void 0,void 0,function*(){if(this.destroyed||this.hardFailed||this.session.state!==e.SessionState.Established)return;if(!this.isTransportAvailable())return void this.waitForTransport(t);if(!this.isRegistrationAvailable())return void this.waitForRegistration(t);const i=this.getPeerConnection();if(i)if("connected"!==i.iceConnectionState&&"completed"!==i.iceConnectionState){if("stable"!==i.signalingState)return this.state="waiting-signaling",void this.scheduleSignalingBusyRetry(`transport-restored:${i.signalingState}`);this.state="idle",yield this.recover(`transport-restored:${t}`)}else this.handleIceRecovered()})}failRecovery(e){var t,i,r,s,n;this.destroyed||this.hardFailed||(this.hardFailed=!0,this.recoveryGeneration++,this.state="failed",this.clearDisconnectedTimer(),this.clearRetryTimer(),this.clearSignalingBusyTimer(),this.clearNegotiationTimer(),this.clearIceRecoveryTimer(),this.clearTransportRecoveryTimer(),this.clearRegistrationRecoveryTimer(),this.transportWaitStartedAt=void 0,this.pendingTransportRecoveryReason=void 0,this.registrationWaitStartedAt=void 0,this.pendingRegistrationRecoveryReason=void 0,this.stopRtpWatchdog(),this.logError("ICE recovery unrecoverable",{reason:e,retryCount:this.retryCount,signalingBusyCount:this.signalingBusyCount,iceConnectionState:null===(t=this.getPeerConnection())||void 0===t?void 0:t.iceConnectionState,connectionState:null===(i=this.getPeerConnection())||void 0===i?void 0:i.connectionState,signalingState:null===(r=this.getPeerConnection())||void 0===r?void 0:r.signalingState}),null===(n=(s=this.options).onRecoveryFailed)||void 0===n||n.call(s,e,this.retryCount))}startRtpWatchdog(){this.rtpStatsTimer||this.destroyed||this.hardFailed||(this.lastRtpProgressAt=Date.now(),this.rtpStatsTimer=setInterval(()=>{this.checkRtpHealth()},this.options.rtpStatsIntervalMs))}stopRtpWatchdog(){this.rtpStatsTimer&&(clearInterval(this.rtpStatsTimer),this.rtpStatsTimer=void 0)}checkRtpHealth(){return r(this,void 0,void 0,function*(){if(this.destroyed||this.hardFailed||this.session.state!==e.SessionState.Established)return;const t=this.getPeerConnection();if(!t)return;if("connected"!==t.iceConnectionState&&"completed"!==t.iceConnectionState)return;if("sending-reinvite"===this.state||"waiting-ice"===this.state||"waiting-signaling"===this.state||"waiting-transport"===this.state)return;let i;try{i=yield this.readRtpSnapshot(t)}catch(e){return void this.logDebug("getStats failed:",e)}if(!i.hasAudio&&!i.hasVideo)return;const r=this.lastRtpSnapshot;if(this.lastRtpSnapshot=i,!r)return void(this.lastRtpProgressAt=Date.now());const s=i.audioBytes>r.audioBytes||i.audioPackets>r.audioPackets,n=i.videoBytes>r.videoBytes||i.videoPackets>r.videoPackets||i.videoFramesDecoded>r.videoFramesDecoded;if(s||n)return void(this.lastRtpProgressAt=Date.now());const o=Date.now()-this.lastRtpProgressAt;if(o<this.options.rtpStallTimeoutMs)return;const a=Date.now();a-this.lastRtpRecoveryAt<this.options.rtpRecoveryCooldownMs||(this.logWarn(`RTP stalled for ${o}ms`,{ice:t.iceConnectionState,connection:t.connectionState,signaling:t.signalingState,audioBytes:i.audioBytes,audioPackets:i.audioPackets,videoBytes:i.videoBytes,videoPackets:i.videoPackets,videoFramesDecoded:i.videoFramesDecoded}),this.options.recoverOnRtpStallWhenIceConnected&&(this.lastRtpRecoveryAt=a,this.recover("rtp-stalled")))})}readRtpSnapshot(e){return r(this,void 0,void 0,function*(){const t=yield e.getStats(),i={timestamp:Date.now(),audioBytes:0,audioPackets:0,videoBytes:0,videoPackets:0,videoFramesDecoded:0,hasAudio:!1,hasVideo:!1};return t.forEach(e=>{var t;if("inbound-rtp"!==e.type)return;if(!0===e.isRemote)return;const r=null!==(t=e.kind)&&void 0!==t?t:e.mediaType;"audio"===r&&(i.hasAudio=!0,"number"==typeof e.bytesReceived&&(i.audioBytes+=e.bytesReceived),"number"==typeof e.packetsReceived&&(i.audioPackets+=e.packetsReceived)),"video"===r&&(i.hasVideo=!0,"number"==typeof e.bytesReceived&&(i.videoBytes+=e.bytesReceived),"number"==typeof e.packetsReceived&&(i.videoPackets+=e.packetsReceived),"number"==typeof e.framesDecoded&&(i.videoFramesDecoded+=e.framesDecoded))}),i})}getSessionDescriptionHandler(){return this.session.sessionDescriptionHandler}getPeerConnection(){var e;return null===(e=this.getSessionDescriptionHandler())||void 0===e?void 0:e.peerConnection}readIceCredentials(e){var t,i,r,s;return e?{ufrag:null===(i=null===(t=e.match(/^a=ice-ufrag:(.+)$/m))||void 0===t?void 0:t[1])||void 0===i?void 0:i.trim(),pwd:null===(s=null===(r=e.match(/^a=ice-pwd:(.+)$/m))||void 0===r?void 0:r[1])||void 0===s?void 0:s.trim()}:{}}hasIceCredentialsChanged(e,t){return e.ufrag!==t.ufrag||e.pwd!==t.pwd}isRequestPendingError(e){return e instanceof Error&&("RequestPendingError"===e.name||/request.*pending/i.test(e.message))}isCurrentGeneration(e){return!this.destroyed&&!this.hardFailed&&e===this.recoveryGeneration}clearDisconnectedTimer(){this.disconnectedTimer&&(clearTimeout(this.disconnectedTimer),this.disconnectedTimer=void 0)}clearRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0)}clearSignalingBusyTimer(){this.signalingBusyTimer&&(clearTimeout(this.signalingBusyTimer),this.signalingBusyTimer=void 0)}clearNegotiationTimer(){this.negotiationTimer&&(clearTimeout(this.negotiationTimer),this.negotiationTimer=void 0)}clearIceRecoveryTimer(){this.iceRecoveryTimer&&(clearTimeout(this.iceRecoveryTimer),this.iceRecoveryTimer=void 0)}clearTransportRecoveryTimer(){this.transportRecoveryTimer&&(clearTimeout(this.transportRecoveryTimer),this.transportRecoveryTimer=void 0)}clearRegistrationRecoveryTimer(){this.registrationRecoveryTimer&&(clearTimeout(this.registrationRecoveryTimer),this.registrationRecoveryTimer=void 0)}clearAllTimers(){this.clearDisconnectedTimer(),this.clearRetryTimer(),this.clearSignalingBusyTimer(),this.clearNegotiationTimer(),this.clearIceRecoveryTimer(),this.stopRtpWatchdog(),this.onlineTimer&&(clearTimeout(this.onlineTimer),this.onlineTimer=void 0)}logDebug(...e){var t,i;null===(i=(t=this.options.logger).debug)||void 0===i||i.call(t,"[SipIceRecovery]",...e)}logInfo(...e){var t,i;null===(i=(t=this.options.logger).info)||void 0===i||i.call(t,"[SipIceRecovery]",...e)}logWarn(...e){var t,i;null===(i=(t=this.options.logger).warn)||void 0===i||i.call(t,"[SipIceRecovery]",...e)}logError(...e){var t,i;null===(i=(t=this.options.logger).error)||void 0===i||i.call(t,"[SipIceRecovery]",...e)}}class Yu{constructor(e,t=200){Object.defineProperty(this,"onAggregateCallback",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"debounceTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingCalls",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.onAggregateCallback=e,this.debounceTime=t,this.pendingCalls=new Map}receive(e){return r(this,void 0,void 0,function*(){const{CALLID:t,ENTRY:i}=e;if(this.pendingCalls.has(t)){const e=this.pendingCalls.get(t);clearTimeout(e.timer),e.data.ENTRY.push(i),e.count+=1,e.timer=setTimeout(()=>this._flush(t),this.debounceTime)}else{const r=JSON.parse(JSON.stringify(e));r.ENTRY=[i];const s=setTimeout(()=>this._flush(t),this.debounceTime);this.pendingCalls.set(t,{timer:s,data:r,count:1})}})}_flush(e){return r(this,void 0,void 0,function*(){if(this.pendingCalls.has(e)){const{data:t}=this.pendingCalls.get(e);this.pendingCalls.delete(e),yield this.onAggregateCallback(t)}})}}class Ju{get armsReportFlag(){return s(this,Lh,"f")}get volumeValue(){return s(this,_h,"f")}getToken(e={}){return r(this,void 0,void 0,function*(){const{appKey:t,appSecret:i,agentId:r,agentTag:o}=e||{};let a=r||s(this,$d,"f"),c=o||s(this,Cd,"f"),l=i||s(this,Id,"f"),h=t||s(this,Ed,"f");if(!a&&c&&l&&h){const e=yield this.getAgentInfo({agentTag:c,appSecret:l,appKey:h});if(200!=e.code)throw new Error(e.message);n(this,$d,a=e.data.agentId,"f")}const{token:d}=yield this.getGatewayAccessToken({corpId:h,secret:l,sid:a,seatOnline:!1});return d})}armsReport(e){var t,i;const{api:r,traceId:n,code:o,success:a,begin:c,time:l,businessInfo:h}=e;"softphone-sdk-hangup"!==e.api&&"softphone-sdk-seats-status-change"!==e.api&&"softphone-sdk-accept"!==e.api&&"softphone-sdk-connect"!==e.api&&"softphone-sdk-send-star-dtmf"!==e.api&&"softphone-sdk-ignore"!==e.api&&"softphone-sdk-manual-call"!==e.api||null===(i=null===(t=Ku.getAliArms())||void 0===t?void 0:t.getInstance())||void 0===i||i.api({api:`${r}-${s(this,Ed,"f")}-${s(this,Oh,"f").authorizationUsername}`,msg:JSON.stringify({appKey:s(this,Ed,"f")||void 0,agentId:s(this,$d,"f")||void 0,agentTag:s(this,Cd,"f")||void 0,agentExtension:s(this,Oh,"f").authorizationUsername||void 0,businessAttribute:Object.keys(s(this,Wd,"f")).length?s(this,Wd,"f"):void 0,businessInfo:Object.keys(h||{}).length?h:void 0,bjDate:Jt(),timestamp:Date.now()}),traceId:n,code:o,success:a,time:l,begin:c})}get appKey(){return s(this,Ed,"f")}get agentTag(){return s(this,Cd,"f")}get agentExtension(){return s(this,Oh,"f").authorizationUsername}get agentId(){return s(this,$d,"f")}get businessAttribute(){return s(this,Wd,"f")}getFastOutboundCall(){return s(this,Wd,"f").voiceType===ti.LABOUR}getSitOutboundCall(){return s(this,Wd,"f").voiceType===ti.AI}constructor(o={}){if(wh.add(this),Sh.set(this,void 0),Th.set(this,void 0),Rh.set(this,void 0),Eh.set(this,void 0),Ih.set(this,void 0),Ch.set(this,void 0),Ph.set(this,[]),Ah.set(this,[]),Oh.set(this,{}),kh.set(this,void 0),Dh.set(this,void 0),$h.set(this,new MediaStream),jh.set(this,JSON.parse(JSON.stringify(Xt))),_h.set(this,0),Hh.set(this,void 0),Mh.set(this,void 0),xh.set(this,void 0),Object.defineProperty(this,"token",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),qh.set(this,void 0),Nh.set(this,48e4),Fh.set(this,12e6),Uh.set(this,{}),Lh.set(this,!1),Bh.set(this,void 0),Wh.set(this,void 0),Gh.set(this,void 0),Vh.set(this,e=>{}),Kh.set(this,e=>{}),zh.set(this,e=>{}),Yh.set(this,e=>{}),Jh.set(this,e=>r(this,void 0,void 0,function*(){if(s(this,Hh,"f")&&s(this,Mh,"f")&&Date.now()-s(this,Mh,"f")>e){const{sign:e,timestamp:t}=(yield s(this,Xh,"f").call(this))||{};n(this,Hh,null!=e?e:s(this,Hh,"f"),"f"),n(this,Mh,null!=t?t:s(this,Mh,"f"),"f")}})),Zh.set(this,e=>r(this,void 0,void 0,function*(){if(s(this,qh,"f")&&Date.now()-s(this,qh,"f")>e)if(s(this,xh,"f")){const{token:e,tokenTimestamp:t}=yield s(this,td,"f").call(this);n(this,xh,null!=e?e:s(this,xh,"f"),"f"),n(this,qh,null!=t?t:Date.now(),"f")}else if(this.token){const{token:e}=yield this.getGatewayAccessToken({corpId:s(this,Ed,"f"),sid:s(this,$d,"f"),secret:s(this,Id,"f"),seatOnline:!1});this.token=e,n(this,qh,Date.now(),"f")}})),Xh.set(this,()=>{}),Qh.set(this,e=>{s(this,Lh,"f")&&s(this,ed,"f").receive(e)}),ed.set(this,new Yu(e=>{var t,i;delete e.INVITE,null===(i=null===(t=Ku.getAliArms())||void 0===t?void 0:t.getInstance())||void 0===i||i.api({api:`softphone-sdk-auto-ignore-${s(this,Ed,"f")}-${s(this,Oh,"f").authorizationUsername}`,msg:JSON.stringify({errorInfo:e,businessAttribute:Object.keys(s(this,Wd,"f")).length?s(this,Wd,"f"):void 0,appKey:s(this,Ed,"f")||void 0,agentId:s(this,$d,"f")||void 0,agentTag:s(this,Cd,"f")||void 0,agentExtension:s(this,Oh,"f").authorizationUsername||void 0,bjDate:Jt(),timestamp:Date.now()}),traceId:e.CALLID,code:e.CODE,success:!0,time:0})})),td.set(this,()=>{}),id.set(this,e=>{}),rd.set(this,e=>{}),sd.set(this,void 0),nd.set(this,void 0),Object.defineProperty(this,"networkSpeed",{enumerable:!0,configurable:!0,writable:!0,value:"0.00Mb/s"}),Object.defineProperty(this,"networkDelay",{enumerable:!0,configurable:!0,writable:!0,value:"0ms"}),Object.defineProperty(this,"onLine",{enumerable:!0,configurable:!0,writable:!0,value:navigator.onLine}),Object.defineProperty(this,"testspeeding",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"goodNetworkSpeed",{enumerable:!0,configurable:!0,writable:!0,value:()=>1e3*Number(this.networkSpeed.replace("Mb/s",""))>=30}),Object.defineProperty(this,"goodNetworkDelay",{enumerable:!0,configurable:!0,writable:!0,value:()=>Number(this.networkDelay.replace("ms",""))<=500&&"0ms"!==this.networkDelay}),Object.defineProperty(this,"authorizedMicrophonePermissions",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"authorizedNotificationPermissions",{enumerable:!0,configurable:!0,writable:!0,value:!1}),od.set(this,100),ad.set(this,3),cd.set(this,8),ld.set(this,2),hd.set(this,0),dd.set(this,!1),ud.set(this,void 0),gd.set(this,3),fd.set(this,3),pd.set(this,0),vd.set(this,0),md.set(this,0),bd.set(this,!1),yd.set(this,!1),wd.set(this,!1),Sd.set(this,void 0),Td.set(this,void 0),Rd.set(this,void 0),Ed.set(this,void 0),Id.set(this,void 0),Cd.set(this,void 0),Pd.set(this,void 0),Ad.set(this,void 0),Od.set(this,void 0),kd.set(this,void 0),Dd.set(this,void 0),$d.set(this,void 0),jd.set(this,void 0),_d.set(this,void 0),Hd.set(this,void 0),Md.set(this,void 0),xd.set(this,e=>{s(this,wh,"m",Nu).call(this)}),qd.set(this,()=>{}),Nd.set(this,void 0),Fd.set(this,void 0),Ud.set(this,!1),Ld.set(this,4e3),Bd.set(this,4e3),Wd.set(this,{}),Gd.set(this,!1),Vd.set(this,!0),Object.defineProperty(this,"ifAutoAnswer",{enumerable:!0,configurable:!0,writable:!0,value:()=>String(s(this,Wd,"f").autoAnswer)===Qt.YES}),Object.defineProperty(this,"notNeedSendStarDtmf",{enumerable:!0,configurable:!0,writable:!0,value:()=>String(s(this,Wd,"f").afterTransferLabour)===ii.DIRECT_ANSWER}),Kd.set(this,()=>{if(s(this,Vd,"f")){s(this,zd,"f").call(this);const e=new(window.AudioContext||window.webkitAudioContext);n(this,Wh,e.createScriptProcessor(2048,1,1),"f"),s(this,Wh,"f").onaudioprocess=e=>{const t=e.inputBuffer.getChannelData(0);let i=0;for(let e=0;e<t.length;++e)i+=t[e]*t[e];n(this,_h,Number(Math.sqrt(i/t.length).toFixed(2)),"f"),s(this,Vh,"f").call(this,s(this,_h,"f"))},n(this,Gh,new MediaStream,"f"),this.getSenders().forEach(e=>{e.track&&s(this,Gh,"f").addTrack(e.track)}),n(this,Bh,e.createMediaStreamSource(s(this,Gh,"f")),"f"),s(this,Bh,"f").connect(s(this,Wh,"f")),s(this,Wh,"f").connect(e.destination)}}),zd.set(this,()=>{if(s(this,Vd,"f")){if(s(this,Bh,"f"))try{s(this,Bh,"f").disconnect()}catch(e){console.log(e)}if(s(this,Wh,"f"))try{s(this,Wh,"f").disconnect()}catch(e){console.log(e)}if(s(this,Gh,"f"))try{s(this,Gh,"f").getTracks().forEach(e=>{e.stop()})}catch(e){console.log(e)}}n(this,Bh,void 0,"f"),n(this,Wh,void 0,"f"),n(this,Gh,void 0,"f"),n(this,_h,0,"f"),s(this,Vh,"f").call(this,s(this,_h,"f"))}),Object.defineProperty(this,"disposeSoftphoneEnvRequirementCheck",{enumerable:!0,configurable:!0,writable:!0,value:()=>{s(this,Yd,"f").call(this),window.removeEventListener("offline",s(this,Xd,"f")),window.removeEventListener("online",s(this,Zd,"f")),window.removeEventListener("unload",this.disposeSoftphoneEnvRequirementCheck)}}),Yd.set(this,()=>{clearInterval(s(this,sd,"f")),n(this,sd,void 0,"f"),clearTimeout(s(this,nd,"f")),n(this,nd,void 0,"f"),this.testspeeding=!1}),Object.defineProperty(this,"softphoneEnvCheck",{enumerable:!0,configurable:!0,writable:!0,value:()=>r(this,void 0,void 0,function*(){this.testspeeding||(s(this,Jd,"f").call(this),this.oneRoundOfTesting())})}),Jd.set(this,()=>{window.addEventListener("offline",s(this,Xd,"f")),window.addEventListener("online",s(this,Zd,"f")),window.addEventListener("unload",this.disposeSoftphoneEnvRequirementCheck)}),Object.defineProperty(this,"oneRoundOfTesting",{enumerable:!0,configurable:!0,writable:!0,value:()=>r(this,void 0,void 0,function*(){this.testspeeding=!0,this.detectNavigatorPermissions(),this.onLine?(s(this,Qd,"f").call(this,this),n(this,nd,setTimeout(()=>{this.testspeeding=!1,this.disposeSoftphoneEnvRequirementCheck()},4e3),"f")):this.testspeeding=!1})}),Zd.set(this,()=>{this.onLine=!0,this.oneRoundOfTesting()}),Xd.set(this,()=>{this.onLine=!1,this.networkSpeed="0.00Mb/s",this.networkDelay="0ms",s(this,rd,"f").call(this,{networkSpeed:this.networkSpeed,networkDelay:this.networkDelay,authorizedMicrophonePermissions:this.authorizedMicrophonePermissions,authorizedNotificationPermissions:this.authorizedNotificationPermissions}),s(this,Yd,"f").call(this)}),Qd.set(this,e=>r(this,void 0,void 0,function*(){const t=e||this;clearInterval(s(t,sd,"f")),n(t,sd,void 0,"f");const i=()=>r(this,void 0,void 0,function*(){if(t.onLine)try{const e=yield s(t,eu,"f").call(t,"1"===s(t,Hd,"f")?"https://seat.teleai.com/favicon.png":void 0);t.networkSpeed=e.networkSpeed,t.networkDelay=e.networkDelay}catch(e){t.networkSpeed="0.00Mb/s",t.networkDelay="0ms"}else t.networkSpeed="0.00Mb/s",t.networkDelay="0ms";s(this,rd,"f").call(this,{networkSpeed:this.networkSpeed,networkDelay:this.networkDelay,authorizedMicrophonePermissions:this.authorizedMicrophonePermissions,authorizedNotificationPermissions:this.authorizedNotificationPermissions}),s(this,nd,"f")||(this.testspeeding=!1,this.disposeSoftphoneEnvRequirementCheck())});yield i(),s(this,nd,"f")&&n(t,sd,setInterval(function(){return r(this,void 0,void 0,function*(){yield i()})},1e3),"f")})),eu.set(this,(e="https://seat.94ai.com/favicon.png",t=63491,i=1)=>r(this,void 0,void 0,function*(){const r=[];for(let n=0;n<i;n++)r.push(s(this,tu,"f").call(this,e+"?d="+Date.now()+n,t));return Promise.all(r).then(e=>{let t=0,r=0;return e.forEach(e=>{t+=Number(e[0]),r+=Number(e[1])}),{networkDelay:(r/i).toFixed(2)+"ms",networkSpeed:(t/i).toFixed(2)+"Mb/s"}})})),tu.set(this,(e="https://seat.94ai.com/favicon.png?d="+Date.now(),t=63491)=>new Promise((i,r)=>{const s=document.createElement("img");s.start=window.performance.now(),s.onload=function(){const e=window.performance.now()-s.start;i([(1e3*t/(1048576*e)).toFixed(2),e])},s.onerror=function(e){r(e)},s.src=e}).catch(e=>{throw e})),Object.defineProperty(this,"openApiAjax",{enumerable:!0,configurable:!0,writable:!0,value:e=>new Promise((i,n)=>r(this,void 0,void 0,function*(){var r,o,a,c,l,h,d,u;try{const g=s(this,Ed,"f")||(null===(r=e.data)||void 0===r?void 0:r.appKey),f=s(this,Id,"f")||(null===(o=e.data)||void 0===o?void 0:o.appSecret);let p=s(this,Hh,"f")||(null===(a=e.data)||void 0===a?void 0:a.sign),v=s(this,Mh,"f")||(null===(c=e.data)||void 0===c?void 0:c.timestamp);if(null===(l=e.data)||void 0===l||delete l.appKey,null===(h=e.data)||void 0===h||delete h.appSecret,null===(d=e.data)||void 0===d||delete d.sign,null===(u=e.data)||void 0===u||delete u.timestamp,!g)throw new Error("缺少appKey");if(f)v=Date.now(),p=t.enc.Base64.stringify(t.HmacSHA1(g+v,f));else{if(!p||!v)throw new Error("缺少appSecret或sign+timestamp");yield s(this,Jh,"f").call(this,s(this,Nh,"f")),p=s(this,Hh,"f")||p,v=s(this,Mh,"f")||v}const{xhr:m,ajaxData:b,contentType:y}=Yt(i,n,e);m.setRequestHeader("appKey",g),m.setRequestHeader("timestamp",String(v)),m.setRequestHeader("sign",p),m.setRequestHeader("Content-type",y||"application/json"),yield s(this,zh,"f").call(this,m),m.send(b)}catch(e){throw n(e.message),e}}))}),Object.defineProperty(this,"requestGateway",{enumerable:!0,configurable:!0,writable:!0,value:(e,t=!0)=>this.gatewayApiAjax(Object.assign(Object.assign({},e),{url:this.getGateway()+e.url}),t)}),Object.defineProperty(this,"gatewayApiAjax",{enumerable:!0,configurable:!0,writable:!0,value:(e,t=!0)=>new Promise((i,n)=>r(this,void 0,void 0,function*(){try{const{xhr:r,ajaxData:o,contentType:a}=Yt(i,n,e);if(t){const e=yield this.getGatewayToken();r.setRequestHeader("x-token",e),r.setRequestHeader("seatsToken",e),r.setRequestHeader("x-authority-token",e)}r.setRequestHeader("x-app-code",3),r.setRequestHeader("content-type",a||"application/json"),yield s(this,Yh,"f").call(this,r),r.send(o)}catch(e){throw n(e.message),e}}))}),Object.defineProperty(this,"requestOpenApi",{enumerable:!0,configurable:!0,writable:!0,value:e=>this.openApiAjax(Object.assign(Object.assign({},e),{url:this.getOpenApi()+e.url}))}),Object.defineProperty(this,"getDeviceId",{enumerable:!0,configurable:!0,writable:!0,value:()=>r(this,void 0,void 0,function*(){if(s(this,Md,"f"))return s(this,Md,"f");const e=yield i.load(),t=yield e.get();return n(this,Md,t.visitorId,"f"),s(this,Md,"f")})}),lu.set(this,()=>r(this,void 0,void 0,function*(){var e,t;if(s(this,wh,"m",cu).call(this)&&(!s(this,Oh,"f").authorizationUsername||!s(this,Oh,"f").uri||!s(this,Oh,"f").authorizationPassword||!s(this,Oh,"f").transportOptions.server)){const i=yield this.getAgentInfo();if(200!=i.code)throw new Error(JSON.stringify(i));{const r=i.data;s(this,Oh,"f").authorizationUsername=r.agentExtension,s(this,Oh,"f").authorizationPassword=r.extensionPwd,s(this,Oh,"f").contactName||(s(this,Oh,"f").contactName=r.agentExtension),s(this,Oh,"f").uri=ot.makeURI(`sip:${r.agentExtension}@${r.wsRegisterAddress}`),s(this,Oh,"f").transportOptions.server=`${r.wsProtocol}://${r.wsRegisterAddress}`,n(this,$d,r.agentId,"f"),n(this,Cd,r.agentTag,"f"),n(this,Pd,r.agentName,"f"),n(this,Ad,r.agentAccount,"f"),n(this,Od,r.agentActive,"f"),n(this,kd,r.agentGroupIds,"f"),n(this,Dd,r.agentStatus,"f"),null===(t=null===(e=Ku.getAliArms())||void 0===e?void 0:e.getInstance())||void 0===t||t.setConfig({setUsername:()=>s(this,Ed,"f")+"-"+s(this,Oh,"f").authorizationUsername})}}})),hu.set(this,()=>r(this,void 0,void 0,function*(){s(this,Oh,"f").viaHost||(s(this,Oh,"f").viaHost=`${yield this.getDeviceId()}.sip`)})),uu.set(this,e=>{var t,i,r,n,o,a,c,l,h,d,u,g,f,p,v,m,b,y,w;s(this,Wd,"f").popWindow=null===(t=e["X-Popwindow"])||void 0===t?void 0:t[0].raw,s(this,Wd,"f").afterTransferLabour=null===(i=e["X-Aftertransferlabour"])||void 0===i?void 0:i[0].raw,s(this,Wd,"f").callId=null===(r=e["X-94callid"])||void 0===r?void 0:r[0].raw,s(this,Wd,"f").cid=null===(n=e["X-Cid"])||void 0===n?void 0:n[0].raw,s(this,Wd,"f").numberId=null===(o=e["X-Numberid"])||void 0===o?void 0:o[0].raw,s(this,Wd,"f").tag=(null===(a=e["X-Tag"])||void 0===a?void 0:a[0].raw)&&"null"!==(null===(c=e["X-Tag"])||void 0===c?void 0:c[0].raw)?e["X-Tag"][0].raw.split("-").map(e=>String.fromCharCode(e)).join(""):"",s(this,Wd,"f").numberTag=(null===(l=e["X-Numbertag"])||void 0===l?void 0:l[0].raw)&&"null"!==(null===(h=e["X-Numbertag"])||void 0===h?void 0:h[0].raw)?decodeURIComponent(e["X-Numbertag"][0].raw):"",s(this,Wd,"f").taskId=null===(d=e["X-Taskid"])||void 0===d?void 0:d[0].raw,s(this,Wd,"f").voiceType=null===(u=e["X-Voicetype"])||void 0===u?void 0:u[0].raw,s(this,Wd,"f").processTime=null===(g=e["X-Processtime"])||void 0===g?void 0:g[0].raw,s(this,Wd,"f").userPhone=null===(f=e["X-Userphone"])||void 0===f?void 0:f[0].raw,s(this,Wd,"f").autoAnswer=null===(p=e["X-94autoanswer"])||void 0===p?void 0:p[0].raw,s(this,Wd,"f").nodeTitle=null===(v=e["X-Nodetitle"])||void 0===v?void 0:v[0].raw.split("-").map(e=>String.fromCharCode(e)).join(""),s(this,Wd,"f").taskName=null===(m=e["X-Taskname"])||void 0===m?void 0:m[0].raw.split("-").map(e=>String.fromCharCode(e)).join(""),s(this,Wd,"f").templateTitle=null===(b=e["X-Templatetitle"])||void 0===b?void 0:b[0].raw.split("-").map(e=>String.fromCharCode(e)).join(""),s(this,Wd,"f").phoneNumber=(null===(y=e["X-Phonenumber"])||void 0===y?void 0:y[0].raw)||(null===(w=e.From)||void 0===w?void 0:w[0].parsed.uri.normal.user)}),Cu.set(this,t=>{switch(t){case e.SessionState.Initial:case e.SessionState.Establishing:break;case e.SessionState.Established:s(this,wh,"m",Iu).call(this);break;case e.SessionState.Terminating:case e.SessionState.Terminated:this.clearIceAutoDetection();let t=setTimeout(()=>{clearTimeout(t),t=void 0,s(this,jh,"f").incomingStatus=!1,s(this,jh,"f").answerStatus=!1},10);s(this,zd,"f").call(this);break;default:throw new Error("Unknown session state.")}}),Au.set(this,(e,t,i)=>{s(this,cd,"f")&&(n(this,dd,!1,"f"),s(this,jh,"f").reconnectStatus=!1,s(this,yd,"f")&&(n(this,yd,!1,"f"),s(this,Du,"f").call(this,e,t,i)))}),Ou.set(this,()=>r(this,void 0,void 0,function*(){if(s(this,cd,"f")){n(this,dd,!0,"f"),n(this,yd,!1,"f");try{this.getUserAgent().transport.disconnect().catch(e=>console.error(e))}catch(e){}console.log("sip transport disconnect");try{s(this,wh,"m",Pu).call(this)}catch(e){}s(this,$u,"f").call(this),s(this,wh,"m",Nu).call(this)}})),ku.set(this,()=>{if(s(this,cd,"f")){const e=s(this,Oh,"f").uri.clone(),t=s(this,Oh,"f").uri.clone(),i=s(this,Oh,"f").uri.clone();i.user=void 0,s(this,Du,"f").call(this,i,e,t)}}),Du.set(this,(e,t,i)=>{if(s(this,cd,"f")){if(s(this,yd,"f"))return;n(this,yd,!0,"f"),n(this,Td,setTimeout(()=>{s(this,wh,"m",xu).call(this);const r=this.getUserAgent().userAgentCore,o=r.makeOutgoingRequestMessage("OPTIONS",e,t,i,{});n(this,ud,r.request(o,{onAccept:()=>{console.log("sip ping ok"),n(this,hd,0,"f"),n(this,ud,void 0,"f"),s(this,Au,"f").call(this,e,t,i)},onReject:r=>{var o;n(this,ud,void 0,"f"),408===r.message.statusCode||503===r.message.statusCode?(console.log("sip ping error with code "+r.message.statusCode),s(this,ld,"f")>0&&s(this,hd,"f")>=s(this,ld,"f")?(console.log("sip maximum ping attempts reached"),s(this,Ou,"f").call(this)):(s(this,hd,"f")>0&&console.log(`sip ping retry ${s(this,hd,"f")} of ${s(this,ld,"f")} fail`),n(this,hd,(o=s(this,hd,"f"),++o),"f"),console.log(`sip ping retry ${s(this,hd,"f")} of ${s(this,ld,"f")}`),s(this,Au,"f").call(this,e,t,i))):(n(this,hd,0,"f"),s(this,Au,"f").call(this,e,t,i))}}),"f")},1e3*s(this,cd,"f")),"f")}}),$u.set(this,()=>{if(s(this,cd,"f")){if(n(this,yd,!1,"f"),n(this,dd,!1,"f"),s(this,ud,"f")){try{s(this,ud,"f").dispose()}catch(e){}n(this,ud,void 0,"f")}s(this,Td,"f")&&s(this,wh,"m",xu).call(this)}}),qu.set(this,()=>{if(s(this,gd,"f")){if(s(this,wd,"f"))return;n(this,wd,!0,"f"),s(this,jh,"f").reconnectStatus=!0,n(this,Rd,setTimeout(()=>r(this,void 0,void 0,function*(){try{s(this,wh,"m",Hu).call(this),0===s(this,pd,"f")&&console.log("sip reconnect success then register start"),yield s(this,Eh,"f").register({requestDelegate:{onAccept:e=>{console.log("sip reconnect success and register ok"),n(this,pd,0,"f"),n(this,wd,!1,"f"),s(this,jh,"f").registerStatus=!0,s(this,jh,"f").reconnectStatus=!1,s(this,ku,"f").call(this)},onReject:e=>r(this,void 0,void 0,function*(){var t;console.log("sip reconnect success but register fail with code "+e.message.statusCode),n(this,wd,!1,"f"),s(this,fd,"f")<=s(this,pd,"f")?(console.log("sip maximum register attempts reached"),n(this,pd,0,"f"),yield this.getUserAgent().transport.disconnect().catch(e=>console.error(e)),s(this,wh,"m",Nu).call(this)):(n(this,pd,(t=s(this,pd,"f"),++t),"f"),console.log(`sip reconnect success and register retry ${s(this,pd,"f")} of ${s(this,fd,"f")}`),s(this,qu,"f").call(this))})},requestOptions:{extraHeaders:s(this,Th,"f")}})}catch(e){console.log("sip reconnect then registerer register error",e),n(this,pd,0,"f"),n(this,wd,!1,"f")}}),1e3*s(this,gd,"f")),"f")}}),"object"!=typeof o)throw new Error("userAgentOption must be plain object");s(this,wh,"m",nu).call(this,o),s(this,wh,"m",ou).call(this,o),s(this,wh,"m",su).call(this,o),s(this,wh,"m",au).call(this,o),s(this,wh,"m",fu).call(this,o),s(this,wh,"m",ru).call(this,o),s(this,wh,"m",iu).call(this,o),n(this,Oh,s(this,wh,"m",vu).call(this,o),"f")}detectNavigatorPermissions(){-1===navigator.userAgent.indexOf("Firefox")?navigator.permissions.query({name:"microphone"}).then(e=>{"granted"===e.state?this.authorizedMicrophonePermissions=!0:this.authorizedMicrophonePermissions=!1}).catch(e=>{console.log("Got error :",e),this.authorizedMicrophonePermissions=!1}):navigator.mediaDevices.enumerateDevices().then(e=>{""!==e.filter(({kind:e})=>"audioinput"===e)[0].label?this.authorizedMicrophonePermissions=!0:this.authorizedMicrophonePermissions=!1}),navigator.permissions.query({name:"notifications"}).then(e=>{"granted"===e.state?this.authorizedNotificationPermissions=!0:this.authorizedNotificationPermissions=!1}).catch(e=>{console.log("Got error :",e),this.authorizedNotificationPermissions=!1})}getGateway(){return"1"===s(this,Hd,"f")?"https://gateway.teleai.com":"https://gateway.94ai.com"}getGatewayToken(){return r(this,void 0,void 0,function*(){if(yield s(this,Zh,"f").call(this,s(this,Fh,"f")),s(this,xh,"f"))return s(this,xh,"f");if(!this.token){yield s(this,lu,"f").call(this);const{token:e}=yield this.getGatewayAccessToken({corpId:s(this,Ed,"f"),sid:s(this,$d,"f"),secret:s(this,Id,"f"),seatOnline:!1});this.token=e,n(this,qh,Date.now(),"f")}return this.token})}getGatewayAccessToken(e){return this.requestGateway({url:"/authority/accessToken/openApi",data:e},!1)}getCallNumberDetail(e){return this.requestGateway({url:"/task-aggre/callCenterNumber/get",data:e})}getCallNumberChats(e){return this.requestGateway({url:"/dialogue-aggre/call-center-number/chat/list",data:e})}getCallInfo(){return r(this,void 0,void 0,function*(){const e=Object.assign({},s(this,Wd,"f")),t=()=>r(this,void 0,void 0,function*(){if(e.numberId&&e.taskId){let t={};try{if(t=yield this.getCallNumberDetail({id:e.numberId,taskId:e.taskId}),200!==t.code)return console.error(t.message),e.stop=!0,void s(this,id,"f").call(this,t.message)}catch(i){const r=`当前会话callid:${e.callId},根据numberId:${e.numberId},taskId:${e.taskId}:查询坐席接听状态异常`;return console.error(r),e.stop=!0,void s(this,id,"f").call(this,t.message)}const{callType:i,newIntentTag:r,intentTag:n,number:o,numberMd5:a,sid:c,config:l,tag:h,state:d}=t.data;if(10===d)return console.log(`当前会话callid:${e.callId}已结束`),void(e.stop=!0);if(e.callType||(e.callType=i),e.intentTag=r||n,e.number||(e.number=o),e.numberMD5||(e.numberMD5=a),e.agentId||(e.agentId=c),e.tag||(e.tag=h),!e.templateId&&l&&"string"==typeof l){const t=JSON.parse(l);t&&t.templateId&&(e.templateId=t.templateId)}if(e.callId){let t={};try{if(t=yield this.getCallNumberChats({callId:e.callId,taskId:e.taskId}),200!==t.code)return console.error(t.message),e.stop=!0,void s(this,id,"f").call(this,t.message)}catch(t){const i=`当前会话根据callId:${e.callId},taskId:${e.taskId}:查询会话对话记录异常`;return console.error(i),e.stop=!0,void s(this,id,"f").call(this,i)}e.chats=t.data.map(e=>(e.matchinfo&&(e.matchinfo=JSON.parse(e.matchinfo)),e)),s(this,Uh,"f")[e.callId]=e}try{s(this,Kh,"f").call(this,s(this,Uh,"f")[e.callId])}catch(e){console.log(e)}}else{if(e.stop=!0,!e.taskId){const t=`当前会话callid:${e.callId}的taskId不存在,无法查询通话记录`;console.error(t),s(this,id,"f").call(this,t)}if(!e.numberId){const t=`当前会话callid:${e.callId}的numberId不存在,无法查询通话记录`;console.error(t),s(this,id,"f").call(this,t)}}});try{for(;!e.stop&&(yield t(),!e.stop);)yield new Promise(e=>{let t=setTimeout(()=>r(this,void 0,void 0,function*(){clearTimeout(t),t=void 0,e(!0)}),3e3)})}catch(e){s(this,id,"f").call(this,e)}})}refreshCallChatInfo(){return r(this,void 0,void 0,function*(){s(this,Wd,"f").numberId&&s(this,Wd,"f").callId&&s(this,Wd,"f").taskId&&s(this,Gd,"f")&&(yield this.getCallInfo())})}getOpenApi(){return function(e){if(!e)return!1;const t=/^[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,}$/;return!!/^(\d{1,3}\.){3}\d{1,3}$/.test(e)||("//"===e.slice(0,2)?t.test(e.slice(2,e.length)):"http://"===e.slice(0,7)?t.test(e.slice(7,e.length)):"https://"===e.slice(0,8)?t.test(e.slice(8,e.length)):t.test(e))}(s(this,jd,"f"))?s(this,jd,"f"):"1"===s(this,Hd,"f")?"1"===s(this,_d,"f")?"https://seat.teleai.com/teleaiopenapi":"https://seat.teleai.com/openapi":"1"===s(this,_d,"f")?"https://seat.94ai.com/teleaiopenapi":"https://seat.94ai.com/openapi"}getAgentInfo(e={}){const t=e||{},{agentTag:i,agentId:r}=t,n=function(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(i[r[s]]=e[r[s]])}return i}(t,["agentTag","agentId"]);return this.requestOpenApi({url:"/v1/agent/getAgent",data:Object.assign({agentTag:i||s(this,Cd,"f"),agentId:r||s(this,$d,"f")},n)})}updateOpenApiAgentStatus(e){return this.requestOpenApi({url:"/v1/agent/updateAgentStatus",data:{agentTag:s(this,Cd,"f"),agentId:s(this,$d,"f"),agentStatus:e}})}importOpenApiAgentCustomer(e){return this.requestOpenApi({url:"/v1/task/importAgentCustomer",data:{agentTag:s(this,Cd,"f"),agentId:s(this,$d,"f"),callType:1001,customers:[{number:e}]}})}callNumber(e){return this.importOpenApiAgentCustomer(e)}toggleNap(e){return e?this.updateOpenApiAgentStatus(3):this.updateOpenApiAgentStatus(1)}refreshSign(e){n(this,Hh,e,"f")}refreshTimestamp(e){n(this,Mh,e,"f")}prepareUserAgent(e,t){var i;return r(this,void 0,void 0,function*(){const{refresh:r,registererOptions:n,registererRegisterOptions:o,extraHeaders:a,authorizationUsername:c,authorizationPassword:l,uri:h,contactName:d,transportOptions:u}=e||{};yield this.dispose(),s(this,Oh,"f").uri=null!=h?h:s(this,Oh,"f").uri,s(this,Oh,"f").authorizationUsername=null!=c?c:s(this,Oh,"f").authorizationUsername,s(this,Oh,"f").authorizationPassword=null!=l?l:s(this,Oh,"f").authorizationPassword,s(this,Oh,"f").contactName=null!==(i=null!=d?d:c)&&void 0!==i?i:s(this,Oh,"f").contactName,u&&(s(this,Oh,"f").transportOptions=Object.assign(Object.assign({},s(this,Oh,"f").transportOptions),u));try{s(this,wh,"m",ou).call(this,e),yield s(this,lu,"f").call(this),yield s(this,hu,"f").call(this),s(this,wh,"m",gu).call(this,{refresh:r}),yield s(this,wh,"m",Lu).call(this),t&&s(this,wh,"m",Uu).call(this,t);return yield s(this,wh,"m",Bu).call(this,{registererOptions:n,registererRegisterOptions:o,extraHeaders:a},s(this,Ud,"f"))}catch(e){throw yield this.dispose(),e}})}dispose(){return r(this,void 0,void 0,function*(){try{s(this,wh,"m",du).call(this),yield s(this,wh,"m",bu).call(this)}catch(e){s(this,wh,"m",wu).call(this),console.log("sip dispose with error",e)}})}ignoreInvite(e={}){return r(this,void 0,void 0,function*(){s(this,jh,"f").incomingStatus=!1,yield this.getCurrentInvitation().reject(e)})}acceptInvite(e={}){return r(this,void 0,void 0,function*(){try{yield new Promise((t,i)=>{(()=>{r(this,void 0,void 0,function*(){try{const r=null==e?void 0:e.onAck,s=null==e?void 0:e.onAckTimeout;null==e||delete e.onAck,null==e||delete e.onAckTimeout,yield this.getCurrentInvitation().accept(Object.assign({sessionDescriptionHandlerOptions:{constraints:{audio:!0,video:!1}},onAck(e){t(e),null==r||r()},onAckTimeout(){null==s||s(),i("接听响应超时")}},e||{}))}catch(e){i(e)}})})()}),s(this,jh,"f").incomingStatus&&(s(this,jh,"f").incomingStatus=!1,s(this,jh,"f").answerStatus=!0)}catch(e){throw s(this,jh,"f").incomingStatus=!1,e}})}hangUpInvite(t){return r(this,void 0,void 0,function*(){const{rejectOptions:i,byeOptions:n,extraHeaders:o,scoutResponse:a}=t||{};return new Promise((t,c)=>r(this,void 0,void 0,function*(){var r,l,h,d,u;try{const g=n||{},f=null===(r=g.requestDelegate)||void 0===r?void 0:r.onAccept,p=null===(l=g.requestDelegate)||void 0===l?void 0:l.onReject;null===(h=g.requestDelegate)||void 0===h||delete h.onAccept,null===(d=g.requestDelegate)||void 0===d||delete d.onReject;const v=s(this,wh,"m",pu).call(this,{onAccept(e){console.log("sip bye success"),t(e),null==f||f(e)},onReject(e){null==p||p(e),c("sip bye fail with code "+e.message.statusCode)}},g.requestDelegate);switch(delete g.requestDelegate,null===(u=s(this,kh,"f"))||void 0===u?void 0:u.state){case e.SessionState.Initial:case e.SessionState.Establishing:yield s(this,kh,"f").reject(Object.assign({extraHeaders:o},i||{})),t(!0);break;case e.SessionState.Established:yield s(this,kh,"f").bye(Object.assign({requestDelegate:v,requestOptions:{extraHeaders:o}},g)),a||t(!0);break;case e.SessionState.Terminating:case e.SessionState.Terminated:t(!0)}}catch(e){c(e)}finally{s(this,jh,"f").incomingStatus=!1,s(this,jh,"f").answerStatus=!1}}))})}sendStarDtmf(e={}){return r(this,void 0,void 0,function*(){return new Promise((t,i)=>r(this,void 0,void 0,function*(){try{const r=e||{},{extraHeaders:n,requestDelegate:o}=r,a=s(this,wh,"m",pu).call(this,{onAccept(e){console.log("sip send dtmf Signal=* success"),t(e)},onReject(e){i("sip send dtmf Signal=* fail with code "+e.message.statusCode)}},o);delete r.requestDelegate,yield this.getCurrentInvitation().info(Object.assign({requestOptions:{body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:"Signal=*\r\nDuration=100"},extraHeaders:n},requestDelegate:a},r)),s(this,Kd,"f").call(this)}catch(e){i(e)}}))})}muteRemoteAudio(){s(this,Ch,"f").getReceivers().forEach(e=>{e.track.enabled=!1})}unMuteRemoteAudio(){s(this,Ch,"f").getReceivers().forEach(e=>{e.track.enabled=!0})}muteLocalAudio(){s(this,Ch,"f").getSenders().forEach(e=>{e.track.enabled=!1})}unMuteLocalAudio(){s(this,Ch,"f").getSenders().forEach(e=>{e.track.enabled=!0})}getUserAgentStatue(){return s(this,jh,"f")}getUserAgent(){return s(this,Rh,"f")||n(this,Rh,new ot(s(this,Oh,"f")),"f"),s(this,Rh,"f")}getSessionDescriptionHandler(){return s(this,Ih,"f")}getPeerConnection(){return s(this,Ch,"f")}getSenders(){return s(this,Ah,"f")}getReceivers(){return s(this,Ph,"f")}getStream(){return s(this,$h,"f")||n(this,$h,new MediaStream,"f"),s(this,Ph,"f").forEach(e=>{e.track&&s(this,$h,"f").addTrack(e.track)}),s(this,$h,"f")}getCurrentInviter(){if(!s(this,Dh,"f"))throw new Error("No currentInviter...");return s(this,Dh,"f")}getCurrentInvitation(){return s(this,kh,"f")}clearIceAutoDetection(){var e;null===(e=s(this,Sh,"f"))||void 0===e||e.destroy(),n(this,Sh,void 0,"f")}iceAutoDetectRecovery(e){var t;null===(t=s(this,Sh,"f"))||void 0===t||t.destroy(),n(this,Sh,new zu(e,this,{debugIceCredentials:!0,onRecoveryStart:(e,t)=>{console.log("开始 ICE 恢复",e,t)},onRecovered:()=>{console.log("媒体连接已恢复")},isSignalingAvailable:()=>s(this,Rh,"f").isConnected(),isRegistrationAvailable:()=>s(this,Eh,"f").state===ne.Registered,onRecoveryFailed:(e,t)=>{console.error("ICE 恢复失败",e,t)}}),"f"),s(this,Sh,"f").start()}invite(e,t={}){return r(this,void 0,void 0,function*(){const i=ot.makeURI(e.uri?e.uri:`sip:${e.extension}@${s(this,Oh,"f").transportOptions.server.split("://")[1]}`);if(!i)throw new Error("Failed to create target URI.");n(this,Dh,new ie(this.getUserAgent(),i,{sessionDescriptionHandlerOptions:{constraints:{audio:!0,video:!1}}}),"f");const{extraHeaders:r}=t||{};return yield this.getCurrentInviter().invite(Object.assign({requestOptions:{extraHeaders:r}},t)),s(this,Dh,"f")})}}Sh=new WeakMap,Th=new WeakMap,Rh=new WeakMap,Eh=new WeakMap,Ih=new WeakMap,Ch=new WeakMap,Ph=new WeakMap,Ah=new WeakMap,Oh=new WeakMap,kh=new WeakMap,Dh=new WeakMap,$h=new WeakMap,jh=new WeakMap,_h=new WeakMap,Hh=new WeakMap,Mh=new WeakMap,xh=new WeakMap,qh=new WeakMap,Nh=new WeakMap,Fh=new WeakMap,Uh=new WeakMap,Lh=new WeakMap,Bh=new WeakMap,Wh=new WeakMap,Gh=new WeakMap,Vh=new WeakMap,Kh=new WeakMap,zh=new WeakMap,Yh=new WeakMap,Jh=new WeakMap,Zh=new WeakMap,Xh=new WeakMap,Qh=new WeakMap,ed=new WeakMap,td=new WeakMap,id=new WeakMap,rd=new WeakMap,sd=new WeakMap,nd=new WeakMap,od=new WeakMap,ad=new WeakMap,cd=new WeakMap,ld=new WeakMap,hd=new WeakMap,dd=new WeakMap,ud=new WeakMap,gd=new WeakMap,fd=new WeakMap,pd=new WeakMap,vd=new WeakMap,md=new WeakMap,bd=new WeakMap,yd=new WeakMap,wd=new WeakMap,Sd=new WeakMap,Td=new WeakMap,Rd=new WeakMap,Ed=new WeakMap,Id=new WeakMap,Cd=new WeakMap,Pd=new WeakMap,Ad=new WeakMap,Od=new WeakMap,kd=new WeakMap,Dd=new WeakMap,$d=new WeakMap,jd=new WeakMap,_d=new WeakMap,Hd=new WeakMap,Md=new WeakMap,xd=new WeakMap,qd=new WeakMap,Nd=new WeakMap,Fd=new WeakMap,Ud=new WeakMap,Ld=new WeakMap,Bd=new WeakMap,Wd=new WeakMap,Gd=new WeakMap,Vd=new WeakMap,Kd=new WeakMap,zd=new WeakMap,Yd=new WeakMap,Jd=new WeakMap,Zd=new WeakMap,Xd=new WeakMap,Qd=new WeakMap,eu=new WeakMap,tu=new WeakMap,lu=new WeakMap,hu=new WeakMap,uu=new WeakMap,Cu=new WeakMap,Au=new WeakMap,Ou=new WeakMap,ku=new WeakMap,Du=new WeakMap,$u=new WeakMap,qu=new WeakMap,wh=new WeakSet,iu=function(e={}){var t,i;n(this,zh,null!==(t=e.openXhrIntercept)&&void 0!==t?t:s(this,zh,"f"),"f"),n(this,Yh,null!==(i=e.gatewayXhrIntercept)&&void 0!==i?i:s(this,Yh,"f"),"f")},ru=function(e={}){var t,i,o,a,c,l;n(this,Gd,null!==(t=e.enableChatInfoPush)&&void 0!==t?t:s(this,Gd,"f"),"f"),n(this,Vd,null!==(i=e.enableVolumnTrack)&&void 0!==i?i:s(this,Vd,"f"),"f"),n(this,Vh,null!==(o=e.refreshSpeekVolumn)&&void 0!==o?o:s(this,Vh,"f"),"f"),n(this,rd,null!==(a=e.refreshRequirementCheck)&&void 0!==a?a:s(this,rd,"f"),"f"),n(this,Kh,null!==(c=e.refreshChat)&&void 0!==c?c:s(this,Kh,"f"),"f"),n(this,id,null!==(l=e.refreshChatErrorCallback)&&void 0!==l?l:s(this,id,"f"),"f");const h=e.errorCallback;e.errorCallback=e=>r(this,void 0,void 0,function*(){try{yield s(this,Qh,"f").call(this,e)}catch(e){}finally{null==h||h(e)}})},su=function(e={}){var t,i,r,o,a;n(this,xh,null!==(t=e.token)&&void 0!==t?t:s(this,xh,"f"),"f"),n(this,qh,null!==(i=e.tokenTimestamp)&&void 0!==i?i:s(this,qh,"f"),"f"),n(this,Fh,null!==(r=e.tokenExpirationTime)&&void 0!==r?r:s(this,Fh,"f"),"f"),s(this,xh,"f")&&!s(this,qh,"f")&&n(this,qh,Date.now(),"f"),n(this,Zh,null!==(o=e.tokenCheck)&&void 0!==o?o:s(this,Zh,"f"),"f"),n(this,td,null!==(a=e.tokenOverdued)&&void 0!==a?a:s(this,td,"f"),"f")},nu=function(e={}){var t,i,r;n(this,Ud,null!==(t=e.clusterMode)&&void 0!==t?t:s(this,Ud,"f"),"f"),n(this,Ld,null!==(i=e.reClusterRegisterTimeout)&&void 0!==i?i:s(this,Ld,"f"),"f"),n(this,Bd,null!==(r=e.reClusterConnectTimeout)&&void 0!==r?r:s(this,Bd,"f"),"f")},ou=function(e={}){var t,i,r;const{agentId:o,agentTag:a,appKey:c,appSecret:l,openBaseUrl:h,sg:d,sgOpen:u,sign:g,armsReport:f,timestamp:p}=e;n(this,$d,null!=o?o:s(this,$d,"f"),"f"),n(this,Cd,null!=a?a:s(this,Cd,"f"),"f"),n(this,Ed,null!=c?c:s(this,Ed,"f"),"f"),n(this,Id,null!=l?l:s(this,Id,"f"),"f"),n(this,jd,null!=h?h:s(this,jd,"f"),"f"),n(this,Lh,null!=f?f:s(this,Lh,"f"),"f"),n(this,Hd,null!=d?d:s(this,Hd,"f"),"f"),n(this,_d,null!=u?u:s(this,_d,"f"),"f"),n(this,Hh,null!=g?g:s(this,Hh,"f"),"f"),n(this,Mh,null!=p?p:s(this,Mh,"f"),"f"),n(this,Nh,null!==(t=e.signExpirationTime)&&void 0!==t?t:s(this,Nh,"f"),"f"),n(this,Jh,null!==(i=e.signCheck)&&void 0!==i?i:s(this,Jh,"f"),"f"),n(this,Xh,null!==(r=e.signOverdued)&&void 0!==r?r:s(this,Xh,"f"),"f")},au=function(e){e.sipHeaders&&(n(this,Th,e.sipHeaders,"f"),delete e.sipHeaders)},cu=function(){return!(!s(this,$d,"f")&&!s(this,Cd,"f")||!(s(this,Ed,"f")&&s(this,Id,"f")||s(this,Hh,"f")&&s(this,Mh,"f")))},du=function(){s(this,wh,"m",yu).call(this),s(this,wh,"m",Ru).call(this),s(this,wh,"m",Eu).call(this),s(this,wh,"m",Tu).call(this),s(this,wh,"m",Su).call(this),s(this,wh,"m",ju).call(this),s(this,wh,"m",_u).call(this),s(this,wh,"m",wu).call(this),s(this,zd,"f").call(this),this.clearIceAutoDetection(),n(this,Wd,{},"f"),n(this,Uh,{},"f")},gu=function(e){n(this,jh,Lt(JSON.parse(JSON.stringify(Xt)),"function"==typeof e.refresh?e.refresh:s(this,qd,"f")),"f")},fu=function(e){var t,i,r,o,a,c,l,h,d,u,g,f,p,v,m;n(this,od,null!==(r=null!==(t=e.reconnectionAttempts)&&void 0!==t?t:null===(i=null==e?void 0:e.transportOptions)||void 0===i?void 0:i.maxReconnectionAttempts)&&void 0!==r?r:s(this,od,"f"),"f"),n(this,ad,null!==(l=null!==(a=null!==(o=e.reconnectionInterval)&&void 0!==o?o:e.reconnectionDelay)&&void 0!==a?a:null===(c=null==e?void 0:e.transportOptions)||void 0===c?void 0:c.reconnectionTimeout)&&void 0!==l?l:s(this,ad,"f"),"f"),n(this,vd,null!==(d=null===(h=e.transportOptions)||void 0===h?void 0:h.keepAliveInterval)&&void 0!==d?d:s(this,vd,"f"),"f"),n(this,md,null!==(g=null===(u=e.transportOptions)||void 0===u?void 0:u.keepAliveDebounce)&&void 0!==g?g:s(this,md,"f"),"f"),n(this,gd,null!==(f=e.registerInterval)&&void 0!==f?f:s(this,gd,"f"),"f"),n(this,cd,null!==(p=e.optionsPingInterval)&&void 0!==p?p:s(this,cd,"f"),"f"),n(this,ld,null!==(v=e.optionsPingAttempts)&&void 0!==v?v:s(this,ld,"f"),"f"),n(this,fd,null!==(m=e.registerAttempts)&&void 0!==m?m:s(this,fd,"f"),"f")},pu=function(e,t){return t?(Object.keys(t).forEach(i=>{if(t[i]&&"function"==typeof t[i])if(e[i]){if("function"==typeof e[i]){const s=e[i];e[i]=e=>r(this,void 0,void 0,function*(){yield t[i](e),yield s(e)})}}else e[i]=t[i]}),e):e},vu=function(e){const t={delegate:{onConnect:()=>r(this,void 0,void 0,function*(){console.log("sip connected"),s(this,ku,"f").call(this)}),onInvite:e=>{s(this,uu,"f").call(this,e.incomingInviteRequest.message.headers),this.refreshCallChatInfo(),s(this,wh,"m",mu).call(this),n(this,kh,e,"f"),s(this,jh,"f").incomingStatus=!0,this.iceAutoDetectRecovery(e),e.stateChange.addListener(s(this,Cu,"f"))},onDisconnect:e=>r(this,void 0,void 0,function*(){console.log("sip disconnected");let t=!1;s(this,cd,"f")>0&&(t=s(this,dd,"f"),s(this,$u,"f").call(this));try{yield s(this,wh,"m",Pu).call(this)}catch(e){}(e||t)&&s(this,wh,"m",Nu).call(this)})}};return e.delegate?Object.keys(e.delegate).forEach(i=>{const s=i;if(e.delegate[s]&&"function"==typeof e.delegate[s]){const i=e.delegate[s];e.delegate[s]=e=>r(this,void 0,void 0,function*(){var r,n;null===(n=(r=t.delegate)[s])||void 0===n||n.call(r,e),yield i(e)})}}):e.delegate=t.delegate,e.reconnectionAttempts=0,e.transportOptions=Object.assign(Object.assign({},e.transportOptions||{}),{keepAliveInterval:s(this,vd,"f"),keepAliveDebounce:s(this,md,"f")}),void 0===e.sessionDescriptionHandlerFactoryOptions&&(e.sessionDescriptionHandlerFactoryOptions={iceGatheringTimeout:2e3,peerConnectionConfiguration:{iceServers:[]}}),Object.assign(Object.assign({},Zt),e)},mu=function(){s(this,kh,"f")&&(s(this,kh,"f").dispose(),n(this,kh,void 0,"f"))},bu=function(){return r(this,void 0,void 0,function*(){s(this,Rh,"f")&&(yield s(this,Rh,"f").stop(),n(this,Rh,void 0,"f"))})},yu=function(){s(this,$h,"f")&&(s(this,$h,"f").getTracks().forEach(e=>{e.stop()}),n(this,$h,void 0,"f"))},wu=function(){Object.keys(Xt).forEach(e=>{const t=e;s(this,jh,"f")[t]=Xt[t]})},Su=function(){s(this,Ih,"f")&&(s(this,Ih,"f").close(),n(this,Ih,void 0,"f"))},Tu=function(){s(this,Ch,"f")&&(s(this,Ch,"f").close(),n(this,Ch,void 0,"f"))},Ru=function(){n(this,Ah,[],"f")},Eu=function(){n(this,Ph,[],"f")},Iu=function(){const e=this.getCurrentInvitation(),{sessionDescriptionHandler:t}=e;s(this,wh,"m",Tu).call(this),s(this,wh,"m",Su).call(this),s(this,wh,"m",Ru).call(this),s(this,wh,"m",Eu).call(this),n(this,Ih,t,"f");n(this,Ch,t.peerConnection,"f"),n(this,Ah,s(this,Ch,"f").getSenders(),"f"),n(this,Ph,s(this,Ch,"f").getReceivers(),"f"),(this.getFastOutboundCall()||!this.getSitOutboundCall()&&this.notNeedSendStarDtmf())&&s(this,Kd,"f").call(this)},Pu=function(e={}){return r(this,void 0,void 0,function*(){if(s(this,Eh,"f"))return console.log("sip due to disconnection, unregistered"),new Promise((t,i)=>r(this,void 0,void 0,function*(){try{const r=e||{},n=s(this,wh,"m",pu).call(this,{onAccept:e=>{console.log("sip unregister successed"),t(e)},onReject(e){i("sip unregister fail with code "+e.message.statusCode)}},r.requestDelegate);delete e.requestDelegate,yield s(this,Eh,"f").unregister(Object.assign({requestDelegate:n},e))}catch(e){i(e)}}))})},ju=function(){s(this,wh,"m",Hu).call(this),s(this,wh,"m",Mu).call(this),s(this,wh,"m",xu).call(this),n(this,wd,!1,"f"),n(this,bd,!1,"f"),n(this,yd,!1,"f")},_u=function(e=!0,t=!0){e&&(clearTimeout(s(this,Nd,"f")),n(this,Nd,void 0,"f")),t&&(clearTimeout(s(this,Fd,"f")),n(this,Fd,void 0,"f"))},Hu=function(){clearTimeout(s(this,Rd,"f")),n(this,Rd,void 0,"f")},Mu=function(){clearTimeout(s(this,Sd,"f")),n(this,Sd,void 0,"f")},xu=function(){clearTimeout(s(this,Td,"f")),n(this,Td,void 0,"f")},Nu=function e(t=1){return r(this,void 0,void 0,function*(){if(s(this,ad,"f")){if(s(this,jh,"f").reconnectStatus=!0,s(this,bd,"f"))return;if(t>s(this,od,"f"))return console.log("sip maximum reconnection attempts reached"),void(yield this.dispose());console.log("sip reconnection attempt..."),n(this,bd,!0,"f"),n(this,Sd,setTimeout(()=>{s(this,wh,"m",Mu).call(this),this.getUserAgent().reconnect().then(()=>r(this,void 0,void 0,function*(){console.log(`sip reconnection attempt ${t} of ${s(this,od,"f")} - succeeded`),n(this,bd,!1,"f"),s(this,qu,"f").call(this)})).catch(i=>{console.error(i),console.log(`sip reconnection attempt ${t} of ${s(this,od,"f")} - failed`),n(this,bd,!1,"f"),s(this,wh,"m",e).call(this,++t)})},1===t?0:1e3*s(this,ad,"f")),"f")}})},Fu=function(e){return Object.keys(e).forEach(t=>{const i=t;if("function"==typeof(null==e?void 0:e[i])){const t=e[i];e[i]=e=>r(this,void 0,void 0,function*(){var r,n;null===(n=(r=s(this,Oh,"f").delegate)[i])||void 0===n||n.call(r,e),yield t(e)})}}),e},Uu=function(e){const t=this.getUserAgent();return t.delegate=s(this,wh,"m",Fu).call(this,e),t},Lu=function(){return r(this,void 0,void 0,function*(){const e=this.getUserAgent();if(yield e.start(),e.isConnected()||(yield e.reconnect()),!e.isConnected())throw new Error("链接失败,请稍后再试");return s(this,jh,"f").connectStatus=!0,e})},Bu=function e(t,i=!1){const{registererOptions:o,registererRegisterOptions:a,extraHeaders:c}=t||{};return new Promise((t,l)=>r(this,void 0,void 0,function*(){const h=this.getUserAgent();let d;n(this,Eh,new ge(h,Object.assign({extraHeaders:c||s(this,Th,"f")},o||{})),"f");const u=a||{},g=s(this,wh,"m",pu).call(this,{onAccept:e=>{d=e,s(this,wh,"m",_u).call(this),s(this,jh,"f").registerStatus=!0,t(h)},onReject:e=>{s(this,wh,"m",_u).call(this),l("sip register fail with code "+e.message.statusCode)}},u.requestDelegate);delete u.requestDelegate,i&&n(this,Nd,setTimeout(()=>r(this,void 0,void 0,function*(){if(!d){n(this,Fd,setTimeout(()=>r(this,void 0,void 0,function*(){if(s(this,wh,"m",_u).call(this,!1,!0),!d)try{try{s(this,Eh,"f").dispose()}catch(e){}s(this,wh,"m",du).call(this),s(this,$u,"f").call(this),n(this,hd,0,"f"),n(this,pd,0,"f"),yield s(this,Rh,"f").transport.dispose(),n(this,Rh,new ot(s(this,Oh,"f")),"f"),yield s(this,wh,"m",Lu).call(this);const i=yield s(this,wh,"m",e).call(this,{registererOptions:o,registererRegisterOptions:a,extraHeaders:c});t(i)}catch(e){l(e)}}),s(this,Bd,"f")),"f");try{s(this,Eh,"f").dispose()}catch(e){}n(this,Eh,new ge(h,Object.assign({extraHeaders:c||s(this,Th,"f")},o||{})),"f"),s(this,wh,"m",_u).call(this,!0,!1);try{yield s(this,Eh,"f").register(Object.assign({requestDelegate:g,requestOptions:{extraHeaders:c||s(this,Th,"f")}},u))}catch(e){s(this,wh,"m",_u).call(this),l(e)}}}),s(this,Ld,"f")),"f");try{yield s(this,Eh,"f").register(Object.assign({requestDelegate:g,requestOptions:{extraHeaders:c||s(this,Th,"f")}},u))}catch(e){s(this,wh,"m",_u).call(this),l(e)}}))};class Zu{static getToken(e={}){return r(this,void 0,void 0,function*(){const{appKey:i,appSecret:s,agentId:n,agentTag:o,teleai:a}=e||{};let c=n;if(!c&&o&&s&&i){const e=yield new Promise((e,r)=>{try{const c=Date.now(),l=t.enc.Base64.stringify(t.HmacSHA1(i+c,s)),{xhr:h,ajaxData:d,contentType:u}=Yt(e,r,{url:(a?"https://seat.teleai.com/teleaiopenapi":"https://seat.94ai.com/openapi")+"/v1/agent/getAgent",data:{agentTag:o,agentId:n}});h.setRequestHeader("appKey",i),h.setRequestHeader("timestamp",String(c)),h.setRequestHeader("sign",l),h.setRequestHeader("Content-type",u||"application/json"),h.send(d)}catch(e){r(e.message)}});if(200!=e.code)throw new Error(e.message);c=e.data.agentId}return(yield new Promise((e,t)=>r(this,void 0,void 0,function*(){try{const{xhr:r,ajaxData:n,contentType:o}=Yt(e,t,{url:(a?"https://gateway.teleai.com":"https://gateway.94ai.com")+"/authority/accessToken/openApi",data:{corpId:i,secret:s,sid:c,seatOnline:!1}});r.setRequestHeader("x-app-code",3),r.setRequestHeader("content-type",o||"application/json"),r.send(n)}catch(e){t(e.message)}}))).token})}static getUserAgentManager(e={}){return s(this,Wu,"f",Gu)||n(this,Wu,new Ju(e),"f",Gu),s(this,Wu,"f",Gu)}static hasUserAgentManager(){return!!s(this,Wu,"f",Gu)}static newUserAgentManager(e={}){return new Ju(e)}static dispose(){if(s(this,Wu,"f",Gu))try{s(this,Wu,"f",Gu).dispose()}catch(e){}finally{n(this,Wu,void 0,"f",Gu)}}}Wu=Zu,Gu={value:void 0},e.AliArms=Ku,e.CallbackAggregator=Yu,e.Inviter=ie,e.Registerer=ge,e.SimpleUser=class{constructor(e,t={}){Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"session",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sessionManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.delegate=t.delegate,this.options=Object.assign({},t);const i={aor:this.options.aor,delegate:{onCallAnswered:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onCallAnswered)||void 0===t?void 0:t.call(e)},onCallCreated:e=>{var t,i;this.session=e,null===(i=null===(t=this.delegate)||void 0===t?void 0:t.onCallCreated)||void 0===i||i.call(t)},onCallReceived:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onCallReceived)||void 0===t?void 0:t.call(e)},onCallHangup:()=>{var e,t;this.session=void 0,(null===(e=this.delegate)||void 0===e?void 0:e.onCallHangup)&&(null===(t=this.delegate)||void 0===t||t.onCallHangup())},onCallHold:(e,t)=>{var i,r;return null===(r=null===(i=this.delegate)||void 0===i?void 0:i.onCallHold)||void 0===r?void 0:r.call(i,t)},onCallDTMFReceived:(e,t,i)=>{var r,s;return null===(s=null===(r=this.delegate)||void 0===r?void 0:r.onCallDTMFReceived)||void 0===s?void 0:s.call(r,t,i)},onMessageReceived:e=>{var t,i;return null===(i=null===(t=this.delegate)||void 0===t?void 0:t.onMessageReceived)||void 0===i?void 0:i.call(t,e.request.body)},onRegistered:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onRegistered)||void 0===t?void 0:t.call(e)},onUnregistered:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onUnregistered)||void 0===t?void 0:t.call(e)},onServerConnect:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onServerConnect)||void 0===t?void 0:t.call(e)},onServerDisconnect:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onServerDisconnect)||void 0===t?void 0:t.call(e)}},maxSimultaneousSessions:1,media:this.options.media,reconnectionAttempts:this.options.reconnectionAttempts,reconnectionDelay:this.options.reconnectionDelay,registererOptions:this.options.registererOptions,sendDTMFUsingSessionDescriptionHandler:this.options.sendDTMFUsingSessionDescriptionHandler,userAgentOptions:this.options.userAgentOptions};this.sessionManager=new at(e,i),this.logger=this.sessionManager.userAgent.getLogger("sip.SimpleUser")}get id(){return this.options.userAgentOptions&&this.options.userAgentOptions.displayName||"Anonymous"}get localMediaStream(){return this.session&&this.sessionManager.getLocalMediaStream(this.session)}get remoteMediaStream(){return this.session&&this.sessionManager.getRemoteMediaStream(this.session)}get localAudioTrack(){return this.session&&this.sessionManager.getLocalAudioTrack(this.session)}get localVideoTrack(){return this.session&&this.sessionManager.getLocalVideoTrack(this.session)}get remoteAudioTrack(){return this.session&&this.sessionManager.getRemoteAudioTrack(this.session)}get remoteVideoTrack(){return this.session&&this.sessionManager.getRemoteVideoTrack(this.session)}connect(){return this.logger.log(`[${this.id}] Connecting UserAgent...`),this.sessionManager.connect()}disconnect(){return this.logger.log(`[${this.id}] Disconnecting UserAgent...`),this.sessionManager.disconnect()}isConnected(){return this.sessionManager.isConnected()}register(e){return this.logger.log(`[${this.id}] Registering UserAgent...`),this.sessionManager.register(e)}unregister(e){return this.logger.log(`[${this.id}] Unregistering UserAgent...`),this.sessionManager.unregister(e)}call(e,t,i){return this.logger.log(`[${this.id}] Beginning Session...`),this.session?Promise.reject(new Error("Session already exists.")):this.sessionManager.call(e,t,i).then(()=>{})}hangup(){return this.logger.log(`[${this.id}] Hangup...`),this.session?this.sessionManager.hangup(this.session).then(()=>{this.session=void 0}):Promise.reject(new Error("Session does not exist."))}answer(e){return this.logger.log(`[${this.id}] Accepting Invitation...`),this.session?this.sessionManager.answer(this.session,e):Promise.reject(new Error("Session does not exist."))}decline(){return this.logger.log(`[${this.id}] rejecting Invitation...`),this.session?this.sessionManager.decline(this.session):Promise.reject(new Error("Session does not exist."))}hold(){return this.logger.log(`[${this.id}] holding session...`),this.session?this.sessionManager.hold(this.session):Promise.reject(new Error("Session does not exist."))}unhold(){return this.logger.log(`[${this.id}] unholding session...`),this.session?this.sessionManager.unhold(this.session):Promise.reject(new Error("Session does not exist."))}isHeld(){return!!this.session&&this.sessionManager.isHeld(this.session)}mute(){return this.logger.log(`[${this.id}] disabling media tracks...`),this.session&&this.sessionManager.mute(this.session)}unmute(){return this.logger.log(`[${this.id}] enabling media tracks...`),this.session&&this.sessionManager.unmute(this.session)}isMuted(){return!!this.session&&this.sessionManager.isMuted(this.session)}sendDTMF(e){return this.logger.log(`[${this.id}] sending DTMF...`),this.session?this.sessionManager.sendDTMF(this.session,e):Promise.reject(new Error("Session does not exist."))}message(e,t){return this.logger.log(`[${this.id}] sending message...`),this.sessionManager.message(e,t)}},e.URI=y,e.UserAgent=ot,e.UserAgentFactory=Zu,e.UserAgentManager=Ju,e.accumulateSec=zt,e.accumulationTimer=function(e){const t=Kt();e(Vt(t));let i=setInterval(()=>{const i=zt(t),r=Vt(i);e(r)},1e3);return()=>{clearInterval(i),i=null}},e.cleanupMedia=function(e){const t=Bt(e);t&&(t.srcObject=null,t.pause())},e.getBeijingTime=Jt,e.getDevicePermission=Gt,e.getMedia=Bt,e.getTimes=Vt,e.getZeorTime=Kt,e.onChange=Lt,e.pauseMedia=function(e){const t=Bt(e);t&&(t.currentTime=0,t.pause())},e.playMedia=function(e){const t=Bt(e);t&&(t.currentTime=0,t.play())},e.requestMicroPhonePermission=function(){try{if(-1===navigator.userAgent.indexOf("Firefox"))return Gt({video:!1,audio:!0}).catch(()=>!0)}catch(e){console.log(e)}},e.stopStreamTracks=Wt,e.userAgentDefault=Zt,e.userAgentStatus=Xt});
1
+ /** 6.0.11 */
2
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("crypto-js"),require("@fingerprintjs/fingerprintjs")):"function"==typeof define&&define.amd?define(["exports","crypto-js","@fingerprintjs/fingerprintjs"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).softphone={},e.CryptoJS,e.FingerprintJS)}(this,function(e,t,i){"use strict";function r(e,t,i,r){return new(i||(i=Promise))(function(s,n){function o(e){try{c(r.next(e))}catch(e){n(e)}}function a(e){try{c(r.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(o,a)}c((r=r.apply(e,t||[])).next())})}function s(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)}function n(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i}"function"==typeof SuppressedError&&SuppressedError;class o extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class a extends o{constructor(e){super(e||"Unsupported content type.")}}class c extends o{constructor(e){super(e||"Request pending.")}}class l extends o{constructor(e){super(e||"Unspecified session description handler error.")}}class h extends o{constructor(){super("The session has terminated.")}}class d extends o{constructor(e){super(e||"An error occurred during state transition.")}}class u{constructor(e){Object.defineProperty(this,"incomingAckRequest",{enumerable:!0,configurable:!0,writable:!0,value:e})}get request(){return this.incomingAckRequest.message}}class g{constructor(e){Object.defineProperty(this,"incomingByeRequest",{enumerable:!0,configurable:!0,writable:!0,value:e})}get request(){return this.incomingByeRequest.message}accept(e){return this.incomingByeRequest.accept(e),Promise.resolve()}reject(e){return this.incomingByeRequest.reject(e),Promise.resolve()}}class f{constructor(e){Object.defineProperty(this,"incomingCancelRequest",{enumerable:!0,configurable:!0,writable:!0,value:e})}get request(){return this.incomingCancelRequest}}class p{constructor(){Object.defineProperty(this,"listeners",{enumerable:!0,configurable:!0,writable:!0,value:new Array})}addListener(e,t){const i=t=>{this.removeListener(i),e(t)};!0===(null==t?void 0:t.once)?this.listeners.push(i):this.listeners.push(e)}emit(e){this.listeners.slice().forEach(t=>t(e))}removeAllListeners(){this.listeners=[]}removeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}on(e){return this.addListener(e)}off(e){return this.removeListener(e)}once(e){return this.addListener(e,{once:!0})}}class v{constructor(e){Object.defineProperty(this,"incomingInfoRequest",{enumerable:!0,configurable:!0,writable:!0,value:e})}get request(){return this.incomingInfoRequest.message}accept(e){return this.incomingInfoRequest.accept(e),Promise.resolve()}reject(e){return this.incomingInfoRequest.reject(e),Promise.resolve()}}class m{constructor(e){Object.defineProperty(this,"parameters",{enumerable:!0,configurable:!0,writable:!0,value:{}});for(const t in e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}setParam(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())}getParam(e){if(e)return this.parameters[e.toLowerCase()]}hasParam(e){return!(!e||void 0===this.parameters[e.toLowerCase()])}deleteParam(e){if(e=e.toLowerCase(),this.hasParam(e)){const t=this.parameters[e];return delete this.parameters[e],t}}clearParams(){this.parameters={}}}class b extends m{constructor(e,t,i){super(i),Object.defineProperty(this,"uri",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_displayName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.uri=e,this._displayName=t}get friendlyName(){return this.displayName||this.uri.aor}get displayName(){return this._displayName}set displayName(e){this._displayName=e}clone(){return new b(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))}toString(){let e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";e+="<"+this.uri.toString()+">";for(const t in this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e}}class y extends m{constructor(e="sip",t,i,r,s,n){if(super(s||{}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"normal",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"raw",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!i)throw new TypeError('missing or invalid "host" parameter');for(const e in n)n.hasOwnProperty(e)&&this.setHeader(e,n[e]);this.raw={scheme:e,user:t,host:i,port:r},this.normal={scheme:e.toLowerCase(),user:t,host:i.toLowerCase(),port:r}}get scheme(){return this.normal.scheme}set scheme(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()}get user(){return this.normal.user}set user(e){this.normal.user=this.raw.user=e}get host(){return this.normal.host}set host(e){this.raw.host=e,this.normal.host=e.toLowerCase()}get aor(){return this.normal.user+"@"+this.normal.host}get port(){return this.normal.port}set port(e){this.normal.port=this.raw.port=e}setHeader(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]}getHeader(e){if(e)return this.headers[this.headerize(e)]}hasHeader(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))}deleteHeader(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){const t=this.headers[e];return delete this.headers[e],t}}clearHeaders(){this.headers={}}clone(){return new y(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))}toRaw(){return this._toString(this._raw)}toString(){return this._toString(this._normal)}get _normal(){return this.normal}get _raw(){return this.raw}_toString(e){let t=e.scheme+":";e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port);for(const e in this.parameters)this.parameters.hasOwnProperty(e)&&(t+=";"+e,null!==this.parameters[e]&&(t+="="+this.parameters[e]));const i=[];for(const e in this.headers)if(this.headers.hasOwnProperty(e))for(const t in this.headers[e])this.headers[e].hasOwnProperty(t)&&i.push(e+"="+this.headers[e][t]);return i.length>0&&(t+="?"+i.join("&")),t}escapeUser(e){let t;try{t=decodeURIComponent(e)}catch(e){throw e}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")}headerize(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},i=e.toLowerCase().replace(/_/g,"-").split("-"),r=i.length;let s="";for(let e=0;e<r;e++)0!==e&&(s+="-"),s+=i[e].charAt(0).toUpperCase()+i[e].substring(1);return t[s]&&(s=t[s]),s}}function w(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){const i=Object.keys(e.parameters),r=Object.keys(t.parameters);return!!i.filter(e=>r.includes(e)).every(i=>e.parameters[i]===t.parameters[i])&&(!!["user","ttl","method","transport"].every(i=>e.hasParam(i)&&t.hasParam(i)||!e.hasParam(i)&&!t.hasParam(i))&&!!["maddr"].every(i=>e.hasParam(i)&&t.hasParam(i)||!e.hasParam(i)&&!t.hasParam(i)))}(e,t))return!1;const i=Object.keys(e.headers),r=Object.keys(t.headers);if(0!==i.length||0!==r.length){if(i.length!==r.length)return!1;const s=i.filter(e=>r.includes(e));if(s.length!==r.length)return!1;if(!s.every(i=>e.headers[i].length&&t.headers[i].length&&e.headers[i][0]===t.headers[i][0]))return!1}return!0}function S(e,t,i){return i=i||" ",e.length>t?e:(t-=e.length,e+(i+=i.repeat(t)).slice(0,t))}class T extends Error{static buildMessage(e,t){function i(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,e=>"\\x0"+i(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+i(e))}function s(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,e=>"\\x0"+i(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+i(e))}function n(e){switch(e.type){case"literal":return'"'+r(e.text)+'"';case"class":const t=e.parts.map(e=>Array.isArray(e)?s(e[0])+"-"+s(e[1]):s(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){const t=e.map(n);let i,r;if(t.sort(),t.length>0){for(i=1,r=1;i<t.length;i++)t[i-1]!==t[i]&&(t[r]=t[i],r++);t.length=r}switch(t.length){case 1:return t[0];case 2:return t[0]+" or "+t[1];default:return t.slice(0,-1).join(", ")+", or "+t[t.length-1]}}(e)+" but "+(((o=t)?'"'+r(o)+'"':"end of input")+" found.");var o}constructor(e,t,i,r){super(),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"expected",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"found",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"location",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.message=e,this.expected=t,this.found=i,this.location=r,this.name="SyntaxError","function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(this,T.prototype):this.__proto__=T.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,T)}format(e){let t="Error: "+this.message;if(this.location){let i,r=null;for(i=0;i<e.length;i++)if(e[i].source===this.location.source){r=e[i].text.split(/\r\n|\n|\r/g);break}let s=this.location.start,n=this.location.source+":"+s.line+":"+s.column;if(r){let e=this.location.end,i=S("",s.line.toString().length," "),o=r[s.line-1],a=s.line===e.line?e.column:o.length+1;t+="\n --\x3e "+n+"\n"+i+" |\n"+s.line+" | "+o+"\n"+i+" | "+S("",s.column-1," ")+S("",a-s.column,"^")}else t+="\n at "+n}return t}}const R=function(e,t){const i={},r=(t=void 0!==t?t:{}).grammarSource,s={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};let n=119;const o=["\r\n",m("\r\n",!1),/^[0-9]/,w([["0","9"]],!1,!1),/^[a-zA-Z]/,w([["a","z"],["A","Z"]],!1,!1),/^[0-9a-fA-F]/,w([["0","9"],["a","f"],["A","F"]],!1,!1),/^[\0-\xFF]/,w([["\0","ÿ"]],!1,!1),/^["]/,w(['"'],!1,!1)," ",m(" ",!1),"\t",m("\t",!1),/^[a-zA-Z0-9]/,w([["a","z"],["A","Z"],["0","9"]],!1,!1),";",m(";",!1),"/",m("/",!1),"?",m("?",!1),":",m(":",!1),"@",m("@",!1),"&",m("&",!1),"=",m("=",!1),"+",m("+",!1),"$",m("$",!1),",",m(",",!1),"-",m("-",!1),"_",m("_",!1),".",m(".",!1),"!",m("!",!1),"~",m("~",!1),"*",m("*",!1),"'",m("'",!1),"(",m("(",!1),")",m(")",!1),"%",m("%",!1),function(){return" "},function(){return":"},/^[!-~]/,w([["!","~"]],!1,!1),/^[\x80-\uFFFF]/,w([["€","￿"]],!1,!1),/^[\x80-\xBF]/,w([["€","¿"]],!1,!1),/^[a-f]/,w([["a","f"]],!1,!1),"`",m("`",!1),"<",m("<",!1),">",m(">",!1),"\\",m("\\",!1),"[",m("[",!1),"]",m("]",!1),"{",m("{",!1),"}",m("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,w([["!","'"]],!1,!1),/^[*-[]/,w([["*","["]],!1,!1),/^[\]-~]/,w([["]","~"]],!1,!1),function(e){return e},/^[#-[]/,w([["#","["]],!1,!1),/^[\0-\t]/,w([["\0","\t"]],!1,!1),/^[\v-\f]/,w([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,w([["",""]],!1,!1),function(){(t=t||{data:{}}).data.uri=new y(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 y(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",m("sips",!0),"sip",m("sip",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(){(t=t||{data:{}}).data.user=decodeURIComponent(p().slice(0,-1))},function(){(t=t||{data:{}}).data.password=p()},function(){return(t=t||{data:{}}).data.host=p(),t.data.host},function(){return(t=t||{data:{}}).data.host_type="domain",p()},/^[a-zA-Z0-9_\-]/,w([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,w([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",p()},"::",m("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",p()},function(){return(t=t||{data:{}}).data.host_type="IPv4",p()},"25",m("25",!1),/^[0-5]/,w([["0","5"]],!1,!1),"2",m("2",!1),/^[0-4]/,w([["0","4"]],!1,!1),"1",m("1",!1),/^[1-9]/,w([["1","9"]],!1,!1),function(e){return t=t||{data:{}},e=parseInt(e.join("")),t.data.port=e,e},"transport=",m("transport=",!0),"udp",m("udp",!0),"tcp",m("tcp",!0),"sctp",m("sctp",!0),"tls",m("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",m("user=",!0),"phone",m("phone",!0),"ip",m("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",m("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",m("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",m("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",m("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,i){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),i=null===i?void 0:i[1],t.data.uri_params[e.toLowerCase()]=i},function(e,i){e=e.join("").toLowerCase(),i=i.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(i):t.data.uri_headers[e]=[i]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new y(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)},"//",m("//",!1),function(){(t=t||{data:{}}).data.scheme=p()},m("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=p()},"INVITE",m("INVITE",!1),"ACK",m("ACK",!1),"VXACH",m("VXACH",!1),"OPTIONS",m("OPTIONS",!1),"BYE",m("BYE",!1),"CANCEL",m("CANCEL",!1),"REGISTER",m("REGISTER",!1),"SUBSCRIBE",m("SUBSCRIBE",!1),"NOTIFY",m("NOTIFY",!1),"REFER",m("REFER",!1),"PUBLISH",m("PUBLISH",!1),function(){return(t=t||{data:{}}).data.method=p(),t.data.method},function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},function(){(t=t||{data:{}}).data.reason_phrase=p()},function(){(t=t||{data:{}}).data=p()},function(){var e,i;for(i=(t=t||{data:{}}).data.multi_header.length,e=0;e<i;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 b(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:c,offset:v().start.offset,parsed:e})},function(e){'"'===(e=p().trim())[0]&&(e=e.substring(1,e.length-1)),(t=t||{data:{}}).data.displayName=e},"q",m("q",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.q=e},"expires",m("expires",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.expires=e},function(e){return parseInt(e.join(""))},"0",m("0",!1),function(){return parseFloat(p())},function(e,i){(t=t||{data:{}}).data.params||(t.data.params={}),i=null===i?void 0:i[1],t.data.params[e.toLowerCase()]=i},"render",m("render",!0),"session",m("session",!0),"icon",m("icon",!0),"alert",m("alert",!0),function(){"Content_Disposition"===(t=t||{data:{}}).startRule&&(t.data.type=p().toLowerCase())},"handling",m("handling",!0),"optional",m("optional",!0),"required",m("required",!0),function(e){(t=t||{data:{}}).data=parseInt(e.join(""))},function(){(t=t||{data:{}}).data=p()},"text",m("text",!0),"image",m("image",!0),"audio",m("audio",!0),"video",m("video",!0),"application",m("application",!0),"message",m("message",!0),"multipart",m("multipart",!0),"x-",m("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 b(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"tag",m("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 b(t.data.uri,t.data.displayName,t.data.params)},"digest",m("Digest",!0),"realm",m("realm",!0),function(e){(t=t||{data:{}}).data.realm=e},"domain",m("domain",!0),"nonce",m("nonce",!0),function(e){(t=t||{data:{}}).data.nonce=e},"opaque",m("opaque",!0),function(e){(t=t||{data:{}}).data.opaque=e},"stale",m("stale",!0),"true",m("true",!0),function(){(t=t||{data:{}}).data.stale=!0},"false",m("false",!0),function(){(t=t||{data:{}}).data.stale=!1},"algorithm",m("algorithm",!0),"md5",m("MD5",!0),"md5-sess",m("MD5-sess",!0),function(e){(t=t||{data:{}}).data.algorithm=e.toUpperCase()},"qop",m("qop",!0),"auth-int",m("auth-int",!0),"auth",m("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,i;for(i=(t=t||{data:{}}).data.multi_header.length,e=0;e<i;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 b(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:c,offset:v().start.offset,parsed:e})},function(){(t=t||{data:{}}).data=new b(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",m("from-tag",!0),function(e){(t=t||{data:{}}).data.replaces_from_tag=e},"to-tag",m("to-tag",!0),function(e){(t=t||{data:{}}).data.replaces_to_tag=e},"early-only",m("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",m("active",!0),"pending",m("pending",!0),"terminated",m("terminated",!0),function(){(t=t||{data:{}}).data.state=p()},"reason",m("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",m("retry_after",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.retry_after=e)},"deactivated",m("deactivated",!0),"probation",m("probation",!0),"rejected",m("rejected",!0),"timeout",m("timeout",!0),"giveup",m("giveup",!0),"noresource",m("noresource",!0),"invariant",m("invariant",!0),function(e){"Supported"===(t=t||{data:{}}).startRule&&(t.data=e||[])},function(){var e=(t=t||{data:{}}).data.tag;t.data=new b(t.data.uri,t.data.displayName,t.data.params),e&&t.data.setParam("tag",e)},"ttl",m("ttl",!0),function(e){(t=t||{data:{}}).data.ttl=e},"maddr",m("maddr",!0),function(e){(t=t||{data:{}}).data.maddr=e},"received",m("received",!0),function(e){(t=t||{data:{}}).data.received=e},"branch",m("branch",!0),function(e){(t=t||{data:{}}).data.branch=e},"rport",m("rport",!0),function(e){t=t||{data:{}},void 0!==e&&(t.data.rport=e.join(""))},function(e){(t=t||{data:{}}).data.protocol=e},m("UDP",!0),m("TCP",!0),m("TLS",!0),m("SCTP",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data.host=p()},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",m("refresher",!1),"uas",m("uas",!1),"uac",m("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",m("stuns",!0),"stun",m("stun",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(e){(t=t||{data:{}}).data.host=e},"?transport=",m("?transport=",!1),"turns",m("turns",!0),"turn",m("turn",!0),function(e){(t=t||{data:{}}).data.transport=e},function(){(t=t||{data:{}}).data=p()},"Referred-By",m("Referred-By",!1),"b",m("b",!1),"cid",m("cid",!1)],a=[I('2 ""6 7!'),I('4"""5!7#'),I('4$""5!7%'),I('4&""5!7\''),I(";'.# &;("),I('4(""5!7)'),I('4*""5!7+'),I('2,""6,7-'),I('2.""6.7/'),I('40""5!71'),I('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'),I(";).# &;,"),I('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),I('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),I('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/&#0#*;$&&&#/\'$8":Z" )("\'#&\'#'),I(';.." &"'),I("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),I('%%$;2/&#0#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),I('4\\""5!7].# &;3'),I('4^""5!7_'),I('4`""5!7a'),I(';!.) &4b""5!7c'),I('%$;).• &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&&&#/"!&,)'),I('%$;).‰ &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&&&#/"!&,)'),I('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.) &;\'.# &;('),I('%$;).ī &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&&&#/"!&,)'),I("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),I("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),I("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),I("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),I("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),I('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),I('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),I("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),I("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),I("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),I("%;//0#;&/'$8\":~\" )(\"'#&'#"),I("%;&/0#;//'$8\":~\" )(\"'#&'#"),I("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),I('4""5!7€.A &4""5!7‚.5 &4ƒ""5!7„.) &;3.# &;.'),I("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),I("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:…$!!)($'#(#'#(\"'#&'#"),I(';..G &2L""6L7M.; &4†""5!7‡./ &4ƒ""5!7„.# &;3'),I('%2j""6j7k/J#4ˆ""5!7‰.5 &4Š""5!7‹.) &4Œ""5!7/#$+")("\'#&\'#'),I("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:Ž$ )($'#(#'#(\"'#&'#"),I("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:& )(&'#(%'#($'#(#'#(\"'#&'#"),I('%3""5$7‘.) &3’""5#7“/\' 8!:”!! )'),I('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:•# )(#\'#("\'#&\'#'),I("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),I('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'),I('%$;+._ &;-.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!:–! )'),I('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),I("%;U.) &;\\.# &;X/& 8!:—! )"),I('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:˜# )(#\'#("\'#&\'#'),I('$4™""5!7š/,#0)*4™""5!7š&&&#'),I('%4$""5!7%/?#$4›""5!7œ0)*4›""5!7œ&/#$+")("\'#&\'#'),I('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:# )(#\'#("\'#&\'#'),I('%%;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!: ! )'),I('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),I("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),I("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),I('%2¢""6¢7£/2#4¤""5!7¥/#$+")("\'#&\'#.˜ &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#\'#("\'#&\'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4¬""5!7­/,#;!/#$+")("\'#&\'#.# &;!'),I('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:®!! )'),I('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),I(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),I('%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("\'#&\'#'),I('%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("\'#&\'#'),I('%3Á""5\'7Â/1#;/($8":Ã"! )("\'#&\'#'),I('%3Ä""5$7Å/1#;ð/($8":Æ"! )("\'#&\'#'),I('%3Ç""5&7È/1#;T/($8":É"! )("\'#&\'#'),I('%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":Ì" )("\'#&\'#'),I('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":Í""! )("\'#&\'#'),I('%$;j/&#0#*;j&&&#/"!&,)'),I('%$;j/&#0#*;j&&&#/"!&,)'),I(";k.) &;+.# &;-"),I('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),I('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),I('%;n/A#2>""6>7?/2$;o/)$8#:Î#"" )(#\'#("\'#&\'#'),I("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),I("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),I('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),I(";‘.# &;r"),I("%;/G#;'/>$;s/5$;'/,$;„/#$+%)(%'#($'#(#'#(\"'#&'#"),I(";M.# &;t"),I("%;/E#28\"\"6879/6$;u.# &;x/'$8#:Ï# )(#'#(\"'#&'#"),I('%;v.# &;w/J#%26""6677/,#;ƒ/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),I('%2Ð""6Ð7Ñ/:#;€/1$;w." &"/#$+#)(#\'#("\'#&\'#'),I('%24""6475/,#;{/#$+")("\'#&\'#'),I("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),I(";*.) &;+.# &;-"),I(';+. &;-.‰ &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'),I('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),I('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),I("$;~0#*;~&"),I(';+.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'),I('%%;"/‡#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:Ò! )'),I(";.# &;‚"),I('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),I('$;+.ƒ &;-.} &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&&&#'),I("$;y0#*;y&"),I('%3’""5#7Ó/q#24""6475/b$$;!/&#0#*;!&&&#/L$2J""6J7K/=$$;!/&#0#*;!&&&#/\'$8%:Ô% )(%\'#($\'#(#\'#("\'#&\'#'),I('2Õ""6Õ7Ö'),I('2×""6×7Ø'),I('2Ù""6Ù7Ú'),I('2Û""6Û7Ü'),I('2Ý""6Ý7Þ'),I('2ß""6ß7à'),I('2á""6á7â'),I('2ã""6ã7ä'),I('2å""6å7æ'),I('2ç""6ç7è'),I('2é""6é7ê'),I("%;….Y &;†.S &;ˆ.M &;‰.G &;Š.A &;‹.; &;Œ.5 &;./ &;.) &;Ž.# &;6/& 8!:ë! )"),I("%;„/G#;'/>$;’/5$;'/,$;”/#$+%)(%'#($'#(#'#(\"'#&'#"),I("%;“/' 8!:ì!! )"),I("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),I("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),I("%;¶/Y#$%;A/,#;¶/#$+\")(\"'#&'#06*%;A/,#;¶/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":î" )("\'#&\'#'),I("%;:.c &%;˜/Y#$%;A/,#;˜/#$+\")(\"'#&'#06*%;A/,#;˜/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:ï! )"),I("%;L.# &;™/]#$%;B/,#;›/#$+\")(\"'#&'#06*%;B/,#;›/#$+\")(\"'#&'#&/'$8\":ð\" )(\"'#&'#"),I("%;š.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),I("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:ñ!! )"),I(";œ.) &;.# &; "),I("%3ò\"\"5!7ó/:#;</1$;Ÿ/($8#:ô#! )(#'#(\"'#&'#"),I("%3õ\"\"5'7ö/:#;</1$;ž/($8#:÷#! )(#'#(\"'#&'#"),I("%$;!/&#0#*;!&&&#/' 8!:ø!! )"),I('%2ù""6ù7ú/o#%2J""6J7K/M#;!." &"/?$;!." &"/1$;!." &"/#$+$)($\'#(#\'#("\'#&\'#." &"/\'$8":û" )("\'#&\'#'),I('%;6/J#%;</,#;¡/#$+")("\'#&\'#." &"/)$8":ü""! )("\'#&\'#'),I(";6.) &;T.# &;H"),I("%;£/Y#$%;B/,#;¤/#$+\")(\"'#&'#06*%;B/,#;¤/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I('%3ý""5&7þ.G &3ÿ""5\'7Ā.; &3ā""5$7Ă./ &3ă""5%7Ą.# &;6/& 8!:ą! )'),I(";¥.# &; "),I('%3Ć""5(7ć/M#;</D$3Ĉ""5(7ĉ./ &3Ċ""5(7ċ.# &;6/#$+#)(#\'#("\'#&\'#'),I("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I("%$;!/&#0#*;!&&&#/' 8!:Č!! )"),I("%;©/& 8!:č! )"),I("%;ª/k#;;/b$;¯/Y$$%;B/,#;°/#$+\")(\"'#&'#06*%;B/,#;°/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),I(";«.# &;¬"),I('3Ď""5$7ď.S &3Đ""5%7đ.G &3Ē""5%7ē.; &3Ĕ""5%7ĕ./ &3Ė""5+7ė.# &;­'),I('3Ę""5\'7ę./ &3Ě""5)7ě.# &;­'),I(";6.# &;®"),I('%3Ĝ""5"7ĝ/,#;6/#$+")("\'#&\'#'),I(";­.# &;6"),I("%;6/5#;</,$;±/#$+#)(#'#(\"'#&'#"),I(";6.# &;H"),I("%;³/5#;./,$;/#$+#)(#'#(\"'#&'#"),I("%$;!/&#0#*;!&&&#/' 8!:Ğ!! )"),I("%;ž/' 8!:ğ!! )"),I('%;¶/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ġ"!!)("\'#&\'#'),I('%%;7/e#$%2J""6J7K/,#;7/#$+")("\'#&\'#0<*%2J""6J7K/,#;7/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),I("%;L.# &;™/]#$%;B/,#;¸/#$+\")(\"'#&'#06*%;B/,#;¸/#$+\")(\"'#&'#&/'$8\":ġ\" )(\"'#&'#"),I(";¹.# &; "),I("%3Ģ\"\"5#7ģ/:#;</1$;6/($8#:Ĥ#! )(#'#(\"'#&'#"),I("%$;!/&#0#*;!&&&#/' 8!:ĥ!! )"),I("%;ž/' 8!:Ħ!! )"),I("%$;š0#*;š&/x#;@/o$;M/f$;?/]$$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8%:ħ% )(%'#($'#(#'#(\"'#&'#"),I(";¾"),I("%3Ĩ\"\"5&7ĩ/k#;./b$;Á/Y$$%;A/,#;Á/#$+\")(\"'#&'#06*%;A/,#;Á/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#.# &;¿"),I("%;6/k#;./b$;À/Y$$%;A/,#;À/#$+\")(\"'#&'#06*%;A/,#;À/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),I("%;6/;#;</2$;6.# &;H/#$+#)(#'#(\"'#&'#"),I(";Â.G &;Ä.A &;Æ.; &;È.5 &;É./ &;Ê.) &;Ë.# &;À"),I("%3Ī\"\"5%7ī/5#;</,$;Ã/#$+#)(#'#(\"'#&'#"),I("%;I/' 8!:Ĭ!! )"),I("%3ĭ\"\"5&7Į/—#;</Ž$;D/…$;Å/|$$%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#0C*%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#&/,$;E/#$+&)(&'#(%'#($'#(#'#(\"'#&'#"),I(";t.# &;w"),I("%3į\"\"5%7İ/5#;</,$;Ç/#$+#)(#'#(\"'#&'#"),I("%;I/' 8!:ı!! )"),I("%3IJ\"\"5&7ij/:#;</1$;I/($8#:Ĵ#! )(#'#(\"'#&'#"),I('%3ĵ""5%7Ķ/]#;</T$%3ķ""5$7ĸ/& 8!:Ĺ! ).4 &%3ĺ""5%7Ļ/& 8!:ļ! )/#$+#)(#\'#("\'#&\'#'),I('%3Ľ""5)7ľ/R#;</I$3Ŀ""5#7ŀ./ &3Ł""5(7ł.# &;6/($8#:Ń#! )(#\'#("\'#&\'#'),I('%3ń""5#7Ņ/“#;</Š$;D/$%;Ì/e#$%2D""6D7E/,#;Ì/#$+")("\'#&\'#0<*%2D""6D7E/,#;Ì/#$+")("\'#&\'#&/#$+")("\'#&\'#/,$;E/#$+%)(%\'#($\'#(#\'#("\'#&\'#'),I('%3ņ""5(7Ň./ &3ň""5$7ʼn.# &;6/\' 8!:Ŋ!! )'),I("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I("%;Ï/G#;./>$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),I("%$;!/&#0#*;!&&&#/' 8!:ŋ!! )"),I("%;Ñ/]#$%;A/,#;Ñ/#$+\")(\"'#&'#06*%;A/,#;Ñ/#$+\")(\"'#&'#&/'$8\":Ō\" )(\"'#&'#"),I("%;™/]#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8\":ō\" )(\"'#&'#"),I('%;L.O &;™.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/\'$8":Ŏ" )("\'#&\'#'),I("%;Ô/]#$%;B/,#;Õ/#$+\")(\"'#&'#06*%;B/,#;Õ/#$+\")(\"'#&'#&/'$8\":ŏ\" )(\"'#&'#"),I("%;–/& 8!:Ő! )"),I('%3ő""5(7Œ/:#;</1$;6/($8#:œ#! )(#\'#("\'#&\'#.g &%3Ŕ""5&7ŕ/:#;</1$;6/($8#:Ŗ#! )(#\'#("\'#&\'#.: &%3ŗ""5*7Ř/& 8!:ř! ).# &; '),I('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:Ŝ!! )'),I("%;Ø/Y#$%;A/,#;Ø/#$+\")(\"'#&'#06*%;A/,#;Ø/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I("%;™/Y#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I("%$;!/&#0#*;!&&&#/' 8!:ŝ!! )"),I("%;Û/Y#$%;B/,#;Ü/#$+\")(\"'#&'#06*%;B/,#;Ü/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I('%3Ş""5&7ş.; &3Š""5\'7š./ &3Ţ""5*7ţ.# &;6/& 8!:Ť! )'),I("%3ť\"\"5&7Ŧ/:#;</1$;Ý/($8#:ŧ#! )(#'#(\"'#&'#.} &%3õ\"\"5'7ö/:#;</1$;ž/($8#:Ũ#! )(#'#(\"'#&'#.P &%3ũ\"\"5+7Ū/:#;</1$;ž/($8#:ū#! )(#'#(\"'#&'#.# &; "),I('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'),I(';1." &"'),I('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:ź!! )'),I("%;L.# &;™/]#$%;B/,#;á/#$+\")(\"'#&'#06*%;B/,#;á/#$+\")(\"'#&'#&/'$8\":Ż\" )(\"'#&'#"),I(";¹.# &; "),I("%;ã/Y#$%;A/,#;ã/#$+\")(\"'#&'#06*%;A/,#;ã/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),I("%;ê/k#;./b$;í/Y$$%;B/,#;ä/#$+\")(\"'#&'#06*%;B/,#;ä/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),I(";å.; &;æ.5 &;ç./ &;è.) &;é.# &; "),I("%3ż\"\"5#7Ž/:#;</1$;ð/($8#:ž#! )(#'#(\"'#&'#"),I("%3ſ\"\"5%7ƀ/:#;</1$;T/($8#:Ɓ#! )(#'#(\"'#&'#"),I("%3Ƃ\"\"5(7ƃ/F#;</=$;\\.) &;Y.# &;X/($8#:Ƅ#! )(#'#(\"'#&'#"),I("%3ƅ\"\"5&7Ɔ/:#;</1$;6/($8#:Ƈ#! )(#'#(\"'#&'#"),I("%3ƈ\"\"5%7Ɖ/A#;</8$$;!0#*;!&/($8#:Ɗ#! )(#'#(\"'#&'#"),I("%;ë/G#;;/>$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#(\"'#&'#"),I('%3’""5#7Ó.# &;6/\' 8!:Ƌ!! )'),I('%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/\' 8!:Ɛ!! )'),I('%;î/D#%;C/,#;ï/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),I("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),I('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:ƒ!! )'),I('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:Ɠ!! )'),I(";¾"),I('%;ž/^#$%;B/,#;ó/#$+")("\'#&\'#06*%;B/,#;ó/#$+")("\'#&\'#&/($8":Ɣ"!!)("\'#&\'#'),I(";ô.# &; "),I('%2ƕ""6ƕ7Ɩ/L#;</C$2Ɨ""6Ɨ7Ƙ.) &2ƙ""6ƙ7ƚ/($8#:ƛ#! )(#\'#("\'#&\'#'),I('%;ž/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ɯ"!!)("\'#&\'#'),I("%;6/5#;0/,$;÷/#$+#)(#'#(\"'#&'#"),I("$;2.) &;4.# &;.0/*;2.) &;4.# &;.&"),I("$;%0#*;%&"),I("%;ú/;#28\"\"6879/,$;û/#$+#)(#'#(\"'#&'#"),I('%3Ɲ""5%7ƞ.) &3Ɵ""5$7Ơ/\' 8!:ơ!! )'),I('%;ü/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),I("%;\\.) &;X.# &;‚/' 8!:Ƣ!! )"),I(';".S &;!.M &2F""6F7G.A &2J""6J7K.5 &2H""6H7I.) &2N""6N7O'),I('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?'),I('%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),I('%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/\' 8!:ơ!! )'),I('%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/\' 8!:Ʃ!! )'),I("%;Ą/‡#2F\"\"6F7G/x$;ă/o$2F\"\"6F7G/`$;ă/W$2F\"\"6F7G/H$;ă/?$2F\"\"6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),I("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),I("%;ă/,#;ă/#$+\")(\"'#&'#"),I("%;ă/5#;ă/,$;ă/#$+#)(#'#(\"'#&'#"),I("%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),I('%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("\'#&\'#0<*%;B/2#;ĉ.# &; /#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),I(";™.# &;L"),I("%2Ư\"\"6Ư7ư/5#;</,$;Ċ/#$+#)(#'#(\"'#&'#"),I("%;D/S#;,/J$2:\"\"6:7;/;$;,.# &;T/,$;E/#$+%)(%'#($'#(#'#(\"'#&'#")];let c=0,l=0;const h=[{line:1,column:1}];let d,u=0,g=[],f=0;if(void 0!==t.startRule){if(!(t.startRule in s))throw new Error("Can't start parsing from rule \""+t.startRule+'".');n=s[t.startRule]}function p(){return e.substring(l,c)}function v(){return R(l,c)}function m(e,t){return{type:"literal",text:e,ignoreCase:t}}function w(e,t,i){return{type:"class",parts:e,inverted:t,ignoreCase:i}}function S(t){let i,r=h[t];if(r)return r;for(i=t-1;!h[i];)i--;for(r=h[i],r={line:r.line,column:r.column};i<t;)10===e.charCodeAt(i)?(r.line++,r.column=1):r.column++,i++;return h[t]=r,r}function R(e,t){const i=S(e),s=S(t);return{source:r,start:{offset:e,line:i.line,column:i.column},end:{offset:t,line:s.line,column:s.column}}}function E(e){c<u||(c>u&&(u=c,g=[]),g.push(e))}function I(e){return e.split("").map(e=>e.charCodeAt(0)-32)}if(t.data={},d=function t(r){const s=a[r];let n=0;const h=[];let d=s.length;const u=[],g=[];let p;for(;;){for(;n<d;)switch(s[n]){case 0:g.push(o[s[n+1]]),n+=2;break;case 1:g.push(void 0),n++;break;case 2:g.push(null),n++;break;case 3:g.push(i),n++;break;case 4:g.push([]),n++;break;case 5:g.push(c),n++;break;case 6:g.pop(),n++;break;case 7:c=g.pop(),n++;break;case 8:g.length-=s[n+1],n+=2;break;case 9:g.splice(-2,1),n++;break;case 10:g[g.length-2].push(g.pop()),n++;break;case 11:g.push(g.splice(g.length-s[n+1],s[n+1])),n+=2;break;case 12:g.push(e.substring(g.pop(),c)),n++;break;case 13:u.push(d),h.push(n+3+s[n+1]+s[n+2]),g[g.length-1]?(d=n+3+s[n+1],n+=3):(d=n+3+s[n+1]+s[n+2],n+=3+s[n+1]);break;case 14:u.push(d),h.push(n+3+s[n+1]+s[n+2]),g[g.length-1]===i?(d=n+3+s[n+1],n+=3):(d=n+3+s[n+1]+s[n+2],n+=3+s[n+1]);break;case 15:u.push(d),h.push(n+3+s[n+1]+s[n+2]),g[g.length-1]!==i?(d=n+3+s[n+1],n+=3):(d=n+3+s[n+1]+s[n+2],n+=3+s[n+1]);break;case 16:g[g.length-1]!==i?(u.push(d),h.push(n),d=n+2+s[n+1],n+=2):n+=2+s[n+1];break;case 17:u.push(d),h.push(n+3+s[n+1]+s[n+2]),e.length>c?(d=n+3+s[n+1],n+=3):(d=n+3+s[n+1]+s[n+2],n+=3+s[n+1]);break;case 18:u.push(d),h.push(n+4+s[n+2]+s[n+3]),e.substr(c,o[s[n+1]].length)===o[s[n+1]]?(d=n+4+s[n+2],n+=4):(d=n+4+s[n+2]+s[n+3],n+=4+s[n+2]);break;case 19:u.push(d),h.push(n+4+s[n+2]+s[n+3]),e.substr(c,o[s[n+1]].length).toLowerCase()===o[s[n+1]]?(d=n+4+s[n+2],n+=4):(d=n+4+s[n+2]+s[n+3],n+=4+s[n+2]);break;case 20:u.push(d),h.push(n+4+s[n+2]+s[n+3]),o[s[n+1]].test(e.charAt(c))?(d=n+4+s[n+2],n+=4):(d=n+4+s[n+2]+s[n+3],n+=4+s[n+2]);break;case 21:g.push(e.substr(c,s[n+1])),c+=s[n+1],n+=2;break;case 22:g.push(o[s[n+1]]),c+=o[s[n+1]].length,n+=2;break;case 23:g.push(i),0===f&&E(o[s[n+1]]),n+=2;break;case 24:l=g[g.length-1-s[n+1]],n+=2;break;case 25:l=c,n++;break;case 26:p=s.slice(n+4,n+4+s[n+3]).map(function(e){return g[g.length-1-e]}),g.splice(g.length-s[n+2],s[n+2],o[s[n+1]].apply(null,p)),n+=4+s[n+3];break;case 27:g.push(t(s[n+1])),n+=2;break;case 28:f++,n++;break;case 29:f--,n++;break;default:throw new Error("Invalid opcode: "+s[n]+".")}if(!(u.length>0))break;d=u.pop(),n=h.pop()}return g[0]}(n),d!==i&&c===e.length)return d;throw d!==i&&c<e.length&&E({type:"end"}),C=g,P=u<e.length?e.charAt(u):null,A=u<e.length?R(u,u+1):R(u,u),new T(T.buildMessage(C,P),C,P,A);var C,P,A};var E;!function(e){e.parse=function(e,t){const i={startRule:t};try{R(e,i)}catch(e){i.data=-1}return i.data},e.nameAddrHeaderParse=function(t){const i=e.parse(t,"Name_Addr_Header");return-1!==i?i:void 0},e.URIParse=function(t){const i=e.parse(t,"SIP_URI");return-1!==i?i:void 0}}(E||(E={}));const I={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 C(e,t=32){let i="";for(let r=0;r<e;r++){i+=Math.floor(Math.random()*t).toString(t)}return i}function P(e){return I[e]||""}function A(){return C(10)}function O(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},i=e.toLowerCase().replace(/_/g,"-").split("-"),r=i.length;let s="";for(let e=0;e<r;e++)0!==e&&(s+="-"),s+=i[e].charAt(0).toUpperCase()+i[e].substring(1);return t[s]&&(s=t[s]),s}function k(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length}class D{constructor(){Object.defineProperty(this,"viaBranch",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"method",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"toTag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"to",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fromTag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"from",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cseq",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"via",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"referTo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}addHeader(e,t){const i={raw:t};e=O(e),this.headers[e]?this.headers[e].push(i):this.headers[e]=[i]}getHeader(e){const t=this.headers[O(e)];if(t)return t[0]?t[0].raw:void 0}getHeaders(e){const t=this.headers[O(e)],i=[];if(!t)return[];for(const e of t)i.push(e.raw);return i}hasHeader(e){return!!this.headers[O(e)]}parseHeader(e,t=0){if(e=O(e),!this.headers[e])return;if(t>=this.headers[e].length)return;const i=this.headers[e][t],r=i.raw;if(i.parsed)return i.parsed;const s=E.parse(r,e.replace(/-/g,"_"));return-1===s?void this.headers[e].splice(t,1):(i.parsed=s,s)}s(e,t=0){return this.parseHeader(e,t)}setHeader(e,t){this.headers[O(e)]=[{raw:t}]}toString(){return this.data}}class $ extends D{constructor(){super(),Object.defineProperty(this,"ruri",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}}class j extends D{constructor(){super(),Object.defineProperty(this,"statusCode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reasonPhrase",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}}class _{constructor(e,t,i,r,s,n,o){Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"method",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ruri",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"from",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fromTag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fromURI",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"to",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"toTag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"toURI",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"branch",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cseq",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extraHeaders",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.options=_.getDefaultOptions(),s&&(this.options=Object.assign(Object.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())),n&&n.length&&(this.extraHeaders=n.slice()),o&&(this.body={body:o.content,contentType:o.contentType}),this.method=e,this.ruri=t.clone(),this.fromURI=i.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:A(),this.from=_.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=r.clone(),this.toTag=this.options.toTag,this.to=_.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+C(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")}static getDefaultOptions(){return{callId:"",callIdPrefix:"",cseq:1,toDisplayName:"",toTag:"",fromDisplayName:"",fromTag:"",forceRport:!1,hackViaTcp:!1,optionTags:["outbound"],routeSet:[],userAgentString:"sip.js",viaHost:""}}static makeNameAddrHeader(e,t,i){const r={};return i&&(r.tag=i),new b(e,t,r)}getHeader(e){const t=this.headers[O(e)];if(t){if(t[0])return t[0]}else{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return e.substring(e.indexOf(":")+1).trim()}}getHeaders(e){const t=[],i=this.headers[O(e)];if(i)for(const e of i)t.push(e);else{const i=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)i.test(e)&&t.push(e.substring(e.indexOf(":")+1).trim())}return t}hasHeader(e){if(this.headers[O(e)])return!0;{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return!0}return!1}setHeader(e,t){this.headers[O(e)]=t instanceof Array?t:[t]}setViaHeader(e,t){this.options.hackViaTcp&&(t="TCP");let i="SIP/2.0/"+t;i+=" "+this.options.viaHost+";branch="+e,this.options.forceRport&&(i+=";rport"),this.setHeader("via",i),this.branch=e}toString(){let e="";e+=this.method+" "+this.ruri.toRaw()+" SIP/2.0\r\n";for(const t in this.headers)if(this.headers[t])for(const i of this.headers[t])e+=t+": "+i+"\r\n";for(const t of this.extraHeaders)e+=t.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: "+k(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: "+k(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}}function H(e){return"application/sdp"===e?"session":"render"}function M(e){const t="string"==typeof e?e:e.body,i="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:H(i),contentType:i,content:t}}function x(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function q(e){let t,i,r;if(e instanceof $&&e.body){const s=e.parseHeader("Content-Disposition");t=s?s.type:void 0,i=e.parseHeader("Content-Type"),r=e.body}if(e instanceof j&&e.body){const s=e.parseHeader("Content-Disposition");t=s?s.type:void 0,i=e.parseHeader("Content-Type"),r=e.body}if(e instanceof _&&e.body)if(t=e.getHeader("Content-Disposition"),i=e.getHeader("Content-Type"),"string"==typeof e.body){if(!i)throw new Error("Header content type header does not equal body content type.");r=e.body}else{if(i&&i!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");i=e.body.contentType,r=e.body.body}if(x(e)&&(t=e.contentDisposition,i=e.contentType,r=e.content),r){if(i&&!t&&(t=H(i)),!t)throw new Error("Content disposition undefined.");if(!i)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:i,content:r}}}var N,F;!function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(N||(N={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(F||(F={}));const U=500,L=5e3,B={T1:U,T2:4e3,T4:L,TIMER_B:32e3,TIMER_D:0,TIMER_F:32e3,TIMER_H:32e3,TIMER_I:0,TIMER_J:0,TIMER_K:0,TIMER_L:32e3,TIMER_M:32e3,TIMER_N:32e3,PROVISIONAL_RESPONSE_INTERVAL:6e4};class W extends o{constructor(e){super(e||"Transaction state error.")}}var G;!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"}(G||(G={}));const V=[G.ACK,G.BYE,G.CANCEL,G.INFO,G.INVITE,G.MESSAGE,G.NOTIFY,G.OPTIONS,G.PRACK,G.REFER,G.REGISTER,G.SUBSCRIBE];class K{constructor(e){Object.defineProperty(this,"incomingMessageRequest",{enumerable:!0,configurable:!0,writable:!0,value:e})}get request(){return this.incomingMessageRequest.message}accept(e){return this.incomingMessageRequest.accept(e),Promise.resolve()}reject(e){return this.incomingMessageRequest.reject(e),Promise.resolve()}}class z{constructor(e){Object.defineProperty(this,"incomingNotifyRequest",{enumerable:!0,configurable:!0,writable:!0,value:e})}get request(){return this.incomingNotifyRequest.message}accept(e){return this.incomingNotifyRequest.accept(e),Promise.resolve()}reject(e){return this.incomingNotifyRequest.reject(e),Promise.resolve()}}class Y{constructor(e,t){Object.defineProperty(this,"incomingReferRequest",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"session",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"inviter",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof b))throw new Error("Failed to parse Refer-To header.");return e}get referredBy(){return this.incomingReferRequest.message.getHeader("referred-by")}get replaces(){const e=this.referTo.uri.getHeader("replaces");return e instanceof Array?e[0]:e}get request(){return this.incomingReferRequest.message}accept(e={statusCode:202}){return this.incomingReferRequest.accept(e),Promise.resolve()}reject(e){return this.incomingReferRequest.reject(e),Promise.resolve()}makeInviter(e){if(this.inviter)return this.inviter;const t=this.referTo.uri.clone();t.clearHeaders();const i=((e=e||{}).extraHeaders||[]).slice(),r=this.replaces;r&&i.push("Replaces: "+decodeURIComponent(r));const s=this.referredBy;return s&&i.push("Referred-By: "+s),e.extraHeaders=i,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter}}function J(){const e=new Date,t=e.getFullYear(),i=e.getMonth()+1,r=e.getDate(),s=e.getHours(),n=e.getMinutes(),o=e.getSeconds();return t+"-"+Z(i)+"-"+Z(r)+" "+Z(s)+":"+Z(n)+":"+Z(o)}function Z(e){return e<10?"0"+e:e}e.SessionState=void 0,function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(e.SessionState||(e.SessionState={}));class X{constructor(t,i={}){Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_contact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_referral",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_replacee",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_assertedIdentity",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_dialog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_referralInviterOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_renderbody",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_rendertype",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onNotify",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingReinvite",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"pendingReinviteAck",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_sessionDescriptionHandler",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sessionDescriptionHandlerModifiers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sessionDescriptionHandlerOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sessionDescriptionHandlerModifiersReInvite",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_sessionDescriptionHandlerOptionsReInvite",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_state",{enumerable:!0,configurable:!0,writable:!0,value:e.SessionState.Initial}),Object.defineProperty(this,"_stateEventEmitter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_userAgent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.delegate=i.delegate,this._stateEventEmitter=new p,this._userAgent=t}dispose(){switch(this.logger.log(`Session ${this.id} in state ${this._state} is being disposed`),delete this.userAgent._sessions[this.id],this._sessionDescriptionHandler&&this._sessionDescriptionHandler.close(),this.state){case e.SessionState.Initial:case e.SessionState.Establishing:break;case e.SessionState.Established:return new Promise(e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})});case e.SessionState.Terminating:case e.SessionState.Terminated:break;default:throw new Error("Unknown state.")}return Promise.resolve()}get assertedIdentity(){return this._assertedIdentity}get dialog(){return this._dialog}get id(){return this._id}get replacee(){return this._replacee}get sessionDescriptionHandler(){return this._sessionDescriptionHandler}get sessionDescriptionHandlerFactory(){return this.userAgent.configuration.sessionDescriptionHandlerFactory}get sessionDescriptionHandlerModifiers(){return this._sessionDescriptionHandlerModifiers||[]}set sessionDescriptionHandlerModifiers(e){this._sessionDescriptionHandlerModifiers=e.slice()}get sessionDescriptionHandlerOptions(){return this._sessionDescriptionHandlerOptions||{}}set sessionDescriptionHandlerOptions(e){this._sessionDescriptionHandlerOptions=Object.assign({},e)}get sessionDescriptionHandlerModifiersReInvite(){return this._sessionDescriptionHandlerModifiersReInvite||[]}set sessionDescriptionHandlerModifiersReInvite(e){this._sessionDescriptionHandlerModifiersReInvite=e.slice()}get sessionDescriptionHandlerOptionsReInvite(){return this._sessionDescriptionHandlerOptionsReInvite||{}}set sessionDescriptionHandlerOptionsReInvite(e){this._sessionDescriptionHandlerOptionsReInvite=Object.assign({},e)}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get userAgent(){return this._userAgent}bye(t={}){let i="Session.bye() may only be called if established session.";switch(this.state){case e.SessionState.Initial:"function"==typeof this.cancel?(i+=" However Inviter.invite() has not yet been called.",i+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(i+=" However Invitation.accept() has not yet been called.",i+=" Perhaps you should have called Invitation.reject()?");break;case e.SessionState.Establishing:"function"==typeof this.cancel?(i+=" However a dialog does not yet exist.",i+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(i+=" However Invitation.accept() has not yet been called (or not yet resolved).",i+=" Perhaps you should have called Invitation.reject()?");break;case e.SessionState.Established:{const e=t.requestDelegate,i=this.copyRequestOptions(t.requestOptions);return this._bye(e,i)}case e.SessionState.Terminating:i+=" However this session is already terminating.","function"==typeof this.cancel?i+=" Perhaps you have already called Inviter.cancel()?":"function"==typeof this.reject&&(i+=" Perhaps you have already called Session.bye()?");break;case e.SessionState.Terminated:i+=" However this session is already terminated.";break;default:throw new Error("Unknown state")}return this.logger.error(i),Promise.reject(new Error(`Invalid session state ${this.state}`))}info(t={}){if(this.state!==e.SessionState.Established){const e="Session.info() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const i=t.requestDelegate,r=this.copyRequestOptions(t.requestOptions);return this._info(i,r)}invite(t={}){if(this.logger.log("Session.invite"),this.state!==e.SessionState.Established)return Promise.reject(new Error(`Invalid session state ${this.state}`));if(this.pendingReinvite)return Promise.reject(new c("Reinvite in progress. Please wait until complete, then try again."));this.pendingReinvite=!0,t.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiersReInvite=t.sessionDescriptionHandlerModifiers),t.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptionsReInvite=t.sessionDescriptionHandlerOptions);const i={onAccept:i=>{const r=q(i.message);if(!r)return this.logger.error("Received 2xx response to re-INVITE without a session description"),this.ackAndBye(i,400,"Missing session description"),this.stateTransition(e.SessionState.Terminated),void(this.pendingReinvite=!1);if(t.withoutSdp){const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setOfferAndGetAnswer(r,s).then(e=>{i.ack({body:e})}).catch(t=>{this.logger.error("Failed to handle offer in 2xx response to re-INVITE"),this.logger.error(t.message),this.state===e.SessionState.Terminated?i.ack():(this.ackAndBye(i,488,"Bad Media Description"),this.stateTransition(e.SessionState.Terminated))}).then(()=>{this.pendingReinvite=!1,t.requestDelegate&&t.requestDelegate.onAccept&&t.requestDelegate.onAccept(i)})}else{const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setAnswer(r,s).then(()=>{i.ack()}).catch(t=>{this.logger.error("Failed to handle answer in 2xx response to re-INVITE"),this.logger.error(t.message),this.state!==e.SessionState.Terminated?(this.ackAndBye(i,488,"Bad Media Description"),this.stateTransition(e.SessionState.Terminated)):i.ack()}).then(()=>{this.pendingReinvite=!1,t.requestDelegate&&t.requestDelegate.onAccept&&t.requestDelegate.onAccept(i)})}},onProgress:e=>{},onRedirect:e=>{},onReject:i=>{this.logger.warn("Received a non-2xx response to re-INVITE"),this.pendingReinvite=!1,t.withoutSdp?t.requestDelegate&&t.requestDelegate.onReject&&t.requestDelegate.onReject(i):this.rollbackOffer().catch(t=>{if(this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),this.logger.error(t.message),this.state!==e.SessionState.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const t=[];t.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:t}),this.stateTransition(e.SessionState.Terminated)}}).then(()=>{t.requestDelegate&&t.requestDelegate.onReject&&t.requestDelegate.onReject(i)})},onTrying:e=>{}},r=t.requestOptions||{};if(r.extraHeaders=(r.extraHeaders||[]).slice(),r.extraHeaders.push("Allow: "+V.toString()),r.extraHeaders.push("Contact: "+this._contact),t.withoutSdp){if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return Promise.resolve(this.dialog.invite(i,r))}const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(s).then(e=>{if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return r.body=e,this.dialog.invite(i,r)}).catch(e=>{throw this.logger.error(e.message),this.logger.error("Failed to send re-INVITE"),this.pendingReinvite=!1,e})}message(t={}){if(this.state!==e.SessionState.Established){const e="Session.message() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const i=t.requestDelegate,r=this.copyRequestOptions(t.requestOptions);return this._message(i,r)}refer(t,i={}){if(this.state!==e.SessionState.Established){const e="Session.refer() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}if(t instanceof X&&!t.dialog){const e="Session.refer() may only be called with session which is established. You are perhaps attempting to attended transfer to a target for which there is not dialog yet established. Perhaps you are attempting a 'semi-attended' tansfer? Regardless, this is not supported. The recommended approached is to check to see if the target Session is in the Established state before calling refer(); if the state is not Established you may proceed by falling back using a URI as the target (blind transfer).";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const r=i.requestDelegate,s=this.copyRequestOptions(i.requestOptions);return s.extraHeaders=s.extraHeaders?s.extraHeaders.concat(this.referExtraHeaders(this.referToString(t))):this.referExtraHeaders(this.referToString(t)),this._refer(i.onNotify,r,s)}_bye(t,i){if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));const r=this.dialog;switch(r.sessionState){case N.Initial:case N.Early:throw new Error(`Invalid dialog state ${r.sessionState}`);case N.AckWait:return this.stateTransition(e.SessionState.Terminating),new Promise(s=>{r.delegate={onAck:()=>{const n=r.bye(t,i);return this.stateTransition(e.SessionState.Terminated),s(n),Promise.resolve()},onAckTimeout:()=>{const n=r.bye(t,i);this.stateTransition(e.SessionState.Terminated),s(n)}}});case N.Confirmed:{const s=r.bye(t,i);return this.stateTransition(e.SessionState.Terminated),Promise.resolve(s)}case N.Terminated:throw new Error(`Invalid dialog state ${r.sessionState}`);default:throw new Error("Unrecognized state.")}}_info(e,t){return this.dialog?Promise.resolve(this.dialog.info(e,t)):Promise.reject(new Error("Session dialog undefined."))}_message(e,t){return this.dialog?Promise.resolve(this.dialog.message(e,t)):Promise.reject(new Error("Session dialog undefined."))}_refer(e,t,i){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,i))):Promise.reject(new Error("Session dialog undefined."))}ackAndBye(e,t,i){e.ack();const r=[];t&&r.push("Reason: "+this.getReasonHeaderValue(t,i)),e.session.bye(void 0,{extraHeaders:r})}onAckRequest(t){if(this.logger.log("Session.onAckRequest"),this.state!==e.SessionState.Established&&this.state!==e.SessionState.Terminating)return this.logger.error(`ACK received while in state ${this.state}, dropping request`),Promise.resolve();const i=this.dialog;if(!i)throw new Error("Dialog undefined.");const r={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};if(this.delegate&&this.delegate.onAck){const e=new u(t);this.delegate.onAck(e)}switch(this.pendingReinviteAck=!1,i.signalingState){case F.Initial:{this.logger.error(`Invalid signaling state ${i.signalingState}.`);const t=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return i.bye(void 0,{extraHeaders:t}),this.stateTransition(e.SessionState.Terminated),Promise.resolve()}case F.Stable:{const s=q(t.message);return s?"render"===s.contentDisposition?(this._renderbody=s.content,this._rendertype=s.contentType,Promise.resolve()):"session"!==s.contentDisposition?Promise.resolve():this.setAnswer(s,r).catch(t=>{this.logger.error(t.message);const r=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];i.bye(void 0,{extraHeaders:r}),this.stateTransition(e.SessionState.Terminated)}):Promise.resolve()}case F.HaveLocalOffer:{this.logger.error(`Invalid signaling state ${i.signalingState}.`);const t=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return i.bye(void 0,{extraHeaders:t}),this.stateTransition(e.SessionState.Terminated),Promise.resolve()}case F.HaveRemoteOffer:{this.logger.error(`Invalid signaling state ${i.signalingState}.`);const t=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return i.bye(void 0,{extraHeaders:t}),this.stateTransition(e.SessionState.Terminated),Promise.resolve()}case F.Closed:default:throw new Error(`Invalid signaling state ${i.signalingState}.`)}}onByeRequest(t){if(this.logger.log("Session.onByeRequest"),this.state===e.SessionState.Established){if(this.delegate&&this.delegate.onBye){const e=new g(t);this.delegate.onBye(e)}else t.accept();this.stateTransition(e.SessionState.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(t){if(this.logger.log("Session.onInfoRequest"),this.state===e.SessionState.Established)if(this.delegate&&this.delegate.onInfo){const e=new v(t);this.delegate.onInfo(e)}else t.accept();else this.logger.error(`INFO received while in state ${this.state}, dropping request`)}onInviteRequest(t){if(this.logger.log("Session.onInviteRequest"),this.state!==e.SessionState.Established)return void this.logger.error(`INVITE received while in state ${this.state}, dropping request`);this.pendingReinviteAck=!0;const i=["Contact: "+this._contact];if(t.message.hasHeader("P-Asserted-Identity")){const e=t.message.getHeader("P-Asserted-Identity");if(!e)throw new Error("Header undefined.");this._assertedIdentity=E.nameAddrHeaderParse(e)}const r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(r,t).then(e=>{const r=t.accept({statusCode:200,extraHeaders:i,body:e});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(t.message,r.message,200)}).catch(i=>{if(this.logger.error(i.message),this.logger.error("Failed to handle to re-INVITE request"),!this.dialog)throw new Error("Dialog undefined.");if(this.logger.error(this.dialog.signalingState),this.dialog.signalingState===F.Stable){const e=t.reject({statusCode:488});return void(this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(t.message,e.message,488))}this.rollbackOffer().then(()=>{const e=t.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(t.message,e.message,488)}).catch(i=>{this.logger.error(i.message),this.logger.error("Failed to rollback offer on re-INVITE request");const r=t.reject({statusCode:488});if(this.state!==e.SessionState.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const t=[];t.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:t}),this.stateTransition(e.SessionState.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(t.message,r.message,488)})})}onMessageRequest(t){if(this.logger.log("Session.onMessageRequest"),this.state===e.SessionState.Established)if(this.delegate&&this.delegate.onMessage){const e=new K(t);this.delegate.onMessage(e)}else t.accept();else this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`)}onNotifyRequest(t){if(this.logger.log("Session.onNotifyRequest"),this.state===e.SessionState.Established){if(this.onNotify){const e=new z(t);return void this.onNotify(e)}if(this.delegate&&this.delegate.onNotify){const e=new z(t);this.delegate.onNotify(e)}else t.accept()}else this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`)}onPrackRequest(t){if(this.logger.log("Session.onPrackRequest"),this.state===e.SessionState.Established)throw new Error("Unimplemented.");this.logger.error(`PRACK received while in state ${this.state}, dropping request`)}onReferRequest(t){if(this.logger.log("Session.onReferRequest"),this.state!==e.SessionState.Established)return void this.logger.error(`REFER received while in state ${this.state}, dropping request`);if(!t.message.hasHeader("refer-to"))return this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),void t.reject();const i=new Y(t,this);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(i):(this.logger.log("No delegate available to handle REFER, automatically accepting and following."),i.accept().then(()=>i.makeInviter(this._referralInviterOptions).invite()).catch(e=>{this.logger.error(e.message)}))}generateResponseOfferAnswer(e,t){if(this.dialog)return this.generateResponseOfferAnswerInDialog(t,e).catch(t=>{var i;throw null===(i=this.userAgent.configuration)||void 0===i||i.errorCallback({ERR_MESSAGE:t.message,CODE:"480",TIMESTAMP:J(),CALLID:e.message.callId,INVITE:e.message.toString(),ENTRY:"session: generateResponseOfferAnswer generateResponseOfferAnswerInDialog catch"}),t});const i=q(e.message);return i&&"session"===i.contentDisposition?this.setOfferAndGetAnswer(i,t,e).catch(t=>{var i;throw null===(i=this.userAgent.configuration)||void 0===i||i.errorCallback({ERR_MESSAGE:t.message,CODE:"480",TIMESTAMP:J(),CALLID:e.message.callId,INVITE:e.message.toString(),ENTRY:"session: generateResponseOfferAnswer setOfferAndGetAnswer catch"}),t}):this.getOffer(t,e).catch(t=>{var i;throw null===(i=this.userAgent.configuration)||void 0===i||i.errorCallback({ERR_MESSAGE:t.message,CODE:"480",TIMESTAMP:J(),CALLID:e.message.callId,INVITE:e.message.toString(),ENTRY:"session: generateResponseOfferAnswer getOffer catch"}),t})}generateResponseOfferAnswerInDialog(t,i){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case F.Initial:return this.getOffer(t,i).catch(e=>{var t;throw null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:(null==i?void 0:i.message.callId)||"",INVITE:(null==i?void 0:i.message.toString())||"",ENTRY:"session: generateResponseOfferAnswerInDialog SignalingState.Initial getOffer catch"}),e});case F.HaveLocalOffer:return Promise.resolve(void 0);case F.HaveRemoteOffer:if(!this.dialog.offer)throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`);return this.setOfferAndGetAnswer(this.dialog.offer,t,i).catch(e=>{var t;throw null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:(null==i?void 0:i.message.callId)||"",INVITE:(null==i?void 0:i.message.toString())||"",ENTRY:"session: generateResponseOfferAnswerInDialog setOfferAndGetAnswer catch"}),e});case F.Stable:return this.state!==e.SessionState.Established?Promise.resolve(void 0):this.getOffer(t,i).catch(e=>{var t;throw null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:(null==i?void 0:i.message.callId)||"",INVITE:(null==i?void 0:i.message.toString())||"",ENTRY:"session: generateResponseOfferAnswerInDialog SignalingState.Stable getOffer catch"}),e});case F.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}getOffer(e,t){var i;try{const i=this.setupSessionDescriptionHandler(),r=e.sessionDescriptionHandlerOptions,s=e.sessionDescriptionHandlerModifiers;return i.getDescription(r,s).catch(e=>{var i;throw null===(i=this.userAgent.configuration)||void 0===i||i.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:(null==t?void 0:t.message.callId)||"",INVITE:(null==t?void 0:t.message.toString())||"",ENTRY:"session: getOffer sdh.getDescription catch"}),e}).then(e=>M(e)).catch(e=>{this.logger.error("Session.getOffer: SDH getDescription rejected...");const t=e instanceof Error?e:new Error("Session.getOffer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.getOffer: SDH getDescription threw...");const r=e instanceof Error?e:new Error(e);return this.logger.error(r.message),null===(i=this.userAgent.configuration)||void 0===i||i.errorCallback({ERR_MESSAGE:r.message,CODE:"480",TIMESTAMP:J(),CALLID:(null==t?void 0:t.message.callId)||"",INVITE:(null==t?void 0:t.message.toString())||"",ENTRY:"session: getOffer setupSessionDescriptionHandler catch"}),Promise.reject(r)}}rollbackOffer(){try{const e=this.setupSessionDescriptionHandler();return void 0===e.rollbackDescription?Promise.resolve():e.rollbackDescription().catch(e=>{this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");const t=e instanceof Error?e:new Error("Session.rollbackOffer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setAnswer(e,t){let i,r,s;try{if(i=this.setupSessionDescriptionHandler(),r=t.sessionDescriptionHandlerOptions,s=t.sessionDescriptionHandlerModifiers,!i.hasDescription(e.contentType))return Promise.reject(new a)}catch(e){this.logger.error("Session.setAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return i.setDescription(e.content,r,s).catch(e=>{this.logger.error("Session.setAnswer: SDH setDescription rejected...");const t=e instanceof Error?e:new Error("Session.setAnswer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.setAnswer: SDH setDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setOfferAndGetAnswer(e,t,i){var r;let s,n,o;try{if(s=this.setupSessionDescriptionHandler(),n=t.sessionDescriptionHandlerOptions,o=t.sessionDescriptionHandlerModifiers,!s.hasDescription(e.contentType))return Promise.reject(new a)}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),null===(r=this.userAgent.configuration)||void 0===r||r.errorCallback({ERR_MESSAGE:t.message,CODE:"480",TIMESTAMP:J(),CALLID:(null==i?void 0:i.message.callId)||"",INVITE:(null==i?void 0:i.message.toString())||"",ENTRY:"session: setOfferAndGetAnswer setupSessionDescriptionHandler catch"}),Promise.reject(t)}try{return s.setDescription(e.content,n,o).catch(e=>{var t;throw null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:(null==i?void 0:i.message.callId)||"",INVITE:(null==i?void 0:i.message.toString())||"",ENTRY:"session: setOfferAndGetAnswer sdh.setDescription catch"}),e}).then(()=>s.getDescription(n,o)).catch(e=>{var t;throw null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:(null==i?void 0:i.message.callId)||"",INVITE:(null==i?void 0:i.message.toString())||"",ENTRY:"session: setOfferAndGetAnswer sdh.getDescription catch"}),e}).then(e=>M(e)).catch(e=>{this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");const t=e instanceof Error?e:new Error("Session.setOfferAndGetAnswer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setSessionDescriptionHandler(e){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=e}setupSessionDescriptionHandler(){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}stateTransition(t){const i=()=>{throw new Error(`Invalid state transition from ${this._state} to ${t}`)};switch(this._state){case e.SessionState.Initial:t!==e.SessionState.Establishing&&t!==e.SessionState.Established&&t!==e.SessionState.Terminating&&t!==e.SessionState.Terminated&&i();break;case e.SessionState.Establishing:t!==e.SessionState.Established&&t!==e.SessionState.Terminating&&t!==e.SessionState.Terminated&&i();break;case e.SessionState.Established:t!==e.SessionState.Terminating&&t!==e.SessionState.Terminated&&i();break;case e.SessionState.Terminating:t!==e.SessionState.Terminated&&i();break;case e.SessionState.Terminated:i();break;default:throw new Error("Unrecognized state.")}this._state=t,this.logger.log(`Session ${this.id} transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),t===e.SessionState.Terminated&&this.dispose()}copyRequestOptions(e={}){return{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}}getReasonHeaderValue(e,t){const i=e;let r=P(e);return!r&&t&&(r=t),"SIP;cause="+i+';text="'+r+'"'}referExtraHeaders(e){const 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}referToString(e){let t;if(e instanceof y)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");const i=e.remoteIdentity.friendlyName,r=e.dialog.remoteTarget.toString(),s=e.dialog.callId,n=e.dialog.remoteTag,o=e.dialog.localTag;t=`"${i}" <${r}?Replaces=${encodeURIComponent(`${s};to-tag=${n};from-tag=${o}`)}>`}return t}}var Q;!function(e){e.Required="Required",e.Supported="Supported",e.Unsupported="Unsupported"}(Q||(Q={}));const ee={"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};class te extends X{constructor(t,i){super(t),Object.defineProperty(this,"incomingInviteRequest",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"disposed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"expiresTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isCanceled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"rel100",{enumerable:!0,configurable:!0,writable:!0,value:"none"}),Object.defineProperty(this,"rseq",{enumerable:!0,configurable:!0,writable:!0,value:Math.floor(1e4*Math.random())}),Object.defineProperty(this,"userNoAnswerTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"waitingForPrack",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"waitingForPrackPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"waitingForPrackResolve",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"waitingForPrackReject",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logger=t.getLogger("sip.Invitation");const r=this.incomingInviteRequest.message,s=r.getHeader("require");s&&s.toLowerCase().includes("100rel")&&(this.rel100="required");const n=r.getHeader("supported");if(n&&n.toLowerCase().includes("100rel")&&(this.rel100="supported"),r.toTag=i.toTag,"string"!=typeof r.toTag)throw new TypeError("toTag should have been a string.");if(this.userNoAnswerTimer=setTimeout(()=>{var t;null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:"NOT ERROR",CODE:"480",TIMESTAMP:J(),CALLID:this.incomingInviteRequest.message.callId,INVITE:this.incomingInviteRequest.message.toString(),ENTRY:"invitation: constructor userNoAnswerTimer "+(this.userAgent.configuration.noAnswerTimeout?1e3*this.userAgent.configuration.noAnswerTimeout:6e4)}),i.reject({statusCode:480}),this.stateTransition(e.SessionState.Terminated)},this.userAgent.configuration.noAnswerTimeout?1e3*this.userAgent.configuration.noAnswerTimeout:6e4),r.hasHeader("expires")){const t=1e3*Number(r.getHeader("expires")||0);this.expiresTimer=setTimeout(()=>{this.state===e.SessionState.Initial&&(i.reject({statusCode:487}),this.stateTransition(e.SessionState.Terminated))},t)}const o=this.request.getHeader("P-Asserted-Identity");o&&(this._assertedIdentity=E.nameAddrHeaderParse(o)),this._contact=this.userAgent.contact.toString();const a=r.parseHeader("Content-Disposition");a&&"render"===a.type&&(this._renderbody=r.body,this._rendertype=r.getHeader("Content-Type")),this._id=r.callId+r.fromTag,this.userAgent._sessions[this._id]=this}dispose(){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 e.SessionState.Initial:case e.SessionState.Establishing:return this.reject().then(()=>super.dispose());case e.SessionState.Established:case e.SessionState.Terminating:case e.SessionState.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get autoSendAnInitialProvisionalResponse(){return"required"!==this.rel100&&this.userAgent.configuration.sendInitialProvisionalResponse}get body(){return this.incomingInviteRequest.message.body}get localIdentity(){return this.request.to}get remoteIdentity(){return this.request.from}get request(){return this.incomingInviteRequest.message}accept(t={}){if(this.logger.log("Invitation.accept"),this.state!==e.SessionState.Initial){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}return t.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=t.sessionDescriptionHandlerModifiers),t.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=t.sessionDescriptionHandlerOptions),this.stateTransition(e.SessionState.Establishing),this.sendAccept(t).then(({message:i,session:r})=>{r.delegate={onAck:e=>{const i=this.onAckRequest(e);return t.onAck&&t.onAck(e),i},onAckTimeout:()=>{this.onAckTimeout(),t.onAckTimeout&&t.onAckTimeout()},onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=r,this.stateTransition(e.SessionState.Established),this._replacee&&this._replacee._bye()}).catch(e=>{var t;return null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:this.incomingInviteRequest.message.callId,INVITE:this.incomingInviteRequest.message.toString(),ENTRY:"invitation: accept sendAccept catch"}),this.handleResponseError(e)})}progress(t={}){if(this.logger.log("Invitation.progress"),this.state!==e.SessionState.Initial){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const i=t.statusCode||180;if(i<100||i>199)throw new TypeError("Invalid statusCode: "+i);return t.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=t.sessionDescriptionHandlerModifiers),t.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=t.sessionDescriptionHandlerOptions),this.waitingForPrack?(this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),Promise.resolve()):100===t.statusCode?this.sendProgressTrying().then(()=>{}).catch(e=>{var t;return null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:this.incomingInviteRequest.message.callId,INVITE:this.incomingInviteRequest.message.toString(),ENTRY:"invitation: progress sendProgressTrying catch"}),this.handleResponseError(e)}):"required"===this.rel100||"supported"===this.rel100&&t.rel100||"supported"===this.rel100&&this.userAgent.configuration.sipExtension100rel===Q.Required?this.sendProgressReliableWaitForPrack(t).then(()=>{}).catch(e=>{var t;return null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:this.incomingInviteRequest.message.callId,INVITE:this.incomingInviteRequest.message.toString(),ENTRY:"invitation: progress sendProgressReliableWaitForPrack catch"}),this.handleResponseError(e)}):this.sendProgress(t).then(()=>{}).catch(e=>{var t;return null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:this.incomingInviteRequest.message.callId,INVITE:this.incomingInviteRequest.message.toString(),ENTRY:"invitation: progress rel100 sendProgress catch"}),this.handleResponseError(e)})}reject(t={}){if(this.logger.log("Invitation.reject"),this.state!==e.SessionState.Initial&&this.state!==e.SessionState.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const i=t.statusCode||480,r=t.reasonPhrase?t.reasonPhrase:P(i),s=t.extraHeaders||[];if(i<300||i>699)throw new TypeError("Invalid statusCode: "+i);const n=t.body?M(t.body):void 0;return i<400?this.incomingInviteRequest.redirect([],{statusCode:i,reasonPhrase:r,extraHeaders:s,body:n}):this.incomingInviteRequest.reject({statusCode:i,reasonPhrase:r,extraHeaders:s,body:n}),this.stateTransition(e.SessionState.Terminated),Promise.resolve()}_onCancel(t){if(this.logger.log("Invitation._onCancel"),this.state===e.SessionState.Initial||this.state===e.SessionState.Establishing){if(this.delegate&&this.delegate.onCancel){const e=new f(t);this.delegate.onCancel(e)}this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(e.SessionState.Terminated)}else this.logger.error(`CANCEL received while in state ${this.state}, dropping request`)}handlePrackOfferAnswer(e){if(!this.dialog)throw new Error("Dialog undefined.");const t=q(e.message);if(!t||"session"!==t.contentDisposition)return Promise.resolve(void 0);const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case F.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case F.Stable:return this.setAnswer(t,i).then(()=>{});case F.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case F.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,i);case F.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}handleResponseError(t){let i=480;if(t instanceof Error?this.logger.error(t.message):this.logger.error(t),t instanceof a?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),i=415):t instanceof l?this.logger.error("A session description handler occurred while sending response"):t instanceof h?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):t instanceof W&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===e.SessionState.Initial||this.state===e.SessionState.Establishing)try{this.incomingInviteRequest.reject({statusCode:i}),this.stateTransition(e.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 t;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.")}onAckTimeout(){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(e.SessionState.Terminated)}sendAccept(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.extraHeaders||[];return this.waitingForPrack?this.waitForArrivalOfPrack().then(()=>clearTimeout(this.userNoAnswerTimer)).then(()=>this.generateResponseOfferAnswer(this.incomingInviteRequest,t)).catch(e=>{var t;throw null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:this.incomingInviteRequest.message.callId,INVITE:this.incomingInviteRequest.message.toString(),ENTRY:"invitation: sendAccept waitForArrivalOfPrack generateResponseOfferAnswer catch"}),e}).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:i})):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,t).catch(e=>{var t;throw null===(t=this.userAgent.configuration)||void 0===t||t.errorCallback({ERR_MESSAGE:e.message,CODE:"480",TIMESTAMP:J(),CALLID:this.incomingInviteRequest.message.callId,INVITE:this.incomingInviteRequest.message.toString(),ENTRY:"invitation: sendAccept generateResponseOfferAnswer catch"}),e}).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:i})))}sendProgress(e={}){const t=e.statusCode||180,i=e.reasonPhrase,r=(e.extraHeaders||[]).slice(),s=e.body?M(e.body):void 0;if(183===t&&!s)return this.sendProgressWithSDP(e);try{const e=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:i,extraHeaders:r,body:s});return this._dialog=e.session,Promise.resolve(e)}catch(e){return Promise.reject(e)}}sendProgressWithSDP(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.statusCode||183,r=e.reasonPhrase,s=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>this.incomingInviteRequest.progress({statusCode:i,reasonPhrase:r,extraHeaders:s,body:e})).then(e=>(this._dialog=e.session,e))}sendProgressReliable(e={}){return e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this.sendProgressWithSDP(e)}sendProgressReliableWaitForPrack(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.statusCode||183,r=e.reasonPhrase,s=(e.extraHeaders||[]).slice();let n;return s.push("Require: 100rel"),s.push("RSeq: "+this.rseq++),new Promise((e,o)=>{this.waitingForPrack=!0,this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>(n=e,this.incomingInviteRequest.progress({statusCode:i,reasonPhrase:r,extraHeaders:s,body:n}))).then(t=>{let a,c;this._dialog=t.session,t.session.delegate={onPrack:i=>{a=i,clearTimeout(l),clearTimeout(g),this.waitingForPrack&&(this.waitingForPrack=!1,this.handlePrackOfferAnswer(a).then(i=>{try{c=a.accept({statusCode:200,body:i}),this.prackArrived(),e({prackRequest:a,prackResponse:c,progressResponse:t})}catch(e){o(e)}}).catch(e=>o(e)))}};const l=setTimeout(()=>{this.waitingForPrack&&(this.waitingForPrack=!1,this.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(g),this.reject({statusCode:504}).then(()=>o(new h)).catch(e=>o(e)))},64*B.T1),d=()=>{try{this.incomingInviteRequest.progress({statusCode:i,reasonPhrase:r,extraHeaders:s,body:n})}catch(e){return this.waitingForPrack=!1,void o(e)}g=setTimeout(d,u*=2)};let u=B.T1,g=setTimeout(d,u)}).catch(e=>{this.waitingForPrack=!1,o(e)})})}sendProgressTrying(){try{const e=this.incomingInviteRequest.trying();return Promise.resolve(e)}catch(e){return Promise.reject(e)}}waitForArrivalOfPrack(){if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise((e,t)=>{this.waitingForPrackResolve=e,this.waitingForPrackReject=t}),this.waitingForPrackPromise}prackArrived(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}prackNeverArrived(){this.waitingForPrackReject&&this.waitingForPrackReject(new h),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}class ie extends X{constructor(e,t,i={}){super(e,i),Object.defineProperty(this,"_referred",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"disposed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"earlyMedia",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"earlyMediaDialog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"earlyMediaSessionDescriptionHandlers",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"fromTag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isCanceled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"inviteWithoutSdp",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"outgoingInviteRequest",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outgoingRequestMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logger=e.getLogger("sip.Inviter"),this.earlyMedia=void 0!==i.earlyMedia?i.earlyMedia:this.earlyMedia,this.fromTag=A(),this.inviteWithoutSdp=void 0!==i.inviteWithoutSdp?i.inviteWithoutSdp:this.inviteWithoutSdp;const r=Object.assign({},i);r.params=Object.assign({},i.params);const s=i.anonymous||!1,n=e.contact.toString({anonymous:s,outbound:s?!e.contact.tempGruu:!e.contact.pubGruu});s&&e.configuration.uri&&(r.params.fromDisplayName="Anonymous",r.params.fromUri="sip:anonymous@anonymous.invalid");let o=e.userAgentCore.configuration.aor;if(r.params.fromUri&&(o="string"==typeof r.params.fromUri?E.URIParse(r.params.fromUri):r.params.fromUri),!o)throw new TypeError("Invalid from URI: "+r.params.fromUri);let a=t;if(r.params.toUri&&(a="string"==typeof r.params.toUri?E.URIParse(r.params.toUri):r.params.toUri),!a)throw new TypeError("Invalid to URI: "+r.params.toUri);const c=Object.assign({},r.params);c.fromTag=this.fromTag;const l=(r.extraHeaders||[]).slice();s&&e.configuration.uri&&(l.push("P-Preferred-Identity: "+e.configuration.uri.toString()),l.push("Privacy: id")),l.push("Contact: "+n),l.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),e.configuration.sipExtension100rel===Q.Required&&l.push("Require: 100rel"),e.configuration.sipExtensionReplaces===Q.Required&&l.push("Require: replaces"),r.extraHeaders=l;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(G.INVITE,t,o,a,c,l,undefined),this._contact=n,this._referralInviterOptions=r,this._renderbody=i.renderbody,this._rendertype=i.rendertype,i.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=i.sessionDescriptionHandlerModifiers),i.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=i.sessionDescriptionHandlerOptions),i.sessionDescriptionHandlerModifiersReInvite&&(this.sessionDescriptionHandlerModifiersReInvite=i.sessionDescriptionHandlerModifiersReInvite),i.sessionDescriptionHandlerOptionsReInvite&&(this.sessionDescriptionHandlerOptionsReInvite=i.sessionDescriptionHandlerOptionsReInvite),this._id=this.outgoingRequestMessage.callId+this.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.disposeEarlyMedia(),this.state){case e.SessionState.Initial:case e.SessionState.Establishing:return this.cancel().then(()=>super.dispose());case e.SessionState.Established:case e.SessionState.Terminating:case e.SessionState.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get body(){return this.outgoingRequestMessage.body}get localIdentity(){return this.outgoingRequestMessage.from}get remoteIdentity(){return this.outgoingRequestMessage.to}get request(){return this.outgoingRequestMessage}cancel(t={}){if(this.logger.log("Inviter.cancel"),this.state!==e.SessionState.Initial&&this.state!==e.SessionState.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}if(this.isCanceled=!0,this.stateTransition(e.SessionState.Terminating),this.outgoingInviteRequest){let e;t.statusCode&&t.reasonPhrase&&(e=function(e,t){if(e&&e<200||e>699)throw new TypeError("Invalid statusCode: "+e);if(e)return"SIP;cause="+e+';text="'+(P(e)||t)+'"'}(t.statusCode,t.reasonPhrase)),this.outgoingInviteRequest.cancel(e,t)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(e.SessionState.Terminated);return Promise.resolve()}invite(t={}){if(this.logger.log("Inviter.invite"),this.state!==e.SessionState.Initial)return super.invite(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(e.SessionState.Establishing),Promise.resolve(this.sendInvite(t));const i={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(i).then(i=>(this.outgoingRequestMessage.body={body:i.content,contentType:i.contentType},this.stateTransition(e.SessionState.Establishing),this.sendInvite(t))).catch(t=>{throw this.logger.log(t.message),this.state!==e.SessionState.Terminated&&this.stateTransition(e.SessionState.Terminated),t})}sendInvite(t={}){return this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:i=>this.dialog?(this.logger.log("Additional confirmed dialog, sending ACK and BYE"),void this.ackAndBye(i)):this.isCanceled?(this.logger.log("Canceled session accepted, sending ACK and BYE"),this.ackAndBye(i),void this.stateTransition(e.SessionState.Terminated)):(this.notifyReferer(i),void this.onAccept(i).then(()=>{this.disposeEarlyMedia()}).catch(()=>{this.disposeEarlyMedia()}).then(()=>{t.requestDelegate&&t.requestDelegate.onAccept&&t.requestDelegate.onAccept(i)})),onProgress:e=>{this.isCanceled||(this.notifyReferer(e),this.onProgress(e).catch(()=>{this.disposeEarlyMedia()}).then(()=>{t.requestDelegate&&t.requestDelegate.onProgress&&t.requestDelegate.onProgress(e)}))},onRedirect:e=>{this.notifyReferer(e),this.onRedirect(e),t.requestDelegate&&t.requestDelegate.onRedirect&&t.requestDelegate.onRedirect(e)},onReject:e=>{this.notifyReferer(e),this.onReject(e),t.requestDelegate&&t.requestDelegate.onReject&&t.requestDelegate.onReject(e)},onTrying:e=>{this.notifyReferer(e),this.onTrying(e),t.requestDelegate&&t.requestDelegate.onTrying&&t.requestDelegate.onTrying(e)}}),this.outgoingInviteRequest}disposeEarlyMedia(){this.earlyMediaSessionDescriptionHandlers.forEach(e=>{e.close()}),this.earlyMediaSessionDescriptionHandlers.clear()}notifyReferer(e){if(!this._referred)return;if(!(this._referred instanceof X))throw new Error("Referred session not instance of session");if(!this._referred.dialog)return;if(!e.message.statusCode)throw new Error("Status code undefined.");if(!e.message.reasonPhrase)throw new Error("Reason phrase undefined.");const t=`SIP/2.0 ${e.message.statusCode} ${e.message.reasonPhrase}`.trim();this._referred.dialog.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:t}}).delegate={onReject:()=>{this._referred=void 0}}}onAccept(t){if(this.logger.log("Inviter.onAccept"),this.state!==e.SessionState.Establishing)return this.logger.error(`Accept received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));const i=t.message,r=t.session;switch(i.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=E.nameAddrHeaderParse(i.getHeader("P-Asserted-Identity"))),r.delegate={onAck:e=>this.onAckRequest(e),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=r,r.signalingState){case F.Initial:case F.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(t,400,"Missing session description"),this.stateTransition(e.SessionState.Terminated),Promise.reject(new Error("Bad Media Description"));case F.HaveRemoteOffer:{if(!this._dialog.offer)throw new Error(`Session offer undefined in signaling state ${this._dialog.signalingState}.`);const i={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,i).then(i=>{t.ack({body:i}),this.stateTransition(e.SessionState.Established)}).catch(i=>{throw this.ackAndBye(t,488,"Invalid session description"),this.stateTransition(e.SessionState.Terminated),i})}case F.Stable:{if(this.earlyMediaSessionDescriptionHandlers.size>0){const i=this.earlyMediaSessionDescriptionHandlers.get(r.id);if(!i)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(i),this.earlyMediaSessionDescriptionHandlers.delete(r.id),t.ack(),this.stateTransition(e.SessionState.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==r){if(this.earlyMedia){const e="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.";this.logger.error(e)}const i=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(i.message),this.ackAndBye(t,488,"Not Acceptable Here"),this.stateTransition(e.SessionState.Terminated),Promise.reject(i)}return t.ack(),this.stateTransition(e.SessionState.Established),Promise.resolve()}const i=r.answer;if(!i)throw new Error("Answer is undefined.");const s={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(i,s).then(()=>{let i;this._renderbody&&this._rendertype&&(i={body:{contentDisposition:"render",contentType:this._rendertype,content:this._renderbody}}),t.ack(i),this.stateTransition(e.SessionState.Established)}).catch(i=>{throw this.logger.error(i.message),this.ackAndBye(t,488,"Not Acceptable Here"),this.stateTransition(e.SessionState.Terminated),i})}case F.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onProgress(t){var i;if(this.logger.log("Inviter.onProgress"),this.state!==e.SessionState.Establishing)return this.logger.error(`Progress received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));if(!this.outgoingInviteRequest)throw new Error("Outgoing INVITE request undefined.");const r=t.message,s=t.session;r.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=E.nameAddrHeaderParse(r.getHeader("P-Asserted-Identity")));const n=r.getHeader("require"),o=r.getHeader("rseq"),a=!!(n&&n.includes("100rel")&&o?Number(o):void 0),c=[];switch(a&&c.push("RAck: "+r.getHeader("rseq")+" "+r.getHeader("cseq")),s.signalingState){case F.Initial:return a&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),t.prack({extraHeaders:c})),Promise.resolve();case F.HaveLocalOffer:return a&&t.prack({extraHeaders:c}),Promise.resolve();case F.HaveRemoteOffer:if(!a)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();{const n=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(i=this.delegate)||void 0===i?void 0:i.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(n,!0),this.earlyMediaSessionDescriptionHandlers.set(s.id,n),n.setDescription(r.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then(()=>n.getDescription(this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers)).then(e=>{const i={contentDisposition:"session",contentType:e.contentType,content:e.body};t.prack({extraHeaders:c,body:i})}).catch(t=>{throw this.stateTransition(e.SessionState.Terminated),t})}case F.Stable:if(a&&t.prack({extraHeaders:c}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=s;const t=s.answer;if(!t)throw new Error("Answer is undefined.");const i={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(t,i).catch(t=>{throw this.stateTransition(e.SessionState.Terminated),t})}return Promise.resolve();case F.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(t){this.logger.log("Inviter.onRedirect"),this.state===e.SessionState.Establishing||this.state===e.SessionState.Terminating?this.stateTransition(e.SessionState.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(t){this.logger.log("Inviter.onReject"),this.state===e.SessionState.Establishing||this.state===e.SessionState.Terminating?this.stateTransition(e.SessionState.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(t){this.logger.log("Inviter.onTrying"),this.state===e.SessionState.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}class re{constructor(e,t,i,r="text/plain",s={}){Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"userAgent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logger=e.getLogger("sip.Messager"),s.params=s.params||{};let n=e.userAgentCore.configuration.aor;if(s.params.fromUri&&(n="string"==typeof s.params.fromUri?E.URIParse(s.params.fromUri):s.params.fromUri),!n)throw new TypeError("Invalid from URI: "+s.params.fromUri);let o=t;if(s.params.toUri&&(o="string"==typeof s.params.toUri?E.URIParse(s.params.toUri):s.params.toUri),!o)throw new TypeError("Invalid to URI: "+s.params.toUri);const a=s.params?Object.assign({},s.params):{},c=(s.extraHeaders||[]).slice(),l={contentDisposition:"render",contentType:r,content:i};this.request=e.userAgentCore.makeOutgoingRequestMessage(G.MESSAGE,t,n,o,a,c,l),this.userAgent=e}message(e={}){return this.userAgent.userAgentCore.request(this.request,e.requestDelegate),Promise.resolve()}}var se,ne,oe,ae,ce,le,he,de,ue;!function(e){e.Initial="Initial",e.Published="Published",e.Unpublished="Unpublished",e.Terminated="Terminated"}(se||(se={})),function(e){e.Initial="Initial",e.Registered="Registered",e.Unregistered="Unregistered",e.Terminated="Terminated"}(ne||(ne={}));class ge{constructor(e,t={}){Object.defineProperty(this,"disposed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"expires",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshFrequency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"userAgent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"registrationExpiredTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"registrationTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_contacts",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_retryAfter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_state",{enumerable:!0,configurable:!0,writable:!0,value:ne.Initial}),Object.defineProperty(this,"_stateEventEmitter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_waiting",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_waitingEventEmitter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._stateEventEmitter=new p,this._waitingEventEmitter=new p,this.userAgent=e;const i=e.configuration.uri.clone();if(i.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},ge.defaultOptions()),{registrar:i}),ge.stripUndefinedProperties(t)),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=this.userAgent.instanceId:!this.options.regId&&this.options.instanceId&&(this.options.regId=1),this.options.instanceId&&-1===E.parse(this.options.instanceId,"uuid"))throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");const r=this.options.registrar,s=this.options.params&&this.options.params.fromUri||e.userAgentCore.configuration.aor,n=this.options.params&&this.options.params.toUri||e.configuration.uri,o=this.options.params||{},a=(t.extraHeaders||[]).slice();if(this.request=e.userAgentCore.makeOutgoingRequestMessage(G.REGISTER,r,s,n,o,a,void 0),this.expires=this.options.expires||ge.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||ge.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=e.getLogger("sip.Registerer"),this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];if("registrar"===e)this.logger.log("· "+e+": "+t);else this.logger.log("· "+e+": "+JSON.stringify(t))})),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}static defaultOptions(){return{expires:ge.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new y("sip","anonymous","anonymous.invalid"),refreshFrequency:ge.defaultRefreshFrequency}}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,i)=>(void 0!==e[i]&&(t[i]=e[i]),t),{})}get contacts(){return this._contacts.slice()}get retryAfter(){return this._retryAfter}get state(){return this._state}get stateChange(){return this._stateEventEmitter}dispose(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log(`Registerer ${this.id} in state ${this.state} is being disposed`),delete this.userAgent._registerers[this.id],new Promise(e=>{const t=()=>{if(!this.waiting&&this._state===ne.Registered)return this.stateChange.addListener(()=>{this.terminated(),e()},{once:!0}),void this.unregister();this.terminated(),e()};this.waiting?this.waitingChange.addListener(()=>{t()},{once:!0}):t()}))}register(e={}){if(this.state===ne.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();const e=new c("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}e.requestOptions&&(this.options=Object.assign(Object.assign({},this.options),e.requestOptions));const t=(this.options.extraHeaders||[]).slice();t.push("Contact: "+this.generateContactHeader(this.expires)),t.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=t,this.waitingToggle(!0);const i=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{let i;t.message.hasHeader("expires")&&(i=Number(t.message.getHeader("expires"))),this._contacts=t.message.getHeaders("contact");let r,s=this._contacts.length;if(!s)return this.logger.error("No Contact header in response to REGISTER, dropping response."),void this.unregistered();for(;s--;){if(r=t.message.parseHeader("contact",s),!r)throw new Error("Contact undefined");if(this.userAgent.contact.pubGruu&&w(r.uri,this.userAgent.contact.pubGruu)){i=Number(r.getParam("expires"));break}if(""===this.userAgent.configuration.contactName){if(r.uri.user===this.userAgent.contact.uri.user){i=Number(r.getParam("expires"));break}}else if(w(r.uri,this.userAgent.contact.uri)){i=Number(r.getParam("expires"));break}r=void 0}if(void 0===r)return this.logger.error("No Contact header pointing to us, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(void 0===i)return this.logger.error("Contact pointing to us is missing expires parameter, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(r.hasParam("temp-gruu")){const e=r.getParam("temp-gruu");e&&(this.userAgent.contact.tempGruu=E.URIParse(e.replace(/"/g,"")))}if(r.hasParam("pub-gruu")){const e=r.getParam("pub-gruu");e&&(this.userAgent.contact.pubGruu=E.URIParse(e.replace(/"/g,"")))}this.registered(i),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Redirect received. Not supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{if(423===t.message.statusCode)return t.message.hasHeader("min-expires")?(this.expires=Number(t.message.getHeader("min-expires")),this.waitingToggle(!1),void this.register()):(this.logger.error("423 response received for REGISTER without Min-Expires, dropping response"),this.unregistered(),void this.waitingToggle(!1));this.logger.warn(`Failed to register, status code ${t.message.statusCode}`);let i=NaN;if(500===t.message.statusCode||503===t.message.statusCode){const e=t.message.getHeader("retry-after");e&&(i=Number.parseInt(e,void 0))}this._retryAfter=isNaN(i)?void 0:i,this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this._retryAfter=void 0,this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(i)}unregister(e={}){if(this.state===ne.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==ne.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new c("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}this._state===ne.Registered||e.all||this.logger.warn("Not currently registered, but sending an unregister anyway.");const t=(e.requestOptions&&e.requestOptions.extraHeaders||[]).slice();this.request.extraHeaders=t,e.all?(t.push("Contact: *"),t.push("Expires: 0")):t.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);const i=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{this._contacts=t.message.getHeaders("contact"),this.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Unregister redirected. Not currently supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{this.logger.error(`Unregister rejected with status code ${t.message.statusCode}`),this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(i)}clearTimers(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)}generateContactHeader(e){let t=this.userAgent.contact.toString({register:!0});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(e=>{t+=";"+e}),t+=";expires="+e,t}registered(e){this.clearTimers(),this.registrationTimer=setTimeout(()=>{this.registrationTimer=void 0,this.register()},this.refreshFrequency/100*e*1e3),this.registrationExpiredTimer=setTimeout(()=>{this.logger.warn("Registration expired"),this.unregistered()},1e3*e),this._state!==ne.Registered&&this.stateTransition(ne.Registered)}unregistered(){this.clearTimers(),this._state!==ne.Unregistered&&this.stateTransition(ne.Unregistered)}terminated(){this.clearTimers(),this._state!==ne.Terminated&&this.stateTransition(ne.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case ne.Initial:e!==ne.Registered&&e!==ne.Unregistered&&e!==ne.Terminated&&t();break;case ne.Registered:e!==ne.Unregistered&&e!==ne.Terminated&&t();break;case ne.Unregistered:e!==ne.Registered&&e!==ne.Terminated&&t();break;case ne.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Registration transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===ne.Terminated&&this.dispose()}get waiting(){return this._waiting}get waitingChange(){return this._waitingEventEmitter}waitingToggle(e){if(this._waiting===e)throw new Error(`Invalid waiting transition from ${this._waiting} to ${e}`);this._waiting=e,this.logger.log(`Waiting toggled to ${this._waiting}`),this._waitingEventEmitter.emit(this._waiting)}waitingWarning(){let e="An attempt was made to send a REGISTER request while a prior one was still in progress.";e+=" RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response",e+=" from the registrar for the previous one or the previous REGISTER request has timed out.",e+=" Note that if the transport disconnects, you still must wait for the prior request to time out before",e+=" sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.",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.")}stateError(){let e=`An attempt was made to send a REGISTER request when the Registerer ${this.state===ne.Terminated?"is in 'Terminated' state":"has been disposed"}.`;e+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",e+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(e)}}Object.defineProperty(ge,"defaultExpires",{enumerable:!0,configurable:!0,writable:!0,value:600}),Object.defineProperty(ge,"defaultRefreshFrequency",{enumerable:!0,configurable:!0,writable:!0,value:99}),function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(oe||(oe={})),function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Subscribed="Subscribed",e.Terminated="Terminated"}(ae||(ae={})),function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(ce||(ce={})),function(e){e.Started="Started",e.Stopped="Stopped"}(le||(le={}));class fe{static hashStr(e,t=!1){return this.onePassHasher.start().appendStr(e).end(t)}static hashAsciiStr(e,t=!1){return this.onePassHasher.start().appendAsciiStr(e).end(t)}static _hex(e){const t=fe.hexChars,i=fe.hexOut;let r,s,n,o;for(o=0;o<4;o+=1)for(s=8*o,r=e[o],n=0;n<8;n+=2)i[s+1+n]=t.charAt(15&r),r>>>=4,i[s+0+n]=t.charAt(15&r),r>>>=4;return i.join("")}static _md5cycle(e,t){let i=e[0],r=e[1],s=e[2],n=e[3];i+=(r&s|~r&n)+t[0]-680876936|0,i=(i<<7|i>>>25)+r|0,n+=(i&r|~i&s)+t[1]-389564586|0,n=(n<<12|n>>>20)+i|0,s+=(n&i|~n&r)+t[2]+606105819|0,s=(s<<17|s>>>15)+n|0,r+=(s&n|~s&i)+t[3]-1044525330|0,r=(r<<22|r>>>10)+s|0,i+=(r&s|~r&n)+t[4]-176418897|0,i=(i<<7|i>>>25)+r|0,n+=(i&r|~i&s)+t[5]+1200080426|0,n=(n<<12|n>>>20)+i|0,s+=(n&i|~n&r)+t[6]-1473231341|0,s=(s<<17|s>>>15)+n|0,r+=(s&n|~s&i)+t[7]-45705983|0,r=(r<<22|r>>>10)+s|0,i+=(r&s|~r&n)+t[8]+1770035416|0,i=(i<<7|i>>>25)+r|0,n+=(i&r|~i&s)+t[9]-1958414417|0,n=(n<<12|n>>>20)+i|0,s+=(n&i|~n&r)+t[10]-42063|0,s=(s<<17|s>>>15)+n|0,r+=(s&n|~s&i)+t[11]-1990404162|0,r=(r<<22|r>>>10)+s|0,i+=(r&s|~r&n)+t[12]+1804603682|0,i=(i<<7|i>>>25)+r|0,n+=(i&r|~i&s)+t[13]-40341101|0,n=(n<<12|n>>>20)+i|0,s+=(n&i|~n&r)+t[14]-1502002290|0,s=(s<<17|s>>>15)+n|0,r+=(s&n|~s&i)+t[15]+1236535329|0,r=(r<<22|r>>>10)+s|0,i+=(r&n|s&~n)+t[1]-165796510|0,i=(i<<5|i>>>27)+r|0,n+=(i&s|r&~s)+t[6]-1069501632|0,n=(n<<9|n>>>23)+i|0,s+=(n&r|i&~r)+t[11]+643717713|0,s=(s<<14|s>>>18)+n|0,r+=(s&i|n&~i)+t[0]-373897302|0,r=(r<<20|r>>>12)+s|0,i+=(r&n|s&~n)+t[5]-701558691|0,i=(i<<5|i>>>27)+r|0,n+=(i&s|r&~s)+t[10]+38016083|0,n=(n<<9|n>>>23)+i|0,s+=(n&r|i&~r)+t[15]-660478335|0,s=(s<<14|s>>>18)+n|0,r+=(s&i|n&~i)+t[4]-405537848|0,r=(r<<20|r>>>12)+s|0,i+=(r&n|s&~n)+t[9]+568446438|0,i=(i<<5|i>>>27)+r|0,n+=(i&s|r&~s)+t[14]-1019803690|0,n=(n<<9|n>>>23)+i|0,s+=(n&r|i&~r)+t[3]-187363961|0,s=(s<<14|s>>>18)+n|0,r+=(s&i|n&~i)+t[8]+1163531501|0,r=(r<<20|r>>>12)+s|0,i+=(r&n|s&~n)+t[13]-1444681467|0,i=(i<<5|i>>>27)+r|0,n+=(i&s|r&~s)+t[2]-51403784|0,n=(n<<9|n>>>23)+i|0,s+=(n&r|i&~r)+t[7]+1735328473|0,s=(s<<14|s>>>18)+n|0,r+=(s&i|n&~i)+t[12]-1926607734|0,r=(r<<20|r>>>12)+s|0,i+=(r^s^n)+t[5]-378558|0,i=(i<<4|i>>>28)+r|0,n+=(i^r^s)+t[8]-2022574463|0,n=(n<<11|n>>>21)+i|0,s+=(n^i^r)+t[11]+1839030562|0,s=(s<<16|s>>>16)+n|0,r+=(s^n^i)+t[14]-35309556|0,r=(r<<23|r>>>9)+s|0,i+=(r^s^n)+t[1]-1530992060|0,i=(i<<4|i>>>28)+r|0,n+=(i^r^s)+t[4]+1272893353|0,n=(n<<11|n>>>21)+i|0,s+=(n^i^r)+t[7]-155497632|0,s=(s<<16|s>>>16)+n|0,r+=(s^n^i)+t[10]-1094730640|0,r=(r<<23|r>>>9)+s|0,i+=(r^s^n)+t[13]+681279174|0,i=(i<<4|i>>>28)+r|0,n+=(i^r^s)+t[0]-358537222|0,n=(n<<11|n>>>21)+i|0,s+=(n^i^r)+t[3]-722521979|0,s=(s<<16|s>>>16)+n|0,r+=(s^n^i)+t[6]+76029189|0,r=(r<<23|r>>>9)+s|0,i+=(r^s^n)+t[9]-640364487|0,i=(i<<4|i>>>28)+r|0,n+=(i^r^s)+t[12]-421815835|0,n=(n<<11|n>>>21)+i|0,s+=(n^i^r)+t[15]+530742520|0,s=(s<<16|s>>>16)+n|0,r+=(s^n^i)+t[2]-995338651|0,r=(r<<23|r>>>9)+s|0,i+=(s^(r|~n))+t[0]-198630844|0,i=(i<<6|i>>>26)+r|0,n+=(r^(i|~s))+t[7]+1126891415|0,n=(n<<10|n>>>22)+i|0,s+=(i^(n|~r))+t[14]-1416354905|0,s=(s<<15|s>>>17)+n|0,r+=(n^(s|~i))+t[5]-57434055|0,r=(r<<21|r>>>11)+s|0,i+=(s^(r|~n))+t[12]+1700485571|0,i=(i<<6|i>>>26)+r|0,n+=(r^(i|~s))+t[3]-1894986606|0,n=(n<<10|n>>>22)+i|0,s+=(i^(n|~r))+t[10]-1051523|0,s=(s<<15|s>>>17)+n|0,r+=(n^(s|~i))+t[1]-2054922799|0,r=(r<<21|r>>>11)+s|0,i+=(s^(r|~n))+t[8]+1873313359|0,i=(i<<6|i>>>26)+r|0,n+=(r^(i|~s))+t[15]-30611744|0,n=(n<<10|n>>>22)+i|0,s+=(i^(n|~r))+t[6]-1560198380|0,s=(s<<15|s>>>17)+n|0,r+=(n^(s|~i))+t[13]+1309151649|0,r=(r<<21|r>>>11)+s|0,i+=(s^(r|~n))+t[4]-145523070|0,i=(i<<6|i>>>26)+r|0,n+=(r^(i|~s))+t[11]-1120210379|0,n=(n<<10|n>>>22)+i|0,s+=(i^(n|~r))+t[2]+718787259|0,s=(s<<15|s>>>17)+n|0,r+=(n^(s|~i))+t[9]-343485551|0,r=(r<<21|r>>>11)+s|0,e[0]=i+e[0]|0,e[1]=r+e[1]|0,e[2]=s+e[2]|0,e[3]=n+e[3]|0}constructor(){Object.defineProperty(this,"_dataLength",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_bufferLength",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_state",{enumerable:!0,configurable:!0,writable:!0,value:new Int32Array(4)}),Object.defineProperty(this,"_buffer",{enumerable:!0,configurable:!0,writable:!0,value:new ArrayBuffer(68)}),Object.defineProperty(this,"_buffer8",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_buffer32",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(fe.stateIdentity),this}appendStr(e){const t=this._buffer8,i=this._buffer32;let r,s,n=this._bufferLength;for(s=0;s<e.length;s+=1){if(r=e.charCodeAt(s),r<128)t[n++]=r;else if(r<2048)t[n++]=(r>>>6)+192,t[n++]=63&r|128;else if(r<55296||r>56319)t[n++]=(r>>>12)+224,t[n++]=r>>>6&63|128,t[n++]=63&r|128;else{if(r=1024*(r-55296)+(e.charCodeAt(++s)-56320)+65536,r>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");t[n++]=(r>>>18)+240,t[n++]=r>>>12&63|128,t[n++]=r>>>6&63|128,t[n++]=63&r|128}n>=64&&(this._dataLength+=64,fe._md5cycle(this._state,i),n-=64,i[0]=i[16])}return this._bufferLength=n,this}appendAsciiStr(e){const t=this._buffer8,i=this._buffer32;let r,s=this._bufferLength,n=0;for(;;){for(r=Math.min(e.length-n,64-s);r--;)t[s++]=e.charCodeAt(n++);if(s<64)break;this._dataLength+=64,fe._md5cycle(this._state,i),s=0}return this._bufferLength=s,this}appendByteArray(e){const t=this._buffer8,i=this._buffer32;let r,s=this._bufferLength,n=0;for(;;){for(r=Math.min(e.length-n,64-s);r--;)t[s++]=e[n++];if(s<64)break;this._dataLength+=64,fe._md5cycle(this._state,i),s=0}return this._bufferLength=s,this}getState(){const 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]]}}setState(e){const t=e.buffer,i=e.state,r=this._state;let s;for(this._dataLength=e.length,this._bufferLength=e.buflen,r[0]=i[0],r[1]=i[1],r[2]=i[2],r[3]=i[3],s=0;s<t.length;s+=1)this._buffer8[s]=t.charCodeAt(s)}end(e=!1){const t=this._bufferLength,i=this._buffer8,r=this._buffer32,s=1+(t>>2);let n;if(this._dataLength+=t,i[t]=128,i[t+1]=i[t+2]=i[t+3]=0,r.set(fe.buffer32Identity.subarray(s),s),t>55&&(fe._md5cycle(this._state,r),r.set(fe.buffer32Identity)),n=8*this._dataLength,n<=4294967295)r[14]=n;else{const e=n.toString(16).match(/(.*?)(.{0,8})$/);if(null===e)return;const t=parseInt(e[2],16),i=parseInt(e[1],16)||0;r[14]=t,r[15]=i}return fe._md5cycle(this._state,r),e?this._state:fe._hex(this._state)}}function pe(e){return fe.hashStr(e)}Object.defineProperty(fe,"stateIdentity",{enumerable:!0,configurable:!0,writable:!0,value:new Int32Array([1732584193,-271733879,-1732584194,271733878])}),Object.defineProperty(fe,"buffer32Identity",{enumerable:!0,configurable:!0,writable:!0,value:new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])}),Object.defineProperty(fe,"hexChars",{enumerable:!0,configurable:!0,writable:!0,value:"0123456789abcdef"}),Object.defineProperty(fe,"hexOut",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(fe,"onePassHasher",{enumerable:!0,configurable:!0,writable:!0,value:new fe}),"5d41402abc4b2a76b9719d911017c592"!==fe.hashStr("hello")&&console.error("Md5 self test failed.");class ve{constructor(e,t,i,r){Object.defineProperty(this,"stale",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ha1",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"username",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"password",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cnonce",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"nc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ncHex",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"algorithm",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"realm",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"nonce",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"opaque",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"qop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"method",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"uri",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logger=e.getLogger("sipjs.digestauthentication"),this.username=i,this.password=r,this.ha1=t,this.nc=0,this.ncHex="00000000"}authenticate(e,t,i){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=C(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(i),!0}toString(){const 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(", ")}updateNcHex(){const e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e}calculateResponse(e){let t,i;t=this.ha1,""!==t&&void 0!==t||(t=pe(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(i=pe(this.method+":"+this.uri),this.response=pe(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+i)):"auth-int"===this.qop?(i=pe(this.method+":"+this.uri+":"+pe(e||"")),this.response=pe(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+i)):void 0===this.qop&&(i=pe(this.method+":"+this.uri),this.response=pe(t+":"+this.nonce+":"+i))}}!function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(he||(he={}));class me{constructor(e,t,i){Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"category",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"label",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logger=e,this.category=t,this.label=i}error(e){this.genericLog(he.error,e)}warn(e){this.genericLog(he.warn,e)}log(e){this.genericLog(he.log,e)}debug(e){this.genericLog(he.debug,e)}genericLog(e,t){this.logger.genericLog(e,this.category,this.label,t)}get level(){return this.logger.level}set level(e){this.logger.level=e}}class be{constructor(){Object.defineProperty(this,"builtinEnabled",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"_level",{enumerable:!0,configurable:!0,writable:!0,value:he.log}),Object.defineProperty(this,"_connector",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"loggers",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logger=this.getLogger("sip:loggerfactory")}get level(){return this._level}set level(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:he.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))}get connector(){return this._connector}set connector(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0}getLogger(e,t){if(t&&3===this.level)return new me(this,e,t);if(this.loggers[e])return this.loggers[e];{const t=new me(this,e);return this.loggers[e]=t,t}}genericLog(e,t,i,r){this.level>=e&&this.builtinEnabled&&this.print(e,t,i,r),this.connector&&this.connector(he[e],t,i,r)}print(e,t,i,r){if("string"==typeof r){const e=[new Date,t];i&&e.push(i),r=e.concat(r).join(" | ")}switch(e){case he.error:console.error(r);break;case he.warn:console.warn(r);break;case he.log:console.log(r);break;case he.debug:console.debug(r)}}}function ye(e,t){const i="\r\n";if(t.statusCode<100||t.statusCode>699)throw new TypeError("Invalid statusCode: "+t.statusCode);const r=t.reasonPhrase?t.reasonPhrase:P(t.statusCode);let s="SIP/2.0 "+t.statusCode+" "+r+i;t.statusCode>=100&&t.statusCode,t.statusCode;const n="From: "+e.getHeader("From")+i,o="Call-ID: "+e.callId+i,a="CSeq: "+e.cseq+" "+e.method+i,c=e.getHeaders("via").reduce((e,t)=>e+"Via: "+t+i,"");let l="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){let e=t.toTag;e||(e=A()),l+=";tag="+e}l+=i;let h="";t.supported&&(h="Supported: "+t.supported.join(", ")+i);let d="";t.userAgent&&(d="User-Agent: "+t.userAgent+i);let u="";return t.extraHeaders&&(u=t.extraHeaders.reduce((e,t)=>e+t.trim()+i,"")),s+=c,s+=n,s+=l,s+=a,s+=o,s+=h,s+=d,s+=u,t.body?(s+="Content-Type: "+t.body.contentType+i,s+="Content-Length: "+k(t.body.content)+i+i,s+=t.body.content):s+="Content-Length: 0\r\n\r\n",{message:s}}!function(e){function t(e,t){let i=t,r=0,s=0;if(e.substring(i,i+2).match(/(^\r\n)/))return-2;for(;0===r;){if(s=e.indexOf("\r\n",i),-1===s)return s;!e.substring(s+2,s+4).match(/(^\r\n)/)&&e.charAt(s+2).match(/(^\s+)/)?i=s+2:r=s}return r}function i(e,t,i,r){const s=t.indexOf(":",i),n=t.substring(i,s).trim(),o=t.substring(s+1,r).trim();let a;switch(n.toLowerCase()){case"via":case"v":e.addHeader("via",o),1===e.getHeaders("via").length?(a=e.parseHeader("Via"),a&&(e.via=a,e.viaBranch=a.branch)):a=0;break;case"from":case"f":e.setHeader("from",o),a=e.parseHeader("from"),a&&(e.from=a,e.fromTag=a.getParam("tag"));break;case"to":case"t":e.setHeader("to",o),a=e.parseHeader("to"),a&&(e.to=a,e.toTag=a.getParam("tag"));break;case"record-route":if(a=E.parse(o,"Record_Route"),-1===a){a=void 0;break}if(!(a instanceof Array)){a=void 0;break}a.forEach(t=>{e.addHeader("record-route",o.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",o),a=e.parseHeader("call-id"),a&&(e.callId=o);break;case"contact":case"m":if(a=E.parse(o,"Contact"),-1===a){a=void 0;break}if(!(a instanceof Array)){a=void 0;break}a.forEach(t=>{e.addHeader("contact",o.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",o),a=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",o),a=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",o),a=e.parseHeader("cseq"),a&&(e.cseq=a.value),e instanceof j&&(e.method=a.method);break;case"max-forwards":e.setHeader("max-forwards",o),a=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",o),a=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",o),a=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",o),a=e.parseHeader("refer-to"),a&&(e.referTo=a);break;default:e.addHeader(n.toLowerCase(),o),a=0}return void 0!==a||{error:"error parsing header '"+n+"'"}}e.getHeader=t,e.parseHeader=i,e.parseMessage=function(e,r){let s=0,n=e.indexOf("\r\n");if(-1===n)return void r.warn("no CRLF found, not a SIP message, discarded");const o=e.substring(0,n),a=E.parse(o,"Request_Response");let c,l;if(-1!==a){for(a.status_code?(c=new j,c.statusCode=a.status_code,c.reasonPhrase=a.reason_phrase):(c=new $,c.method=a.method,c.ruri=a.uri),c.data=e,s=n+2;;){if(n=t(e,s),-2===n){l=s+2;break}if(-1===n)return void r.error("malformed message");const o=i(c,e,s,n);if(o&&!0!==o)return void r.error(o.error);s=n+2}return c.hasHeader("content-length")?c.body=e.substr(l,Number(c.getHeader("content-length"))):c.body=e.substring(l),c}r.warn('error parsing first line of SIP message: "'+o+'"')}}(de||(de={}));class we extends o{constructor(e){super(e||"Unspecified transport error.")}}class Se{constructor(e,t,i,r,s){Object.defineProperty(this,"_transport",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"_user",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"_id",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"_state",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"listeners",{enumerable:!0,configurable:!0,writable:!0,value:new Array}),this.logger=t.loggerFactory.getLogger(s,i),this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`)}dispose(){this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`)}get id(){return this._id}get kind(){throw new Error("Invalid kind.")}get state(){return this._state}get transport(){return this._transport}addStateChangeListener(e,t){const i=()=>{this.removeStateChangeListener(i),e()};!0===(null==t?void 0:t.once)?this.listeners.push(i):this.listeners.push(e)}notifyStateChangeListeners(){this.listeners.slice().forEach(e=>e())}removeStateChangeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}logTransportError(e,t){this.logger.error(e.message),this.logger.error(`Transport error occurred in ${this.typeToString()} with id ${this.id}.`),this.logger.error(t)}send(e){return this.transport.send(e).catch(e=>{if(e instanceof we)throw this.onTransportError(e),e;let t;throw t=e&&"string"==typeof e.message?new we(e.message):new we,this.onTransportError(t),t})}setState(e){this.logger.debug(`State change to "${e}" on ${this.typeToString()} with id ${this.id}.`),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.notifyStateChangeListeners()}typeToString(){return"UnknownType"}}class Te extends Se{constructor(e,t,i,r,s){super(t,i,e.viaBranch,r,s),Object.defineProperty(this,"_request",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:i})}get request(){return this._request}}!function(e){e.Accepted="Accepted",e.Calling="Calling",e.Completed="Completed",e.Confirmed="Confirmed",e.Proceeding="Proceeding",e.Terminated="Terminated",e.Trying="Trying"}(ue||(ue={}));class Re extends Te{constructor(e,t,i){super(e,t,i,ue.Proceeding,"sip.transaction.ist"),Object.defineProperty(this,"lastFinalResponse",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lastProvisionalResponse",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"H",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"I",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"L",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"progressExtensionTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}dispose(){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),super.dispose()}get kind(){return"ist"}receiveRequest(e){switch(this.state){case ue.Proceeding:if(e.method===G.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case ue.Accepted:if(e.method===G.INVITE)return;break;case ue.Completed:if(e.method===G.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")})}if(e.method===G.ACK)return void this.stateTransition(ue.Confirmed);break;case ue.Confirmed:case ue.Terminated:if(e.method===G.INVITE||e.method===G.ACK)return;break;default:throw new Error(`Invalid state ${this.state}`)}const t=`INVITE server transaction received unexpected ${e.method} request while in state ${this.state}.`;this.logger.warn(t)}receiveResponse(e,t){if(e<100||e>699)throw new Error(`Invalid status code ${e}`);switch(this.state){case ue.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 1xx response.")});if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(ue.Accepted),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(ue.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send non-2xx final response.")});break;case ue.Accepted:if(e>=200&&e<=299)return void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});break;case ue.Completed:case ue.Confirmed:case ue.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const i=`INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(i),new Error(i)}retransmitAcceptedResponse(){this.state===ue.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")})}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e)}typeToString(){return"INVITE server transaction"}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case ue.Proceeding:t();break;case ue.Accepted:case ue.Completed:this.state!==ue.Proceeding&&t();break;case ue.Confirmed:this.state!==ue.Completed&&t();break;case ue.Terminated:this.state!==ue.Accepted&&this.state!==ue.Completed&&this.state!==ue.Confirmed&&t();break;default:t()}this.stopProgressExtensionTimer(),e===ue.Accepted&&(this.L=setTimeout(()=>this.timerL(),B.TIMER_L)),e===ue.Completed&&(this.H=setTimeout(()=>this.timerH(),B.TIMER_H)),e===ue.Confirmed&&(this.I=setTimeout(()=>this.timerI(),B.TIMER_I)),e===ue.Terminated&&this.dispose(),this.setState(e)}startProgressExtensionTimer(){void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval(()=>{if(this.logger.debug(`Progress extension timer expired for INVITE server transaction ${this.id}.`),!this.lastProvisionalResponse)throw new Error("Last provisional response undefined.");this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")})},B.PROVISIONAL_RESPONSE_INTERVAL))}stopProgressExtensionTimer(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)}timerG(){}timerH(){this.logger.debug(`Timer H expired for INVITE server transaction ${this.id}.`),this.state===ue.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(ue.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(ue.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===ue.Accepted&&this.stateTransition(ue.Terminated)}}class Ee extends Se{constructor(e,t,i,r,s){super(t,i,Ee.makeId(e),r,s),Object.defineProperty(this,"_request",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:i}),e.setViaHeader(this.id,t.protocol)}static makeId(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())}get request(){return this._request}onRequestTimeout(){this.user.onRequestTimeout&&this.user.onRequestTimeout()}}class Ie extends Ee{constructor(e,t,i){super(e,t,i,ue.Trying,"sip.transaction.nict"),Object.defineProperty(this,"F",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"K",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.F=setTimeout(()=>this.timerF(),B.TIMER_F),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),super.dispose()}get kind(){return"nict"}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error(`Invalid status code ${t}`);switch(this.state){case ue.Trying:if(t>=100&&t<=199)return this.stateTransition(ue.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(ue.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case ue.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(ue.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case ue.Completed:case ue.Terminated:return;default:throw new Error(`Invalid state ${this.state}`)}const i=`Non-INVITE client transaction received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(i)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(ue.Terminated,!0)}typeToString(){return"non-INVITE client transaction"}stateTransition(e,t=!1){const i=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case ue.Trying:i();break;case ue.Proceeding:this.state!==ue.Trying&&i();break;case ue.Completed:this.state!==ue.Trying&&this.state!==ue.Proceeding&&i();break;case ue.Terminated:this.state!==ue.Trying&&this.state!==ue.Proceeding&&this.state!==ue.Completed&&(t||i());break;default:i()}e===ue.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(()=>this.timerK(),B.TIMER_K)),e===ue.Terminated&&this.dispose(),this.setState(e)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==ue.Trying&&this.state!==ue.Proceeding||(this.onRequestTimeout(),this.stateTransition(ue.Terminated))}timerK(){this.state===ue.Completed&&this.stateTransition(ue.Terminated)}}class Ce{constructor(e,t){Object.defineProperty(this,"core",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"dialogState",{enumerable:!0,configurable:!0,writable:!0,value:t}),this.core.dialogs.set(this.id,this)}static initialDialogStateForUserAgentClient(e,t){const i=t.getHeaders("record-route").reverse(),r=t.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof b))throw new Error("Contact not instance of NameAddrHeader.");const s=r.uri,n=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.");const l=e.from.uri,h=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:n,remoteSequenceNumber:undefined,localURI:l,remoteURI:h,remoteTarget:s,routeSet:i,secure:!1}}static initialDialogStateForUserAgentServer(e,t,i=!1){const r=e.getHeaders("record-route"),s=e.parseHeader("contact");if(!s)throw new Error("Contact undefined.");if(!(s instanceof b))throw new Error("Contact not instance of NameAddrHeader.");const n=s.uri,o=e.cseq,a=e.callId,c=t,l=e.fromTag,h=e.from.uri;return{id:a+c+l,early:i,callId:a,localTag:c,remoteTag:l,localSequenceNumber:undefined,remoteSequenceNumber:o,localURI:e.to.uri,remoteURI:h,remoteTarget:n,routeSet:r,secure:!1}}dispose(){this.core.dialogs.delete(this.id)}get id(){return this.dialogState.id}get early(){return this.dialogState.early}get callId(){return this.dialogState.callId}get localTag(){return this.dialogState.localTag}get remoteTag(){return this.dialogState.remoteTag}get localSequenceNumber(){return this.dialogState.localSequenceNumber}get remoteSequenceNumber(){return this.dialogState.remoteSequenceNumber}get localURI(){return this.dialogState.localURI}get remoteURI(){return this.dialogState.remoteURI}get remoteTarget(){return this.dialogState.remoteTarget}get routeSet(){return this.dialogState.routeSet}get secure(){return this.dialogState.secure}get userAgentCore(){return this.core}confirm(){this.dialogState.early=!1}receiveRequest(e){if(e.method!==G.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)}}recomputeRouteSet(e){this.dialogState.routeSet=e.getHeaders("record-route").reverse()}createOutgoingRequestMessage(e,t){const i=this.remoteURI,r=this.remoteTag,s=this.localURI,n=this.localTag,o=this.callId;let a;a=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;const c=this.remoteTarget,l=this.routeSet,h=t&&t.extraHeaders,d=t&&t.body;return this.userAgentCore.makeOutgoingRequestMessage(e,c,s,i,{callId:o,cseq:a,fromTag:n,toTag:r,routeSet:l},h,d)}incrementLocalSequenceNumber(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1}sequenceGuard(e){return e.method===G.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))}}class Pe extends Ee{constructor(e,t,i){super(e,t,i,ue.Calling,"sip.transaction.ict"),Object.defineProperty(this,"B",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"D",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"M",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ackRetransmissionCache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),this.B=setTimeout(()=>this.timerB(),B.TIMER_B),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){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),super.dispose()}get kind(){return"ict"}ackResponse(e){const t=e.toTag;if(!t)throw new Error("To tag undefined.");const i="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(i,this.transport.protocol),this.ackRetransmissionCache.set(t,e),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send ACK to 2xx response.")})}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error(`Invalid status code ${t}`);switch(this.state){case ue.Calling:if(t>=100&&t<=199)return this.stateTransition(ue.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(ue.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(ue.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case ue.Proceeding:if(t>=100&&t<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(ue.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(ue.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case ue.Accepted:if(t>=200&&t<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));const t=this.ackRetransmissionCache.get(e.toTag);return t?void this.send(t.toString()).catch(e=>{this.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")}):void 0}break;case ue.Completed:if(t>=300&&t<=699)return void this.ack(e);break;case ue.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const i=`Received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(i)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(ue.Terminated,!0)}typeToString(){return"INVITE client transaction"}ack(e){const t=this.request.ruri,i=this.request.callId,r=this.request.cseq,s=this.request.getHeader("from"),n=e.getHeader("to"),o=this.request.getHeader("via"),a=this.request.getHeader("route");if(!s)throw new Error("From undefined.");if(!n)throw new Error("To undefined.");if(!o)throw new Error("Via undefined.");let c=`ACK ${t} SIP/2.0\r\n`;a&&(c+=`Route: ${a}\r\n`),c+=`Via: ${o}\r\n`,c+=`To: ${n}\r\n`,c+=`From: ${s}\r\n`,c+=`Call-ID: ${i}\r\n`,c+=`CSeq: ${r} ACK\r\n`,c+="Max-Forwards: 70\r\n",c+="Content-Length: 0\r\n\r\n",this.send(c).catch(e=>{this.logTransportError(e,"Failed to send ACK to non-2xx response.")})}stateTransition(e,t=!1){const i=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case ue.Calling:i();break;case ue.Proceeding:this.state!==ue.Calling&&i();break;case ue.Accepted:case ue.Completed:this.state!==ue.Calling&&this.state!==ue.Proceeding&&i();break;case ue.Terminated:this.state!==ue.Calling&&this.state!==ue.Accepted&&this.state!==ue.Completed&&(t||i());break;default:i()}this.B&&(clearTimeout(this.B),this.B=void 0),ue.Proceeding,e===ue.Completed&&(this.D=setTimeout(()=>this.timerD(),B.TIMER_D)),e===ue.Accepted&&(this.M=setTimeout(()=>this.timerM(),B.TIMER_M)),e===ue.Terminated&&this.dispose(),this.setState(e)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===ue.Calling&&(this.onRequestTimeout(),this.stateTransition(ue.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===ue.Completed&&this.stateTransition(ue.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===ue.Accepted&&this.stateTransition(ue.Terminated)}}class Ae{constructor(e,t,i,r){Object.defineProperty(this,"transactionConstructor",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"core",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_transaction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"credentials",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"challenged",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"stale",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}cancel(e,t={}){if(!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.");const i=this.core.makeOutgoingRequestMessage(G.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},t.extraHeaders);return i.branch=this.message.branch,this.message.headers.Route&&(i.headers.Route=this.message.headers.Route),e&&i.setHeader("Reason",e),this.transaction.state===ue.Proceeding?new Ae(Ie,this.core,i):this.transaction.addStateChangeListener(()=>{this.transaction&&this.transaction.state===ue.Proceeding&&new Ae(Ie,this.core,i)},{once:!0}),i}authenticationGuard(e,t){const i=e.statusCode;if(!i)throw new Error("Response status code undefined.");if(401!==i&&407!==i)return!0;let r,s;if(401===i?(r=e.parseHeader("www-authenticate"),s="authorization"):(r=e.parseHeader("proxy-authenticate"),s="proxy-authorization"),!r)return this.logger.warn(i+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==r.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,r))return!0;this.challenged=!0,r.stale&&(this.stale=!0);let n=this.message.cseq+=1;return t&&t.localSequenceNumber&&(t.incrementLocalSequenceNumber(),n=this.message.cseq=t.localSequenceNumber),this.message.setHeader("cseq",n+" "+this.message.method),this.message.setHeader(s,this.credentials.toString()),this.init(),!1}onRequestTimeout(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");const e=new j;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)}onTransportError(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");const t=new j;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)}receiveResponse(e){if(!this.authenticationGuard(e))return;const 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 ${t}`)}}init(){const e={loggerFactory:this.loggerFactory,onRequestTimeout:()=>this.onRequestTimeout(),onStateChange:e=>{e===ue.Terminated&&(this.core.userAgentClients.delete(i),t===this._transaction&&this.dispose())},onTransportError:e=>this.onTransportError(e),receiveResponse:e=>this.receiveResponse(e)},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const i=t.id+t.request.method;this.core.userAgentClients.set(i,this)}}class Oe extends Ae{constructor(e,t,i){const r=e.createOutgoingRequestMessage(G.BYE,i);super(Ie,e.userAgentCore,r,t),e.dispose()}}class ke extends Te{constructor(e,t,i){super(e,t,i,ue.Trying,"sip.transaction.nist"),Object.defineProperty(this,"lastResponse",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"J",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}dispose(){this.J&&(clearTimeout(this.J),this.J=void 0),super.dispose()}get kind(){return"nist"}receiveRequest(e){switch(this.state){case ue.Trying:break;case ue.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")});break;case ue.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")});break;case ue.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}}receiveResponse(e,t){if(e<100||e>699)throw new Error(`Invalid status code ${e}`);if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case ue.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(ue.Proceeding),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send provisional response.")});if(e>=200&&e<=699)return this.stateTransition(ue.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case ue.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(ue.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case ue.Completed:return;case ue.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const i=`Non-INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(i),new Error(i)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(ue.Terminated,!0)}typeToString(){return"non-INVITE server transaction"}stateTransition(e,t=!1){const i=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case ue.Trying:i();break;case ue.Proceeding:this.state!==ue.Trying&&i();break;case ue.Completed:this.state!==ue.Trying&&this.state!==ue.Proceeding&&i();break;case ue.Terminated:this.state!==ue.Proceeding&&this.state!==ue.Completed&&(t||i());break;default:i()}e===ue.Completed&&(this.J=setTimeout(()=>this.timerJ(),B.TIMER_J)),e===ue.Terminated&&this.dispose(),this.setState(e)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===ue.Completed&&this.stateTransition(ue.Terminated)}}class De{constructor(e,t,i,r){Object.defineProperty(this,"transactionConstructor",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"core",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"toTag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_transaction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=i.toTag?i.toTag:A(),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}accept(e={statusCode:200}){if(!this.acceptable)throw new W(`${this.message.method} not acceptable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<200||t>299)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}progress(e={statusCode:180}){if(!this.progressable)throw new W(`${this.message.method} not progressable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<101||t>199)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}redirect(e,t={statusCode:302}){if(!this.redirectable)throw new W(`${this.message.method} not redirectable in state ${this.transaction.state}.`);const i=t.statusCode;if(i<300||i>399)throw new TypeError(`Invalid statusCode: ${i}`);const r=new Array;e.forEach(e=>r.push(`Contact: ${e.toString()}`)),t.extraHeaders=(t.extraHeaders||[]).concat(r);return this.reply(t)}reject(e={statusCode:480}){if(!this.rejectable)throw new W(`${this.message.method} not rejectable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<400||t>699)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}trying(e){if(!this.tryingable)throw new W(`${this.message.method} not tryingable in state ${this.transaction.state}.`);return this.reply({statusCode:100})}receiveCancel(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)}get acceptable(){if(this.transaction instanceof Re)return this.transaction.state===ue.Proceeding||this.transaction.state===ue.Accepted;if(this.transaction instanceof ke)return this.transaction.state===ue.Trying||this.transaction.state===ue.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof Re)return this.transaction.state===ue.Proceeding;if(this.transaction instanceof ke)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof Re)return this.transaction.state===ue.Proceeding;if(this.transaction instanceof ke)return this.transaction.state===ue.Trying||this.transaction.state===ue.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof Re)return this.transaction.state===ue.Proceeding;if(this.transaction instanceof ke)return this.transaction.state===ue.Trying||this.transaction.state===ue.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof Re)return this.transaction.state===ue.Proceeding;if(this.transaction instanceof ke)return this.transaction.state===ue.Trying;throw new Error("Unknown transaction type.")}reply(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;const t=ye(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t}init(){const e={loggerFactory:this.loggerFactory,onStateChange:e=>{e===ue.Terminated&&(this.core.userAgentServers.delete(i),this.dispose())},onTransportError:e=>{this.logger.error(e.message),this.delegate&&this.delegate.onTransportError?this.delegate.onTransportError(e):this.logger.error("User agent server response transport error.")}},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const i=t.id;this.core.userAgentServers.set(t.id,this)}}class $e extends De{constructor(e,t,i){super(ke,e.userAgentCore,t,i)}}class je extends Ae{constructor(e,t,i){const r=e.createOutgoingRequestMessage(G.INFO,i);super(Ie,e.userAgentCore,r,t)}}class _e extends De{constructor(e,t,i){super(ke,e.userAgentCore,t,i)}}class He extends Ae{constructor(e,t,i){super(Ie,e,t,i)}}class Me extends De{constructor(e,t,i){super(ke,e,t,i)}}class xe extends Ae{constructor(e,t,i){const r=e.createOutgoingRequestMessage(G.NOTIFY,i);super(Ie,e.userAgentCore,r,t)}}class qe extends De{constructor(e,t,i){const r=void 0!==e.userAgentCore?e.userAgentCore:e;super(ke,r,t,i)}}class Ne extends Ae{constructor(e,t,i){const r=e.createOutgoingRequestMessage(G.PRACK,i);super(Ie,e.userAgentCore,r,t),e.signalingStateTransition(r)}}class Fe extends De{constructor(e,t,i){super(ke,e.userAgentCore,t,i),Object.defineProperty(this,"dialog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e.signalingStateTransition(t),this.dialog=e}accept(e={statusCode:200}){return e.body&&this.dialog.signalingStateTransition(e.body),super.accept(e)}}class Ue extends Ae{constructor(e,t,i){const r=e.createOutgoingRequestMessage(G.INVITE,i);super(Pe,e.userAgentCore,r,t),Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dialog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.delegate=t,e.signalingStateTransition(r),e.reinviteUserAgentClient=this,this.dialog=e}receiveResponse(e){if(!this.authenticationGuard(e,this.dialog))return;const 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,session:this.dialog,prack:e=>{throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(t):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:e=>this.dialog.ack(e)});break;case/^3[0-9]{2}$/.test(t):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(t):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 ${t}`)}}}class Le extends De{constructor(e,t,i){super(Re,e.userAgentCore,t,i),Object.defineProperty(this,"dialog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e.reinviteUserAgentServer=this,this.dialog=e}accept(e={statusCode:200}){e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(this.dialog.routeSet.map(e=>`Record-Route: ${e}`));const t=super.accept(e),i=this.dialog,r=Object.assign(Object.assign({},t),{session:i});return e.body&&this.dialog.signalingStateTransition(e.body),this.dialog.reConfirm(),r}progress(e={statusCode:180}){const t=super.progress(e),i=this.dialog,r=Object.assign(Object.assign({},t),{session:i});return e.body&&this.dialog.signalingStateTransition(e.body),r}redirect(e,t={statusCode:302}){throw this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")}reject(e={statusCode:488}){return this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,super.reject(e)}}class Be extends Ae{constructor(e,t,i){const r=e.createOutgoingRequestMessage(G.REFER,i);super(Ie,e.userAgentCore,r,t)}}class We extends De{constructor(e,t,i){const r=void 0!==e.userAgentCore?e.userAgentCore:e;super(ke,r,t,i)}}class Ge extends Ce{constructor(e,t,i,r){super(t,i),Object.defineProperty(this,"initialTransaction",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reinviteUserAgentClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reinviteUserAgentServer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_signalingState",{enumerable:!0,configurable:!0,writable:!0,value:F.Initial}),Object.defineProperty(this,"_offer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_answer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_rollbackOffer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_rollbackAnswer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ackWait",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ackProcessing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"invite2xxTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"rseq",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.delegate=r,e instanceof Re&&(this.ackWait=!0),this.early||this.start2xxRetransmissionTimer(),this.signalingStateTransition(e.request),this.logger=t.loggerFactory.getLogger("sip.invite-dialog"),this.logger.log(`INVITE dialog ${this.id} constructed`)}dispose(){super.dispose(),this._signalingState=F.Closed,this._offer=void 0,this._answer=void 0,this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.logger.log(`INVITE dialog ${this.id} destroyed`)}get sessionState(){return this.early?N.Early:this.ackWait?N.AckWait:this._signalingState===F.Closed?N.Terminated:N.Confirmed}get signalingState(){return this._signalingState}get offer(){return this._offer}get answer(){return this._answer}confirm(){this.early&&this.start2xxRetransmissionTimer(),super.confirm()}reConfirm(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()}ack(e={}){let t;if(this.logger.log(`INVITE dialog ${this.id} sending ACK request`),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof Pe))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof Pe))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}const i=this.createOutgoingRequestMessage(G.ACK,{cseq:t.request.cseq,extraHeaders:e.extraHeaders,body:e.body});return t.ackResponse(i),this.signalingStateTransition(i),{message:i}}bye(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending BYE request`),this.initialTransaction instanceof Re){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==ue.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 Oe(this,e,t)}info(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending INFO request`),this.early)throw new Error("Dialog not confirmed.");return new je(this,e,t)}invite(e,t){if(this.logger.log(`INVITE dialog ${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 Ue(this,e,t)}message(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending MESSAGE request`),this.early)throw new Error("Dialog not confirmed.");const i=this.createOutgoingRequestMessage(G.MESSAGE,t);return new He(this.core,i,e)}notify(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending NOTIFY request`),this.early)throw new Error("Dialog not confirmed.");return new xe(this,e,t)}prack(e,t){return this.logger.log(`INVITE dialog ${this.id} sending PRACK request`),new Ne(this,e,t)}refer(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending REFER request`),this.early)throw new Error("Dialog not confirmed.");return new Be(this,e,t)}receiveRequest(e){if(this.logger.log(`INVITE dialog ${this.id} received ${e.method} request`),e.method!==G.ACK)if(this.sequenceGuard(e)){if(super.receiveRequest(e),e.method===G.INVITE){const t=()=>{const e=this.ackWait?"waiting for initial ACK":"processing initial ACK";this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${e}`);let t="RFC 5407 suggests the following to avoid this race condition... ";t+=" Note: Implementation issues are outside the scope of this document,",t+=" but the following tip is provided for avoiding race conditions of",t+=" this type. The caller can delay sending re-INVITE F6 for some period",t+=" of time (2 seconds, perhaps), after which the caller can reasonably",t+=" assume that its ACK has been received. Implementors can decouple the",t+=" actions of the user (e.g., pressing the hold button) from the actions",t+=" of the protocol (the sending of re-INVITE F6), so that the UA can",t+=" behave like this. In this case, it is the implementor's choice as to",t+=" how long to wait. In most cases, such an implementation may be",t+=" useful to prevent the type of race condition shown in this section.",t+=" This document expresses no preference about whether or not they",t+=" should wait for an ACK to be delivered. After considering the impact",t+=" on user experience, implementors should decide whether or not to wait",t+=" for a while, because the user experience depends on the",t+=" implementation and has no direct bearing on protocol behavior.",this.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=[`Retry-After: ${Math.floor(10*Math.random())+1}`];if(this.ackProcessing)return this.core.replyStateless(e,{statusCode:500,extraHeaders:i}),void t();if(this.ackWait&&this.signalingState!==F.Stable)return this.core.replyStateless(e,{statusCode:500,extraHeaders:i}),void t();if(this.reinviteUserAgentServer)return void this.core.replyStateless(e,{statusCode:500,extraHeaders:i});if(this.reinviteUserAgentClient)return void this.core.replyStateless(e,{statusCode:491})}if(e.method===G.INVITE){const t=e.parseHeader("contact");if(!t)throw new Error("Contact undefined.");if(!(t instanceof b))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=t.uri}switch(e.method){case G.BYE:{const t=new $e(this,e);this.delegate&&this.delegate.onBye?this.delegate.onBye(t):t.accept(),this.dispose()}break;case G.INFO:{const t=new _e(this,e);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(t):t.reject({statusCode:469,extraHeaders:["Recv-Info:"]})}break;case G.INVITE:{const t=new Le(this,e);this.signalingStateTransition(e),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(t):t.reject({statusCode:488})}break;case G.MESSAGE:{const t=new Me(this.core,e);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case G.NOTIFY:{const t=new qe(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(t):t.accept()}break;case G.PRACK:{const t=new Fe(this,e);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(t):t.accept()}break;case G.REFER:{const t=new We(this,e);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):t.reject()}break;default:this.logger.log(`INVITE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501})}}else this.logger.log(`INVITE dialog ${this.id} rejected out of order ${e.method} request.`);else{if(this.ackWait){if(this.initialTransaction instanceof Pe)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.initialTransaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.reinviteUserAgentServer.transaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.reinviteUserAgentServer=void 0}if(this.signalingStateTransition(e),this.delegate&&this.delegate.onAck){const t=this.delegate.onAck({message:e});t instanceof Promise&&(this.ackProcessing=!0,t.then(()=>this.ackProcessing=!1).catch(()=>this.ackProcessing=!1))}}}reliableSequenceGuard(e){const t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){const t=e.getHeader("require"),i=e.getHeader("rseq"),r=t&&t.includes("100rel")&&i?Number(i):void 0;if(r){if(this.rseq&&this.rseq+1!==r)return!1;this.rseq=this.rseq?this.rseq+1:r}}return!0}signalingStateRollback(){this._signalingState!==F.HaveLocalOffer&&this.signalingState!==F.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=F.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(e){const t=q(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===F.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof $)switch(this._signalingState){case F.Initial:case F.Stable:this._signalingState=F.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case F.HaveLocalOffer:this._signalingState=F.Stable,this._answer=t;break;case F.HaveRemoteOffer:case F.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof j)switch(this._signalingState){case F.Initial:case F.Stable:this._signalingState=F.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case F.HaveLocalOffer:this._signalingState=F.Stable,this._answer=t;break;case F.HaveRemoteOffer:case F.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof _)switch(this._signalingState){case F.Initial:case F.Stable:this._signalingState=F.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case F.HaveLocalOffer:break;case F.HaveRemoteOffer:this._signalingState=F.Stable,this._answer=t;break;case F.Closed:break;default:throw new Error("Unexpected signaling state.")}if(x(e))switch(this._signalingState){case F.Initial:case F.Stable:this._signalingState=F.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case F.HaveLocalOffer:break;case F.HaveRemoteOffer:this._signalingState=F.Stable,this._answer=t;break;case F.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof Re){const e=this.initialTransaction;let t=B.T1;const i=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,B.T2),this.invite2xxTimer=setTimeout(i,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(i,t);const r=()=>{e.state===ue.Terminated&&(e.removeStateChangeListener(r),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.ackWait&&(this.delegate&&this.delegate.onAckTimeout?this.delegate.onAckTimeout():this.bye()))};e.addStateChangeListener(r)}}startReInvite2xxRetransmissionTimer(){if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof Re){const e=this.reinviteUserAgentServer.transaction;let t=B.T1;const i=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,B.T2),this.invite2xxTimer=setTimeout(i,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(i,t);const r=()=>{e.state===ue.Terminated&&(e.removeStateChangeListener(r),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};e.addStateChangeListener(r)}}}class Ve extends Ae{constructor(e,t,i){super(Pe,e,t,i),Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"confirmedDialogAcks",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"confirmedDialogs",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"earlyDialogs",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),this.delegate=i}dispose(){this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),super.dispose()}onTransportError(e){if(this.transaction.state===ue.Calling)return super.onTransportError(e);this.logger.error(e.message),this.logger.error("User agent client request transport error while sending ACK.")}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(t):{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.");const t=Ce.initialDialogStateForUserAgentClient(this.message,e);let i=this.earlyDialogs.get(t.id);if(!i){const e=this.transaction;if(!(e instanceof Pe))throw new Error("Transaction not instance of InviteClientTransaction.");i=new Ge(e,this.core,t),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!==F.Initial&&i.signalingState!==F.HaveLocalOffer||i.signalingStateTransition(e);const r=i;this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:r,prack:e=>r.prack(void 0,e)})}return;case/^2[0-9]{2}$/.test(t):{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.");const t=Ce.initialDialogStateForUserAgentClient(this.message,e);let i=this.confirmedDialogs.get(t.id);if(i){const e=this.confirmedDialogAcks.get(t.id);if(e){const t=this.transaction;if(!(t instanceof Pe))throw new Error("Client transaction not instance of InviteClientTransaction.");t.ackResponse(e.message)}return}if(i=this.earlyDialogs.get(t.id),i)i.confirm(),i.recomputeRouteSet(e),this.earlyDialogs.delete(i.id),this.confirmedDialogs.set(i.id,i);else{const e=this.transaction;if(!(e instanceof Pe))throw new Error("Transaction not instance of InviteClientTransaction.");i=new Ge(e,this.core,t),this.confirmedDialogs.set(i.id,i)}i.signalingState!==F.Initial&&i.signalingState!==F.HaveLocalOffer||i.signalingStateTransition(e);const r=i;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:r,ack:e=>{const t=r.ack(e);return this.confirmedDialogAcks.set(r.id,t),t}});else{const e=r.ack();this.confirmedDialogAcks.set(r.id,e)}}return;case/^3[0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error(`Invalid status code ${t}`)}}}class Ke extends De{constructor(e,t,i){super(Re,e,t,i),Object.defineProperty(this,"core",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"confirmedDialog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"earlyDialog",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(e={statusCode:200}){if(!this.acceptable)throw new W(`${this.message.method} not acceptable in state ${this.transaction.state}.`);if(!this.confirmedDialog)if(this.earlyDialog)this.earlyDialog.confirm(),this.confirmedDialog=this.earlyDialog,this.earlyDialog=void 0;else{const e=this.transaction;if(!(e instanceof Re))throw new Error("Transaction not instance of InviteClientTransaction.");const t=Ce.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new Ge(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>`Record-Route: ${e}`),i=`Contact: ${this.core.configuration.contact.toString()}`,r="Allow: "+V.toString();if(!e.body)if(this.confirmedDialog.signalingState===F.Stable)e.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===F.Initial||this.confirmedDialog.signalingState===F.HaveRemoteOffer)throw new Error("Response must have a body.");e.statusCode=e.statusCode||200,e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(r),e.extraHeaders.push(i);const s=super.accept(e),n=this.confirmedDialog,o=Object.assign(Object.assign({},s),{session:n});return e.body&&this.confirmedDialog.signalingState!==F.Stable&&this.confirmedDialog.signalingStateTransition(e.body),o}progress(e={statusCode:180}){if(!this.progressable)throw new W(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const e=this.transaction;if(!(e instanceof Re))throw new Error("Transaction not instance of InviteClientTransaction.");const t=Ce.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new Ge(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>`Record-Route: ${e}`),i=`Contact: ${this.core.configuration.contact}`;e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(i);const r=super.progress(e),s=this.earlyDialog,n=Object.assign(Object.assign({},r),{session:s});return e.body&&this.earlyDialog.signalingState!==F.Stable&&this.earlyDialog.signalingStateTransition(e.body),n}redirect(e,t={statusCode:302}){return super.redirect(e,t)}reject(e={statusCode:486}){return super.reject(e)}}class ze extends Ae{constructor(e,t,i){super(Ie,e,t,i)}}class Ye extends Ae{constructor(e,t,i){super(Ie,e,t,i)}}class Je extends De{constructor(e,t,i){super(ke,e,t,i),Object.defineProperty(this,"core",{enumerable:!0,configurable:!0,writable:!0,value:e})}}class Ze extends Ae{constructor(e,t,i){const r=e.createOutgoingRequestMessage(G.SUBSCRIBE,i);super(Ie,e.userAgentCore,r,t),Object.defineProperty(this,"dialog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.dialog=e}waitNotifyStop(){}receiveResponse(e){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);this.dialog.subscriptionExpires>e&&(this.dialog.subscriptionExpires=e)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(e.statusCode&&e.statusCode>=400&&e.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(e.statusCode)&&this.dialog.terminate()}super.receiveResponse(e)}}class Xe extends Ce{constructor(e,t,i,r,s,n){super(r,s),Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_autoRefresh",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_subscriptionEvent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_subscriptionExpires",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_subscriptionExpiresInitial",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_subscriptionExpiresLastSet",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_subscriptionRefresh",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_subscriptionRefreshLastSet",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_subscriptionState",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"N",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.delegate=n,this._autoRefresh=!1,this._subscriptionEvent=e,this._subscriptionExpires=t,this._subscriptionExpiresInitial=t,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this._subscriptionState=i,this.logger=r.loggerFactory.getLogger("sip.subscribe-dialog"),this.logger.log(`SUBSCRIBE dialog ${this.id} constructed`)}static initialDialogStateForSubscription(e,t){const i=t.getHeaders("record-route"),r=t.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof b))throw new Error("Contact not instance of NameAddrHeader.");const s=r.uri,n=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:n,remoteSequenceNumber:undefined,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:s,routeSet:i,secure:!1}}dispose(){super.dispose(),this.N&&(clearTimeout(this.N),this.N=void 0),this.refreshTimerClear(),this.logger.log(`SUBSCRIBE dialog ${this.id} destroyed`)}get autoRefresh(){return this._autoRefresh}set autoRefresh(e){this._autoRefresh=!0,this.refreshTimerSet()}get subscriptionEvent(){return this._subscriptionEvent}get subscriptionExpires(){const e=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,t=this._subscriptionExpires-e;return Math.max(t,0)}set subscriptionExpires(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){const t=this.subscriptionRefresh;(void 0===t||t>=e)&&this.refreshTimerSet()}}get subscriptionExpiresInitial(){return this._subscriptionExpiresInitial}get subscriptionRefresh(){if(void 0===this._subscriptionRefresh||void 0===this._subscriptionRefreshLastSet)return;const e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}get subscriptionState(){return this._subscriptionState}receiveRequest(e){if(this.logger.log(`SUBSCRIBE dialog ${this.id} received ${e.method} request`),this.sequenceGuard(e))if(super.receiveRequest(e),e.method===G.NOTIFY)this.onNotify(e);else this.logger.log(`SUBSCRIBE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501});else this.logger.log(`SUBSCRIBE dialog ${this.id} rejected out of order ${e.method} request.`)}refresh(){const e="Allow: "+V.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)}subscribe(e,t={}){var i;if(this.subscriptionState!==oe.Pending&&this.subscriptionState!==oe.Active)throw new Error(`Invalid state ${this.subscriptionState}. May only re-subscribe while in state "pending" or "active".`);this.logger.log(`SUBSCRIBE dialog ${this.id} sending SUBSCRIBE request`);const r=new Ze(this,e,t);return this.N&&(clearTimeout(this.N),this.N=void 0),(null===(i=t.extraHeaders)||void 0===i?void 0:i.includes("Expires: 0"))||(this.N=setTimeout(()=>this.timerN(),B.TIMER_N)),r}terminate(){this.stateTransition(oe.Terminated),this.onTerminated()}unsubscribe(){const e="Allow: "+V.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)}onNotify(e){const t=e.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return void this.core.replyStateless(e,{statusCode:489});this.N&&(clearTimeout(this.N),this.N=void 0);const i=e.parseHeader("Subscription-State");if(!i||!i.state)return void this.core.replyStateless(e,{statusCode:489});const r=i.state,s=i.expires?Math.max(i.expires,0):void 0;switch(r){case"pending":this.stateTransition(oe.Pending,s);break;case"active":this.stateTransition(oe.Active,s);break;case"terminated":this.stateTransition(oe.Terminated,s);break;default:this.logger.warn("Unrecognized subscription state.")}const n=new qe(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(n):n.accept()}onRefresh(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)}onTerminated(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()}refreshTimerClear(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}refreshTimerSet(){if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){const e=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(e/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout(()=>{this.refreshTimer=void 0,this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this.onRefresh(this.refresh())},e)}}stateTransition(e,t){const i=()=>{this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${e}`)};switch(e){case oe.Initial:case oe.NotifyWait:return void i();case oe.Pending:if(this.subscriptionState!==oe.NotifyWait&&this.subscriptionState!==oe.Pending)return void i();break;case oe.Active:case oe.Terminated:if(this.subscriptionState!==oe.NotifyWait&&this.subscriptionState!==oe.Pending&&this.subscriptionState!==oe.Active)return void i();break;default:return void i()}e===oe.Pending&&t&&(this.subscriptionExpires=t),e===oe.Active&&t&&(this.subscriptionExpires=t),e===oe.Terminated&&this.dispose(),this._subscriptionState=e}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==oe.Terminated&&(this.stateTransition(oe.Terminated),this.onTerminated())}}class Qe extends Ae{constructor(e,t,i){const r=t.getHeader("Event");if(!r)throw new Error("Event undefined");const s=t.getHeader("Expires");if(!s)throw new Error("Expires undefined");super(Ie,e,t,i),Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dialog",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"subscriberId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"subscriptionExpires",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"subscriptionExpiresRequested",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"subscriptionEvent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"subscriptionState",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"N",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.delegate=i,this.subscriberId=t.callId+t.fromTag+r,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(s),this.subscriptionEvent=r,this.subscriptionState=oe.NotifyWait,this.waitNotifyStart()}dispose(){super.dispose()}onNotify(e){const t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});const i=e.message.parseHeader("Subscription-State");if(!i||!i.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});const r=i.state;switch(r){case"pending":case"active":case"terminated":break;default:return this.logger.warn(`Invalid subscription state ${r}`),void e.reject({statusCode:489})}if("terminated"!==r){if(!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=i.expires?Math.min(this.subscriptionExpires,Math.max(i.expires,0)):this.subscriptionExpires,r){case"pending":this.subscriptionState=oe.Pending;break;case"active":this.subscriptionState=oe.Active;break;case"terminated":this.subscriptionState=oe.Terminated;break;default:throw new Error(`Unrecognized state ${r}.`)}if(this.subscriptionState!==oe.Terminated){const t=Xe.initialDialogStateForSubscription(this.message,e.message);this.dialog=new Xe(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,t)}if(this.delegate&&this.delegate.onNotify){const t=e,i=this.dialog;this.delegate.onNotify({request:t,subscription:i})}else e.accept()}waitNotifyStart(){this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout(()=>this.timerN(),B.TIMER_N))}waitNotifyStop(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)}receiveResponse(e){if(this.authenticationGuard(e)){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);e>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),e<this.subscriptionExpires&&(this.subscriptionExpires=e)}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)}e.statusCode&&e.statusCode>=300&&e.statusCode<700&&this.waitNotifyStop(),super.receiveResponse(e)}}timerN(){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()}}class et extends De{constructor(e,t,i){super(ke,e,t,i),Object.defineProperty(this,"core",{enumerable:!0,configurable:!0,writable:!0,value:e})}}const tt=["application/sdp","application/dtmf-relay"];class it{constructor(e,t={}){Object.defineProperty(this,"configuration",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dialogs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"subscribers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"userAgentClients",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"userAgentServers",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.configuration=e,this.delegate=t,this.dialogs=new Map,this.subscribers=new Map,this.logger=e.loggerFactory.getLogger("sip.user-agent-core")}dispose(){this.reset()}reset(){this.dialogs.forEach(e=>e.dispose()),this.dialogs.clear(),this.subscribers.forEach(e=>e.dispose()),this.subscribers.clear(),this.userAgentClients.forEach(e=>e.dispose()),this.userAgentClients.clear(),this.userAgentServers.forEach(e=>e.dispose()),this.userAgentServers.clear()}get loggerFactory(){return this.configuration.loggerFactory}get transport(){const e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e}invite(e,t){return new Ve(this,e,t)}message(e,t){return new He(this,e,t)}publish(e,t){return new ze(this,e,t)}register(e,t){return new Ye(this,e,t)}subscribe(e,t){return new Qe(this,e,t)}request(e,t){return new Ae(Ie,this,e,t)}makeOutgoingRequestMessage(e,t,i,r,s,n,o){const a=this.configuration.sipjsId,c=this.configuration.displayName,l=this.configuration.viaForceRport,h=this.configuration.hackViaTcp,d=this.configuration.supportedOptionTags.slice();e===G.REGISTER&&d.push("path","gruu"),e===G.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&d.push("gruu");const u={callIdPrefix:a,forceRport:l,fromDisplayName:c,hackViaTcp:h,optionTags:d,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},g=Object.assign(Object.assign({},u),s);return new _(e,t,i,r,g,n,o)}receiveIncomingRequestFromTransport(e){this.receiveRequestFromTransport(e)}receiveIncomingResponseFromTransport(e){this.receiveResponseFromTransport(e)}replyStateless(e,t){const i=this.configuration.userAgentHeaderFieldValue,r=this.configuration.supportedOptionTagsResponse;t=Object.assign(Object.assign({},t),{userAgent:i,supported:r});const s=ye(e,t);return this.transport.send(s.message).catch(t=>{t instanceof Error&&this.logger.error(t.message),this.logger.error(`Transport error occurred sending stateless reply to ${e.method} request.`)}),s}receiveRequestFromTransport(e){const t=e.viaBranch,i=this.userAgentServers.get(t);e.method===G.ACK&&i&&i.transaction.state===ue.Accepted&&i instanceof Ke?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${t}.`):e.method!==G.CANCEL?i?i.transaction.receiveRequest(e):this.receiveRequest(e):i?(this.replyStateless(e,{statusCode:200}),i.transaction instanceof Re&&i.transaction.state===ue.Proceeding&&i instanceof Ke&&i.receiveCancel(e)):this.replyStateless(e,{statusCode:481})}receiveRequest(e){if(!V.includes(e.method)){const t="Allow: "+V.toString();return void this.replyStateless(e,{statusCode:405,extraHeaders:[t]})}if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"!==e.ruri.scheme)return void this.replyStateless(e,{statusCode:416});const t=e.ruri,i=e=>!!e&&e.user===t.user;if(!i(this.configuration.aor)&&!(i(this.configuration.contact.uri)||i(this.configuration.contact.pubGruu)||i(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==G.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==G.INVITE||e.hasHeader("Contact")){if(!e.toTag){const t=e.viaBranch;if(!this.userAgentServers.has(t)){if(Array.from(this.userAgentServers.values()).some(t=>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"})}receiveInsideDialogRequest(e){if(e.method===G.NOTIFY){const t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});const i=e.callId+e.toTag+t.event,r=this.subscribers.get(i);if(r){const t=new qe(this,e);return void r.onNotify(t)}}const t=e.callId+e.toTag+e.fromTag,i=this.dialogs.get(t);if(i){if(e.method===G.OPTIONS){const t="Allow: "+V.toString(),i="Accept: "+tt.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[t,i]})}i.receiveRequest(e)}else e.method!==G.ACK&&this.replyStateless(e,{statusCode:481})}receiveOutsideDialogRequest(e){switch(e.method){case G.ACK:break;case G.BYE:this.replyStateless(e,{statusCode:481});break;case G.CANCEL:throw new Error(`Unexpected out of dialog request method ${e.method}.`);case G.INFO:this.replyStateless(e,{statusCode:405});break;case G.INVITE:{const t=new Ke(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject()}break;case G.MESSAGE:{const t=new Me(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case G.NOTIFY:{const t=new qe(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405})}break;case G.OPTIONS:{const t="Allow: "+V.toString(),i="Accept: "+tt.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[t,i]})}break;case G.REFER:{const t=new We(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405})}break;case G.REGISTER:{const t=new Je(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405})}break;case G.SUBSCRIBE:{const t=new et(this,e);this.delegate.onSubscribe?this.delegate.onSubscribe(t):t.reject({statusCode:480})}break;default:throw new Error(`Unexpected out of dialog request method ${e.method}.`)}}receiveResponseFromTransport(e){if(e.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response, dropping");const t=e.viaBranch+e.method,i=this.userAgentClients.get(t);i?i.transaction.receiveResponse(e):this.logger.warn(`Discarding unmatched ${e.statusCode} response to ${e.method} ${t}.`)}}class rt{constructor(e,t,i){Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mediaStreamFactory",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sessionDescriptionHandlerConfiguration",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_localMediaStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_remoteMediaStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_dataChannel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_peerConnection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_peerConnectionDelegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"iceGatheringCompletePromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"iceGatheringCompleteTimeoutId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"iceGatheringCompleteResolve",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"iceGatheringCompleteReject",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"localMediaStreamConstraints",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onDataChannel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e.debug("SessionDescriptionHandler.constructor"),this.logger=e,this.mediaStreamFactory=t,this.sessionDescriptionHandlerConfiguration=i,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==i?void 0:i.peerConnectionConfiguration),this.initPeerConnectionEventHandlers()}get localMediaStream(){return this._localMediaStream}get remoteMediaStream(){return this._remoteMediaStream}get dataChannel(){return this._dataChannel}get peerConnection(){return this._peerConnection}get peerConnectionDelegate(){return this._peerConnectionDelegate}set peerConnectionDelegate(e){this._peerConnectionDelegate=e}static dispatchAddTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("addtrack",{track:t}))}static dispatchRemoveTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("removetrack",{track:t}))}close(){this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this._peerConnection.getReceivers().forEach(e=>{e.track&&e.track.stop()}),this._peerConnection.getSenders().forEach(e=>{e.track&&e.track.stop()}),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)}enableReceiverTracks(e){const t=this.peerConnection;if(!t)throw new Error("Peer connection closed.");t.getReceivers().forEach(t=>{t.track&&(t.track.enabled=e)})}enableSenderTracks(e){const t=this.peerConnection;if(!t)throw new Error("Peer connection closed.");t.getSenders().forEach(t=>{t.track&&(t.track.enabled=e)})}getDescription(e,t){var i,r;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;const s=null===(i=null==e?void 0:e.offerOptions)||void 0===i?void 0:i.iceRestart,n=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(()=>this.updateDirection(e)).then(()=>this.createDataChannel(e)).then(()=>this.createLocalOfferOrAnswer(e)).then(e=>this.applyModifiers(e,t)).then(e=>this.setLocalSessionDescription(e)).then(()=>this.waitForIceGatheringComplete(s,n)).then(()=>this.getLocalSessionDescription()).then(t=>{const i=null==e?void 0:e.finalModifiers;return i&&0!==i.length?(this.logger.debug("SessionDescriptionHandler.getDescription - applying final SDP modifiers"),this.applyFinalModifiers(t,i)):t}).then(e=>{const t=e.sdp||"";return this.logger.log("SessionDescriptionHandler.getDescription - final SDP "+JSON.stringify({hasRecoveryReason:t.includes("a=x-recovery-reason:"),hasReinviteReason:t.includes("a=x-reinvite-reason:")})),{body:t,contentType:"application/sdp"}}).catch(e=>{throw this.logger.error("SessionDescriptionHandler.getDescription failed - "+e),e})}hasDescription(e){return this.logger.debug("SessionDescriptionHandler.hasDescription"),"application/sdp"===e}iceGatheringComplete(){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)}sendDtmf(e,t){if(this.logger.debug("SessionDescriptionHandler.sendDtmf"),void 0===this._peerConnection)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"),!1;const i=this._peerConnection.getSenders();if(0===i.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;const r=i[0].dtmf;if(!r)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;const s=null==t?void 0:t.duration,n=null==t?void 0:t.interToneGap;try{r.insertDTMF(e,s,n)}catch(e){return this.logger.error(e.toString()),!1}return this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: "+e.toString()),!0}setDescription(e,t,i){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;const r="have-local-offer"===this._peerConnection.signalingState?"answer":"offer";return this.getLocalMediaStream(t).then(()=>this.applyModifiers({sdp:e,type:r},i)).then(e=>this.setRemoteSessionDescription(e)).catch(e=>{throw this.logger.error("SessionDescriptionHandler.setDescription failed - "+e),e})}applyFinalModifiers(e,t){return this.logger.debug("SessionDescriptionHandler.applyFinalModifiers"),t&&0!==t.length?t.reduce((e,t)=>e.then(e=>r(this,void 0,void 0,function*(){var i;const r=yield t(e);if(!r||!r.sdp)throw new Error("Invalid final SDP.");return{sdp:r.sdp,type:null!==(i=r.type)&&void 0!==i?i:e.type}})),Promise.resolve({sdp:e.sdp,type:e.type})):Promise.resolve(e)}applyModifiers(e,t){return this.logger.debug("SessionDescriptionHandler.applyModifiers"),t&&0!==t.length?t.reduce((e,t)=>e.then(t),Promise.resolve(e)).then(e=>{if(this.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)}createDataChannel(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))}}createLocalOfferOrAnswer(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))}}getLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));let t=Object.assign({},null==e?void 0:e.constraints);if(this.localMediaStreamConstraints){if(t.audio=t.audio||this.localMediaStreamConstraints.audio,t.video=t.video||this.localMediaStreamConstraints.video,JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(t.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(t.video))return Promise.resolve()}else void 0===t.audio&&void 0===t.video&&(t={audio:!0});return this.localMediaStreamConstraints=t,this.mediaStreamFactory(t,this,e).then(e=>this.setLocalMediaStream(e))}setLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");const t=this._peerConnection,i=this._localMediaStream,r=[],s=e=>{const s=e.kind;if("audio"!==s&&"video"!==s)throw new Error(`Unknown new track kind ${s}.`);const n=t.getSenders().find(e=>e.track&&e.track.kind===s);n?r.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${s} track`),e()}).then(()=>n.replaceTrack(e).then(()=>{const t=i.getTracks().find(e=>e.kind===s);t&&(t.stop(),i.removeTrack(t),rt.dispatchRemoveTrackEvent(i,t)),i.addTrack(e),rt.dispatchAddTrackEvent(i,e)}).catch(e=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${s} track`),e}))):r.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${s} track`),e()}).then(()=>{try{t.addTrack(e,i)}catch(e){throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${s} track`),e}i.addTrack(e),rt.dispatchAddTrackEvent(i,e)}))},n=e.getAudioTracks();n.length&&s(n[0]);const o=e.getVideoTracks();return o.length&&s(o[0]),r.reduce((e,t)=>e.then(()=>t),Promise.resolve())}getLocalSessionDescription(){if(this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const e=this._peerConnection.localDescription;return e?Promise.resolve(e):Promise.reject(new Error("Failed to get local session description"))}setLocalSessionDescription(e){return this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"),void 0===this._peerConnection?Promise.reject(new Error("Peer connection closed.")):this._peerConnection.setLocalDescription(e)}setRemoteSessionDescription(e){if(this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const t=e.sdp;let i;switch(this._peerConnection.signalingState){case"stable":i="offer";break;case"have-local-offer":i="answer";break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return t?this._peerConnection.setRemoteDescription({sdp:t,type:i}):(this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"),Promise.reject(new Error("SDP is undefined")))}setRemoteTrack(e){this.logger.debug("SessionDescriptionHandler.setRemoteTrack");const t=this._remoteMediaStream;t.getTrackById(e.id)?this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${e.kind} track`):"audio"===e.kind?(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getAudioTracks().forEach(e=>{e.stop(),t.removeTrack(e),rt.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),rt.dispatchAddTrackEvent(t,e)):"video"===e.kind&&(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getVideoTracks().forEach(e=>{e.stop(),t.removeTrack(e),rt.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),rt.dispatchAddTrackEvent(t,e))}updateDirection(e){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");{const t=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")}};this._peerConnection.getTransceivers().forEach(e=>{if(e.direction){const i=t(e.direction);e.direction!==i&&(e.direction=i)}})}break;case"have-remote-offer":this.logger.debug("SessionDescriptionHandler.updateDirection - setting answer direction");{const t=(()=>{const e=this._peerConnection.remoteDescription;if(!e)throw new Error("Failed to read remote offer");const t=/a=sendrecv\r\n|a=sendonly\r\n|a=recvonly\r\n|a=inactive\r\n/.exec(e.sdp);if(t)switch(t[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"})(),i=(()=>{switch(t){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(e=>{e.direction&&"stopped"!==e.direction&&e.direction!==i&&(e.direction=i)})}break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return Promise.resolve()}waitForIceGatheringComplete(e=!1,t=0){return 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((e,i)=>{this.iceGatheringCompleteResolve=e,this.iceGatheringCompleteReject=i,t>0&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in "+t),this.iceGatheringCompleteTimeoutId=setTimeout(()=>{this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"),this.iceGatheringComplete()},t))}),this.iceGatheringCompletePromise):(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"),Promise.resolve())}initPeerConnectionEventHandlers(){if(this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"),!this._peerConnection)throw new Error("Peer connection undefined.");const e=this._peerConnection;e.onconnectionstatechange=t=>{var i;const r=e.connectionState;this.logger.debug(`SessionDescriptionHandler.onconnectionstatechange ${r}`),(null===(i=this._peerConnectionDelegate)||void 0===i?void 0:i.onconnectionstatechange)&&this._peerConnectionDelegate.onconnectionstatechange(t)},e.ondatachannel=e=>{var t;this.logger.debug("SessionDescriptionHandler.ondatachannel"),this._dataChannel=e.channel,this.onDataChannel&&this.onDataChannel(this._dataChannel),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ondatachannel)&&this._peerConnectionDelegate.ondatachannel(e)},e.onicecandidate=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidate"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidate)&&this._peerConnectionDelegate.onicecandidate(e)},e.onicecandidateerror=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidateerror"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidateerror)&&this._peerConnectionDelegate.onicecandidateerror(e)},e.oniceconnectionstatechange=t=>{var i;const r=e.iceConnectionState;this.logger.debug(`SessionDescriptionHandler.oniceconnectionstatechange ${r}`),(null===(i=this._peerConnectionDelegate)||void 0===i?void 0:i.oniceconnectionstatechange)&&this._peerConnectionDelegate.oniceconnectionstatechange(t)},e.onicegatheringstatechange=t=>{var i;const r=e.iceGatheringState;this.logger.debug(`SessionDescriptionHandler.onicegatheringstatechange ${r}`),"complete"===r&&this.iceGatheringComplete(),(null===(i=this._peerConnectionDelegate)||void 0===i?void 0:i.onicegatheringstatechange)&&this._peerConnectionDelegate.onicegatheringstatechange(t)},e.onnegotiationneeded=e=>{var t;this.logger.debug("SessionDescriptionHandler.onnegotiationneeded"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onnegotiationneeded)&&this._peerConnectionDelegate.onnegotiationneeded(e)},e.onsignalingstatechange=t=>{var i;const r=e.signalingState;this.logger.debug(`SessionDescriptionHandler.onsignalingstatechange ${r}`),(null===(i=this._peerConnectionDelegate)||void 0===i?void 0:i.onsignalingstatechange)&&this._peerConnectionDelegate.onsignalingstatechange(t)},e.ontrack=e=>{var t;const i=e.track.kind,r=e.track.enabled?"enabled":"disabled";this.logger.debug(`SessionDescriptionHandler.ontrack ${i} ${r}`),this.setRemoteTrack(e.track),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ontrack)&&this._peerConnectionDelegate.ontrack(e)}}}function st(e){return(t,i)=>{void 0===e&&(e=e=>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));const r={iceGatheringTimeout:void 0!==(null==i?void 0:i.iceGatheringTimeout)?null==i?void 0:i.iceGatheringTimeout:5e3,peerConnectionConfiguration:Object.assign(Object.assign({},{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",rtcpMuxPolicy:"require"}),null==i?void 0:i.peerConnectionConfiguration)},s=t.userAgent.getLogger("sip.SessionDescriptionHandler");return new rt(s,e,r)}}class nt{constructor(e,t){if(Object.defineProperty(this,"onConnect",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onDisconnect",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_protocol",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_state",{enumerable:!0,configurable:!0,writable:!0,value:ce.Disconnected}),Object.defineProperty(this,"_stateEventEmitter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ws",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"configuration",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"connectPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"connectResolve",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"connectReject",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"connectTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"disconnectPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"disconnectResolve",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"disconnectReject",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keepAliveInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keepAliveDebounceTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"transitioningState",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this._stateEventEmitter=new p,this.logger=e,t){const e=t,i=null==e?void 0:e.wsServers,r=null==e?void 0:e.maxReconnectionAttempts;if(void 0!==i){const e='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(e)}if(void 0!==r){const e='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(e)}i&&!t.server&&("string"==typeof i&&(t.server=i),i instanceof Array&&(t.server=i[0]))}this.configuration=Object.assign(Object.assign({},nt.defaultOptions),t);const i=this.configuration.server,r=E.parse(i,"absoluteURI");if(-1===r)throw this.logger.error(`Invalid WebSocket Server URL "${i}"`),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(r.scheme))throw this.logger.error(`Invalid scheme in WebSocket Server URL "${i}"`),new Error("Invalid scheme in WebSocket Server URL");this._protocol=r.scheme.toUpperCase()}dispose(){return this.disconnect()}get protocol(){return this._protocol}get server(){return this.configuration.server}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get ws(){return this._ws}connect(){return this._connect()}disconnect(){return this._disconnect()}isConnected(){return this.state===ce.Connected}send(e){return this._send(e)}_connect(){switch(this.logger.log(`Connecting ${this.server}`),this.state){case ce.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ce.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case ce.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ce.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case ce.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(ce.Connecting)}catch(e){if(e instanceof d)return Promise.reject(e);throw e}break;case ce.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(ce.Connecting)}catch(e){if(e instanceof d)return Promise.reject(e);throw e}break;default:throw new Error("Unknown state")}let e;try{e=new WebSocket(this.server,"sip"),e.binaryType="arraybuffer",e.addEventListener("close",t=>this.onWebSocketClose(t,e)),e.addEventListener("error",t=>this.onWebSocketError(t,e)),e.addEventListener("open",t=>this.onWebSocketOpen(t,e)),e.addEventListener("message",t=>this.onWebSocketMessage(t,e)),this._ws=e}catch(e){return this._ws=void 0,this.logger.error("WebSocket construction failed."),this.logger.error(e.toString()),new Promise((t,i)=>{this.connectResolve=t,this.connectReject=i,this.transitionState(ce.Disconnected,e)})}return this.connectPromise=new Promise((t,i)=>{this.connectResolve=t,this.connectReject=i,this.connectTimeout=setTimeout(()=>{this.logger.warn("Connect timed out. Exceeded time set in configuration.connectionTimeout: "+this.configuration.connectionTimeout+"s."),e.close(1e3)},1e3*this.configuration.connectionTimeout)}),this.connectPromise}_disconnect(){switch(this.logger.log(`Disconnecting ${this.server}`),this.state){case ce.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(ce.Disconnecting)}catch(e){if(e instanceof d)return Promise.reject(e);throw e}break;case ce.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(ce.Disconnecting)}catch(e){if(e instanceof d)return Promise.reject(e);throw e}break;case ce.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ce.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case ce.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ce.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.");const e=this._ws;return this.disconnectPromise=new Promise((t,i)=>{this.disconnectResolve=t,this.disconnectReject=i;try{e.close(1e3)}catch(e){throw this.logger.error("WebSocket close failed."),this.logger.error(e.toString()),e}}),this.disconnectPromise}_send(e){if(!0===this.configuration.traceSip&&this.logger.log("Sending WebSocket message:\n\n"+e+"\n"),this._state!==ce.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()}onWebSocketClose(e,t){if(t!==this._ws)return;const i=`WebSocket closed ${this.server} (code: ${e.code})`,r=this.disconnectPromise?void 0:new Error(i);r&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(i),this._ws=void 0,this.transitionState(ce.Disconnected,r)}onWebSocketError(e,t){t===this._ws&&this.logger.error("WebSocket error occurred.")}onWebSocketMessage(e,t){if(t!==this._ws)return;const i=e.data;let r;if(/^(\r\n)+$/.test(i))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(i){if("string"!=typeof i){try{r=(new TextDecoder).decode(new Uint8Array(i))}catch(e){return this.logger.error(e.toString()),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"+r+"\n")}else r=i,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+r+"\n");if(this.state===ce.Connected){if(this.onMessage)try{this.onMessage(r)}catch(e){throw this.logger.error(e.toString()),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...")}onWebSocketOpen(e,t){t===this._ws&&this._state===ce.Connecting&&(this.logger.log(`WebSocket opened ${this.server}`),this.transitionState(ce.Connected))}transitionLoopDetectedError(e){let t="A state transition loop has been detected.";return t+=` An attempt to transition from ${this._state} to ${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 d("Loop detected.")}transitionState(e,t){const i=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};if(this.transitioningState)throw this.transitionLoopDetectedError(e);switch(this.transitioningState=!0,this._state){case ce.Connecting:e!==ce.Connected&&e!==ce.Disconnecting&&e!==ce.Disconnected&&i();break;case ce.Connected:e!==ce.Disconnecting&&e!==ce.Disconnected&&i();break;case ce.Disconnecting:e!==ce.Connecting&&e!==ce.Disconnected&&i();break;case ce.Disconnected:e!==ce.Connecting&&i();break;default:throw new Error("Unknown state.")}const r=this._state;this._state=e;const s=this.connectResolve,n=this.connectReject;r===ce.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const o=this.disconnectResolve,a=this.disconnectReject;if(r===ce.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 ${r} to ${this._state}`),this._stateEventEmitter.emit(this._state),e===ce.Connected&&(this.startSendingKeepAlives(),this.onConnect))try{this.onConnect()}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onConnect callback"),e}if(r===ce.Connected&&(this.stopSendingKeepAlives(),this.onDisconnect))try{t?this.onDisconnect(t):this.onDisconnect()}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onDisconnect callback"),e}if(r===ce.Connecting){if(!s)throw new Error("Connect resolve undefined.");if(!n)throw new Error("Connect reject undefined.");e===ce.Connected?s():n(t||new Error("Connect aborted."))}if(r===ce.Disconnecting){if(!o)throw new Error("Disconnect resolve undefined.");if(!a)throw new Error("Disconnect reject undefined.");e===ce.Disconnected?o():a(t||new Error("Disconnect aborted."))}this.transitioningState=!1}clearKeepAliveTimeout(){this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveDebounceTimeout=void 0}sendKeepAlive(){return this.keepAliveDebounceTimeout?Promise.resolve():(this.keepAliveDebounceTimeout=setTimeout(()=>{this.clearKeepAliveTimeout()},1e3*this.configuration.keepAliveDebounce),this.send("\r\n\r\n"))}startSendingKeepAlives(){this.configuration.keepAliveInterval&&!this.keepAliveInterval&&(this.keepAliveInterval=setInterval(()=>{this.sendKeepAlive(),this.startSendingKeepAlives()},(e=>{const t=.8*e;return 1e3*(Math.random()*(e-t)+t)})(this.configuration.keepAliveInterval)))}stopSendingKeepAlives(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0}}Object.defineProperty(nt,"defaultOptions",{enumerable:!0,configurable:!0,writable:!0,value:{server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0}});class ot{constructor(e={}){if(Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_publishers",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_registerers",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_sessions",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_subscriptions",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_contact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_instanceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_state",{enumerable:!0,configurable:!0,writable:!0,value:le.Stopped}),Object.defineProperty(this,"_stateEventEmitter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_transport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_userAgentCore",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"loggerFactory",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._stateEventEmitter=new p,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},ot.defaultOptions()),{sipjsId:C(5)}),{uri:new y("sip","anonymous."+C(6),"anonymous.invalid")}),{viaHost:C(12)+".invalid"}),ot.stripUndefinedProperties(e)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){const e=1,t=254,i=Math.floor(Math.random()*(t-e+1)+e);this.options.viaHost="192.0.2."+i}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new be,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=he.error;break;case"warn":this.loggerFactory.level=he.warn;break;case"log":this.loggerFactory.level=he.log;break;case"debug":this.loggerFactory.level=he.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];switch(e){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("· "+e+": "+t);break;case"authorizationPassword":this.logger.log("· "+e+": NOT SHOWN");break;case"transportConstructor":this.logger.log("· "+e+": "+t.name);break;default:this.logger.log("· "+e+": "+JSON.stringify(t))}})),this.options.transportOptions){const t=this.options.transportOptions,i=t.maxReconnectionAttempts,r=t.reconnectionTimeout;if(void 0!==i){const e='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(e)}if(void 0!==r){const e='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(e)}void 0===e.reconnectionDelay&&void 0!==r&&(this.options.reconnectionDelay=r),void 0===e.reconnectionAttempts&&void 0!==i&&(this.options.reconnectionAttempts=i)}if(void 0!==e.reconnectionDelay){const e='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(e)}if(void 0!==e.reconnectionAttempts){const e='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(e)}if(this._transport=new this.options.transportConstructor(this.getLogger("sip.Transport"),this.options.transportOptions),this.initTransportCallbacks(),this._contact=this.initContact(),this._instanceId=this.options.instanceId?this.options.instanceId:ot.newUUID(),-1===E.parse(this._instanceId,"uuid"))throw new Error("Invalid instanceId.");this._userAgentCore=this.initCore()}static makeURI(e){return E.URIParse(e)}static defaultOptions(){return{errorCallback:()=>{},allowLegacyNotifications:!1,authorizationHa1:"",authorizationPassword:"",authorizationUsername:"",delegate:{},contactName:"",contactParams:{transport:"ws"},displayName:"",forceRport:!1,gracefulShutdown:!0,hackAllowUnregisteredOptionTags:!1,hackIpInContact:!1,hackViaTcp:!1,instanceId:"",instanceIdAlwaysAdded:!1,logBuiltinEnabled:!0,logConfiguration:!0,logConnector:()=>{},logLevel:"log",noAnswerTimeout:60,preloadedRouteSet:[],reconnectionAttempts:0,reconnectionDelay:4,sendInitialProvisionalResponse:!0,sessionDescriptionHandlerFactory:st(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:Q.Unsupported,sipExtensionReplaces:Q.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:nt,transportOptions:{},uri:new y("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/0.21.17",viaHost:""}}static newUUID(){const e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.floor(16*Math.random());return("x"===e?t:t%4+8).toString(16)});return e}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,i)=>(void 0!==e[i]&&(t[i]=e[i]),t),{})}get configuration(){return this.options}get contact(){return this._contact}get instanceId(){return this._instanceId}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get transport(){return this._transport}get userAgentCore(){return this._userAgentCore}getLogger(e,t){return this.loggerFactory.getLogger(e,t)}getLoggerFactory(){return this.loggerFactory}isConnected(){return this.transport.isConnected()}reconnect(){return this.state===le.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(()=>this.transport.connect())}start(){return this.state===le.Started?(this.logger.warn("User agent already started"),Promise.resolve()):(this.logger.log(`Starting ${this.configuration.uri}`),this.transitionState(le.Started),this.transport.connect())}stop(){return r(this,void 0,void 0,function*(){if(this.state===le.Stopped)return this.logger.warn("User agent already stopped"),Promise.resolve();if(this.logger.log(`Stopping ${this.configuration.uri}`),!this.options.gracefulShutdown)return this.logger.log("Dispose of transport"),this.transport.dispose().catch(e=>{throw this.logger.error(e.message),e}),this.logger.log("Dispose of core"),this.userAgentCore.dispose(),this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this.transitionState(le.Stopped),Promise.resolve();const e=Object.assign({},this._publishers),t=Object.assign({},this._registerers),i=Object.assign({},this._sessions),r=Object.assign({},this._subscriptions),s=this.transport,n=this.userAgentCore;this.logger.log("Dispose of registerers");for(const e in t)t[e]&&(yield t[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._registerers[e],t}));this.logger.log("Dispose of sessions");for(const e in i)i[e]&&(yield i[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._sessions[e],t}));this.logger.log("Dispose of subscriptions");for(const e in r)r[e]&&(yield r[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._subscriptions[e],t}));this.logger.log("Dispose of publishers");for(const t in e)e[t]&&(yield e[t].dispose().catch(e=>{throw this.logger.error(e.message),delete this._publishers[t],e}));this.logger.log("Dispose of transport"),yield s.dispose().catch(e=>{throw this.logger.error(e.message),e}),this.logger.log("Dispose of core"),n.dispose(),this.transitionState(le.Stopped)})}_makeInviter(e,t){return new ie(this,e,t)}attemptReconnection(e=1){const t=this.options.reconnectionAttempts,i=this.options.reconnectionDelay;e>t?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log(`Reconnection attempt ${e} of ${t} - trying`),setTimeout(()=>{this.reconnect().then(()=>{this.logger.log(`Reconnection attempt ${e} of ${t} - succeeded`)}).catch(i=>{this.logger.error(i.message),this.logger.log(`Reconnection attempt ${e} of ${t} - failed`),this.attemptReconnection(++e)})},1===e?0:1e3*i))}initContact(){const e=""!==this.options.contactName?this.options.contactName:C(8),t=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new y("sip",e,this.options.viaHost,void 0,t),toString:(e={})=>{const i=e.anonymous||!1,r=e.outbound||!1,s=e.register||!1;let n="<";return n+=i?this.contact.tempGruu||`sip:anonymous@anonymous.invalid;transport=${t.transport?t.transport:"ws"}`:s?this.contact.uri:this.contact.pubGruu||this.contact.uri,r&&(n+=";ob"),n+=">",this.options.instanceIdAlwaysAdded&&(n+=';+sip.instance="<urn:uuid:'+this._instanceId+'>"'),n}}}initCore(){let e=[];e.push("outbound"),this.options.sipExtension100rel===Q.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===Q.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter(e=>ee[e])),e=Array.from(new Set(e));const t=e.slice();(this.contact.pubGruu||this.contact.tempGruu)&&t.push("gruu");const i={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:e,supportedOptionTagsResponse:t,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:()=>{const e=this.options.authorizationUsername?this.options.authorizationUsername:this.options.uri.user,t=this.options.authorizationPassword?this.options.authorizationPassword:void 0,i=this.options.authorizationHa1?this.options.authorizationHa1:void 0;return new ve(this.getLoggerFactory(),i,e,t)},transportAccessor:()=>this.transport},r={onInvite:e=>{var t;const i=new te(this,e);if(e.delegate={onCancel:e=>{i._onCancel(e)},onTransportError:e=>{this.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},e.trying(),this.options.sipExtensionReplaces!==Q.Unsupported){const t=e.message.parseHeader("replaces");if(t){const e=t.call_id;if("string"!=typeof e)throw new Error("Type of call id is not string");const r=t.replaces_to_tag;if("string"!=typeof r)throw new Error("Type of to tag is not string");const s=t.replaces_from_tag;if("string"!=typeof s)throw new Error("type of from tag is not string");const n=e+r+s,o=this.userAgentCore.dialogs.get(n);if(!o)return void i.reject({statusCode:481});if(!o.early&&!0===t.early_only)return void i.reject({statusCode:486});const a=this._sessions[e+s]||this._sessions[e+r]||void 0;if(!a)throw new Error("Session does not exist.");i._replacee=a}}if(null===(t=this.delegate)||void 0===t?void 0:t.onInvite)return i.autoSendAnInitialProvisionalResponse?void i.progress().then(()=>{var e;if(void 0===(null===(e=this.delegate)||void 0===e?void 0:e.onInvite))throw new Error("onInvite undefined.");this.delegate.onInvite(i)}):void this.delegate.onInvite(i);i.reject({statusCode:486})},onMessage:e=>{if(this.delegate&&this.delegate.onMessage){const t=new K(e);this.delegate.onMessage(t)}else e.accept()},onNotify:e=>{if(this.delegate&&this.delegate.onNotify){const t=new z(e);this.delegate.onNotify(t)}else this.options.allowLegacyNotifications?e.accept():e.reject({statusCode:481})},onRefer:e=>{this.logger.warn("Received an out of dialog REFER request"),this.delegate&&this.delegate.onReferRequest?this.delegate.onReferRequest(e):e.reject({statusCode:405})},onRegister:e=>{this.logger.warn("Received an out of dialog REGISTER request"),this.delegate&&this.delegate.onRegisterRequest?this.delegate.onRegisterRequest(e):e.reject({statusCode:405})},onSubscribe:e=>{this.logger.warn("Received an out of dialog SUBSCRIBE request"),this.delegate&&this.delegate.onSubscribeRequest?this.delegate.onSubscribeRequest(e):e.reject({statusCode:405})}};return new it(i,r)}initTransportCallbacks(){this.transport.onConnect=()=>this.onTransportConnect(),this.transport.onDisconnect=e=>this.onTransportDisconnect(e),this.transport.onMessage=e=>this.onTransportMessage(e)}onTransportConnect(){this.state!==le.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==le.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const t=de.parseMessage(e,this.getLogger("sip.Parser"));if(!t)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===le.Stopped&&t instanceof $)return void this.logger.warn(`Received ${t.method} request while stopped. Dropping.`);const i=()=>{const e=["from","to","call_id","cseq","via"];for(const i of e)if(!t.hasHeader(i))return this.logger.warn(`Missing mandatory header field : ${i}.`),!1;return!0};if(t instanceof $){if(!i())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!t.toTag&&t.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(t,{statusCode:482});const e=k(t.body),r=t.getHeader("content-length");if(r&&e<Number(r))return void this.userAgentCore.replyStateless(t,{statusCode:400})}if(t instanceof j){if(!i())return void this.logger.warn("Response missing mandatory header field. Dropping.");if(t.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(t.via.host!==this.options.viaHost||void 0!==t.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");const e=k(t.body),r=t.getHeader("content-length");if(r&&e<Number(r))return void this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping.")}if(t instanceof $)this.userAgentCore.receiveIncomingRequestFromTransport(t);else{if(!(t instanceof j))throw new Error("Invalid message type.");this.userAgentCore.receiveIncomingResponseFromTransport(t)}}transitionState(e,t){const i=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case le.Started:e!==le.Stopped&&i();break;case le.Stopped:e!==le.Started&&i();break;default:throw new Error("Unknown state.")}this.logger.log(`Transitioned from ${this._state} to ${e}`),this._state=e,this._stateEventEmitter.emit(this._state)}}class at{constructor(e,t={}){Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"managedSessions",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"userAgent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attemptingReconnection",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"optionsPingFailure",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"optionsPingRequest",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"optionsPingRunning",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"optionsPingTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"registrationAttemptTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"registerer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"registererOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"registererRegisterOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shouldBeConnected",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"shouldBeRegistered",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.delegate=t.delegate,this.options=Object.assign({aor:"",autoStop:!0,delegate:{},iceStopWaitingOnServerReflexive:!1,managedSessionFactory:(e,t)=>({session:t,held:!1,muted:!1}),maxSimultaneousSessions:2,media:{},optionsPingInterval:-1,optionsPingRequestURI:"",reconnectionAttempts:3,reconnectionDelay:4,registrationRetry:!1,registrationRetryInterval:3,registerGuard:null,registererOptions:{},registererRegisterOptions:{},sendDTMFUsingSessionDescriptionHandler:!1,userAgentOptions:{}},at.stripUndefinedProperties(t));const i=Object.assign({},t.userAgentOptions);if(i.transportConstructor||(i.transportConstructor=nt),i.transportOptions||(i.transportOptions={server:e}),!i.uri&&t.aor){const e=ot.makeURI(t.aor);if(!e)throw new Error(`Failed to create valid URI from ${t.aor}`);i.uri=e}if(this.userAgent=new ot(i),this.userAgent.delegate={onConnect:()=>{this.logger.log("Connected"),this.delegate&&this.delegate.onServerConnect&&this.delegate.onServerConnect(),this.shouldBeRegistered&&this.register(),this.options.optionsPingInterval>0&&this.optionsPingStart()},onDisconnect:e=>r(this,void 0,void 0,function*(){this.logger.log("Disconnected");let t=!1;this.options.optionsPingInterval>0&&(t=this.optionsPingFailure,this.optionsPingFailure=!1,this.optionsPingStop()),this.delegate&&this.delegate.onServerDisconnect&&this.delegate.onServerDisconnect(e),(e||t)&&(this.registerer&&(this.logger.log("Disposing of registerer..."),this.registerer.dispose().catch(e=>{this.logger.debug("Error occurred disposing of registerer after connection with server was lost."),this.logger.debug(e.toString())}),this.registerer=void 0),this.managedSessions.slice().map(e=>e.session).forEach(e=>r(this,void 0,void 0,function*(){this.logger.log("Disposing of session..."),e.dispose().catch(e=>{this.logger.debug("Error occurred disposing of a session after connection with server was lost."),this.logger.debug(e.toString())})})),this.shouldBeConnected&&this.attemptReconnection())}),onInvite:e=>{this.logger.log(`[${e.id}] Received INVITE`);const t=this.options.maxSimultaneousSessions;if(0!==t&&this.managedSessions.length>t)return this.logger.warn(`[${e.id}] Session already in progress, rejecting INVITE...`),void e.reject().then(()=>{this.logger.log(`[${e.id}] Rejected INVITE`)}).catch(t=>{this.logger.error(`[${e.id}] Failed to reject INVITE`),this.logger.error(t.toString())});const i={sessionDescriptionHandlerOptions:{constraints:this.constraints}};this.initSession(e,i),this.delegate&&this.delegate.onCallReceived?this.delegate.onCallReceived(e):(this.logger.warn(`[${e.id}] No handler available, rejecting INVITE...`),e.reject().then(()=>{this.logger.log(`[${e.id}] Rejected INVITE`)}).catch(t=>{this.logger.error(`[${e.id}] Failed to reject INVITE`),this.logger.error(t.toString())}))},onMessage:e=>{e.accept().then(()=>{this.delegate&&this.delegate.onMessageReceived&&this.delegate.onMessageReceived(e)})},onNotify:e=>{e.accept().then(()=>{this.delegate&&this.delegate.onNotificationReceived&&this.delegate.onNotificationReceived(e)})}},this.registererOptions=Object.assign({},t.registererOptions),this.registererRegisterOptions=Object.assign({},t.registererRegisterOptions),this.options.registrationRetry){this.registererRegisterOptions.requestDelegate=this.registererRegisterOptions.requestDelegate||{};const e=this.registererRegisterOptions.requestDelegate.onReject;this.registererRegisterOptions.requestDelegate.onReject=t=>{e&&e(t),this.attemptRegistration()}}this.logger=this.userAgent.getLogger("sip.SessionManager"),window.addEventListener("online",()=>{this.logger.log("Online"),this.shouldBeConnected&&this.connect()}),this.options.autoStop&&window.addEventListener("beforeunload",()=>r(this,void 0,void 0,function*(){this.shouldBeConnected=!1,this.shouldBeRegistered=!1,this.userAgent.state!==le.Stopped&&(yield this.userAgent.stop())}))}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,i)=>(void 0!==e[i]&&(t[i]=e[i]),t),{})}getLocalMediaStream(e){const t=e.sessionDescriptionHandler;if(t){if(!(t instanceof rt))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.localMediaStream}}getRemoteMediaStream(e){const t=e.sessionDescriptionHandler;if(t){if(!(t instanceof rt))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.remoteMediaStream}}getLocalAudioTrack(e){var t;return null===(t=this.getLocalMediaStream(e))||void 0===t?void 0:t.getTracks().find(e=>"audio"===e.kind)}getLocalVideoTrack(e){var t;return null===(t=this.getLocalMediaStream(e))||void 0===t?void 0:t.getTracks().find(e=>"video"===e.kind)}getRemoteAudioTrack(e){var t;return null===(t=this.getRemoteMediaStream(e))||void 0===t?void 0:t.getTracks().find(e=>"audio"===e.kind)}getRemoteVideoTrack(e){var t;return null===(t=this.getRemoteMediaStream(e))||void 0===t?void 0:t.getTracks().find(e=>"video"===e.kind)}connect(){return r(this,void 0,void 0,function*(){return this.logger.log("Connecting UserAgent..."),this.shouldBeConnected=!0,this.userAgent.state!==le.Started?this.userAgent.start():this.userAgent.reconnect()})}disconnect(){return r(this,void 0,void 0,function*(){return this.logger.log("Disconnecting UserAgent..."),this.userAgent.state===le.Stopped?Promise.resolve():(this.shouldBeConnected=!1,this.shouldBeRegistered=!1,this.registerer=void 0,this.userAgent.stop())})}isConnected(){return this.userAgent.isConnected()}register(e){return r(this,void 0,void 0,function*(){return this.logger.log("Registering UserAgent..."),this.shouldBeRegistered=!0,void 0!==e&&(this.registererRegisterOptions=Object.assign({},e)),this.registerer||(this.registerer=new ge(this.userAgent,this.registererOptions),this.registerer.stateChange.addListener(e=>{switch(e){case ne.Initial:break;case ne.Registered:this.delegate&&this.delegate.onRegistered&&this.delegate.onRegistered();break;case ne.Unregistered:this.delegate&&this.delegate.onUnregistered&&this.delegate.onUnregistered(),this.shouldBeRegistered&&this.attemptRegistration();break;case ne.Terminated:break;default:throw new Error("Unknown registerer state.")}})),this.attemptRegistration(!0)})}unregister(e){return r(this,void 0,void 0,function*(){return this.logger.log("Unregistering UserAgent..."),this.shouldBeRegistered=!1,this.registerer?this.registerer.unregister(e).then(()=>{}):(this.logger.warn("No registerer to unregister."),Promise.resolve())})}call(e,t,i){return r(this,void 0,void 0,function*(){this.logger.log("Beginning Session...");const r=this.options.maxSimultaneousSessions;if(0!==r&&this.managedSessions.length>r)return Promise.reject(new Error("Maximum number of sessions already exists."));const s=ot.makeURI(e);if(!s)return Promise.reject(new Error(`Failed to create a valid URI from "${e}"`));if(t||(t={}),t.sessionDescriptionHandlerOptions||(t.sessionDescriptionHandlerOptions={}),t.sessionDescriptionHandlerOptions.constraints||(t.sessionDescriptionHandlerOptions.constraints=this.constraints),t.earlyMedia){(i=i||{}).requestDelegate=i.requestDelegate||{};const e=i.requestDelegate.onProgress;i.requestDelegate.onProgress=t=>{183===t.message.statusCode&&this.setupRemoteMedia(n),e&&e(t)}}this.options.iceStopWaitingOnServerReflexive&&(t.delegate=t.delegate||{},t.delegate.onSessionDescriptionHandler=e=>{if(!(e instanceof rt))throw new Error("Session description handler not instance of SessionDescriptionHandler");e.peerConnectionDelegate={onicecandidate:t=>{var i;if("srflx"===(null===(i=t.candidate)||void 0===i?void 0:i.type)){this.logger.log(`[${n.id}] Found srflx ICE candidate, stop waiting...`);e.iceGatheringComplete()}}}});const n=new ie(this.userAgent,s,t);return this.sendInvite(n,t,i).then(()=>n)})}hangup(e){return r(this,void 0,void 0,function*(){return this.logger.log(`[${e.id}] Hangup...`),this.sessionExists(e)?this.terminate(e):Promise.reject(new Error("Session does not exist."))})}answer(e,t){return r(this,void 0,void 0,function*(){return this.logger.log(`[${e.id}] Accepting Invitation...`),this.sessionExists(e)?e instanceof te?(t||(t={}),t.sessionDescriptionHandlerOptions||(t.sessionDescriptionHandlerOptions={}),t.sessionDescriptionHandlerOptions.constraints||(t.sessionDescriptionHandlerOptions.constraints=this.constraints),e.accept(t)):Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))})}decline(e){return r(this,void 0,void 0,function*(){return this.logger.log(`[${e.id}] Rejecting Invitation...`),this.sessionExists(e)?e instanceof te?e.reject():Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))})}hold(e){return r(this,void 0,void 0,function*(){return this.logger.log(`[${e.id}] Holding session...`),this.setHold(e,!0)})}unhold(e){return r(this,void 0,void 0,function*(){return this.logger.log(`[${e.id}] Unholding session...`),this.setHold(e,!1)})}isHeld(e){const t=this.sessionManaged(e);return!!t&&t.held}mute(e){this.logger.log(`[${e.id}] Disabling media tracks...`),this.setMute(e,!0)}unmute(e){this.logger.log(`[${e.id}] Enabling media tracks...`),this.setMute(e,!1)}isMuted(e){const t=this.sessionManaged(e);return!!t&&t.muted}sendDTMF(e,t){return r(this,void 0,void 0,function*(){if(this.logger.log(`[${e.id}] Sending DTMF...`),!/^[0-9A-D#*,]$/.exec(t))return Promise.reject(new Error("Invalid DTMF tone."));if(!this.sessionExists(e))return Promise.reject(new Error("Session does not exist."));if(this.logger.log(`[${e.id}] Sending DTMF tone: ${t}`),this.options.sendDTMFUsingSessionDescriptionHandler)return e.sessionDescriptionHandler?e.sessionDescriptionHandler.sendDtmf(t)?Promise.resolve():Promise.reject(new Error("Failed to send DTMF")):Promise.reject(new Error("Session desciption handler undefined."));{const i={body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:"Signal="+t+"\r\nDuration="+2e3}};return e.info({requestOptions:i}).then(()=>{})}})}transfer(e,t,i){return r(this,void 0,void 0,function*(){if(this.logger.log(`[${e.id}] Referring session...`),t instanceof X)return e.refer(t,i).then(()=>{});const r=ot.makeURI(t);return r?e.refer(r,i).then(()=>{}):Promise.reject(new Error(`Failed to create a valid URI from "${t}"`))})}message(e,t){return r(this,void 0,void 0,function*(){this.logger.log("Sending message...");const i=ot.makeURI(e);return i?new re(this.userAgent,i,t).message():Promise.reject(new Error(`Failed to create a valid URI from "${e}"`))})}get constraints(){let e={audio:!0,video:!1};return this.options.media.constraints&&(e=Object.assign({},this.options.media.constraints)),e}attemptReconnection(e=1){const t=this.options.reconnectionAttempts,i=this.options.reconnectionDelay;this.shouldBeConnected?(this.attemptingReconnection&&this.logger.log("Reconnection attempt already in progress"),e>t?this.logger.log("Reconnection maximum attempts reached"):(1===e?this.logger.log(`Reconnection attempt ${e} of ${t} - trying`):this.logger.log(`Reconnection attempt ${e} of ${t} - trying in ${i} seconds`),this.attemptingReconnection=!0,setTimeout(()=>{if(!this.shouldBeConnected)return this.logger.log(`Reconnection attempt ${e} of ${t} - aborted`),void(this.attemptingReconnection=!1);this.userAgent.reconnect().then(()=>{this.logger.log(`Reconnection attempt ${e} of ${t} - succeeded`),this.attemptingReconnection=!1}).catch(i=>{this.logger.log(`Reconnection attempt ${e} of ${t} - failed`),this.logger.error(i.message),this.attemptingReconnection=!1,this.attemptReconnection(++e)})},1===e?0:1e3*i))):this.logger.log("Should not be connected currently")}attemptRegistration(e=!1){if(this.logger.log("Registration attempt "+(e?"without delay":"")),!this.shouldBeRegistered)return this.logger.log("Should not be registered currently"),Promise.resolve();if(void 0!==this.registrationAttemptTimeout)return this.logger.log("Registration attempt already in progress"),Promise.resolve();const t=()=>this.registerer?this.isConnected()?this.userAgent.state===le.Stopped?(this.logger.log("User agent stopped"),Promise.resolve()):this.options.registerGuard?this.options.registerGuard().catch(e=>{throw this.logger.log("Register guard rejected will making registration attempt"),e}).then(e=>e||!this.registerer?Promise.resolve():this.registerer.register(this.registererRegisterOptions).then(()=>{})):this.registerer.register(this.registererRegisterOptions).then(()=>{}):(this.logger.log("User agent not connected"),Promise.resolve()):(this.logger.log("Registerer undefined"),Promise.resolve());return new Promise((i,r)=>{this.registrationAttemptTimeout=setTimeout(()=>{t().then(()=>{this.registrationAttemptTimeout=void 0,i()}).catch(e=>{this.registrationAttemptTimeout=void 0,e instanceof c?i():r(e)})},e?0:(e=>{const t=2*e;return 1e3*(Math.random()*(t-e)+e)})(this.options.registrationRetryInterval))})}cleanupMedia(e){const t=this.sessionManaged(e);if(!t)throw new Error("Managed session does not exist.");t.mediaLocal&&t.mediaLocal.video&&(t.mediaLocal.video.srcObject=null,t.mediaLocal.video.pause()),t.mediaRemote&&(t.mediaRemote.audio&&(t.mediaRemote.audio.srcObject=null,t.mediaRemote.audio.pause()),t.mediaRemote.video&&(t.mediaRemote.video.srcObject=null,t.mediaRemote.video.pause()))}enableReceiverTracks(e,t){if(!this.sessionExists(e))throw new Error("Session does not exist.");const i=e.sessionDescriptionHandler;if(!(i instanceof rt))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");i.enableReceiverTracks(t)}enableSenderTracks(e,t){if(!this.sessionExists(e))throw new Error("Session does not exist.");const i=e.sessionDescriptionHandler;if(!(i instanceof rt))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");i.enableSenderTracks(t)}initSession(t,i){this.sessionAdd(t),this.delegate&&this.delegate.onCallCreated&&this.delegate.onCallCreated(t),t.stateChange.addListener(i=>{switch(this.logger.log(`[${t.id}] Session state changed to ${i}`),i){case e.SessionState.Initial:case e.SessionState.Establishing:break;case e.SessionState.Established:this.setupLocalMedia(t),this.setupRemoteMedia(t),this.delegate&&this.delegate.onCallAnswered&&this.delegate.onCallAnswered(t);break;case e.SessionState.Terminating:case e.SessionState.Terminated:this.sessionExists(t)&&(this.cleanupMedia(t),this.sessionRemove(t),this.delegate&&this.delegate.onCallHangup&&this.delegate.onCallHangup(t));break;default:throw new Error("Unknown session state.")}}),t.delegate=t.delegate||{},t.delegate.onInfo=e=>{var i;if(void 0===(null===(i=this.delegate)||void 0===i?void 0:i.onCallDTMFReceived))return void e.reject();const r=e.request.getHeader("content-type");if(!r||!/^application\/dtmf-relay/i.exec(r))return void e.reject();const s=e.request.body.split("\r\n",2);if(2!==s.length)return void e.reject();let n;const o=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;if(void 0!==s[0]&&o.test(s[0])&&(n=s[0].replace(o,"$2")),!n)return void e.reject();let a;const c=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;void 0!==s[1]&&c.test(s[1])&&(a=parseInt(s[1].replace(c,"$2"),10)),a?e.accept().then(()=>{if(this.delegate&&this.delegate.onCallDTMFReceived){if(!n||!a)throw new Error("Tone or duration undefined.");this.delegate.onCallDTMFReceived(t,n,a)}}).catch(e=>{this.logger.error(e.message)}):e.reject()},t.delegate.onRefer=e=>{e.accept().then(()=>this.sendInvite(e.makeInviter(i),i)).catch(e=>{this.logger.error(e.message)})}}optionsPingRun(e,t,i){if(this.options.optionsPingInterval<1)throw new Error("Invalid options ping interval.");this.optionsPingRunning||(this.optionsPingRunning=!0,this.optionsPingTimeout=setTimeout(()=>{this.optionsPingTimeout=void 0;const r=()=>{this.optionsPingFailure=!1,this.optionsPingRunning&&(this.optionsPingRunning=!1,this.optionsPingRun(e,t,i))},s=()=>{this.logger.error("OPTIONS ping failed"),this.optionsPingFailure=!0,this.optionsPingRunning=!1,this.userAgent.transport.disconnect().catch(e=>this.logger.error(e))},n=this.userAgent.userAgentCore,o=n.makeOutgoingRequestMessage("OPTIONS",e,t,i,{});this.optionsPingRequest=n.request(o,{onAccept:()=>{this.optionsPingRequest=void 0,r()},onReject:e=>{this.optionsPingRequest=void 0,408===e.message.statusCode||503===e.message.statusCode?s():r()}})},1e3*this.options.optionsPingInterval))}optionsPingStart(){let e,t,i;if(this.logger.log("OPTIONS pings started"),this.options.optionsPingRequestURI){if(e=ot.makeURI(this.options.optionsPingRequestURI),!e)throw new Error("Failed to create Request URI.");t=this.userAgent.contact.uri.clone(),i=this.userAgent.contact.uri.clone()}else{if(!this.options.aor)return void this.logger.error("You have enabled sending OPTIONS pings and as such you must provide either a) an AOR to register, or b) an RURI to use for the target of the OPTIONS ping requests. ");{const r=ot.makeURI(this.options.aor);if(!r)throw new Error("Failed to create URI.");e=r.clone(),e.user=void 0,t=r.clone(),i=r.clone()}}this.optionsPingRun(e,t,i)}optionsPingStop(){this.logger.log("OPTIONS pings stopped"),this.optionsPingRunning=!1,this.optionsPingFailure=!1,this.optionsPingRequest&&(this.optionsPingRequest.dispose(),this.optionsPingRequest=void 0),this.optionsPingTimeout&&(clearTimeout(this.optionsPingTimeout),this.optionsPingTimeout=void 0)}sendInvite(e,t,i){return r(this,void 0,void 0,function*(){return this.initSession(e,t),e.invite(i).then(()=>{this.logger.log(`[${e.id}] Sent INVITE`)})})}sessionAdd(e){const t=this.options.managedSessionFactory(this,e);this.managedSessions.push(t)}sessionExists(e){return void 0!==this.sessionManaged(e)}sessionManaged(e){return this.managedSessions.find(t=>t.session.id===e.id)}sessionRemove(e){this.managedSessions=this.managedSessions.filter(t=>t.session.id!==e.id)}setHold(e,t){return r(this,void 0,void 0,function*(){if(!this.sessionExists(e))return Promise.reject(new Error("Session does not exist."));if(this.isHeld(e)===t)return Promise.resolve();if(!(e.sessionDescriptionHandler instanceof rt))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");const i={requestDelegate:{onAccept:()=>{const i=this.sessionManaged(e);void 0!==i&&(i.held=t,this.enableReceiverTracks(e,!i.held),this.enableSenderTracks(e,!i.held&&!i.muted),this.delegate&&this.delegate.onCallHold&&this.delegate.onCallHold(e,i.held))},onReject:()=>{this.logger.warn(`[${e.id}] Re-invite request was rejected`);const i=this.sessionManaged(e);void 0!==i&&(i.held=!t,this.enableReceiverTracks(e,!i.held),this.enableSenderTracks(e,!i.held&&!i.muted),this.delegate&&this.delegate.onCallHold&&this.delegate.onCallHold(e,i.held))}}},r=e.sessionDescriptionHandlerOptionsReInvite;r.hold=t,e.sessionDescriptionHandlerOptionsReInvite=r;const s=this.sessionManaged(e);if(!s)throw new Error("Managed session is undefiend.");return s.held=t,e.invite(i).then(()=>{const t=this.sessionManaged(e);void 0!==t&&(this.enableReceiverTracks(e,!t.held),this.enableSenderTracks(e,!t.held&&!t.muted))}).catch(i=>{throw s.held=!t,i instanceof c&&this.logger.error(`[${e.id}] A hold request is already in progress.`),i})})}setMute(t,i){if(!this.sessionExists(t))return void this.logger.warn(`[${t.id}] A session is required to enabled/disable media tracks`);if(t.state!==e.SessionState.Established)return void this.logger.warn(`[${t.id}] An established session is required to enable/disable media tracks`);const r=this.sessionManaged(t);void 0!==r&&(r.muted=i,this.enableSenderTracks(t,!r.held&&!r.muted))}setupLocalMedia(e){const t=this.sessionManaged(e);if(!t)throw new Error("Managed session does not exist.");const i="function"==typeof this.options.media.local?this.options.media.local(e):this.options.media.local;t.mediaLocal=i;const r=null==i?void 0:i.video;if(r){const t=this.getLocalMediaStream(e);if(!t)throw new Error("Local media stream undefiend.");r.srcObject=t,r.volume=0,r.play().catch(t=>{this.logger.error(`[${e.id}] Failed to play local media`),this.logger.error(t.message)})}}setupRemoteMedia(e){const t=this.sessionManaged(e);if(!t)throw new Error("Managed session does not exist.");const i="function"==typeof this.options.media.remote?this.options.media.remote(e):this.options.media.remote;t.mediaRemote=i;const r=(null==i?void 0:i.video)||(null==i?void 0:i.audio);if(r){const t=this.getRemoteMediaStream(e);if(!t)throw new Error("Remote media stream undefiend.");r.autoplay=!0,r.srcObject=t,r.play().catch(t=>{this.logger.error(`[${e.id}] Failed to play remote media`),this.logger.error(t.message)}),t.onaddtrack=()=>{this.logger.log("Remote media onaddtrack"),r.load(),r.play().catch(t=>{this.logger.error(`[${e.id}] Failed to play remote media`),this.logger.error(t.message)})}}}terminate(t){return r(this,void 0,void 0,function*(){switch(this.logger.log(`[${t.id}] Terminating...`),t.state){case e.SessionState.Initial:if(t instanceof ie)return t.cancel().then(()=>{this.logger.log(`[${t.id}] Inviter never sent INVITE (canceled)`)});if(t instanceof te)return t.reject().then(()=>{this.logger.log(`[${t.id}] Invitation rejected (sent 480)`)});throw new Error("Unknown session type.");case e.SessionState.Establishing:if(t instanceof ie)return t.cancel().then(()=>{this.logger.log(`[${t.id}] Inviter canceled (sent CANCEL)`)});if(t instanceof te)return t.reject().then(()=>{this.logger.log(`[${t.id}] Invitation rejected (sent 480)`)});throw new Error("Unknown session type.");case e.SessionState.Established:return t.bye().then(()=>{this.logger.log(`[${t.id}] Session ended (sent BYE)`)});case e.SessionState.Terminating:case e.SessionState.Terminated:break;default:throw new Error("Unknown state")}return this.logger.log(`[${t.id}] Terminating in state ${t.state}, no action taken`),Promise.resolve()})}}const ct=".",lt=Symbol("target"),ht=Symbol("unsubscribe");function dt(e){return e instanceof Date||e instanceof Set||e instanceof Map||e instanceof WeakSet||e instanceof WeakMap||ArrayBuffer.isView(e)}var ut=Array.isArray;function gt(e){return"symbol"==typeof e}const ft={after:(e,t)=>ut(e)?e.slice(t.length):""===t?e:e.slice(t.length+1),concat:(e,t)=>ut(e)?(e=[...e],t&&e.push(t),e):t&&void 0!==t.toString?(""!==e&&(e+=ct),gt(t)?e+t.toString():e+t):e,initial:e=>{if(ut(e))return e.slice(0,-1);if(""===e)return e;const t=e.lastIndexOf(ct);return-1===t?"":e.slice(0,t)},last:e=>{if(ut(e))return e[e.length-1]||"";if(""===e)return e;const t=e.lastIndexOf(ct);return-1===t?e:e.slice(t+1)},walk:(e,t)=>{if(ut(e))for(const i of e)t(i);else if(""!==e){let i=0,r=e.indexOf(ct);if(-1===r)t(e);else for(;i<e.length;)-1===r&&(r=e.length),t(e.slice(i,r)),i=r+1,r=e.indexOf(ct,i)}},get(e,t){return this.walk(t,t=>{e&&(e=e[t])}),e}};function pt(e,t,i){return e.isUnsubscribed||t.ignoreSymbols&&gt(i)||t.ignoreUnderscores&&"_"===i.charAt(0)||"ignoreKeys"in t&&t.ignoreKeys.includes(i)}class vt{constructor(e){this._equals=e,this._proxyCache=new WeakMap,this._pathCache=new WeakMap,this.isUnsubscribed=!1}_getDescriptorCache(){return void 0===this._descriptorCache&&(this._descriptorCache=new WeakMap),this._descriptorCache}_getProperties(e){const t=this._getDescriptorCache();let i=t.get(e);return void 0===i&&(i={},t.set(e,i)),i}_getOwnPropertyDescriptor(e,t){if(this.isUnsubscribed)return Reflect.getOwnPropertyDescriptor(e,t);const i=this._getProperties(e);let r=i[t];return void 0===r&&(r=Reflect.getOwnPropertyDescriptor(e,t),i[t]=r),r}getProxy(e,t,i,r){if(this.isUnsubscribed)return e;const s=e[r],n=s||e;this._pathCache.set(n,t);let o=this._proxyCache.get(n);return void 0===o&&(o=void 0===s?new Proxy(e,i):e,this._proxyCache.set(n,o)),o}getPath(e){return this.isUnsubscribed?void 0:this._pathCache.get(e)}isDetached(e,t){return!Object.is(e,ft.get(t,this.getPath(e)))}defineProperty(e,t,i){return!!Reflect.defineProperty(e,t,i)&&(this.isUnsubscribed||(this._getProperties(e)[t]=i),!0)}setProperty(e,t,i,r,s){if(!this._equals(s,i)||!(t in e)){const s=this._getOwnPropertyDescriptor(e,t);return void 0!==s&&"set"in s?Reflect.set(e,t,i,r):Reflect.set(e,t,i)}return!0}deleteProperty(e,t,i){if(Reflect.deleteProperty(e,t)){if(!this.isUnsubscribed){const r=this._getDescriptorCache().get(e);r&&(delete r[t],this._pathCache.delete(i))}return!0}return!1}isSameDescriptor(e,t,i){const r=this._getOwnPropertyDescriptor(t,i);return void 0!==e&&void 0!==r&&Object.is(e.value,r.value)&&(e.writable||!1)===(r.writable||!1)&&(e.enumerable||!1)===(r.enumerable||!1)&&(e.configurable||!1)===(r.configurable||!1)&&e.get===r.get&&e.set===r.set}isGetInvariant(e,t){const i=this._getOwnPropertyDescriptor(e,t);return void 0!==i&&!0!==i.configurable&&!0!==i.writable}unsubscribe(){this._descriptorCache=null,this._pathCache=null,this._proxyCache=null,this.isUnsubscribed=!0}}function mt(e){return"[object Object]"===toString.call(e)}function bt(){return!0}function yt(e,t){return e.length!==t.length||e.some((e,i)=>t[i]!==e)}const wt=new Set(["hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]),St=new Set(["concat","includes","indexOf","join","keys","lastIndexOf"]),Tt={push:bt,pop:bt,shift:bt,unshift:bt,copyWithin:yt,reverse:yt,sort:yt,splice:yt,flat:yt,fill:yt},Rt=new Set([...wt,...St,...Object.keys(Tt)]);function Et(e,t){if(e.size!==t.size)return!0;for(const i of e)if(!t.has(i))return!0;return!1}const It=["keys","values","entries"],Ct=new Set(["has","toString"]),Pt={add:Et,clear:Et,delete:Et,forEach:Et},At=new Set([...Ct,...Object.keys(Pt),...It]);function Ot(e,t){if(e.size!==t.size)return!0;let i;for(const[r,s]of e)if(i=t.get(r),i!==s||void 0===i&&!t.has(r))return!0;return!1}const kt=new Set([...Ct,"get"]),Dt={set:Ot,clear:Ot,delete:Ot,forEach:Ot},$t=new Set([...kt,...Object.keys(Dt),...It]);class jt{constructor(e,t,i,r){this._path=t,this._isChanged=!1,this._clonedCache=new Set,this._hasOnValidate=r,this._changes=r?[]:null,this.clone=void 0===t?e:this._shallowClone(e)}static isHandledMethod(e){return wt.has(e)}_shallowClone(e){let t=e;if(mt(e))t={...e};else if(ut(e)||ArrayBuffer.isView(e))t=[...e];else if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set([...e].map(e=>this._shallowClone(e)));else if(e instanceof Map){t=new Map;for(const[i,r]of e.entries())t.set(i,this._shallowClone(r))}return this._clonedCache.add(t),t}preferredThisArg(e,t,i,r){return e?(ut(r)?this._onIsChanged=Tt[t]:r instanceof Set?this._onIsChanged=Pt[t]:r instanceof Map&&(this._onIsChanged=Dt[t]),r):i}update(e,t,i){const r=ft.after(e,this._path);if("length"!==t){let e=this.clone;ft.walk(r,t=>{e&&e[t]&&(this._clonedCache.has(e[t])||(e[t]=this._shallowClone(e[t])),e=e[t])}),this._hasOnValidate&&this._changes.push({path:r,property:t,previous:i}),e&&e[t]&&(e[t]=i)}this._isChanged=!0}undo(e){let t;for(let i=this._changes.length-1;-1!==i;i--)t=this._changes[i],ft.get(e,t.path)[t.property]=t.previous}isChanged(e){return void 0===this._onIsChanged?this._isChanged:this._onIsChanged(this.clone,e)}}class _t extends jt{static isHandledMethod(e){return Rt.has(e)}}class Ht extends jt{undo(e){e.setTime(this.clone.getTime())}isChanged(e,t){return!t(this.clone.valueOf(),e.valueOf())}}class Mt extends jt{static isHandledMethod(e){return At.has(e)}undo(e){for(const t of this.clone)e.add(t);for(const t of e)this.clone.has(t)||e.delete(t)}}class xt extends jt{static isHandledMethod(e){return $t.has(e)}undo(e){for(const[t,i]of this.clone.entries())e.set(t,i);for(const t of e.keys())this.clone.has(t)||e.delete(t)}}class qt extends jt{constructor(e,t,i,r){super(void 0,t,i,r),this._arg1=i[0],this._weakValue=e.has(this._arg1)}isChanged(e){return this._weakValue!==e.has(this._arg1)}undo(e){this._weakValue&&!e.has(this._arg1)?e.add(this._arg1):e.delete(this._arg1)}}class Nt extends jt{constructor(e,t,i,r){super(void 0,t,i,r),this._weakKey=i[0],this._weakHas=e.has(this._weakKey),this._weakValue=e.get(this._weakKey)}isChanged(e){return this._weakValue!==e.get(this._weakKey)}undo(e){const t=e.has(this._weakKey);this._weakHas&&!t?e.set(this._weakKey,this._weakValue):!this._weakHas&&t?e.delete(this._weakKey):this._weakValue!==e.get(this._weakKey)&&e.set(this._weakKey,this._weakValue)}}class Ft{constructor(e){this._stack=[],this._hasOnValidate=e}static isHandledType(e){return mt(e)||ut(e)||dt(e)}static isHandledMethod(e,t){return mt(e)?jt.isHandledMethod(t):ut(e)?_t.isHandledMethod(t):e instanceof Set?Mt.isHandledMethod(t):e instanceof Map?xt.isHandledMethod(t):dt(e)}get isCloning(){return this._stack.length>0}start(e,t,i){let r=jt;ut(e)?r=_t:e instanceof Date?r=Ht:e instanceof Set?r=Mt:e instanceof Map?r=xt:e instanceof WeakSet?r=qt:e instanceof WeakMap&&(r=Nt),this._stack.push(new r(e,t,i,this._hasOnValidate))}update(e,t,i){this._stack[this._stack.length-1].update(e,t,i)}preferredThisArg(e,t,i){const{name:r}=e,s=Ft.isHandledMethod(i,r);return this._stack[this._stack.length-1].preferredThisArg(s,r,t,i)}isChanged(e,t,i){return this._stack[this._stack.length-1].isChanged(e,t,i)}undo(e){void 0!==this._previousClone&&this._previousClone.undo(e)}stop(){return this._previousClone=this._stack.pop(),this._previousClone.clone}}const Ut={equals:Object.is,isShallow:!1,pathAsArray:!1,ignoreSymbols:!1,ignoreUnderscores:!1,ignoreDetached:!1,details:!1},Lt=(e,t,i={})=>{i={...Ut,...i};const r=Symbol("ProxyTarget"),{equals:s,isShallow:n,ignoreDetached:o,details:a}=i,c=new vt(s),l="function"==typeof i.onValidate,h=new Ft(l),d=(e,t,r,s,n)=>!l||h.isCloning||!0===i.onValidate(ft.concat(c.getPath(e),t),r,s,n),u=(t,r,s,n)=>{pt(c,i,r)||o&&c.isDetached(t,e)||g(c.getPath(t),r,s,n)},g=(e,i,r,s,n)=>{h.isCloning?h.update(e,i,s):t(ft.concat(e,i),r,s,n)},f=e=>e&&e[r]||e,p=(t,s,a,l)=>function(e){return("object"==typeof e?null===e:"function"!=typeof e)||e instanceof RegExp}(t)||"constructor"===a||n&&!Ft.isHandledMethod(s,a)||pt(c,i,a)||c.isGetInvariant(s,a)||o&&c.isDetached(s,e)?t:(void 0===l&&(l=c.getPath(s)),c.getProxy(t,ft.concat(l,a),v,r)),v={get(e,t,i){if(gt(t)){if(t===r||t===lt)return e;if(t===ht&&!c.isUnsubscribed&&0===c.getPath(e).length)return c.unsubscribe(),e}const s=dt(e)?Reflect.get(e,t):Reflect.get(e,t,i);return p(s,e,t)},set(e,t,i,n){i=f(i);const o=e[r]||e,a=o[t];if(s(a,i)&&t in e)return!0;const l=d(e,t,i,a);return l&&c.setProperty(o,t,i,n,a)?(u(e,t,e[t],a),!0):!l},defineProperty(e,t,i){if(!c.isSameDescriptor(i,e,t)){const r=e[t];d(e,t,i.value,r)&&c.defineProperty(e,t,i,r)&&u(e,t,i.value,r)}return!0},deleteProperty(e,t){if(!Reflect.has(e,t))return!0;const i=Reflect.get(e,t),r=d(e,t,void 0,i);return r&&c.deleteProperty(e,t,i)?(u(e,t,void 0,i),!0):!r},apply(t,i,n){const o=i[r]||i;if(c.isUnsubscribed)return Reflect.apply(t,o,n);if((!1===a||!0!==a&&!a.includes(t.name))&&Ft.isHandledType(o)){let r=ft.initial(c.getPath(t));const a=Ft.isHandledMethod(o,t.name);h.start(o,r,n);let u=Reflect.apply(t,h.preferredThisArg(t,i,o),a?n.map(e=>f(e)):n);const m=h.isChanged(o,s),b=h.stop();if(Ft.isHandledType(u)&&a&&(i instanceof Map&&"get"===t.name&&(r=ft.concat(r,n[0])),u=c.getProxy(u,r,v)),m){const i={name:t.name,args:n,result:u},s=h.isCloning?ft.initial(r):r,a=h.isCloning?ft.last(r):"";d(ft.get(e,s),a,o,b,i)?g(s,a,o,b,i):h.undo(o)}return(i instanceof Map||i instanceof Set)&&("object"==typeof(l=u)&&"function"==typeof l.next)?function(e,t,i,r,s){const n=e.next;if("entries"===t.name)e.next=function(){const e=n.call(this);return!1===e.done&&(e.value[0]=s(e.value[0],t,e.value[0],r),e.value[1]=s(e.value[1],t,e.value[0],r)),e};else if("values"===t.name){const o=i[lt].keys();e.next=function(){const e=n.call(this);return!1===e.done&&(e.value=s(e.value,t,o.next().value,r)),e}}else e.next=function(){const e=n.call(this);return!1===e.done&&(e.value=s(e.value,t,e.value,r)),e};return e}(u,t,i,r,p):u}var l;return Reflect.apply(t,i,n)}},m=c.getProxy(e,i.pathAsArray?[]:"",v);return t=t.bind(m),l&&(i.onValidate=i.onValidate.bind(m)),m};function Bt(e){return document.getElementById(e)}function Wt(e){if(e&&e.getTracks)try{e.getTracks().forEach(e=>{try{e.stop()}catch(e){}})}catch(e){}}function Gt(e){return navigator.mediaDevices.getUserMedia(e).then(e=>e?(Wt(e),!0):Promise.reject(new Error("EmptyStreamError"))).catch(e=>(!e||"NotAllowedError"!==e.name)&&Promise.reject(e))}Lt.target=e=>e&&e[lt]||e,Lt.unsubscribe=e=>e[ht]||e;const Vt=e=>e.getHours().toString().padStart(2,"0")+":"+e.getMinutes().toString().padStart(2,"0")+":"+e.getSeconds().toString().padStart(2,"0"),Kt=()=>new Date(new Date((new Date).toLocaleDateString()).getTime()),zt=e=>new Date(e.setSeconds(e.getSeconds()+1));function Yt(e,t,i){const r=window.XMLHttpRequest?new window.XMLHttpRequest:window.ActiveXObject?new window.ActiveXObject("Microsoft.XMLHTTP"):void 0;r||t(new Error("Your Browser does not support ajax")),r.onreadystatechange=function(){if(4==r.readyState){const i=r.response||r.responseText;if(200==r.status){const t=r.getResponseHeader("Content-Type");-1!=t.indexOf("json")?e(JSON.parse(r.responseText)):-1!=t.indexOf("xml")?e(r.responseXML):e(r.responseText)}else t(i)}};const{url:s,data:n,type:o,contentType:a}=i,c=o||"POST";let l=s,h=null;return n&&("GET"===c?l=l+"?"+function(e){let t=[];for(let i in e)t.push(i+"="+e[i]);return t.join("&")}(n):"POST"===c&&(h=JSON.stringify(n))),r.open(c,l,!0),{xhr:r,ajaxData:h,contentType:a}}function Jt(){const e=new Date,t=e.getUTCFullYear(),i=e.getUTCMonth()+1,r=e.getUTCDate(),s=e.getUTCHours(),n=e.getUTCMinutes(),o=e.getUTCSeconds(),a=new Date(Date.UTC(t,i-1,r,s+8,n,o)),c=e=>String(e).padStart(2,"0");return`${a.getUTCFullYear()}-${c(a.getUTCMonth()+1)}-${c(a.getUTCDate())} ${c(a.getUTCHours())}:${c(a.getUTCMinutes())}:${c(a.getUTCSeconds())}`}const Zt={authorizationPassword:"",authorizationUsername:"",viaHost:"",uri:ot.makeURI("sip:@"),logLevel:"error",transportOptions:{server:"://"},contactName:""},Xt={connectStatus:!1,registerStatus:!1,invitatingStatus:!1,incomingStatus:!1,answerStatus:!1,reconnectStatus:!1};var Qt,ei,ti,ii;!function(e){e.NO="0",e.YES="1"}(Qt||(Qt={})),e.PopWindow=void 0,(ei=e.PopWindow||(e.PopWindow={})).NO="0",ei.YES="1",e.VoiceType=void 0,(ti=e.VoiceType||(e.VoiceType={})).MULTI_AI="1",ti.MULTI_VOICE_NOTIFY="2",ti.MULTI_PRETEST="3",ti.LABOUR="4",ti.AI="5",ti.NEW_VOICE_NOTIFY="6",ti.VOICE_TEST="7",ti.CALL_IN_AI="8",ti.CALL_IN_LABOUR="9",ti.MOVIE_CALL="10",ti.GATEWAY_TEST_CALL="11",e.AfterTransferLabour=void 0,(ii=e.AfterTransferLabour||(e.AfterTransferLabour={})).DIRECT_ANSWER="1",ii.LISTEN_FIRST_AND_THEN_ANSWER_MANUALLY="2";var ri="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function si(e,t){return e(t={exports:{}},t.exports),t.exports}var ni,oi,ai=function(e){return e&&e.Math===Math&&e},ci=ai("object"==typeof globalThis&&globalThis)||ai("object"==typeof window&&window)||ai("object"==typeof self&&self)||ai("object"==typeof ri&&ri)||ai("object"==typeof ri&&ri)||function(){return this}()||Function("return this")(),li=function(e){try{return!!e()}catch(e){return!0}},hi=!li(function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")}),di=Function.prototype,ui=di.apply,gi=di.call,fi="object"==typeof Reflect&&Reflect.apply||(hi?gi.bind(ui):function(){return gi.apply(ui,arguments)}),pi=Function.prototype,vi=pi.call,mi=hi&&pi.bind.bind(vi,vi),bi=hi?mi:function(e){return function(){return vi.apply(e,arguments)}},yi=bi({}.toString),wi=bi("".slice),Si=function(e){return wi(yi(e),8,-1)},Ti=function(e){if("Function"===Si(e))return bi(e)},Ri="object"==typeof document&&document.all,Ei=void 0===Ri&&void 0!==Ri?function(e){return"function"==typeof e||e===Ri}:function(e){return"function"==typeof e},Ii=!li(function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]}),Ci=Function.prototype.call,Pi=hi?Ci.bind(Ci):function(){return Ci.apply(Ci,arguments)},Ai={}.propertyIsEnumerable,Oi=Object.getOwnPropertyDescriptor,ki=Oi&&!Ai.call({1:2},1)?function(e){var t=Oi(this,e);return!!t&&t.enumerable}:Ai,Di={f:ki},$i=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},ji=Object,_i=bi("".split),Hi=li(function(){return!ji("z").propertyIsEnumerable(0)})?function(e){return"String"===Si(e)?_i(e,""):ji(e)}:ji,Mi=function(e){return null==e},xi=TypeError,qi=function(e){if(Mi(e))throw new xi("Can't call method on "+e);return e},Ni=function(e){return Hi(qi(e))},Fi=function(e){return"object"==typeof e?null!==e:Ei(e)},Ui={},Li=function(e){return Ei(e)?e:void 0},Bi=function(e,t){return arguments.length<2?Li(Ui[e])||Li(ci[e]):Ui[e]&&Ui[e][t]||ci[e]&&ci[e][t]},Wi=bi({}.isPrototypeOf),Gi=ci.navigator,Vi=Gi&&Gi.userAgent,Ki=Vi?String(Vi):"",zi=ci.process,Yi=ci.Deno,Ji=zi&&zi.versions||Yi&&Yi.version,Zi=Ji&&Ji.v8;Zi&&(oi=(ni=Zi.split("."))[0]>0&&ni[0]<4?1:+(ni[0]+ni[1])),!oi&&Ki&&(!(ni=Ki.match(/Edge\/(\d+)/))||ni[1]>=74)&&(ni=Ki.match(/Chrome\/(\d+)/))&&(oi=+ni[1]);var Xi=oi,Qi=ci.String,er=!!Object.getOwnPropertySymbols&&!li(function(){var e=Symbol("symbol detection");return!Qi(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&Xi&&Xi<41}),tr=er&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,ir=Object,rr=tr?function(e){return"symbol"==typeof e}:function(e){var t=Bi("Symbol");return Ei(t)&&Wi(t.prototype,ir(e))},sr=String,nr=function(e){try{return sr(e)}catch(e){return"Object"}},or=TypeError,ar=function(e){if(Ei(e))return e;throw new or(nr(e)+" is not a function")},cr=function(e,t){var i=e[t];return Mi(i)?void 0:ar(i)},lr=TypeError,hr=!0,dr=Object.defineProperty,ur=si(function(e){var t="__core-js_shared__",i=e.exports=ci[t]||function(e,t){try{dr(ci,e,{value:t,configurable:!0,writable:!0})}catch(i){ci[e]=t}return t}(t,{});(i.versions||(i.versions=[])).push({version:"3.46.0",mode:"pure",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru), 2025 CoreJS Company (core-js.io)",license:"https://github.com/zloirock/core-js/blob/v3.46.0/LICENSE",source:"https://github.com/zloirock/core-js"})}),gr=function(e,t){return ur[e]||(ur[e]=t||{})},fr=Object,pr=function(e){return fr(qi(e))},vr=bi({}.hasOwnProperty),mr=Object.hasOwn||function(e,t){return vr(pr(e),t)},br=0,yr=Math.random(),wr=bi(1.1.toString),Sr=function(e){return"Symbol("+(void 0===e?"":e)+")_"+wr(++br+yr,36)},Tr=ci.Symbol,Rr=gr("wks"),Er=tr?Tr.for||Tr:Tr&&Tr.withoutSetter||Sr,Ir=function(e){return mr(Rr,e)||(Rr[e]=er&&mr(Tr,e)?Tr[e]:Er("Symbol."+e)),Rr[e]},Cr=TypeError,Pr=Ir("toPrimitive"),Ar=function(e,t){if(!Fi(e)||rr(e))return e;var i,r=cr(e,Pr);if(r){if(void 0===t&&(t="default"),i=Pi(r,e,t),!Fi(i)||rr(i))return i;throw new Cr("Can't convert object to primitive value")}return void 0===t&&(t="number"),function(e,t){var i,r;if("string"===t&&Ei(i=e.toString)&&!Fi(r=Pi(i,e)))return r;if(Ei(i=e.valueOf)&&!Fi(r=Pi(i,e)))return r;if("string"!==t&&Ei(i=e.toString)&&!Fi(r=Pi(i,e)))return r;throw new lr("Can't convert object to primitive value")}(e,t)},Or=function(e){var t=Ar(e,"string");return rr(t)?t:t+""},kr=ci.document,Dr=Fi(kr)&&Fi(kr.createElement),$r=function(e){return Dr?kr.createElement(e):{}},jr=!Ii&&!li(function(){return 7!==Object.defineProperty($r("div"),"a",{get:function(){return 7}}).a}),_r=Object.getOwnPropertyDescriptor,Hr={f:Ii?_r:function(e,t){if(e=Ni(e),t=Or(t),jr)try{return _r(e,t)}catch(e){}if(mr(e,t))return $i(!Pi(Di.f,e,t),e[t])}},Mr=/#|\.prototype\./,xr=function(e,t){var i=Nr[qr(e)];return i===Ur||i!==Fr&&(Ei(t)?li(t):!!t)},qr=xr.normalize=function(e){return String(e).replace(Mr,".").toLowerCase()},Nr=xr.data={},Fr=xr.NATIVE="N",Ur=xr.POLYFILL="P",Lr=xr,Br=Ti(Ti.bind),Wr=function(e,t){return ar(e),void 0===t?e:hi?Br(e,t):function(){return e.apply(t,arguments)}},Gr=Ii&&li(function(){return 42!==Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype}),Vr=String,Kr=TypeError,zr=function(e){if(Fi(e))return e;throw new Kr(Vr(e)+" is not an object")},Yr=TypeError,Jr=Object.defineProperty,Zr=Object.getOwnPropertyDescriptor,Xr="enumerable",Qr="configurable",es="writable",ts={f:Ii?Gr?function(e,t,i){if(zr(e),t=Or(t),zr(i),"function"==typeof e&&"prototype"===t&&"value"in i&&es in i&&!i[es]){var r=Zr(e,t);r&&r[es]&&(e[t]=i.value,i={configurable:Qr in i?i[Qr]:r[Qr],enumerable:Xr in i?i[Xr]:r[Xr],writable:!1})}return Jr(e,t,i)}:Jr:function(e,t,i){if(zr(e),t=Or(t),zr(i),jr)try{return Jr(e,t,i)}catch(e){}if("get"in i||"set"in i)throw new Yr("Accessors not supported");return"value"in i&&(e[t]=i.value),e}},is=Ii?function(e,t,i){return ts.f(e,t,$i(1,i))}:function(e,t,i){return e[t]=i,e},rs=Hr.f,ss=function(e){var t=function(i,r,s){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(i);case 2:return new e(i,r)}return new e(i,r,s)}return fi(e,this,arguments)};return t.prototype=e.prototype,t},ns=function(e,t){var i,r,s,n,o,a,c,l,h,d=e.target,u=e.global,g=e.stat,f=e.proto,p=u?ci:g?ci[d]:ci[d]&&ci[d].prototype,v=u?Ui:Ui[d]||is(Ui,d,{})[d],m=v.prototype;for(n in t)r=!(i=Lr(u?n:d+(g?".":"#")+n,e.forced))&&p&&mr(p,n),a=v[n],r&&(c=e.dontCallGetSet?(h=rs(p,n))&&h.value:p[n]),o=r&&c?c:t[n],(i||f||typeof a!=typeof o)&&(l=e.bind&&r?Wr(o,ci):e.wrap&&r?ss(o):f&&Ei(o)?Ti(o):o,(e.sham||o&&o.sham||a&&a.sham)&&is(l,"sham",!0),is(v,n,l),f&&(mr(Ui,s=d+"Prototype")||is(Ui,s,{}),is(Ui[s],n,o),e.real&&m&&(i||!m[n])&&is(m,n,o)))},os=ts.f;ns({target:"Object",stat:!0,forced:Object.defineProperty!==os,sham:!Ii},{defineProperty:os});var as=si(function(e){var t=Ui.Object,i=e.exports=function(e,i,r){return t.defineProperty(e,i,r)};t.defineProperty.sham&&(i.sham=!0)}),cs=as,ls=Array.isArray||function(e){return"Array"===Si(e)},hs=Math.ceil,ds=Math.floor,us=Math.trunc||function(e){var t=+e;return(t>0?ds:hs)(t)},gs=function(e){var t=+e;return t!=t||0===t?0:us(t)},fs=Math.min,ps=function(e){return t=e.length,(i=gs(t))>0?fs(i,9007199254740991):0;var t,i},vs=TypeError,ms=function(e){if(e>9007199254740991)throw vs("Maximum allowed index exceeded");return e},bs=function(e,t,i){Ii?ts.f(e,t,$i(0,i)):e[t]=i},ys={};ys[Ir("toStringTag")]="z";var ws="[object z]"===String(ys),Ss=Ir("toStringTag"),Ts=Object,Rs="Arguments"===Si(function(){return arguments}()),Es=ws?Si:function(e){var t,i,r;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t]}catch(e){}}(t=Ts(e),Ss))?i:Rs?Si(t):"Object"===(r=Si(t))&&Ei(t.callee)?"Arguments":r},Is=bi(Function.toString);Ei(ur.inspectSource)||(ur.inspectSource=function(e){return Is(e)});var Cs=ur.inspectSource,Ps=function(){},As=Bi("Reflect","construct"),Os=/^\s*(?:class|function)\b/,ks=bi(Os.exec),Ds=!Os.test(Ps),$s=function(e){if(!Ei(e))return!1;try{return As(Ps,[],e),!0}catch(e){return!1}},js=function(e){if(!Ei(e))return!1;switch(Es(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Ds||!!ks(Os,Cs(e))}catch(e){return!0}};js.sham=!0;var _s,Hs=!As||li(function(){var e;return $s($s.call)||!$s(Object)||!$s(function(){e=!0})||e})?js:$s,Ms=Ir("species"),xs=Array,qs=function(e,t){return new(function(e){var t;return ls(e)&&(t=e.constructor,(Hs(t)&&(t===xs||ls(t.prototype))||Fi(t)&&null===(t=t[Ms]))&&(t=void 0)),void 0===t?xs:t}(e))(0===t?0:t)},Ns=Ir("species"),Fs=Ir("isConcatSpreadable"),Us=Xi>=51||!li(function(){var e=[];return e[Fs]=!1,e.concat()[0]!==e}),Ls=function(e){if(!Fi(e))return!1;var t=e[Fs];return void 0!==t?!!t:ls(e)},Bs=!(Us&&(_s="concat",Xi>=51||!li(function(){var e=[];return(e.constructor={})[Ns]=function(){return{foo:1}},1!==e[_s](Boolean).foo})));ns({target:"Array",proto:!0,arity:1,forced:Bs},{concat:function(e){var t,i,r,s,n,o=pr(this),a=qs(o,0),c=0;for(t=-1,r=arguments.length;t<r;t++)if(Ls(n=-1===t?o:arguments[t]))for(s=ps(n),ms(c+s),i=0;i<s;i++,c++)i in n&&bs(a,c,n[i]);else ms(c+1),bs(a,c++,n);return a.length=c,a}});var Ws,Gs=String,Vs=function(e){if("Symbol"===Es(e))throw new TypeError("Cannot convert a Symbol value to a string");return Gs(e)},Ks=Math.max,zs=Math.min,Ys=function(e){return function(t,i,r){var s=Ni(t),n=ps(s);if(0===n)return!e&&-1;var o,a=function(e,t){var i=gs(e);return i<0?Ks(i+t,0):zs(i,t)}(r,n);if(e&&i!=i){for(;n>a;)if((o=s[a++])!=o)return!0}else for(;n>a;a++)if((e||a in s)&&s[a]===i)return e||a||0;return!e&&-1}},Js={includes:Ys(!0),indexOf:Ys(!1)},Zs={},Xs=Js.indexOf,Qs=bi([].push),en=function(e,t){var i,r=Ni(e),s=0,n=[];for(i in r)!mr(Zs,i)&&mr(r,i)&&Qs(n,i);for(;t.length>s;)mr(r,i=t[s++])&&(~Xs(n,i)||Qs(n,i));return n},tn=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],rn=Object.keys||function(e){return en(e,tn)},sn=Ii&&!Gr?Object.defineProperties:function(e,t){zr(e);for(var i,r=Ni(t),s=rn(t),n=s.length,o=0;n>o;)ts.f(e,i=s[o++],r[i]);return e},nn={f:sn},on=Bi("document","documentElement"),an=gr("keys"),cn=function(e){return an[e]||(an[e]=Sr(e))},ln="prototype",hn="script",dn=cn("IE_PROTO"),un=function(){},gn=function(e){return"<"+hn+">"+e+"</"+hn+">"},fn=function(e){e.write(gn("")),e.close();var t=e.parentWindow.Object;return e=null,t},pn=function(){try{Ws=new ActiveXObject("htmlfile")}catch(e){}var e,t,i;pn="undefined"!=typeof document?document.domain&&Ws?fn(Ws):(t=$r("iframe"),i="java"+hn+":",t.style.display="none",on.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(gn("document.F=Object")),e.close(),e.F):fn(Ws);for(var r=tn.length;r--;)delete pn[ln][tn[r]];return pn()};Zs[dn]=!0;var vn,mn,bn,yn=Object.create||function(e,t){var i;return null!==e?(un[ln]=zr(e),i=new un,un[ln]=null,i[dn]=e):i=pn(),void 0===t?i:nn.f(i,t)},wn=tn.concat("length","prototype"),Sn={f:Object.getOwnPropertyNames||function(e){return en(e,wn)}},Tn=bi([].slice),Rn=Sn.f,En="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],In={f:function(e){return En&&"Window"===Si(e)?function(e){try{return Rn(e)}catch(e){return Tn(En)}}(e):Rn(Ni(e))}},Cn={f:Object.getOwnPropertySymbols},Pn=function(e,t,i,r){return r&&r.enumerable?e[t]=i:is(e,t,i),e},An={f:Ir},On=ts.f,kn=function(e){var t=Ui.Symbol||(Ui.Symbol={});mr(t,e)||On(t,e,{value:An.f(e)})},Dn=function(){var e=Bi("Symbol"),t=e&&e.prototype,i=t&&t.valueOf,r=Ir("toPrimitive");t&&!t[r]&&Pn(t,r,function(e){return Pi(i,this)},{arity:1})},$n=ws?{}.toString:function(){return"[object "+Es(this)+"]"},jn=ts.f,_n=Ir("toStringTag"),Hn=function(e,t,i,r){var s=i?e:e&&e.prototype;s&&(mr(s,_n)||jn(s,_n,{configurable:!0,value:t}),r&&!ws&&is(s,"toString",$n))},Mn=ci.WeakMap,xn=Ei(Mn)&&/native code/.test(String(Mn)),qn="Object already initialized",Nn=ci.TypeError,Fn=ci.WeakMap;if(xn||ur.state){var Un=ur.state||(ur.state=new Fn);Un.get=Un.get,Un.has=Un.has,Un.set=Un.set,vn=function(e,t){if(Un.has(e))throw new Nn(qn);return t.facade=e,Un.set(e,t),t},mn=function(e){return Un.get(e)||{}},bn=function(e){return Un.has(e)}}else{var Ln=cn("state");Zs[Ln]=!0,vn=function(e,t){if(mr(e,Ln))throw new Nn(qn);return t.facade=e,is(e,Ln,t),t},mn=function(e){return mr(e,Ln)?e[Ln]:{}},bn=function(e){return mr(e,Ln)}}var Bn,Wn,Gn,Vn={set:vn,get:mn,has:bn,enforce:function(e){return bn(e)?mn(e):vn(e,{})},getterFor:function(e){return function(t){var i;if(!Fi(t)||(i=mn(t)).type!==e)throw new Nn("Incompatible receiver, "+e+" required");return i}}},Kn=bi([].push),zn=function(e){var t=1===e,i=2===e,r=3===e,s=4===e,n=6===e,o=7===e,a=5===e||n;return function(c,l,h,d){for(var u,g,f=pr(c),p=Hi(f),v=ps(p),m=Wr(l,h),b=0,y=d||qs,w=t?y(c,v):i||o?y(c,0):void 0;v>b;b++)if((a||b in p)&&(g=m(u=p[b],b,f),e))if(t)w[b]=g;else if(g)switch(e){case 3:return!0;case 5:return u;case 6:return b;case 2:Kn(w,u)}else switch(e){case 4:return!1;case 7:Kn(w,u)}return n?-1:r||s?s:w}},Yn={forEach:zn(0),map:zn(1),filter:zn(2),some:zn(3),every:zn(4),find:zn(5),findIndex:zn(6),filterReject:zn(7)},Jn=Yn.forEach,Zn=cn("hidden"),Xn="Symbol",Qn="prototype",eo=Vn.set,to=Vn.getterFor(Xn),io=Object[Qn],ro=ci.Symbol,so=ro&&ro[Qn],no=ci.RangeError,oo=ci.TypeError,ao=ci.QObject,co=Hr.f,lo=ts.f,ho=In.f,uo=Di.f,go=bi([].push),fo=gr("symbols"),po=gr("op-symbols"),vo=gr("wks"),mo=!ao||!ao[Qn]||!ao[Qn].findChild,bo=function(e,t,i){var r=co(io,t);r&&delete io[t],lo(e,t,i),r&&e!==io&&lo(io,t,r)},yo=Ii&&li(function(){return 7!==yn(lo({},"a",{get:function(){return lo(this,"a",{value:7}).a}})).a})?bo:lo,wo=function(e,t){var i=fo[e]=yn(so);return eo(i,{type:Xn,tag:e,description:t}),Ii||(i.description=t),i},So=function(e,t,i){e===io&&So(po,t,i),zr(e);var r=Or(t);return zr(i),mr(fo,r)?(i.enumerable?(mr(e,Zn)&&e[Zn][r]&&(e[Zn][r]=!1),i=yn(i,{enumerable:$i(0,!1)})):(mr(e,Zn)||lo(e,Zn,$i(1,yn(null))),e[Zn][r]=!0),yo(e,r,i)):lo(e,r,i)},To=function(e,t){zr(e);var i=Ni(t),r=rn(i).concat(Co(i));return Jn(r,function(t){Ii&&!Pi(Ro,i,t)||So(e,t,i[t])}),e},Ro=function(e){var t=Or(e),i=Pi(uo,this,t);return!(this===io&&mr(fo,t)&&!mr(po,t))&&(!(i||!mr(this,t)||!mr(fo,t)||mr(this,Zn)&&this[Zn][t])||i)},Eo=function(e,t){var i=Ni(e),r=Or(t);if(i!==io||!mr(fo,r)||mr(po,r)){var s=co(i,r);return!s||!mr(fo,r)||mr(i,Zn)&&i[Zn][r]||(s.enumerable=!0),s}},Io=function(e){var t=ho(Ni(e)),i=[];return Jn(t,function(e){mr(fo,e)||mr(Zs,e)||go(i,e)}),i},Co=function(e){var t=e===io,i=ho(t?po:Ni(e)),r=[];return Jn(i,function(e){!mr(fo,e)||t&&!mr(io,e)||go(r,fo[e])}),r};er||(ro=function(){if(Wi(so,this))throw new oo("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?Vs(arguments[0]):void 0,t=Sr(e),i=function(e){var r=void 0===this?ci:this;r===io&&Pi(i,po,e),mr(r,Zn)&&mr(r[Zn],t)&&(r[Zn][t]=!1);var s=$i(1,e);try{yo(r,t,s)}catch(e){if(!(e instanceof no))throw e;bo(r,t,s)}};return Ii&&mo&&yo(io,t,{configurable:!0,set:i}),wo(t,e)},so=ro[Qn],Pn(so,"toString",function(){return to(this).tag}),Pn(ro,"withoutSetter",function(e){return wo(Sr(e),e)}),Di.f=Ro,ts.f=So,nn.f=To,Hr.f=Eo,Sn.f=In.f=Io,Cn.f=Co,An.f=function(e){return wo(Ir(e),e)},Ii&&(Bn=so,Wn="description",Gn={configurable:!0,get:function(){return to(this).description}},ts.f(Bn,Wn,Gn))),ns({global:!0,constructor:!0,wrap:!0,forced:!er,sham:!er},{Symbol:ro}),Jn(rn(vo),function(e){kn(e)}),ns({target:Xn,stat:!0,forced:!er},{useSetter:function(){mo=!0},useSimple:function(){mo=!1}}),ns({target:"Object",stat:!0,forced:!er,sham:!Ii},{create:function(e,t){return void 0===t?yn(e):To(yn(e),t)},defineProperty:So,defineProperties:To,getOwnPropertyDescriptor:Eo}),ns({target:"Object",stat:!0,forced:!er},{getOwnPropertyNames:Io}),Dn(),Hn(ro,Xn),Zs[Zn]=!0;var Po=er&&!!Symbol.for&&!!Symbol.keyFor,Ao=gr("string-to-symbol-registry"),Oo=gr("symbol-to-string-registry");ns({target:"Symbol",stat:!0,forced:!Po},{for:function(e){var t=Vs(e);if(mr(Ao,t))return Ao[t];var i=Bi("Symbol")(t);return Ao[t]=i,Oo[i]=t,i}});var ko=gr("symbol-to-string-registry");ns({target:"Symbol",stat:!0,forced:!Po},{keyFor:function(e){if(!rr(e))throw new TypeError(nr(e)+" is not a symbol");if(mr(ko,e))return ko[e]}});var Do=bi([].push),$o=String,jo=Bi("JSON","stringify"),_o=bi(/./.exec),Ho=bi("".charAt),Mo=bi("".charCodeAt),xo=bi("".replace),qo=bi(1.1.toString),No=/[\uD800-\uDFFF]/g,Fo=/^[\uD800-\uDBFF]$/,Uo=/^[\uDC00-\uDFFF]$/,Lo=!er||li(function(){var e=Bi("Symbol")("stringify detection");return"[null]"!==jo([e])||"{}"!==jo({a:e})||"{}"!==jo(Object(e))}),Bo=li(function(){return'"\\udf06\\ud834"'!==jo("\udf06\ud834")||'"\\udead"'!==jo("\udead")}),Wo=function(e,t){var i=Tn(arguments),r=function(e){if(Ei(e))return e;if(ls(e)){for(var t=e.length,i=[],r=0;r<t;r++){var s=e[r];"string"==typeof s?Do(i,s):"number"!=typeof s&&"Number"!==Si(s)&&"String"!==Si(s)||Do(i,Vs(s))}var n=i.length,o=!0;return function(e,t){if(o)return o=!1,t;if(ls(this))return t;for(var r=0;r<n;r++)if(i[r]===e)return t}}}(t);if(Ei(r)||void 0!==e&&!rr(e))return i[1]=function(e,t){if(Ei(r)&&(t=Pi(r,this,$o(e),t)),!rr(t))return t},fi(jo,null,i)},Go=function(e,t,i){var r=Ho(i,t-1),s=Ho(i,t+1);return _o(Fo,e)&&!_o(Uo,s)||_o(Uo,e)&&!_o(Fo,r)?"\\u"+qo(Mo(e,0),16):e};jo&&ns({target:"JSON",stat:!0,arity:3,forced:Lo||Bo},{stringify:function(e,t,i){var r=Tn(arguments),s=fi(Lo?Wo:jo,null,r);return Bo&&"string"==typeof s?xo(s,No,Go):s}});var Vo=!er||li(function(){Cn.f(1)});ns({target:"Object",stat:!0,forced:Vo},{getOwnPropertySymbols:function(e){var t=Cn.f;return t?t(pr(e)):[]}}),kn("asyncDispose"),kn("asyncIterator"),kn("dispose"),kn("hasInstance"),kn("isConcatSpreadable"),kn("iterator"),kn("match"),kn("matchAll"),kn("replace"),kn("search"),kn("species"),kn("split"),kn("toPrimitive"),Dn(),kn("toStringTag"),Hn(Bi("Symbol"),"Symbol"),kn("unscopables"),Hn(ci.JSON,"JSON",!0);var Ko,zo,Yo,Jo=Ui.Symbol,Zo={},Xo=Function.prototype,Qo=Ii&&Object.getOwnPropertyDescriptor,ea=mr(Xo,"name"),ta={EXISTS:ea,PROPER:ea&&"something"===function(){}.name,CONFIGURABLE:ea&&(!Ii||Ii&&Qo(Xo,"name").configurable)},ia=!li(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}),ra=cn("IE_PROTO"),sa=Object,na=sa.prototype,oa=ia?sa.getPrototypeOf:function(e){var t=pr(e);if(mr(t,ra))return t[ra];var i=t.constructor;return Ei(i)&&t instanceof i?i.prototype:t instanceof sa?na:null},aa=Ir("iterator"),ca=!1;[].keys&&("next"in(Yo=[].keys())?(zo=oa(oa(Yo)))!==Object.prototype&&(Ko=zo):ca=!0);var la=!Fi(Ko)||li(function(){var e={};return Ko[aa].call(e)!==e});Ko=la?{}:yn(Ko),Ei(Ko[aa])||Pn(Ko,aa,function(){return this});var ha={IteratorPrototype:Ko,BUGGY_SAFARI_ITERATORS:ca},da=ha.IteratorPrototype,ua=function(){return this},ga=ta.PROPER,fa=ha.BUGGY_SAFARI_ITERATORS,pa=Ir("iterator"),va="keys",ma="values",ba="entries",ya=function(){return this},wa=function(e,t,i,r,s,n,o){!function(e,t,i,r){var s=t+" Iterator";e.prototype=yn(da,{next:$i(+!r,i)}),Hn(e,s,!1,!0),Zo[s]=ua}(i,t,r);var a,c,l,h=function(e){if(e===s&&p)return p;if(!fa&&e&&e in g)return g[e];switch(e){case va:case ma:case ba:return function(){return new i(this,e)}}return function(){return new i(this)}},d=t+" Iterator",u=!1,g=e.prototype,f=g[pa]||g["@@iterator"]||s&&g[s],p=!fa&&f||h(s),v="Array"===t&&g.entries||f;if(v&&(a=oa(v.call(new e)))!==Object.prototype&&a.next&&(Hn(a,d,!0,!0),Zo[d]=ya),ga&&s===ma&&f&&f.name!==ma&&(u=!0,p=function(){return Pi(f,this)}),s)if(c={values:h(ma),keys:n?p:h(va),entries:h(ba)},o)for(l in c)(fa||u||!(l in g))&&Pn(g,l,c[l]);else ns({target:t,proto:!0,forced:fa||u},c);return o&&g[pa]!==p&&Pn(g,pa,p,{name:s}),Zo[t]=p,c},Sa=function(e,t){return{value:e,done:t}};ts.f;var Ta="Array Iterator",Ra=Vn.set,Ea=Vn.getterFor(Ta);wa(Array,"Array",function(e,t){Ra(this,{type:Ta,target:Ni(e),index:0,kind:t})},function(){var e=Ea(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,Sa(void 0,!0);switch(e.kind){case"keys":return Sa(i,!1);case"values":return Sa(t[i],!1)}return Sa([i,t[i]],!1)},"values"),Zo.Arguments=Zo.Array;for(var Ia in{CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0})Hn(ci[Ia],Ia),Zo[Ia]=Zo.Array;var Ca=Jo,Pa=ts.f,Aa=Ir("metadata"),Oa=Function.prototype;void 0===Oa[Aa]&&Pa(Oa,Aa,{value:null}),kn("metadata");var ka=Ca,Da=Bi("Symbol"),$a=Da.keyFor,ja=bi(Da.prototype.valueOf),_a=Da.isRegisteredSymbol||function(e){try{return void 0!==$a(ja(e))}catch(e){return!1}};ns({target:"Symbol",stat:!0},{isRegisteredSymbol:_a});for(var Ha=Bi("Symbol"),Ma=Ha.isWellKnownSymbol,xa=Bi("Object","getOwnPropertyNames"),qa=bi(Ha.prototype.valueOf),Na=gr("wks"),Fa=0,Ua=xa(Ha),La=Ua.length;Fa<La;Fa++)try{var Ba=Ua[Fa];rr(Ha[Ba])&&Ir(Ba)}catch(e){}var Wa=function(e){if(Ma&&Ma(e))return!0;try{for(var t=qa(e),i=0,r=xa(Na),s=r.length;i<s;i++)if(Na[r[i]]==t)return!0}catch(e){}return!1};ns({target:"Symbol",stat:!0,forced:!0},{isWellKnownSymbol:Wa}),kn("customMatcher"),kn("observable"),ns({target:"Symbol",stat:!0,name:"isRegisteredSymbol"},{isRegistered:_a}),ns({target:"Symbol",stat:!0,name:"isWellKnownSymbol",forced:!0},{isWellKnown:Wa}),kn("matcher"),kn("metadataKey"),kn("patternMatch"),kn("replaceAll");var Ga=ka,Va=bi("".charAt),Ka=bi("".charCodeAt),za=bi("".slice),Ya=function(e){return function(t,i){var r,s,n=Vs(qi(t)),o=gs(i),a=n.length;return o<0||o>=a?e?"":void 0:(r=Ka(n,o))<55296||r>56319||o+1===a||(s=Ka(n,o+1))<56320||s>57343?e?Va(n,o):r:e?za(n,o,o+2):s-56320+(r-55296<<10)+65536}},Ja={codeAt:Ya(!1),charAt:Ya(!0)}.charAt,Za="String Iterator",Xa=Vn.set,Qa=Vn.getterFor(Za);wa(String,"String",function(e){Xa(this,{type:Za,string:Vs(e),index:0})},function(){var e,t=Qa(this),i=t.string,r=t.index;return r>=i.length?Sa(void 0,!0):(e=Ja(i,r),t.index+=e.length,Sa(e,!1))});var ec=An.f("iterator");function tc(e){return tc="function"==typeof Ga&&"symbol"==typeof ec?function(e){return typeof e}:function(e){return e&&"function"==typeof Ga&&e.constructor===Ga&&e!==Ga.prototype?"symbol":typeof e},tc(e)}var ic=An.f("toPrimitive");function rc(e){var t=function(e,t){if("object"!=tc(e)||!e)return e;var i=e[ic];if(void 0!==i){var r=i.call(e,t||"default");if("object"!=tc(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==tc(t)?t:t+""}function sc(e,t){for(var i=0;i<t.length;i++){var r=t[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),cs(e,rc(r.key),r)}}var nc=Object.assign,oc=Object.defineProperty,ac=bi([].concat),cc=!nc||li(function(){if(Ii&&1!==nc({b:1},nc(oc({},"a",{enumerable:!0,get:function(){oc(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},i=Symbol("assign detection"),r="abcdefghijklmnopqrst";return e[i]=7,r.split("").forEach(function(e){t[e]=e}),7!==nc({},e)[i]||rn(nc({},t)).join("")!==r})?function(e,t){for(var i=pr(e),r=arguments.length,s=1,n=Cn.f,o=Di.f;r>s;)for(var a,c=Hi(arguments[s++]),l=n?ac(rn(c),n(c)):rn(c),h=l.length,d=0;h>d;)a=l[d++],Ii&&!Pi(o,c,a)||(i[a]=c[a]);return i}:nc;ns({target:"Object",stat:!0,arity:2,forced:Object.assign!==cc},{assign:cc});var lc=Ui.Object.assign,hc=!li(function(){return Object.isExtensible(Object.preventExtensions({}))}),dc=function(e,t,i){for(var r in t)i&&i.unsafe&&e[r]?e[r]=t[r]:Pn(e,r,t[r],i);return e},uc=li(function(){if("function"==typeof ArrayBuffer){var e=new ArrayBuffer(8);Object.isExtensible(e)&&Object.defineProperty(e,"a",{value:8})}}),gc=Object.isExtensible,fc=li(function(){gc(1)})||uc?function(e){return!!Fi(e)&&((!uc||"ArrayBuffer"!==Si(e))&&(!gc||gc(e)))}:gc,pc=si(function(e){var t=ts.f,i=!1,r=Sr("meta"),s=0,n=function(e){t(e,r,{value:{objectID:"O"+s++,weakData:{}}})},o=e.exports={enable:function(){o.enable=function(){},i=!0;var e=Sn.f,t=bi([].splice),s={};s[r]=1,e(s).length&&(Sn.f=function(i){for(var s=e(i),n=0,o=s.length;n<o;n++)if(s[n]===r){t(s,n,1);break}return s},ns({target:"Object",stat:!0,forced:!0},{getOwnPropertyNames:In.f}))},fastKey:function(e,t){if(!Fi(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!mr(e,r)){if(!fc(e))return"F";if(!t)return"E";n(e)}return e[r].objectID},getWeakData:function(e,t){if(!mr(e,r)){if(!fc(e))return!0;if(!t)return!1;n(e)}return e[r].weakData},onFreeze:function(e){return hc&&i&&fc(e)&&!mr(e,r)&&n(e),e}};Zs[r]=!0});pc.enable,pc.fastKey,pc.getWeakData,pc.onFreeze;var vc=Ir("iterator"),mc=Array.prototype,bc=Ir("iterator"),yc=function(e){if(!Mi(e))return cr(e,bc)||cr(e,"@@iterator")||Zo[Es(e)]},wc=TypeError,Sc=function(e,t,i){var r,s;zr(e);try{if(!(r=cr(e,"return"))){if("throw"===t)throw i;return i}r=Pi(r,e)}catch(e){s=!0,r=e}if("throw"===t)throw i;if(s)throw r;return zr(r),i},Tc=TypeError,Rc=function(e,t){this.stopped=e,this.result=t},Ec=Rc.prototype,Ic=function(e,t,i){var r,s,n,o,a,c,l,h,d=i&&i.that,u=!(!i||!i.AS_ENTRIES),g=!(!i||!i.IS_RECORD),f=!(!i||!i.IS_ITERATOR),p=!(!i||!i.INTERRUPTED),v=Wr(t,d),m=function(e){return r&&Sc(r,"normal"),new Rc(!0,e)},b=function(e){return u?(zr(e),p?v(e[0],e[1],m):v(e[0],e[1])):p?v(e,m):v(e)};if(g)r=e.iterator;else if(f)r=e;else{if(!(s=yc(e)))throw new Tc(nr(e)+" is not iterable");if(void 0!==(h=s)&&(Zo.Array===h||mc[vc]===h)){for(n=0,o=ps(e);o>n;n++)if((a=b(e[n]))&&Wi(Ec,a))return a;return new Rc(!1)}r=function(e,t){var i=arguments.length<2?yc(e):t;if(ar(i))return zr(Pi(i,e));throw new wc(nr(e)+" is not iterable")}(e,s)}for(c=g?e.next:r.next;!(l=Pi(c,r)).done;){try{a=b(l.value)}catch(e){Sc(r,"throw",e)}if("object"==typeof a&&a&&Wi(Ec,a))return a}return new Rc(!1)},Cc=TypeError,Pc=function(e,t){if(Wi(t,e))return e;throw new Cc("Incorrect invocation")},Ac=ts.f,Oc=Yn.forEach,kc=Vn.set,Dc=Vn.getterFor,$c=function(e,t,i){var r,s=-1!==e.indexOf("Map"),n=-1!==e.indexOf("Weak"),o=s?"set":"add",a=ci[e],c=a&&a.prototype,l={};if(Ii&&Ei(a)&&(n||c.forEach&&!li(function(){(new a).entries().next()}))){r=t(function(t,i){kc(Pc(t,h),{type:e,collection:new a}),Mi(i)||Ic(i,t[o],{that:t,AS_ENTRIES:s})});var h=r.prototype,d=Dc(e);Oc(["add","clear","delete","forEach","get","has","set","keys","values","entries"],function(e){var t="add"===e||"set"===e;!(e in c)||n&&"clear"===e||is(h,e,function(i,r){var s=d(this).collection;if(!t&&n&&!Fi(i))return"get"===e&&void 0;var o=s[e](0===i?0:i,r);return t?this:o})}),n||Ac(h,"size",{configurable:!0,get:function(){return d(this).collection.size}})}else r=i.getConstructor(t,e,s,o),pc.enable();return Hn(r,e,!1,!0),l[e]=r,ns({global:!0,forced:!0},l),n||i.setStrong(r,e,s),r},jc=pc.getWeakData,_c=Vn.set,Hc=Vn.getterFor,Mc=Yn.find,xc=Yn.findIndex,qc=bi([].splice),Nc=0,Fc=function(e){return e.frozen||(e.frozen=new Uc)},Uc=function(){this.entries=[]},Lc=function(e,t){return Mc(e.entries,function(e){return e[0]===t})};Uc.prototype={get:function(e){var t=Lc(this,e);if(t)return t[1]},has:function(e){return!!Lc(this,e)},set:function(e,t){var i=Lc(this,e);i?i[1]=t:this.entries.push([e,t])},delete:function(e){var t=xc(this.entries,function(t){return t[0]===e});return~t&&qc(this.entries,t,1),!!~t}};var Bc,Wc={getConstructor:function(e,t,i,r){var s=e(function(e,s){Pc(e,n),_c(e,{type:t,id:Nc++,frozen:null}),Mi(s)||Ic(s,e[r],{that:e,AS_ENTRIES:i})}),n=s.prototype,o=Hc(t),a=function(e,t,i){var r=o(e),s=jc(zr(t),!0);return!0===s?Fc(r).set(t,i):s[r.id]=i,e};return dc(n,{delete:function(e){var t=o(this);if(!Fi(e))return!1;var i=jc(e);return!0===i?Fc(t).delete(e):i&&mr(i,t.id)&&delete i[t.id]},has:function(e){var t=o(this);if(!Fi(e))return!1;var i=jc(e);return!0===i?Fc(t).has(e):i&&mr(i,t.id)}}),dc(n,i?{get:function(e){var t=o(this);if(Fi(e)){var i=jc(e);if(!0===i)return Fc(t).get(e);if(i)return i[t.id]}},set:function(e,t){return a(this,e,t)}}:{add:function(e){return a(this,e,!0)}}),s}},Gc=Vn.enforce,Vc=Object,Kc=Array.isArray,zc=Vc.isExtensible,Yc=Vc.isFrozen,Jc=Vc.isSealed,Zc=Vc.freeze,Xc=Vc.seal,Qc=!ci.ActiveXObject&&"ActiveXObject"in ci,el=function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}},tl=$c("WeakMap",el,Wc),il=tl.prototype,rl=bi(il.set);if(xn)if(Qc){Bc=Wc.getConstructor(el,"WeakMap",!0),pc.enable();var sl=bi(il.delete),nl=bi(il.has),ol=bi(il.get);dc(il,{delete:function(e){if(Fi(e)&&!zc(e)){var t=Gc(this);return t.frozen||(t.frozen=new Bc),sl(this,e)||t.frozen.delete(e)}return sl(this,e)},has:function(e){if(Fi(e)&&!zc(e)){var t=Gc(this);return t.frozen||(t.frozen=new Bc),nl(this,e)||t.frozen.has(e)}return nl(this,e)},get:function(e){if(Fi(e)&&!zc(e)){var t=Gc(this);return t.frozen||(t.frozen=new Bc),nl(this,e)?ol(this,e):t.frozen.get(e)}return ol(this,e)},set:function(e,t){if(Fi(e)&&!zc(e)){var i=Gc(this);i.frozen||(i.frozen=new Bc),nl(this,e)?rl(this,e,t):i.frozen.set(e,t)}else rl(this,e,t);return this}})}else hc&&li(function(){var e=Zc([]);return rl(new tl,e,1),!Yc(e)})&&dc(il,{set:function(e,t){var i;return Kc(e)&&(Yc(e)?i=Zc:Jc(e)&&(i=Xc)),rl(this,e,t),i&&i(e),this}});var al=Ui.WeakMap,cl=TypeError,ll=function(e){if("object"==typeof e&&"has"in e&&"get"in e&&"set"in e)return e;throw new cl(nr(e)+" is not a weakmap")},hl=function(e,t){return 1===t?function(t,i){return t[e](i)}:function(t,i,r){return t[e](i,r)}},dl={WeakMap:Bi("WeakMap"),set:hl("set",2),get:hl("get",1),has:hl("has",1),remove:hl("delete",1)},ul=dl.get,gl=dl.has,fl=dl.set;ns({target:"WeakMap",proto:!0,real:!0,forced:hr},{getOrInsert:function(e,t){return gl(ll(this),e)?ul(this,e):(fl(this,e,t),t)}});var pl=new dl.WeakMap,vl=dl.set,ml=dl.remove,bl=dl.get,yl=dl.has,wl=dl.set;ns({target:"WeakMap",proto:!0,real:!0,forced:true},{getOrInsertComputed:function(e,t){if(ll(this),function(e){vl(pl,e,1),ml(pl,e)}(e),ar(t),yl(this,e))return bl(this,e);var i=t(e);return wl(this,e,i),i}});var Sl=al,Tl=function(e,t,i){return function(r){var s=pr(r),n=arguments.length,o=n>1?arguments[1]:void 0,a=void 0!==o,c=a?Wr(o,n>2?arguments[2]:void 0):void 0,l=new e,h=0;return Ic(s,function(e){var r=a?c(e,h++):e;i?t(l,zr(r)[0],r[1]):t(l,r)}),l}};ns({target:"WeakMap",stat:!0,forced:!0},{from:Tl(dl.WeakMap,dl.set,!0)});var Rl=function(e,t,i){return function(){for(var r=new e,s=arguments.length,n=0;n<s;n++){var o=arguments[n];i?t(r,zr(o)[0],o[1]):t(r,o)}return r}};ns({target:"WeakMap",stat:!0,forced:!0},{of:Rl(dl.WeakMap,dl.set,!0)});var El=dl.get,Il=dl.has,Cl=dl.set;ns({target:"WeakMap",proto:!0,real:!0,forced:!0},{emplace:function(e,t){var i,r,s=ll(this);return Il(s,e)?(i=El(s,e),"update"in t&&(i=t.update(i,e,s),Cl(s,e,i)),i):(r=t.insert(e,s),Cl(s,e,r),r)}});var Pl=dl.remove;ns({target:"WeakMap",proto:!0,real:!0,forced:!0},{deleteAll:function(){for(var e,t=ll(this),i=!0,r=0,s=arguments.length;r<s;r++)e=Pl(t,arguments[r]),i=i&&e;return!!i}});var Al=TypeError;ns({target:"WeakMap",proto:!0,real:!0,forced:!0},{upsert:function(e,t){var i,r=zr(this),s=ar(r.get),n=ar(r.has),o=ar(r.set),a=arguments.length>2?arguments[2]:void 0;if(!Ei(t)&&!Ei(a))throw new Al("At least one callback required");return Pi(n,r,e)?(i=Pi(s,r,e),Ei(t)&&(i=t(i),Pi(o,r,e,i))):Ei(a)&&(i=a(),Pi(o,r,e,i)),i}});var Ol=Sl;$c("WeakSet",function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}},Wc);var kl=Ui.WeakSet,Dl=TypeError,$l=function(e){if("object"==typeof e&&"has"in e&&"add"in e&&"delete"in e)return e;throw new Dl(nr(e)+" is not a weakset")},jl={WeakSet:Bi("WeakSet"),add:hl("add",1),has:hl("has",1),remove:hl("delete",1)},_l=jl.add;ns({target:"WeakSet",proto:!0,real:!0,forced:!0},{addAll:function(){for(var e=$l(this),t=0,i=arguments.length;t<i;t++)_l(e,arguments[t]);return e}});var Hl=jl.remove;ns({target:"WeakSet",proto:!0,real:!0,forced:!0},{deleteAll:function(){for(var e,t=$l(this),i=!0,r=0,s=arguments.length;r<s;r++)e=Hl(t,arguments[r]),i=i&&e;return!!i}}),ns({target:"WeakSet",stat:!0,forced:!0},{from:Tl(jl.WeakSet,jl.add,!1)}),ns({target:"WeakSet",stat:!0,forced:!0},{of:Rl(jl.WeakSet,jl.add,!1)});var Ml=kl,xl=si(function(e,t){e.exports=function(){function e(e){return!isNaN(parseFloat(e))&&isFinite(e)}function t(e){return e.charAt(0).toUpperCase()+e.substring(1)}function i(e){return function(){return this[e]}}var r=["isConstructor","isEval","isNative","isToplevel"],s=["columnNumber","lineNumber"],n=["fileName","functionName","source"],o=["args"],a=["evalOrigin"],c=r.concat(s,n,o,a);function l(e){if(e)for(var i=0;i<c.length;i++)void 0!==e[c[i]]&&this["set"+t(c[i])](e[c[i]])}l.prototype={getArgs:function(){return this.args},setArgs:function(e){if("[object Array]"!==Object.prototype.toString.call(e))throw new TypeError("Args must be an Array");this.args=e},getEvalOrigin:function(){return this.evalOrigin},setEvalOrigin:function(e){if(e instanceof l)this.evalOrigin=e;else{if(!(e instanceof Object))throw new TypeError("Eval Origin must be an Object or StackFrame");this.evalOrigin=new l(e)}},toString:function(){var e=this.getFileName()||"",t=this.getLineNumber()||"",i=this.getColumnNumber()||"",r=this.getFunctionName()||"";return this.getIsEval()?e?"[eval] ("+e+":"+t+":"+i+")":"[eval]:"+t+":"+i:r?r+" ("+e+":"+t+":"+i+")":e+":"+t+":"+i}},l.fromString=function(e){var t=e.indexOf("("),i=e.lastIndexOf(")"),r=e.substring(0,t),s=e.substring(t+1,i).split(","),n=e.substring(i+1);if(0===n.indexOf("@"))var o=/@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(n,""),a=o[1],c=o[2],h=o[3];return new l({functionName:r,args:s||void 0,fileName:a,lineNumber:c||void 0,columnNumber:h||void 0})};for(var h=0;h<r.length;h++)l.prototype["get"+t(r[h])]=i(r[h]),l.prototype["set"+t(r[h])]=function(e){return function(t){this[e]=Boolean(t)}}(r[h]);for(var d=0;d<s.length;d++)l.prototype["get"+t(s[d])]=i(s[d]),l.prototype["set"+t(s[d])]=function(t){return function(i){if(!e(i))throw new TypeError(t+" must be a Number");this[t]=Number(i)}}(s[d]);for(var u=0;u<n.length;u++)l.prototype["get"+t(n[u])]=i(n[u]),l.prototype["set"+t(n[u])]=function(e){return function(t){this[e]=String(t)}}(n[u]);return l}()}),ql=si(function(e,t){var i,r,s,n;e.exports=(i=xl,r=/(^|@)\S+:\d+/,s=/^\s*at .*(\S+:\d+|\(native\))/m,n=/^(eval@)?(\[native code])?$/,{parse:function(e){if(void 0!==e.stacktrace||void 0!==e["opera#sourceloc"])return this.parseOpera(e);if(e.stack&&e.stack.match(s))return this.parseV8OrIE(e);if(e.stack)return this.parseFFOrSafari(e);throw new Error("Cannot parse given Error object")},extractLocation:function(e){if(-1===e.indexOf(":"))return[e];var t=/(.+?)(?::(\d+))?(?::(\d+))?$/.exec(e.replace(/[()]/g,""));return[t[1],t[2]||void 0,t[3]||void 0]},parseV8OrIE:function(e){return e.stack.split("\n").filter(function(e){return!!e.match(s)},this).map(function(e){e.indexOf("(eval ")>-1&&(e=e.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var t=e.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),r=t.match(/ (\(.+\)$)/);t=r?t.replace(r[0],""):t;var s=this.extractLocation(r?r[1]:t),n=r&&t||void 0,o=["eval","<anonymous>"].indexOf(s[0])>-1?void 0:s[0];return new i({functionName:n,fileName:o,lineNumber:s[1],columnNumber:s[2],source:e})},this)},parseFFOrSafari:function(e){return e.stack.split("\n").filter(function(e){return!e.match(n)},this).map(function(e){if(e.indexOf(" > eval")>-1&&(e=e.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),-1===e.indexOf("@")&&-1===e.indexOf(":"))return new i({functionName:e});var t=/((.*".+"[^@]*)?[^@]*)(?:@)/,r=e.match(t),s=r&&r[1]?r[1]:void 0,n=this.extractLocation(e.replace(t,""));return new i({functionName:s,fileName:n[0],lineNumber:n[1],columnNumber:n[2],source:e})},this)},parseOpera:function(e){return!e.stacktrace||e.message.indexOf("\n")>-1&&e.message.split("\n").length>e.stacktrace.split("\n").length?this.parseOpera9(e):e.stack?this.parseOpera11(e):this.parseOpera10(e)},parseOpera9:function(e){for(var t=/Line (\d+).*script (?:in )?(\S+)/i,r=e.message.split("\n"),s=[],n=2,o=r.length;n<o;n+=2){var a=t.exec(r[n]);a&&s.push(new i({fileName:a[2],lineNumber:a[1],source:r[n]}))}return s},parseOpera10:function(e){for(var t=/Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i,r=e.stacktrace.split("\n"),s=[],n=0,o=r.length;n<o;n+=2){var a=t.exec(r[n]);a&&s.push(new i({functionName:a[3]||void 0,fileName:a[2],lineNumber:a[1],source:r[n]}))}return s},parseOpera11:function(e){return e.stack.split("\n").filter(function(e){return!!e.match(r)&&!e.match(/^Error created at/)},this).map(function(e){var t,r=e.split("@"),s=this.extractLocation(r.pop()),n=r.shift()||"",o=n.replace(/<anonymous function(: (\w+))?>/,"$2").replace(/\([^)]*\)/g,"")||void 0;n.match(/\(([^)]*)\)/)&&(t=n.replace(/^[^(]+\(([^)]*)\)$/,"$1"));var a=void 0===t||"[arguments not available]"===t?void 0:t.split(",");return new i({functionName:o,args:a,fileName:s[0],lineNumber:s[1],columnNumber:s[2],source:e})},this)}})});Date.now=Date.now||function(){return(new Date).getTime()};var Nl=Date.now(),Fl=function(){},Ul={noop:Fl,warn:function(){var e="object"==typeof console?console.warn:Fl;try{var t={warn:e};t.warn.call(t)}catch(e){return Fl}return e}(),key:"__bl",selfErrKey:"ARMS_SDK_ERROR",selfErrPage:"ARMSSDK",win:"object"==typeof window&&window.document?window:void 0,regionMap:{cn:"https://arms-retcode.aliyuncs.com/r.png?",sg:"https://arms-retcode-sg.aliyuncs.com/r.png?",sg_2:"https://retcode-sg-lazada.arms.aliyuncs.com/r.png?",daily:"http://arms-retcode-daily.alibaba.net/r.png?",daily_2:"https://arms-retcode-daily.alibaba.net/r.png?",us:"https://retcode-us-west-1.arms.aliyuncs.com/r.png?",tw:"https://arms-retcode.orientalgame.com.tw/r.png?",tw_sg:"https://arms-retcode-sg.orientalgame.com.tw/r.png?",hz_finance:"https://arms-retcode-hz-finance.aliyuncs.com/r.png?"},defaultImgUrl:"https://arms-retcode.aliyuncs.com/r.png?",createObject:function(e){if(Object.create)return Object.create(e);var t=function(){};return t.prototype=e,new t},each:function(e,t){var i=0,r=e.length;if(this.T(e,"Array"))for(;i<r&&!1!==t.call(e[i],e[i],i);i++);else for(i in e)if(!1===t.call(e[i],e[i],i))break;return e},safetyCall:function(e,t,i){if("function"!=typeof e)return i;try{return e.apply(this,t)}catch(e){return i}},T:function(e,t){var i=Object.prototype.toString.call(e).substring(8).replace("]","");return t?i===t:i},filterByRule:function(e,t){if(!e)return"";if(!t)return e;var i=this,r=i.T(t);return"Function"===r?i.safetyCall(t,[e],e):"Array"===r?(this.each(t,function(t){e=i.filterByRule(e,t)}),e):"Object"===r?e.replace(t.rule,t.target||""):e.replace(t,"")},ignoreByRule:function(e,t){if(!e||!t)return!1;if((this.isString(t)||t.source||"Function"===this.T(t))&&(t=[t]),!this.isArray(t))return this.warn("[arms] invalid rules of ignore config, (list of) String/RegExp/Funcitons are available"),!1;for(var i,r=[],s=0,n=t.length;s<n;s++)if(i=t[s],this.isString(i))r.push(i.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1"));else if(i&&i.source)r.push(i.source);else if(i&&"Function"===this.T(i)&&!0===this.safetyCall(i,[e],!1))return!0;var o=new RegExp(r.join("|"),"i");return!!(r.length&&o.test&&o.test(e))},J:function(e){if(!e||"string"!=typeof e)return e;var t=null;try{t=JSON.parse(e)}catch(e){}return t},pick:function(e){return 1===e||1===Math.ceil(Math.random()*e)},verifyConfig:function(e){if("sample"in e){var t=e.sample,i=t;t&&/^\d+(\.\d+)?%$/.test(t)&&(i=parseInt(100/parseFloat(t))),0<i&&1>i&&(i=parseInt(1/i)),i>=1&&i<=100?e.sample=i:delete e.sample}return e},on:function(e,t,i,r,s){return e.addEventListener?(s=s||!1,e.addEventListener(t,function n(o){r&&e.removeEventListener(t,n,s),i.call(this,o)},s)):e.attachEvent&&e.attachEvent("on"+t,function s(n){r&&e.detachEvent("on"+t,s),i.call(this,n)}),this},off:function(e,t,i){return i?(e.removeEventListener?e.removeEventListener(t,i):e.detachEvent&&e.detachEvent(t,i),this):this},delay:function(e,t){return-1===t?(e(),null):setTimeout(e,t||0)},ext:function(e){for(var t=1,i=arguments.length;t<i;t++){var r=arguments[t];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},sub:function(e,t){var i={};return this.each(e,function(e,r){-1!==t.indexOf(r)&&(i[r]=e)}),i},uu:function(){for(var e,t,i=20,r=new Array(i),s=Date.now().toString(36).split("");i-- >0;)t=(e=36*Math.random()|0).toString(36),r[i]=e%3?t:t.toUpperCase();for(var n=0;n<8;n++)r.splice(3*n+2,0,s[n]);return r.join("")},seq:function(){return(Nl++).toString(36)},decode:function(e){try{e=decodeURIComponent(e)}catch(e){}return e},encode:function(e,t){try{e=t?encodeURIComponent(e).replace(/\(/g,"%28").replace(/\)/g,"%29"):encodeURIComponent(e)}catch(e){}return e},serialize:function(e){e=e||{};var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&void 0!==e[i]&&t.push(i+"="+this.encode(e[i],"msg"===i));return t.join("&")},checkAPI:function(e,t){if(!e||"string"!=typeof e)return!1;var i=/arms-retcode[\w-]*\.aliyuncs/.test(e);return!i&&t&&(i=/(\.png)|(\.gif)|(alicdn\.com)|(mmstat\.com)/.test(e)),!i},checkAutoError:function(e){return!(!e||!e.message||/failed[\w\s]+fetch/i.test(e.message))},cutUrlSearch:function(e){return e&&"string"==typeof e?e.replace(/^(https?:)?\/\//,"").replace(/\?.*$/,""):""},removeUrlSearch:function(e){return e&&"string"==typeof e?e.replace(/\?.*$/,""):""},createFakeToString:function(e){return function(){return e+"() { [native code] }"}},checkSameOrigin:function(e,t){if(!t||!e)return!1;var i="//"+t.split("/")[2];return e===t||e.slice(0,t.length+1)===t+"/"||e===i||e.slice(0,i.length+1)===i+"/"||!/^(\/\/|http:|https:).*/.test(e)},getRandIP:function(){for(var e=[],t=0;t<4;t++){var i=Math.floor(256*Math.random());e[t]=(i>15?"":"0")+i.toString(16)}return e.join("").replace(/^0/,"1")},getSortNum:function(e){return e?(e+=1)>=1e3&&e<=9999?e:e<1e3?e+1e3:e%1e4+1e3:1e3},getRandNum:function(e){return e&&"string"==typeof e?e.length<5?this.getNum(5):e.substring(e.length-5):this.getNum(5)},getNum:function(e){for(var t=[],i=0;i<e;i++){var r=Math.floor(16*Math.random());t[i]=r.toString(16)}return t.join("")},getCurDomain:function(){return location&&location.hostname||""},parseFetchHeaders:function(e){if(!e)return{};var t={};try{if("function"==typeof e.keys)for(var i=e.keys(),r=i.next();!r.done;){var s=r.value;t[s]=e.get(s),r=i.next()}else t=e}catch(e){t={}}return t},parseXhrHeaders:function(e){if(!e&&"string"!=typeof e)return{};var t={};try{t=e.split("\r\n").reduce(function(e,t){var i=t.split(": ");return e[i[0]]=i[1],e},{})}catch(e){t={}}return t},getQuerys:function(e){if(!e)return"";var t={},i=[],r="",s="";try{var n=[];if(e.indexOf("?")>=0&&(n=e.substring(e.indexOf("?")+1,e.length).split("&")),n.length>0)for(var o in n)r=(i=n[o].split("="))[0],s=i[1],t[r]=s}catch(e){t={}}return t},getFetchSnapshot:function(e,t,i){var r,s;try{var n=(e&&"string"!=typeof e[0]?e[0].url:e[0])||"",o=(e&&"string"!=typeof e[0]?e[0]:e[1])||{},a="POST"===o.method.toUpperCase()?o.body:this.getQuerys(n);r={originApi:n,method:o.method||"unknown",params:a,response:t||"",reqHeaders:this.parseFetchHeaders(o.headers||null),resHeaders:this.parseFetchHeaders(i)},s="function"==typeof encodeURIComponent&&JSON&&encodeURIComponent(JSON.stringify(r))||"{}"}catch(e){s="{}"}return s},getXhrSnapshot:function(e,t,i){if(!e||!t||!i)return{};var r,s;try{var n="";""===i.responseType||"text"===i.responseType?n=i.responseText:"document"===i.responseType&&(n=i.responseXML),r={originApi:e,method:t,params:this.getQuerys(e),response:n,reqHeaders:{},resHeaders:this.parseXhrHeaders("function"==typeof i.getAllResponseHeaders&&i.getAllResponseHeaders()||"")},s="function"==typeof encodeURIComponent&&JSON&&encodeURIComponent(JSON.stringify(r))||"{}"}catch(e){s="{}"}return s},isRobot:function(){var e=["nuhk","googlebot/","googlebot-image","yammybot","openbot","slurp","msnbot","ask jeeves/teoma","ia_archiver","baiduspider","bingbot/","adsbot"];if(!navigator||"string"!=typeof navigator.userAgent)return!1;try{for(var t=navigator.userAgent.toLowerCase(),i=0;i<e.length;i++){var r=e[i];if(t.lastIndexOf(r)>=0)return!0}}catch(e){this.warn("[arms] useragent parse error")}return!1},isFunction:function(e){return"function"==typeof e},isPlainObject:function(e){return"[object Object]"===Object.prototype.toString.call(e)},isString:function(e){return"[object String]"===Object.prototype.toString.call(e)},isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},joinRegExp:function(e){for(var t,i=[],r=0,s=e.length;r<s;r++)t=e[r],this.isString(t)?i.push(t.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1")):t&&t.source&&i.push(t.source);return new RegExp(i.join("|"),"i")},reWriteMethod:function(e,t,i){if(null!==e){var r=e[t];e[t]=i(r)}},checkSDKError:function(e,t){return!(!e&&!t)&&(!!new RegExp(this.selfErrKey,"i").test(e)||!!this.ignoreByRule(t,[/retcode.alicdn.com\/retcode\/bl.js/,/g.alicdn.com\/retcode\/cloud-sdk\/bl.js/,/laz-g-cdn.alicdn.com\/retcode\/cloud-sdk\/bl.js/,/local.taobao.com:8880\/build\/bl/]))},sdkError:function(e){return{msg:e,message:this.selfErrKey}},dealParam:function(e,t,i){var r={};try{r=this.isPlainObject(e)?this.ext({key:e.key||"default",val:e.val||e.value||i},e,{begin:Date.now()}):{key:e||"default",val:t||i,begin:Date.now()}}catch(e){this.warn("[retcode] baseLog error: "+e)}return r}},Ll=Ul,Bl=si(function(e){var t="aokcdqn3ly@e629dabd48a9933",i=function(e,t){var i;if("error"!==t.t||!(i=e.requestQueue[0])||"error"!==i.t||t.msg!==i.msg){if("behavior"===t.t){var r=e.requestQueue&&e.requestQueue.length;if(r>0&&"behavior"===e.requestQueue[r-1].t){var s=t.behavior||[];e.requestQueue[r-1].behavior.concat(s)}else e.requestQueue.push(t)}else e.requestQueue.unshift(t);return e.onReady(function(){e.requestTimmer=Ll.delay(function(){e.clear()},e.requestQueue[0]&&"error"===e.requestQueue[0].t?3e3:-1)}),!0}i.times++},r=function(e){return this.ver="1.8.30",this._conf=Ll.ext({},r.dftCon),this.sampleCache={},this.requestQueue=[],this.selfQueue=[],this.sdkFlag=!0,this.hash=Ll.seq(),this.resetPageview(),this.setConfig(e),this.rip=Ll.getRandIP(),this.record=999,this["EagleEye-TraceID"]=this.getTraceId()["EagleEye-TraceID"],this._common={},this};r.dftCon={sample:1,pvSample:1,tag:"",imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",region:null,ignore:{ignoreUrls:[],ignoreApis:[],ignoreErrors:[/^Script error\.?$/],ignoreResErrors:[]},release:void 0,environment:"prod"},r.prototype={constructor:r,onReady:function(e){return e()},getPage:function(){var e=this._conf.page;return Ll.safetyCall(e,[],e+"")},setPage:function(){},setConfig:function(e){e&&"object"==typeof e&&(Ll.verifyConfig(e),e=this.setImgUrl(e),this._conf=Ll.ext({},this._conf,e))},setImgUrl:function(e){var t=e.region,i=e.imgUrl;if(t){var r=Ll.regionMap[t];return e.imgUrl=r||Ll.defaultImgUrl,e}return i&&(e.imgUrl=i),e},checkImgUrl:function(e){if(this.getConfig("debug"))return!0;var t=Ll.regionMap,i=!1;for(var r in t)if(t[r]===e){i=!0;break}return!i&&Ll.warn("[retcode] invalid url: "+e),i},sendRequest:function(){},sendBeacon:function(e){!function(e,t){"object"==typeof e&&(e=Ll.serialize(e));var i=t+e;window&&window.navigator&&"function"==typeof window.navigator.sendBeacon?window.navigator.sendBeacon(i,"&post_res="):Ll.warn("[arms] navigator.sendBeacon not surported")}(e,this.getConfig("imgUrl"))},postData:function(){},commonInfo:function(){return{}},setCommonInfo:function(e){e&&"object"==typeof e&&(this._common=Ll.ext({},this._common,e))},resetPageview:function(){this.pageview=Ll.uu(),this.sBegin=Date.now()},getUsername:function(){if(this.username)return this.username;var e=this._conf,t=e&&e.setUsername;if("function"==typeof t)try{var i=t();"string"==typeof i&&(i=i.substr(0,40),this.username=i)}catch(e){Ll.warn("[arms] setUsername fail",e)}return this.username},getTraceId:function(){var e=this.rip,t=Date.now(),i=Ll.getSortNum(this.record),r=e+t+i+Ll.getRandNum(this._conf.pid);return this["EagleEye-TraceID"]=r,this.record=i,{"EagleEye-TraceID":r}},getUberTraceId:function(e){var t=this.rip,i=Date.now(),r=Ll.getSortNum(this.record),s=Ll.getRandNum(this._conf.pid),n=t+i+r+Ll.getNum(2)+s,o=n.substring(0,16);return{"uber-trace-id":n+":"+o+":0:"+(e=e?"1":"0"),traceId:n}},getPageviewId:function(){return{"EagleEye-SessionID":this.pageview}},getConfig:function(e){return e?this._conf[e]:Ll.ext({},this._conf)},sampling:function(e){return 1===e||("boolean"==typeof this.sampleCache[e]||(this.sampleCache[e]=Ll.pick(e)),this.sampleCache[e])},clear:function(e){var t;clearTimeout(this.requestTimmer),this.requestTimmer=null;for(var i=this._conf&&"function"==typeof this._conf.sendRequest;t=this.requestQueue.pop();)"res"===t.t?this.postData(t,"res"):"error"===t.t?this.postData(t,"err"):"api"===t.t?this.postData(t,"apiSnapshot"):"behavior"===t.t?this.postData(t,"behavior"):"health"===t.t&&!i&&window&&window.navigator&&"function"==typeof window.navigator.sendBeacon?this.sendBeacon(t):this.sendRequest(t);return e&&this.clearSelf(),this},clearSelf:function(){var e;for(clearTimeout(this.Timmer),this.Timmer=null;e=this.selfQueue.pop();)this.postData(e,"err");return this},_lg:function(e,t,r,s){var n=this._conf,o=this.getPage(),a=n.ignore||{},c=a.ignoreErrors,l=a.ignoreResErrors,h=a.ignoreUrls,d=a.ignoreApis;if(this._isRobot)return this;if(Ll.ignoreByRule(o,h)||Ll.ignoreByRule(Ll.decode(o),h))return this;if("error"===e&&(Ll.ignoreByRule(t.msg,c)||Ll.ignoreByRule(Ll.decode(t.msg),c)))return this;if("resourceError"===e&&(Ll.ignoreByRule(t.src,l)||Ll.ignoreByRule(Ll.decode(t.src),l)))return this;if("api"===e&&(Ll.ignoreByRule(t.api,d)||Ll.ignoreByRule(Ll.decode(t.api),d)))return this;if(!this.checkImgUrl(n.imgUrl))return this;if(!t||n.disabled||!n.pid)return this;if(0===s)return this;var u=t.dl;return delete t.dl,t=Ll.ext({t:e,times:1,page:o,tag:n.tag||"",release:n.release||"",environment:n.environment,begin:Date.now(),c1:n.c1,c2:n.c2,c3:n.c3},t,this.commonInfo(),this._common,{pid:n.pid,_v:this.ver,pv_id:this.pageview,username:this.getUsername(),sampling:r||1,dl:u,z:Ll.seq()}),1===s?i(this,t):r&&!this.sampling(r)?this:i(this,t)},_self:function(e,i,r){var s=this,n=s._conf;if("error"!==e)return s;if(!s.checkImgUrl(n.imgUrl))return s;if(!i||n.disabled||!n.pid)return s;if(r&&!s.sampling(r))return s;i=Ll.ext({t:e,times:1,page:Ll.selfErrPage,tag:n.pid,begin:Date.now()},i,{pid:t,_v:s.ver,sampling:r||1,z:Ll.seq()});var o=s.selfQueue[0];if(o){o.times++;try{o.err&&i.err&&o.err.msg_raw&&i.err.msg_raw&&o.err.msg_raw.split("&").indexOf(i.err.msg_raw)<0&&o.err.msg_raw.length<1e3&&(o.err.msg_raw+="&"+i.err.msg_raw)}catch(e){}}else s.selfQueue.unshift(i),s.onReady(function(){s.sdkFlag&&(s.sdkFlag=!1,s.Timmer=Ll.delay(function(){s.clearSelf()},1e4))})},custom:function(e,t){if(!e||"object"!=typeof e)return this;var i=!1,r={begin:Date.now()};return Ll.each(e,function(e,t){return!(i=t&&t.length<=20)&&Ll.warn("[retcode] invalid key: "+t),r["x-"+t]=e,i}),i?this._lg("custom",r,t||1):this}},e.exports=r}),Wl=si(function(e){var t=["api","success","time","code","msg","trace","traceId","begin","pv_id","sid","seq","domain","flag"],i=function(e){var t=(e.key||"default").split("::");return t.length>1?Ll.ext(e,{group:t[0],key:t[1]}):Ll.ext(e,{group:"default_group",key:t[0]})},r=function(e){var t;Bl.call(this,e);try{t="object"==typeof performance?performance.timing.fetchStart:Date.now()}catch(e){t=Date.now()}return this._startTime=t,this};r.prototype=Ll.createObject(Bl.prototype),Ll.ext(Bl.dftCon,{startTime:null}),Ll.ext(r.prototype,{constructor:r,_super:Bl,sum:function(e,t,r){try{var s=Ll.dealParam(e,t,1);return this._lg("sum",i(s),r)}catch(e){Ll.warn("[retcode] can not get parseStatData: "+e)}},avg:function(e,t,r){try{var s=Ll.dealParam(e,t,0);return this._lg("avg",i(s),r)}catch(e){Ll.warn("[retcode] can not get parseStatData: "+e)}},percent:function(e,t,r,s){try{return this._lg("percent",i({key:e,subkey:t,val:r||0,begin:Date.now()}),s)}catch(e){Ll.warn("[retcode] can not get parseStatData: "+e)}},msg:function(e,t){if(e&&!(e.length>180))return this.custom({msg:e},t)},error:function(e,t){if(!e)return Ll.warn("[retcode] invalid param e: "+e),this;1===arguments.length?("string"==typeof e&&(e={message:e},t={}),"object"==typeof e&&(t=e=e.error||e)):("string"==typeof e&&(e={message:e}),"object"!=typeof t&&(t={}));var i=e.name||"CustomError",r=e.message||"",s=e.stack||"";t=t||{};var n="object"==typeof location&&"string"==typeof location.href&&location.href.substring(0,500)||"";if(Ll.checkSDKError(r,t.filename)){var o=/^Script error\.?$/,a=e.msg||e.message;if(Ll.ignoreByRule(a,o)||Ll.ignoreByRule(Ll.decode(a),o))return this;var c={msg:Ll.selfErrKey,err:{msg_raw:Ll.encode(e.msg||e.message)}};return this._self("error",c,1)}for(var l={begin:Date.now(),cate:i,msg:r&&r.substring(0,1e3),stack:s&&s.substring(0,1e3),file:Ll.removeUrlSearch(t.filename||""),line:t.lineno||"",col:t.colno||"",err:{msg_raw:Ll.encode(r),stack_raw:Ll.encode(s)},dl:n},h=["tag","c1","c2","c3"],d=0;d<h.length;d++){var u=h[d];t[u]&&(l[u]=t[u])}var g=(this.getConfig("ignore")||{}).ignoreErrors;return Ll.ignoreByRule(l.msg,g)||Ll.ignoreByRule(Ll.decode(l.msg),g)?this:(this.beforeSend&&this.beforeSend("error",l),this._lg("error",l,1))},behavior:function(e){if(e){var t="object"==typeof e&&e.behavior?e:{behavior:e};return this.beforeSend&&this.beforeSend("behavior",t),this._lg("behavior",t,1)}},api:function(e,i,r,s,n,o,a,c,l,h,d,u){if(!e)return Ll.warn("[retcode] api is null"),this;if(e="string"==typeof e?{api:e,success:i,time:r,code:s,msg:n,begin:o,traceId:a,pv_id:c,apiSnapshot:l,domain:h,flag:u}:Ll.sub(e,t),!Ll.checkAPI(e.api,!0))return this;e.code=e.code||"";var g=e.msg||"";if(g="string"==typeof g?g.substring(0,1e3):g,e.msg=g,e.success=e.success?1:0,e.time=+e.time,e.begin=e.begin,e.traceId=e.traceId||"",e.pv_id=e.pv_id||"",e.domain=e.domain||"",e.flag=e.flag,e.dl="object"==typeof location&&"string"==typeof location.href&&location.href.substring(0,500)||"",e.success?e.apiSnapshot&&delete e.apiSnapshot:e.apiSnapshot=l,d&&(e.traceOrigin=d),!e.api||isNaN(e.time))return Ll.warn("[retcode] invalid time or api"),this;var f=(this.getConfig("ignore")||{}).ignoreApis;return Ll.ignoreByRule(e.api,f)||Ll.ignoreByRule(Ll.decode(e.api),f)?this:(this.beforeSend&&this.beforeSend("api",e),this._lg("api",e,e.success&&this.getConfig("sample"),e.flag))},speed:function(e,t,i){var r=this,s=this.getConfig("startTime")||this._startTime;return/^s(\d|1[0])$/.test(e)?(t="number"!=typeof t?Date.now()-s:t>=s?t-s:t,r.speedCache=r.speedCache||{},r.speedCache[e]=t,r.speedCache.begin=s,clearTimeout(r.speedTimmer),r.speedTimmer=setTimeout(function(){i||(r.speedCache.page=r.getPage(!0)),r._lg("speed",r.speedCache),r.speedCache=null},5e3),r):(Ll.warn("[retcode] invalid point: "+e),r)},performance:function(e){if(e&&"object"==typeof e&&!this.hasSendPerf){var t={},i={},r=this.getConfig("autoSendPerf");if(e.autoSend&&r)return i=Ll.ext(this.perfData||{},e),this.hasSendPerf=!0,this._lg("perf",i,this.getConfig("sample"));if(e.autoSend&&!r)return delete e.autoSend,this.perfData?(i=Ll.ext(this.perfData||{},e),this.hasSendPerf=!0,this._lg("perf",i,this.getConfig("sample"))):void(this.perfData=e);for(var s in e)(/^t([1-9]|1[0])$/.test(s)||"ctti"===s||"cfpt"===s)&&(t[s]=e[s]);if(!0===e.autoSend||!r&&(r||this.perfData))return!0!==e.autoSend&&!1===r&&this.perfData?(t=Ll.ext(this.perfData||{},t),this.hasSendPerf=!0,this._lg("perf",t,this.getConfig("sample"))):void 0;this.perfData=Ll.ext(this.perfData||{},t)}},resource:function(e,t){if(!e||!Ll.isPlainObject(e))return Ll.warn("[arms] invalid param data: "+e),this;var i=Object.keys(e),r=["begin","dom","load","res","dl"],s=!1;for(var n in r)if(i.indexOf(r[n])<0){s=!0;break}if(s)return Ll.warn("[arms] lack param data: "+e),this;var o={begin:e.begin||Date.now(),dom:e.dom||"",load:e.load||"",res:Ll.isArray(e.res)?JSON.stringify(e.res):JSON.stringify([]),dl:e.dl||""};return this._lg("res",o,t)},event:function(e,t){if("object"==typeof e&&e&&e.key){var i={},r=["key","success","time","c1","c2","c3"];for(var s in e)r.indexOf(s)>-1&&(i[s]=e[s]);i.success=!1===e.success?0:1,this._lg("event",i,t)}}}),r._super=Bl,r._root=Bl,Bl.Reporter=r,e.exports=r}),Gl=si(function(e){var t="object"==typeof window?window:{},i=t.__oFetch_||t.fetch;i="function"==typeof i?i:void 0,e.exports=function(e,r){var s=-1;"object"==typeof e&&(s=e.z,e=Ll.serialize(e));var n=r+e;if(i)return i(n,{method:"HEAD",mode:"no-cors"}).catch(Ll.noop);if(t.document&&t.document.createElement){var o="__request_hold_"+s,a=t[o]=new Image;a.onload=a.onerror=function(){t[o]=void 0},a.src=n,a=null}}}),Vl=si(function(e){var t="object"==typeof window?window:{},i=t.__oXMLHttpRequest_||t.XMLHttpRequest;i="function"==typeof i?i:void 0,e.exports=function(e,t){try{var r=new i;r.open("POST",t,!0),r.setRequestHeader("Content-Type","text/plain"),r.send(JSON.stringify(e))}catch(e){Ll.warn("[retcode] Failed to log, exception is :\n"+e)}}}),Kl=function(e,t){var i=[],r=null,s=t&&t.location&&t.location.href,n=0,o=void 0,a=null,c=function(e,t,i){if(null!==e){var r=e[t];e[t]=i(r)}},l=function(e){var t,i,r,s,n,o=[];if(!e||"string"!=typeof e.tagName)return"";if(o.push(e.tagName.toLowerCase()),"string"==typeof e.id&&o.push("#".concat(e.id)),"string"==typeof(t=e.className))for(i=t.split(/\s+/),n=0;n<i.length;n++)o.push(".".concat(i[n]));var a=["type","name","title","alt","data-arms-attr"];for(n=0;n<a.length;n++)r=a[n],"string"==typeof(s=e.getAttribute(r))&&o.push("[".concat(r,'="').concat(s,'"]'));return o.join("")},h=function(e,t){return function(i){if(i&&i!==a){var s;a=i;try{s=i.target}catch(e){s="<unknown>"}if(0!==s.length){var c={type:"ui.".concat(e),data:{message:function(e){if(!e||1!==e.nodeType)return"";for(var t=e||null,i=[],r=0,s=0,n="";t&&r++<5&&!("html"===(n=l(t))||r>1&&s+3*i.length+n.length>=80);)i.push(n),s+=n.length,t=t.parentNode;return i.reverse().join(" > ")}(s)},timestamp:Date.now()};"click"===e?(n&&clearTimeout(n),t?n=setTimeout(function(){r&&r.addBehavior(c)},0):r&&r.addBehavior(c)):"keypress"===e&&(o||r&&r.addBehavior(c),clearTimeout(o),o=setTimeout(function(){o=void 0},100))}}}};Ll.ext(e.prototype,{addBehavior:function(e){if(this.getConfig("behavior")&&e&&"object"==typeof e){var r={},s=e.data||{};if(e.type)r=s;else{if("string"!=typeof s.name||"string"!=typeof s.message)return;r.name=s.name.substr(0,20),r.message=s.message.substr(0,200)}r.message&&(r.message=Ll.encode(r.message));var n={type:e.type||"custom",data:r||{},timestamp:e.timestamp||Date.now(),page:e.page||t&&t.location&&t.location.pathname};return i.push(n),i=i.slice(-100)}},getBehavior:function(){return i||[]},setBehavior:function(e){return e&&(i=e),i},reportBehavior:function(e){var t=this;t.getConfig("behavior")&&(t.sendBhTimer&&(clearTimeout(t.sendBhTimer),t.sendBhTimer=void 0),t.sendBhTimer=setTimeout(function(){i&&i.length>0&&(t.behavior(i),i=[],t.sendBhTimer=void 0,e&&"function"==typeof e&&e())},0))},initBehavior:function(){if(!this.hasInitBehavior&&!r){try{!function(){if(document&&document.referrer&&document.location){var e=document.referrer,t=document.location.href;if(""!==e){var i={type:"navigation",data:{from:e,to:t}};s=t,r&&r.addBehavior(i)}}}(),t&&t.document&&t.document.addEventListener&&(t.document.addEventListener("click",h("click"),!1),t.document.addEventListener("keypress",h("keypress"),!1)),function(){if(function(){var e=t&&t.chrome,i=e&&e.app&&e.app.runtime,r="history"in t&&!!t.history.pushState&&!!t.history.replaceState;return!i&&r}()){var e=function(e,t){var i={type:"navigation",data:{from:e,to:t}};r&&r.addBehavior(i),s=t},i=t.onpopstate;t.onpopstate=function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];var a=t.location.href;if(e(s,a),i)return i.apply(this,n)};var n=function(t){return function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];var o=r.length>2?r[2]:void 0;return o&&e(s,String(o)),t.apply(this,r)}};c(t.history,"pushState",n),c(t.history,"replaceState",n)}}(),this.getConfig("enableConsole")&&function(){if(t&&t.console)for(var e=["debug","info","warn","log","error","assert"],i=0;i<e.length;i++){var s=e[i];t.console[s]&&"function"==typeof t.console[s]&&c(t.console,s,function(e){var i=s;return function(){for(var s=arguments.length,n=new Array(s),o=0;o<s;o++)n[o]=arguments[o];var a={type:"console",data:{level:i,message:n}};if(r&&r.addBehavior(a),"error"===i)for(var c=0;c<n.length;c++){var l=n[c];l&&l.message&&l.stack&&r&&r.errorHandler(new ErrorEvent("error",{error:l,message:l.message}))}e&&Function.prototype.apply.call(e,t.console,n)}})}}()}catch(e){Ll.warn("[arms] error in initBehavior",e)}r=this,this.hasInitBehavior=!0}return this}})},zl=["","fetchStart","domainLookupStart","domainLookupEnd","connectStart","connectEnd","requestStart","responseStart","responseEnd","","domInteractive","","domContentLoadedEventEnd","","loadEventStart","","msFirstPaint","secureConnectionStart"],Yl=zl,Jl=function(){var e=Ll.win||{},t=e.performance;if(!t||"object"!=typeof t||"function"!=typeof t.getEntriesByType)return null;var i={},r=t.timing||{},s=t.getEntriesByType("resource")||[];if(i.begin=r[Yl[1]]||Date.now(),"function"==typeof e.PerformanceNavigationTiming){var n=t.getEntriesByType("navigation")[0];n&&(r=n)}return Ll.each({dom:[10,8],load:[14,1]},function(e,t){var s=r[Yl[e[1]]],n=r[Yl[e[0]]];if(s>0&&n>0){var o=Math.round(n-s);o>=0&&o<6e5&&(i[t]=o)}}),i.res=JSON.stringify(s),i},Zl=zl,Xl=function(){var e=Ll.win||{},t=e.performance;if(!t||"object"!=typeof t)return null;var i={},r=t.timing||{},s=Date.now(),n=1;if("function"==typeof e.PerformanceNavigationTiming){var o=t.getEntriesByType("navigation")[0];o&&(r=o,n=2)}Ll.each({dns:[3,2],tcp:[5,4],ssl:[5,17],ttfb:[7,6],trans:[8,7],dom:[10,8],res:[14,12],firstbyte:[7,2],fpt:[8,1],tti:[10,1],ready:[12,1],load:[14,1]},function(e,t){var s=r[Zl[e[1]]],o=r[Zl[e[0]]];if(2===n||s>0&&o>0){var a=Math.round(o-s);a>=0&&a<6e5&&(i[t]=a)}});var a=e.navigator.connection,c=t.navigation||{};i.ct=a?a.effectiveType||a.type:"";var l=a&&(a.downlink||a.downlinkMax||a.bandwidth)||null;if((l=l>999?999:l)&&(i.bandwidth=l),i.navtype=1===c.type?"Reload":"Other",1===n&&r[Zl[16]]>0&&r[Zl[1]]>0){var h=r[Zl[16]]-r[Zl[1]];h>=0&&h<36e5&&(i.fpt=h)}return 1===n&&r[Zl[1]]>0?i.begin=r[Zl[1]]:2===n&&i.load>0?i.begin=s-i.load:i.begin=s,i},Ql=function(e,t,i){function r(e,t,i){var s=0,o=e.tagName;if("SCRIPT"!==o&&"STYLE"!==o&&"META"!==o&&"HEAD"!==o){var a=e.children?e.children.length:0;if(a>0)for(var c=e.children,l=a-1;l>=0;l--)s+=r(c[l],t+1,s>0);if(s<=0&&!i&&!(e.getBoundingClientRect&&e.getBoundingClientRect().top<n))return 0;s+=1+.5*t}return s}function s(e){for(var t=1;t<e.length;t++)if(e[t].score<e[t-1].score)return e.splice(t,1),s(e);return e}var n=t.innerHeight||0,o=[],a=null,c=0;Ll.ext(e.prototype,{initFmpObserver:function(e){var s=this;if(!s._conf||!s._conf.useFmp)return null;if(!t.MutationObserver)return Ll.warn("[retcode] first meaningful paint can not be retrieved"),s.sendPerformance(),null;Ll.on(t,"beforeunload",function(){s.endObserving(0,!0)});var n=t.MutationObserver;return(a=new n(function(){!function(e){var t=Date.now()-e,s=i.querySelector("body");if(s){var n=0;n+=r(s,1,!1),o.push({score:n,t:t})}else o.push({score:0,t:t})}(s._startTime)})).observe(document,{childList:!0,subtree:!0}),c=1,s.onReady(function(){s.endObserving(e)}),a},endObserving:function(e,t){var i=this;if(a&&c)if(i.fmpTimmer&&(clearTimeout(i.fmpTimmer),i.fmpTimmer=null),t||!function(e,t){var i=Date.now()-e;return!(i>t||i-(o&&o.length&&o[o.length-1].t||0)>1e3)}(i._startTime,e)){a.disconnect(),c=0,o=s(o);for(var r=null,n=1;n<o.length;n++)if(o[n].t>=o[n-1].t){var l=o[n].score-o[n-1].score;(!r||r.rate<=l)&&(r={t:o[n].t,rate:l})}r&&r.t>0&&r.t<36e5?i.sendPerformance({fmp:r.t}):i.sendPerformance()}else i.fmpTimmer=Ll.delay(function(){i.endObserving(e)},500)}})},eh=si(function(e){var t=Ll.win,i=t.document,r=/^(error|api|speed|sum|avg|percent|custom|msg|setPage|setConfig|behavior|performance)$/,s=function(e){var i=this;return Wl.call(i,e),i._initialPage=e.page&&Ll.safetyCall(e.page,[],e.page+"")||null,i._isRobot=Ll.isRobot(),i._health={errcount:0,apisucc:0,apifail:0},i.beforeSend=function(e,t){"error"===e?i._health.errcount++:"api"===e&&i._health[t.success?"apisucc":"apifail"]++},!1!==e.enableInstanceAutoSend&&(i.initHandler(),i.initHook(),i.initFmpObserver(1e4),i._conf&&i._conf.behavior&&"function"==typeof i.initBehavior&&i.initBehavior()),Object.defineProperty&&t.addEventListener&&Object.defineProperty(i,"pipe",{set:i.sendPipe}),i};s.prototype=Ll.createObject(Wl.prototype),Ll.ext(Wl._root.dftCon,{uid:null,setUsername:null,ignoreUrlPath:null,ignoreApiPath:null,urlHelper:[{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},/\/$/],apiHelper:{rule:/\/([a-z\-_]+)?\d{2,20}/g,target:"/$1**"},ignoreUrlCase:!0,imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",disableHook:!1,autoSendPv:!0,autoSendPerf:!0,enableSPA:!1,enableLinkTrace:!1,linkType:"arms",enableApiCors:!1,sendResource:!0,behavior:!0,enableConsole:!1,parseHash:function(e){return(e?Ll.cutUrlSearch(e.replace(/^#\/?/,"")):"")||"[index]"},parseResponse:function(e){if(!e||"object"!=typeof e)return{};var t=e.code,i=e.msg||e.message||e.subMsg||e.errorMsg||e.ret||e.errorResponse||"";return"object"==typeof i&&(t=t||i.code,i=i.msg||i.message||i.info||i.ret||JSON.stringify(i)),{msg:i,code:t,success:!0}}}),Ll.ext(s.prototype,{constructor:s,_super:Wl,onReady:function(e){var r=this;if(r.hasReady)return e();"complete"===i.readyState?(r.hasReady=!0,e()):Ll.on(t,"load",function(){r.hasReady=!0,e()},!0)},getPage:function(e){var t=this._conf,i=t.page,r=location,s=r.host+r.pathname;return i&&!e?Ll.safetyCall(i,[],i+""):this._initialPage||Ll.filterByRule(t.ignoreUrlCase?s.toLowerCase():s,t.ignoreUrlPath?t.ignoreUrlPath:t.urlHelper)},setPage:function(e,t){var i=this,r=i.prevPage;if(!1!==t){if(!e||e===r)return i;i.prevPage=e,clearTimeout(i.sendPVTimmer),i.handleUnload(1),i.resetPageview(),i.sendPVTimmer=setTimeout(function(){i.sendPV()},10)}else i.prevPage=e;return i._conf.page=e,i},setConfig:function(e,t){if(e&&"object"==typeof e){Ll.verifyConfig(e),e=this.setImgUrl(e);var i=this._conf;if(this._conf=Ll.ext({},i,e),!t){var r="disableHook";r in e&&i[r]!==e[r]&&(e[r]?this.removeHook():this.addHook()),(r="enableSPA")in e&&i[r]!==e[r]&&this.bindHashChange(e[r])}}},sendRequest:function(e){Gl(e,this.getConfig("imgUrl"))},postData:function(e,t){var i={};i[t]=e[t],delete e[t];var r="";"object"==typeof e&&(r=Ll.serialize(e)),Vl(i,this.getConfig("imgUrl")+r+"&post_res=")},sendPipe:function(e){var t=this;if(!e||!e.length)return t;try{if("Array"===Ll.T(e[0]))return Ll.each(e,function(e){return t.sendPipe(e)});if("Array"!==Ll.T(e))return t;var i=e.shift();if(!r.test(i))return t;t[i].apply(t,e)}catch(e){return Ll.warn("[retcode] error in sendPipe",e),t}},sendHealth:function(){var e=Ll.ext({},this._health);e.healthy=e.errcount>0?0:1,e.begin=Date.now();var t=e.begin-this.sBegin;e.stay=t,this._lg("health",e,1),this._health={errcount:0,apisucc:0,apifail:0}},createInstance:function(e){e=Ll.ext({pid:this._conf.pid},e);var t=this.__proto__.constructor(e);return e.page&&t.sendPV(),t}}),Kl(s,t),function(e,t,i){var r=Ll,s=Jl,n=Xl,o=null,a=i.documentElement,c=t.innerWidth||a.clientWidth||i.body.clientWidth,l=t.innerHeight||a.clientHeight||i.body.clientHeight,h=t.navigator.connection,d={sr:screen.width+"x"+screen.height,vp:c+"x"+l,ct:h?h.effectiveType||h.type:""},u={},g=function(e,t,s,n,o){if(void 0===t){var a,c;if(!u[e]){a=new RegExp(e+"=([^;]+)");try{c=a.exec(i.cookie)}catch(e){return r.warn("[retcode] can not get cookie:",e),null}c&&(u[e]=c[1])}return u[e]}var l=e+"="+t;n&&(l+="; domain="+n),l+="; path="+(o||"/"),s&&(l+="; max-age="+s);try{return i.cookie=l,!!i.cookie}catch(e){return r.warn("[retcode] can not set cookie: ",e),!1}},f=function(e){var t=e._conf.uid||g("_nk_")||g("_bl_uid");return t||(t=r.uu(),g("_bl_uid",t,15552e3))?t:null};r.ext(e.prototype,{activeErrHandler:function(e){return o&&!e||(o=this),this},errorHandler:function(e){if(!e)return this;var t=e.type;if("error"===t){var i=e.target||e.srcElement;!i||!i.tagName||e.message||e.filename||e.lineno||e.colno?this.error(e.error||{message:e.message},e):this.resourceErrorHandler(e)}else"unhandledrejection"===t&&r.T(e.reason,"Error")&&r.checkAutoError(e.reason)&&this.error(e.reason);try{this.getConfig("behavior")&&this.reportBehavior&&this.reportBehavior()}catch(e){}return this},resourceErrorHandler:function(e){var t=this,i=e.target||e.srcElement;try{var s=t.getSrc(i),n="string"==typeof i.tagName?i.tagName.toLowerCase():"",o=t.getXPath(i,5);return t._lg("resourceError",{src:s&&s.substring(0,1e3),node_name:n,xpath:o}),t}catch(e){return r.warn("[ARMS] resourceErrorHandler error :",e),t}},getSrc:function(e){var t=e.src||e.href;try{if(!t){var i="object"===("string"==typeof e.tagName?e.tagName.toLowerCase():""),r=e.getAttribute("classid")&&"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"===e.getAttribute("classid").toLowerCase()||"application/x-shockwave-flash"===e.getAttribute("type");i&&r&&(t=e.getAttribute("data")||e.getAttribute("codebase")),t||(t=e.outerHTML||e.innerHTML)}}catch(e){t=""}return t},getXPath:function(e,t){var i=e.id?"#"+e.id:"",r="string"==typeof e.className?"."+e.className.split(" ").join("."):"",s=("string"==typeof e.tagName?e.tagName.toLowerCase():"")+i+r;return e.parentNode&&e.parentNode.tagName&&t-1!=0?this.getXPath(e.parentNode,t-1)+" > "+s:s},sendPerformance:function(e){var t=this;t.onReady(function(){var i=n();i&&i.load&&i.load>0&&(i.page=t.getPage(!0),e&&(i=r.ext(i,e)),i.autoSend=!0,t.performance(i))})},sendResources:function(e){var t=this;t.onReady(function(){var i=s();i&&i.load&&i.load>0&&(i.load&&i.load<=2e3||i.load&&i.load<=8e3&&Math.random()>.05||(i.page=t.getPage(!0),i.dl=location.href,e&&(i=r.ext(i,e)),t._lg("res",i,t.getConfig("sample"))))})},sendPV:function(){var e=this;e.onReady(function(){var r=function(e){var r=f(e),s=t.devicePixelRatio||1;return{uid:r,dt:i.title,dl:location.href,dr:i.referrer,dpr:s.toFixed(2),de:(i.characterSet||i.defaultCharset||"").toLowerCase(),ul:a.lang,begin:Date.now()}}(e);r&&r.uid&&e._lg("pv",r,e.getConfig("pvSample"))})},commonInfo:function(){return d.uid=f(this),d.sid=function(e){if(e.session)return e.session;var t;try{if("object"==typeof window&&"object"==typeof sessionStorage&&"function"==typeof sessionStorage.getItem)return"string"==typeof(t=sessionStorage.getItem("_bl_sid"))?(e.session=t,t):(t=r.uu(),e.session=t,"function"==typeof sessionStorage.setItem&&sessionStorage.setItem("_bl_sid",t),t)}catch(e){r.warn("[ARMS] getSid error :",e)}return e.session=t=r.uu(),t}(this),d},handleUnload:function(e){var t=Date.now();if(t-this._lastUnload<200)return this;this._lastUnload=t,this.sendHealth(e),this.speedCache&&(this._lg("speed",this.speedCache),this.speedCache=null,clearTimeout(this.speedTimmer)),this.clear(!0)},bindHashChange:function(e){var i=this;if(!e^i.hashChangeHandler)return i;e?(i.hackHistoryState(),i.hashChangeHandler=function(e){var t=i._conf.parseHash(location.hash);t&&i.setPage(t,!1!==e)},i.stateChangeHandler=function(e){var t=i._conf.parseHash(e.detail);t&&i.setPage(t)},r.on(t,"hashchange",i.hashChangeHandler),r.on(t,"historystatechange",i.stateChangeHandler),i.hashChangeHandler(!1)):(r.off(t,"hashchange",i.hashChangeHandler),r.off(t,"historystatechange",i.stateChangeHandler),i.hashChangeHandler=null,i.stateChangeHandler=null)},initHandler:function(){var e=this;if(e.hasInitHandler)return e;var i=e._conf;return r.on(t,"beforeunload",function(){e.handleUnload(0)}),e.bindHashChange(i.enableSPA),e.activeErrHandler(!1),e.hasInitHandler=!0,e}}),r.on(t,"error",function(e){o&&o.errorHandler(e)},!1,!0).on(t,"unhandledrejection",function(e){o&&o.errorHandler(e)})}(s,t,i),Ql(s,t,i),function(e,t){var i=Ll,r=null,s=i.getCurDomain(),n=function(e,t,r,n,o,a,c,l,h,d,u,g,f){var p=i.J(o)||null,v=i.safetyCall(t,[p,n],null);if(!v)return!1;var m=v.code||a,b=!("success"in v)||v.success;e.api(r,b,c,m,v.msg,l,h,d,u,s,g,f)},o="fetch",a="__oFetch_",c="__oXMLHttpRequest_",l="XMLHttpRequest";i.ext(e.prototype,{removeHook:function(e,i){return r&&(i||this===r)?(t[a]&&(t[o]=t[a],delete t[a]),t[c]&&(t[l]=t[c],delete t[c]),r=null,this):this},addHook:function(e){return!e&&r||(r||(function(){if("function"==typeof t[o]){var e=t[o];t[a]=e,t[o]=function(o,a){var c=1===arguments.length?[arguments[0]]:Array.apply(null,arguments),l=r;if(!l||!l.api)return e.apply(t,c);if(a&&("HEAD"===a.method||"no-cors"===a.mode))return e.apply(t,c);var h=Date.now(),d=l._conf,u=(o&&"string"!=typeof o?o.url:o)||"",g=u;u=i.cutUrlSearch(u);var f=(d.ignore||{}).ignoreApis;if(!i.checkAPI(u,!0)||i.ignoreByRule(u,f))return e.apply(t,c);u=i.filterByRule(u,d.ignoreApiPath?d.ignoreApiPath:d.apiHelper);var p=d.enableLinkTrace,v="",m="",b=l.getConfig("pid"),y=null,w=l.getConfig("sample"),S=l.getConfig("linkType"),T=1;if(w&&!l.sampling(w)&&(T=0),p){var R="";try{R=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch(e){R=""}var E=i.checkSameOrigin(g,R);if(l.getConfig("enableApiCors")||E){if(o&&"string"!=typeof o)try{if(c[0].headers&&"function"==typeof c[0].headers.get&&"function"==typeof c[0].headers.append)if("tracing"===S){var I=c[0].headers.get("uber-trace-id");I?v=I.split(":")[0]:(I=l.getUberTraceId(T),c[0].headers.append("uber-trace-id",I["uber-trace-id"]),v=I.traceId),m=l.pageview}else{var C=c[0].headers.get("EagleEye-TraceID"),P=c[0].headers.get("EagleEye-SessionID"),A=c[0].headers.get("EagleEye-pAppName");C?v=C:(v=l.getTraceId()["EagleEye-TraceID"],c[0].headers.append("EagleEye-TraceID",v)),P?m=P:(m=l.getPageviewId()["EagleEye-SessionID"],c[0].headers.append("EagleEye-SessionID",m)),A||c[0].headers.append("EagleEye-pAppName",b)}}catch(e){i.warn("[retcode] fetch failed to set header, exception is :\n"+e)}if(a)if("tracing"===(a.headers=a.headers?a.headers:{},S)){if(a.headers["uber-trace-id"])v=a.headers["uber-trace-id"].split(":")[0];else{var O=l.getUberTraceId(T);a.headers["uber-trace-id"]=O["uber-trace-id"],v=O.traceId}m=l.getPageviewId()["EagleEye-SessionID"]}else a.headers["EagleEye-TraceID"]?v=a.headers["EagleEye-TraceID"]:(v=l.getTraceId()["EagleEye-TraceID"],a.headers["EagleEye-TraceID"]=v),a.headers["EagleEye-SessionID"]?m=a.headers["EagleEye-SessionID"]:(m=l.getPageviewId()["EagleEye-SessionID"],a.headers["EagleEye-SessionID"]=m),a.headers["EagleEye-pAppName"]||(a.headers["EagleEye-pAppName"]=b)}}return e.apply(t,c).then(function(e){if(!l||!l.api)return e;try{if(!e||"function"!=typeof e.clone)return e;var t=e.clone(),r=t.headers;if(r&&"function"==typeof r.get){var o=r.get("content-type");if(o&&!/(text)|(json)/.test(o))return e;if(!v){var a=i.parseFetchHeaders(r);"object"==typeof a&&a["eagleeye-traceid"]&&(v=a["eagleeye-traceid"],y="response")}}var f=Date.now()-h;return t.text().then(function(e){var o=i.getFetchSnapshot(c,e,r);t.ok?n(l,d.parseResponse,u,g,e,t.status||200,f,h,v,m,o,y,T):l.api(u,!1,f,t.status||404,t.statusText,h,v,m,o,s,y,T)}),e}catch(t){return i.warn("[ARMS] fetch response error :",t),e}}).catch(function(e){if(!l||!l.api)throw e;var t=Date.now()-h;throw l.api(u,!1,t,e.name||"Error",e.message,h,v,m,{},s),e})},t[o].toString=i.createFakeToString(o)}}(),function(){if("function"==typeof t[l]){var e,o=t[l];t[c]=o;var a=function(t){var a=new o(t),c=r;if(!c||!c.api||!a.addEventListener)return a;var l,h,d,u=a.send,g=a.open,f=a.setRequestHeader,p=c._conf,v=(p.ignore||{}).ignoreApis,m=c.getConfig("enableLinkTrace"),b="",y="",w="",S=null,T=c.getConfig("sample"),R=c.getConfig("linkType"),E=1;return T&&!c.sampling(T)&&(E=0),a.open=function(t,r){e=t;var s=1===arguments.length?[arguments[0]]:Array.apply(null,arguments);g.apply(a,s),d=r||"",h=i.cutUrlSearch(d);var n=!i.checkAPI(h,!0)||i.ignoreByRule(h,v);if(h=h?i.filterByRule(h,p.ignoreApiPath?p.ignoreApiPath:p.apiHelper):"",!n&&m){var o="";try{o=location.origin?location.origin:location.protocol+"//"+location.hostname+(location.port?":"+location.port:"")}catch(e){o=""}var l=i.checkSameOrigin(d,o);if((c.getConfig("enableApiCors")||l)&&f&&"function"==typeof f)if("tracing"===R){var u=c.getUberTraceId(E);f.apply(a,["uber-trace-id",u["uber-trace-id"]]),b=u.traceId,y=c.getPageviewId()["EagleEye-SessionID"]}else b=c.getTraceId()["EagleEye-TraceID"],f.apply(a,["EagleEye-TraceID",b]),y=c.getPageviewId()["EagleEye-SessionID"],f.apply(a,["EagleEye-SessionID",y]),w=c.getConfig("pid"),f.apply(a,["EagleEye-pAppName",w])}},a.send=function(){l=Date.now();var e=1===arguments.length?[arguments[0]]:Array.apply(null,arguments);u.apply(a,e)},i.on(a,"readystatechange",function(){if(h&&4===a.readyState){var t=Date.now()-l,r=i.getXhrSnapshot(d,e,a);if(!b){var o=i.parseXhrHeaders("function"==typeof a.getAllResponseHeaders&&a.getAllResponseHeaders()||"");"object"==typeof o&&o["eagleeye-traceid"]&&(b=o["eagleeye-traceid"],S="response")}if(a.status>=200&&a.status<=299){var u=a.status||200;if("function"==typeof a.getResponseHeader){var g=a.getResponseHeader("Content-Type");if(g&&!/(text)|(json)/.test(g))return}a.responseType&&"text"!==a.responseType?c.api(h,!0,t,u,"",l,b,y,{},s,S,E):n(c,p.parseResponse,h,d,a.responseText,u,t,l,b,y,r,S,E)}else c.api(h,!1,t,a.status||"FAILED",a.statusText,l,b,y,r,s,S,E)}}),a};a.prototype=o.prototype,t[l]=a,t[l].toString=i.createFakeToString(l)}}()),r=this),this},initHook:function(){return this.hasInitHook||(this.getConfig("disableHook")||this.addHook(),this.hasInitHook=!0),this}})}(s,t),function(e,t){var i=Ll,r=t.history||{},s=t.document,n=function(e,i){var r;t.CustomEvent?r=new CustomEvent(e,{detail:i}):((r=s.createEvent("HTMLEvents")).initEvent(e,!1,!0),r.detail=i),t.dispatchEvent(r)},o=function(e){var t=r[e];"function"==typeof t&&(r[e]=function(s,o,a){var c=1===arguments.length?[arguments[0]]:Array.apply(null,arguments),l=location.href,h=t.apply(r,c);if(!a||"string"!=typeof a)return h;if(a===l)return h;try{var d=l.split("#"),u=a.split("#"),g=i.cutUrlSearch(d[0]),f=i.cutUrlSearch(u[0]),p=d[1]&&d[1].replace(/^\/?(.*)/,"$1"),v=u[1]&&u[1].replace(/^\/?(.*)/,"$1");g!==f?n("historystatechange",f):p!==v&&n("historystatechange",v)}catch(t){i.warn("[retcode] error in "+e+": "+t)}return h},r[e].toString=i.createFakeToString(e))};i.ext(e.prototype,{hackHistoryState:function(){return this.hasHackedHistoryState||(o("pushState"),o("replaceState"),this.hasHackedHistoryState=!0),this}})}(s,t),s._super=Wl,s._root=Wl._root,Wl.Browser=s,e.exports=s}),th=si(function(e){function t(e,t){var o=i[s]=new r(e);o.sendPipe(t);var a=o._conf;return!1!==a.autoSendPv&&o.sendPV(),a&&a.useFmp||o.sendPerformance(),a&&a.sendResource&&o.sendResources(),i[n]=!0,o}var i=window,r=i.BrowserLogger=eh,s=Ll.key,n="__hasInitBlSdk";r.singleton=function(e,r){return i[n]?i[s]:t(e,r)},r.createExtraInstance=function(e){e&&"object"==typeof e&&!0!==e.enableInstanceAutoSend&&(e.enableInstanceAutoSend=!1);var t=new r(e),i=t._conf;return i.enableInstanceAutoSend&&(!1!==i.autoSendPv&&t.sendPV(),i&&i.useFmp||t.sendPerformance(),i&&i.sendResource&&t.sendResources()),t},"object"==typeof window&&!!window.navigator&&i[s]&&(r.bl=function(){if(i[n])return i[s];var e={},r=[];return s in i&&(e=i[s].config||{},r=i[s].pipe||[]),t(e,r)}()),e.exports=r});function ih(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)}function rh(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i}var sh,nh,oh,ah,ch,lh,hh,dh,uh,gh,fh,ph,vh,mh,bh,yh,wh,Sh,Th,Rh,Eh,Ih,Ch,Ph,Ah,Oh,kh,Dh,$h,jh,_h,Hh,Mh,xh,qh,Nh,Fh,Uh,Lh,Bh,Wh,Gh,Vh,Kh,zh,Yh,Jh,Zh,Xh,Qh,ed,td,id,rd,sd,nd,od,ad,cd,ld,hd,dd,ud,gd,fd,pd,vd,md,bd,yd,wd,Sd,Td,Rd,Ed,Id,Cd,Pd,Ad,Od,kd,Dd,$d,jd,_d,Hd,Md,xd,qd,Nd,Fd,Ud,Ld,Bd,Wd,Gd,Vd,Kd,zd,Yd,Jd,Zd,Xd,Qd,eu,tu,iu,ru,su,nu,ou,au,cu,lu,hu,du,uu,gu,fu,pu,vu,mu,bu,yu,wu,Su,Tu,Ru,Eu,Iu,Cu,Pu,Au,Ou,ku,Du,$u,ju,_u,Hu,Mu,xu,qu,Nu,Fu,Uu,Lu,Bu,Wu,Gu,Vu=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),sh.add(this),nh.set(this,void 0),oh.set(this,void 0),ah.set(this,void 0),ch.set(this,void 0),lh.set(this,void 0),hh.set(this,void 0),dh.set(this,"https://arms-retcode.aliyuncs.com/r.png?"),uh.set(this,!0),gh.set(this,!0),fh.set(this,{});var i=t.release,r=t.environment,s=t.uid,n=t.pid,o=t.appType,a=t.imgUrl,c=t.sendResource,l=t.disableHook,h=function(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(i[r[s]]=e[r[s]])}return i}(t,["release","environment","uid","pid","appType","imgUrl","sendResource","disableHook"]);rh(this,oh,i,"f"),rh(this,ah,r,"f"),rh(this,ch,s,"f"),rh(this,lh,n,"f"),rh(this,hh,o,"f"),rh(this,dh,null!=a?a:ih(this,dh,"f"),"f"),rh(this,uh,null!=c?c:ih(this,uh,"f"),"f"),rh(this,gh,null!=l?l:ih(this,gh,"f"),"f"),rh(this,fh,h,"f"),this.getInstance(),ih(this,sh,"m",ph).call(this)}return t=e,i=[{key:"getInstance",value:function(){return ih(this,nh,"f")||rh(this,nh,th.singleton(lc({uid:ih(this,ch,"f"),pid:ih(this,lh,"f"),appType:ih(this,hh,"f"),imgUrl:ih(this,dh,"f"),sendResource:ih(this,uh,"f"),disableHook:ih(this,gh,"f"),environment:ih(this,ah,"f"),release:ih(this,oh,"f")},ih(this,fh,"f"))),"f"),ih(this,nh,"f")}},{key:"errorParser",value:function(e){return ql.parse(e)}},{key:"errReport",value:function(e){this.getInstance().error(e,{filename:void 0,lineno:void 0,colno:void 0})}}],i&&sc(t.prototype,i),r&&sc(t,r),cs(t,"prototype",{writable:!1}),e;var t,i,r}();nh=new Ol,oh=new Ol,ah=new Ol,ch=new Ol,lh=new Ol,hh=new Ol,dh=new Ol,uh=new Ol,gh=new Ol,fh=new Ol,sh=new Ml,ph=function(){var e=this;window.onerror=function(t,i,r,s,n){e.getInstance().error(n,{filename:i,lineno:r,colno:s})},window.addEventListener("unhandledrejection",function(t){t.promise.catch(function(t){e.errReport(t)})}),window.addEventListener("rejectionhandled",function(t){t.promise.catch(function(t){e.errReport(t)})})};class Ku{static getAliArms(e){const t=e&&e!==s(this,vh,"f",bh);return t&&n(this,vh,e,"f",bh),s(this,vh,"f",mh)&&!t||(n(this,vh,new Vu({uid:s(this,vh,"f",bh),pid:"jjn8k2jk90@aa39edd52601f08",appType:"web",imgUrl:"https://arms-retcode.aliyuncs.com/r.png?",release:"6.0.10",environment:"prod",sendResource:!1,autoSendPerf:!1,useFmp:!1,autoSendPv:!1,enableSPA:!1,jsReport:!1,behavior:!1,enableConsole:!1,disableHook:!0,ignore:{ignoreErrors:[()=>!0],ignoreResErrors:[()=>!0]}}),"f",mh),s(this,vh,"f",yh).push({uid:s(this,vh,"f",bh),aliArms:s(this,vh,"f",mh)})),s(this,vh,"f",mh)}static getAliArmsList(){return s(this,vh,"f",yh)}static errReport(e,t){var i;null===(i=Ku.getAliArms(t))||void 0===i||i.errReport(e)}}vh=Ku,mh={value:void 0},bh={value:void 0},yh={value:[]};class zu{constructor(t,i,s={}){var n,o,a,c,l,h,d,u,g,f,p,v,m,b,y,w,S,T,R,E,I,C,P,A;Object.defineProperty(this,"session",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"userAgentManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:"idle"}),Object.defineProperty(this,"destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"hardFailed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"signalingBusyCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"disconnectedTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"retryTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signalingBusyTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"negotiationTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"iceRecoveryTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"rtpStatsTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onlineTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"transportRecoveryTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"registrationRecoveryTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"transportWaitStartedAt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingTransportRecoveryReason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"registrationWaitStartedAt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingRegistrationRecoveryReason",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lastRtpSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lastRtpProgressAt",{enumerable:!0,configurable:!0,writable:!0,value:Date.now()}),Object.defineProperty(this,"lastRtpRecoveryAt",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"recoveryGeneration",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"acceptedRecoveryGeneration",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"recoveryReason",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"reinviteReason",{enumerable:!0,configurable:!0,writable:!0,value:"unknown"}),Object.defineProperty(this,"permanentRecoverySdpModifier",{enumerable:!0,configurable:!0,writable:!0,value:e=>r(this,void 0,void 0,function*(){return this.applyRecoveryReasonToSdp(e)})}),Object.defineProperty(this,"handleSessionStateChange",{enumerable:!0,configurable:!0,writable:!0,value:t=>{switch(this.logInfo("SIP session state:",t),t){case e.SessionState.Established:this.handleEstablished();break;case e.SessionState.Terminating:case e.SessionState.Terminated:this.destroy()}}}),Object.defineProperty(this,"handleOffline",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.destroyed||this.hardFailed||(this.logInfo("browser offline"),this.clearDisconnectedTimer(),this.clearRetryTimer(),this.clearSignalingBusyTimer(),this.clearIceRecoveryTimer(),this.clearTransportRecoveryTimer(),"sending-reinvite"!==this.state&&(this.state="idle"))}}),Object.defineProperty(this,"handleOnline",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.destroyed||this.hardFailed||(this.logInfo("browser online"),this.onlineTimer&&clearTimeout(this.onlineTimer),this.onlineTimer=setTimeout(()=>{if(this.onlineTimer=void 0,this.destroyed||this.hardFailed)return;if(this.session.state!==e.SessionState.Established)return;if(!this.isTransportAvailable())return void this.waitForTransport("network-online");const t=this.getPeerConnection();if(t)if("stable"===t.signalingState)switch(t.iceConnectionState){case"failed":case"disconnected":this.state="idle",this.recover("network-online")}else this.scheduleSignalingBusyRetry(`network-online:${t.signalingState}`)},this.options.onlineRecoveryDelayMs))}}),this.session=t,this.userAgentManager=i,this.options={disconnectedTimeoutMs:null!==(n=s.disconnectedTimeoutMs)&&void 0!==n?n:3e3,negotiationTimeoutMs:null!==(o=s.negotiationTimeoutMs)&&void 0!==o?o:1e4,iceRecoveryTimeoutMs:null!==(a=s.iceRecoveryTimeoutMs)&&void 0!==a?a:1e4,iceGatheringTimeoutMs:null!==(c=s.iceGatheringTimeoutMs)&&void 0!==c?c:5e3,maxRetries:null!==(l=s.maxRetries)&&void 0!==l?l:3,retryBaseDelayMs:null!==(h=s.retryBaseDelayMs)&&void 0!==h?h:1e3,retryMaxDelayMs:null!==(d=s.retryMaxDelayMs)&&void 0!==d?d:1e4,maxSignalingBusyRetries:null!==(u=s.maxSignalingBusyRetries)&&void 0!==u?u:3,signalingBusyRetryDelayMs:null!==(g=s.signalingBusyRetryDelayMs)&&void 0!==g?g:1e3,enableRtpWatchdog:null===(f=s.enableRtpWatchdog)||void 0===f||f,rtpStatsIntervalMs:null!==(p=s.rtpStatsIntervalMs)&&void 0!==p?p:1e3,rtpStallTimeoutMs:null!==(v=s.rtpStallTimeoutMs)&&void 0!==v?v:5e3,recoverOnRtpStallWhenIceConnected:null===(m=s.recoverOnRtpStallWhenIceConnected)||void 0===m||m,rtpRecoveryCooldownMs:null!==(b=s.rtpRecoveryCooldownMs)&&void 0!==b?b:1e4,onlineRecoveryDelayMs:null!==(y=s.onlineRecoveryDelayMs)&&void 0!==y?y:800,transportRecoveryPollMs:null!==(w=s.transportRecoveryPollMs)&&void 0!==w?w:1e3,transportRecoveryTimeoutMs:null!==(S=s.transportRecoveryTimeoutMs)&&void 0!==S?S:6e4,registrationRecoveryPollMs:null!==(T=s.registrationRecoveryPollMs)&&void 0!==T?T:1e3,registrationRecoveryTimeoutMs:null!==(R=s.registrationRecoveryTimeoutMs)&&void 0!==R?R:6e4,debugIceCredentials:null!==(E=s.debugIceCredentials)&&void 0!==E&&E,includeRecoveryReasonInSdp:null===(I=s.includeRecoveryReasonInSdp)||void 0===I||I,recoveryReasonSdpAttribute:null!==(C=s.recoveryReasonSdpAttribute)&&void 0!==C?C:"x-recovery-reason",reinviteReasonSdpAttribute:null!==(P=s.reinviteReasonSdpAttribute)&&void 0!==P?P:"x-reinvite-reason",isSignalingAvailable:s.isSignalingAvailable,isRegistrationAvailable:s.isRegistrationAvailable,logger:null!==(A=s.logger)&&void 0!==A?A:console,onRecoveryStart:s.onRecoveryStart,onRecovered:s.onRecovered,onRecoveryFailed:s.onRecoveryFailed}}start(){this.destroyed||this.hardFailed||(this.logInfo("start"),this.session.stateChange.addListener(this.handleSessionStateChange),"undefined"!=typeof window&&(window.addEventListener("online",this.handleOnline),window.addEventListener("offline",this.handleOffline)),this.session.state===e.SessionState.Established&&this.handleEstablished())}restartNow(e="manual"){return r(this,void 0,void 0,function*(){yield this.recover(e)})}getState(){return this.state}getRetryCount(){return this.retryCount}getIceConnectionState(){var e;return null===(e=this.getPeerConnection())||void 0===e?void 0:e.iceConnectionState}destroy(){if(this.destroyed)return;this.destroyed=!0,this.hardFailed=!0,this.recoveryGeneration++,this.state="terminated",this.clearAllTimers(),this.session.stateChange.removeListener(this.handleSessionStateChange),"undefined"!=typeof window&&(window.removeEventListener("online",this.handleOnline),window.removeEventListener("offline",this.handleOffline));const e=this.getSessionDescriptionHandler();e&&this.bound&&(e.peerConnectionDelegate=void 0),this.bound=!1,this.logInfo("destroy")}handleEstablished(){this.destroyed||this.hardFailed||(this.bindPeerConnectionDelegate(),this.options.enableRtpWatchdog&&this.startRtpWatchdog())}bindPeerConnectionDelegate(){const e=this.getSessionDescriptionHandler(),t=null==e?void 0:e.peerConnection;e&&t?this.bound||(this.bound=!0,this.logInfo("bind PeerConnection",{iceConnectionState:t.iceConnectionState,connectionState:t.connectionState,signalingState:t.signalingState}),e.peerConnectionDelegate={oniceconnectionstatechange:()=>{this.handleIceConnectionStateChange()},onconnectionstatechange:()=>{this.logInfo("connectionState:",t.connectionState),"failed"===t.connectionState&&"stable"!==t.signalingState&&this.logWarn("PeerConnection failed while signaling is busy",{signalingState:t.signalingState,iceConnectionState:t.iceConnectionState})},onicegatheringstatechange:()=>{this.logDebug("iceGatheringState:",t.iceGatheringState)},onsignalingstatechange:()=>{this.logInfo("signalingState:",t.signalingState),"stable"===t.signalingState&&(this.signalingBusyCount=0,"waiting-signaling"!==this.state||this.signalingBusyTimer||(this.state="idle",this.recover("signaling-became-stable"))),"closed"===t.signalingState&&this.destroy()},onicecandidate:e=>{e.candidate?this.logDebug("ICE candidate:",{type:e.candidate.type,protocol:e.candidate.protocol,address:e.candidate.address,port:e.candidate.port}):this.logDebug("ICE candidate gathering complete")}}):this.logWarn("SessionDescriptionHandler / PeerConnection unavailable")}handleIceConnectionStateChange(){if(this.destroyed||this.hardFailed)return;const e=this.getPeerConnection();if(!e)return;const t=e.iceConnectionState;switch(this.logInfo("iceConnectionState:",t,"recoveryState:",this.state),t){case"new":break;case"checking":this.clearDisconnectedTimer(),"sending-reinvite"!==this.state&&"waiting-ice"!==this.state||(this.state="waiting-ice");break;case"connected":case"completed":this.handleIceRecovered();break;case"disconnected":this.handleIceDisconnected();break;case"failed":this.clearDisconnectedTimer(),this.recover("ice-failed");break;case"closed":this.destroy()}}handleIceDisconnected(){this.destroyed||this.hardFailed||"sending-reinvite"!==this.state&&"waiting-ice"!==this.state&&(this.disconnectedTimer||(this.state="waiting-disconnected",this.logInfo(`ICE disconnected, wait ${this.options.disconnectedTimeoutMs}ms`),this.disconnectedTimer=setTimeout(()=>{if(this.disconnectedTimer=void 0,this.destroyed||this.hardFailed)return;const e=this.getPeerConnection();if(e){if("disconnected"===e.iceConnectionState)return this.state="idle",void this.recover("ice-disconnected-timeout");this.logInfo("ICE self recovered:",e.iceConnectionState),this.state="idle"}},this.options.disconnectedTimeoutMs)))}handleIceRecovered(){var e,t;if(this.destroyed||this.hardFailed)return;const i="idle"!==this.state||this.retryCount>0;!i||"sending-reinvite"!==this.state&&"waiting-ice"!==this.state||this.acceptedRecoveryGeneration===this.recoveryGeneration?(this.clearDisconnectedTimer(),this.clearRetryTimer(),this.clearSignalingBusyTimer(),this.clearNegotiationTimer(),this.clearIceRecoveryTimer(),this.clearTransportRecoveryTimer(),this.clearRegistrationRecoveryTimer(),this.transportWaitStartedAt=void 0,this.pendingTransportRecoveryReason=void 0,this.registrationWaitStartedAt=void 0,this.pendingRegistrationRecoveryReason=void 0,this.state="idle",this.retryCount=0,this.signalingBusyCount=0,this.acceptedRecoveryGeneration=void 0,this.recoveryReason="",this.reinviteReason="unknown",this.lastRtpProgressAt=Date.now(),this.lastRtpSnapshot=void 0,this.logInfo("ICE healthy"),i&&(this.logInfo("ICE recovery succeeded"),null===(t=(e=this.options).onRecovered)||void 0===t||t.call(e))):this.logInfo("ICE healthy, waiting for re-INVITE acceptance")}getIceCandidates(){return r(this,void 0,void 0,function*(){const e=this.getPeerConnection();if(!e)return;const t=yield e.getStats(),i=[],r=[];return t.forEach(e=>{if("local-candidate"!==e.type&&"remote-candidate"!==e.type)return;const t={address:e.address,port:e.port,protocol:e.protocol,candidateType:e.candidateType};"local-candidate"===e.type?i.push(t):r.push(t)}),{localCandidates:i,remoteCandidates:r,iceGatheringState:e.iceGatheringState,iceConnectionState:e.iceConnectionState}})}recover(t){var i,s,n,o,a;return r(this,void 0,void 0,function*(){if(this.destroyed||this.hardFailed)return;if(this.session.state!==e.SessionState.Established)return void this.logWarn("skip recovery: session not established",this.session.state);if("undefined"!=typeof navigator&&!1===navigator.onLine)return this.logWarn("skip recovery: browser offline"),void(this.state="idle");if(!this.isTransportAvailable())return void this.waitForTransport(t);if(!this.isRegistrationAvailable())return void this.waitForRegistration(t);if("sending-reinvite"===this.state||"waiting-ice"===this.state)return void this.logDebug("skip recovery: recovery already running");const c=this.getPeerConnection();if(!c)return;if("stable"!==c.signalingState)return this.logWarn("skip recovery: signalingState not stable",c.signalingState),this.state="waiting-signaling",void this.scheduleSignalingBusyRetry(`signaling-busy:${c.signalingState}`);if(this.signalingBusyCount=0,this.clearSignalingBusyTimer(),this.retryCount>=this.options.maxRetries)return void this.failRecovery(`${t}:max-retries`);this.clearDisconnectedTimer(),this.clearRetryTimer(),this.retryCount++;const l=++this.recoveryGeneration;this.state="sending-reinvite";const h=this.readIceCredentials(null===(i=c.localDescription)||void 0===i?void 0:i.sdp);this.recoveryReason||(this.reinviteReason=this.resolveReinviteReason(t),this.recoveryReason=this.normalizeRecoveryReason(t,this.reinviteReason)),this.acceptedRecoveryGeneration=void 0,this.logInfo(`ICE recovery #${this.retryCount}`,{recoveryReason:this.recoveryReason,reinviteReason:this.reinviteReason}),null===(n=(s=this.options).onRecoveryStart)||void 0===n||n.call(s,this.recoveryReason,this.retryCount),this.startNegotiationTimeout(l,t);try{const e={offerOptions:{iceRestart:!0},iceGatheringTimeout:this.options.iceGatheringTimeoutMs,finalModifiers:this.options.includeRecoveryReasonInSdp?[this.permanentRecoverySdpModifier]:[]};this.session.sessionDescriptionHandlerOptionsReInvite=e,this.session.sessionDescriptionHandlerModifiersReInvite=[],this.logDebug("re-INVITE Final SDP configured",{recoveryReason:this.recoveryReason,reinviteReason:this.reinviteReason,includeRecoveryReasonInSdp:this.options.includeRecoveryReasonInSdp,finalModifierCount:null!==(a=null===(o=e.finalModifiers)||void 0===o?void 0:o.length)&&void 0!==a?a:0});const i=Date.now();yield this.session.invite({requestDelegate:{onTrying:()=>{this.isCurrentGeneration(l)&&this.logDebug("ICE re-INVITE trying")},onProgress:e=>{this.isCurrentGeneration(l)&&this.logDebug("ICE re-INVITE progress:",e.message.statusCode)},onAccept:()=>r(this,void 0,void 0,function*(){var e,r,s;if(!this.isCurrentGeneration(l))return;if(this.logInfo("ICE re-INVITE accepted"),this.userAgentManager.armsReportFlag)try{const t=Date.now();null===(r=null===(e=Ku.getAliArms())||void 0===e?void 0:e.getInstance())||void 0===r||r.api({api:`softphone-sdk-re-invite-${this.userAgentManager.appKey}-${this.userAgentManager.agentExtension}`,msg:JSON.stringify(Object.assign(Object.assign({businessAttribute:Object.keys(this.userAgentManager.businessAttribute).length?this.userAgentManager.businessAttribute:void 0,appKey:this.userAgentManager.appKey||void 0,agentId:this.userAgentManager.agentId||void 0,agentTag:this.userAgentManager.agentTag||void 0,agentExtension:this.userAgentManager.agentExtension||void 0,recoveryReason:this.recoveryReason||void 0,reinviteReason:this.reinviteReason||void 0},(yield this.getIceCandidates())||{}),{bjDate:Jt(),timestamp:Date.now()})),traceId:this.userAgentManager.businessAttribute.callId||this.userAgentManager.businessAttribute.cid,code:200,success:!0,time:t-i,begin:i})}catch(e){}this.clearNegotiationTimer(),this.acceptedRecoveryGeneration=l;const n=this.getPeerConnection();if(n&&"stable"!==n.signalingState&&this.logWarn("re-INVITE accepted but signalingState is not stable",n.signalingState),this.state="waiting-ice",this.options.debugIceCredentials){const e=this.readIceCredentials(null===(s=null==n?void 0:n.localDescription)||void 0===s?void 0:s.sdp);this.logInfo("ICE credentials:",{old:h,new:e,changed:this.hasIceCredentialsChanged(h,e)})}this.startIceRecoveryTimeout(l,t)}),onReject:e=>r(this,void 0,void 0,function*(){var r,s;if(this.userAgentManager.armsReportFlag)try{const t=Date.now();null===(s=null===(r=Ku.getAliArms())||void 0===r?void 0:r.getInstance())||void 0===s||s.api({api:`softphone-sdk-re-invite-${this.userAgentManager.appKey}-${this.userAgentManager.agentExtension}`,msg:JSON.stringify(Object.assign(Object.assign({businessAttribute:Object.keys(this.userAgentManager.businessAttribute).length?this.userAgentManager.businessAttribute:void 0,appKey:this.userAgentManager.appKey||void 0,agentId:this.userAgentManager.agentId||void 0,agentTag:this.userAgentManager.agentTag||void 0,agentExtension:this.userAgentManager.agentExtension||void 0,recoveryReason:this.recoveryReason||void 0,reinviteReason:this.reinviteReason||void 0},(yield this.getIceCandidates())||{}),{bjDate:Jt(),reasonPhrase:e.message.reasonPhrase||void 0,timestamp:Date.now()})),traceId:this.userAgentManager.businessAttribute.callId||this.userAgentManager.businessAttribute.cid,code:e.message.statusCode,success:!1,time:t-i,begin:i})}catch(e){}this.handleReinviteRejected(l,t,e.message.statusCode,e.message.reasonPhrase)})}})}catch(e){if(!this.isCurrentGeneration(l))return;this.clearNegotiationTimer(),this.clearIceRecoveryTimer(),this.logWarn("ICE re-INVITE error:",e);const i=yield this.rollbackLocalOffer("invite-exception");if(!this.isCurrentGeneration(l))return;if(!i)return void this.failRecovery(`${t}:rollback-failed:exception`);if(this.state="idle",this.signalingBusyCount=0,!this.isTransportAvailable())return void this.waitForTransport(`${t}:invite-exception`);if(this.isRequestPendingError(e))return void this.scheduleRetry(`${t}:request-pending`,1500);this.scheduleRetry(`${t}:exception`)}})}rollbackLocalOffer(e){return r(this,void 0,void 0,function*(){const t=this.getPeerConnection();if(!t)return!1;if("stable"===t.signalingState)return!0;if("have-local-offer"!==t.signalingState)return this.logWarn("cannot rollback current signaling state",{reason:e,signalingState:t.signalingState}),!1;try{this.logWarn("rollback local offer",{reason:e,signalingState:t.signalingState}),yield t.setLocalDescription({type:"rollback"});const i=t.signalingState,r="stable"===i;return this.logInfo("local offer rollback result",{success:r,signalingState:i}),r}catch(i){return this.logError("local offer rollback failed",{reason:e,error:i,signalingState:t.signalingState}),!1}})}normalizeRecoveryReason(e,t){return e.toLowerCase().includes("transport-restored")?`transport-restored:${t}`:"unknown"!==t?t:"unknown"}resolveReinviteReason(e){const t=e.toLowerCase();return t.includes("rtp-stalled")?"rtp-stalled":t.includes("ice-failed")?"ice-failed":t.includes("ice-disconnected")||t.includes("disconnected-timeout")?"ice-disconnected":t.includes("network-changed")?"network-changed":t.includes("transport-restored")?"transport-restored":t.includes("manual")?"manual":"unknown"}sanitizeSdpReason(e,t=256){return e.replace(/[\r\n]/g,"").replace(/[^a-zA-Z0-9._:-]/g,"_").slice(0,t)}sanitizeSdpAttributeName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"").slice(0,64)||"x-reinvite-reason"}applyRecoveryReasonToSdp(e){return r(this,void 0,void 0,function*(){if(!e.sdp||!this.options.includeRecoveryReasonInSdp)return e;const t=this.sanitizeSdpAttributeName(this.options.recoveryReasonSdpAttribute),i=this.sanitizeSdpAttributeName(this.options.reinviteReasonSdpAttribute),r=this.sanitizeSdpReason(this.recoveryReason||"unknown"),s=this.sanitizeSdpReason(this.reinviteReason||"unknown",64),n=e.sdp.split(/\r?\n/).filter(e=>!e.startsWith(`a=${t}:`)&&!e.startsWith(`a=${i}:`));for(;n.length>0&&""===n[n.length-1];)n.pop();const o=n.findIndex(e=>e.startsWith("m=")),a=o>=0?o:n.length;n.splice(a,0,`a=${t}:${r}`,`a=${i}:${s}`);const c=`${n.join("\r\n")}\r\n`,l=c.includes(`a=${t}:${r}`),h=c.includes(`a=${i}:${s}`);return this.logInfo("SDP modifier RESULT",{recoveryReason:r,reinviteReason:s,containsRecoveryReason:l,containsReinviteReason:h,insertedBeforeFirstMedia:o>=0}),this.logDebug("SDP custom reason lines",{recoveryLine:`a=${t}:${r}`,reinviteLine:`a=${i}:${s}`}),Object.assign(Object.assign({},e),{sdp:c})})}createRecoveryReasonSdpModifier(e,t){return i=>r(this,void 0,void 0,function*(){return this.recoveryReason=e,this.reinviteReason=t,this.applyRecoveryReasonToSdp(i)})}handleReinviteRejected(e,t,i,s){return r(this,void 0,void 0,function*(){if(!this.isCurrentGeneration(e))return;this.clearNegotiationTimer(),this.clearIceRecoveryTimer(),this.logWarn("ICE re-INVITE rejected:",i,s);const r=yield this.rollbackLocalOffer(`sip-${i}`);this.isCurrentGeneration(e)&&(r?(this.state="idle",this.signalingBusyCount=0,481!==i?this.isTransportAvailable()?491!==i?503!==i?this.scheduleRetry(`${t}:sip-${i}`):this.scheduleRetry(`${t}:sip-503`,3e3):this.scheduleRetry(`${t}:sip-491`,1500):this.waitForTransport(`${t}:sip-${i}`):this.failRecovery(`${t}:sip-481`)):this.failRecovery(`${t}:rollback-failed:sip-${i}`))})}startNegotiationTimeout(e,t){this.clearNegotiationTimer(),this.negotiationTimer=setTimeout(()=>{if(this.negotiationTimer=void 0,!this.isCurrentGeneration(e))return;const i=this.getPeerConnection();this.logError("re-INVITE negotiation timeout",{reason:t,signalingState:null==i?void 0:i.signalingState,iceConnectionState:null==i?void 0:i.iceConnectionState,connectionState:null==i?void 0:i.connectionState}),this.failRecovery(`${t}:negotiation-timeout`)},this.options.negotiationTimeoutMs)}startIceRecoveryTimeout(e,t){this.clearIceRecoveryTimer(),this.iceRecoveryTimer=setTimeout(()=>{if(this.iceRecoveryTimer=void 0,!this.isCurrentGeneration(e))return;const i=this.getPeerConnection();i&&("connected"!==i.iceConnectionState&&"completed"!==i.iceConnectionState?(this.logWarn("ICE recovery timeout",{reason:t,iceConnectionState:i.iceConnectionState,connectionState:i.connectionState,signalingState:i.signalingState}),this.state="idle","stable"===i.signalingState?this.scheduleRetry(`${t}:ice-timeout`):this.scheduleSignalingBusyRetry(`ice-timeout:${i.signalingState}`)):this.handleIceRecovered())},this.options.iceRecoveryTimeoutMs)}scheduleRetry(e,t=0){if(this.destroyed||this.hardFailed)return;if(this.retryCount>=this.options.maxRetries)return void this.failRecovery(`${e}:max-retries`);if(this.retryTimer)return;this.state="waiting-retry";const i=this.options.retryBaseDelayMs*Math.pow(2,Math.max(0,this.retryCount-1)),r=Math.min(i,this.options.retryMaxDelayMs),s=Math.floor(500*Math.random()),n=Math.max(r+s,t);this.logInfo(`schedule ICE retry in ${n}ms`,e),this.retryTimer=setTimeout(()=>{if(this.retryTimer=void 0,this.destroyed||this.hardFailed)return;if(!this.isTransportAvailable())return void this.waitForTransport(this.recoveryReason||e);const t=this.getPeerConnection();if(t)if("connected"!==t.iceConnectionState&&"completed"!==t.iceConnectionState){if("stable"!==t.signalingState)return this.state="waiting-signaling",void this.scheduleSignalingBusyRetry(`retry-signaling-busy:${t.signalingState}`);this.state="idle",this.recover(this.recoveryReason||e)}else this.handleIceRecovered()},n)}scheduleSignalingBusyRetry(t){var i;if(this.destroyed||this.hardFailed)return;if(!this.isTransportAvailable())return void this.waitForTransport(t);if(this.signalingBusyTimer)return;this.signalingBusyCount++;const r=this.getPeerConnection();if(this.logWarn("signalingState still busy",{reason:t,signalingState:null==r?void 0:r.signalingState,count:this.signalingBusyCount,max:this.options.maxSignalingBusyRetries}),this.signalingBusyCount>this.options.maxSignalingBusyRetries)return void this.failRecovery(`signaling-stuck:${null!==(i=null==r?void 0:r.signalingState)&&void 0!==i?i:"unknown"}`);this.state="waiting-signaling";const s=Math.floor(500*Math.random()),n=this.options.signalingBusyRetryDelayMs+s;this.logInfo(`schedule signaling retry in ${n}ms`),this.signalingBusyTimer=setTimeout(()=>{if(this.signalingBusyTimer=void 0,this.destroyed||this.hardFailed)return;if(this.session.state!==e.SessionState.Established)return;if(!this.isTransportAvailable())return void this.waitForTransport("signaling-unavailable");const t=this.getPeerConnection();return t?"stable"===t.signalingState?(this.signalingBusyCount=0,this.state="idle","connected"===t.iceConnectionState||"completed"===t.iceConnectionState?void this.handleIceRecovered():void this.recover("signaling-recovered")):void this.scheduleSignalingBusyRetry(`signaling-busy:${t.signalingState}`):void 0},n)}isTransportAvailable(){const e=this.options.isSignalingAvailable;if(!e)return!0;try{return e()}catch(e){return this.logWarn("isSignalingAvailable() threw",e),!1}}isRegistrationAvailable(){const e=this.options.isRegistrationAvailable;if(!e)return!0;try{return e()}catch(e){return this.logWarn("isRegistrationAvailable() threw",e),!1}}waitForRegistration(t){if(this.destroyed||this.hardFailed)return;if(!this.isTransportAvailable())return this.clearRegistrationRecoveryTimer(),this.registrationWaitStartedAt=void 0,this.pendingRegistrationRecoveryReason=void 0,void this.waitForTransport(t);if(this.isRegistrationAvailable()){const e=void 0===this.registrationWaitStartedAt?0:Date.now()-this.registrationWaitStartedAt;return this.clearRegistrationRecoveryTimer(),this.registrationWaitStartedAt=void 0,this.pendingRegistrationRecoveryReason=void 0,this.state="idle",this.logInfo("SIP registration recovered",{waitedMs:e,reason:t}),void this.resumeAfterRegistrationRecovery(t)}if(this.state="waiting-registration",this.pendingRegistrationRecoveryReason=t,void 0===this.registrationWaitStartedAt&&(this.registrationWaitStartedAt=Date.now(),this.logWarn("SIP registration unavailable; pause ICE restart",{reason:t,timeoutMs:this.options.registrationRecoveryTimeoutMs})),this.registrationRecoveryTimer)return;Date.now()-this.registrationWaitStartedAt>=this.options.registrationRecoveryTimeoutMs?this.failRecovery(`registration-recovery-timeout:${t}`):this.registrationRecoveryTimer=setTimeout(()=>{var i;this.registrationRecoveryTimer=void 0,this.destroyed||this.hardFailed||this.session.state===e.SessionState.Established&&this.waitForRegistration(null!==(i=this.pendingRegistrationRecoveryReason)&&void 0!==i?i:t)},this.options.registrationRecoveryPollMs)}resumeAfterRegistrationRecovery(t){return r(this,void 0,void 0,function*(){if(this.destroyed||this.hardFailed||this.session.state!==e.SessionState.Established)return;if(!this.isTransportAvailable())return void this.waitForTransport(t);if(!this.isRegistrationAvailable())return void this.waitForRegistration(t);const i=this.getPeerConnection();if(i)if("connected"!==i.iceConnectionState&&"completed"!==i.iceConnectionState){if("stable"!==i.signalingState)return this.state="waiting-signaling",void this.scheduleSignalingBusyRetry(`registration-restored:${i.signalingState}`);this.state="idle",yield this.recover(`registration-restored:${t}`)}else this.handleIceRecovered()})}waitForTransport(t){if(this.destroyed||this.hardFailed)return;if(this.isTransportAvailable())return this.transportWaitStartedAt=void 0,this.pendingTransportRecoveryReason=void 0,this.clearTransportRecoveryTimer(),this.state="idle",void this.resumeAfterTransportRecovery(t);if(this.state="waiting-transport",void 0===this.transportWaitStartedAt&&(this.transportWaitStartedAt=Date.now(),this.logWarn("SIP Transport unavailable; pause ICE restart",{reason:t,timeoutMs:this.options.transportRecoveryTimeoutMs})),this.pendingTransportRecoveryReason=t,this.transportRecoveryTimer)return;Date.now()-this.transportWaitStartedAt>=this.options.transportRecoveryTimeoutMs?this.failRecovery(`transport-recovery-timeout:${t}`):this.transportRecoveryTimer=setTimeout(()=>{var i,r;if(this.transportRecoveryTimer=void 0,this.destroyed||this.hardFailed)return;if(this.session.state!==e.SessionState.Established)return;if(!this.isTransportAvailable())return void this.waitForTransport(null!==(i=this.pendingTransportRecoveryReason)&&void 0!==i?i:t);const s=null!==(r=this.pendingTransportRecoveryReason)&&void 0!==r?r:t,n=void 0===this.transportWaitStartedAt?0:Date.now()-this.transportWaitStartedAt;this.transportWaitStartedAt=void 0,this.pendingTransportRecoveryReason=void 0,this.logInfo("SIP Transport recovered",{waitedMs:n,reason:s}),this.state="idle",this.resumeAfterTransportRecovery(s)},this.options.transportRecoveryPollMs)}resumeAfterTransportRecovery(t){return r(this,void 0,void 0,function*(){if(this.destroyed||this.hardFailed||this.session.state!==e.SessionState.Established)return;if(!this.isTransportAvailable())return void this.waitForTransport(t);if(!this.isRegistrationAvailable())return void this.waitForRegistration(t);const i=this.getPeerConnection();if(i)if("connected"!==i.iceConnectionState&&"completed"!==i.iceConnectionState){if("stable"!==i.signalingState)return this.state="waiting-signaling",void this.scheduleSignalingBusyRetry(`transport-restored:${i.signalingState}`);this.state="idle",yield this.recover(`transport-restored:${t}`)}else this.handleIceRecovered()})}failRecovery(e){var t,i,r,s,n;this.destroyed||this.hardFailed||(this.hardFailed=!0,this.recoveryGeneration++,this.state="failed",this.clearDisconnectedTimer(),this.clearRetryTimer(),this.clearSignalingBusyTimer(),this.clearNegotiationTimer(),this.clearIceRecoveryTimer(),this.clearTransportRecoveryTimer(),this.clearRegistrationRecoveryTimer(),this.transportWaitStartedAt=void 0,this.pendingTransportRecoveryReason=void 0,this.registrationWaitStartedAt=void 0,this.pendingRegistrationRecoveryReason=void 0,this.stopRtpWatchdog(),this.logError("ICE recovery unrecoverable",{reason:e,retryCount:this.retryCount,signalingBusyCount:this.signalingBusyCount,iceConnectionState:null===(t=this.getPeerConnection())||void 0===t?void 0:t.iceConnectionState,connectionState:null===(i=this.getPeerConnection())||void 0===i?void 0:i.connectionState,signalingState:null===(r=this.getPeerConnection())||void 0===r?void 0:r.signalingState}),null===(n=(s=this.options).onRecoveryFailed)||void 0===n||n.call(s,e,this.retryCount))}startRtpWatchdog(){this.rtpStatsTimer||this.destroyed||this.hardFailed||(this.lastRtpProgressAt=Date.now(),this.rtpStatsTimer=setInterval(()=>{this.checkRtpHealth()},this.options.rtpStatsIntervalMs))}stopRtpWatchdog(){this.rtpStatsTimer&&(clearInterval(this.rtpStatsTimer),this.rtpStatsTimer=void 0)}checkRtpHealth(){return r(this,void 0,void 0,function*(){if(this.destroyed||this.hardFailed||this.session.state!==e.SessionState.Established)return;const t=this.getPeerConnection();if(!t)return;if("connected"!==t.iceConnectionState&&"completed"!==t.iceConnectionState)return;if("sending-reinvite"===this.state||"waiting-ice"===this.state||"waiting-signaling"===this.state||"waiting-transport"===this.state)return;let i;try{i=yield this.readRtpSnapshot(t)}catch(e){return void this.logDebug("getStats failed:",e)}if(!i.hasAudio&&!i.hasVideo)return;const r=this.lastRtpSnapshot;if(this.lastRtpSnapshot=i,!r)return void(this.lastRtpProgressAt=Date.now());const s=i.audioBytes>r.audioBytes||i.audioPackets>r.audioPackets,n=i.videoBytes>r.videoBytes||i.videoPackets>r.videoPackets||i.videoFramesDecoded>r.videoFramesDecoded;if(s||n)return void(this.lastRtpProgressAt=Date.now());const o=Date.now()-this.lastRtpProgressAt;if(o<this.options.rtpStallTimeoutMs)return;const a=Date.now();a-this.lastRtpRecoveryAt<this.options.rtpRecoveryCooldownMs||(this.logWarn(`RTP stalled for ${o}ms`,{ice:t.iceConnectionState,connection:t.connectionState,signaling:t.signalingState,audioBytes:i.audioBytes,audioPackets:i.audioPackets,videoBytes:i.videoBytes,videoPackets:i.videoPackets,videoFramesDecoded:i.videoFramesDecoded}),this.options.recoverOnRtpStallWhenIceConnected&&(this.lastRtpRecoveryAt=a,this.recover("rtp-stalled")))})}readRtpSnapshot(e){return r(this,void 0,void 0,function*(){const t=yield e.getStats(),i={timestamp:Date.now(),audioBytes:0,audioPackets:0,videoBytes:0,videoPackets:0,videoFramesDecoded:0,hasAudio:!1,hasVideo:!1};return t.forEach(e=>{var t;if("inbound-rtp"!==e.type)return;if(!0===e.isRemote)return;const r=null!==(t=e.kind)&&void 0!==t?t:e.mediaType;"audio"===r&&(i.hasAudio=!0,"number"==typeof e.bytesReceived&&(i.audioBytes+=e.bytesReceived),"number"==typeof e.packetsReceived&&(i.audioPackets+=e.packetsReceived)),"video"===r&&(i.hasVideo=!0,"number"==typeof e.bytesReceived&&(i.videoBytes+=e.bytesReceived),"number"==typeof e.packetsReceived&&(i.videoPackets+=e.packetsReceived),"number"==typeof e.framesDecoded&&(i.videoFramesDecoded+=e.framesDecoded))}),i})}getSessionDescriptionHandler(){return this.session.sessionDescriptionHandler}getPeerConnection(){var e;return null===(e=this.getSessionDescriptionHandler())||void 0===e?void 0:e.peerConnection}readIceCredentials(e){var t,i,r,s;return e?{ufrag:null===(i=null===(t=e.match(/^a=ice-ufrag:(.+)$/m))||void 0===t?void 0:t[1])||void 0===i?void 0:i.trim(),pwd:null===(s=null===(r=e.match(/^a=ice-pwd:(.+)$/m))||void 0===r?void 0:r[1])||void 0===s?void 0:s.trim()}:{}}hasIceCredentialsChanged(e,t){return e.ufrag!==t.ufrag||e.pwd!==t.pwd}isRequestPendingError(e){return e instanceof Error&&("RequestPendingError"===e.name||/request.*pending/i.test(e.message))}isCurrentGeneration(e){return!this.destroyed&&!this.hardFailed&&e===this.recoveryGeneration}clearDisconnectedTimer(){this.disconnectedTimer&&(clearTimeout(this.disconnectedTimer),this.disconnectedTimer=void 0)}clearRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=void 0)}clearSignalingBusyTimer(){this.signalingBusyTimer&&(clearTimeout(this.signalingBusyTimer),this.signalingBusyTimer=void 0)}clearNegotiationTimer(){this.negotiationTimer&&(clearTimeout(this.negotiationTimer),this.negotiationTimer=void 0)}clearIceRecoveryTimer(){this.iceRecoveryTimer&&(clearTimeout(this.iceRecoveryTimer),this.iceRecoveryTimer=void 0)}clearTransportRecoveryTimer(){this.transportRecoveryTimer&&(clearTimeout(this.transportRecoveryTimer),this.transportRecoveryTimer=void 0)}clearRegistrationRecoveryTimer(){this.registrationRecoveryTimer&&(clearTimeout(this.registrationRecoveryTimer),this.registrationRecoveryTimer=void 0)}clearAllTimers(){this.clearDisconnectedTimer(),this.clearRetryTimer(),this.clearSignalingBusyTimer(),this.clearNegotiationTimer(),this.clearIceRecoveryTimer(),this.stopRtpWatchdog(),this.onlineTimer&&(clearTimeout(this.onlineTimer),this.onlineTimer=void 0)}logDebug(...e){var t,i;null===(i=(t=this.options.logger).debug)||void 0===i||i.call(t,"[SipIceRecovery]",...e)}logInfo(...e){var t,i;null===(i=(t=this.options.logger).info)||void 0===i||i.call(t,"[SipIceRecovery]",...e)}logWarn(...e){var t,i;null===(i=(t=this.options.logger).warn)||void 0===i||i.call(t,"[SipIceRecovery]",...e)}logError(...e){var t,i;null===(i=(t=this.options.logger).error)||void 0===i||i.call(t,"[SipIceRecovery]",...e)}}class Yu{constructor(e,t=200){Object.defineProperty(this,"onAggregateCallback",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"debounceTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingCalls",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.onAggregateCallback=e,this.debounceTime=t,this.pendingCalls=new Map}receive(e){return r(this,void 0,void 0,function*(){const{CALLID:t,ENTRY:i}=e;if(this.pendingCalls.has(t)){const e=this.pendingCalls.get(t);clearTimeout(e.timer),e.data.ENTRY.push(i),e.count+=1,e.timer=setTimeout(()=>this._flush(t),this.debounceTime)}else{const r=JSON.parse(JSON.stringify(e));r.ENTRY=[i];const s=setTimeout(()=>this._flush(t),this.debounceTime);this.pendingCalls.set(t,{timer:s,data:r,count:1})}})}_flush(e){return r(this,void 0,void 0,function*(){if(this.pendingCalls.has(e)){const{data:t}=this.pendingCalls.get(e);this.pendingCalls.delete(e),yield this.onAggregateCallback(t)}})}}class Ju{get armsReportFlag(){return s(this,Lh,"f")}set armsReportFlag(e){n(this,Lh,e,"f")}get volumeValue(){return s(this,_h,"f")}getToken(e={}){return r(this,void 0,void 0,function*(){const{appKey:t,appSecret:i,agentId:r,agentTag:o}=e||{};let a=r||s(this,$d,"f"),c=o||s(this,Cd,"f"),l=i||s(this,Id,"f"),h=t||s(this,Ed,"f");if(!a&&c&&l&&h){const e=yield this.getAgentInfo({agentTag:c,appSecret:l,appKey:h});if(200!=e.code)throw new Error(e.message);n(this,$d,a=e.data.agentId,"f")}const{token:d}=yield this.getGatewayAccessToken({corpId:h,secret:l,sid:a,seatOnline:!1});return d})}armsReport(e){var t,i;const{api:r,traceId:n,code:o,success:a,begin:c,time:l,businessInfo:h}=e;"softphone-sdk-hangup"!==e.api&&"softphone-sdk-seats-status-change"!==e.api&&"softphone-sdk-accept"!==e.api&&"softphone-sdk-connect"!==e.api&&"softphone-sdk-send-star-dtmf"!==e.api&&"softphone-sdk-ignore"!==e.api&&"softphone-sdk-manual-call"!==e.api||null===(i=null===(t=Ku.getAliArms())||void 0===t?void 0:t.getInstance())||void 0===i||i.api({api:`${r}-${s(this,Ed,"f")}-${s(this,Oh,"f").authorizationUsername}`,msg:JSON.stringify({appKey:s(this,Ed,"f")||void 0,agentId:s(this,$d,"f")||void 0,agentTag:s(this,Cd,"f")||void 0,agentExtension:s(this,Oh,"f").authorizationUsername||void 0,businessAttribute:Object.keys(s(this,Wd,"f")).length?s(this,Wd,"f"):void 0,businessInfo:Object.keys(h||{}).length?h:void 0,bjDate:Jt(),timestamp:Date.now()}),traceId:n,code:o,success:a,time:l,begin:c})}get appKey(){return s(this,Ed,"f")}get agentTag(){return s(this,Cd,"f")}get agentExtension(){return s(this,Oh,"f").authorizationUsername}get agentId(){return s(this,$d,"f")}get businessAttribute(){return s(this,Wd,"f")}getFastOutboundCall(){return s(this,Wd,"f").voiceType===e.VoiceType.LABOUR}getSitOutboundCall(){return s(this,Wd,"f").voiceType===e.VoiceType.AI}constructor(o={}){if(wh.add(this),Sh.set(this,void 0),Th.set(this,void 0),Rh.set(this,void 0),Eh.set(this,void 0),Ih.set(this,void 0),Ch.set(this,void 0),Ph.set(this,[]),Ah.set(this,[]),Oh.set(this,{}),kh.set(this,void 0),Dh.set(this,void 0),$h.set(this,new MediaStream),jh.set(this,JSON.parse(JSON.stringify(Xt))),_h.set(this,0),Hh.set(this,void 0),Mh.set(this,void 0),xh.set(this,void 0),Object.defineProperty(this,"token",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),qh.set(this,void 0),Nh.set(this,48e4),Fh.set(this,12e6),Uh.set(this,{}),Lh.set(this,!1),Bh.set(this,void 0),Wh.set(this,void 0),Gh.set(this,void 0),Vh.set(this,e=>{}),Kh.set(this,e=>{}),zh.set(this,e=>{}),Yh.set(this,e=>{}),Jh.set(this,e=>r(this,void 0,void 0,function*(){if(s(this,Hh,"f")&&s(this,Mh,"f")&&Date.now()-s(this,Mh,"f")>e){const{sign:e,timestamp:t}=(yield s(this,Xh,"f").call(this))||{};n(this,Hh,null!=e?e:s(this,Hh,"f"),"f"),n(this,Mh,null!=t?t:s(this,Mh,"f"),"f")}})),Zh.set(this,e=>r(this,void 0,void 0,function*(){if(s(this,qh,"f")&&Date.now()-s(this,qh,"f")>e)if(s(this,xh,"f")){const{token:e,tokenTimestamp:t}=yield s(this,td,"f").call(this);n(this,xh,null!=e?e:s(this,xh,"f"),"f"),n(this,qh,null!=t?t:Date.now(),"f")}else if(this.token){const{token:e}=yield this.getGatewayAccessToken({corpId:s(this,Ed,"f"),sid:s(this,$d,"f"),secret:s(this,Id,"f"),seatOnline:!1});this.token=e,n(this,qh,Date.now(),"f")}})),Xh.set(this,()=>{}),Qh.set(this,e=>{s(this,Lh,"f")&&s(this,ed,"f").receive(e)}),ed.set(this,new Yu(e=>{var t,i;delete e.INVITE,null===(i=null===(t=Ku.getAliArms())||void 0===t?void 0:t.getInstance())||void 0===i||i.api({api:`softphone-sdk-auto-ignore-${s(this,Ed,"f")}-${s(this,Oh,"f").authorizationUsername}`,msg:JSON.stringify({errorInfo:e,businessAttribute:Object.keys(s(this,Wd,"f")).length?s(this,Wd,"f"):void 0,appKey:s(this,Ed,"f")||void 0,agentId:s(this,$d,"f")||void 0,agentTag:s(this,Cd,"f")||void 0,agentExtension:s(this,Oh,"f").authorizationUsername||void 0,bjDate:Jt(),timestamp:Date.now()}),traceId:e.CALLID,code:e.CODE,success:!0,time:0})})),td.set(this,()=>{}),id.set(this,e=>{}),rd.set(this,e=>{}),sd.set(this,void 0),nd.set(this,void 0),Object.defineProperty(this,"networkSpeed",{enumerable:!0,configurable:!0,writable:!0,value:"0.00Mb/s"}),Object.defineProperty(this,"networkDelay",{enumerable:!0,configurable:!0,writable:!0,value:"0ms"}),Object.defineProperty(this,"onLine",{enumerable:!0,configurable:!0,writable:!0,value:navigator.onLine}),Object.defineProperty(this,"testspeeding",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"goodNetworkSpeed",{enumerable:!0,configurable:!0,writable:!0,value:()=>1e3*Number(this.networkSpeed.replace("Mb/s",""))>=30}),Object.defineProperty(this,"goodNetworkDelay",{enumerable:!0,configurable:!0,writable:!0,value:()=>Number(this.networkDelay.replace("ms",""))<=500&&"0ms"!==this.networkDelay}),Object.defineProperty(this,"authorizedMicrophonePermissions",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"authorizedNotificationPermissions",{enumerable:!0,configurable:!0,writable:!0,value:!1}),od.set(this,100),ad.set(this,3),cd.set(this,8),ld.set(this,2),hd.set(this,0),dd.set(this,!1),ud.set(this,void 0),gd.set(this,3),fd.set(this,3),pd.set(this,0),vd.set(this,0),md.set(this,0),bd.set(this,!1),yd.set(this,!1),wd.set(this,!1),Sd.set(this,void 0),Td.set(this,void 0),Rd.set(this,void 0),Ed.set(this,void 0),Id.set(this,void 0),Cd.set(this,void 0),Pd.set(this,void 0),Ad.set(this,void 0),Od.set(this,void 0),kd.set(this,void 0),Dd.set(this,void 0),$d.set(this,void 0),jd.set(this,void 0),_d.set(this,void 0),Hd.set(this,void 0),Md.set(this,void 0),xd.set(this,e=>{s(this,wh,"m",Nu).call(this)}),qd.set(this,()=>{}),Nd.set(this,void 0),Fd.set(this,void 0),Ud.set(this,!1),Ld.set(this,4e3),Bd.set(this,4e3),Wd.set(this,{}),Gd.set(this,!1),Vd.set(this,!0),Object.defineProperty(this,"ifAutoAnswer",{enumerable:!0,configurable:!0,writable:!0,value:()=>String(s(this,Wd,"f").autoAnswer)===Qt.YES}),Object.defineProperty(this,"notNeedSendStarDtmf",{enumerable:!0,configurable:!0,writable:!0,value:()=>String(s(this,Wd,"f").afterTransferLabour)===e.AfterTransferLabour.DIRECT_ANSWER}),Kd.set(this,()=>{if(s(this,Vd,"f")){s(this,zd,"f").call(this);const e=new(window.AudioContext||window.webkitAudioContext);n(this,Wh,e.createScriptProcessor(2048,1,1),"f"),s(this,Wh,"f").onaudioprocess=e=>{const t=e.inputBuffer.getChannelData(0);let i=0;for(let e=0;e<t.length;++e)i+=t[e]*t[e];n(this,_h,Number(Math.sqrt(i/t.length).toFixed(2)),"f"),s(this,Vh,"f").call(this,s(this,_h,"f"))},n(this,Gh,new MediaStream,"f"),this.getSenders().forEach(e=>{e.track&&s(this,Gh,"f").addTrack(e.track)}),n(this,Bh,e.createMediaStreamSource(s(this,Gh,"f")),"f"),s(this,Bh,"f").connect(s(this,Wh,"f")),s(this,Wh,"f").connect(e.destination)}}),zd.set(this,()=>{if(s(this,Vd,"f")){if(s(this,Bh,"f"))try{s(this,Bh,"f").disconnect()}catch(e){console.log(e)}if(s(this,Wh,"f"))try{s(this,Wh,"f").disconnect()}catch(e){console.log(e)}if(s(this,Gh,"f"))try{s(this,Gh,"f").getTracks().forEach(e=>{e.stop()})}catch(e){console.log(e)}}n(this,Bh,void 0,"f"),n(this,Wh,void 0,"f"),n(this,Gh,void 0,"f"),n(this,_h,0,"f"),s(this,Vh,"f").call(this,s(this,_h,"f"))}),Object.defineProperty(this,"disposeSoftphoneEnvRequirementCheck",{enumerable:!0,configurable:!0,writable:!0,value:()=>{s(this,Yd,"f").call(this),window.removeEventListener("offline",s(this,Xd,"f")),window.removeEventListener("online",s(this,Zd,"f")),window.removeEventListener("unload",this.disposeSoftphoneEnvRequirementCheck)}}),Yd.set(this,()=>{clearInterval(s(this,sd,"f")),n(this,sd,void 0,"f"),clearTimeout(s(this,nd,"f")),n(this,nd,void 0,"f"),this.testspeeding=!1}),Object.defineProperty(this,"softphoneEnvCheck",{enumerable:!0,configurable:!0,writable:!0,value:()=>r(this,void 0,void 0,function*(){this.testspeeding||(s(this,Jd,"f").call(this),this.oneRoundOfTesting())})}),Jd.set(this,()=>{window.addEventListener("offline",s(this,Xd,"f")),window.addEventListener("online",s(this,Zd,"f")),window.addEventListener("unload",this.disposeSoftphoneEnvRequirementCheck)}),Object.defineProperty(this,"oneRoundOfTesting",{enumerable:!0,configurable:!0,writable:!0,value:()=>r(this,void 0,void 0,function*(){this.testspeeding=!0,this.detectNavigatorPermissions(),this.onLine?(s(this,Qd,"f").call(this,this),n(this,nd,setTimeout(()=>{this.testspeeding=!1,this.disposeSoftphoneEnvRequirementCheck()},4e3),"f")):this.testspeeding=!1})}),Zd.set(this,()=>{this.onLine=!0,this.oneRoundOfTesting()}),Xd.set(this,()=>{this.onLine=!1,this.networkSpeed="0.00Mb/s",this.networkDelay="0ms",s(this,rd,"f").call(this,{networkSpeed:this.networkSpeed,networkDelay:this.networkDelay,authorizedMicrophonePermissions:this.authorizedMicrophonePermissions,authorizedNotificationPermissions:this.authorizedNotificationPermissions}),s(this,Yd,"f").call(this)}),Qd.set(this,e=>r(this,void 0,void 0,function*(){const t=e||this;clearInterval(s(t,sd,"f")),n(t,sd,void 0,"f");const i=()=>r(this,void 0,void 0,function*(){if(t.onLine)try{const e=yield s(t,eu,"f").call(t,"1"===s(t,Hd,"f")?"https://seat.teleai.com/favicon.png":void 0);t.networkSpeed=e.networkSpeed,t.networkDelay=e.networkDelay}catch(e){t.networkSpeed="0.00Mb/s",t.networkDelay="0ms"}else t.networkSpeed="0.00Mb/s",t.networkDelay="0ms";s(this,rd,"f").call(this,{networkSpeed:this.networkSpeed,networkDelay:this.networkDelay,authorizedMicrophonePermissions:this.authorizedMicrophonePermissions,authorizedNotificationPermissions:this.authorizedNotificationPermissions}),s(this,nd,"f")||(this.testspeeding=!1,this.disposeSoftphoneEnvRequirementCheck())});yield i(),s(this,nd,"f")&&n(t,sd,setInterval(function(){return r(this,void 0,void 0,function*(){yield i()})},1e3),"f")})),eu.set(this,(e="https://seat.94ai.com/favicon.png",t=63491,i=1)=>r(this,void 0,void 0,function*(){const r=[];for(let n=0;n<i;n++)r.push(s(this,tu,"f").call(this,e+"?d="+Date.now()+n,t));return Promise.all(r).then(e=>{let t=0,r=0;return e.forEach(e=>{t+=Number(e[0]),r+=Number(e[1])}),{networkDelay:(r/i).toFixed(2)+"ms",networkSpeed:(t/i).toFixed(2)+"Mb/s"}})})),tu.set(this,(e="https://seat.94ai.com/favicon.png?d="+Date.now(),t=63491)=>new Promise((i,r)=>{const s=document.createElement("img");s.start=window.performance.now(),s.onload=function(){const e=window.performance.now()-s.start;i([(1e3*t/(1048576*e)).toFixed(2),e])},s.onerror=function(e){r(e)},s.src=e}).catch(e=>{throw e})),Object.defineProperty(this,"openApiAjax",{enumerable:!0,configurable:!0,writable:!0,value:e=>new Promise((i,n)=>r(this,void 0,void 0,function*(){var r,o,a,c,l,h,d,u;try{const g=s(this,Ed,"f")||(null===(r=e.data)||void 0===r?void 0:r.appKey),f=s(this,Id,"f")||(null===(o=e.data)||void 0===o?void 0:o.appSecret);let p=s(this,Hh,"f")||(null===(a=e.data)||void 0===a?void 0:a.sign),v=s(this,Mh,"f")||(null===(c=e.data)||void 0===c?void 0:c.timestamp);if(null===(l=e.data)||void 0===l||delete l.appKey,null===(h=e.data)||void 0===h||delete h.appSecret,null===(d=e.data)||void 0===d||delete d.sign,null===(u=e.data)||void 0===u||delete u.timestamp,!g)throw new Error("缺少appKey");if(f)v=Date.now(),p=t.enc.Base64.stringify(t.HmacSHA1(g+v,f));else{if(!p||!v)throw new Error("缺少appSecret或sign+timestamp");yield s(this,Jh,"f").call(this,s(this,Nh,"f")),p=s(this,Hh,"f")||p,v=s(this,Mh,"f")||v}const{xhr:m,ajaxData:b,contentType:y}=Yt(i,n,e);m.setRequestHeader("appKey",g),m.setRequestHeader("timestamp",String(v)),m.setRequestHeader("sign",p),m.setRequestHeader("Content-type",y||"application/json"),yield s(this,zh,"f").call(this,m),m.send(b)}catch(e){throw n(e.message),e}}))}),Object.defineProperty(this,"requestGateway",{enumerable:!0,configurable:!0,writable:!0,value:(e,t=!0)=>this.gatewayApiAjax(Object.assign(Object.assign({},e),{url:this.getGateway()+e.url}),t)}),Object.defineProperty(this,"gatewayApiAjax",{enumerable:!0,configurable:!0,writable:!0,value:(e,t=!0)=>new Promise((i,n)=>r(this,void 0,void 0,function*(){try{const{xhr:r,ajaxData:o,contentType:a}=Yt(i,n,e);if(t){const e=yield this.getGatewayToken();r.setRequestHeader("x-token",e),r.setRequestHeader("seatsToken",e),r.setRequestHeader("x-authority-token",e)}r.setRequestHeader("x-app-code",3),r.setRequestHeader("content-type",a||"application/json"),yield s(this,Yh,"f").call(this,r),r.send(o)}catch(e){throw n(e.message),e}}))}),Object.defineProperty(this,"requestOpenApi",{enumerable:!0,configurable:!0,writable:!0,value:e=>this.openApiAjax(Object.assign(Object.assign({},e),{url:this.getOpenApi()+e.url}))}),Object.defineProperty(this,"getDeviceId",{enumerable:!0,configurable:!0,writable:!0,value:()=>r(this,void 0,void 0,function*(){if(s(this,Md,"f"))return s(this,Md,"f");const e=yield i.load(),t=yield e.get();return n(this,Md,t.visitorId,"f"),s(this,Md,"f")})}),lu.set(this,()=>r(this,void 0,void 0,function*(){var e,t;if(s(this,wh,"m",cu).call(this)&&(!s(this,Oh,"f").authorizationUsername||!s(this,Oh,"f").uri||!s(this,Oh,"f").authorizationPassword||!s(this,Oh,"f").transportOptions.server)){const i=yield this.getAgentInfo();if(200!=i.code)throw new Error(JSON.stringify(i));{const r=i.data;s(this,Oh,"f").authorizationUsername=r.agentExtension,s(this,Oh,"f").authorizationPassword=r.extensionPwd,s(this,Oh,"f").contactName||(s(this,Oh,"f").contactName=r.agentExtension),s(this,Oh,"f").uri=ot.makeURI(`sip:${r.agentExtension}@${r.wsRegisterAddress}`),s(this,Oh,"f").transportOptions.server=`${r.wsProtocol}://${r.wsRegisterAddress}`,n(this,$d,r.agentId,"f"),n(this,Cd,r.agentTag,"f"),n(this,Pd,r.agentName,"f"),n(this,Ad,r.agentAccount,"f"),n(this,Od,r.agentActive,"f"),n(this,kd,r.agentGroupIds,"f"),n(this,Dd,r.agentStatus,"f"),null===(t=null===(e=Ku.getAliArms())||void 0===e?void 0:e.getInstance())||void 0===t||t.setConfig({setUsername:()=>s(this,Ed,"f")+"-"+s(this,Oh,"f").authorizationUsername})}}})),hu.set(this,()=>r(this,void 0,void 0,function*(){s(this,Oh,"f").viaHost||(s(this,Oh,"f").viaHost=`${yield this.getDeviceId()}.sip`)})),uu.set(this,e=>{var t,i,r,n,o,a,c,l,h,d,u,g,f,p,v,m,b,y,w;s(this,Wd,"f").popWindow=null===(t=e["X-Popwindow"])||void 0===t?void 0:t[0].raw,s(this,Wd,"f").afterTransferLabour=null===(i=e["X-Aftertransferlabour"])||void 0===i?void 0:i[0].raw,s(this,Wd,"f").callId=null===(r=e["X-94callid"])||void 0===r?void 0:r[0].raw,s(this,Wd,"f").cid=null===(n=e["X-Cid"])||void 0===n?void 0:n[0].raw,s(this,Wd,"f").numberId=null===(o=e["X-Numberid"])||void 0===o?void 0:o[0].raw,s(this,Wd,"f").tag=(null===(a=e["X-Tag"])||void 0===a?void 0:a[0].raw)&&"null"!==(null===(c=e["X-Tag"])||void 0===c?void 0:c[0].raw)?e["X-Tag"][0].raw.split("-").map(e=>String.fromCharCode(e)).join(""):"",s(this,Wd,"f").numberTag=(null===(l=e["X-Numbertag"])||void 0===l?void 0:l[0].raw)&&"null"!==(null===(h=e["X-Numbertag"])||void 0===h?void 0:h[0].raw)?decodeURIComponent(e["X-Numbertag"][0].raw):"",s(this,Wd,"f").taskId=null===(d=e["X-Taskid"])||void 0===d?void 0:d[0].raw,s(this,Wd,"f").voiceType=null===(u=e["X-Voicetype"])||void 0===u?void 0:u[0].raw,s(this,Wd,"f").processTime=null===(g=e["X-Processtime"])||void 0===g?void 0:g[0].raw,s(this,Wd,"f").userPhone=null===(f=e["X-Userphone"])||void 0===f?void 0:f[0].raw,s(this,Wd,"f").autoAnswer=null===(p=e["X-94autoanswer"])||void 0===p?void 0:p[0].raw,s(this,Wd,"f").nodeTitle=null===(v=e["X-Nodetitle"])||void 0===v?void 0:v[0].raw.split("-").map(e=>String.fromCharCode(e)).join(""),s(this,Wd,"f").taskName=null===(m=e["X-Taskname"])||void 0===m?void 0:m[0].raw.split("-").map(e=>String.fromCharCode(e)).join(""),s(this,Wd,"f").templateTitle=null===(b=e["X-Templatetitle"])||void 0===b?void 0:b[0].raw.split("-").map(e=>String.fromCharCode(e)).join(""),s(this,Wd,"f").phoneNumber=(null===(y=e["X-Phonenumber"])||void 0===y?void 0:y[0].raw)||(null===(w=e.From)||void 0===w?void 0:w[0].parsed.uri.normal.user)}),Cu.set(this,t=>{switch(t){case e.SessionState.Initial:case e.SessionState.Establishing:break;case e.SessionState.Established:s(this,wh,"m",Iu).call(this);break;case e.SessionState.Terminating:case e.SessionState.Terminated:this.clearIceAutoDetection();let t=setTimeout(()=>{clearTimeout(t),t=void 0,s(this,jh,"f").incomingStatus=!1,s(this,jh,"f").answerStatus=!1},10);s(this,zd,"f").call(this);break;default:throw new Error("Unknown session state.")}}),Au.set(this,(e,t,i)=>{s(this,cd,"f")&&(n(this,dd,!1,"f"),s(this,jh,"f").reconnectStatus=!1,s(this,yd,"f")&&(n(this,yd,!1,"f"),s(this,Du,"f").call(this,e,t,i)))}),Ou.set(this,()=>r(this,void 0,void 0,function*(){if(s(this,cd,"f")){n(this,dd,!0,"f"),n(this,yd,!1,"f");try{this.getUserAgent().transport.disconnect().catch(e=>console.error(e))}catch(e){}console.log("sip transport disconnect");try{s(this,wh,"m",Pu).call(this)}catch(e){}s(this,$u,"f").call(this),s(this,wh,"m",Nu).call(this)}})),ku.set(this,()=>{if(s(this,cd,"f")){const e=s(this,Oh,"f").uri.clone(),t=s(this,Oh,"f").uri.clone(),i=s(this,Oh,"f").uri.clone();i.user=void 0,s(this,Du,"f").call(this,i,e,t)}}),Du.set(this,(e,t,i)=>{if(s(this,cd,"f")){if(s(this,yd,"f"))return;n(this,yd,!0,"f"),n(this,Td,setTimeout(()=>{s(this,wh,"m",xu).call(this);const r=this.getUserAgent().userAgentCore,o=r.makeOutgoingRequestMessage("OPTIONS",e,t,i,{});n(this,ud,r.request(o,{onAccept:()=>{console.log("sip ping ok"),n(this,hd,0,"f"),n(this,ud,void 0,"f"),s(this,Au,"f").call(this,e,t,i)},onReject:r=>{var o;n(this,ud,void 0,"f"),408===r.message.statusCode||503===r.message.statusCode?(console.log("sip ping error with code "+r.message.statusCode),s(this,ld,"f")>0&&s(this,hd,"f")>=s(this,ld,"f")?(console.log("sip maximum ping attempts reached"),s(this,Ou,"f").call(this)):(s(this,hd,"f")>0&&console.log(`sip ping retry ${s(this,hd,"f")} of ${s(this,ld,"f")} fail`),n(this,hd,(o=s(this,hd,"f"),++o),"f"),console.log(`sip ping retry ${s(this,hd,"f")} of ${s(this,ld,"f")}`),s(this,Au,"f").call(this,e,t,i))):(n(this,hd,0,"f"),s(this,Au,"f").call(this,e,t,i))}}),"f")},1e3*s(this,cd,"f")),"f")}}),$u.set(this,()=>{if(s(this,cd,"f")){if(n(this,yd,!1,"f"),n(this,dd,!1,"f"),s(this,ud,"f")){try{s(this,ud,"f").dispose()}catch(e){}n(this,ud,void 0,"f")}s(this,Td,"f")&&s(this,wh,"m",xu).call(this)}}),qu.set(this,()=>{if(s(this,gd,"f")){if(s(this,wd,"f"))return;n(this,wd,!0,"f"),s(this,jh,"f").reconnectStatus=!0,n(this,Rd,setTimeout(()=>r(this,void 0,void 0,function*(){try{s(this,wh,"m",Hu).call(this),0===s(this,pd,"f")&&console.log("sip reconnect success then register start"),yield s(this,Eh,"f").register({requestDelegate:{onAccept:e=>{console.log("sip reconnect success and register ok"),n(this,pd,0,"f"),n(this,wd,!1,"f"),s(this,jh,"f").registerStatus=!0,s(this,jh,"f").reconnectStatus=!1,s(this,ku,"f").call(this)},onReject:e=>r(this,void 0,void 0,function*(){var t;console.log("sip reconnect success but register fail with code "+e.message.statusCode),n(this,wd,!1,"f"),s(this,fd,"f")<=s(this,pd,"f")?(console.log("sip maximum register attempts reached"),n(this,pd,0,"f"),yield this.getUserAgent().transport.disconnect().catch(e=>console.error(e)),s(this,wh,"m",Nu).call(this)):(n(this,pd,(t=s(this,pd,"f"),++t),"f"),console.log(`sip reconnect success and register retry ${s(this,pd,"f")} of ${s(this,fd,"f")}`),s(this,qu,"f").call(this))})},requestOptions:{extraHeaders:s(this,Th,"f")}})}catch(e){console.log("sip reconnect then registerer register error",e),n(this,pd,0,"f"),n(this,wd,!1,"f")}}),1e3*s(this,gd,"f")),"f")}}),"object"!=typeof o)throw new Error("userAgentOption must be plain object");s(this,wh,"m",nu).call(this,o),s(this,wh,"m",ou).call(this,o),s(this,wh,"m",su).call(this,o),s(this,wh,"m",au).call(this,o),s(this,wh,"m",fu).call(this,o),s(this,wh,"m",ru).call(this,o),s(this,wh,"m",iu).call(this,o),n(this,Oh,s(this,wh,"m",vu).call(this,o),"f")}detectNavigatorPermissions(){-1===navigator.userAgent.indexOf("Firefox")?navigator.permissions.query({name:"microphone"}).then(e=>{"granted"===e.state?this.authorizedMicrophonePermissions=!0:this.authorizedMicrophonePermissions=!1}).catch(e=>{console.log("Got error :",e),this.authorizedMicrophonePermissions=!1}):navigator.mediaDevices.enumerateDevices().then(e=>{""!==e.filter(({kind:e})=>"audioinput"===e)[0].label?this.authorizedMicrophonePermissions=!0:this.authorizedMicrophonePermissions=!1}),navigator.permissions.query({name:"notifications"}).then(e=>{"granted"===e.state?this.authorizedNotificationPermissions=!0:this.authorizedNotificationPermissions=!1}).catch(e=>{console.log("Got error :",e),this.authorizedNotificationPermissions=!1})}getGateway(){return"1"===s(this,Hd,"f")?"https://gateway.teleai.com":"https://gateway.94ai.com"}getGatewayToken(){return r(this,void 0,void 0,function*(){if(yield s(this,Zh,"f").call(this,s(this,Fh,"f")),s(this,xh,"f"))return s(this,xh,"f");if(!this.token){yield s(this,lu,"f").call(this);const{token:e}=yield this.getGatewayAccessToken({corpId:s(this,Ed,"f"),sid:s(this,$d,"f"),secret:s(this,Id,"f"),seatOnline:!1});this.token=e,n(this,qh,Date.now(),"f")}return this.token})}getGatewayAccessToken(e){return this.requestGateway({url:"/authority/accessToken/openApi",data:e},!1)}getCallNumberDetail(e){return this.requestGateway({url:"/task-aggre/callCenterNumber/get",data:e})}getCallNumberChats(e){return this.requestGateway({url:"/dialogue-aggre/call-center-number/chat/list",data:e})}getCallInfo(){return r(this,void 0,void 0,function*(){const e=Object.assign({},s(this,Wd,"f")),t=()=>r(this,void 0,void 0,function*(){if(e.numberId&&e.taskId){let t={};try{if(t=yield this.getCallNumberDetail({id:e.numberId,taskId:e.taskId}),200!==t.code)return console.error(t.message),e.stop=!0,void s(this,id,"f").call(this,t.message)}catch(i){const r=`当前会话callid:${e.callId},根据numberId:${e.numberId},taskId:${e.taskId}:查询坐席接听状态异常`;return console.error(r),e.stop=!0,void s(this,id,"f").call(this,t.message)}const{callType:i,newIntentTag:r,intentTag:n,number:o,numberMd5:a,sid:c,config:l,tag:h,state:d}=t.data;if(10===d)return console.log(`当前会话callid:${e.callId}已结束`),void(e.stop=!0);if(e.callType||(e.callType=i),e.intentTag=r||n,e.number||(e.number=o),e.numberMD5||(e.numberMD5=a),e.agentId||(e.agentId=c),e.tag||(e.tag=h),!e.templateId&&l&&"string"==typeof l){const t=JSON.parse(l);t&&t.templateId&&(e.templateId=t.templateId)}if(e.callId){let t={};try{if(t=yield this.getCallNumberChats({callId:e.callId,taskId:e.taskId}),200!==t.code)return console.error(t.message),e.stop=!0,void s(this,id,"f").call(this,t.message)}catch(t){const i=`当前会话根据callId:${e.callId},taskId:${e.taskId}:查询会话对话记录异常`;return console.error(i),e.stop=!0,void s(this,id,"f").call(this,i)}e.chats=t.data.map(e=>(e.matchinfo&&(e.matchinfo=JSON.parse(e.matchinfo)),e)),s(this,Uh,"f")[e.callId]=e}try{s(this,Kh,"f").call(this,s(this,Uh,"f")[e.callId])}catch(e){console.log(e)}}else{if(e.stop=!0,!e.taskId){const t=`当前会话callid:${e.callId}的taskId不存在,无法查询通话记录`;console.error(t),s(this,id,"f").call(this,t)}if(!e.numberId){const t=`当前会话callid:${e.callId}的numberId不存在,无法查询通话记录`;console.error(t),s(this,id,"f").call(this,t)}}});try{for(;!e.stop&&(yield t(),!e.stop);)yield new Promise(e=>{let t=setTimeout(()=>r(this,void 0,void 0,function*(){clearTimeout(t),t=void 0,e(!0)}),3e3)})}catch(e){s(this,id,"f").call(this,e)}})}refreshCallChatInfo(){return r(this,void 0,void 0,function*(){let e=s(this,Gd,"f");"string"==typeof e?e=e===s(this,Wd,"f").voiceType:Array.isArray(e)&&(e=!!e.find(e=>e===s(this,Wd,"f").voiceType)),s(this,Wd,"f").numberId&&s(this,Wd,"f").callId&&s(this,Wd,"f").taskId&&e&&(yield this.getCallInfo())})}getOpenApi(){return function(e){if(!e)return!1;const t=/^[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,}$/;return!!/^(\d{1,3}\.){3}\d{1,3}$/.test(e)||("//"===e.slice(0,2)?t.test(e.slice(2,e.length)):"http://"===e.slice(0,7)?t.test(e.slice(7,e.length)):"https://"===e.slice(0,8)?t.test(e.slice(8,e.length)):t.test(e))}(s(this,jd,"f"))?s(this,jd,"f"):"1"===s(this,Hd,"f")?"1"===s(this,_d,"f")?"https://seat.teleai.com/teleaiopenapi":"https://seat.teleai.com/openapi":"1"===s(this,_d,"f")?"https://seat.94ai.com/teleaiopenapi":"https://seat.94ai.com/openapi"}getAgentInfo(e={}){const t=e||{},{agentTag:i,agentId:r}=t,n=function(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(i[r[s]]=e[r[s]])}return i}(t,["agentTag","agentId"]);return this.requestOpenApi({url:"/v1/agent/getAgent",data:Object.assign({agentTag:i||s(this,Cd,"f"),agentId:r||s(this,$d,"f")},n)})}updateOpenApiAgentStatus(e){return this.requestOpenApi({url:"/v1/agent/updateAgentStatus",data:{agentTag:s(this,Cd,"f"),agentId:s(this,$d,"f"),agentStatus:e}})}importOpenApiAgentCustomer(e){return this.requestOpenApi({url:"/v1/task/importAgentCustomer",data:{agentTag:s(this,Cd,"f"),agentId:s(this,$d,"f"),callType:1001,customers:[{number:e}]}})}callNumber(e){return this.importOpenApiAgentCustomer(e)}toggleNap(e){return e?this.updateOpenApiAgentStatus(3):this.updateOpenApiAgentStatus(1)}refreshSign(e){n(this,Hh,e,"f")}refreshTimestamp(e){n(this,Mh,e,"f")}prepareUserAgent(e,t){var i;return r(this,void 0,void 0,function*(){const{refresh:r,registererOptions:n,registererRegisterOptions:o,extraHeaders:a,authorizationUsername:c,authorizationPassword:l,uri:h,contactName:d,transportOptions:u}=e||{};yield this.dispose(),s(this,Oh,"f").uri=null!=h?h:s(this,Oh,"f").uri,s(this,Oh,"f").authorizationUsername=null!=c?c:s(this,Oh,"f").authorizationUsername,s(this,Oh,"f").authorizationPassword=null!=l?l:s(this,Oh,"f").authorizationPassword,s(this,Oh,"f").contactName=null!==(i=null!=d?d:c)&&void 0!==i?i:s(this,Oh,"f").contactName,u&&(s(this,Oh,"f").transportOptions=Object.assign(Object.assign({},s(this,Oh,"f").transportOptions),u));try{s(this,wh,"m",ou).call(this,e),yield s(this,lu,"f").call(this),yield s(this,hu,"f").call(this),s(this,wh,"m",gu).call(this,{refresh:r}),yield s(this,wh,"m",Lu).call(this),t&&s(this,wh,"m",Uu).call(this,t);return yield s(this,wh,"m",Bu).call(this,{registererOptions:n,registererRegisterOptions:o,extraHeaders:a},s(this,Ud,"f"))}catch(e){throw yield this.dispose(),e}})}dispose(){return r(this,void 0,void 0,function*(){try{s(this,wh,"m",du).call(this),yield s(this,wh,"m",bu).call(this)}catch(e){s(this,wh,"m",wu).call(this),console.log("sip dispose with error",e)}})}ignoreInvite(e={}){return r(this,void 0,void 0,function*(){s(this,jh,"f").incomingStatus=!1,yield this.getCurrentInvitation().reject(e)})}acceptInvite(e={}){return r(this,void 0,void 0,function*(){try{yield new Promise((t,i)=>{(()=>{r(this,void 0,void 0,function*(){try{const r=null==e?void 0:e.onAck,s=null==e?void 0:e.onAckTimeout;null==e||delete e.onAck,null==e||delete e.onAckTimeout,yield this.getCurrentInvitation().accept(Object.assign({sessionDescriptionHandlerOptions:{constraints:{audio:!0,video:!1}},onAck(e){t(e),null==r||r()},onAckTimeout(){null==s||s(),i("接听响应超时")}},e||{}))}catch(e){i(e)}})})()}),s(this,jh,"f").incomingStatus&&(s(this,jh,"f").incomingStatus=!1,s(this,jh,"f").answerStatus=!0)}catch(e){throw s(this,jh,"f").incomingStatus=!1,e}})}hangUpInvite(t){return r(this,void 0,void 0,function*(){const{rejectOptions:i,byeOptions:n,extraHeaders:o,scoutResponse:a}=t||{};return new Promise((t,c)=>r(this,void 0,void 0,function*(){var r,l,h,d,u;try{const g=n||{},f=null===(r=g.requestDelegate)||void 0===r?void 0:r.onAccept,p=null===(l=g.requestDelegate)||void 0===l?void 0:l.onReject;null===(h=g.requestDelegate)||void 0===h||delete h.onAccept,null===(d=g.requestDelegate)||void 0===d||delete d.onReject;const v=s(this,wh,"m",pu).call(this,{onAccept(e){console.log("sip bye success"),t(e),null==f||f(e)},onReject(e){null==p||p(e),c("sip bye fail with code "+e.message.statusCode)}},g.requestDelegate);switch(delete g.requestDelegate,null===(u=s(this,kh,"f"))||void 0===u?void 0:u.state){case e.SessionState.Initial:case e.SessionState.Establishing:yield s(this,kh,"f").reject(Object.assign({extraHeaders:o},i||{})),t(!0);break;case e.SessionState.Established:yield s(this,kh,"f").bye(Object.assign({requestDelegate:v,requestOptions:{extraHeaders:o}},g)),a||t(!0);break;case e.SessionState.Terminating:case e.SessionState.Terminated:t(!0)}}catch(e){c(e)}finally{s(this,jh,"f").incomingStatus=!1,s(this,jh,"f").answerStatus=!1}}))})}sendStarDtmf(e={}){return r(this,void 0,void 0,function*(){return new Promise((t,i)=>r(this,void 0,void 0,function*(){try{const r=e||{},{extraHeaders:n,requestDelegate:o}=r,a=s(this,wh,"m",pu).call(this,{onAccept(e){console.log("sip send dtmf Signal=* success"),t(e)},onReject(e){i("sip send dtmf Signal=* fail with code "+e.message.statusCode)}},o);delete r.requestDelegate,yield this.getCurrentInvitation().info(Object.assign({requestOptions:{body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:"Signal=*\r\nDuration=100"},extraHeaders:n},requestDelegate:a},r)),s(this,Kd,"f").call(this)}catch(e){i(e)}}))})}muteRemoteAudio(){s(this,Ch,"f").getReceivers().forEach(e=>{e.track.enabled=!1})}unMuteRemoteAudio(){s(this,Ch,"f").getReceivers().forEach(e=>{e.track.enabled=!0})}muteLocalAudio(){s(this,Ch,"f").getSenders().forEach(e=>{e.track.enabled=!1})}unMuteLocalAudio(){s(this,Ch,"f").getSenders().forEach(e=>{e.track.enabled=!0})}getUserAgentStatue(){return s(this,jh,"f")}getUserAgent(){return s(this,Rh,"f")||n(this,Rh,new ot(s(this,Oh,"f")),"f"),s(this,Rh,"f")}getSessionDescriptionHandler(){return s(this,Ih,"f")}getPeerConnection(){return s(this,Ch,"f")}getSenders(){return s(this,Ah,"f")}getReceivers(){return s(this,Ph,"f")}getStream(){return s(this,$h,"f")||n(this,$h,new MediaStream,"f"),s(this,Ph,"f").forEach(e=>{e.track&&s(this,$h,"f").addTrack(e.track)}),s(this,$h,"f")}getCurrentInviter(){if(!s(this,Dh,"f"))throw new Error("No currentInviter...");return s(this,Dh,"f")}getCurrentInvitation(){return s(this,kh,"f")}clearIceAutoDetection(){var e;null===(e=s(this,Sh,"f"))||void 0===e||e.destroy(),n(this,Sh,void 0,"f")}iceAutoDetectRecovery(e){var t;null===(t=s(this,Sh,"f"))||void 0===t||t.destroy(),n(this,Sh,new zu(e,this,{debugIceCredentials:!0,onRecoveryStart:(e,t)=>{console.log("开始 ICE 恢复",e,t)},onRecovered:()=>{console.log("媒体连接已恢复")},isSignalingAvailable:()=>s(this,Rh,"f").isConnected(),isRegistrationAvailable:()=>s(this,Eh,"f").state===ne.Registered,onRecoveryFailed:(e,t)=>{console.error("ICE 恢复失败",e,t)}}),"f"),s(this,Sh,"f").start()}invite(e,t={}){return r(this,void 0,void 0,function*(){const i=ot.makeURI(e.uri?e.uri:`sip:${e.extension}@${s(this,Oh,"f").transportOptions.server.split("://")[1]}`);if(!i)throw new Error("Failed to create target URI.");n(this,Dh,new ie(this.getUserAgent(),i,{sessionDescriptionHandlerOptions:{constraints:{audio:!0,video:!1}}}),"f");const{extraHeaders:r}=t||{};return yield this.getCurrentInviter().invite(Object.assign({requestOptions:{extraHeaders:r}},t)),s(this,Dh,"f")})}}Sh=new WeakMap,Th=new WeakMap,Rh=new WeakMap,Eh=new WeakMap,Ih=new WeakMap,Ch=new WeakMap,Ph=new WeakMap,Ah=new WeakMap,Oh=new WeakMap,kh=new WeakMap,Dh=new WeakMap,$h=new WeakMap,jh=new WeakMap,_h=new WeakMap,Hh=new WeakMap,Mh=new WeakMap,xh=new WeakMap,qh=new WeakMap,Nh=new WeakMap,Fh=new WeakMap,Uh=new WeakMap,Lh=new WeakMap,Bh=new WeakMap,Wh=new WeakMap,Gh=new WeakMap,Vh=new WeakMap,Kh=new WeakMap,zh=new WeakMap,Yh=new WeakMap,Jh=new WeakMap,Zh=new WeakMap,Xh=new WeakMap,Qh=new WeakMap,ed=new WeakMap,td=new WeakMap,id=new WeakMap,rd=new WeakMap,sd=new WeakMap,nd=new WeakMap,od=new WeakMap,ad=new WeakMap,cd=new WeakMap,ld=new WeakMap,hd=new WeakMap,dd=new WeakMap,ud=new WeakMap,gd=new WeakMap,fd=new WeakMap,pd=new WeakMap,vd=new WeakMap,md=new WeakMap,bd=new WeakMap,yd=new WeakMap,wd=new WeakMap,Sd=new WeakMap,Td=new WeakMap,Rd=new WeakMap,Ed=new WeakMap,Id=new WeakMap,Cd=new WeakMap,Pd=new WeakMap,Ad=new WeakMap,Od=new WeakMap,kd=new WeakMap,Dd=new WeakMap,$d=new WeakMap,jd=new WeakMap,_d=new WeakMap,Hd=new WeakMap,Md=new WeakMap,xd=new WeakMap,qd=new WeakMap,Nd=new WeakMap,Fd=new WeakMap,Ud=new WeakMap,Ld=new WeakMap,Bd=new WeakMap,Wd=new WeakMap,Gd=new WeakMap,Vd=new WeakMap,Kd=new WeakMap,zd=new WeakMap,Yd=new WeakMap,Jd=new WeakMap,Zd=new WeakMap,Xd=new WeakMap,Qd=new WeakMap,eu=new WeakMap,tu=new WeakMap,lu=new WeakMap,hu=new WeakMap,uu=new WeakMap,Cu=new WeakMap,Au=new WeakMap,Ou=new WeakMap,ku=new WeakMap,Du=new WeakMap,$u=new WeakMap,qu=new WeakMap,wh=new WeakSet,iu=function(e={}){var t,i;n(this,zh,null!==(t=e.openXhrIntercept)&&void 0!==t?t:s(this,zh,"f"),"f"),n(this,Yh,null!==(i=e.gatewayXhrIntercept)&&void 0!==i?i:s(this,Yh,"f"),"f")},ru=function(e={}){var t,i,o,a,c,l;n(this,Gd,null!==(t=e.enableChatInfoPush)&&void 0!==t?t:s(this,Gd,"f"),"f"),n(this,Vd,null!==(i=e.enableVolumnTrack)&&void 0!==i?i:s(this,Vd,"f"),"f"),n(this,Vh,null!==(o=e.refreshSpeekVolumn)&&void 0!==o?o:s(this,Vh,"f"),"f"),n(this,rd,null!==(a=e.refreshRequirementCheck)&&void 0!==a?a:s(this,rd,"f"),"f"),n(this,Kh,null!==(c=e.refreshChat)&&void 0!==c?c:s(this,Kh,"f"),"f"),n(this,id,null!==(l=e.refreshChatErrorCallback)&&void 0!==l?l:s(this,id,"f"),"f");const h=e.errorCallback;e.errorCallback=e=>r(this,void 0,void 0,function*(){try{yield s(this,Qh,"f").call(this,e)}catch(e){}finally{null==h||h(e)}})},su=function(e={}){var t,i,r,o,a;n(this,xh,null!==(t=e.token)&&void 0!==t?t:s(this,xh,"f"),"f"),n(this,qh,null!==(i=e.tokenTimestamp)&&void 0!==i?i:s(this,qh,"f"),"f"),n(this,Fh,null!==(r=e.tokenExpirationTime)&&void 0!==r?r:s(this,Fh,"f"),"f"),s(this,xh,"f")&&!s(this,qh,"f")&&n(this,qh,Date.now(),"f"),n(this,Zh,null!==(o=e.tokenCheck)&&void 0!==o?o:s(this,Zh,"f"),"f"),n(this,td,null!==(a=e.tokenOverdued)&&void 0!==a?a:s(this,td,"f"),"f")},nu=function(e={}){var t,i,r;n(this,Ud,null!==(t=e.clusterMode)&&void 0!==t?t:s(this,Ud,"f"),"f"),n(this,Ld,null!==(i=e.reClusterRegisterTimeout)&&void 0!==i?i:s(this,Ld,"f"),"f"),n(this,Bd,null!==(r=e.reClusterConnectTimeout)&&void 0!==r?r:s(this,Bd,"f"),"f")},ou=function(e={}){var t,i,r;const{agentId:o,agentTag:a,appKey:c,appSecret:l,openBaseUrl:h,sg:d,sgOpen:u,sign:g,armsReport:f,timestamp:p}=e;n(this,$d,null!=o?o:s(this,$d,"f"),"f"),n(this,Cd,null!=a?a:s(this,Cd,"f"),"f"),n(this,Ed,null!=c?c:s(this,Ed,"f"),"f"),n(this,Id,null!=l?l:s(this,Id,"f"),"f"),n(this,jd,null!=h?h:s(this,jd,"f"),"f"),n(this,Lh,null!=f?f:s(this,Lh,"f"),"f"),n(this,Hd,null!=d?d:s(this,Hd,"f"),"f"),n(this,_d,null!=u?u:s(this,_d,"f"),"f"),n(this,Hh,null!=g?g:s(this,Hh,"f"),"f"),n(this,Mh,null!=p?p:s(this,Mh,"f"),"f"),n(this,Nh,null!==(t=e.signExpirationTime)&&void 0!==t?t:s(this,Nh,"f"),"f"),n(this,Jh,null!==(i=e.signCheck)&&void 0!==i?i:s(this,Jh,"f"),"f"),n(this,Xh,null!==(r=e.signOverdued)&&void 0!==r?r:s(this,Xh,"f"),"f")},au=function(e){e.sipHeaders&&(n(this,Th,e.sipHeaders,"f"),delete e.sipHeaders)},cu=function(){return!(!s(this,$d,"f")&&!s(this,Cd,"f")||!(s(this,Ed,"f")&&s(this,Id,"f")||s(this,Hh,"f")&&s(this,Mh,"f")))},du=function(){s(this,wh,"m",yu).call(this),s(this,wh,"m",Ru).call(this),s(this,wh,"m",Eu).call(this),s(this,wh,"m",Tu).call(this),s(this,wh,"m",Su).call(this),s(this,wh,"m",ju).call(this),s(this,wh,"m",_u).call(this),s(this,wh,"m",wu).call(this),s(this,zd,"f").call(this),this.clearIceAutoDetection(),n(this,Wd,{},"f"),n(this,Uh,{},"f")},gu=function(e){n(this,jh,Lt(JSON.parse(JSON.stringify(Xt)),"function"==typeof e.refresh?e.refresh:s(this,qd,"f")),"f")},fu=function(e){var t,i,r,o,a,c,l,h,d,u,g,f,p,v,m;n(this,od,null!==(r=null!==(t=e.reconnectionAttempts)&&void 0!==t?t:null===(i=null==e?void 0:e.transportOptions)||void 0===i?void 0:i.maxReconnectionAttempts)&&void 0!==r?r:s(this,od,"f"),"f"),n(this,ad,null!==(l=null!==(a=null!==(o=e.reconnectionInterval)&&void 0!==o?o:e.reconnectionDelay)&&void 0!==a?a:null===(c=null==e?void 0:e.transportOptions)||void 0===c?void 0:c.reconnectionTimeout)&&void 0!==l?l:s(this,ad,"f"),"f"),n(this,vd,null!==(d=null===(h=e.transportOptions)||void 0===h?void 0:h.keepAliveInterval)&&void 0!==d?d:s(this,vd,"f"),"f"),n(this,md,null!==(g=null===(u=e.transportOptions)||void 0===u?void 0:u.keepAliveDebounce)&&void 0!==g?g:s(this,md,"f"),"f"),n(this,gd,null!==(f=e.registerInterval)&&void 0!==f?f:s(this,gd,"f"),"f"),n(this,cd,null!==(p=e.optionsPingInterval)&&void 0!==p?p:s(this,cd,"f"),"f"),n(this,ld,null!==(v=e.optionsPingAttempts)&&void 0!==v?v:s(this,ld,"f"),"f"),n(this,fd,null!==(m=e.registerAttempts)&&void 0!==m?m:s(this,fd,"f"),"f")},pu=function(e,t){return t?(Object.keys(t).forEach(i=>{if(t[i]&&"function"==typeof t[i])if(e[i]){if("function"==typeof e[i]){const s=e[i];e[i]=e=>r(this,void 0,void 0,function*(){yield t[i](e),yield s(e)})}}else e[i]=t[i]}),e):e},vu=function(e){const t={delegate:{onConnect:()=>r(this,void 0,void 0,function*(){console.log("sip connected"),s(this,ku,"f").call(this)}),onInvite:e=>{s(this,uu,"f").call(this,e.incomingInviteRequest.message.headers),this.refreshCallChatInfo(),s(this,wh,"m",mu).call(this),n(this,kh,e,"f"),s(this,jh,"f").incomingStatus=!0,this.iceAutoDetectRecovery(e),e.stateChange.addListener(s(this,Cu,"f"))},onDisconnect:e=>r(this,void 0,void 0,function*(){console.log("sip disconnected");let t=!1;s(this,cd,"f")>0&&(t=s(this,dd,"f"),s(this,$u,"f").call(this));try{yield s(this,wh,"m",Pu).call(this)}catch(e){}(e||t)&&s(this,wh,"m",Nu).call(this)})}};return e.delegate?Object.keys(e.delegate).forEach(i=>{const s=i;if(e.delegate[s]&&"function"==typeof e.delegate[s]){const i=e.delegate[s];e.delegate[s]=e=>r(this,void 0,void 0,function*(){var r,n;null===(n=(r=t.delegate)[s])||void 0===n||n.call(r,e),yield i(e)})}}):e.delegate=t.delegate,e.reconnectionAttempts=0,e.transportOptions=Object.assign(Object.assign({},e.transportOptions||{}),{keepAliveInterval:s(this,vd,"f"),keepAliveDebounce:s(this,md,"f")}),void 0===e.sessionDescriptionHandlerFactoryOptions&&(e.sessionDescriptionHandlerFactoryOptions={iceGatheringTimeout:2e3,peerConnectionConfiguration:{iceServers:[]}}),Object.assign(Object.assign({},Zt),e)},mu=function(){s(this,kh,"f")&&(s(this,kh,"f").dispose(),n(this,kh,void 0,"f"))},bu=function(){return r(this,void 0,void 0,function*(){s(this,Rh,"f")&&(yield s(this,Rh,"f").stop(),n(this,Rh,void 0,"f"))})},yu=function(){s(this,$h,"f")&&(s(this,$h,"f").getTracks().forEach(e=>{e.stop()}),n(this,$h,void 0,"f"))},wu=function(){Object.keys(Xt).forEach(e=>{const t=e;s(this,jh,"f")[t]=Xt[t]})},Su=function(){s(this,Ih,"f")&&(s(this,Ih,"f").close(),n(this,Ih,void 0,"f"))},Tu=function(){s(this,Ch,"f")&&(s(this,Ch,"f").close(),n(this,Ch,void 0,"f"))},Ru=function(){n(this,Ah,[],"f")},Eu=function(){n(this,Ph,[],"f")},Iu=function(){const e=this.getCurrentInvitation(),{sessionDescriptionHandler:t}=e;s(this,wh,"m",Tu).call(this),s(this,wh,"m",Su).call(this),s(this,wh,"m",Ru).call(this),s(this,wh,"m",Eu).call(this),n(this,Ih,t,"f");n(this,Ch,t.peerConnection,"f"),n(this,Ah,s(this,Ch,"f").getSenders(),"f"),n(this,Ph,s(this,Ch,"f").getReceivers(),"f"),(this.getFastOutboundCall()||!this.getSitOutboundCall()&&this.notNeedSendStarDtmf())&&s(this,Kd,"f").call(this)},Pu=function(e={}){return r(this,void 0,void 0,function*(){if(s(this,Eh,"f"))return console.log("sip due to disconnection, unregistered"),new Promise((t,i)=>r(this,void 0,void 0,function*(){try{const r=e||{},n=s(this,wh,"m",pu).call(this,{onAccept:e=>{console.log("sip unregister successed"),t(e)},onReject(e){i("sip unregister fail with code "+e.message.statusCode)}},r.requestDelegate);delete e.requestDelegate,yield s(this,Eh,"f").unregister(Object.assign({requestDelegate:n},e))}catch(e){i(e)}}))})},ju=function(){s(this,wh,"m",Hu).call(this),s(this,wh,"m",Mu).call(this),s(this,wh,"m",xu).call(this),n(this,wd,!1,"f"),n(this,bd,!1,"f"),n(this,yd,!1,"f")},_u=function(e=!0,t=!0){e&&(clearTimeout(s(this,Nd,"f")),n(this,Nd,void 0,"f")),t&&(clearTimeout(s(this,Fd,"f")),n(this,Fd,void 0,"f"))},Hu=function(){clearTimeout(s(this,Rd,"f")),n(this,Rd,void 0,"f")},Mu=function(){clearTimeout(s(this,Sd,"f")),n(this,Sd,void 0,"f")},xu=function(){clearTimeout(s(this,Td,"f")),n(this,Td,void 0,"f")},Nu=function e(t=1){return r(this,void 0,void 0,function*(){if(s(this,ad,"f")){if(s(this,jh,"f").reconnectStatus=!0,s(this,bd,"f"))return;if(t>s(this,od,"f"))return console.log("sip maximum reconnection attempts reached"),void(yield this.dispose());console.log("sip reconnection attempt..."),n(this,bd,!0,"f"),n(this,Sd,setTimeout(()=>{s(this,wh,"m",Mu).call(this),this.getUserAgent().reconnect().then(()=>r(this,void 0,void 0,function*(){console.log(`sip reconnection attempt ${t} of ${s(this,od,"f")} - succeeded`),n(this,bd,!1,"f"),s(this,qu,"f").call(this)})).catch(i=>{console.error(i),console.log(`sip reconnection attempt ${t} of ${s(this,od,"f")} - failed`),n(this,bd,!1,"f"),s(this,wh,"m",e).call(this,++t)})},1===t?0:1e3*s(this,ad,"f")),"f")}})},Fu=function(e){return Object.keys(e).forEach(t=>{const i=t;if("function"==typeof(null==e?void 0:e[i])){const t=e[i];e[i]=e=>r(this,void 0,void 0,function*(){var r,n;null===(n=(r=s(this,Oh,"f").delegate)[i])||void 0===n||n.call(r,e),yield t(e)})}}),e},Uu=function(e){const t=this.getUserAgent();return t.delegate=s(this,wh,"m",Fu).call(this,e),t},Lu=function(){return r(this,void 0,void 0,function*(){const e=this.getUserAgent();if(yield e.start(),e.isConnected()||(yield e.reconnect()),!e.isConnected())throw new Error("链接失败,请稍后再试");return s(this,jh,"f").connectStatus=!0,e})},Bu=function e(t,i=!1){const{registererOptions:o,registererRegisterOptions:a,extraHeaders:c}=t||{};return new Promise((t,l)=>r(this,void 0,void 0,function*(){const h=this.getUserAgent();let d;n(this,Eh,new ge(h,Object.assign({extraHeaders:c||s(this,Th,"f")},o||{})),"f");const u=a||{},g=s(this,wh,"m",pu).call(this,{onAccept:e=>{d=e,s(this,wh,"m",_u).call(this),s(this,jh,"f").registerStatus=!0,t(h)},onReject:e=>{s(this,wh,"m",_u).call(this),l("sip register fail with code "+e.message.statusCode)}},u.requestDelegate);delete u.requestDelegate,i&&n(this,Nd,setTimeout(()=>r(this,void 0,void 0,function*(){if(!d){n(this,Fd,setTimeout(()=>r(this,void 0,void 0,function*(){if(s(this,wh,"m",_u).call(this,!1,!0),!d)try{try{s(this,Eh,"f").dispose()}catch(e){}s(this,wh,"m",du).call(this),s(this,$u,"f").call(this),n(this,hd,0,"f"),n(this,pd,0,"f"),yield s(this,Rh,"f").transport.dispose(),n(this,Rh,new ot(s(this,Oh,"f")),"f"),yield s(this,wh,"m",Lu).call(this);const i=yield s(this,wh,"m",e).call(this,{registererOptions:o,registererRegisterOptions:a,extraHeaders:c});t(i)}catch(e){l(e)}}),s(this,Bd,"f")),"f");try{s(this,Eh,"f").dispose()}catch(e){}n(this,Eh,new ge(h,Object.assign({extraHeaders:c||s(this,Th,"f")},o||{})),"f"),s(this,wh,"m",_u).call(this,!0,!1);try{yield s(this,Eh,"f").register(Object.assign({requestDelegate:g,requestOptions:{extraHeaders:c||s(this,Th,"f")}},u))}catch(e){s(this,wh,"m",_u).call(this),l(e)}}}),s(this,Ld,"f")),"f");try{yield s(this,Eh,"f").register(Object.assign({requestDelegate:g,requestOptions:{extraHeaders:c||s(this,Th,"f")}},u))}catch(e){s(this,wh,"m",_u).call(this),l(e)}}))};class Zu{static getToken(e={}){return r(this,void 0,void 0,function*(){const{appKey:i,appSecret:s,agentId:n,agentTag:o,teleai:a}=e||{};let c=n;if(!c&&o&&s&&i){const e=yield new Promise((e,r)=>{try{const c=Date.now(),l=t.enc.Base64.stringify(t.HmacSHA1(i+c,s)),{xhr:h,ajaxData:d,contentType:u}=Yt(e,r,{url:(a?"https://seat.teleai.com/teleaiopenapi":"https://seat.94ai.com/openapi")+"/v1/agent/getAgent",data:{agentTag:o,agentId:n}});h.setRequestHeader("appKey",i),h.setRequestHeader("timestamp",String(c)),h.setRequestHeader("sign",l),h.setRequestHeader("Content-type",u||"application/json"),h.send(d)}catch(e){r(e.message)}});if(200!=e.code)throw new Error(e.message);c=e.data.agentId}return(yield new Promise((e,t)=>r(this,void 0,void 0,function*(){try{const{xhr:r,ajaxData:n,contentType:o}=Yt(e,t,{url:(a?"https://gateway.teleai.com":"https://gateway.94ai.com")+"/authority/accessToken/openApi",data:{corpId:i,secret:s,sid:c,seatOnline:!1}});r.setRequestHeader("x-app-code",3),r.setRequestHeader("content-type",o||"application/json"),r.send(n)}catch(e){t(e.message)}}))).token})}static getUserAgentManager(e={}){return s(this,Wu,"f",Gu)||n(this,Wu,new Ju(e),"f",Gu),s(this,Wu,"f",Gu)}static hasUserAgentManager(){return!!s(this,Wu,"f",Gu)}static newUserAgentManager(e={}){return new Ju(e)}static dispose(){if(s(this,Wu,"f",Gu))try{s(this,Wu,"f",Gu).dispose()}catch(e){}finally{n(this,Wu,void 0,"f",Gu)}}}Wu=Zu,Gu={value:void 0},e.AliArms=Ku,e.CallbackAggregator=Yu,e.Inviter=ie,e.Registerer=ge,e.SimpleUser=class{constructor(e,t={}){Object.defineProperty(this,"delegate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"session",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sessionManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.delegate=t.delegate,this.options=Object.assign({},t);const i={aor:this.options.aor,delegate:{onCallAnswered:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onCallAnswered)||void 0===t?void 0:t.call(e)},onCallCreated:e=>{var t,i;this.session=e,null===(i=null===(t=this.delegate)||void 0===t?void 0:t.onCallCreated)||void 0===i||i.call(t)},onCallReceived:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onCallReceived)||void 0===t?void 0:t.call(e)},onCallHangup:()=>{var e,t;this.session=void 0,(null===(e=this.delegate)||void 0===e?void 0:e.onCallHangup)&&(null===(t=this.delegate)||void 0===t||t.onCallHangup())},onCallHold:(e,t)=>{var i,r;return null===(r=null===(i=this.delegate)||void 0===i?void 0:i.onCallHold)||void 0===r?void 0:r.call(i,t)},onCallDTMFReceived:(e,t,i)=>{var r,s;return null===(s=null===(r=this.delegate)||void 0===r?void 0:r.onCallDTMFReceived)||void 0===s?void 0:s.call(r,t,i)},onMessageReceived:e=>{var t,i;return null===(i=null===(t=this.delegate)||void 0===t?void 0:t.onMessageReceived)||void 0===i?void 0:i.call(t,e.request.body)},onRegistered:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onRegistered)||void 0===t?void 0:t.call(e)},onUnregistered:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onUnregistered)||void 0===t?void 0:t.call(e)},onServerConnect:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onServerConnect)||void 0===t?void 0:t.call(e)},onServerDisconnect:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onServerDisconnect)||void 0===t?void 0:t.call(e)}},maxSimultaneousSessions:1,media:this.options.media,reconnectionAttempts:this.options.reconnectionAttempts,reconnectionDelay:this.options.reconnectionDelay,registererOptions:this.options.registererOptions,sendDTMFUsingSessionDescriptionHandler:this.options.sendDTMFUsingSessionDescriptionHandler,userAgentOptions:this.options.userAgentOptions};this.sessionManager=new at(e,i),this.logger=this.sessionManager.userAgent.getLogger("sip.SimpleUser")}get id(){return this.options.userAgentOptions&&this.options.userAgentOptions.displayName||"Anonymous"}get localMediaStream(){return this.session&&this.sessionManager.getLocalMediaStream(this.session)}get remoteMediaStream(){return this.session&&this.sessionManager.getRemoteMediaStream(this.session)}get localAudioTrack(){return this.session&&this.sessionManager.getLocalAudioTrack(this.session)}get localVideoTrack(){return this.session&&this.sessionManager.getLocalVideoTrack(this.session)}get remoteAudioTrack(){return this.session&&this.sessionManager.getRemoteAudioTrack(this.session)}get remoteVideoTrack(){return this.session&&this.sessionManager.getRemoteVideoTrack(this.session)}connect(){return this.logger.log(`[${this.id}] Connecting UserAgent...`),this.sessionManager.connect()}disconnect(){return this.logger.log(`[${this.id}] Disconnecting UserAgent...`),this.sessionManager.disconnect()}isConnected(){return this.sessionManager.isConnected()}register(e){return this.logger.log(`[${this.id}] Registering UserAgent...`),this.sessionManager.register(e)}unregister(e){return this.logger.log(`[${this.id}] Unregistering UserAgent...`),this.sessionManager.unregister(e)}call(e,t,i){return this.logger.log(`[${this.id}] Beginning Session...`),this.session?Promise.reject(new Error("Session already exists.")):this.sessionManager.call(e,t,i).then(()=>{})}hangup(){return this.logger.log(`[${this.id}] Hangup...`),this.session?this.sessionManager.hangup(this.session).then(()=>{this.session=void 0}):Promise.reject(new Error("Session does not exist."))}answer(e){return this.logger.log(`[${this.id}] Accepting Invitation...`),this.session?this.sessionManager.answer(this.session,e):Promise.reject(new Error("Session does not exist."))}decline(){return this.logger.log(`[${this.id}] rejecting Invitation...`),this.session?this.sessionManager.decline(this.session):Promise.reject(new Error("Session does not exist."))}hold(){return this.logger.log(`[${this.id}] holding session...`),this.session?this.sessionManager.hold(this.session):Promise.reject(new Error("Session does not exist."))}unhold(){return this.logger.log(`[${this.id}] unholding session...`),this.session?this.sessionManager.unhold(this.session):Promise.reject(new Error("Session does not exist."))}isHeld(){return!!this.session&&this.sessionManager.isHeld(this.session)}mute(){return this.logger.log(`[${this.id}] disabling media tracks...`),this.session&&this.sessionManager.mute(this.session)}unmute(){return this.logger.log(`[${this.id}] enabling media tracks...`),this.session&&this.sessionManager.unmute(this.session)}isMuted(){return!!this.session&&this.sessionManager.isMuted(this.session)}sendDTMF(e){return this.logger.log(`[${this.id}] sending DTMF...`),this.session?this.sessionManager.sendDTMF(this.session,e):Promise.reject(new Error("Session does not exist."))}message(e,t){return this.logger.log(`[${this.id}] sending message...`),this.sessionManager.message(e,t)}},e.URI=y,e.UserAgent=ot,e.UserAgentFactory=Zu,e.UserAgentManager=Ju,e.accumulateSec=zt,e.accumulationTimer=function(e){const t=Kt();e(Vt(t));let i=setInterval(()=>{const i=zt(t),r=Vt(i);e(r)},1e3);return()=>{clearInterval(i),i=null}},e.cleanupMedia=function(e){const t=Bt(e);t&&(t.srcObject=null,t.pause())},e.getBeijingTime=Jt,e.getDevicePermission=Gt,e.getMedia=Bt,e.getTimes=Vt,e.getZeorTime=Kt,e.onChange=Lt,e.pauseMedia=function(e){const t=Bt(e);t&&(t.currentTime=0,t.pause())},e.playMedia=function(e){const t=Bt(e);t&&(t.currentTime=0,t.play())},e.requestMicroPhonePermission=function(){try{if(-1===navigator.userAgent.indexOf("Firefox"))return Gt({video:!1,audio:!0}).catch(()=>!0)}catch(e){console.log(e)}},e.stopStreamTracks=Wt,e.userAgentDefault=Zt,e.userAgentStatus=Xt});