@voicenter-team/opensips-js 1.0.133 → 1.0.135
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/opensips-js.cjs.js +13 -13
- package/dist/opensips-js.es.js +107 -98
- package/dist/opensips-js.iife.js +3 -3
- package/dist/opensips-js.umd.js +3 -3
- package/package.json +1 -1
package/dist/opensips-js.cjs.js
CHANGED
@@ -61,15 +61,15 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
61
61
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,r=!1,d;return{s:function(){n=c[Symbol.iterator]()},n:function(){var _=n.next();return s=_.done,_},e:function(_){r=!0,d=_},f:function(){try{!s&&n.return!=null&&n.return()}finally{if(r)throw d}}}}function Wp(c,t){if(c){if(typeof c=="string")return Fc(c,t);var n=Object.prototype.toString.call(c).slice(8,-1);if(n==="Object"&&c.constructor&&(n=c.constructor.name),n==="Map"||n==="Set")return Array.from(c);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Fc(c,t)}}function Fc(c,t){(t==null||t>c.length)&&(t=c.length);for(var n=0,a=new Array(t);n<t;n++)a[n]=c[n];return a}var Kp=ht,Tu=os(),vu=Ss,Kl=new Kp("Parser");ih.parseMessage=function(c,t){var n,a,o=c.indexOf(`\r
|
62
62
|
`);if(o===-1){Kl.warn("parseMessage() | no CRLF found, not a SIP message");return}var s=c.substring(0,o),r=Tu.parse(s,"Request_Response");if(r===-1){Kl.warn('parseMessage() | error parsing first line of SIP message: "'.concat(s,'"'));return}else r.status_code?(n=new vu.IncomingResponse,n.status_code=r.status_code,n.reason_phrase=r.reason_phrase):(n=new vu.IncomingRequest(t),n.method=r.method,n.ruri=r.uri);n.data=c;for(var d=o+2;;){if(o=Yp(c,d),o===-2){a=d+2;break}else if(o===-1){Kl.warn("parseMessage() | malformed message");return}if(r=Jp(n,c,d,o),r!==!0){Kl.warn("parseMessage() |",r.error);return}d=o+2}if(n.hasHeader("content-length")){var h=n.getHeader("content-length");n.body=c.substr(a,h)}else n.body=c.substring(a);return n};function Yp(c,t){var n=t,a=0,o=0;if(c.substring(n,n+2).match(/(^\r\n)/))return-2;for(;a===0;){if(o=c.indexOf(`\r
|
63
63
|
`,n),o===-1)return o;!c.substring(o+2,o+4).match(/(^\r\n)/)&&c.charAt(o+2).match(/(^\s+)/)?n=o+2:a=o}return a}function Jp(c,t,n,a){var o,s=t.indexOf(":",n),r=t.substring(n,s).trim(),d=t.substring(s+1,a).trim();switch(r.toLowerCase()){case"via":case"v":c.addHeader("via",d),c.getHeaders("via").length===1?(o=c.parseHeader("Via"),o&&(c.via=o,c.via_branch=o.branch)):o=0;break;case"from":case"f":c.setHeader("from",d),o=c.parseHeader("from"),o&&(c.from=o,c.from_tag=o.getParam("tag"));break;case"to":case"t":c.setHeader("to",d),o=c.parseHeader("to"),o&&(c.to=o,c.to_tag=o.getParam("tag"));break;case"record-route":if(o=Tu.parse(d,"Record_Route"),o===-1)o=void 0;else{var h=Hc(o),_;try{for(h.s();!(_=h.n()).done;){var g=_.value;c.addHeader("record-route",d.substring(g.possition,g.offset)),c.headers["Record-Route"][c.getHeaders("record-route").length-1].parsed=g.parsed}}catch(A){h.e(A)}finally{h.f()}}break;case"call-id":case"i":c.setHeader("call-id",d),o=c.parseHeader("call-id"),o&&(c.call_id=d);break;case"contact":case"m":if(o=Tu.parse(d,"Contact"),o===-1)o=void 0;else{var T=Hc(o),E;try{for(T.s();!(E=T.n()).done;){var y=E.value;c.addHeader("contact",d.substring(y.possition,y.offset)),c.headers.Contact[c.getHeaders("contact").length-1].parsed=y.parsed}}catch(A){T.e(A)}finally{T.f()}}break;case"content-length":case"l":c.setHeader("content-length",d),o=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",d),o=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",d),o=c.parseHeader("cseq"),o&&(c.cseq=o.value),c instanceof vu.IncomingResponse&&(c.method=o.method);break;case"max-forwards":c.setHeader("max-forwards",d),o=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",d),o=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",d),o=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",d),o=c.parseHeader("session-expires"),o&&(c.session_expires=o.expires,c.session_expires_refresher=o.refresher);break;case"refer-to":case"r":c.setHeader("refer-to",d),o=c.parseHeader("refer-to"),o&&(c.refer_to=o);break;case"replaces":c.setHeader("replaces",d),o=c.parseHeader("replaces"),o&&(c.replaces=o);break;case"event":case"o":c.setHeader("event",d),o=c.parseHeader("event"),o&&(c.event=o);break;default:c.addHeader(r,d),o=0}return o===void 0?{error:'error parsing header "'.concat(r,'"')}:!0}function Ia(c,t){var n;if(typeof Symbol>"u"||c[Symbol.iterator]==null){if(Array.isArray(c)||(n=zp(c))||t&&c&&typeof c.length=="number"){n&&(c=n);var a=0,o=function(){};return{s:o,n:function(){return a>=c.length?{done:!0}:{done:!1,value:c[a++]}},e:function(_){throw _},f:o}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
|
64
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,r=!1,d;return{s:function(){n=c[Symbol.iterator]()},n:function(){var _=n.next();return s=_.done,_},e:function(_){r=!0,d=_},f:function(){try{!s&&n.return!=null&&n.return()}finally{if(r)throw d}}}}function zp(c,t){if(c){if(typeof c=="string")return jc(c,t);var n=Object.prototype.toString.call(c).slice(8,-1);if(n==="Object"&&c.constructor&&(n=c.constructor.name),n==="Map"||n==="Set")return Array.from(c);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return jc(c,t)}}function jc(c,t){(t==null||t>c.length)&&(t=c.length);for(var n=0,a=new Array(t);n<t;n++)a[n]=c[n];return a}var Xp=ht,lh=lt,qc=Ss,ku=bt(),Mu=new Xp("sanityCheck"),Qp=[om],Zp=[sm,nm,rm,im],em=[lm,am],
|
64
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,r=!1,d;return{s:function(){n=c[Symbol.iterator]()},n:function(){var _=n.next();return s=_.done,_},e:function(_){r=!0,d=_},f:function(){try{!s&&n.return!=null&&n.return()}finally{if(r)throw d}}}}function zp(c,t){if(c){if(typeof c=="string")return jc(c,t);var n=Object.prototype.toString.call(c).slice(8,-1);if(n==="Object"&&c.constructor&&(n=c.constructor.name),n==="Map"||n==="Set")return Array.from(c);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return jc(c,t)}}function jc(c,t){(t==null||t>c.length)&&(t=c.length);for(var n=0,a=new Array(t);n<t;n++)a[n]=c[n];return a}var Xp=ht,lh=lt,qc=Ss,ku=bt(),Mu=new Xp("sanityCheck"),Qp=[om],Zp=[sm,nm,rm,im],em=[lm,am],Fe,rs,ah,tm=function(c,t,n){Fe=c,rs=t,ah=n;var a=Ia(Qp),o;try{for(a.s();!(o=a.n()).done;){var s=o.value;if(s()===!1)return!1}}catch(E){a.e(E)}finally{a.f()}if(Fe instanceof qc.IncomingRequest){var r=Ia(Zp),d;try{for(r.s();!(d=r.n()).done;){var h=d.value;if(h()===!1)return!1}}catch(E){r.e(E)}finally{r.f()}}else if(Fe instanceof qc.IncomingResponse){var _=Ia(em),g;try{for(_.s();!(g=_.n()).done;){var T=g.value;if(T()===!1)return!1}}catch(E){_.e(E)}finally{_.f()}}return!0};function sm(){if(Fe.s("to").uri.scheme!=="sip")return tl(416),!1}function nm(){if(!Fe.to_tag&&Fe.call_id.substr(0,5)===rs.configuration.jssip_id)return tl(482),!1}function rm(){var c=ku.str_utf8_length(Fe.body),t=Fe.getHeader("content-length");if(c<t)return tl(400),!1}function im(){var c=Fe.from_tag,t=Fe.call_id,n=Fe.cseq,a;if(!Fe.to_tag)if(Fe.method===lh.INVITE){if(rs._transactions.ist[Fe.via_branch])return!1;for(var o in rs._transactions.ist)if(Object.prototype.hasOwnProperty.call(rs._transactions.ist,o)&&(a=rs._transactions.ist[o],a.request.from_tag===c&&a.request.call_id===t&&a.request.cseq===n))return tl(482),!1}else{if(rs._transactions.nist[Fe.via_branch])return!1;for(var s in rs._transactions.nist)if(Object.prototype.hasOwnProperty.call(rs._transactions.nist,s)&&(a=rs._transactions.nist[s],a.request.from_tag===c&&a.request.call_id===t&&a.request.cseq===n))return tl(482),!1}}function lm(){if(Fe.getHeaders("via").length>1)return Mu.debug("more than one Via header field present in the response, dropping the response"),!1}function am(){var c=ku.str_utf8_length(Fe.body),t=Fe.getHeader("content-length");if(c<t)return Mu.debug("message body length is lower than the value in Content-Length header field, dropping the response"),!1}function om(){for(var c=["from","to","call_id","cseq","via"],t=0,n=c;t<n.length;t++){var a=n[t];if(!Fe.hasHeader(a))return Mu.debug("missing mandatory header field : ".concat(a,", dropping the response")),!1}}function tl(c){var t=Fe.getHeaders("via"),n,a="SIP/2.0 ".concat(c," ").concat(lh.REASON_PHRASE[c],`\r
|
65
65
|
`),o=Ia(t),s;try{for(o.s();!(s=o.n()).done;){var r=s.value;a+="Via: ".concat(r,`\r
|
66
|
-
`)}}catch(d){o.e(d)}finally{o.f()}n=
|
67
|
-
`),a+="From: ".concat(
|
68
|
-
`),a+="Call-ID: ".concat(
|
69
|
-
`),a+="CSeq: ".concat(
|
66
|
+
`)}}catch(d){o.e(d)}finally{o.f()}n=Fe.getHeader("To"),Fe.to_tag||(n+=";tag=".concat(ku.newTag())),a+="To: ".concat(n,`\r
|
67
|
+
`),a+="From: ".concat(Fe.getHeader("From"),`\r
|
68
|
+
`),a+="Call-ID: ".concat(Fe.call_id,`\r
|
69
|
+
`),a+="CSeq: ".concat(Fe.cseq," ").concat(Fe.method,`\r
|
70
70
|
`),a+=`\r
|
71
71
|
`,ah.send(a)}var Lu={};function Vc(c,t){var n;if(typeof Symbol>"u"||c[Symbol.iterator]==null){if(Array.isArray(c)||(n=um(c))||t&&c&&typeof c.length=="number"){n&&(c=n);var a=0,o=function(){};return{s:o,n:function(){return a>=c.length?{done:!0}:{done:!1,value:c[a++]}},e:function(_){throw _},f:o}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
|
72
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,r=!1,d;return{s:function(){n=c[Symbol.iterator]()},n:function(){var _=n.next();return s=_.done,_},e:function(_){r=!0,d=_},f:function(){try{!s&&n.return!=null&&n.return()}finally{if(r)throw d}}}}function um(c,t){if(c){if(typeof c=="string")return Bc(c,t);var n=Object.prototype.toString.call(c).slice(8,-1);if(n==="Object"&&c.constructor&&(n=c.constructor.name),n==="Map"||n==="Set")return Array.from(c);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Bc(c,t)}}function Bc(c,t){(t==null||t>c.length)&&(t=c.length);for(var n=0,a=new Array(t);n<t;n++)a[n]=c[n];return a}var fr=bt(),yn=lt,wo=os(),Gc=Ks(),Oo=xu,Do=Ws;Lu.settings={authorization_user:null,password:null,realm:null,ha1:null,authorization_jwt:null,display_name:null,uri:null,contact_uri:null,instance_id:null,use_preloaded_route:!1,session_timers:!0,session_timers_refresh_method:yn.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:yn.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:yn.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:"".concat(fr.createRandomToken(12),".invalid")};var Yl={mandatory:{sockets:function(t){var n=[];if(Oo.isSocket(t))n.push({socket:t});else if(Array.isArray(t)&&t.length){var a=Vc(t),o;try{for(a.s();!(o=a.n()).done;){var s=o.value;Object.prototype.hasOwnProperty.call(s,"socket")&&Oo.isSocket(s.socket)?n.push(s):Oo.isSocket(s)&&n.push({socket:s})}}catch(r){a.e(r)}finally{a.f()}}else return;return n},uri:function(t){/^sip:/i.test(t)||(t="".concat(yn.SIP,":").concat(t));var n=Gc.parse(t);if(n)return n.user?n:void 0}},optional:{authorization_user:function(t){if(wo.parse('"'.concat(t,'"'),"quoted_string")!==-1)return t},authorization_jwt:function(t){if(typeof t=="string")return t},user_agent:function(t){if(typeof t=="string")return t},connection_recovery_max_interval:function(t){if(fr.isDecimal(t)){var n=Number(t);if(n>0)return n}},connection_recovery_min_interval:function(t){if(fr.isDecimal(t)){var n=Number(t);if(n>0)return n}},contact_uri:function(t){if(typeof t=="string"){var n=wo.parse(t,"SIP_URI");if(n!==-1)return n}},display_name:function(t){return t},instance_id:function(t){if(/^uuid:/i.test(t)&&(t=t.substr(5)),wo.parse(t,"uuid")!==-1)return t},no_answer_timeout:function(t){if(fr.isDecimal(t)){var n=Number(t);if(n>0)return n}},session_timers:function(t){if(typeof t=="boolean")return t},session_timers_refresh_method:function(t){if(typeof t=="string"&&(t=t.toUpperCase(),t===yn.INVITE||t===yn.UPDATE))return t},session_timers_force_refresher:function(t){if(typeof t=="boolean")return t},password:function(t){return String(t)},realm:function(t){return String(t)},ha1:function(t){return String(t)},register:function(t){if(typeof t=="boolean")return t},register_expires:function(t){if(fr.isDecimal(t)){var n=Number(t);if(n>0)return n}},registrar_server:function(t){/^sip:/i.test(t)||(t="".concat(yn.SIP,":").concat(t));var n=Gc.parse(t);if(n)return n.user?void 0:n},use_preloaded_route:function(t){if(typeof t=="boolean")return t},extra_headers:function(t){var n=[];if(Array.isArray(t)&&t.length){var a=Vc(t),o;try{for(a.s();!(o=a.n()).done;){var s=o.value;typeof s=="string"&&n.push(s)}}catch(r){a.e(r)}finally{a.f()}}else return;return n}}};Lu.load=function(c,t){for(var n in Yl.mandatory)if(t.hasOwnProperty(n)){var a=t[n],o=Yl.mandatory[n](a);if(o!==void 0)c[n]=o;else throw new Do.ConfigurationError(n,a)}else throw new Do.ConfigurationError(n);for(var s in Yl.optional)if(t.hasOwnProperty(s)){var r=t[s];if(fr.isEmpty(r))continue;var d=Yl.optional[s](r);if(d!==void 0)c[s]=d;else throw new Do.ConfigurationError(s,r)}};function ba(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?ba=function(n){return typeof n}:ba=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},ba(c)}function cm(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Wc(c,t){for(var n=0;n<t.length;n++){var a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(c,a.key,a)}}function Kc(c,t,n){return t&&Wc(c.prototype,t),n&&Wc(c,n),c}function fm(c,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(t&&t.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),t&&Eu(c,t)}function Eu(c,t){return Eu=Object.setPrototypeOf||function(a,o){return a.__proto__=o,a},Eu(c,t)}function hm(c){var t=_m();return function(){var a=La(c),o;if(t){var s=La(this).constructor;o=Reflect.construct(a,arguments,s)}else o=a.apply(this,arguments);return dm(this,o)}}function dm(c,t){return t&&(ba(t)==="object"||typeof t=="function")?t:oh(c)}function oh(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function _m(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function La(c){return La=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},La(c)}var pm=ft.EventEmitter,mm=ht,pt=lt,gm=r_,Yc=dp,Jc=Ip,zc=$p,No=hl,Tm=Gp,Jl=bt(),vm=Ws,Em=Ks(),Sm=ih,Uo=Ss,ym=tm,Po=Lu,je=new mm("UA"),Tt={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},Am=function(c){fm(n,c);var t=hm(n);Kc(n,null,[{key:"C",get:function(){return Tt}}]);function n(a){var o;if(cm(this,n),je.debug("new() [configuration:%o]",a),o=t.call(this),o._cache={credentials:{}},o._configuration=Object.assign({},Po.settings),o._dynConfiguration={},o._dialogs={},o._applicants={},o._sessions={},o._transport=null,o._contact=null,o._status=Tt.STATUS_INIT,o._error=null,o._transactions={nist:{},nict:{},ist:{},ict:{}},o._data={},o._closeTimer=null,a===void 0)throw new TypeError("Not enough arguments");try{o._loadConfig(a)}catch(s){throw o._status=Tt.STATUS_NOT_READY,o._error=Tt.CONFIGURATION_ERROR,s}return o._registrator=new gm(oh(o)),o}return Kc(n,[{key:"start",value:function(){je.debug("start()"),this._status===Tt.STATUS_INIT?this._transport.connect():this._status===Tt.STATUS_USER_CLOSED?(je.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=Tt.STATUS_INIT,this._transport.connect()):this._status===Tt.STATUS_READY?je.debug("UA is in READY status, not restarted"):je.debug("ERROR: connection is down, Auto-Recovery system is trying to reconnect"),this._dynConfiguration.register=this._configuration.register}},{key:"register",value:function(){je.debug("register()"),this._dynConfiguration.register=!0,this._registrator.register()}},{key:"unregister",value:function(o){je.debug("unregister()"),this._dynConfiguration.register=!1,this._registrator.unregister(o)}},{key:"registrator",value:function(){return this._registrator}},{key:"isRegistered",value:function(){return this._registrator.registered}},{key:"isConnected",value:function(){return this._transport.isConnected()}},{key:"call",value:function(o,s){je.debug("call()");var r=new Yc(this);return r.connect(o,s),r}},{key:"sendMessage",value:function(o,s,r){je.debug("sendMessage()");var d=new Jc(this);return d.send(o,s,r),d}},{key:"sendOptions",value:function(o,s,r){je.debug("sendOptions()");var d=new zc(this);return d.send(o,s,r),d}},{key:"terminateSessions",value:function(o){je.debug("terminateSessions()");for(var s in this._sessions)this._sessions[s].isEnded()||this._sessions[s].terminate(o)}},{key:"stop",value:function(){var o=this;if(je.debug("stop()"),this._dynConfiguration={},this._status===Tt.STATUS_USER_CLOSED){je.debug("UA already closed");return}this._registrator.close();var s=Object.keys(this._sessions).length;for(var r in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,r)){je.debug("closing session ".concat(r));try{this._sessions[r].terminate()}catch{}}for(var d in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,d))try{this._applicants[d].close()}catch{}this._status=Tt.STATUS_USER_CLOSED;var h=Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length;h===0&&s===0?this._transport.disconnect():this._closeTimer=setTimeout(function(){o._closeTimer=null,o._transport.disconnect()},2e3)}},{key:"normalizeTarget",value:function(o){return Jl.normalizeTarget(o,this._configuration.hostport_params)}},{key:"get",value:function(o){switch(o){case"authorization_user":return this._configuration.authorization_user;case"realm":return this._configuration.realm;case"ha1":return this._configuration.ha1;case"authorization_jwt":return this._configuration.authorization_jwt;default:je.warn('get() | cannot get "%s" parameter in runtime',o);return}}},{key:"set",value:function(o,s){switch(o){case"authorization_user":{this._configuration.authorization_user=String(s);break}case"password":{this._configuration.password=String(s);break}case"realm":{this._configuration.realm=String(s);break}case"ha1":{this._configuration.ha1=String(s),this._configuration.password=null;break}case"authorization_jwt":{this._configuration.authorization_jwt=String(s);break}case"display_name":{this._configuration.display_name=s;break}default:return je.warn('set() | cannot set "%s" parameter in runtime',o),!1}return!0}},{key:"newTransaction",value:function(o){this._transactions[o.type][o.id]=o,this.emit("newTransaction",{transaction:o})}},{key:"destroyTransaction",value:function(o){delete this._transactions[o.type][o.id],this.emit("transactionDestroyed",{transaction:o})}},{key:"newDialog",value:function(o){this._dialogs[o.id]=o}},{key:"destroyDialog",value:function(o){delete this._dialogs[o.id]}},{key:"newMessage",value:function(o,s){this._applicants[o]=o,this.emit("newMessage",s)}},{key:"newOptions",value:function(o,s){this._applicants[o]=o,this.emit("newOptions",s)}},{key:"destroyMessage",value:function(o){delete this._applicants[o]}},{key:"newRTCSession",value:function(o,s){this._sessions[o.id]=o,this.emit("newRTCSession",s)}},{key:"destroyRTCSession",value:function(o){delete this._sessions[o.id]}},{key:"registered",value:function(o){this.emit("registered",o)}},{key:"unregistered",value:function(o){this.emit("unregistered",o)}},{key:"registrationFailed",value:function(o){this.emit("registrationFailed",o)}},{key:"receiveRequest",value:function(o){var s=o.method;if(o.ruri.user!==this._configuration.uri.user&&o.ruri.user!==this._contact.uri.user){je.debug("Request-URI does not point to us"),o.method!==pt.ACK&&o.reply_sl(404);return}if(o.ruri.scheme===pt.SIPS){o.reply_sl(416);return}if(!No.checkTransaction(this,o)){if(s===pt.INVITE?new No.InviteServerTransaction(this,this._transport,o):s!==pt.ACK&&s!==pt.CANCEL&&new No.NonInviteServerTransaction(this,this._transport,o),s===pt.OPTIONS){if(this.listeners("newOptions").length===0){o.reply(200);return}var r=new zc(this);r.init_incoming(o)}else if(s===pt.MESSAGE){if(this.listeners("newMessage").length===0){o.reply(405);return}var d=new Jc(this);d.init_incoming(o)}else if(s===pt.INVITE&&!o.to_tag&&this.listeners("newRTCSession").length===0){o.reply(405);return}var h,_;if(o.to_tag)h=this._findDialog(o.call_id,o.from_tag,o.to_tag),h?h.receiveRequest(o):s===pt.NOTIFY?(_=this._findSession(o),_?_.receiveRequest(o):(je.debug("received NOTIFY request for a non existent subscription"),o.reply(481,"Subscription does not exist"))):s!==pt.ACK&&o.reply(481);else switch(s){case pt.INVITE:if(window.RTCPeerConnection)if(o.hasHeader("replaces")){var g=o.replaces;h=this._findDialog(g.call_id,g.from_tag,g.to_tag),h?(_=h.owner,_.isEnded()?o.reply(603):_.receiveRequest(o)):o.reply(481)}else _=new Yc(this),_.init_incoming(o);else je.warn("INVITE received but WebRTC is not supported"),o.reply(488);break;case pt.BYE:o.reply(481);break;case pt.CANCEL:_=this._findSession(o),_?_.receiveRequest(o):je.debug("received CANCEL request for a non existent session");break;case pt.ACK:break;case pt.NOTIFY:this.emit("sipEvent",{event:o.event,request:o}),o.reply(200);break;default:o.reply(405);break}}}},{key:"_findSession",value:function(o){var s=o.call_id,r=o.from_tag,d=o.to_tag,h=s+r,_=this._sessions[h],g=s+d,T=this._sessions[g];return _||T||null}},{key:"_findDialog",value:function(o,s,r){var d=o+s+r,h=this._dialogs[d];return h||(d=o+r+s,h=this._dialogs[d],h||null)}},{key:"_loadConfig",value:function(o){try{Po.load(this._configuration,o)}catch(g){throw g}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=Jl.newUUID()),this._configuration.jssip_id=Jl.createRandomToken(5);var s=this._configuration.uri.clone();s.user=null,this._configuration.hostport_params=s.toString().replace(/^sip:/i,"");try{this._transport=new Tm(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=Cm.bind(this),this._transport.onconnect=Rm.bind(this),this._transport.ondisconnect=Im.bind(this),this._transport.ondata=bm.bind(this)}catch(g){throw je.warn(g),new vm.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){var r=this._configuration.uri.clone();r.user=null,r.clearParams(),r.clearHeaders(),this._configuration.registrar_server=r}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new Em("sip",Jl.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString:function(){var T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},E=T.anonymous||null,y=T.outbound||null,A="<";return E?A+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":A+=this.pub_gruu||this.uri.toString(),y&&(E?!this.temp_gruu:!this.pub_gruu)&&(A+=";ob"),A+=">",A}};var d=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(var h in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,h)&&(d.indexOf(h)!==-1?Object.defineProperty(this._configuration,h,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,h,{writable:!1,configurable:!1}));je.debug("configuration parameters after validation:");for(var _ in this._configuration)if(Object.prototype.hasOwnProperty.call(Po.settings,_))switch(_){case"uri":case"registrar_server":je.debug("- ".concat(_,": ").concat(this._configuration[_]));break;case"password":case"ha1":case"authorization_jwt":je.debug("- ".concat(_,": NOT SHOWN"));break;default:je.debug("- ".concat(_,": ").concat(JSON.stringify(this._configuration[_])))}}},{key:"C",get:function(){return Tt}},{key:"status",get:function(){return this._status}},{key:"contact",get:function(){return this._contact}},{key:"configuration",get:function(){return this._configuration}},{key:"transport",get:function(){return this._transport}}]),n}(pm);function Cm(c){this.emit("connecting",c)}function Rm(c){this._status!==Tt.STATUS_USER_CLOSED&&(this._status=Tt.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function Im(c){for(var t=["nict","ict","nist","ist"],n=0,a=t;n<a.length;n++){var o=a[n];for(var s in this._transactions[o])Object.prototype.hasOwnProperty.call(this._transactions[o],s)&&this._transactions[o][s].onTransportError()}this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==Tt.STATUS_USER_CLOSED&&(this._status=Tt.STATUS_NOT_READY,this._error=Tt.NETWORK_ERROR)}function bm(c){var t=c.transport,n=c.message;if(n=Sm.parseMessage(n,this),!!n&&!(this._status===Tt.STATUS_USER_CLOSED&&n instanceof Uo.IncomingRequest)&&ym(n,this,t)){if(n instanceof Uo.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof Uo.IncomingResponse){var a;switch(n.method){case pt.INVITE:a=this._transactions.ict[n.via_branch],a&&a.receiveResponse(n);break;case pt.ACK:break;default:a=this._transactions.nict[n.via_branch],a&&a.receiveResponse(n);break}}}}function wm(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Xc(c,t){for(var n=0;n<t.length;n++){var a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(c,a.key,a)}}function Om(c,t,n){return t&&Xc(c.prototype,t),n&&Xc(c,n),c}var Dm=ht,Nm=os(),Ot=new Dm("WebSocketInterface"),Um=function(){function c(t){wm(this,c),Ot.debug('new() [url:"%s"]',t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;var n=Nm.parse(t,"absoluteURI");if(n===-1)throw Ot.warn("invalid WebSocket URI: ".concat(t)),new TypeError("Invalid argument: ".concat(t));if(n.scheme!=="wss"&&n.scheme!=="ws")throw Ot.warn("invalid WebSocket URI scheme: ".concat(n.scheme)),new TypeError("Invalid argument: ".concat(t));this._sip_uri="sip:".concat(n.host).concat(n.port?":".concat(n.port):"",";transport=ws"),this._via_transport=n.scheme.toUpperCase()}return Om(c,[{key:"connect",value:function(){if(Ot.debug("connect()"),this.isConnected()){Ot.debug("WebSocket ".concat(this._url," is already connected"));return}else if(this.isConnecting()){Ot.debug("WebSocket ".concat(this._url," is connecting"));return}this._ws&&this.disconnect(),Ot.debug("connecting to WebSocket ".concat(this._url));try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(n){this._onError(n)}}},{key:"disconnect",value:function(){Ot.debug("disconnect()"),this._ws&&(this._ws.onopen=function(){},this._ws.onclose=function(){},this._ws.onmessage=function(){},this._ws.onerror=function(){},this._ws.close(),this._ws=null)}},{key:"send",value:function(n){return Ot.debug("send()"),this.isConnected()?(this._ws.send(n),!0):(Ot.warn("unable to send message, WebSocket is not open"),!1)}},{key:"isConnected",value:function(){return this._ws&&this._ws.readyState===this._ws.OPEN}},{key:"isConnecting",value:function(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}},{key:"_onOpen",value:function(){Ot.debug("WebSocket ".concat(this._url," connected")),this.onconnect()}},{key:"_onClose",value:function(n){var a=n.wasClean,o=n.code,s=n.reason;Ot.debug("WebSocket ".concat(this._url," closed")),a===!1&&Ot.debug("WebSocket abrupt disconnection"),this.ondisconnect(!a,o,s)}},{key:"_onMessage",value:function(n){var a=n.data;Ot.debug("received WebSocket message"),this.ondata(a)}},{key:"_onError",value:function(n){Ot.warn("WebSocket ".concat(this._url," error: "),n)}},{key:"via_transport",get:function(){return this._via_transport},set:function(n){this._via_transport=n.toUpperCase()}},{key:"sip_uri",get:function(){return this._sip_uri}},{key:"url",get:function(){return this._url}}]),c}(),Su=Ha,Pm=lt,xm=Ws,km=bt(),Mm=Am,Lm=Ks(),$m=Ou(),Hm=os(),Fm=Um,jm=gr("JsSIP");jm("version %s",Su.version);var Qc={C:Pm,Exceptions:xm,Utils:km,UA:Mm,URI:Lm,NameAddrHeader:$m,WebSocketInterface:Fm,Grammar:Hm,debug:gr,get name(){return Su.title},get version(){return Su.version}};const or=gr,ur="JsSIP";var ut=class{constructor(t){t?(this._debug=or.default(`${ur}:${t}`),this._warn=or.default(`${ur}:WARN:${t}`),this._error=or.default(`${ur}:ERROR:${t}`)):(this._debug=or.default(ur),this._warn=or.default(`${ur}:WARN`),this._error=or.default(`${ur}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};const Ga=ze(ut),Zc=Ha;var De={USER_AGENT:`${Zc.title} ${Zc.version}`,SIP:"sip",SIPS:"sips",causes:{CONNECTION_ERROR:"Connection Error",REQUEST_TIMEOUT:"Request Timeout",SIP_FAILURE_CODE:"SIP Failure Code",INTERNAL_ERROR:"Internal Error",BUSY:"Busy",REJECTED:"Rejected",REDIRECTED:"Redirected",UNAVAILABLE:"Unavailable",NOT_FOUND:"Not Found",ADDRESS_INCOMPLETE:"Address Incomplete",INCOMPATIBLE_SDP:"Incompatible SDP",MISSING_SDP:"Missing SDP",AUTHENTICATION_ERROR:"Authentication Error",BYE:"Terminated",WEBRTC_ERROR:"WebRTC Error",CANCELED:"Canceled",NO_ANSWER:"No Answer",EXPIRES:"Expires",NO_ACK:"No ACK",DIALOG_ERROR:"Dialog Error",USER_DENIED_MEDIA_ACCESS:"User Denied Media Access",BAD_MEDIA_DESCRIPTION:"Bad Media Description",RTP_TIMEOUT:"RTP Timeout"},SIP_ERROR_CAUSES:{REDIRECTED:[300,301,302,305,380],BUSY:[486,600],REJECTED:[403,603],NOT_FOUND:[404,604],UNAVAILABLE:[480,410,408,430],ADDRESS_INCOMPLETE:[484,424],INCOMPATIBLE_SDP:[488,606],AUTHENTICATION_ERROR:[401,407]},ACK:"ACK",BYE:"BYE",CANCEL:"CANCEL",INFO:"INFO",INVITE:"INVITE",MESSAGE:"MESSAGE",NOTIFY:"NOTIFY",OPTIONS:"OPTIONS",REGISTER:"REGISTER",REFER:"REFER",UPDATE:"UPDATE",SUBSCRIBE:"SUBSCRIBE",DTMF_TRANSPORT:{INFO:"INFO",RFC2833:"RFC2833"},REASON_PHRASE:{100:"Trying",180:"Ringing",181:"Call Is Being Forwarded",182:"Queued",183:"Session Progress",199:"Early Dialog Terminated",200:"OK",202:"Accepted",204:"No Notification",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",305:"Use Proxy",380:"Alternative Service",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",410:"Gone",412:"Conditional Request Failed",413:"Request Entity Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Unsupported URI Scheme",417:"Unknown Resource-Priority",420:"Bad Extension",421:"Extension Required",422:"Session Interval Too Small",423:"Interval Too Brief",424:"Bad Location Information",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:"JsSIP Internal 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"},ALLOWED_METHODS:"INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS,REFER,INFO,NOTIFY",ACCEPTED_BODY_TYPES:"application/sdp, application/dtmf-relay",MAX_FORWARDS:69,SESSION_EXPIRES:90,MIN_SESSION_EXPIRES:60,CONNECTION_RECOVERY_MAX_INTERVAL:30,CONNECTION_RECOVERY_MIN_INTERVAL:2};const L=ze(De);var et={},xo,ef;function $u(){if(ef)return xo;ef=1;const c=ys(),t=Zt();return xo=class uh{static parse(a){if(a=t.parse(a,"Name_Addr_Header"),a!==-1)return a}constructor(a,o,s){if(!a||!(a instanceof c))throw new TypeError('missing or invalid "uri" parameter');this._uri=a,this._parameters={},this.display_name=o;for(const r in s)Object.prototype.hasOwnProperty.call(s,r)&&this.setParam(r,s[r])}get uri(){return this._uri}get display_name(){return this._display_name}set display_name(a){this._display_name=a===0?"0":a}setParam(a,o){a&&(this._parameters[a.toLowerCase()]=typeof o>"u"||o===null?null:o.toString())}getParam(a){if(a)return this._parameters[a.toLowerCase()]}hasParam(a){if(a)return this._parameters.hasOwnProperty(a.toLowerCase())&&!0||!1}deleteParam(a){if(a=a.toLowerCase(),this._parameters.hasOwnProperty(a)){const o=this._parameters[a];return delete this._parameters[a],o}}clearParams(){this._parameters={}}clone(){return new uh(this._uri.clone(),this._display_name,JSON.parse(JSON.stringify(this._parameters)))}_quote(a){return a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}toString(){let a=this._display_name?`"${this._quote(this._display_name)}" `:"";a+=`<${this._uri.toString()}>`;for(const o in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,o)&&(a+=`;${o}`,this._parameters[o]!==null&&(a+=`=${this._parameters[o]}`));return a}},xo}var ko,tf;function Zt(){return tf||(tf=1,ko=function(){function c(n){return'"'+n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\x08/g,"\\b").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g,escape)+'"'}var t={parse:function(n,a){var o={CRLF:_,DIGIT:g,ALPHA:T,HEXDIG:E,WSP:y,OCTET:A,DQUOTE:C,SP:I,HTAB:H,alphanum:$,reserved:oe,unreserved:N,mark:j,escaped:Se,LWS:ve,SWS:k,HCOLON:D,TEXT_UTF8_TRIM:B,TEXT_UTF8char:V,UTF8_NONASCII:J,UTF8_CONT:F,LHEX:X,token:U,token_nodot:P,separators:se,word:st,STAR:ee,SLASH:W,EQUAL:G,LPAREN:re,RPAREN:ge,RAQUOT:be,LAQUOT:xe,COMMA:Ce,SEMI:le,COLON:ye,LDQUOT:nt,RDQUOT:at,comment:Ee,ctext:Ae,quoted_string:Ie,quoted_string_clean:Oe,qdtext:pe,quoted_pair:ue,SIP_URI_noparams:_e,SIP_URI:we,uri_scheme:Ne,uri_scheme_sips:Qe,uri_scheme_sip:Le,userinfo:Lt,user:dt,user_unreserved:wn,password:On,hostport:Ys,host:es,hostname:us,domainlabel:Js,toplabel:Dn,IPv6reference:Nn,IPv6address:zs,h16:me,ls32:ae,IPv4address:ot,dec_octet:Wt,port:Cs,uri_parameters:Er,uri_parameter:Un,transport_param:Pn,user_param:Sr,method_param:yr,ttl_param:Ar,maddr_param:Cr,lr_param:Rr,other_param:Ir,pname:br,pvalue:wr,paramchar:Rs,param_unreserved:Is,headers:Or,header:Xs,hname:Qs,hvalue:Dr,hnv_unreserved:bs,Request_Response:Zs,Request_Line:gl,Request_URI:Nr,absoluteURI:xn,hier_part:kn,net_path:Ur,abs_path:en,opaque_part:tn,uric:ws,uric_no_slash:Os,path_segments:Pr,segment:sn,param:Ds,pchar:cs,scheme:Ns,authority:xr,srvr:kr,reg_name:Mr,query:Lr,SIP_Version:Mn,INVITEm:Ln,ACKm:$r,OPTIONSm:Hr,BYEm:Fr,CANCELm:jr,REGISTERm:qr,SUBSCRIBEm:Vr,NOTIFYm:Br,REFERm:Gr,Method:nn,Status_Line:rn,Status_Code:Wr,extension_code:Kr,Reason_Phrase:Yr,Allow_Events:Tl,Call_ID:Ya,Contact:Ja,contact_param:$n,name_addr:$t,display_name:Ht,contact_params:Us,c_p_q:Hn,c_p_expires:Jr,delta_seconds:ts,qvalue:ss,generic_param:Ge,gen_value:We,Content_Disposition:vl,disp_type:El,disp_param:Fn,handling_param:jn,Content_Encoding:Sl,Content_Length:za,Content_Type:Xa,media_type:yl,m_type:zr,discrete_type:Xr,composite_type:Qr,extension_token:ln,x_token:an,m_subtype:Zr,m_parameter:qn,m_value:Vn,CSeq:Al,CSeq_value:Cl,Expires:Rl,Event:Qa,event_type:on,From:un,from_param:ei,tag_param:cn,Max_Forwards:ti,Min_Expires:Za,Name_Addr_Header:eo,Proxy_Authenticate:to,challenge:si,other_challenge:Bn,auth_param:Ps,digest_cln:ns,realm:fn,realm_value:ni,domain:ri,URI:hn,nonce:dn,nonce_value:ii,opaque:li,stale:ai,algorithm:oi,qop_options:ui,qop_value:_n,Proxy_Require:Gn,Record_Route:so,rec_route:Wn,Reason:Kn,reason_param:ci,reason_cause:Yn,Require:Il,Route:no,route_param:Jn,Subscription_State:zn,substate_value:bl,subexp_params:Xn,event_reason_value:Qn,Subject:wl,Supported:ro,To:io,to_param:fi,Via:hi,via_param:Zn,via_params:xs,via_ttl:er,via_maddr:di,via_received:_i,via_branch:pi,response_port:mi,rport:gi,sent_protocol:Ti,protocol_name:vi,transport:Ei,sent_by:Si,via_host:yi,via_port:Ai,ttl:tr,WWW_Authenticate:Ci,Session_Expires:lo,s_e_expires:Ol,s_e_params:sr,s_e_refresher:nr,extension_header:Dl,header_value:Nl,message_body:Ul,uuid_URI:ao,uuid:Pl,hex4:Ft,hex8:jt,hex12:Ri,Refer_To:xl,Replaces:oo,call_id:kl,replaces_param:rr,to_tag:ir,from_tag:Ii,early_flag:bi};if(a!==void 0){if(o[a]===void 0)throw new Error("Invalid rule name: "+c(a)+".")}else a="CRLF";var s=0,r=0,d=[];function h(i){s<r||(s>r&&(r=s,d=[]),d.push(i))}function _(){var i;return n.substr(s,2)===`\r
|
72
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,r=!1,d;return{s:function(){n=c[Symbol.iterator]()},n:function(){var _=n.next();return s=_.done,_},e:function(_){r=!0,d=_},f:function(){try{!s&&n.return!=null&&n.return()}finally{if(r)throw d}}}}function um(c,t){if(c){if(typeof c=="string")return Bc(c,t);var n=Object.prototype.toString.call(c).slice(8,-1);if(n==="Object"&&c.constructor&&(n=c.constructor.name),n==="Map"||n==="Set")return Array.from(c);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Bc(c,t)}}function Bc(c,t){(t==null||t>c.length)&&(t=c.length);for(var n=0,a=new Array(t);n<t;n++)a[n]=c[n];return a}var fr=bt(),yn=lt,wo=os(),Gc=Ks(),Oo=xu,Do=Ws;Lu.settings={authorization_user:null,password:null,realm:null,ha1:null,authorization_jwt:null,display_name:null,uri:null,contact_uri:null,instance_id:null,use_preloaded_route:!1,session_timers:!0,session_timers_refresh_method:yn.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:yn.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:yn.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:"".concat(fr.createRandomToken(12),".invalid")};var Yl={mandatory:{sockets:function(t){var n=[];if(Oo.isSocket(t))n.push({socket:t});else if(Array.isArray(t)&&t.length){var a=Vc(t),o;try{for(a.s();!(o=a.n()).done;){var s=o.value;Object.prototype.hasOwnProperty.call(s,"socket")&&Oo.isSocket(s.socket)?n.push(s):Oo.isSocket(s)&&n.push({socket:s})}}catch(r){a.e(r)}finally{a.f()}}else return;return n},uri:function(t){/^sip:/i.test(t)||(t="".concat(yn.SIP,":").concat(t));var n=Gc.parse(t);if(n)return n.user?n:void 0}},optional:{authorization_user:function(t){if(wo.parse('"'.concat(t,'"'),"quoted_string")!==-1)return t},authorization_jwt:function(t){if(typeof t=="string")return t},user_agent:function(t){if(typeof t=="string")return t},connection_recovery_max_interval:function(t){if(fr.isDecimal(t)){var n=Number(t);if(n>0)return n}},connection_recovery_min_interval:function(t){if(fr.isDecimal(t)){var n=Number(t);if(n>0)return n}},contact_uri:function(t){if(typeof t=="string"){var n=wo.parse(t,"SIP_URI");if(n!==-1)return n}},display_name:function(t){return t},instance_id:function(t){if(/^uuid:/i.test(t)&&(t=t.substr(5)),wo.parse(t,"uuid")!==-1)return t},no_answer_timeout:function(t){if(fr.isDecimal(t)){var n=Number(t);if(n>0)return n}},session_timers:function(t){if(typeof t=="boolean")return t},session_timers_refresh_method:function(t){if(typeof t=="string"&&(t=t.toUpperCase(),t===yn.INVITE||t===yn.UPDATE))return t},session_timers_force_refresher:function(t){if(typeof t=="boolean")return t},password:function(t){return String(t)},realm:function(t){return String(t)},ha1:function(t){return String(t)},register:function(t){if(typeof t=="boolean")return t},register_expires:function(t){if(fr.isDecimal(t)){var n=Number(t);if(n>0)return n}},registrar_server:function(t){/^sip:/i.test(t)||(t="".concat(yn.SIP,":").concat(t));var n=Gc.parse(t);if(n)return n.user?void 0:n},use_preloaded_route:function(t){if(typeof t=="boolean")return t},extra_headers:function(t){var n=[];if(Array.isArray(t)&&t.length){var a=Vc(t),o;try{for(a.s();!(o=a.n()).done;){var s=o.value;typeof s=="string"&&n.push(s)}}catch(r){a.e(r)}finally{a.f()}}else return;return n}}};Lu.load=function(c,t){for(var n in Yl.mandatory)if(t.hasOwnProperty(n)){var a=t[n],o=Yl.mandatory[n](a);if(o!==void 0)c[n]=o;else throw new Do.ConfigurationError(n,a)}else throw new Do.ConfigurationError(n);for(var s in Yl.optional)if(t.hasOwnProperty(s)){var r=t[s];if(fr.isEmpty(r))continue;var d=Yl.optional[s](r);if(d!==void 0)c[s]=d;else throw new Do.ConfigurationError(s,r)}};function ba(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?ba=function(n){return typeof n}:ba=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},ba(c)}function cm(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Wc(c,t){for(var n=0;n<t.length;n++){var a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(c,a.key,a)}}function Kc(c,t,n){return t&&Wc(c.prototype,t),n&&Wc(c,n),c}function fm(c,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(t&&t.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),t&&Eu(c,t)}function Eu(c,t){return Eu=Object.setPrototypeOf||function(a,o){return a.__proto__=o,a},Eu(c,t)}function hm(c){var t=_m();return function(){var a=La(c),o;if(t){var s=La(this).constructor;o=Reflect.construct(a,arguments,s)}else o=a.apply(this,arguments);return dm(this,o)}}function dm(c,t){return t&&(ba(t)==="object"||typeof t=="function")?t:oh(c)}function oh(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function _m(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function La(c){return La=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},La(c)}var pm=ft.EventEmitter,mm=ht,pt=lt,gm=r_,Yc=dp,Jc=Ip,zc=$p,No=hl,Tm=Gp,Jl=bt(),vm=Ws,Em=Ks(),Sm=ih,Uo=Ss,ym=tm,Po=Lu,qe=new mm("UA"),Tt={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},Am=function(c){fm(n,c);var t=hm(n);Kc(n,null,[{key:"C",get:function(){return Tt}}]);function n(a){var o;if(cm(this,n),console.log("constructor es5"),qe.debug("new() [configuration:%o]",a),o=t.call(this),o._cache={credentials:{}},o._configuration=Object.assign({},Po.settings),o._dynConfiguration={},o._dialogs={},o._applicants={},o._sessions={},o._transport=null,o._contact=null,o._status=Tt.STATUS_INIT,o._error=null,o._transactions={nist:{},nict:{},ist:{},ict:{}},o._data={},o._closeTimer=null,a===void 0)throw new TypeError("Not enough arguments");try{o._loadConfig(a)}catch(s){throw o._status=Tt.STATUS_NOT_READY,o._error=Tt.CONFIGURATION_ERROR,s}return o._registrator=new gm(oh(o)),o}return Kc(n,[{key:"start",value:function(){qe.debug("start()"),this._status===Tt.STATUS_INIT?this._transport.connect():this._status===Tt.STATUS_USER_CLOSED?(qe.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=Tt.STATUS_INIT,this._transport.connect()):this._status===Tt.STATUS_READY?qe.debug("UA is in READY status, not restarted"):qe.debug("ERROR: connection is down, Auto-Recovery system is trying to reconnect"),this._dynConfiguration.register=this._configuration.register}},{key:"register",value:function(){qe.debug("register()"),this._dynConfiguration.register=!0,this._registrator.register()}},{key:"unregister",value:function(o){qe.debug("unregister()"),this._dynConfiguration.register=!1,this._registrator.unregister(o)}},{key:"registrator",value:function(){return this._registrator}},{key:"isRegistered",value:function(){return this._registrator.registered}},{key:"isConnected",value:function(){return this._transport.isConnected()}},{key:"call",value:function(o,s){qe.debug("call()");var r=new Yc(this);return r.connect(o,s),r}},{key:"sendMessage",value:function(o,s,r){qe.debug("sendMessage()");var d=new Jc(this);return d.send(o,s,r),d}},{key:"sendOptions",value:function(o,s,r){qe.debug("sendOptions()");var d=new zc(this);return d.send(o,s,r),d}},{key:"terminateSessions",value:function(o){qe.debug("terminateSessions()");for(var s in this._sessions)this._sessions[s].isEnded()||this._sessions[s].terminate(o)}},{key:"stop",value:function(){var o=this;if(qe.debug("stop()"),this._dynConfiguration={},this._status===Tt.STATUS_USER_CLOSED){qe.debug("UA already closed");return}this._registrator.close();var s=Object.keys(this._sessions).length;for(var r in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,r)){qe.debug("closing session ".concat(r));try{this._sessions[r].terminate()}catch{}}for(var d in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,d))try{this._applicants[d].close()}catch{}this._status=Tt.STATUS_USER_CLOSED;var h=Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length;h===0&&s===0?this._transport.disconnect():this._closeTimer=setTimeout(function(){o._closeTimer=null,o._transport.disconnect()},2e3)}},{key:"normalizeTarget",value:function(o){return Jl.normalizeTarget(o,this._configuration.hostport_params)}},{key:"get",value:function(o){switch(o){case"authorization_user":return this._configuration.authorization_user;case"realm":return this._configuration.realm;case"ha1":return this._configuration.ha1;case"authorization_jwt":return this._configuration.authorization_jwt;default:qe.warn('get() | cannot get "%s" parameter in runtime',o);return}}},{key:"set",value:function(o,s){switch(o){case"authorization_user":{this._configuration.authorization_user=String(s);break}case"password":{this._configuration.password=String(s);break}case"realm":{this._configuration.realm=String(s);break}case"ha1":{this._configuration.ha1=String(s),this._configuration.password=null;break}case"authorization_jwt":{this._configuration.authorization_jwt=String(s);break}case"display_name":{this._configuration.display_name=s;break}default:return qe.warn('set() | cannot set "%s" parameter in runtime',o),!1}return!0}},{key:"newTransaction",value:function(o){this._transactions[o.type][o.id]=o,this.emit("newTransaction",{transaction:o})}},{key:"destroyTransaction",value:function(o){delete this._transactions[o.type][o.id],this.emit("transactionDestroyed",{transaction:o})}},{key:"newDialog",value:function(o){this._dialogs[o.id]=o}},{key:"destroyDialog",value:function(o){delete this._dialogs[o.id]}},{key:"newMessage",value:function(o,s){this._applicants[o]=o,this.emit("newMessage",s)}},{key:"newOptions",value:function(o,s){this._applicants[o]=o,this.emit("newOptions",s)}},{key:"destroyMessage",value:function(o){delete this._applicants[o]}},{key:"newRTCSession",value:function(o,s){this._sessions[o.id]=o,this.emit("newRTCSession",s)}},{key:"destroyRTCSession",value:function(o){delete this._sessions[o.id]}},{key:"registered",value:function(o){this.emit("registered",o)}},{key:"unregistered",value:function(o){this.emit("unregistered",o)}},{key:"registrationFailed",value:function(o){this.emit("registrationFailed",o)}},{key:"receiveRequest",value:function(o){console.log("receiveRequest");var s=o.method;if(o.ruri.user!==this._configuration.uri.user&&o.ruri.user!==this._contact.uri.user){qe.debug("Request-URI does not point to us"),o.method!==pt.ACK&&o.reply_sl(404);return}if(o.ruri.scheme===pt.SIPS){o.reply_sl(416);return}if(!No.checkTransaction(this,o)){if(s===pt.INVITE?new No.InviteServerTransaction(this,this._transport,o):s!==pt.ACK&&s!==pt.CANCEL&&new No.NonInviteServerTransaction(this,this._transport,o),s===pt.OPTIONS){if(console.log("OPPP in option"),this.listeners("newOptions").length===0){o.reply(200);return}var r=new zc(this);r.init_incoming(o)}else if(s===pt.MESSAGE){if(this.listeners("newMessage").length===0){o.reply(405);return}var d=new Jc(this);d.init_incoming(o)}else if(s===pt.INVITE&&!o.to_tag&&this.listeners("newRTCSession").length===0){o.reply(405);return}var h,_;if(o.to_tag)h=this._findDialog(o.call_id,o.from_tag,o.to_tag),h?h.receiveRequest(o):s===pt.NOTIFY?(_=this._findSession(o),_?_.receiveRequest(o):(qe.debug("received NOTIFY request for a non existent subscription"),o.reply(481,"Subscription does not exist"))):s!==pt.ACK&&o.reply(481);else switch(s){case pt.INVITE:if(window.RTCPeerConnection)if(o.hasHeader("replaces")){var g=o.replaces;h=this._findDialog(g.call_id,g.from_tag,g.to_tag),h?(_=h.owner,_.isEnded()?o.reply(603):_.receiveRequest(o)):o.reply(481)}else _=new Yc(this),_.init_incoming(o);else qe.warn("INVITE received but WebRTC is not supported"),o.reply(488);break;case pt.BYE:o.reply(481);break;case pt.CANCEL:_=this._findSession(o),_?_.receiveRequest(o):qe.debug("received CANCEL request for a non existent session");break;case pt.ACK:break;case pt.NOTIFY:this.emit("sipEvent",{event:o.event,request:o}),o.reply(200);break;default:o.reply(405);break}}}},{key:"_findSession",value:function(o){var s=o.call_id,r=o.from_tag,d=o.to_tag,h=s+r,_=this._sessions[h],g=s+d,T=this._sessions[g];return _||T||null}},{key:"_findDialog",value:function(o,s,r){var d=o+s+r,h=this._dialogs[d];return h||(d=o+r+s,h=this._dialogs[d],h||null)}},{key:"_loadConfig",value:function(o){try{Po.load(this._configuration,o)}catch(g){throw g}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=Jl.newUUID()),this._configuration.jssip_id=Jl.createRandomToken(5);var s=this._configuration.uri.clone();s.user=null,this._configuration.hostport_params=s.toString().replace(/^sip:/i,"");try{this._transport=new Tm(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=Cm.bind(this),this._transport.onconnect=Rm.bind(this),this._transport.ondisconnect=Im.bind(this),this._transport.ondata=bm.bind(this)}catch(g){throw qe.warn(g),new vm.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){var r=this._configuration.uri.clone();r.user=null,r.clearParams(),r.clearHeaders(),this._configuration.registrar_server=r}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new Em("sip",Jl.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString:function(){var T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},E=T.anonymous||null,y=T.outbound||null,A="<";return E?A+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":A+=this.pub_gruu||this.uri.toString(),y&&(E?!this.temp_gruu:!this.pub_gruu)&&(A+=";ob"),A+=">",A}};var d=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(var h in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,h)&&(d.indexOf(h)!==-1?Object.defineProperty(this._configuration,h,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,h,{writable:!1,configurable:!1}));qe.debug("configuration parameters after validation:");for(var _ in this._configuration)if(Object.prototype.hasOwnProperty.call(Po.settings,_))switch(_){case"uri":case"registrar_server":qe.debug("- ".concat(_,": ").concat(this._configuration[_]));break;case"password":case"ha1":case"authorization_jwt":qe.debug("- ".concat(_,": NOT SHOWN"));break;default:qe.debug("- ".concat(_,": ").concat(JSON.stringify(this._configuration[_])))}}},{key:"C",get:function(){return Tt}},{key:"status",get:function(){return this._status}},{key:"contact",get:function(){return this._contact}},{key:"configuration",get:function(){return this._configuration}},{key:"transport",get:function(){return this._transport}}]),n}(pm);function Cm(c){this.emit("connecting",c)}function Rm(c){this._status!==Tt.STATUS_USER_CLOSED&&(this._status=Tt.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function Im(c){for(var t=["nict","ict","nist","ist"],n=0,a=t;n<a.length;n++){var o=a[n];for(var s in this._transactions[o])Object.prototype.hasOwnProperty.call(this._transactions[o],s)&&this._transactions[o][s].onTransportError()}this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==Tt.STATUS_USER_CLOSED&&(this._status=Tt.STATUS_NOT_READY,this._error=Tt.NETWORK_ERROR)}function bm(c){console.log("onTransportData");var t=c.transport,n=c.message;if(n=Sm.parseMessage(n,this),!!n&&!(this._status===Tt.STATUS_USER_CLOSED&&n instanceof Uo.IncomingRequest)&&ym(n,this,t)){if(n instanceof Uo.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof Uo.IncomingResponse){var a;switch(n.method){case pt.INVITE:a=this._transactions.ict[n.via_branch],a&&a.receiveResponse(n);break;case pt.ACK:break;default:a=this._transactions.nict[n.via_branch],a&&a.receiveResponse(n);break}}}}function wm(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Xc(c,t){for(var n=0;n<t.length;n++){var a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(c,a.key,a)}}function Om(c,t,n){return t&&Xc(c.prototype,t),n&&Xc(c,n),c}var Dm=ht,Nm=os(),Ot=new Dm("WebSocketInterface"),Um=function(){function c(t){wm(this,c),Ot.debug('new() [url:"%s"]',t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;var n=Nm.parse(t,"absoluteURI");if(n===-1)throw Ot.warn("invalid WebSocket URI: ".concat(t)),new TypeError("Invalid argument: ".concat(t));if(n.scheme!=="wss"&&n.scheme!=="ws")throw Ot.warn("invalid WebSocket URI scheme: ".concat(n.scheme)),new TypeError("Invalid argument: ".concat(t));this._sip_uri="sip:".concat(n.host).concat(n.port?":".concat(n.port):"",";transport=ws"),this._via_transport=n.scheme.toUpperCase()}return Om(c,[{key:"connect",value:function(){if(Ot.debug("connect()"),this.isConnected()){Ot.debug("WebSocket ".concat(this._url," is already connected"));return}else if(this.isConnecting()){Ot.debug("WebSocket ".concat(this._url," is connecting"));return}this._ws&&this.disconnect(),Ot.debug("connecting to WebSocket ".concat(this._url));try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(n){this._onError(n)}}},{key:"disconnect",value:function(){Ot.debug("disconnect()"),this._ws&&(this._ws.onopen=function(){},this._ws.onclose=function(){},this._ws.onmessage=function(){},this._ws.onerror=function(){},this._ws.close(),this._ws=null)}},{key:"send",value:function(n){return Ot.debug("send()"),this.isConnected()?(this._ws.send(n),!0):(Ot.warn("unable to send message, WebSocket is not open"),!1)}},{key:"isConnected",value:function(){return this._ws&&this._ws.readyState===this._ws.OPEN}},{key:"isConnecting",value:function(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}},{key:"_onOpen",value:function(){Ot.debug("WebSocket ".concat(this._url," connected")),this.onconnect()}},{key:"_onClose",value:function(n){var a=n.wasClean,o=n.code,s=n.reason;Ot.debug("WebSocket ".concat(this._url," closed")),a===!1&&Ot.debug("WebSocket abrupt disconnection"),this.ondisconnect(!a,o,s)}},{key:"_onMessage",value:function(n){var a=n.data;Ot.debug("received WebSocket message"),this.ondata(a)}},{key:"_onError",value:function(n){Ot.warn("WebSocket ".concat(this._url," error: "),n)}},{key:"via_transport",get:function(){return this._via_transport},set:function(n){this._via_transport=n.toUpperCase()}},{key:"sip_uri",get:function(){return this._sip_uri}},{key:"url",get:function(){return this._url}}]),c}(),Su=Ha,Pm=lt,xm=Ws,km=bt(),Mm=Am,Lm=Ks(),$m=Ou(),Hm=os(),Fm=Um,jm=gr("JsSIP");jm("version %s",Su.version);var Qc={C:Pm,Exceptions:xm,Utils:km,UA:Mm,URI:Lm,NameAddrHeader:$m,WebSocketInterface:Fm,Grammar:Hm,debug:gr,get name(){return Su.title},get version(){return Su.version}};const or=gr,ur="JsSIP";var ut=class{constructor(t){t?(this._debug=or.default(`${ur}:${t}`),this._warn=or.default(`${ur}:WARN:${t}`),this._error=or.default(`${ur}:ERROR:${t}`)):(this._debug=or.default(ur),this._warn=or.default(`${ur}:WARN`),this._error=or.default(`${ur}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};const Ga=ze(ut),Zc=Ha;var De={USER_AGENT:`${Zc.title} ${Zc.version}`,SIP:"sip",SIPS:"sips",causes:{CONNECTION_ERROR:"Connection Error",REQUEST_TIMEOUT:"Request Timeout",SIP_FAILURE_CODE:"SIP Failure Code",INTERNAL_ERROR:"Internal Error",BUSY:"Busy",REJECTED:"Rejected",REDIRECTED:"Redirected",UNAVAILABLE:"Unavailable",NOT_FOUND:"Not Found",ADDRESS_INCOMPLETE:"Address Incomplete",INCOMPATIBLE_SDP:"Incompatible SDP",MISSING_SDP:"Missing SDP",AUTHENTICATION_ERROR:"Authentication Error",BYE:"Terminated",WEBRTC_ERROR:"WebRTC Error",CANCELED:"Canceled",NO_ANSWER:"No Answer",EXPIRES:"Expires",NO_ACK:"No ACK",DIALOG_ERROR:"Dialog Error",USER_DENIED_MEDIA_ACCESS:"User Denied Media Access",BAD_MEDIA_DESCRIPTION:"Bad Media Description",RTP_TIMEOUT:"RTP Timeout"},SIP_ERROR_CAUSES:{REDIRECTED:[300,301,302,305,380],BUSY:[486,600],REJECTED:[403,603],NOT_FOUND:[404,604],UNAVAILABLE:[480,410,408,430],ADDRESS_INCOMPLETE:[484,424],INCOMPATIBLE_SDP:[488,606],AUTHENTICATION_ERROR:[401,407]},ACK:"ACK",BYE:"BYE",CANCEL:"CANCEL",INFO:"INFO",INVITE:"INVITE",MESSAGE:"MESSAGE",NOTIFY:"NOTIFY",OPTIONS:"OPTIONS",REGISTER:"REGISTER",REFER:"REFER",UPDATE:"UPDATE",SUBSCRIBE:"SUBSCRIBE",DTMF_TRANSPORT:{INFO:"INFO",RFC2833:"RFC2833"},REASON_PHRASE:{100:"Trying",180:"Ringing",181:"Call Is Being Forwarded",182:"Queued",183:"Session Progress",199:"Early Dialog Terminated",200:"OK",202:"Accepted",204:"No Notification",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",305:"Use Proxy",380:"Alternative Service",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",410:"Gone",412:"Conditional Request Failed",413:"Request Entity Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Unsupported URI Scheme",417:"Unknown Resource-Priority",420:"Bad Extension",421:"Extension Required",422:"Session Interval Too Small",423:"Interval Too Brief",424:"Bad Location Information",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:"JsSIP Internal 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"},ALLOWED_METHODS:"INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS,REFER,INFO,NOTIFY",ACCEPTED_BODY_TYPES:"application/sdp, application/dtmf-relay",MAX_FORWARDS:69,SESSION_EXPIRES:90,MIN_SESSION_EXPIRES:60,CONNECTION_RECOVERY_MAX_INTERVAL:30,CONNECTION_RECOVERY_MIN_INTERVAL:2};const L=ze(De);var et={},xo,ef;function $u(){if(ef)return xo;ef=1;const c=ys(),t=Zt();return xo=class uh{static parse(a){if(a=t.parse(a,"Name_Addr_Header"),a!==-1)return a}constructor(a,o,s){if(!a||!(a instanceof c))throw new TypeError('missing or invalid "uri" parameter');this._uri=a,this._parameters={},this.display_name=o;for(const r in s)Object.prototype.hasOwnProperty.call(s,r)&&this.setParam(r,s[r])}get uri(){return this._uri}get display_name(){return this._display_name}set display_name(a){this._display_name=a===0?"0":a}setParam(a,o){a&&(this._parameters[a.toLowerCase()]=typeof o>"u"||o===null?null:o.toString())}getParam(a){if(a)return this._parameters[a.toLowerCase()]}hasParam(a){if(a)return this._parameters.hasOwnProperty(a.toLowerCase())&&!0||!1}deleteParam(a){if(a=a.toLowerCase(),this._parameters.hasOwnProperty(a)){const o=this._parameters[a];return delete this._parameters[a],o}}clearParams(){this._parameters={}}clone(){return new uh(this._uri.clone(),this._display_name,JSON.parse(JSON.stringify(this._parameters)))}_quote(a){return a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}toString(){let a=this._display_name?`"${this._quote(this._display_name)}" `:"";a+=`<${this._uri.toString()}>`;for(const o in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,o)&&(a+=`;${o}`,this._parameters[o]!==null&&(a+=`=${this._parameters[o]}`));return a}},xo}var ko,tf;function Zt(){return tf||(tf=1,ko=function(){function c(n){return'"'+n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\x08/g,"\\b").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g,escape)+'"'}var t={parse:function(n,a){var o={CRLF:_,DIGIT:g,ALPHA:T,HEXDIG:E,WSP:y,OCTET:A,DQUOTE:C,SP:I,HTAB:H,alphanum:$,reserved:oe,unreserved:N,mark:j,escaped:Se,LWS:ve,SWS:k,HCOLON:D,TEXT_UTF8_TRIM:B,TEXT_UTF8char:V,UTF8_NONASCII:J,UTF8_CONT:F,LHEX:X,token:U,token_nodot:P,separators:se,word:st,STAR:ee,SLASH:W,EQUAL:G,LPAREN:re,RPAREN:ge,RAQUOT:be,LAQUOT:xe,COMMA:Ce,SEMI:le,COLON:ye,LDQUOT:nt,RDQUOT:at,comment:Ee,ctext:Ae,quoted_string:Ie,quoted_string_clean:Oe,qdtext:pe,quoted_pair:ue,SIP_URI_noparams:_e,SIP_URI:we,uri_scheme:Ne,uri_scheme_sips:Qe,uri_scheme_sip:Le,userinfo:Lt,user:dt,user_unreserved:wn,password:On,hostport:Ys,host:es,hostname:us,domainlabel:Js,toplabel:Dn,IPv6reference:Nn,IPv6address:zs,h16:me,ls32:ae,IPv4address:ot,dec_octet:Wt,port:Cs,uri_parameters:Er,uri_parameter:Un,transport_param:Pn,user_param:Sr,method_param:yr,ttl_param:Ar,maddr_param:Cr,lr_param:Rr,other_param:Ir,pname:br,pvalue:wr,paramchar:Rs,param_unreserved:Is,headers:Or,header:Xs,hname:Qs,hvalue:Dr,hnv_unreserved:bs,Request_Response:Zs,Request_Line:gl,Request_URI:Nr,absoluteURI:xn,hier_part:kn,net_path:Ur,abs_path:en,opaque_part:tn,uric:ws,uric_no_slash:Os,path_segments:Pr,segment:sn,param:Ds,pchar:cs,scheme:Ns,authority:xr,srvr:kr,reg_name:Mr,query:Lr,SIP_Version:Mn,INVITEm:Ln,ACKm:$r,OPTIONSm:Hr,BYEm:Fr,CANCELm:jr,REGISTERm:qr,SUBSCRIBEm:Vr,NOTIFYm:Br,REFERm:Gr,Method:nn,Status_Line:rn,Status_Code:Wr,extension_code:Kr,Reason_Phrase:Yr,Allow_Events:Tl,Call_ID:Ya,Contact:Ja,contact_param:$n,name_addr:$t,display_name:Ht,contact_params:Us,c_p_q:Hn,c_p_expires:Jr,delta_seconds:ts,qvalue:ss,generic_param:Ge,gen_value:We,Content_Disposition:vl,disp_type:El,disp_param:Fn,handling_param:jn,Content_Encoding:Sl,Content_Length:za,Content_Type:Xa,media_type:yl,m_type:zr,discrete_type:Xr,composite_type:Qr,extension_token:ln,x_token:an,m_subtype:Zr,m_parameter:qn,m_value:Vn,CSeq:Al,CSeq_value:Cl,Expires:Rl,Event:Qa,event_type:on,From:un,from_param:ei,tag_param:cn,Max_Forwards:ti,Min_Expires:Za,Name_Addr_Header:eo,Proxy_Authenticate:to,challenge:si,other_challenge:Bn,auth_param:Ps,digest_cln:ns,realm:fn,realm_value:ni,domain:ri,URI:hn,nonce:dn,nonce_value:ii,opaque:li,stale:ai,algorithm:oi,qop_options:ui,qop_value:_n,Proxy_Require:Gn,Record_Route:so,rec_route:Wn,Reason:Kn,reason_param:ci,reason_cause:Yn,Require:Il,Route:no,route_param:Jn,Subscription_State:zn,substate_value:bl,subexp_params:Xn,event_reason_value:Qn,Subject:wl,Supported:ro,To:io,to_param:fi,Via:hi,via_param:Zn,via_params:xs,via_ttl:er,via_maddr:di,via_received:_i,via_branch:pi,response_port:mi,rport:gi,sent_protocol:Ti,protocol_name:vi,transport:Ei,sent_by:Si,via_host:yi,via_port:Ai,ttl:tr,WWW_Authenticate:Ci,Session_Expires:lo,s_e_expires:Ol,s_e_params:sr,s_e_refresher:nr,extension_header:Dl,header_value:Nl,message_body:Ul,uuid_URI:ao,uuid:Pl,hex4:Ft,hex8:jt,hex12:Ri,Refer_To:xl,Replaces:oo,call_id:kl,replaces_param:rr,to_tag:ir,from_tag:Ii,early_flag:bi};if(a!==void 0){if(o[a]===void 0)throw new Error("Invalid rule name: "+c(a)+".")}else a="CRLF";var s=0,r=0,d=[];function h(i){s<r||(s>r&&(r=s,d=[]),d.push(i))}function _(){var i;return n.substr(s,2)===`\r
|
73
73
|
`?(i=`\r
|
74
74
|
`,s+=2):(i=null,h('"\\r\\n"')),i}function g(){var i;return/^[0-9]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,h("[0-9]")),i}function T(){var i;return/^[a-zA-Z]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,h("[a-zA-Z]")),i}function E(){var i;return/^[0-9a-fA-F]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,h("[0-9a-fA-F]")),i}function y(){var i;return i=I(),i===null&&(i=H()),i}function A(){var i;return/^[\0-\xFF]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,h("[\\0-\\xFF]")),i}function C(){var i;return/^["]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,h('["]')),i}function I(){var i;return n.charCodeAt(s)===32?(i=" ",s++):(i=null,h('" "')),i}function H(){var i;return n.charCodeAt(s)===9?(i=" ",s++):(i=null,h('"\\t"')),i}function $(){var i;return/^[a-zA-Z0-9]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,h("[a-zA-Z0-9]")),i}function oe(){var i;return n.charCodeAt(s)===59?(i=";",s++):(i=null,h('";"')),i===null&&(n.charCodeAt(s)===47?(i="/",s++):(i=null,h('"/"')),i===null&&(n.charCodeAt(s)===63?(i="?",s++):(i=null,h('"?"')),i===null&&(n.charCodeAt(s)===58?(i=":",s++):(i=null,h('":"')),i===null&&(n.charCodeAt(s)===64?(i="@",s++):(i=null,h('"@"')),i===null&&(n.charCodeAt(s)===38?(i="&",s++):(i=null,h('"&"')),i===null&&(n.charCodeAt(s)===61?(i="=",s++):(i=null,h('"="')),i===null&&(n.charCodeAt(s)===43?(i="+",s++):(i=null,h('"+"')),i===null&&(n.charCodeAt(s)===36?(i="$",s++):(i=null,h('"$"')),i===null&&(n.charCodeAt(s)===44?(i=",",s++):(i=null,h('","'))))))))))),i}function N(){var i;return i=$(),i===null&&(i=j()),i}function j(){var i;return n.charCodeAt(s)===45?(i="-",s++):(i=null,h('"-"')),i===null&&(n.charCodeAt(s)===95?(i="_",s++):(i=null,h('"_"')),i===null&&(n.charCodeAt(s)===46?(i=".",s++):(i=null,h('"."')),i===null&&(n.charCodeAt(s)===33?(i="!",s++):(i=null,h('"!"')),i===null&&(n.charCodeAt(s)===126?(i="~",s++):(i=null,h('"~"')),i===null&&(n.charCodeAt(s)===42?(i="*",s++):(i=null,h('"*"')),i===null&&(n.charCodeAt(s)===39?(i="'",s++):(i=null,h(`"'"`)),i===null&&(n.charCodeAt(s)===40?(i="(",s++):(i=null,h('"("')),i===null&&(n.charCodeAt(s)===41?(i=")",s++):(i=null,h('")"')))))))))),i}function Se(){var i,e,l,u,f;return u=s,f=s,n.charCodeAt(s)===37?(i="%",s++):(i=null,h('"%"')),i!==null?(e=E(),e!==null?(l=E(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){return m.join("")}(u,i)),i===null&&(s=u),i}function ve(){var i,e,l,u,f,p;for(u=s,f=s,p=s,i=[],e=y();e!==null;)i.push(e),e=y();if(i!==null?(e=_(),e!==null?i=[i,e]:(i=null,s=p)):(i=null,s=p),i=i!==null?i:"",i!==null){if(l=y(),l!==null)for(e=[];l!==null;)e.push(l),l=y();else e=null;e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i!==null&&(i=function(m){return" "}()),i===null&&(s=u),i}function k(){var i;return i=ve(),i=i!==null?i:"",i}function D(){var i,e,l,u,f;for(u=s,f=s,i=[],e=I(),e===null&&(e=H());e!==null;)i.push(e),e=I(),e===null&&(e=H());return i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,h('":"')),e!==null?(l=k(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return":"}()),i===null&&(s=u),i}function B(){var i,e,l,u,f,p,m;if(f=s,p=s,e=V(),e!==null)for(i=[];e!==null;)i.push(e),e=V();else i=null;if(i!==null){for(e=[],m=s,l=[],u=ve();u!==null;)l.push(u),u=ve();for(l!==null?(u=V(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;){for(e.push(l),m=s,l=[],u=ve();u!==null;)l.push(u),u=ve();l!==null?(u=V(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m)}e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){return n.substring(s,v)}(f)),i===null&&(s=f),i}function V(){var i;return/^[!-~]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,h("[!-~]")),i===null&&(i=J()),i}function J(){var i;return/^[\x80-\uFFFF]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,h("[\\x80-\\uFFFF]")),i}function F(){var i;return/^[\x80-\xBF]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,h("[\\x80-\\xBF]")),i}function X(){var i;return i=g(),i===null&&(/^[a-f]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,h("[a-f]"))),i}function U(){var i,e,l;if(l=s,e=$(),e===null&&(n.charCodeAt(s)===45?(e="-",s++):(e=null,h('"-"')),e===null&&(n.charCodeAt(s)===46?(e=".",s++):(e=null,h('"."')),e===null&&(n.charCodeAt(s)===33?(e="!",s++):(e=null,h('"!"')),e===null&&(n.charCodeAt(s)===37?(e="%",s++):(e=null,h('"%"')),e===null&&(n.charCodeAt(s)===42?(e="*",s++):(e=null,h('"*"')),e===null&&(n.charCodeAt(s)===95?(e="_",s++):(e=null,h('"_"')),e===null&&(n.charCodeAt(s)===43?(e="+",s++):(e=null,h('"+"')),e===null&&(n.charCodeAt(s)===96?(e="`",s++):(e=null,h('"`"')),e===null&&(n.charCodeAt(s)===39?(e="'",s++):(e=null,h(`"'"`)),e===null&&(n.charCodeAt(s)===126?(e="~",s++):(e=null,h('"~"')))))))))))),e!==null)for(i=[];e!==null;)i.push(e),e=$(),e===null&&(n.charCodeAt(s)===45?(e="-",s++):(e=null,h('"-"')),e===null&&(n.charCodeAt(s)===46?(e=".",s++):(e=null,h('"."')),e===null&&(n.charCodeAt(s)===33?(e="!",s++):(e=null,h('"!"')),e===null&&(n.charCodeAt(s)===37?(e="%",s++):(e=null,h('"%"')),e===null&&(n.charCodeAt(s)===42?(e="*",s++):(e=null,h('"*"')),e===null&&(n.charCodeAt(s)===95?(e="_",s++):(e=null,h('"_"')),e===null&&(n.charCodeAt(s)===43?(e="+",s++):(e=null,h('"+"')),e===null&&(n.charCodeAt(s)===96?(e="`",s++):(e=null,h('"`"')),e===null&&(n.charCodeAt(s)===39?(e="'",s++):(e=null,h(`"'"`)),e===null&&(n.charCodeAt(s)===126?(e="~",s++):(e=null,h('"~"'))))))))))));else i=null;return i!==null&&(i=function(u){return n.substring(s,u)}(l)),i===null&&(s=l),i}function P(){var i,e,l;if(l=s,e=$(),e===null&&(n.charCodeAt(s)===45?(e="-",s++):(e=null,h('"-"')),e===null&&(n.charCodeAt(s)===33?(e="!",s++):(e=null,h('"!"')),e===null&&(n.charCodeAt(s)===37?(e="%",s++):(e=null,h('"%"')),e===null&&(n.charCodeAt(s)===42?(e="*",s++):(e=null,h('"*"')),e===null&&(n.charCodeAt(s)===95?(e="_",s++):(e=null,h('"_"')),e===null&&(n.charCodeAt(s)===43?(e="+",s++):(e=null,h('"+"')),e===null&&(n.charCodeAt(s)===96?(e="`",s++):(e=null,h('"`"')),e===null&&(n.charCodeAt(s)===39?(e="'",s++):(e=null,h(`"'"`)),e===null&&(n.charCodeAt(s)===126?(e="~",s++):(e=null,h('"~"'))))))))))),e!==null)for(i=[];e!==null;)i.push(e),e=$(),e===null&&(n.charCodeAt(s)===45?(e="-",s++):(e=null,h('"-"')),e===null&&(n.charCodeAt(s)===33?(e="!",s++):(e=null,h('"!"')),e===null&&(n.charCodeAt(s)===37?(e="%",s++):(e=null,h('"%"')),e===null&&(n.charCodeAt(s)===42?(e="*",s++):(e=null,h('"*"')),e===null&&(n.charCodeAt(s)===95?(e="_",s++):(e=null,h('"_"')),e===null&&(n.charCodeAt(s)===43?(e="+",s++):(e=null,h('"+"')),e===null&&(n.charCodeAt(s)===96?(e="`",s++):(e=null,h('"`"')),e===null&&(n.charCodeAt(s)===39?(e="'",s++):(e=null,h(`"'"`)),e===null&&(n.charCodeAt(s)===126?(e="~",s++):(e=null,h('"~"')))))))))));else i=null;return i!==null&&(i=function(u){return n.substring(s,u)}(l)),i===null&&(s=l),i}function se(){var i;return n.charCodeAt(s)===40?(i="(",s++):(i=null,h('"("')),i===null&&(n.charCodeAt(s)===41?(i=")",s++):(i=null,h('")"')),i===null&&(n.charCodeAt(s)===60?(i="<",s++):(i=null,h('"<"')),i===null&&(n.charCodeAt(s)===62?(i=">",s++):(i=null,h('">"')),i===null&&(n.charCodeAt(s)===64?(i="@",s++):(i=null,h('"@"')),i===null&&(n.charCodeAt(s)===44?(i=",",s++):(i=null,h('","')),i===null&&(n.charCodeAt(s)===59?(i=";",s++):(i=null,h('";"')),i===null&&(n.charCodeAt(s)===58?(i=":",s++):(i=null,h('":"')),i===null&&(n.charCodeAt(s)===92?(i="\\",s++):(i=null,h('"\\\\"')),i===null&&(i=C(),i===null&&(n.charCodeAt(s)===47?(i="/",s++):(i=null,h('"/"')),i===null&&(n.charCodeAt(s)===91?(i="[",s++):(i=null,h('"["')),i===null&&(n.charCodeAt(s)===93?(i="]",s++):(i=null,h('"]"')),i===null&&(n.charCodeAt(s)===63?(i="?",s++):(i=null,h('"?"')),i===null&&(n.charCodeAt(s)===61?(i="=",s++):(i=null,h('"="')),i===null&&(n.charCodeAt(s)===123?(i="{",s++):(i=null,h('"{"')),i===null&&(n.charCodeAt(s)===125?(i="}",s++):(i=null,h('"}"')),i===null&&(i=I(),i===null&&(i=H())))))))))))))))))),i}function st(){var i,e,l;if(l=s,e=$(),e===null&&(n.charCodeAt(s)===45?(e="-",s++):(e=null,h('"-"')),e===null&&(n.charCodeAt(s)===46?(e=".",s++):(e=null,h('"."')),e===null&&(n.charCodeAt(s)===33?(e="!",s++):(e=null,h('"!"')),e===null&&(n.charCodeAt(s)===37?(e="%",s++):(e=null,h('"%"')),e===null&&(n.charCodeAt(s)===42?(e="*",s++):(e=null,h('"*"')),e===null&&(n.charCodeAt(s)===95?(e="_",s++):(e=null,h('"_"')),e===null&&(n.charCodeAt(s)===43?(e="+",s++):(e=null,h('"+"')),e===null&&(n.charCodeAt(s)===96?(e="`",s++):(e=null,h('"`"')),e===null&&(n.charCodeAt(s)===39?(e="'",s++):(e=null,h(`"'"`)),e===null&&(n.charCodeAt(s)===126?(e="~",s++):(e=null,h('"~"')),e===null&&(n.charCodeAt(s)===40?(e="(",s++):(e=null,h('"("')),e===null&&(n.charCodeAt(s)===41?(e=")",s++):(e=null,h('")"')),e===null&&(n.charCodeAt(s)===60?(e="<",s++):(e=null,h('"<"')),e===null&&(n.charCodeAt(s)===62?(e=">",s++):(e=null,h('">"')),e===null&&(n.charCodeAt(s)===58?(e=":",s++):(e=null,h('":"')),e===null&&(n.charCodeAt(s)===92?(e="\\",s++):(e=null,h('"\\\\"')),e===null&&(e=C(),e===null&&(n.charCodeAt(s)===47?(e="/",s++):(e=null,h('"/"')),e===null&&(n.charCodeAt(s)===91?(e="[",s++):(e=null,h('"["')),e===null&&(n.charCodeAt(s)===93?(e="]",s++):(e=null,h('"]"')),e===null&&(n.charCodeAt(s)===63?(e="?",s++):(e=null,h('"?"')),e===null&&(n.charCodeAt(s)===123?(e="{",s++):(e=null,h('"{"')),e===null&&(n.charCodeAt(s)===125?(e="}",s++):(e=null,h('"}"'))))))))))))))))))))))))),e!==null)for(i=[];e!==null;)i.push(e),e=$(),e===null&&(n.charCodeAt(s)===45?(e="-",s++):(e=null,h('"-"')),e===null&&(n.charCodeAt(s)===46?(e=".",s++):(e=null,h('"."')),e===null&&(n.charCodeAt(s)===33?(e="!",s++):(e=null,h('"!"')),e===null&&(n.charCodeAt(s)===37?(e="%",s++):(e=null,h('"%"')),e===null&&(n.charCodeAt(s)===42?(e="*",s++):(e=null,h('"*"')),e===null&&(n.charCodeAt(s)===95?(e="_",s++):(e=null,h('"_"')),e===null&&(n.charCodeAt(s)===43?(e="+",s++):(e=null,h('"+"')),e===null&&(n.charCodeAt(s)===96?(e="`",s++):(e=null,h('"`"')),e===null&&(n.charCodeAt(s)===39?(e="'",s++):(e=null,h(`"'"`)),e===null&&(n.charCodeAt(s)===126?(e="~",s++):(e=null,h('"~"')),e===null&&(n.charCodeAt(s)===40?(e="(",s++):(e=null,h('"("')),e===null&&(n.charCodeAt(s)===41?(e=")",s++):(e=null,h('")"')),e===null&&(n.charCodeAt(s)===60?(e="<",s++):(e=null,h('"<"')),e===null&&(n.charCodeAt(s)===62?(e=">",s++):(e=null,h('">"')),e===null&&(n.charCodeAt(s)===58?(e=":",s++):(e=null,h('":"')),e===null&&(n.charCodeAt(s)===92?(e="\\",s++):(e=null,h('"\\\\"')),e===null&&(e=C(),e===null&&(n.charCodeAt(s)===47?(e="/",s++):(e=null,h('"/"')),e===null&&(n.charCodeAt(s)===91?(e="[",s++):(e=null,h('"["')),e===null&&(n.charCodeAt(s)===93?(e="]",s++):(e=null,h('"]"')),e===null&&(n.charCodeAt(s)===63?(e="?",s++):(e=null,h('"?"')),e===null&&(n.charCodeAt(s)===123?(e="{",s++):(e=null,h('"{"')),e===null&&(n.charCodeAt(s)===125?(e="}",s++):(e=null,h('"}"')))))))))))))))))))))))));else i=null;return i!==null&&(i=function(u){return n.substring(s,u)}(l)),i===null&&(s=l),i}function ee(){var i,e,l,u,f;return u=s,f=s,i=k(),i!==null?(n.charCodeAt(s)===42?(e="*",s++):(e=null,h('"*"')),e!==null?(l=k(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return"*"}()),i===null&&(s=u),i}function W(){var i,e,l,u,f;return u=s,f=s,i=k(),i!==null?(n.charCodeAt(s)===47?(e="/",s++):(e=null,h('"/"')),e!==null?(l=k(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return"/"}()),i===null&&(s=u),i}function G(){var i,e,l,u,f;return u=s,f=s,i=k(),i!==null?(n.charCodeAt(s)===61?(e="=",s++):(e=null,h('"="')),e!==null?(l=k(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return"="}()),i===null&&(s=u),i}function re(){var i,e,l,u,f;return u=s,f=s,i=k(),i!==null?(n.charCodeAt(s)===40?(e="(",s++):(e=null,h('"("')),e!==null?(l=k(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return"("}()),i===null&&(s=u),i}function ge(){var i,e,l,u,f;return u=s,f=s,i=k(),i!==null?(n.charCodeAt(s)===41?(e=")",s++):(e=null,h('")"')),e!==null?(l=k(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return")"}()),i===null&&(s=u),i}function be(){var i,e,l,u;return l=s,u=s,n.charCodeAt(s)===62?(i=">",s++):(i=null,h('">"')),i!==null?(e=k(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f){return">"}()),i===null&&(s=l),i}function xe(){var i,e,l,u;return l=s,u=s,i=k(),i!==null?(n.charCodeAt(s)===60?(e="<",s++):(e=null,h('"<"')),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f){return"<"}()),i===null&&(s=l),i}function Ce(){var i,e,l,u,f;return u=s,f=s,i=k(),i!==null?(n.charCodeAt(s)===44?(e=",",s++):(e=null,h('","')),e!==null?(l=k(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return","}()),i===null&&(s=u),i}function le(){var i,e,l,u,f;return u=s,f=s,i=k(),i!==null?(n.charCodeAt(s)===59?(e=";",s++):(e=null,h('";"')),e!==null?(l=k(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return";"}()),i===null&&(s=u),i}function ye(){var i,e,l,u,f;return u=s,f=s,i=k(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,h('":"')),e!==null?(l=k(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return":"}()),i===null&&(s=u),i}function nt(){var i,e,l,u;return l=s,u=s,i=k(),i!==null?(e=C(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f){return'"'}()),i===null&&(s=l),i}function at(){var i,e,l,u;return l=s,u=s,i=C(),i!==null?(e=k(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f){return'"'}()),i===null&&(s=l),i}function Ee(){var i,e,l,u;if(u=s,i=re(),i!==null){for(e=[],l=Ae(),l===null&&(l=ue(),l===null&&(l=Ee()));l!==null;)e.push(l),l=Ae(),l===null&&(l=ue(),l===null&&(l=Ee()));e!==null?(l=ge(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)}else i=null,s=u;return i}function Ae(){var i;return/^[!-']/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,h("[!-']")),i===null&&(/^[*-[]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,h("[*-[]")),i===null&&(/^[\]-~]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,h("[\\]-~]")),i===null&&(i=J(),i===null&&(i=ve())))),i}function Ie(){var i,e,l,u,f,p;if(f=s,p=s,i=k(),i!==null)if(e=C(),e!==null){for(l=[],u=pe(),u===null&&(u=ue());u!==null;)l.push(u),u=pe(),u===null&&(u=ue());l!==null?(u=C(),u!==null?i=[i,e,l,u]:(i=null,s=p)):(i=null,s=p)}else i=null,s=p;else i=null,s=p;return i!==null&&(i=function(m){return n.substring(s,m)}(f)),i===null&&(s=f),i}function Oe(){var i,e,l,u,f,p;if(f=s,p=s,i=k(),i!==null)if(e=C(),e!==null){for(l=[],u=pe(),u===null&&(u=ue());u!==null;)l.push(u),u=pe(),u===null&&(u=ue());l!==null?(u=C(),u!==null?i=[i,e,l,u]:(i=null,s=p)):(i=null,s=p)}else i=null,s=p;else i=null,s=p;return i!==null&&(i=function(m){var v=n.substring(s,m).trim();return v.substring(1,v.length-1).replace(/\\([\x00-\x09\x0b-\x0c\x0e-\x7f])/g,"$1")}(f)),i===null&&(s=f),i}function pe(){var i;return i=ve(),i===null&&(n.charCodeAt(s)===33?(i="!",s++):(i=null,h('"!"')),i===null&&(/^[#-[]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,h("[#-[]")),i===null&&(/^[\]-~]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,h("[\\]-~]")),i===null&&(i=J())))),i}function ue(){var i,e,l;return l=s,n.charCodeAt(s)===92?(i="\\",s++):(i=null,h('"\\\\"')),i!==null?(/^[\0-\t]/.test(n.charAt(s))?(e=n.charAt(s),s++):(e=null,h("[\\0-\\t]")),e===null&&(/^[\x0B-\f]/.test(n.charAt(s))?(e=n.charAt(s),s++):(e=null,h("[\\x0B-\\f]")),e===null&&(/^[\x0E-]/.test(n.charAt(s))?(e=n.charAt(s),s++):(e=null,h("[\\x0E-]")))),e!==null?i=[i,e]:(i=null,s=l)):(i=null,s=l),i}function _e(){var i,e,l,u,f,p;return f=s,p=s,i=Ne(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,h('":"')),e!==null?(l=Lt(),l=l!==null?l:"",l!==null?(u=Ys(),u!==null?i=[i,e,l,u]:(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p),i!==null&&(i=function(m){try{b.uri=new Ll(b.scheme,b.user,b.host,b.port),delete b.scheme,delete b.user,delete b.host,delete b.host_type,delete b.port}catch{b=-1}}()),i===null&&(s=f),i}function we(){var i,e,l,u,f,p,m,v;return m=s,v=s,i=Ne(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,h('":"')),e!==null?(l=Lt(),l=l!==null?l:"",l!==null?(u=Ys(),u!==null?(f=Er(),f!==null?(p=Or(),p=p!==null?p:"",p!==null?i=[i,e,l,u,f,p]:(i=null,s=v)):(i=null,s=v)):(i=null,s=v)):(i=null,s=v)):(i=null,s=v)):(i=null,s=v),i!==null&&(i=function(S){try{b.uri=new Ll(b.scheme,b.user,b.host,b.port,b.uri_params,b.uri_headers),delete b.scheme,delete b.user,delete b.host,delete b.host_type,delete b.port,delete b.uri_params,a==="SIP_URI"&&(b=b.uri)}catch{b=-1}}()),i===null&&(s=m),i}function Ne(){var i;return i=Qe(),i===null&&(i=Le()),i}function Qe(){var i,e;return e=s,n.substr(s,4).toLowerCase()==="sips"?(i=n.substr(s,4),s+=4):(i=null,h('"sips"')),i!==null&&(i=function(l,u){b.scheme=u.toLowerCase()}(e,i)),i===null&&(s=e),i}function Le(){var i,e;return e=s,n.substr(s,3).toLowerCase()==="sip"?(i=n.substr(s,3),s+=3):(i=null,h('"sip"')),i!==null&&(i=function(l,u){b.scheme=u.toLowerCase()}(e,i)),i===null&&(s=e),i}function Lt(){var i,e,l,u,f,p;return u=s,f=s,i=dt(),i!==null?(p=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,h('":"')),e!==null?(l=On(),l!==null?e=[e,l]:(e=null,s=p)):(e=null,s=p),e=e!==null?e:"",e!==null?(n.charCodeAt(s)===64?(l="@",s++):(l=null,h('"@"')),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(m){b.user=decodeURIComponent(n.substring(s-1,m))}(u)),i===null&&(s=u),i}function dt(){var i,e;if(e=N(),e===null&&(e=Se(),e===null&&(e=wn())),e!==null)for(i=[];e!==null;)i.push(e),e=N(),e===null&&(e=Se(),e===null&&(e=wn()));else i=null;return i}function wn(){var i;return n.charCodeAt(s)===38?(i="&",s++):(i=null,h('"&"')),i===null&&(n.charCodeAt(s)===61?(i="=",s++):(i=null,h('"="')),i===null&&(n.charCodeAt(s)===43?(i="+",s++):(i=null,h('"+"')),i===null&&(n.charCodeAt(s)===36?(i="$",s++):(i=null,h('"$"')),i===null&&(n.charCodeAt(s)===44?(i=",",s++):(i=null,h('","')),i===null&&(n.charCodeAt(s)===59?(i=";",s++):(i=null,h('";"')),i===null&&(n.charCodeAt(s)===63?(i="?",s++):(i=null,h('"?"')),i===null&&(n.charCodeAt(s)===47?(i="/",s++):(i=null,h('"/"'))))))))),i}function On(){var i,e,l;for(l=s,i=[],e=N(),e===null&&(e=Se(),e===null&&(n.charCodeAt(s)===38?(e="&",s++):(e=null,h('"&"')),e===null&&(n.charCodeAt(s)===61?(e="=",s++):(e=null,h('"="')),e===null&&(n.charCodeAt(s)===43?(e="+",s++):(e=null,h('"+"')),e===null&&(n.charCodeAt(s)===36?(e="$",s++):(e=null,h('"$"')),e===null&&(n.charCodeAt(s)===44?(e=",",s++):(e=null,h('","'))))))));e!==null;)i.push(e),e=N(),e===null&&(e=Se(),e===null&&(n.charCodeAt(s)===38?(e="&",s++):(e=null,h('"&"')),e===null&&(n.charCodeAt(s)===61?(e="=",s++):(e=null,h('"="')),e===null&&(n.charCodeAt(s)===43?(e="+",s++):(e=null,h('"+"')),e===null&&(n.charCodeAt(s)===36?(e="$",s++):(e=null,h('"$"')),e===null&&(n.charCodeAt(s)===44?(e=",",s++):(e=null,h('","'))))))));return i!==null&&(i=function(u){b.password=n.substring(s,u)}(l)),i===null&&(s=l),i}function Ys(){var i,e,l,u,f;return u=s,i=es(),i!==null?(f=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,h('":"')),e!==null?(l=Cs(),l!==null?e=[e,l]:(e=null,s=f)):(e=null,s=f),e=e!==null?e:"",e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i}function es(){var i,e;return e=s,i=us(),i===null&&(i=ot(),i===null&&(i=Nn())),i!==null&&(i=function(l){return b.host=n.substring(s,l).toLowerCase(),b.host}(e)),i===null&&(s=e),i}function us(){var i,e,l,u,f,p;for(u=s,f=s,i=[],p=s,e=Js(),e!==null?(n.charCodeAt(s)===46?(l=".",s++):(l=null,h('"."')),l!==null?e=[e,l]:(e=null,s=p)):(e=null,s=p);e!==null;)i.push(e),p=s,e=Js(),e!==null?(n.charCodeAt(s)===46?(l=".",s++):(l=null,h('"."')),l!==null?e=[e,l]:(e=null,s=p)):(e=null,s=p);return i!==null?(e=Dn(),e!==null?(n.charCodeAt(s)===46?(l=".",s++):(l=null,h('"."')),l=l!==null?l:"",l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(m){return b.host_type="domain",n.substring(s,m)}(u)),i===null&&(s=u),i}function Js(){var i,e,l,u;if(u=s,i=$(),i!==null){for(e=[],l=$(),l===null&&(n.charCodeAt(s)===45?(l="-",s++):(l=null,h('"-"')),l===null&&(n.charCodeAt(s)===95?(l="_",s++):(l=null,h('"_"'))));l!==null;)e.push(l),l=$(),l===null&&(n.charCodeAt(s)===45?(l="-",s++):(l=null,h('"-"')),l===null&&(n.charCodeAt(s)===95?(l="_",s++):(l=null,h('"_"'))));e!==null?i=[i,e]:(i=null,s=u)}else i=null,s=u;return i}function Dn(){var i,e,l,u;if(u=s,i=T(),i!==null){for(e=[],l=$(),l===null&&(n.charCodeAt(s)===45?(l="-",s++):(l=null,h('"-"')),l===null&&(n.charCodeAt(s)===95?(l="_",s++):(l=null,h('"_"'))));l!==null;)e.push(l),l=$(),l===null&&(n.charCodeAt(s)===45?(l="-",s++):(l=null,h('"-"')),l===null&&(n.charCodeAt(s)===95?(l="_",s++):(l=null,h('"_"'))));e!==null?i=[i,e]:(i=null,s=u)}else i=null,s=u;return i}function Nn(){var i,e,l,u,f;return u=s,f=s,n.charCodeAt(s)===91?(i="[",s++):(i=null,h('"["')),i!==null?(e=zs(),e!==null?(n.charCodeAt(s)===93?(l="]",s++):(l=null,h('"]"')),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return b.host_type="IPv6",n.substring(s,p)}(u)),i===null&&(s=u),i}function zs(){var i,e,l,u,f,p,m,v,S,O,ie,Ue,wt,ks,M,R;return ks=s,M=s,i=me(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,h('":"')),e!==null?(l=me(),l!==null?(n.charCodeAt(s)===58?(u=":",s++):(u=null,h('":"')),u!==null?(f=me(),f!==null?(n.charCodeAt(s)===58?(p=":",s++):(p=null,h('":"')),p!==null?(m=me(),m!==null?(n.charCodeAt(s)===58?(v=":",s++):(v=null,h('":"')),v!==null?(S=me(),S!==null?(n.charCodeAt(s)===58?(O=":",s++):(O=null,h('":"')),O!==null?(ie=me(),ie!==null?(n.charCodeAt(s)===58?(Ue=":",s++):(Ue=null,h('":"')),Ue!==null?(wt=ae(),wt!==null?i=[i,e,l,u,f,p,m,v,S,O,ie,Ue,wt]:(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M),i===null&&(M=s,n.substr(s,2)==="::"?(i="::",s+=2):(i=null,h('"::"')),i!==null?(e=me(),e!==null?(n.charCodeAt(s)===58?(l=":",s++):(l=null,h('":"')),l!==null?(u=me(),u!==null?(n.charCodeAt(s)===58?(f=":",s++):(f=null,h('":"')),f!==null?(p=me(),p!==null?(n.charCodeAt(s)===58?(m=":",s++):(m=null,h('":"')),m!==null?(v=me(),v!==null?(n.charCodeAt(s)===58?(S=":",s++):(S=null,h('":"')),S!==null?(O=me(),O!==null?(n.charCodeAt(s)===58?(ie=":",s++):(ie=null,h('":"')),ie!==null?(Ue=ae(),Ue!==null?i=[i,e,l,u,f,p,m,v,S,O,ie,Ue]:(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M),i===null&&(M=s,n.substr(s,2)==="::"?(i="::",s+=2):(i=null,h('"::"')),i!==null?(e=me(),e!==null?(n.charCodeAt(s)===58?(l=":",s++):(l=null,h('":"')),l!==null?(u=me(),u!==null?(n.charCodeAt(s)===58?(f=":",s++):(f=null,h('":"')),f!==null?(p=me(),p!==null?(n.charCodeAt(s)===58?(m=":",s++):(m=null,h('":"')),m!==null?(v=me(),v!==null?(n.charCodeAt(s)===58?(S=":",s++):(S=null,h('":"')),S!==null?(O=ae(),O!==null?i=[i,e,l,u,f,p,m,v,S,O]:(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M),i===null&&(M=s,n.substr(s,2)==="::"?(i="::",s+=2):(i=null,h('"::"')),i!==null?(e=me(),e!==null?(n.charCodeAt(s)===58?(l=":",s++):(l=null,h('":"')),l!==null?(u=me(),u!==null?(n.charCodeAt(s)===58?(f=":",s++):(f=null,h('":"')),f!==null?(p=me(),p!==null?(n.charCodeAt(s)===58?(m=":",s++):(m=null,h('":"')),m!==null?(v=ae(),v!==null?i=[i,e,l,u,f,p,m,v]:(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M),i===null&&(M=s,n.substr(s,2)==="::"?(i="::",s+=2):(i=null,h('"::"')),i!==null?(e=me(),e!==null?(n.charCodeAt(s)===58?(l=":",s++):(l=null,h('":"')),l!==null?(u=me(),u!==null?(n.charCodeAt(s)===58?(f=":",s++):(f=null,h('":"')),f!==null?(p=ae(),p!==null?i=[i,e,l,u,f,p]:(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M),i===null&&(M=s,n.substr(s,2)==="::"?(i="::",s+=2):(i=null,h('"::"')),i!==null?(e=me(),e!==null?(n.charCodeAt(s)===58?(l=":",s++):(l=null,h('":"')),l!==null?(u=ae(),u!==null?i=[i,e,l,u]:(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M),i===null&&(M=s,n.substr(s,2)==="::"?(i="::",s+=2):(i=null,h('"::"')),i!==null?(e=ae(),e!==null?i=[i,e]:(i=null,s=M)):(i=null,s=M),i===null&&(M=s,n.substr(s,2)==="::"?(i="::",s+=2):(i=null,h('"::"')),i!==null?(e=me(),e!==null?i=[i,e]:(i=null,s=M)):(i=null,s=M),i===null&&(M=s,i=me(),i!==null?(n.substr(s,2)==="::"?(e="::",s+=2):(e=null,h('"::"')),e!==null?(l=me(),l!==null?(n.charCodeAt(s)===58?(u=":",s++):(u=null,h('":"')),u!==null?(f=me(),f!==null?(n.charCodeAt(s)===58?(p=":",s++):(p=null,h('":"')),p!==null?(m=me(),m!==null?(n.charCodeAt(s)===58?(v=":",s++):(v=null,h('":"')),v!==null?(S=me(),S!==null?(n.charCodeAt(s)===58?(O=":",s++):(O=null,h('":"')),O!==null?(ie=ae(),ie!==null?i=[i,e,l,u,f,p,m,v,S,O,ie]:(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M),i===null&&(M=s,i=me(),i!==null?(R=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,h('":"')),e!==null?(l=me(),l!==null?e=[e,l]:(e=null,s=R)):(e=null,s=R),e=e!==null?e:"",e!==null?(n.substr(s,2)==="::"?(l="::",s+=2):(l=null,h('"::"')),l!==null?(u=me(),u!==null?(n.charCodeAt(s)===58?(f=":",s++):(f=null,h('":"')),f!==null?(p=me(),p!==null?(n.charCodeAt(s)===58?(m=":",s++):(m=null,h('":"')),m!==null?(v=me(),v!==null?(n.charCodeAt(s)===58?(S=":",s++):(S=null,h('":"')),S!==null?(O=ae(),O!==null?i=[i,e,l,u,f,p,m,v,S,O]:(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M),i===null&&(M=s,i=me(),i!==null?(R=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,h('":"')),e!==null?(l=me(),l!==null?e=[e,l]:(e=null,s=R)):(e=null,s=R),e=e!==null?e:"",e!==null?(R=s,n.charCodeAt(s)===58?(l=":",s++):(l=null,h('":"')),l!==null?(u=me(),u!==null?l=[l,u]:(l=null,s=R)):(l=null,s=R),l=l!==null?l:"",l!==null?(n.substr(s,2)==="::"?(u="::",s+=2):(u=null,h('"::"')),u!==null?(f=me(),f!==null?(n.charCodeAt(s)===58?(p=":",s++):(p=null,h('":"')),p!==null?(m=me(),m!==null?(n.charCodeAt(s)===58?(v=":",s++):(v=null,h('":"')),v!==null?(S=ae(),S!==null?i=[i,e,l,u,f,p,m,v,S]:(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M),i===null&&(M=s,i=me(),i!==null?(R=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,h('":"')),e!==null?(l=me(),l!==null?e=[e,l]:(e=null,s=R)):(e=null,s=R),e=e!==null?e:"",e!==null?(R=s,n.charCodeAt(s)===58?(l=":",s++):(l=null,h('":"')),l!==null?(u=me(),u!==null?l=[l,u]:(l=null,s=R)):(l=null,s=R),l=l!==null?l:"",l!==null?(R=s,n.charCodeAt(s)===58?(u=":",s++):(u=null,h('":"')),u!==null?(f=me(),f!==null?u=[u,f]:(u=null,s=R)):(u=null,s=R),u=u!==null?u:"",u!==null?(n.substr(s,2)==="::"?(f="::",s+=2):(f=null,h('"::"')),f!==null?(p=me(),p!==null?(n.charCodeAt(s)===58?(m=":",s++):(m=null,h('":"')),m!==null?(v=ae(),v!==null?i=[i,e,l,u,f,p,m,v]:(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M),i===null&&(M=s,i=me(),i!==null?(R=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,h('":"')),e!==null?(l=me(),l!==null?e=[e,l]:(e=null,s=R)):(e=null,s=R),e=e!==null?e:"",e!==null?(R=s,n.charCodeAt(s)===58?(l=":",s++):(l=null,h('":"')),l!==null?(u=me(),u!==null?l=[l,u]:(l=null,s=R)):(l=null,s=R),l=l!==null?l:"",l!==null?(R=s,n.charCodeAt(s)===58?(u=":",s++):(u=null,h('":"')),u!==null?(f=me(),f!==null?u=[u,f]:(u=null,s=R)):(u=null,s=R),u=u!==null?u:"",u!==null?(R=s,n.charCodeAt(s)===58?(f=":",s++):(f=null,h('":"')),f!==null?(p=me(),p!==null?f=[f,p]:(f=null,s=R)):(f=null,s=R),f=f!==null?f:"",f!==null?(n.substr(s,2)==="::"?(p="::",s+=2):(p=null,h('"::"')),p!==null?(m=ae(),m!==null?i=[i,e,l,u,f,p,m]:(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M),i===null&&(M=s,i=me(),i!==null?(R=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,h('":"')),e!==null?(l=me(),l!==null?e=[e,l]:(e=null,s=R)):(e=null,s=R),e=e!==null?e:"",e!==null?(R=s,n.charCodeAt(s)===58?(l=":",s++):(l=null,h('":"')),l!==null?(u=me(),u!==null?l=[l,u]:(l=null,s=R)):(l=null,s=R),l=l!==null?l:"",l!==null?(R=s,n.charCodeAt(s)===58?(u=":",s++):(u=null,h('":"')),u!==null?(f=me(),f!==null?u=[u,f]:(u=null,s=R)):(u=null,s=R),u=u!==null?u:"",u!==null?(R=s,n.charCodeAt(s)===58?(f=":",s++):(f=null,h('":"')),f!==null?(p=me(),p!==null?f=[f,p]:(f=null,s=R)):(f=null,s=R),f=f!==null?f:"",f!==null?(R=s,n.charCodeAt(s)===58?(p=":",s++):(p=null,h('":"')),p!==null?(m=me(),m!==null?p=[p,m]:(p=null,s=R)):(p=null,s=R),p=p!==null?p:"",p!==null?(n.substr(s,2)==="::"?(m="::",s+=2):(m=null,h('"::"')),m!==null?(v=me(),v!==null?i=[i,e,l,u,f,p,m,v]:(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M),i===null&&(M=s,i=me(),i!==null?(R=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,h('":"')),e!==null?(l=me(),l!==null?e=[e,l]:(e=null,s=R)):(e=null,s=R),e=e!==null?e:"",e!==null?(R=s,n.charCodeAt(s)===58?(l=":",s++):(l=null,h('":"')),l!==null?(u=me(),u!==null?l=[l,u]:(l=null,s=R)):(l=null,s=R),l=l!==null?l:"",l!==null?(R=s,n.charCodeAt(s)===58?(u=":",s++):(u=null,h('":"')),u!==null?(f=me(),f!==null?u=[u,f]:(u=null,s=R)):(u=null,s=R),u=u!==null?u:"",u!==null?(R=s,n.charCodeAt(s)===58?(f=":",s++):(f=null,h('":"')),f!==null?(p=me(),p!==null?f=[f,p]:(f=null,s=R)):(f=null,s=R),f=f!==null?f:"",f!==null?(R=s,n.charCodeAt(s)===58?(p=":",s++):(p=null,h('":"')),p!==null?(m=me(),m!==null?p=[p,m]:(p=null,s=R)):(p=null,s=R),p=p!==null?p:"",p!==null?(R=s,n.charCodeAt(s)===58?(m=":",s++):(m=null,h('":"')),m!==null?(v=me(),v!==null?m=[m,v]:(m=null,s=R)):(m=null,s=R),m=m!==null?m:"",m!==null?(n.substr(s,2)==="::"?(v="::",s+=2):(v=null,h('"::"')),v!==null?i=[i,e,l,u,f,p,m,v]:(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M)):(i=null,s=M))))))))))))))),i!==null&&(i=function(Te){return b.host_type="IPv6",n.substring(s,Te)}(ks)),i===null&&(s=ks),i}function me(){var i,e,l,u,f;return f=s,i=E(),i!==null?(e=E(),e=e!==null?e:"",e!==null?(l=E(),l=l!==null?l:"",l!==null?(u=E(),u=u!==null?u:"",u!==null?i=[i,e,l,u]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i}function ae(){var i,e,l,u;return u=s,i=me(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,h('":"')),e!==null?(l=me(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i===null&&(i=ot()),i}function ot(){var i,e,l,u,f,p,m,v,S;return v=s,S=s,i=Wt(),i!==null?(n.charCodeAt(s)===46?(e=".",s++):(e=null,h('"."')),e!==null?(l=Wt(),l!==null?(n.charCodeAt(s)===46?(u=".",s++):(u=null,h('"."')),u!==null?(f=Wt(),f!==null?(n.charCodeAt(s)===46?(p=".",s++):(p=null,h('"."')),p!==null?(m=Wt(),m!==null?i=[i,e,l,u,f,p,m]:(i=null,s=S)):(i=null,s=S)):(i=null,s=S)):(i=null,s=S)):(i=null,s=S)):(i=null,s=S)):(i=null,s=S),i!==null&&(i=function(O){return b.host_type="IPv4",n.substring(s,O)}(v)),i===null&&(s=v),i}function Wt(){var i,e,l,u;return u=s,n.substr(s,2)==="25"?(i="25",s+=2):(i=null,h('"25"')),i!==null?(/^[0-5]/.test(n.charAt(s))?(e=n.charAt(s),s++):(e=null,h("[0-5]")),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i===null&&(u=s,n.charCodeAt(s)===50?(i="2",s++):(i=null,h('"2"')),i!==null?(/^[0-4]/.test(n.charAt(s))?(e=n.charAt(s),s++):(e=null,h("[0-4]")),e!==null?(l=g(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i===null&&(u=s,n.charCodeAt(s)===49?(i="1",s++):(i=null,h('"1"')),i!==null?(e=g(),e!==null?(l=g(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i===null&&(u=s,/^[1-9]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,h("[1-9]")),i!==null?(e=g(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i===null&&(i=g())))),i}function Cs(){var i,e,l,u,f,p,m;return p=s,m=s,i=g(),i=i!==null?i:"",i!==null?(e=g(),e=e!==null?e:"",e!==null?(l=g(),l=l!==null?l:"",l!==null?(u=g(),u=u!==null?u:"",u!==null?(f=g(),f=f!==null?f:"",f!==null?i=[i,e,l,u,f]:(i=null,s=m)):(i=null,s=m)):(i=null,s=m)):(i=null,s=m)):(i=null,s=m),i!==null&&(i=function(v,S){return S=parseInt(S.join("")),b.port=S,S}(p,i)),i===null&&(s=p),i}function Er(){var i,e,l,u;for(i=[],u=s,n.charCodeAt(s)===59?(e=";",s++):(e=null,h('";"')),e!==null?(l=Un(),l!==null?e=[e,l]:(e=null,s=u)):(e=null,s=u);e!==null;)i.push(e),u=s,n.charCodeAt(s)===59?(e=";",s++):(e=null,h('";"')),e!==null?(l=Un(),l!==null?e=[e,l]:(e=null,s=u)):(e=null,s=u);return i}function Un(){var i;return i=Pn(),i===null&&(i=Sr(),i===null&&(i=yr(),i===null&&(i=Ar(),i===null&&(i=Cr(),i===null&&(i=Rr(),i===null&&(i=Ir())))))),i}function Pn(){var i,e,l,u;return l=s,u=s,n.substr(s,10).toLowerCase()==="transport="?(i=n.substr(s,10),s+=10):(i=null,h('"transport="')),i!==null?(n.substr(s,3).toLowerCase()==="udp"?(e=n.substr(s,3),s+=3):(e=null,h('"udp"')),e===null&&(n.substr(s,3).toLowerCase()==="tcp"?(e=n.substr(s,3),s+=3):(e=null,h('"tcp"')),e===null&&(n.substr(s,4).toLowerCase()==="sctp"?(e=n.substr(s,4),s+=4):(e=null,h('"sctp"')),e===null&&(n.substr(s,3).toLowerCase()==="tls"?(e=n.substr(s,3),s+=3):(e=null,h('"tls"')),e===null&&(e=U())))),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f,p){b.uri_params||(b.uri_params={}),b.uri_params.transport=p.toLowerCase()}(l,i[1])),i===null&&(s=l),i}function Sr(){var i,e,l,u;return l=s,u=s,n.substr(s,5).toLowerCase()==="user="?(i=n.substr(s,5),s+=5):(i=null,h('"user="')),i!==null?(n.substr(s,5).toLowerCase()==="phone"?(e=n.substr(s,5),s+=5):(e=null,h('"phone"')),e===null&&(n.substr(s,2).toLowerCase()==="ip"?(e=n.substr(s,2),s+=2):(e=null,h('"ip"')),e===null&&(e=U())),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f,p){b.uri_params||(b.uri_params={}),b.uri_params.user=p.toLowerCase()}(l,i[1])),i===null&&(s=l),i}function yr(){var i,e,l,u;return l=s,u=s,n.substr(s,7).toLowerCase()==="method="?(i=n.substr(s,7),s+=7):(i=null,h('"method="')),i!==null?(e=nn(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f,p){b.uri_params||(b.uri_params={}),b.uri_params.method=p}(l,i[1])),i===null&&(s=l),i}function Ar(){var i,e,l,u;return l=s,u=s,n.substr(s,4).toLowerCase()==="ttl="?(i=n.substr(s,4),s+=4):(i=null,h('"ttl="')),i!==null?(e=tr(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f,p){b.params||(b.params={}),b.params.ttl=p}(l,i[1])),i===null&&(s=l),i}function Cr(){var i,e,l,u;return l=s,u=s,n.substr(s,6).toLowerCase()==="maddr="?(i=n.substr(s,6),s+=6):(i=null,h('"maddr="')),i!==null?(e=es(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f,p){b.uri_params||(b.uri_params={}),b.uri_params.maddr=p}(l,i[1])),i===null&&(s=l),i}function Rr(){var i,e,l,u,f,p;return u=s,f=s,n.substr(s,2).toLowerCase()==="lr"?(i=n.substr(s,2),s+=2):(i=null,h('"lr"')),i!==null?(p=s,n.charCodeAt(s)===61?(e="=",s++):(e=null,h('"="')),e!==null?(l=U(),l!==null?e=[e,l]:(e=null,s=p)):(e=null,s=p),e=e!==null?e:"",e!==null?i=[i,e]:(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(m){b.uri_params||(b.uri_params={}),b.uri_params.lr=void 0}()),i===null&&(s=u),i}function Ir(){var i,e,l,u,f,p;return u=s,f=s,i=br(),i!==null?(p=s,n.charCodeAt(s)===61?(e="=",s++):(e=null,h('"="')),e!==null?(l=wr(),l!==null?e=[e,l]:(e=null,s=p)):(e=null,s=p),e=e!==null?e:"",e!==null?i=[i,e]:(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(m,v,S){b.uri_params||(b.uri_params={}),typeof S>"u"?S=void 0:S=S[1],b.uri_params[v.toLowerCase()]=S}(u,i[0],i[1])),i===null&&(s=u),i}function br(){var i,e,l;if(l=s,e=Rs(),e!==null)for(i=[];e!==null;)i.push(e),e=Rs();else i=null;return i!==null&&(i=function(u,f){return f.join("")}(l,i)),i===null&&(s=l),i}function wr(){var i,e,l;if(l=s,e=Rs(),e!==null)for(i=[];e!==null;)i.push(e),e=Rs();else i=null;return i!==null&&(i=function(u,f){return f.join("")}(l,i)),i===null&&(s=l),i}function Rs(){var i;return i=Is(),i===null&&(i=N(),i===null&&(i=Se())),i}function Is(){var i;return n.charCodeAt(s)===91?(i="[",s++):(i=null,h('"["')),i===null&&(n.charCodeAt(s)===93?(i="]",s++):(i=null,h('"]"')),i===null&&(n.charCodeAt(s)===47?(i="/",s++):(i=null,h('"/"')),i===null&&(n.charCodeAt(s)===58?(i=":",s++):(i=null,h('":"')),i===null&&(n.charCodeAt(s)===38?(i="&",s++):(i=null,h('"&"')),i===null&&(n.charCodeAt(s)===43?(i="+",s++):(i=null,h('"+"')),i===null&&(n.charCodeAt(s)===36?(i="$",s++):(i=null,h('"$"')))))))),i}function Or(){var i,e,l,u,f,p,m;if(p=s,n.charCodeAt(s)===63?(i="?",s++):(i=null,h('"?"')),i!==null)if(e=Xs(),e!==null){for(l=[],m=s,n.charCodeAt(s)===38?(u="&",s++):(u=null,h('"&"')),u!==null?(f=Xs(),f!==null?u=[u,f]:(u=null,s=m)):(u=null,s=m);u!==null;)l.push(u),m=s,n.charCodeAt(s)===38?(u="&",s++):(u=null,h('"&"')),u!==null?(f=Xs(),f!==null?u=[u,f]:(u=null,s=m)):(u=null,s=m);l!==null?i=[i,e,l]:(i=null,s=p)}else i=null,s=p;else i=null,s=p;return i}function Xs(){var i,e,l,u,f;return u=s,f=s,i=Qs(),i!==null?(n.charCodeAt(s)===61?(e="=",s++):(e=null,h('"="')),e!==null?(l=Dr(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m,v){m=m.join("").toLowerCase(),v=v.join(""),b.uri_headers||(b.uri_headers={}),b.uri_headers[m]?b.uri_headers[m].push(v):b.uri_headers[m]=[v]}(u,i[0],i[2])),i===null&&(s=u),i}function Qs(){var i,e;if(e=bs(),e===null&&(e=N(),e===null&&(e=Se())),e!==null)for(i=[];e!==null;)i.push(e),e=bs(),e===null&&(e=N(),e===null&&(e=Se()));else i=null;return i}function Dr(){var i,e;for(i=[],e=bs(),e===null&&(e=N(),e===null&&(e=Se()));e!==null;)i.push(e),e=bs(),e===null&&(e=N(),e===null&&(e=Se()));return i}function bs(){var i;return n.charCodeAt(s)===91?(i="[",s++):(i=null,h('"["')),i===null&&(n.charCodeAt(s)===93?(i="]",s++):(i=null,h('"]"')),i===null&&(n.charCodeAt(s)===47?(i="/",s++):(i=null,h('"/"')),i===null&&(n.charCodeAt(s)===63?(i="?",s++):(i=null,h('"?"')),i===null&&(n.charCodeAt(s)===58?(i=":",s++):(i=null,h('":"')),i===null&&(n.charCodeAt(s)===43?(i="+",s++):(i=null,h('"+"')),i===null&&(n.charCodeAt(s)===36?(i="$",s++):(i=null,h('"$"')))))))),i}function Zs(){var i;return i=rn(),i===null&&(i=gl()),i}function gl(){var i,e,l,u,f,p;return p=s,i=nn(),i!==null?(e=I(),e!==null?(l=Nr(),l!==null?(u=I(),u!==null?(f=Mn(),f!==null?i=[i,e,l,u,f]:(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p),i}function Nr(){var i;return i=we(),i===null&&(i=xn()),i}function xn(){var i,e,l,u;return u=s,i=Ns(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,h('":"')),e!==null?(l=kn(),l===null&&(l=tn()),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function kn(){var i,e,l,u,f;return u=s,i=Ur(),i===null&&(i=en()),i!==null?(f=s,n.charCodeAt(s)===63?(e="?",s++):(e=null,h('"?"')),e!==null?(l=Lr(),l!==null?e=[e,l]:(e=null,s=f)):(e=null,s=f),e=e!==null?e:"",e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i}function Ur(){var i,e,l,u;return u=s,n.substr(s,2)==="//"?(i="//",s+=2):(i=null,h('"//"')),i!==null?(e=xr(),e!==null?(l=en(),l=l!==null?l:"",l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function en(){var i,e,l;return l=s,n.charCodeAt(s)===47?(i="/",s++):(i=null,h('"/"')),i!==null?(e=Pr(),e!==null?i=[i,e]:(i=null,s=l)):(i=null,s=l),i}function tn(){var i,e,l,u;if(u=s,i=Os(),i!==null){for(e=[],l=ws();l!==null;)e.push(l),l=ws();e!==null?i=[i,e]:(i=null,s=u)}else i=null,s=u;return i}function ws(){var i;return i=oe(),i===null&&(i=N(),i===null&&(i=Se())),i}function Os(){var i;return i=N(),i===null&&(i=Se(),i===null&&(n.charCodeAt(s)===59?(i=";",s++):(i=null,h('";"')),i===null&&(n.charCodeAt(s)===63?(i="?",s++):(i=null,h('"?"')),i===null&&(n.charCodeAt(s)===58?(i=":",s++):(i=null,h('":"')),i===null&&(n.charCodeAt(s)===64?(i="@",s++):(i=null,h('"@"')),i===null&&(n.charCodeAt(s)===38?(i="&",s++):(i=null,h('"&"')),i===null&&(n.charCodeAt(s)===61?(i="=",s++):(i=null,h('"="')),i===null&&(n.charCodeAt(s)===43?(i="+",s++):(i=null,h('"+"')),i===null&&(n.charCodeAt(s)===36?(i="$",s++):(i=null,h('"$"')),i===null&&(n.charCodeAt(s)===44?(i=",",s++):(i=null,h('","')))))))))))),i}function Pr(){var i,e,l,u,f,p;if(f=s,i=sn(),i!==null){for(e=[],p=s,n.charCodeAt(s)===47?(l="/",s++):(l=null,h('"/"')),l!==null?(u=sn(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,n.charCodeAt(s)===47?(l="/",s++):(l=null,h('"/"')),l!==null?(u=sn(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function sn(){var i,e,l,u,f,p;for(f=s,i=[],e=cs();e!==null;)i.push(e),e=cs();if(i!==null){for(e=[],p=s,n.charCodeAt(s)===59?(l=";",s++):(l=null,h('";"')),l!==null?(u=Ds(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,n.charCodeAt(s)===59?(l=";",s++):(l=null,h('";"')),l!==null?(u=Ds(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Ds(){var i,e;for(i=[],e=cs();e!==null;)i.push(e),e=cs();return i}function cs(){var i;return i=N(),i===null&&(i=Se(),i===null&&(n.charCodeAt(s)===58?(i=":",s++):(i=null,h('":"')),i===null&&(n.charCodeAt(s)===64?(i="@",s++):(i=null,h('"@"')),i===null&&(n.charCodeAt(s)===38?(i="&",s++):(i=null,h('"&"')),i===null&&(n.charCodeAt(s)===61?(i="=",s++):(i=null,h('"="')),i===null&&(n.charCodeAt(s)===43?(i="+",s++):(i=null,h('"+"')),i===null&&(n.charCodeAt(s)===36?(i="$",s++):(i=null,h('"$"')),i===null&&(n.charCodeAt(s)===44?(i=",",s++):(i=null,h('","')))))))))),i}function Ns(){var i,e,l,u,f;if(u=s,f=s,i=T(),i!==null){for(e=[],l=T(),l===null&&(l=g(),l===null&&(n.charCodeAt(s)===43?(l="+",s++):(l=null,h('"+"')),l===null&&(n.charCodeAt(s)===45?(l="-",s++):(l=null,h('"-"')),l===null&&(n.charCodeAt(s)===46?(l=".",s++):(l=null,h('"."'))))));l!==null;)e.push(l),l=T(),l===null&&(l=g(),l===null&&(n.charCodeAt(s)===43?(l="+",s++):(l=null,h('"+"')),l===null&&(n.charCodeAt(s)===45?(l="-",s++):(l=null,h('"-"')),l===null&&(n.charCodeAt(s)===46?(l=".",s++):(l=null,h('"."'))))));e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i!==null&&(i=function(p){b.scheme=n.substring(s,p)}(u)),i===null&&(s=u),i}function xr(){var i;return i=kr(),i===null&&(i=Mr()),i}function kr(){var i,e,l,u;return l=s,u=s,i=Lt(),i!==null?(n.charCodeAt(s)===64?(e="@",s++):(e=null,h('"@"')),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i=i!==null?i:"",i!==null?(e=Ys(),e!==null?i=[i,e]:(i=null,s=l)):(i=null,s=l),i=i!==null?i:"",i}function Mr(){var i,e;if(e=N(),e===null&&(e=Se(),e===null&&(n.charCodeAt(s)===36?(e="$",s++):(e=null,h('"$"')),e===null&&(n.charCodeAt(s)===44?(e=",",s++):(e=null,h('","')),e===null&&(n.charCodeAt(s)===59?(e=";",s++):(e=null,h('";"')),e===null&&(n.charCodeAt(s)===58?(e=":",s++):(e=null,h('":"')),e===null&&(n.charCodeAt(s)===64?(e="@",s++):(e=null,h('"@"')),e===null&&(n.charCodeAt(s)===38?(e="&",s++):(e=null,h('"&"')),e===null&&(n.charCodeAt(s)===61?(e="=",s++):(e=null,h('"="')),e===null&&(n.charCodeAt(s)===43?(e="+",s++):(e=null,h('"+"'))))))))))),e!==null)for(i=[];e!==null;)i.push(e),e=N(),e===null&&(e=Se(),e===null&&(n.charCodeAt(s)===36?(e="$",s++):(e=null,h('"$"')),e===null&&(n.charCodeAt(s)===44?(e=",",s++):(e=null,h('","')),e===null&&(n.charCodeAt(s)===59?(e=";",s++):(e=null,h('";"')),e===null&&(n.charCodeAt(s)===58?(e=":",s++):(e=null,h('":"')),e===null&&(n.charCodeAt(s)===64?(e="@",s++):(e=null,h('"@"')),e===null&&(n.charCodeAt(s)===38?(e="&",s++):(e=null,h('"&"')),e===null&&(n.charCodeAt(s)===61?(e="=",s++):(e=null,h('"="')),e===null&&(n.charCodeAt(s)===43?(e="+",s++):(e=null,h('"+"')))))))))));else i=null;return i}function Lr(){var i,e;for(i=[],e=ws();e!==null;)i.push(e),e=ws();return i}function Mn(){var i,e,l,u,f,p,m,v;if(m=s,v=s,n.substr(s,3).toLowerCase()==="sip"?(i=n.substr(s,3),s+=3):(i=null,h('"SIP"')),i!==null)if(n.charCodeAt(s)===47?(e="/",s++):(e=null,h('"/"')),e!==null){if(u=g(),u!==null)for(l=[];u!==null;)l.push(u),u=g();else l=null;if(l!==null)if(n.charCodeAt(s)===46?(u=".",s++):(u=null,h('"."')),u!==null){if(p=g(),p!==null)for(f=[];p!==null;)f.push(p),p=g();else f=null;f!==null?i=[i,e,l,u,f]:(i=null,s=v)}else i=null,s=v;else i=null,s=v}else i=null,s=v;else i=null,s=v;return i!==null&&(i=function(S){b.sip_version=n.substring(s,S)}(m)),i===null&&(s=m),i}function Ln(){var i;return n.substr(s,6)==="INVITE"?(i="INVITE",s+=6):(i=null,h('"INVITE"')),i}function $r(){var i;return n.substr(s,3)==="ACK"?(i="ACK",s+=3):(i=null,h('"ACK"')),i}function Hr(){var i;return n.substr(s,7)==="OPTIONS"?(i="OPTIONS",s+=7):(i=null,h('"OPTIONS"')),i}function Fr(){var i;return n.substr(s,3)==="BYE"?(i="BYE",s+=3):(i=null,h('"BYE"')),i}function jr(){var i;return n.substr(s,6)==="CANCEL"?(i="CANCEL",s+=6):(i=null,h('"CANCEL"')),i}function qr(){var i;return n.substr(s,8)==="REGISTER"?(i="REGISTER",s+=8):(i=null,h('"REGISTER"')),i}function Vr(){var i;return n.substr(s,9)==="SUBSCRIBE"?(i="SUBSCRIBE",s+=9):(i=null,h('"SUBSCRIBE"')),i}function Br(){var i;return n.substr(s,6)==="NOTIFY"?(i="NOTIFY",s+=6):(i=null,h('"NOTIFY"')),i}function Gr(){var i;return n.substr(s,5)==="REFER"?(i="REFER",s+=5):(i=null,h('"REFER"')),i}function nn(){var i,e;return e=s,i=Ln(),i===null&&(i=$r(),i===null&&(i=Hr(),i===null&&(i=Fr(),i===null&&(i=jr(),i===null&&(i=qr(),i===null&&(i=Vr(),i===null&&(i=Br(),i===null&&(i=Gr(),i===null&&(i=U()))))))))),i!==null&&(i=function(l){return b.method=n.substring(s,l),b.method}(e)),i===null&&(s=e),i}function rn(){var i,e,l,u,f,p;return p=s,i=Mn(),i!==null?(e=I(),e!==null?(l=Wr(),l!==null?(u=I(),u!==null?(f=Yr(),f!==null?i=[i,e,l,u,f]:(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p),i}function Wr(){var i,e;return e=s,i=Kr(),i!==null&&(i=function(l,u){b.status_code=parseInt(u.join(""))}(e,i)),i===null&&(s=e),i}function Kr(){var i,e,l,u;return u=s,i=g(),i!==null?(e=g(),e!==null?(l=g(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Yr(){var i,e,l;for(l=s,i=[],e=oe(),e===null&&(e=N(),e===null&&(e=Se(),e===null&&(e=J(),e===null&&(e=F(),e===null&&(e=I(),e===null&&(e=H()))))));e!==null;)i.push(e),e=oe(),e===null&&(e=N(),e===null&&(e=Se(),e===null&&(e=J(),e===null&&(e=F(),e===null&&(e=I(),e===null&&(e=H()))))));return i!==null&&(i=function(u){b.reason_phrase=n.substring(s,u)}(l)),i===null&&(s=l),i}function Tl(){var i,e,l,u,f,p;if(f=s,i=on(),i!==null){for(e=[],p=s,l=Ce(),l!==null?(u=on(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=Ce(),l!==null?(u=on(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Ya(){var i,e,l,u,f,p;return u=s,f=s,i=st(),i!==null?(p=s,n.charCodeAt(s)===64?(e="@",s++):(e=null,h('"@"')),e!==null?(l=st(),l!==null?e=[e,l]:(e=null,s=p)):(e=null,s=p),e=e!==null?e:"",e!==null?i=[i,e]:(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(m){b=n.substring(s,m)}(u)),i===null&&(s=u),i}function Ja(){var i,e,l,u,f,p,m;if(f=s,i=ee(),i===null)if(p=s,i=$n(),i!==null){for(e=[],m=s,l=Ce(),l!==null?(u=$n(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;)e.push(l),m=s,l=Ce(),l!==null?(u=$n(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){var S,O;for(O=b.multi_header.length,S=0;S<O;S++)if(b.multi_header[S].parsed===null){b=null;break}b!==null?b=b.multi_header:b=-1}()),i===null&&(s=f),i}function $n(){var i,e,l,u,f,p,m;if(f=s,p=s,i=_e(),i===null&&(i=$t()),i!==null){for(e=[],m=s,l=le(),l!==null?(u=Us(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;)e.push(l),m=s,l=le(),l!==null?(u=Us(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){var S;b.multi_header||(b.multi_header=[]);try{S=new fs(b.uri,b.display_name,b.params),delete b.uri,delete b.display_name,delete b.params}catch{S=null}b.multi_header.push({possition:s,offset:v,parsed:S})}(f)),i===null&&(s=f),i}function $t(){var i,e,l,u,f;return f=s,i=Ht(),i=i!==null?i:"",i!==null?(e=xe(),e!==null?(l=we(),l!==null?(u=be(),u!==null?i=[i,e,l,u]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i}function Ht(){var i,e,l,u,f,p,m;if(f=s,p=s,i=U(),i!==null){for(e=[],m=s,l=ve(),l!==null?(u=U(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;)e.push(l),m=s,l=ve(),l!==null?(u=U(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i===null&&(i=Oe()),i!==null&&(i=function(v,S){typeof S=="string"?b.display_name=S:b.display_name=S[1].reduce(function(O,ie){return O+ie[0]+ie[1]},S[0])}(f,i)),i===null&&(s=f),i}function Us(){var i;return i=Hn(),i===null&&(i=Jr(),i===null&&(i=Ge())),i}function Hn(){var i,e,l,u,f;return u=s,f=s,n.substr(s,1).toLowerCase()==="q"?(i=n.substr(s,1),s++):(i=null,h('"q"')),i!==null?(e=G(),e!==null?(l=ss(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.params||(b.params={}),b.params.q=m}(u,i[2])),i===null&&(s=u),i}function Jr(){var i,e,l,u,f;return u=s,f=s,n.substr(s,7).toLowerCase()==="expires"?(i=n.substr(s,7),s+=7):(i=null,h('"expires"')),i!==null?(e=G(),e!==null?(l=ts(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.params||(b.params={}),b.params.expires=m}(u,i[2])),i===null&&(s=u),i}function ts(){var i,e,l;if(l=s,e=g(),e!==null)for(i=[];e!==null;)i.push(e),e=g();else i=null;return i!==null&&(i=function(u,f){return parseInt(f.join(""))}(l,i)),i===null&&(s=l),i}function ss(){var i,e,l,u,f,p,m,v;return p=s,m=s,n.charCodeAt(s)===48?(i="0",s++):(i=null,h('"0"')),i!==null?(v=s,n.charCodeAt(s)===46?(e=".",s++):(e=null,h('"."')),e!==null?(l=g(),l=l!==null?l:"",l!==null?(u=g(),u=u!==null?u:"",u!==null?(f=g(),f=f!==null?f:"",f!==null?e=[e,l,u,f]:(e=null,s=v)):(e=null,s=v)):(e=null,s=v)):(e=null,s=v),e=e!==null?e:"",e!==null?i=[i,e]:(i=null,s=m)):(i=null,s=m),i!==null&&(i=function(S){return parseFloat(n.substring(s,S))}(p)),i===null&&(s=p),i}function Ge(){var i,e,l,u,f,p;return u=s,f=s,i=U(),i!==null?(p=s,e=G(),e!==null?(l=We(),l!==null?e=[e,l]:(e=null,s=p)):(e=null,s=p),e=e!==null?e:"",e!==null?i=[i,e]:(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(m,v,S){b.params||(b.params={}),typeof S>"u"?S=void 0:S=S[1],b.params[v.toLowerCase()]=S}(u,i[0],i[1])),i===null&&(s=u),i}function We(){var i;return i=U(),i===null&&(i=es(),i===null&&(i=Ie())),i}function vl(){var i,e,l,u,f,p;if(f=s,i=El(),i!==null){for(e=[],p=s,l=le(),l!==null?(u=Fn(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=le(),l!==null?(u=Fn(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function El(){var i;return n.substr(s,6).toLowerCase()==="render"?(i=n.substr(s,6),s+=6):(i=null,h('"render"')),i===null&&(n.substr(s,7).toLowerCase()==="session"?(i=n.substr(s,7),s+=7):(i=null,h('"session"')),i===null&&(n.substr(s,4).toLowerCase()==="icon"?(i=n.substr(s,4),s+=4):(i=null,h('"icon"')),i===null&&(n.substr(s,5).toLowerCase()==="alert"?(i=n.substr(s,5),s+=5):(i=null,h('"alert"')),i===null&&(i=U())))),i}function Fn(){var i;return i=jn(),i===null&&(i=Ge()),i}function jn(){var i,e,l,u;return u=s,n.substr(s,8).toLowerCase()==="handling"?(i=n.substr(s,8),s+=8):(i=null,h('"handling"')),i!==null?(e=G(),e!==null?(n.substr(s,8).toLowerCase()==="optional"?(l=n.substr(s,8),s+=8):(l=null,h('"optional"')),l===null&&(n.substr(s,8).toLowerCase()==="required"?(l=n.substr(s,8),s+=8):(l=null,h('"required"')),l===null&&(l=U())),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Sl(){var i,e,l,u,f,p;if(f=s,i=U(),i!==null){for(e=[],p=s,l=Ce(),l!==null?(u=U(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=Ce(),l!==null?(u=U(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function za(){var i,e,l;if(l=s,e=g(),e!==null)for(i=[];e!==null;)i.push(e),e=g();else i=null;return i!==null&&(i=function(u,f){b=parseInt(f.join(""))}(l,i)),i===null&&(s=l),i}function Xa(){var i,e;return e=s,i=yl(),i!==null&&(i=function(l){b=n.substring(s,l)}(e)),i===null&&(s=e),i}function yl(){var i,e,l,u,f,p,m,v;if(m=s,i=zr(),i!==null)if(e=W(),e!==null)if(l=Zr(),l!==null){for(u=[],v=s,f=le(),f!==null?(p=qn(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);f!==null;)u.push(f),v=s,f=le(),f!==null?(p=qn(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);u!==null?i=[i,e,l,u]:(i=null,s=m)}else i=null,s=m;else i=null,s=m;else i=null,s=m;return i}function zr(){var i;return i=Xr(),i===null&&(i=Qr()),i}function Xr(){var i;return n.substr(s,4).toLowerCase()==="text"?(i=n.substr(s,4),s+=4):(i=null,h('"text"')),i===null&&(n.substr(s,5).toLowerCase()==="image"?(i=n.substr(s,5),s+=5):(i=null,h('"image"')),i===null&&(n.substr(s,5).toLowerCase()==="audio"?(i=n.substr(s,5),s+=5):(i=null,h('"audio"')),i===null&&(n.substr(s,5).toLowerCase()==="video"?(i=n.substr(s,5),s+=5):(i=null,h('"video"')),i===null&&(n.substr(s,11).toLowerCase()==="application"?(i=n.substr(s,11),s+=11):(i=null,h('"application"')),i===null&&(i=ln()))))),i}function Qr(){var i;return n.substr(s,7).toLowerCase()==="message"?(i=n.substr(s,7),s+=7):(i=null,h('"message"')),i===null&&(n.substr(s,9).toLowerCase()==="multipart"?(i=n.substr(s,9),s+=9):(i=null,h('"multipart"')),i===null&&(i=ln())),i}function ln(){var i;return i=U(),i===null&&(i=an()),i}function an(){var i,e,l;return l=s,n.substr(s,2).toLowerCase()==="x-"?(i=n.substr(s,2),s+=2):(i=null,h('"x-"')),i!==null?(e=U(),e!==null?i=[i,e]:(i=null,s=l)):(i=null,s=l),i}function Zr(){var i;return i=ln(),i===null&&(i=U()),i}function qn(){var i,e,l,u;return u=s,i=U(),i!==null?(e=G(),e!==null?(l=Vn(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Vn(){var i;return i=U(),i===null&&(i=Ie()),i}function Al(){var i,e,l,u;return u=s,i=Cl(),i!==null?(e=ve(),e!==null?(l=nn(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Cl(){var i,e,l;if(l=s,e=g(),e!==null)for(i=[];e!==null;)i.push(e),e=g();else i=null;return i!==null&&(i=function(u,f){b.value=parseInt(f.join(""))}(l,i)),i===null&&(s=l),i}function Rl(){var i,e;return e=s,i=ts(),i!==null&&(i=function(l,u){b=u}(e,i)),i===null&&(s=e),i}function Qa(){var i,e,l,u,f,p,m;if(f=s,p=s,i=on(),i!==null){for(e=[],m=s,l=le(),l!==null?(u=Ge(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;)e.push(l),m=s,l=le(),l!==null?(u=Ge(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v,S){b.event=S.join("").toLowerCase()}(f,i[0])),i===null&&(s=f),i}function on(){var i,e,l,u,f,p;if(f=s,i=P(),i!==null){for(e=[],p=s,n.charCodeAt(s)===46?(l=".",s++):(l=null,h('"."')),l!==null?(u=P(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,n.charCodeAt(s)===46?(l=".",s++):(l=null,h('"."')),l!==null?(u=P(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function un(){var i,e,l,u,f,p,m;if(f=s,p=s,i=_e(),i===null&&(i=$t()),i!==null){for(e=[],m=s,l=le(),l!==null?(u=ei(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;)e.push(l),m=s,l=le(),l!==null?(u=ei(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){var S=b.tag;try{b=new fs(b.uri,b.display_name,b.params),S&&b.setParam("tag",S)}catch{b=-1}}()),i===null&&(s=f),i}function ei(){var i;return i=cn(),i===null&&(i=Ge()),i}function cn(){var i,e,l,u,f;return u=s,f=s,n.substr(s,3).toLowerCase()==="tag"?(i=n.substr(s,3),s+=3):(i=null,h('"tag"')),i!==null?(e=G(),e!==null?(l=U(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.tag=m}(u,i[2])),i===null&&(s=u),i}function ti(){var i,e,l;if(l=s,e=g(),e!==null)for(i=[];e!==null;)i.push(e),e=g();else i=null;return i!==null&&(i=function(u,f){b=parseInt(f.join(""))}(l,i)),i===null&&(s=l),i}function Za(){var i,e;return e=s,i=ts(),i!==null&&(i=function(l,u){b=u}(e,i)),i===null&&(s=e),i}function eo(){var i,e,l,u,f,p,m,v,S,O;for(v=s,S=s,i=[],e=Ht();e!==null;)i.push(e),e=Ht();if(i!==null)if(e=xe(),e!==null)if(l=we(),l!==null)if(u=be(),u!==null){for(f=[],O=s,p=le(),p!==null?(m=Ge(),m!==null?p=[p,m]:(p=null,s=O)):(p=null,s=O);p!==null;)f.push(p),O=s,p=le(),p!==null?(m=Ge(),m!==null?p=[p,m]:(p=null,s=O)):(p=null,s=O);f!==null?i=[i,e,l,u,f]:(i=null,s=S)}else i=null,s=S;else i=null,s=S;else i=null,s=S;else i=null,s=S;return i!==null&&(i=function(ie){try{b=new fs(b.uri,b.display_name,b.params)}catch{b=-1}}()),i===null&&(s=v),i}function to(){var i;return i=si(),i}function si(){var i,e,l,u,f,p,m,v;if(m=s,n.substr(s,6).toLowerCase()==="digest"?(i=n.substr(s,6),s+=6):(i=null,h('"Digest"')),i!==null)if(e=ve(),e!==null)if(l=ns(),l!==null){for(u=[],v=s,f=Ce(),f!==null?(p=ns(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);f!==null;)u.push(f),v=s,f=Ce(),f!==null?(p=ns(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);u!==null?i=[i,e,l,u]:(i=null,s=m)}else i=null,s=m;else i=null,s=m;else i=null,s=m;return i===null&&(i=Bn()),i}function Bn(){var i,e,l,u,f,p,m,v;if(m=s,i=U(),i!==null)if(e=ve(),e!==null)if(l=Ps(),l!==null){for(u=[],v=s,f=Ce(),f!==null?(p=Ps(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);f!==null;)u.push(f),v=s,f=Ce(),f!==null?(p=Ps(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);u!==null?i=[i,e,l,u]:(i=null,s=m)}else i=null,s=m;else i=null,s=m;else i=null,s=m;return i}function Ps(){var i,e,l,u;return u=s,i=U(),i!==null?(e=G(),e!==null?(l=U(),l===null&&(l=Ie()),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function ns(){var i;return i=fn(),i===null&&(i=ri(),i===null&&(i=dn(),i===null&&(i=li(),i===null&&(i=ai(),i===null&&(i=oi(),i===null&&(i=ui(),i===null&&(i=Ps()))))))),i}function fn(){var i,e,l,u;return u=s,n.substr(s,5).toLowerCase()==="realm"?(i=n.substr(s,5),s+=5):(i=null,h('"realm"')),i!==null?(e=G(),e!==null?(l=ni(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function ni(){var i,e;return e=s,i=Oe(),i!==null&&(i=function(l,u){b.realm=u}(e,i)),i===null&&(s=e),i}function ri(){var i,e,l,u,f,p,m,v,S;if(v=s,n.substr(s,6).toLowerCase()==="domain"?(i=n.substr(s,6),s+=6):(i=null,h('"domain"')),i!==null)if(e=G(),e!==null)if(l=nt(),l!==null)if(u=hn(),u!==null){if(f=[],S=s,m=I(),m!==null)for(p=[];m!==null;)p.push(m),m=I();else p=null;for(p!==null?(m=hn(),m!==null?p=[p,m]:(p=null,s=S)):(p=null,s=S);p!==null;){if(f.push(p),S=s,m=I(),m!==null)for(p=[];m!==null;)p.push(m),m=I();else p=null;p!==null?(m=hn(),m!==null?p=[p,m]:(p=null,s=S)):(p=null,s=S)}f!==null?(p=at(),p!==null?i=[i,e,l,u,f,p]:(i=null,s=v)):(i=null,s=v)}else i=null,s=v;else i=null,s=v;else i=null,s=v;else i=null,s=v;return i}function hn(){var i;return i=xn(),i===null&&(i=en()),i}function dn(){var i,e,l,u;return u=s,n.substr(s,5).toLowerCase()==="nonce"?(i=n.substr(s,5),s+=5):(i=null,h('"nonce"')),i!==null?(e=G(),e!==null?(l=ii(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function ii(){var i,e;return e=s,i=Oe(),i!==null&&(i=function(l,u){b.nonce=u}(e,i)),i===null&&(s=e),i}function li(){var i,e,l,u,f;return u=s,f=s,n.substr(s,6).toLowerCase()==="opaque"?(i=n.substr(s,6),s+=6):(i=null,h('"opaque"')),i!==null?(e=G(),e!==null?(l=Oe(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.opaque=m}(u,i[2])),i===null&&(s=u),i}function ai(){var i,e,l,u,f;return u=s,n.substr(s,5).toLowerCase()==="stale"?(i=n.substr(s,5),s+=5):(i=null,h('"stale"')),i!==null?(e=G(),e!==null?(f=s,n.substr(s,4).toLowerCase()==="true"?(l=n.substr(s,4),s+=4):(l=null,h('"true"')),l!==null&&(l=function(p){b.stale=!0}()),l===null&&(s=f),l===null&&(f=s,n.substr(s,5).toLowerCase()==="false"?(l=n.substr(s,5),s+=5):(l=null,h('"false"')),l!==null&&(l=function(p){b.stale=!1}()),l===null&&(s=f)),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function oi(){var i,e,l,u,f;return u=s,f=s,n.substr(s,9).toLowerCase()==="algorithm"?(i=n.substr(s,9),s+=9):(i=null,h('"algorithm"')),i!==null?(e=G(),e!==null?(n.substr(s,3).toLowerCase()==="md5"?(l=n.substr(s,3),s+=3):(l=null,h('"MD5"')),l===null&&(n.substr(s,8).toLowerCase()==="md5-sess"?(l=n.substr(s,8),s+=8):(l=null,h('"MD5-sess"')),l===null&&(l=U())),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.algorithm=m.toUpperCase()}(u,i[2])),i===null&&(s=u),i}function ui(){var i,e,l,u,f,p,m,v,S,O;if(v=s,n.substr(s,3).toLowerCase()==="qop"?(i=n.substr(s,3),s+=3):(i=null,h('"qop"')),i!==null)if(e=G(),e!==null)if(l=nt(),l!==null){if(S=s,u=_n(),u!==null){for(f=[],O=s,n.charCodeAt(s)===44?(p=",",s++):(p=null,h('","')),p!==null?(m=_n(),m!==null?p=[p,m]:(p=null,s=O)):(p=null,s=O);p!==null;)f.push(p),O=s,n.charCodeAt(s)===44?(p=",",s++):(p=null,h('","')),p!==null?(m=_n(),m!==null?p=[p,m]:(p=null,s=O)):(p=null,s=O);f!==null?u=[u,f]:(u=null,s=S)}else u=null,s=S;u!==null?(f=at(),f!==null?i=[i,e,l,u,f]:(i=null,s=v)):(i=null,s=v)}else i=null,s=v;else i=null,s=v;else i=null,s=v;return i}function _n(){var i,e;return e=s,n.substr(s,8).toLowerCase()==="auth-int"?(i=n.substr(s,8),s+=8):(i=null,h('"auth-int"')),i===null&&(n.substr(s,4).toLowerCase()==="auth"?(i=n.substr(s,4),s+=4):(i=null,h('"auth"')),i===null&&(i=U())),i!==null&&(i=function(l,u){b.qop||(b.qop=[]),b.qop.push(u.toLowerCase())}(e,i)),i===null&&(s=e),i}function Gn(){var i,e,l,u,f,p;if(f=s,i=U(),i!==null){for(e=[],p=s,l=Ce(),l!==null?(u=U(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=Ce(),l!==null?(u=U(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function so(){var i,e,l,u,f,p,m;if(f=s,p=s,i=Wn(),i!==null){for(e=[],m=s,l=Ce(),l!==null?(u=Wn(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;)e.push(l),m=s,l=Ce(),l!==null?(u=Wn(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){var S,O;for(O=b.multi_header.length,S=0;S<O;S++)if(b.multi_header[S].parsed===null){b=null;break}b!==null?b=b.multi_header:b=-1}()),i===null&&(s=f),i}function Wn(){var i,e,l,u,f,p,m;if(f=s,p=s,i=$t(),i!==null){for(e=[],m=s,l=le(),l!==null?(u=Ge(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;)e.push(l),m=s,l=le(),l!==null?(u=Ge(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){var S;b.multi_header||(b.multi_header=[]);try{S=new fs(b.uri,b.display_name,b.params),delete b.uri,delete b.display_name,delete b.params}catch{S=null}b.multi_header.push({possition:s,offset:v,parsed:S})}(f)),i===null&&(s=f),i}function Kn(){var i,e,l,u,f,p,m;if(f=s,p=s,n.substr(s,3).toLowerCase()==="sip"?(i=n.substr(s,3),s+=3):(i=null,h('"SIP"')),i===null&&(i=U()),i!==null){for(e=[],m=s,l=le(),l!==null?(u=ci(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;)e.push(l),m=s,l=le(),l!==null?(u=ci(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v,S){if(b.protocol=S.toLowerCase(),b.params||(b.params={}),b.params.text&&b.params.text[0]==='"'){var O=b.params.text;b.text=O.substring(1,O.length-1),delete b.params.text}}(f,i[0])),i===null&&(s=f),i}function ci(){var i;return i=Yn(),i===null&&(i=Ge()),i}function Yn(){var i,e,l,u,f,p;if(f=s,p=s,n.substr(s,5).toLowerCase()==="cause"?(i=n.substr(s,5),s+=5):(i=null,h('"cause"')),i!==null)if(e=G(),e!==null){if(u=g(),u!==null)for(l=[];u!==null;)l.push(u),u=g();else l=null;l!==null?i=[i,e,l]:(i=null,s=p)}else i=null,s=p;else i=null,s=p;return i!==null&&(i=function(m,v){b.cause=parseInt(v.join(""))}(f,i[2])),i===null&&(s=f),i}function Il(){var i,e,l,u,f,p;if(f=s,i=U(),i!==null){for(e=[],p=s,l=Ce(),l!==null?(u=U(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=Ce(),l!==null?(u=U(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function no(){var i,e,l,u,f,p;if(f=s,i=Jn(),i!==null){for(e=[],p=s,l=Ce(),l!==null?(u=Jn(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=Ce(),l!==null?(u=Jn(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Jn(){var i,e,l,u,f,p;if(f=s,i=$t(),i!==null){for(e=[],p=s,l=le(),l!==null?(u=Ge(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=le(),l!==null?(u=Ge(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function zn(){var i,e,l,u,f,p;if(f=s,i=bl(),i!==null){for(e=[],p=s,l=le(),l!==null?(u=Xn(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=le(),l!==null?(u=Xn(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function bl(){var i,e;return e=s,n.substr(s,6).toLowerCase()==="active"?(i=n.substr(s,6),s+=6):(i=null,h('"active"')),i===null&&(n.substr(s,7).toLowerCase()==="pending"?(i=n.substr(s,7),s+=7):(i=null,h('"pending"')),i===null&&(n.substr(s,10).toLowerCase()==="terminated"?(i=n.substr(s,10),s+=10):(i=null,h('"terminated"')),i===null&&(i=U()))),i!==null&&(i=function(l){b.state=n.substring(s,l)}(e)),i===null&&(s=e),i}function Xn(){var i,e,l,u,f;return u=s,f=s,n.substr(s,6).toLowerCase()==="reason"?(i=n.substr(s,6),s+=6):(i=null,h('"reason"')),i!==null?(e=G(),e!==null?(l=Qn(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){typeof m<"u"&&(b.reason=m)}(u,i[2])),i===null&&(s=u),i===null&&(u=s,f=s,n.substr(s,7).toLowerCase()==="expires"?(i=n.substr(s,7),s+=7):(i=null,h('"expires"')),i!==null?(e=G(),e!==null?(l=ts(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){typeof m<"u"&&(b.expires=m)}(u,i[2])),i===null&&(s=u),i===null&&(u=s,f=s,n.substr(s,11).toLowerCase()==="retry_after"?(i=n.substr(s,11),s+=11):(i=null,h('"retry_after"')),i!==null?(e=G(),e!==null?(l=ts(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){typeof m<"u"&&(b.retry_after=m)}(u,i[2])),i===null&&(s=u),i===null&&(i=Ge()))),i}function Qn(){var i;return n.substr(s,11).toLowerCase()==="deactivated"?(i=n.substr(s,11),s+=11):(i=null,h('"deactivated"')),i===null&&(n.substr(s,9).toLowerCase()==="probation"?(i=n.substr(s,9),s+=9):(i=null,h('"probation"')),i===null&&(n.substr(s,8).toLowerCase()==="rejected"?(i=n.substr(s,8),s+=8):(i=null,h('"rejected"')),i===null&&(n.substr(s,7).toLowerCase()==="timeout"?(i=n.substr(s,7),s+=7):(i=null,h('"timeout"')),i===null&&(n.substr(s,6).toLowerCase()==="giveup"?(i=n.substr(s,6),s+=6):(i=null,h('"giveup"')),i===null&&(n.substr(s,10).toLowerCase()==="noresource"?(i=n.substr(s,10),s+=10):(i=null,h('"noresource"')),i===null&&(n.substr(s,9).toLowerCase()==="invariant"?(i=n.substr(s,9),s+=9):(i=null,h('"invariant"')),i===null&&(i=U()))))))),i}function wl(){var i;return i=B(),i=i!==null?i:"",i}function ro(){var i,e,l,u,f,p;if(f=s,i=U(),i!==null){for(e=[],p=s,l=Ce(),l!==null?(u=U(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=Ce(),l!==null?(u=U(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i=i!==null?i:"",i}function io(){var i,e,l,u,f,p,m;if(f=s,p=s,i=_e(),i===null&&(i=$t()),i!==null){for(e=[],m=s,l=le(),l!==null?(u=fi(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;)e.push(l),m=s,l=le(),l!==null?(u=fi(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){var S=b.tag;try{b=new fs(b.uri,b.display_name,b.params),S&&b.setParam("tag",S)}catch{b=-1}}()),i===null&&(s=f),i}function fi(){var i;return i=cn(),i===null&&(i=Ge()),i}function hi(){var i,e,l,u,f,p;if(f=s,i=Zn(),i!==null){for(e=[],p=s,l=Ce(),l!==null?(u=Zn(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=Ce(),l!==null?(u=Zn(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Zn(){var i,e,l,u,f,p,m,v;if(m=s,i=Ti(),i!==null)if(e=ve(),e!==null)if(l=Si(),l!==null){for(u=[],v=s,f=le(),f!==null?(p=xs(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);f!==null;)u.push(f),v=s,f=le(),f!==null?(p=xs(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);u!==null?i=[i,e,l,u]:(i=null,s=m)}else i=null,s=m;else i=null,s=m;else i=null,s=m;return i}function xs(){var i;return i=er(),i===null&&(i=di(),i===null&&(i=_i(),i===null&&(i=pi(),i===null&&(i=mi(),i===null&&(i=Ge()))))),i}function er(){var i,e,l,u,f;return u=s,f=s,n.substr(s,3).toLowerCase()==="ttl"?(i=n.substr(s,3),s+=3):(i=null,h('"ttl"')),i!==null?(e=G(),e!==null?(l=tr(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.ttl=m}(u,i[2])),i===null&&(s=u),i}function di(){var i,e,l,u,f;return u=s,f=s,n.substr(s,5).toLowerCase()==="maddr"?(i=n.substr(s,5),s+=5):(i=null,h('"maddr"')),i!==null?(e=G(),e!==null?(l=es(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.maddr=m}(u,i[2])),i===null&&(s=u),i}function _i(){var i,e,l,u,f;return u=s,f=s,n.substr(s,8).toLowerCase()==="received"?(i=n.substr(s,8),s+=8):(i=null,h('"received"')),i!==null?(e=G(),e!==null?(l=ot(),l===null&&(l=zs()),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.received=m}(u,i[2])),i===null&&(s=u),i}function pi(){var i,e,l,u,f;return u=s,f=s,n.substr(s,6).toLowerCase()==="branch"?(i=n.substr(s,6),s+=6):(i=null,h('"branch"')),i!==null?(e=G(),e!==null?(l=U(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.branch=m}(u,i[2])),i===null&&(s=u),i}function mi(){var i,e,l,u,f;return u=s,n.substr(s,5).toLowerCase()==="rport"?(i=n.substr(s,5),s+=5):(i=null,h('"rport"')),i!==null?(f=s,e=G(),e!==null?(l=gi(),l!==null?e=[e,l]:(e=null,s=f)):(e=null,s=f),e=e!==null?e:"",e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i}function gi(){var i,e,l,u,f,p,m;return p=s,m=s,i=g(),i=i!==null?i:"",i!==null?(e=g(),e=e!==null?e:"",e!==null?(l=g(),l=l!==null?l:"",l!==null?(u=g(),u=u!==null?u:"",u!==null?(f=g(),f=f!==null?f:"",f!==null?i=[i,e,l,u,f]:(i=null,s=m)):(i=null,s=m)):(i=null,s=m)):(i=null,s=m)):(i=null,s=m),i!==null&&(i=function(v,S){b.rport=parseInt(S.join(""))}(p,i)),i===null&&(s=p),i}function Ti(){var i,e,l,u,f,p;return p=s,i=vi(),i!==null?(e=W(),e!==null?(l=U(),l!==null?(u=W(),u!==null?(f=Ei(),f!==null?i=[i,e,l,u,f]:(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p),i}function vi(){var i,e;return e=s,n.substr(s,3).toLowerCase()==="sip"?(i=n.substr(s,3),s+=3):(i=null,h('"SIP"')),i===null&&(i=U()),i!==null&&(i=function(l,u){b.protocol=u}(e,i)),i===null&&(s=e),i}function Ei(){var i,e;return e=s,n.substr(s,3).toLowerCase()==="udp"?(i=n.substr(s,3),s+=3):(i=null,h('"UDP"')),i===null&&(n.substr(s,3).toLowerCase()==="tcp"?(i=n.substr(s,3),s+=3):(i=null,h('"TCP"')),i===null&&(n.substr(s,3).toLowerCase()==="tls"?(i=n.substr(s,3),s+=3):(i=null,h('"TLS"')),i===null&&(n.substr(s,4).toLowerCase()==="sctp"?(i=n.substr(s,4),s+=4):(i=null,h('"SCTP"')),i===null&&(i=U())))),i!==null&&(i=function(l,u){b.transport=u}(e,i)),i===null&&(s=e),i}function Si(){var i,e,l,u,f;return u=s,i=yi(),i!==null?(f=s,e=ye(),e!==null?(l=Ai(),l!==null?e=[e,l]:(e=null,s=f)):(e=null,s=f),e=e!==null?e:"",e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i}function yi(){var i,e;return e=s,i=ot(),i===null&&(i=Nn(),i===null&&(i=us())),i!==null&&(i=function(l){b.host=n.substring(s,l)}(e)),i===null&&(s=e),i}function Ai(){var i,e,l,u,f,p,m;return p=s,m=s,i=g(),i=i!==null?i:"",i!==null?(e=g(),e=e!==null?e:"",e!==null?(l=g(),l=l!==null?l:"",l!==null?(u=g(),u=u!==null?u:"",u!==null?(f=g(),f=f!==null?f:"",f!==null?i=[i,e,l,u,f]:(i=null,s=m)):(i=null,s=m)):(i=null,s=m)):(i=null,s=m)):(i=null,s=m),i!==null&&(i=function(v,S){b.port=parseInt(S.join(""))}(p,i)),i===null&&(s=p),i}function tr(){var i,e,l,u,f;return u=s,f=s,i=g(),i!==null?(e=g(),e=e!==null?e:"",e!==null?(l=g(),l=l!==null?l:"",l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){return parseInt(m.join(""))}(u,i)),i===null&&(s=u),i}function Ci(){var i;return i=si(),i}function lo(){var i,e,l,u,f,p;if(f=s,i=Ol(),i!==null){for(e=[],p=s,l=le(),l!==null?(u=sr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=le(),l!==null?(u=sr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Ol(){var i,e;return e=s,i=ts(),i!==null&&(i=function(l,u){b.expires=u}(e,i)),i===null&&(s=e),i}function sr(){var i;return i=nr(),i===null&&(i=Ge()),i}function nr(){var i,e,l,u,f;return u=s,f=s,n.substr(s,9).toLowerCase()==="refresher"?(i=n.substr(s,9),s+=9):(i=null,h('"refresher"')),i!==null?(e=G(),e!==null?(n.substr(s,3).toLowerCase()==="uac"?(l=n.substr(s,3),s+=3):(l=null,h('"uac"')),l===null&&(n.substr(s,3).toLowerCase()==="uas"?(l=n.substr(s,3),s+=3):(l=null,h('"uas"'))),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.refresher=m.toLowerCase()}(u,i[2])),i===null&&(s=u),i}function Dl(){var i,e,l,u;return u=s,i=U(),i!==null?(e=D(),e!==null?(l=Nl(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Nl(){var i,e;for(i=[],e=V(),e===null&&(e=F(),e===null&&(e=ve()));e!==null;)i.push(e),e=V(),e===null&&(e=F(),e===null&&(e=ve()));return i}function Ul(){var i,e;for(i=[],e=A();e!==null;)i.push(e),e=A();return i}function ao(){var i,e,l;return l=s,n.substr(s,5)==="uuid:"?(i="uuid:",s+=5):(i=null,h('"uuid:"')),i!==null?(e=Pl(),e!==null?i=[i,e]:(i=null,s=l)):(i=null,s=l),i}function Pl(){var i,e,l,u,f,p,m,v,S,O,ie;return O=s,ie=s,i=jt(),i!==null?(n.charCodeAt(s)===45?(e="-",s++):(e=null,h('"-"')),e!==null?(l=Ft(),l!==null?(n.charCodeAt(s)===45?(u="-",s++):(u=null,h('"-"')),u!==null?(f=Ft(),f!==null?(n.charCodeAt(s)===45?(p="-",s++):(p=null,h('"-"')),p!==null?(m=Ft(),m!==null?(n.charCodeAt(s)===45?(v="-",s++):(v=null,h('"-"')),v!==null?(S=Ri(),S!==null?i=[i,e,l,u,f,p,m,v,S]:(i=null,s=ie)):(i=null,s=ie)):(i=null,s=ie)):(i=null,s=ie)):(i=null,s=ie)):(i=null,s=ie)):(i=null,s=ie)):(i=null,s=ie)):(i=null,s=ie),i!==null&&(i=function(Ue,wt){b=n.substring(s+5,Ue)}(O,i[0])),i===null&&(s=O),i}function Ft(){var i,e,l,u,f;return f=s,i=E(),i!==null?(e=E(),e!==null?(l=E(),l!==null?(u=E(),u!==null?i=[i,e,l,u]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i}function jt(){var i,e,l;return l=s,i=Ft(),i!==null?(e=Ft(),e!==null?i=[i,e]:(i=null,s=l)):(i=null,s=l),i}function Ri(){var i,e,l,u;return u=s,i=Ft(),i!==null?(e=Ft(),e!==null?(l=Ft(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function xl(){var i,e,l,u,f,p,m;if(f=s,p=s,i=_e(),i===null&&(i=$t()),i!==null){for(e=[],m=s,l=le(),l!==null?(u=Ge(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;)e.push(l),m=s,l=le(),l!==null?(u=Ge(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){try{b=new fs(b.uri,b.display_name,b.params)}catch{b=-1}}()),i===null&&(s=f),i}function oo(){var i,e,l,u,f,p;if(f=s,i=kl(),i!==null){for(e=[],p=s,l=le(),l!==null?(u=rr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=le(),l!==null?(u=rr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function kl(){var i,e,l,u,f,p;return u=s,f=s,i=st(),i!==null?(p=s,n.charCodeAt(s)===64?(e="@",s++):(e=null,h('"@"')),e!==null?(l=st(),l!==null?e=[e,l]:(e=null,s=p)):(e=null,s=p),e=e!==null?e:"",e!==null?i=[i,e]:(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(m){b.call_id=n.substring(s,m)}(u)),i===null&&(s=u),i}function rr(){var i;return i=ir(),i===null&&(i=Ii(),i===null&&(i=bi(),i===null&&(i=Ge()))),i}function ir(){var i,e,l,u,f;return u=s,f=s,n.substr(s,6)==="to-tag"?(i="to-tag",s+=6):(i=null,h('"to-tag"')),i!==null?(e=G(),e!==null?(l=U(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.to_tag=m}(u,i[2])),i===null&&(s=u),i}function Ii(){var i,e,l,u,f;return u=s,f=s,n.substr(s,8)==="from-tag"?(i="from-tag",s+=8):(i=null,h('"from-tag"')),i!==null?(e=G(),e!==null?(l=U(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.from_tag=m}(u,i[2])),i===null&&(s=u),i}function bi(){var i,e;return e=s,n.substr(s,10)==="early-only"?(i="early-only",s+=10):(i=null,h('"early-only"')),i!==null&&(i=function(l){b.early_only=!0}()),i===null&&(s=e),i}function Ml(i){i.sort();for(var e=null,l=[],u=0;u<i.length;u++)i[u]!==e&&(l.push(i[u]),e=i[u]);return l}function uo(){for(var i=1,e=1,l=!1,u=0;u<Math.max(s,r);u++){var f=n.charAt(u);f===`
|
75
75
|
`?(l||i++,e=1,l=!1):f==="\r"||f==="\u2028"||f==="\u2029"?(i++,e=1,l=!0):(e++,l=!1)}return{line:i,column:e}}var Ll=ys(),fs=$u(),b={},w=o[a]();if(w===null||s!==n.length){var wi=Math.max(s,r),Oi=wi<n.length?n.charAt(wi):null,$l=uo();return new this.SyntaxError(Ml(d),Oi,wi,$l.line,$l.column),-1}return b},toSource:function(){return this._source}};return t.SyntaxError=function(n,a,o,s,r){function d(h,_){var g,T;switch(h.length){case 0:g="end of input";break;case 1:g=h[0];break;default:g=h.slice(0,h.length-1).join(", ")+" or "+h[h.length-1]}return T=_?c(_):"end of input","Expected "+g+" but "+T+" found."}this.name="SyntaxError",this.expected=n,this.found=a,this.message=d(n,a),this.offset=o,this.line=s,this.column=r},t.SyntaxError.prototype=Error.prototype,t}()),ko}var Mo,sf;function ys(){if(sf)return Mo;sf=1;const c=De,t=At(),n=Zt();return Mo=class ch{static parse(o){if(o=n.parse(o,"SIP_URI"),o!==-1)return o}constructor(o,s,r,d,h={},_={}){if(!r)throw new TypeError('missing or invalid "host" parameter');this._parameters={},this._headers={},this._scheme=o||c.SIP,this._user=s,this._host=r,this._port=d;for(const g in h)Object.prototype.hasOwnProperty.call(h,g)&&this.setParam(g,h[g]);for(const g in _)Object.prototype.hasOwnProperty.call(_,g)&&this.setHeader(g,_[g])}get scheme(){return this._scheme}set scheme(o){this._scheme=o.toLowerCase()}get user(){return this._user}set user(o){this._user=o}get host(){return this._host}set host(o){this._host=o.toLowerCase()}get port(){return this._port}set port(o){this._port=o===0?o:parseInt(o,10)||null}setParam(o,s){o&&(this._parameters[o.toLowerCase()]=typeof s>"u"||s===null?null:s.toString())}getParam(o){if(o)return this._parameters[o.toLowerCase()]}hasParam(o){if(o)return this._parameters.hasOwnProperty(o.toLowerCase())&&!0||!1}deleteParam(o){if(o=o.toLowerCase(),this._parameters.hasOwnProperty(o)){const s=this._parameters[o];return delete this._parameters[o],s}}clearParams(){this._parameters={}}setHeader(o,s){this._headers[t.headerize(o)]=Array.isArray(s)?s:[s]}getHeader(o){if(o)return this._headers[t.headerize(o)]}hasHeader(o){if(o)return this._headers.hasOwnProperty(t.headerize(o))&&!0||!1}deleteHeader(o){if(o=t.headerize(o),this._headers.hasOwnProperty(o)){const s=this._headers[o];return delete this._headers[o],s}}clearHeaders(){this._headers={}}clone(){return new ch(this._scheme,this._user,this._host,this._port,JSON.parse(JSON.stringify(this._parameters)),JSON.parse(JSON.stringify(this._headers)))}toString(){const o=[];let s=`${this._scheme}:`;this._user&&(s+=`${t.escapeUser(this._user)}@`),s+=this._host,(this._port||this._port===0)&&(s+=`:${this._port}`);for(const r in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,r)&&(s+=`;${r}`,this._parameters[r]!==null&&(s+=`=${this._parameters[r]}`));for(const r in this._headers)if(Object.prototype.hasOwnProperty.call(this._headers,r))for(const d of this._headers[r])o.push(`${r}=${d}`);return o.length>0&&(s+=`?${o.join("&")}`),s}toAor(o){let s=`${this._scheme}:`;return this._user&&(s+=`${t.escapeUser(this._user)}@`),s+=this._host,o&&(this._port||this._port===0)&&(s+=`:${this._port}`),s}},Mo}var nf;function At(){if(nf)return et;nf=1;const c=De,t=ys(),n=Zt();et.str_utf8_length=r=>unescape(encodeURIComponent(r)).length;const a=et.isFunction=r=>r!==void 0?Object.prototype.toString.call(r)==="[object Function]":!1;et.isString=r=>r!==void 0?Object.prototype.toString.call(r)==="[object String]":!1,et.isDecimal=r=>!isNaN(r)&&parseFloat(r)===parseInt(r,10),et.isEmpty=r=>r===null||r===""||r===void 0||Array.isArray(r)&&r.length===0||typeof r=="number"&&isNaN(r),et.hasMethods=function(r,...d){for(const h of d)if(a(r[h]))return!1;return!0};const o=et.createRandomToken=(r,d=32)=>{let h,_,g="";for(h=0;h<r;h++)_=Math.random()*d|0,g+=_.toString(d);return g};et.newTag=()=>o(10),et.newUUID=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,d=>{const h=Math.random()*16|0;return(d==="x"?h:h&3|8).toString(16)}),et.hostType=r=>{if(r){if(r=n.parse(r,"host"),r!==-1)return r.host_type}else return};const s=et.escapeUser=r=>encodeURIComponent(decodeURIComponent(r)).replace(/%3A/ig,":").replace(/%2B/ig,"+").replace(/%3F/ig,"?").replace(/%2F/ig,"/");return et.normalizeTarget=(r,d)=>{if(r){if(r instanceof t)return r;if(typeof r=="string"){const h=r.split("@");let _,g;switch(h.length){case 1:if(!d)return;_=r,g=d;break;case 2:_=h[0],g=h[1];break;default:_=h.slice(0,h.length-1).join("@"),g=h[h.length-1]}_=_.replace(/^(sips?|tel):/i,""),/^[-.()]*\+?[0-9\-.()]+$/.test(_)&&(_=_.replace(/[-.()]/g,"")),r=`${c.SIP}:${s(_)}@${g}`;let T;return(T=t.parse(r))?T:void 0}else return}else return},et.headerize=r=>{const d={"Call-Id":"Call-ID",Cseq:"CSeq","Www-Authenticate":"WWW-Authenticate"},h=r.toLowerCase().replace(/_/g,"-").split("-");let _="";const g=h.length;let T;for(T=0;T<g;T++)T!==0&&(_+="-"),_+=h[T].charAt(0).toUpperCase()+h[T].substring(1);return d[_]&&(_=d[_]),_},et.sipErrorCause=r=>{for(const d in c.SIP_ERROR_CAUSES)if(c.SIP_ERROR_CAUSES[d].indexOf(r)!==-1)return c.causes[d];return c.causes.SIP_FAILURE_CODE},et.getRandomTestNetIP=()=>{function r(d,h){return Math.floor(Math.random()*(h-d+1)+d)}return`192.0.2.${r(1,254)}`},et.calculateMD5=r=>{function d(Ee,Ae){return Ee<<Ae|Ee>>>32-Ae}function h(Ee,Ae){const Ie=Ee&2147483648,Oe=Ae&2147483648,pe=Ee&1073741824,ue=Ae&1073741824,_e=(Ee&1073741823)+(Ae&1073741823);return pe&ue?_e^2147483648^Ie^Oe:pe|ue?_e&1073741824?_e^3221225472^Ie^Oe:_e^1073741824^Ie^Oe:_e^Ie^Oe}function _(Ee,Ae,Ie){return Ee&Ae|~Ee&Ie}function g(Ee,Ae,Ie){return Ee&Ie|Ae&~Ie}function T(Ee,Ae,Ie){return Ee^Ae^Ie}function E(Ee,Ae,Ie){return Ae^(Ee|~Ie)}function y(Ee,Ae,Ie,Oe,pe,ue,_e){return Ee=h(Ee,h(h(_(Ae,Ie,Oe),pe),_e)),h(d(Ee,ue),Ae)}function A(Ee,Ae,Ie,Oe,pe,ue,_e){return Ee=h(Ee,h(h(g(Ae,Ie,Oe),pe),_e)),h(d(Ee,ue),Ae)}function C(Ee,Ae,Ie,Oe,pe,ue,_e){return Ee=h(Ee,h(h(T(Ae,Ie,Oe),pe),_e)),h(d(Ee,ue),Ae)}function I(Ee,Ae,Ie,Oe,pe,ue,_e){return Ee=h(Ee,h(h(E(Ae,Ie,Oe),pe),_e)),h(d(Ee,ue),Ae)}function H(Ee){let Ae;const Ie=Ee.length,Oe=Ie+8,ue=((Oe-Oe%64)/64+1)*16,_e=new Array(ue-1);let we=0,Ne=0;for(;Ne<Ie;)Ae=(Ne-Ne%4)/4,we=Ne%4*8,_e[Ae]=_e[Ae]|Ee.charCodeAt(Ne)<<we,Ne++;return Ae=(Ne-Ne%4)/4,we=Ne%4*8,_e[Ae]=_e[Ae]|128<<we,_e[ue-2]=Ie<<3,_e[ue-1]=Ie>>>29,_e}function $(Ee){let Ae="",Ie="",Oe,pe;for(pe=0;pe<=3;pe++)Oe=Ee>>>pe*8&255,Ie=`0${Oe.toString(16)}`,Ae=Ae+Ie.substr(Ie.length-2,2);return Ae}function oe(Ee){let Ae="";for(let Ie=0;Ie<Ee.length;Ie++){const Oe=Ee.charCodeAt(Ie);Oe<128?Ae+=String.fromCharCode(Oe):Oe>127&&Oe<2048?(Ae+=String.fromCharCode(Oe>>6|192),Ae+=String.fromCharCode(Oe&63|128)):(Ae+=String.fromCharCode(Oe>>12|224),Ae+=String.fromCharCode(Oe>>6&63|128),Ae+=String.fromCharCode(Oe&63|128))}return Ae}let N=[],j,Se,ve,k,D,B,V,J,F;const X=7,U=12,P=17,se=22,st=5,ee=9,W=14,G=20,re=4,ge=11,be=16,xe=23,Ce=6,le=10,ye=15,nt=21;for(r=oe(r),N=H(r),B=1732584193,V=4023233417,J=2562383102,F=271733878,j=0;j<N.length;j+=16)Se=B,ve=V,k=J,D=F,B=y(B,V,J,F,N[j+0],X,3614090360),F=y(F,B,V,J,N[j+1],U,3905402710),J=y(J,F,B,V,N[j+2],P,606105819),V=y(V,J,F,B,N[j+3],se,3250441966),B=y(B,V,J,F,N[j+4],X,4118548399),F=y(F,B,V,J,N[j+5],U,1200080426),J=y(J,F,B,V,N[j+6],P,2821735955),V=y(V,J,F,B,N[j+7],se,4249261313),B=y(B,V,J,F,N[j+8],X,1770035416),F=y(F,B,V,J,N[j+9],U,2336552879),J=y(J,F,B,V,N[j+10],P,4294925233),V=y(V,J,F,B,N[j+11],se,2304563134),B=y(B,V,J,F,N[j+12],X,1804603682),F=y(F,B,V,J,N[j+13],U,4254626195),J=y(J,F,B,V,N[j+14],P,2792965006),V=y(V,J,F,B,N[j+15],se,1236535329),B=A(B,V,J,F,N[j+1],st,4129170786),F=A(F,B,V,J,N[j+6],ee,3225465664),J=A(J,F,B,V,N[j+11],W,643717713),V=A(V,J,F,B,N[j+0],G,3921069994),B=A(B,V,J,F,N[j+5],st,3593408605),F=A(F,B,V,J,N[j+10],ee,38016083),J=A(J,F,B,V,N[j+15],W,3634488961),V=A(V,J,F,B,N[j+4],G,3889429448),B=A(B,V,J,F,N[j+9],st,568446438),F=A(F,B,V,J,N[j+14],ee,3275163606),J=A(J,F,B,V,N[j+3],W,4107603335),V=A(V,J,F,B,N[j+8],G,1163531501),B=A(B,V,J,F,N[j+13],st,2850285829),F=A(F,B,V,J,N[j+2],ee,4243563512),J=A(J,F,B,V,N[j+7],W,1735328473),V=A(V,J,F,B,N[j+12],G,2368359562),B=C(B,V,J,F,N[j+5],re,4294588738),F=C(F,B,V,J,N[j+8],ge,2272392833),J=C(J,F,B,V,N[j+11],be,1839030562),V=C(V,J,F,B,N[j+14],xe,4259657740),B=C(B,V,J,F,N[j+1],re,2763975236),F=C(F,B,V,J,N[j+4],ge,1272893353),J=C(J,F,B,V,N[j+7],be,4139469664),V=C(V,J,F,B,N[j+10],xe,3200236656),B=C(B,V,J,F,N[j+13],re,681279174),F=C(F,B,V,J,N[j+0],ge,3936430074),J=C(J,F,B,V,N[j+3],be,3572445317),V=C(V,J,F,B,N[j+6],xe,76029189),B=C(B,V,J,F,N[j+9],re,3654602809),F=C(F,B,V,J,N[j+12],ge,3873151461),J=C(J,F,B,V,N[j+15],be,530742520),V=C(V,J,F,B,N[j+2],xe,3299628645),B=I(B,V,J,F,N[j+0],Ce,4096336452),F=I(F,B,V,J,N[j+7],le,1126891415),J=I(J,F,B,V,N[j+14],ye,2878612391),V=I(V,J,F,B,N[j+5],nt,4237533241),B=I(B,V,J,F,N[j+12],Ce,1700485571),F=I(F,B,V,J,N[j+3],le,2399980690),J=I(J,F,B,V,N[j+10],ye,4293915773),V=I(V,J,F,B,N[j+1],nt,2240044497),B=I(B,V,J,F,N[j+8],Ce,1873313359),F=I(F,B,V,J,N[j+15],le,4264355552),J=I(J,F,B,V,N[j+6],ye,2734768916),V=I(V,J,F,B,N[j+13],nt,1309151649),B=I(B,V,J,F,N[j+4],Ce,4149444226),F=I(F,B,V,J,N[j+11],le,3174756917),J=I(J,F,B,V,N[j+2],ye,718787259),V=I(V,J,F,B,N[j+9],nt,3951481745),B=h(B,Se),V=h(V,ve),J=h(J,k),F=h(F,D);return($(B)+$(V)+$(J)+$(F)).toLowerCase()},et.closeMediaStream=r=>{if(r)try{let d;if(r.getTracks){d=r.getTracks();for(const h of d)h.stop()}else{d=r.getAudioTracks();for(const h of d)h.stop();d=r.getVideoTracks();for(const h of d)h.stop()}}catch{(typeof r.stop=="function"||typeof r.stop=="object")&&r.stop()}},et.cloneArray=r=>r&&r.slice()||[],et.cloneObject=(r,d={})=>r&&Object.assign({},r)||d,et}const fh=xt,qm=ut,St=De,it=At(),rf=$u(),Vm=Zt(),Lo=new qm("SIPMessage");class Wa{constructor(t,n,a,o,s,r){if(!t||!n||!a)return null;o=o||{},this.ua=a,this.headers={},this.method=t,this.ruri=n,this.body=r,this.extraHeaders=it.cloneArray(s),this.ua.configuration.extra_headers&&(this.extraHeaders=this.extraHeaders.concat(this.ua.configuration.extra_headers)),o.route_set?this.setHeader("route",o.route_set):a.configuration.use_preloaded_route&&this.setHeader("route",`<${a.transport.sip_uri};lr>`),this.setHeader("via",""),this.setHeader("max-forwards",St.MAX_FORWARDS);const d=o.to_uri||n,h=o.to_tag?{tag:o.to_tag}:null,_=typeof o.to_display_name<"u"?o.to_display_name:null;this.to=new rf(d,_,h),this.setHeader("to",this.to.toString());const g=o.from_uri||a.configuration.uri,T={tag:o.from_tag||it.newTag()};let E;typeof o.from_display_name<"u"?E=o.from_display_name:a.configuration.display_name?E=a.configuration.display_name:E=null,this.from=new rf(g,E,T),this.setHeader("from",this.from.toString());const y=o.call_id||a.configuration.jssip_id+it.createRandomToken(15);this.call_id=y,this.setHeader("call-id",y);const A=o.cseq||Math.floor(Math.random()*1e4);this.cseq=A,this.setHeader("cseq",`${A} ${t}`)}setHeader(t,n){const a=new RegExp(`^\\s*${t}\\s*:`,"i");for(let o=0;o<this.extraHeaders.length;o++)a.test(this.extraHeaders[o])&&this.extraHeaders.splice(o,1);this.headers[it.headerize(t)]=Array.isArray(n)?n:[n]}getHeader(t){const n=this.headers[it.headerize(t)];if(n){if(n[0])return n[0]}else{const a=new RegExp(`^\\s*${t}\\s*:`,"i");for(const o of this.extraHeaders)if(a.test(o))return o.substring(o.indexOf(":")+1).trim()}}getHeaders(t){const n=this.headers[it.headerize(t)],a=[];if(n){for(const o of n)a.push(o);return a}else{const o=new RegExp(`^\\s*${t}\\s*:`,"i");for(const s of this.extraHeaders)o.test(s)&&a.push(s.substring(s.indexOf(":")+1).trim());return a}}hasHeader(t){if(this.headers[it.headerize(t)])return!0;{const n=new RegExp(`^\\s*${t}\\s*:`,"i");for(const a of this.extraHeaders)if(n.test(a))return!0}return!1}parseSDP(t){return!t&&this.sdp?this.sdp:(this.sdp=fh.parse(this.body||""),this.sdp)}toString(){let t=`${this.method} ${this.ruri} SIP/2.0\r
|
@@ -124,14 +124,14 @@ ${t}
|
|
124
124
|
${t}
|
125
125
|
`);this.ondata({transport:this,message:t})}};const eT=ze(yh);var Ah={};const tT=ut,Cu=Zt(),Ru=yt,ia=new tT("Parser");Ah.parseMessage=(c,t)=>{let n,a,o=c.indexOf(`\r
|
126
126
|
`);if(o===-1){ia.warn("parseMessage() | no CRLF found, not a SIP message");return}const s=c.substring(0,o);let r=Cu.parse(s,"Request_Response");if(r===-1){ia.warn(`parseMessage() | error parsing first line of SIP message: "${s}"`);return}else r.status_code?(n=new Ru.IncomingResponse,n.status_code=r.status_code,n.reason_phrase=r.reason_phrase):(n=new Ru.IncomingRequest(t),n.method=r.method,n.ruri=r.uri);n.data=c;let d=o+2;for(;;){if(o=sT(c,d),o===-2){a=d+2;break}else if(o===-1){ia.warn("parseMessage() | malformed message");return}if(r=nT(n,c,d,o),r!==!0){ia.warn("parseMessage() |",r.error);return}d=o+2}if(n.hasHeader("content-length")){const h=n.getHeader("content-length");n.body=c.substr(a,h)}else n.body=c.substring(a);return n};function sT(c,t){let n=t,a=0,o=0;if(c.substring(n,n+2).match(/(^\r\n)/))return-2;for(;a===0;){if(o=c.indexOf(`\r
|
127
|
-
`,n),o===-1)return o;!c.substring(o+2,o+4).match(/(^\r\n)/)&&c.charAt(o+2).match(/(^\s+)/)?n=o+2:a=o}return a}function nT(c,t,n,a){let o;const s=t.indexOf(":",n),r=t.substring(n,s).trim(),d=t.substring(s+1,a).trim();switch(r.toLowerCase()){case"via":case"v":c.addHeader("via",d),c.getHeaders("via").length===1?(o=c.parseHeader("Via"),o&&(c.via=o,c.via_branch=o.branch)):o=0;break;case"from":case"f":c.setHeader("from",d),o=c.parseHeader("from"),o&&(c.from=o,c.from_tag=o.getParam("tag"));break;case"to":case"t":c.setHeader("to",d),o=c.parseHeader("to"),o&&(c.to=o,c.to_tag=o.getParam("tag"));break;case"record-route":if(o=Cu.parse(d,"Record_Route"),o===-1)o=void 0;else for(const h of o)c.addHeader("record-route",d.substring(h.possition,h.offset)),c.headers["Record-Route"][c.getHeaders("record-route").length-1].parsed=h.parsed;break;case"call-id":case"i":c.setHeader("call-id",d),o=c.parseHeader("call-id"),o&&(c.call_id=d);break;case"contact":case"m":if(o=Cu.parse(d,"Contact"),o===-1)o=void 0;else for(const h of o)c.addHeader("contact",d.substring(h.possition,h.offset)),c.headers.Contact[c.getHeaders("contact").length-1].parsed=h.parsed;break;case"content-length":case"l":c.setHeader("content-length",d),o=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",d),o=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",d),o=c.parseHeader("cseq"),o&&(c.cseq=o.value),c instanceof Ru.IncomingResponse&&(c.method=o.method);break;case"max-forwards":c.setHeader("max-forwards",d),o=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",d),o=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",d),o=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",d),o=c.parseHeader("session-expires"),o&&(c.session_expires=o.expires,c.session_expires_refresher=o.refresher);break;case"refer-to":case"r":c.setHeader("refer-to",d),o=c.parseHeader("refer-to"),o&&(c.refer_to=o);break;case"replaces":c.setHeader("replaces",d),o=c.parseHeader("replaces"),o&&(c.replaces=o);break;case"event":case"o":c.setHeader("event",d),o=c.parseHeader("event"),o&&(c.event=o);break;default:c.addHeader(r,d),o=0}return o===void 0?{error:`error parsing header "${r}"`}:!0}const rT=ut,Ch=De,Cf=yt,Vu=At(),Bu=new rT("sanityCheck"),iT=[_T],lT=[oT,uT,cT,fT],aT=[hT,dT];let
|
127
|
+
`,n),o===-1)return o;!c.substring(o+2,o+4).match(/(^\r\n)/)&&c.charAt(o+2).match(/(^\s+)/)?n=o+2:a=o}return a}function nT(c,t,n,a){let o;const s=t.indexOf(":",n),r=t.substring(n,s).trim(),d=t.substring(s+1,a).trim();switch(r.toLowerCase()){case"via":case"v":c.addHeader("via",d),c.getHeaders("via").length===1?(o=c.parseHeader("Via"),o&&(c.via=o,c.via_branch=o.branch)):o=0;break;case"from":case"f":c.setHeader("from",d),o=c.parseHeader("from"),o&&(c.from=o,c.from_tag=o.getParam("tag"));break;case"to":case"t":c.setHeader("to",d),o=c.parseHeader("to"),o&&(c.to=o,c.to_tag=o.getParam("tag"));break;case"record-route":if(o=Cu.parse(d,"Record_Route"),o===-1)o=void 0;else for(const h of o)c.addHeader("record-route",d.substring(h.possition,h.offset)),c.headers["Record-Route"][c.getHeaders("record-route").length-1].parsed=h.parsed;break;case"call-id":case"i":c.setHeader("call-id",d),o=c.parseHeader("call-id"),o&&(c.call_id=d);break;case"contact":case"m":if(o=Cu.parse(d,"Contact"),o===-1)o=void 0;else for(const h of o)c.addHeader("contact",d.substring(h.possition,h.offset)),c.headers.Contact[c.getHeaders("contact").length-1].parsed=h.parsed;break;case"content-length":case"l":c.setHeader("content-length",d),o=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",d),o=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",d),o=c.parseHeader("cseq"),o&&(c.cseq=o.value),c instanceof Ru.IncomingResponse&&(c.method=o.method);break;case"max-forwards":c.setHeader("max-forwards",d),o=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",d),o=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",d),o=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",d),o=c.parseHeader("session-expires"),o&&(c.session_expires=o.expires,c.session_expires_refresher=o.refresher);break;case"refer-to":case"r":c.setHeader("refer-to",d),o=c.parseHeader("refer-to"),o&&(c.refer_to=o);break;case"replaces":c.setHeader("replaces",d),o=c.parseHeader("replaces"),o&&(c.replaces=o);break;case"event":case"o":c.setHeader("event",d),o=c.parseHeader("event"),o&&(c.event=o);break;default:c.addHeader(r,d),o=0}return o===void 0?{error:`error parsing header "${r}"`}:!0}const rT=ut,Ch=De,Cf=yt,Vu=At(),Bu=new rT("sanityCheck"),iT=[_T],lT=[oT,uT,cT,fT],aT=[hT,dT];let je,is,Rh;var Ih=(c,t,n)=>{je=c,is=t,Rh=n;for(const a of iT)if(a()===!1)return!1;if(je instanceof Cf.IncomingRequest){for(const a of lT)if(a()===!1)return!1}else if(je instanceof Cf.IncomingResponse){for(const a of aT)if(a()===!1)return!1}return!0};function oT(){if(je.s("to").uri.scheme!=="sip")return nl(416),!1}function uT(){if(!je.to_tag&&je.call_id.substr(0,5)===is.configuration.jssip_id)return nl(482),!1}function cT(){const c=Vu.str_utf8_length(je.body),t=je.getHeader("content-length");if(c<t)return nl(400),!1}function fT(){const c=je.from_tag,t=je.call_id,n=je.cseq;let a;if(!je.to_tag)if(je.method===Ch.INVITE){if(is._transactions.ist[je.via_branch])return!1;for(const o in is._transactions.ist)if(Object.prototype.hasOwnProperty.call(is._transactions.ist,o)&&(a=is._transactions.ist[o],a.request.from_tag===c&&a.request.call_id===t&&a.request.cseq===n))return nl(482),!1}else{if(is._transactions.nist[je.via_branch])return!1;for(const o in is._transactions.nist)if(Object.prototype.hasOwnProperty.call(is._transactions.nist,o)&&(a=is._transactions.nist[o],a.request.from_tag===c&&a.request.call_id===t&&a.request.cseq===n))return nl(482),!1}}function hT(){if(je.getHeaders("via").length>1)return Bu.debug("more than one Via header field present in the response, dropping the response"),!1}function dT(){const c=Vu.str_utf8_length(je.body),t=je.getHeader("content-length");if(c<t)return Bu.debug("message body length is lower than the value in Content-Length header field, dropping the response"),!1}function _T(){const c=["from","to","call_id","cseq","via"];for(const t of c)if(!je.hasHeader(t))return Bu.debug(`missing mandatory header field : ${t}, dropping the response`),!1}function nl(c){const t=je.getHeaders("via");let n,a=`SIP/2.0 ${c} ${Ch.REASON_PHRASE[c]}\r
|
128
128
|
`;for(const o of t)a+=`Via: ${o}\r
|
129
|
-
`;n=
|
130
|
-
`,a+=`From: ${
|
131
|
-
`,a+=`Call-ID: ${
|
132
|
-
`,a+=`CSeq: ${
|
129
|
+
`;n=je.getHeader("To"),je.to_tag||(n+=`;tag=${Vu.newTag()}`),a+=`To: ${n}\r
|
130
|
+
`,a+=`From: ${je.getHeader("From")}\r
|
131
|
+
`,a+=`Call-ID: ${je.call_id}\r
|
132
|
+
`,a+=`CSeq: ${je.cseq} ${je.method}\r
|
133
133
|
`,a+=`\r
|
134
|
-
`,Rh.send(a)}const pT=ze(Ih);var rl={};const hr=At(),An=De,Jo=Zt(),Rf=ys(),zo=qu,Xo=As;rl.settings={authorization_user:null,password:null,realm:null,ha1:null,authorization_jwt:null,display_name:null,uri:null,contact_uri:null,instance_id:null,use_preloaded_route:!1,session_timers:!0,session_timers_refresh_method:An.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:An.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:An.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:`${hr.createRandomToken(12)}.invalid`};const la={mandatory:{sockets(c){const t=[];if(zo.isSocket(c))t.push({socket:c});else if(Array.isArray(c)&&c.length)for(const n of c)Object.prototype.hasOwnProperty.call(n,"socket")&&zo.isSocket(n.socket)?t.push(n):zo.isSocket(n)&&t.push({socket:n});else return;return t},uri(c){/^sip:/i.test(c)||(c=`${An.SIP}:${c}`);const t=Rf.parse(c);if(t)return t.user?t:void 0}},optional:{authorization_user(c){if(Jo.parse(`"${c}"`,"quoted_string")!==-1)return c},authorization_jwt(c){if(typeof c=="string")return c},user_agent(c){if(typeof c=="string")return c},connection_recovery_max_interval(c){if(hr.isDecimal(c)){const t=Number(c);if(t>0)return t}},connection_recovery_min_interval(c){if(hr.isDecimal(c)){const t=Number(c);if(t>0)return t}},contact_uri(c){if(typeof c=="string"){const t=Jo.parse(c,"SIP_URI");if(t!==-1)return t}},display_name(c){return c},instance_id(c){if(/^uuid:/i.test(c)&&(c=c.substr(5)),Jo.parse(c,"uuid")!==-1)return c},no_answer_timeout(c){if(hr.isDecimal(c)){const t=Number(c);if(t>0)return t}},session_timers(c){if(typeof c=="boolean")return c},session_timers_refresh_method(c){if(typeof c=="string"&&(c=c.toUpperCase(),c===An.INVITE||c===An.UPDATE))return c},session_timers_force_refresher(c){if(typeof c=="boolean")return c},password(c){return String(c)},realm(c){return String(c)},ha1(c){return String(c)},register(c){if(typeof c=="boolean")return c},register_expires(c){if(hr.isDecimal(c)){const t=Number(c);if(t>0)return t}},registrar_server(c){/^sip:/i.test(c)||(c=`${An.SIP}:${c}`);const t=Rf.parse(c);if(t)return t.user?void 0:t},use_preloaded_route(c){if(typeof c=="boolean")return c},extra_headers(c){const t=[];if(Array.isArray(c)&&c.length)for(const n of c)typeof n=="string"&&t.push(n);else return;return t}}};rl.load=(c,t)=>{for(const n in la.mandatory)if(t.hasOwnProperty(n)){const a=t[n],o=la.mandatory[n](a);if(o!==void 0)c[n]=o;else throw new Xo.ConfigurationError(n,a)}else throw new Xo.ConfigurationError(n);for(const n in la.optional)if(t.hasOwnProperty(n)){const a=t[n];if(hr.isEmpty(a))continue;const o=la.optional[n](a);if(o!==void 0)c[n]=o;else throw new Xo.ConfigurationError(n,a)}};const mT=ft.EventEmitter,gT=ut,mt=De,TT=lg,If=Sh,bf=Bg,wf=Jg,Qo=Tr,vT=yh,aa=At(),ET=As,ST=ys(),yT=Ah,Zo=yt,AT=Ih,eu=rl,qe=new gT("UA"),vt={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2};var bh=class extends mT{static get C(){return vt}constructor(t){if(qe.debug("new() [configuration:%o]",t),super(),this._cache={credentials:{}},this._configuration=Object.assign({},eu.settings),this._dynConfiguration={},this._dialogs={},this._applicants={},this._sessions={},this._transport=null,this._contact=null,this._status=vt.STATUS_INIT,this._error=null,this._transactions={nist:{},nict:{},ist:{},ict:{}},this._data={},this._closeTimer=null,t===void 0)throw new TypeError("Not enough arguments");try{this._loadConfig(t)}catch(n){throw this._status=vt.STATUS_NOT_READY,this._error=vt.CONFIGURATION_ERROR,n}this._registrator=new TT(this)}get C(){return vt}get status(){return this._status}get contact(){return this._contact}get configuration(){return this._configuration}get transport(){return this._transport}start(){qe.debug("start()"),this._status===vt.STATUS_INIT?this._transport.connect():this._status===vt.STATUS_USER_CLOSED?(qe.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=vt.STATUS_INIT,this._transport.connect()):this._status===vt.STATUS_READY?qe.debug("UA is in READY status, not restarted"):qe.debug("ERROR: connection is down, Auto-Recovery system is trying to reconnect"),this._dynConfiguration.register=this._configuration.register}register(){qe.debug("register()"),this._dynConfiguration.register=!0,this._registrator.register()}unregister(t){qe.debug("unregister()"),this._dynConfiguration.register=!1,this._registrator.unregister(t)}registrator(){return this._registrator}isRegistered(){return this._registrator.registered}isConnected(){return this._transport.isConnected()}call(t,n){qe.debug("call()");const a=new If(this);return a.connect(t,n),a}sendMessage(t,n,a){qe.debug("sendMessage()");const o=new bf(this);return o.send(t,n,a),o}sendOptions(t,n,a){qe.debug("sendOptions()");const o=new wf(this);return o.send(t,n,a),o}terminateSessions(t){qe.debug("terminateSessions()");for(const n in this._sessions)this._sessions[n].isEnded()||this._sessions[n].terminate(t)}stop(){if(qe.debug("stop()"),this._dynConfiguration={},this._status===vt.STATUS_USER_CLOSED){qe.debug("UA already closed");return}this._registrator.close();const t=Object.keys(this._sessions).length;for(const a in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,a)){qe.debug(`closing session ${a}`);try{this._sessions[a].terminate()}catch{}}for(const a in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,a))try{this._applicants[a].close()}catch{}this._status=vt.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&t===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}normalizeTarget(t){return aa.normalizeTarget(t,this._configuration.hostport_params)}get(t){switch(t){case"authorization_user":return this._configuration.authorization_user;case"realm":return this._configuration.realm;case"ha1":return this._configuration.ha1;case"authorization_jwt":return this._configuration.authorization_jwt;default:qe.warn('get() | cannot get "%s" parameter in runtime',t);return}}set(t,n){switch(t){case"authorization_user":{this._configuration.authorization_user=String(n);break}case"password":{this._configuration.password=String(n);break}case"realm":{this._configuration.realm=String(n);break}case"ha1":{this._configuration.ha1=String(n),this._configuration.password=null;break}case"authorization_jwt":{this._configuration.authorization_jwt=String(n);break}case"display_name":{this._configuration.display_name=n;break}default:return qe.warn('set() | cannot set "%s" parameter in runtime',t),!1}return!0}newTransaction(t){this._transactions[t.type][t.id]=t,this.emit("newTransaction",{transaction:t})}destroyTransaction(t){delete this._transactions[t.type][t.id],this.emit("transactionDestroyed",{transaction:t})}newDialog(t){this._dialogs[t.id]=t}destroyDialog(t){delete this._dialogs[t.id]}newMessage(t,n){this._applicants[t]=t,this.emit("newMessage",n)}newOptions(t,n){this._applicants[t]=t,this.emit("newOptions",n)}destroyMessage(t){delete this._applicants[t]}newRTCSession(t,n){this._sessions[t.id]=t,this.emit("newRTCSession",n)}destroyRTCSession(t){delete this._sessions[t.id]}registered(t){this.emit("registered",t)}unregistered(t){this.emit("unregistered",t)}registrationFailed(t){this.emit("registrationFailed",t)}receiveRequest(t){const n=t.method;if(t.ruri.user!==this._configuration.uri.user&&t.ruri.user!==this._contact.uri.user){qe.debug("Request-URI does not point to us"),t.method!==mt.ACK&&t.reply_sl(404);return}if(t.ruri.scheme===mt.SIPS){t.reply_sl(416);return}if(Qo.checkTransaction(this,t))return;if(n===mt.INVITE?new Qo.InviteServerTransaction(this,this._transport,t):n!==mt.ACK&&n!==mt.CANCEL&&new Qo.NonInviteServerTransaction(this,this._transport,t),n===mt.OPTIONS){if(this.listeners("newOptions").length===0){t.reply(200);return}new wf(this).init_incoming(t)}else if(n===mt.MESSAGE){if(this.listeners("newMessage").length===0){t.reply(405);return}new bf(this).init_incoming(t)}else if(n===mt.INVITE&&!t.to_tag&&this.listeners("newRTCSession").length===0){t.reply(405);return}let a,o;if(t.to_tag)a=this._findDialog(t.call_id,t.from_tag,t.to_tag),a?a.receiveRequest(t):n===mt.NOTIFY?(o=this._findSession(t),o?o.receiveRequest(t):(qe.debug("received NOTIFY request for a non existent subscription"),t.reply(481,"Subscription does not exist"))):n!==mt.ACK&&t.reply(481);else switch(n){case mt.INVITE:if(window.RTCPeerConnection)if(t.hasHeader("replaces")){const s=t.replaces;a=this._findDialog(s.call_id,s.from_tag,s.to_tag),a?(o=a.owner,o.isEnded()?t.reply(603):o.receiveRequest(t)):t.reply(481)}else o=new If(this),o.init_incoming(t);else qe.warn("INVITE received but WebRTC is not supported"),t.reply(488);break;case mt.BYE:t.reply(481);break;case mt.CANCEL:o=this._findSession(t),o?o.receiveRequest(t):qe.debug("received CANCEL request for a non existent session");break;case mt.ACK:break;case mt.NOTIFY:this.emit("sipEvent",{event:t.event,request:t}),t.reply(200);break;default:t.reply(405);break}}_findSession({call_id:t,from_tag:n,to_tag:a}){const o=t+n,s=this._sessions[o],r=t+a,d=this._sessions[r];return s||d||null}_findDialog(t,n,a){let o=t+n+a,s=this._dialogs[o];return s||(o=t+a+n,s=this._dialogs[o],s||null)}_loadConfig(t){try{eu.load(this._configuration,t)}catch(o){throw o}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=aa.newUUID()),this._configuration.jssip_id=aa.createRandomToken(5);const n=this._configuration.uri.clone();n.user=null,this._configuration.hostport_params=n.toString().replace(/^sip:/i,"");try{this._transport=new vT(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=CT.bind(this),this._transport.onconnect=RT.bind(this),this._transport.ondisconnect=IT.bind(this),this._transport.ondata=bT.bind(this)}catch(o){throw qe.warn(o),new ET.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const o=this._configuration.uri.clone();o.user=null,o.clearParams(),o.clearHeaders(),this._configuration.registrar_server=o}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new ST("sip",aa.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(o={}){const s=o.anonymous||null,r=o.outbound||null;let d="<";return s?d+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":d+=this.pub_gruu||this.uri.toString(),r&&(s?!this.temp_gruu:!this.pub_gruu)&&(d+=";ob"),d+=">",d}};const a=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const o in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,o)&&(a.indexOf(o)!==-1?Object.defineProperty(this._configuration,o,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,o,{writable:!1,configurable:!1}));qe.debug("configuration parameters after validation:");for(const o in this._configuration)if(Object.prototype.hasOwnProperty.call(eu.settings,o))switch(o){case"uri":case"registrar_server":qe.debug(`- ${o}: ${this._configuration[o]}`);break;case"password":case"ha1":case"authorization_jwt":qe.debug(`- ${o}: NOT SHOWN`);break;default:qe.debug(`- ${o}: ${JSON.stringify(this._configuration[o])}`)}}};function CT(c){this.emit("connecting",c)}function RT(c){this._status!==vt.STATUS_USER_CLOSED&&(this._status=vt.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function IT(c){const t=["nict","ict","nist","ist"];for(const n of t)for(const a in this._transactions[n])Object.prototype.hasOwnProperty.call(this._transactions[n],a)&&this._transactions[n][a].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==vt.STATUS_USER_CLOSED&&(this._status=vt.STATUS_NOT_READY,this._error=vt.NETWORK_ERROR)}function bT(c){const t=c.transport;let n=c.message;if(n=yT.parseMessage(n,this),!!n&&!(this._status===vt.STATUS_USER_CLOSED&&n instanceof Zo.IncomingRequest)&&AT(n,this,t)){if(n instanceof Zo.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof Zo.IncomingResponse){let a;switch(n.method){case mt.INVITE:a=this._transactions.ict[n.via_branch],a&&a.receiveResponse(n);break;case mt.ACK:break;default:a=this._transactions.nict[n.via_branch],a&&a.receiveResponse(n);break}}}}const wT=ze(bh);var _t=[];for(var tu=0;tu<256;++tu)_t.push((tu+256).toString(16).slice(1));function OT(c,t=0){return(_t[c[t+0]]+_t[c[t+1]]+_t[c[t+2]]+_t[c[t+3]]+"-"+_t[c[t+4]]+_t[c[t+5]]+"-"+_t[c[t+6]]+_t[c[t+7]]+"-"+_t[c[t+8]]+_t[c[t+9]]+"-"+_t[c[t+10]]+_t[c[t+11]]+_t[c[t+12]]+_t[c[t+13]]+_t[c[t+14]]+_t[c[t+15]]).toLowerCase()}var oa,DT=new Uint8Array(16);function NT(){if(!oa&&(oa=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!oa))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return oa(DT)}var UT=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Of={randomUUID:UT};function Df(c,t,n){if(Of.randomUUID&&!t&&!c)return Of.randomUUID();c=c||{};var a=c.random||(c.rng||NT)();if(a[6]=a[6]&15|64,a[8]=a[8]&63|128,t){n=n||0;for(var o=0;o<16;++o)t[n+o]=a[o];return t}return OT(a)}var ke=At();const Ts=ze(ke),su=new Ga("Dialog"),Fs={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};class ua{static get C(){return Fs}constructor(t,n,a,o=Fs.STATUS_CONFIRMED){if(this._owner=t,this._ua=t._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,n instanceof yt.IncomingResponse&&(o=n.status_code<200?Fs.STATUS_EARLY:Fs.STATUS_CONFIRMED),a==="UAS"){this._id={call_id:n.call_id,local_tag:n.to_tag,remote_tag:n.from_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=o,this._remote_seqnum=n.cseq,this._local_uri=n.parseHeader("to").uri,this._remote_uri=n.parseHeader("from").uri;let s=n.getHeaders("to")[0].split(";")[0];s=s.match(/<([^>]*)>/)[1],this._remote_target=s,this._route_set=n.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum}else if(a==="UAC"){this._id={call_id:n.call_id,local_tag:n.from_tag,remote_tag:n.to_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=o,this._local_seqnum=n.cseq,this._local_uri=n.parseHeader("from").uri,this._remote_uri=n.parseHeader("to").uri;let s=n.getHeaders("to")[0].split(";")[0];s=s.match(/<([^>]*)>/)[1],this._remote_target=s,this._route_set=n.getHeaders("record-route").reverse(),this._ack_seqnum=null}this._ua.newDialog(this),su.debug(`new ${a} dialog created with status ${this._state===Fs.STATUS_EARLY?"EARLY":"CONFIRMED"}`)}get id(){return this._id}get local_seqnum(){return this._local_seqnum}set local_seqnum(t){this._local_seqnum=t}get owner(){return this._owner}get uac_pending_reply(){return this._uac_pending_reply}set uac_pending_reply(t){this._uac_pending_reply=t}get uas_pending_reply(){return this._uas_pending_reply}isTerminated(){return this._status===Fs.STATUS_TERMINATED}update(t,n){this._state=Fs.STATUS_CONFIRMED,su.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),n==="UAC"&&(this._route_set=t.getHeaders("record-route").reverse())}terminate(){su.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=Fs.STATUS_TERMINATED}sendRequest(t,n={}){const a=Ts.cloneArray(n.extraHeaders),o=Ts.cloneObject(n.eventHandlers),s=n.body||null,r=this._createRequest(t,a,s);return o.onAuthenticated=()=>{this._local_seqnum+=1},new hg(this,r,o).send(),r}receiveRequest(t){this._checkInDialogRequest(t)&&(t.method===L.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:t.method===L.INVITE&&(this._ack_seqnum=t.cseq),this._owner.receiveRequest(t))}_createRequest(t,n,a){n=Ts.cloneArray(n),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));const o=t===L.CANCEL||t===L.ACK?this._local_seqnum:this._local_seqnum+=1;return new yt.OutgoingRequest(t,this._remote_target,this._ua,{cseq:o,call_id:this._id.call_id,from_uri:this._local_uri,from_tag:this._id.local_tag,to_uri:this._remote_uri,to_tag:this._id.remote_tag,route_set:this._route_set},n,a)}_checkInDialogRequest(t){if(!this._remote_seqnum)this._remote_seqnum=t.cseq;else if(t.cseq<this._remote_seqnum)if(t.method===L.ACK){if(this._ack_seqnum===null||t.cseq!==this._ack_seqnum)return!1}else return t.reply(500),!1;else t.cseq>this._remote_seqnum&&(this._remote_seqnum=t.cseq);if(t.method===L.INVITE||t.method===L.UPDATE&&t.body){if(this._uac_pending_reply===!0)t.reply(491);else if(this._uas_pending_reply===!0){const n=(Math.random()*10|0)+1;return t.reply(500,null,[`Retry-After:${n}`]),!1}else{this._uas_pending_reply=!0;const n=()=>{(t.server_transaction.state===Gt.C.STATUS_ACCEPTED||t.server_transaction.state===Gt.C.STATUS_COMPLETED||t.server_transaction.state===Gt.C.STATUS_TERMINATED)&&(t.server_transaction.removeListener("stateChanged",n),this._uas_pending_reply=!1)};t.server_transaction.on("stateChanged",n)}t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===Gt.C.STATUS_ACCEPTED&&(this._remote_target=t.parseHeader("contact").uri)})}else t.method===L.NOTIFY&&t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===Gt.C.STATUS_COMPLETED&&(this._remote_target=t.parseHeader("contact").uri)});return!0}}class PT{constructor(t,n){Kt(this,"plugin",null);Kt(this,"rtcpPeer",null);Kt(this,"handleId",0);Kt(this,"info",null);Kt(this,"joinResult",null);Kt(this,"state",{});Kt(this,"stream",null);Kt(this,"loaded",!1);Kt(this,"aTracks",[]);Kt(this,"vTracks",[]);this.info=t,this.plugin=n,this.rtcpPeer=new RTCPeerConnection({iceServers:[]})}get memberInfo(){return{stream:this.stream,joinResult:this.joinResult,sender:this.handleId,type:"subscriber",name:this.info.display,state:this.state,id:this.handleId}}updateMemberState(t){var n;this.state={...this.state,...t||{}},(n=this.plugin)==null||n.session.emit("member:update",this.memberInfo)}updateMemberStateFromMessage(t){var s,r,d,h;const n=(r=(s=t==null?void 0:t.plugindata)==null?void 0:s.data)==null?void 0:r.newStatePublisher,o=((h=(d=t==null?void 0:t.plugindata)==null?void 0:d.data)==null?void 0:h.publisher_state).find(_=>_.id===n);this.updateMemberState(o==null?void 0:o.state)}hangup(){this.rtcpPeer&&(this.rtcpPeer.close(),this.rtcpPeer=null),this.stream&&this.stream.getTracks().forEach(t=>{t.stop()})}}class Qt{static canGetMediaDevices(){return!(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)}static async getDevices(t){return Qt.canGetMediaDevices()?(await navigator.mediaDevices.enumerateDevices()).filter(a=>a.kind===t):[]}static async getMicrophoneList(){return(await Qt.getDevices("audioinput")).map((n,a)=>({...n,deviceId:n.deviceId,label:n.label||`microphone ${a+1}`,kind:n.kind,groupId:n.groupId}))}static async getSpeakerList(){return(await Qt.getDevices("audiooutput")).map((n,a)=>({...n,deviceId:n.deviceId,label:n.label||`speaker ${a+1}`,kind:n.kind,groupId:n.groupId}))}static async getCameraList(){return(await Qt.getDevices("videoinput")).map((n,a)=>({...n,deviceId:n.deviceId,label:n.label||`camera ${a+1}`,kind:n.kind,groupId:n.groupId}))}static stopStreamTracks(t){t&&t.getTracks().forEach(n=>{n.stop()})}static async getMediaFromInputs({videoInput:t,audioInput:n}){let a,o;t==="default"?a=!0:t&&t!=="default"&&(a={deviceId:{exact:t}}),n==="default"?o=!0:n&&n!=="default"&&(o={deviceId:{exact:n}});const s={audio:o,video:a};return Qt.getUserMedia(s)}static async getUserMedia(t){return await navigator.mediaDevices.getUserMedia(t)}static async changeAudioOutput(t,n){if(!(!t||!n))if(typeof t.sinkId<"u")try{await t.setSinkId(n)}catch(a){let o=a;a.name==="SecurityError"&&(o=`You need to use HTTPS for selecting audio output device: ${a}`),console.error(o)}else console.warn("Browser does not support output device selection.")}static toggleAudioMute(t){const n=t.getAudioTracks();if(n.length!==0)return n.forEach(a=>{a.enabled=!a.enabled}),n[0].enabled}static toggleVideoMute(t){const n=t.getVideoTracks();if(n.length!==0)return n.forEach(a=>{a.enabled=!a.enabled}),n[0].enabled}static async getStream(t={video:!0,audio:!0}){try{const n=await navigator.mediaDevices.getUserMedia(t);let a=n.getTracks();return t.video?a=n.getVideoTracks():t.audio&&(a=n.getAudioTracks()),a.length===0?{stream:n,track:null}:{stream:n,track:a[0]}}catch(n){return console.warn(n),{stream:null,track:null}}}}var xT=ys();const In=ze(xT),Pt={LEAVE:"Leave",DETACH:"Detach",AUDIO_CHANGE:"AudioChange",VIDEO_CHANGE:"VideoChange",STATE:"State",ICE:"Ice",CONFIGURE:"Configure",TRICKLE:"Trickle",SUBSCRIBER:"Subscriber",PUBLISHER:"Publisher"},z=new Ga("JanusSession"),kT="/opt/recordings/",te={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},ca=["audio","video"];class $a extends ft.EventEmitter{static get C(){return te}constructor(t){z.debug("new"),super(),this._id=null,this._ua=t,this._status=te.STATUS_NULL,this._dialog=null,this._earlyDialogs={},this._contact=null,this._from_tag=null,this._to_tag=null,this.lastTransaction=0,this._connection=null,this._connectionPromiseQueue=Promise.resolve(),this._request=null,this._is_canceled=!1,this._cancel_reason="",this._is_confirmed=!1,this._late_sdp=!1,this._rtcOfferConstraints=null,this._rtcAnswerConstraints=null,this._localMediaStream=null,this._localMediaStreamLocallyGenerated=!1,this._rtcReady=!0,this._iceReady=!1,this._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},this._direction=null,this._local_identity=null,this._remote_identity=null,this._start_time=null,this._end_time=null,this._audioMuted=!1,this._videoMuted=!1,this._localHold=!1,this._remoteHold=!1,this._sessionTimers={enabled:this._ua.configuration.session_timers,refreshMethod:this._ua.configuration.session_timers_refresh_method,defaultExpires:L.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._candidates=[],this.publishers=[],this.private_id=null,this.memberList={},this.myFeedList=[],this.display_name="",this.stunServers=[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}],this.opaque_id=this.generateOpaqueId(),this.screen_share_opaque_id=this.generateOpaqueId(),this._data={},this.isAudioOn=!0,this.isVideoOn=!0,this.mediaConstraints={}}get C(){return te}get causes(){return L.causes}get id(){return this._id}get connection(){return this._connection}get contact(){return this._contact}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}get start_time(){return this._start_time}get end_time(){return this._end_time}get data(){return this._data}set data(t){this._data=t}get status(){return this._status}isInProgress(){switch(this._status){case te.STATUS_NULL:case te.STATUS_INVITE_SENT:case te.STATUS_1XX_RECEIVED:case te.STATUS_INVITE_RECEIVED:case te.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case te.STATUS_ANSWERED:case te.STATUS_WAITING_FOR_ACK:case te.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case te.STATUS_CANCELED:case te.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}getPTypeHeader(t){return`PTYPE: ${t}`}generateOpaqueId(){return`videoroomtest-${Df().replace(/-/g,"").slice(0,12)}`}connect(t,n,a={},o){z.debug("connect()"),this.display_name=n;const s=t,r=ke.cloneObject(a.eventHandlers),d=ke.cloneArray(a.extraHeaders),h=ke.cloneObject(a.mediaConstraints,{audio:!0,video:!0});this.mediaConstraints={...h};const _=a.mediaStream||null,g=ke.cloneObject(a.pcConfig,{iceServers:[]}),T=a.rtcConstraints||null,E=a.rtcOfferConstraints||null;if(this._rtcOfferConstraints=E,this._rtcAnswerConstraints=a.rtcAnswerConstraints||null,this._data=a.data||this._data,t===void 0)throw new TypeError("Not enough arguments");if(this._status!==te.STATUS_NULL)throw new qs.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new qs.NotSupportedError("WebRTC not supported");if(t=this._ua.normalizeTarget(t),this.room_id=t.user,this.target=t,!t)throw new TypeError(`Invalid target: ${s}`);this._sessionTimers.enabled&&ke.isDecimal(a.sessionTimersExpires)&&(a.sessionTimersExpires>=L.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=a.sessionTimersExpires:this._sessionTimers.defaultExpires=L.SESSION_EXPIRES);for(const C in r)Object.prototype.hasOwnProperty.call(r,C)&&this.on(C,r[C]);this._from_tag=ke.newTag();const y=a.anonymous||!1,A={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:y,outbound:!0}),y?(A.from_display_name="Anonymous",A.from_uri=new In("sip","anonymous","anonymous.invalid"),d.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),d.push("Privacy: id")):a.fromUserName&&(A.from_uri=new In("sip",a.fromUserName,this._ua.configuration.uri.host),d.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),a.fromDisplayName&&(A.from_display_name=a.fromDisplayName),d.push(`Contact: ${this._contact}`),d.push("Content-Type: application/json"),this._sessionTimers.enabled&&d.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new yt.InitialOutgoingInviteRequest(t,this._ua,A,d),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(g,T),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,o&&o(this),this._newJanusSession("local",this._request),this._sendInitialRequest(h,E,_)}_overrideSenderTracks(t,n){t.getTracks().forEach(a=>{n.getSenders().forEach(async s=>{s.track.kind===a.kind&&(a.kind==="audio"&&!this.isAudioOn&&(a.enabled=!1),a.kind==="video"&&!this.isVideoOn&&(a.enabled=!1),await s.replaceTrack(a))})})}init_incoming(t,n){z.debug("init_incoming()");let a;const o=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;if(t.body&&o!=="application/sdp"){t.reply(415);return}if(this._status=te.STATUS_INVITE_RECEIVED,this._from_tag=t.from_tag,this._id=t.call_id+this._from_tag,this._request=t,this._contact=this._ua.contact.toString(),t.hasHeader("expires")&&(a=t.getHeader("expires")*1e3),t.to_tag=ke.newTag(),!this._createDialog(t,"UAS",!0)){t.reply(500,"Missing Contact header field");return}t.body?this._late_sdp=!1:this._late_sdp=!0,this._status=te.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{t.reply(408),this._failed("local",null,L.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),a&&(this._timers.expiresTimer=setTimeout(()=>{this._status===te.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),this._failed("system",null,L.causes.EXPIRES))},a)),this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from,n&&n(this),this._newJanusSession("remote",t),this._status!==te.STATUS_TERMINATED&&(t.reply(180,null,[`Contact: ${this._contact}`]),this._progress("local",null))}answer(t={}){z.debug("answer()");const n=this._request,a=ke.cloneArray(t.extraHeaders),o=ke.cloneObject(t.mediaConstraints),s=t.mediaStream||null,r=ke.cloneObject(t.pcConfig,{iceServers:[]}),d=t.rtcConstraints||null,h=t.rtcAnswerConstraints||null,_=ke.cloneObject(t.rtcOfferConstraints);let g,T=!1,E=!1,y=!1,A=!1;if(this._rtcAnswerConstraints=h,this._rtcOfferConstraints=t.rtcOfferConstraints||null,this._data=t.data||this._data,this._direction!=="incoming")throw new qs.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==te.STATUS_WAITING_FOR_ANSWER)throw new qs.InvalidStateError(this._status);if(this._sessionTimers.enabled&&ke.isDecimal(t.sessionTimersExpires)&&(t.sessionTimersExpires>=L.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=t.sessionTimersExpires:this._sessionTimers.defaultExpires=L.SESSION_EXPIRES),this._status=te.STATUS_ANSWERED,!this._createDialog(n,"UAS")){n.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),a.unshift(`Contact: ${this._contact}`);const C=n.parseSDP();Array.isArray(C.media)||(C.media=[C.media]);for(const I of C.media)I.type==="audio"&&(T=!0,(!I.direction||I.direction==="sendrecv")&&(y=!0)),I.type==="video"&&(E=!0,(!I.direction||I.direction==="sendrecv")&&(A=!0));if(s&&o.audio===!1){g=s.getAudioTracks();for(const I of g)s.removeTrack(I)}if(s&&o.video===!1){g=s.getVideoTracks();for(const I of g)s.removeTrack(I)}!s&&o.audio===void 0&&(o.audio=y),!s&&o.video===void 0&&(o.video=A),!s&&!T&&!_.offerToReceiveAudio&&(o.audio=!1),!s&&!E&&!_.offerToReceiveVideo&&(o.video=!1),this._createRTCConnection(r,d),Promise.resolve().then(()=>{if(s)return s;if(o.audio||o.video)return this._localMediaStreamLocallyGenerated=!0,this.loadStream().catch(I=>{throw this._status===te.STATUS_TERMINATED?new Error("terminated"):(n.reply(480),this._failed("local",null,L.causes.USER_DENIED_MEDIA_ACCESS),z.warn('emit "getusermediafailed" [error:%o]',I),this.emit("getusermediafailed",I),new Error("getUserMedia() failed"))})}).then(I=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=I,I&&I.getTracks().forEach(H=>{this._connection.addTrack(H,I)})}).then(()=>{if(this._late_sdp)return;const I={originator:"remote",type:"offer",sdp:n.body};z.debug('emit "sdp"'),this.emit("sdp",I);const H=new RTCSessionDescription({type:"offer",sdp:I.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(H)).catch($=>{throw n.reply(488),this._failed("system",null,L.causes.WEBRTC_ERROR),z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',$),this.emit("peerconnection:setremotedescriptionfailed",$),new Error("peerconnection.setRemoteDescription() failed")}),this._connectionPromiseQueue}).then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._connecting(n),this._late_sdp?this._createLocalDescription("offer",this._rtcOfferConstraints).catch(()=>{throw n.reply(500),new Error("_createLocalDescription() failed")}):this._createLocalDescription("answer",h).catch(()=>{throw n.reply(500),new Error("_createLocalDescription() failed")})}).then(I=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(n,a),n.reply(200,null,a,I,()=>{this._status=te.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(n,I),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,L.causes.CONNECTION_ERROR)})}).catch(I=>{this._status!==te.STATUS_TERMINATED&&z.warn(I)})}terminate(t={}){z.debug("terminate()");const n=t.cause||L.causes.BYE,a=ke.cloneArray(t.extraHeaders),o=t.body;let s,r=t.status_code,d=t.reason_phrase;if(this._status===te.STATUS_TERMINATED)throw new qs.InvalidStateError(this._status);switch(this._status){case te.STATUS_NULL:case te.STATUS_INVITE_SENT:case te.STATUS_1XX_RECEIVED:if(z.debug("canceling session"),r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);r&&(d=d||L.REASON_PHRASE[r]||"",s=`SIP ;cause=${r} ;text="${d}"`),this._status===te.STATUS_NULL||this._status===te.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=s):this._status===te.STATUS_1XX_RECEIVED&&this._request.cancel(s),this._status=te.STATUS_CANCELED,this._failed("local",null,L.causes.CANCELED);break;case te.STATUS_WAITING_FOR_ANSWER:case te.STATUS_ANSWERED:if(z.debug("rejecting session"),r=r||480,r<300||r>=700)throw new TypeError(`Invalid status_code: ${r}`);this._request.reply(r,d,a,o),this._failed("local",null,L.causes.REJECTED);break;case te.STATUS_WAITING_FOR_ACK:case te.STATUS_CONFIRMED:if(z.debug("terminating session"),d=t.reason_phrase||L.REASON_PHRASE[r]||"",r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);if(r&&a.push(`Reason: SIP ;cause=${r}; text="${d}"`),this._status===te.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Gt.C.STATUS_TERMINATED){const h=this._dialog;this.receiveRequest=({method:_})=>{_===L.ACK&&(this.sendRequest(L.BYE,{extraHeaders:a,body:o}),h.terminate(),this.closeSession())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Gt.C.STATUS_TERMINATED&&(this.sendRequest(L.BYE,{extraHeaders:a,body:o}),h.terminate(),this.closeSession())}),this._ended("local",null,n),this._dialog=h,this._ua.newDialog(h)}else{const h={janus:"leave"},_=["Content-Type: application/json",this.getPTypeHeader(Pt.LEAVE)];this.sendRequest(L.BYE,{extraHeaders:_,body:JSON.stringify(h)}),this.closeSession(),this._ended("local",null,n)}}}configureMedia(t){this.isAudioOn=t.audio,this.isVideoOn=t.video}enableAudio(t){const n={janus:"message",body:{audio:t},handle_id:this.handle_id,session_id:this.session_id},a=["Content-Type: application/json",this.getPTypeHeader(Pt.AUDIO_CHANGE)];this.sendRequest(L.INFO,{extraHeaders:a,body:JSON.stringify(n),eventHandlers:{onSuccessResponse:async o=>{o.status_code===200&&(this._ua.emit("changeAudioState",t),this.sendStateMessage({audio:t}))}}})}startAudio(){Qt.toggleAudioMute(this.stream),this._toggleMuteAudio(!1),this.enableAudio(!0),this.isAudioOn=!0}stopAudio(){Qt.toggleAudioMute(this.stream),this._toggleMuteAudio(!0),this.enableAudio(!1),this.isAudioOn=!1}enableVideo(t){const n={janus:"message",body:{video:t},handle_id:this.handle_id,session_id:this.session_id},a=["Content-Type: application/json",this.getPTypeHeader(Pt.VIDEO_CHANGE)];this.sendRequest(L.INFO,{extraHeaders:a,body:JSON.stringify(n),eventHandlers:{onSuccessResponse:async o=>{o.status_code===200&&(this._ua.emit("changeVideoState",t),this.sendStateMessage({video:t}))}}})}startVideo(){Qt.toggleVideoMute(this.stream),this._toggleMuteVideo(!1),this.enableVideo(!0),this.isVideoOn=!0}stopVideo(){Qt.toggleVideoMute(this.stream),this._toggleMuteVideo(!0),this.enableVideo(!1),this.isVideoOn=!1}sendStateMessage(t){const n={janus:"message",body:{request:"state",data:t},handle_id:this.handle_id,session_id:this.session_id},a=["Content-Type: application/json",this.getPTypeHeader(Pt.STATE)];this.sendRequest(L.INFO,{extraHeaders:a,body:JSON.stringify(n)})}sendInfo(t,n,a={}){if(z.debug("sendInfo()"),this._status!==te.STATUS_CONFIRMED&&this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_1XX_RECEIVED)throw new qs.InvalidStateError(this._status);new yu(this).send(t,n,a)}mute(t={audio:!0,video:!1}){z.debug("mute()");let n=!1,a=!1;this._audioMuted===!1&&t.audio&&(n=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&t.video&&(a=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(n===!0||a===!0)&&this._onmute({audio:n,video:a})}unmute(t={audio:!0,video:!0}){z.debug("unmute()");let n=!1,a=!1;this._audioMuted===!0&&t.audio&&(n=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&t.video&&(a=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(n===!0||a===!0)&&this._onunmute({audio:n,video:a})}hold(t={},n){if(z.debug("hold()"),this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");const a={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:L.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:a,extraHeaders:t.extraHeaders}),!0}unhold(t={},n){if(z.debug("unhold()"),this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");const a={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:L.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:a,extraHeaders:t.extraHeaders}),!0}renegotiate(t={},n){z.debug("renegotiate()");const a=t.rtcOfferConstraints||null;if(this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;const o={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:L.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:o,rtcOfferConstraints:a,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:o,rtcOfferConstraints:a,extraHeaders:t.extraHeaders}),!0}refer(t,n){z.debug("refer()");const a=t;if(this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${a}`);const o=new Ng(this);o.sendRefer(t,n);const s=o.id;return this._referSubscribers[s]=o,o.on("requestFailed",()=>{delete this._referSubscribers[s]}),o.on("accepted",()=>{delete this._referSubscribers[s]}),o.on("failed",()=>{delete this._referSubscribers[s]}),o}sendRequest(t,n){return z.debug("sendRequest()"),this._dialog.sendRequest(t,n)}receiveNotify(t){z.debug("receiveRequest()")}receiveRequest(t){if(z.debug("receiveRequest()"),t.method===L.CANCEL)(this._status===te.STATUS_WAITING_FOR_ANSWER||this._status===te.STATUS_ANSWERED)&&(this._status=te.STATUS_CANCELED,this._request.reply(487),this._failed("remote",t,L.causes.CANCELED));else switch(t.method){case L.ACK:if(this._status!==te.STATUS_WAITING_FOR_ACK)return;if(this._status=te.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!t.body){this.terminate({cause:L.causes.MISSING_SDP,status_code:400});break}const n={originator:"remote",type:"answer",sdp:t.body};z.debug('emit "sdp"'),this.emit("sdp",n);const a=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>{this._is_confirmed||this._confirmed("remote",t)}).catch(o=>{this.terminate({cause:L.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',o),this.emit("peerconnection:setremotedescriptionfailed",o)})}else this._is_confirmed||this._confirmed("remote",t);break;case L.BYE:this._status===te.STATUS_CONFIRMED||this._status===te.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,L.causes.BYE)):this._status===te.STATUS_INVITE_RECEIVED||this._status===te.STATUS_WAITING_FOR_ANSWER?(t.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",t,L.causes.BYE)):t.reply(403,"Wrong Status");break;case L.INVITE:this._status===te.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case L.INFO:if(this._status===te.STATUS_1XX_RECEIVED||this._status===te.STATUS_WAITING_FOR_ANSWER||this._status===te.STATUS_ANSWERED||this._status===te.STATUS_WAITING_FOR_ACK||this._status===te.STATUS_CONFIRMED){const n=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;n&&n.match(/^application\/dtmf-relay/i)?new Eg(this).init_incoming(t):n!==void 0?new yu(this).init_incoming(t):t.reply(415)}else t.reply(403,"Wrong Status");break;case L.UPDATE:this._status===te.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case L.REFER:this._status===te.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case L.NOTIFY:this._status===te.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){z.warn("onTransportError()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:L.causes.CONNECTION_ERROR,cause:L.causes.CONNECTION_ERROR})}onRequestTimeout(){z.warn("onRequestTimeout()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:L.causes.REQUEST_TIMEOUT,cause:L.causes.REQUEST_TIMEOUT})}onDialogError(){z.warn("onDialogError()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:L.causes.DIALOG_ERROR,cause:L.causes.DIALOG_ERROR})}newDTMF(t){z.debug("newDTMF()"),this.emit("newDTMF",t)}newInfo(t){z.debug("newInfo()"),this.emit("newInfo",t)}_isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(z.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(z.debug("_isReadyToReOffer() | session not established yet"),!1):(z.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}_close(){if(z.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(z.debug("close() | closing local MediaStream"),ke.closeMediaStream(this._localMediaStream)),this._status!==te.STATUS_TERMINATED){if(this._status=te.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(t){z.warn("close() | error closing the RTCPeerConnection: %o",t)}for(const t in this._timers)Object.prototype.hasOwnProperty.call(this._timers,t)&&clearTimeout(this._timers[t]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const t in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,t)&&(this._earlyDialogs[t].terminate(),delete this._earlyDialogs[t]);for(const t in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,t)&&delete this._referSubscribers[t];this._ua.destroyRTCSession(this)}}_setInvite2xxTimer(t,n){let a=$i.T1;function o(){this._status===te.STATUS_WAITING_FOR_ACK&&(t.reply(200,null,[`Contact: ${this._contact}`],n),a<$i.T2&&(a=a*2,a>$i.T2&&(a=$i.T2)),this._timers.invite2xxTimer=setTimeout(o.bind(this),a))}this._timers.invite2xxTimer=setTimeout(o.bind(this),a)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===te.STATUS_WAITING_FOR_ACK&&(z.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(L.BYE),this._ended("remote",null,L.causes.NO_ACK))},$i.TIMER_H)}_createRTCConnection(t,n){this.stunServers,this._connection=new RTCPeerConnection(t,n),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:L.causes.RTP_TIMEOUT,status_code:408,reason_phrase:L.causes.RTP_TIMEOUT})});let a;const o=s=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||s.candidate&&(this._candidates.push(s.candidate),clearTimeout(a),a=setTimeout(()=>{this.lastTrickleReceived=!0,this.subscribeSent&&!this.isConfigureSent&&(this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream}),this._sendConfigureMessage({audio:!0,video:!0}).then(()=>{}))},500))};this._connection.onicecandidate=o,z.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(t,n){if(z.debug("createLocalDescription()"),t!=="offer"&&t!=="answer")throw new Error(`createLocalDescription() | invalid type "${t}"`);const a=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>t==="offer"?a.createOffer(n).catch(o=>(z.warn('emit "peerconnection:createofferfailed" [error:%o]',o),this.emit("peerconnection:createofferfailed",o),Promise.reject(o))):a.createAnswer(n).catch(o=>(z.warn('emit "peerconnection:createanswerfailed" [error:%o]',o),this.emit("peerconnection:createanswerfailed",o),Promise.reject(o)))).then(o=>(this.jsepOffer=o,a.setLocalDescription(o).catch(s=>(this._rtcReady=!0,z.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',s),this.emit("peerconnection:setlocaldescriptionfailed",s),Promise.reject(s))))).then(()=>{const o=n&&n.iceRestart;if(a.iceGatheringState==="complete"&&!o||a.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const s={originator:"local",type:t,sdp:a.localDescription.sdp};return z.debug('emit "sdp"'),this.emit("sdp",s),Promise.resolve(s.sdp)}return new Promise(s=>{let r=!1,d,h;this._iceReady=!1;const _=()=>{a.removeEventListener("icecandidate",d),a.removeEventListener("icegatheringstatechange",h),r=!0,this._rtcReady=!0,this._iceReady=!0;const g={originator:"local",type:t,sdp:a.localDescription.sdp};z.debug('emit "sdp"'),this.emit("sdp",g),s(g.sdp)};a.addEventListener("icecandidate",d=g=>{const T=g.candidate;T?this.emit("icecandidate",{candidate:T,ready:_}):r||_()}),a.addEventListener("icegatheringstatechange",h=()=>{a.iceGatheringState==="complete"&&!r&&_()})})})}_createDialog(t,n,a){const o=n==="UAS"?t.to_tag:t.from_tag,s=n==="UAS"?t.from_tag:t.to_tag,r=t.call_id+o+s;let d=this._earlyDialogs[r];if(a)return d?!0:(d=new ua(this,t,n,ua.C.STATUS_EARLY),d.error?(z.debug(d.error),this._failed("remote",t,L.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[r]=d,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,d)return d.update(t,n),this._dialog=d,delete this._earlyDialogs[r],!0;const h=new ua(this,t,n);return h.error?(z.debug(h.error),this._failed("remote",t,L.causes.INTERNAL_ERROR),!1):(this._dialog=h,!0)}}_receiveReinvite(t){z.debug("receiveReinvite()");const n=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,a={request:t,callback:void 0,reject:s.bind(this)};let o=!1;function s(d={}){o=!0;const h=d.status_code||403,_=d.reason_phrase||"",g=ke.cloneArray(d.extraHeaders);if(this._status!==te.STATUS_CONFIRMED)return!1;if(h<300||h>=700)throw new TypeError(`Invalid status_code: ${h}`);t.reply(h,_,g)}if(this.emit("reinvite",a),o)return;if(this._late_sdp=!1,!t.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",this._rtcOfferConstraints)).then(d=>{r.call(this,d)}).catch(()=>{t.reply(500)});return}if(n!=="application/sdp"){z.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(d=>{this._status!==te.STATUS_TERMINATED&&r.call(this,d)}).catch(d=>{z.warn(d)});function r(d){const h=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,h),this._late_sdp&&(d=this._mangleOffer(d)),t.reply(200,null,h,d,()=>{this._status=te.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(t,d),this._setACKTimer()}),typeof a.callback=="function"&&a.callback()}}_receiveUpdate(t){z.debug("receiveUpdate()");const n=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,a={request:t,callback:void 0,reject:s.bind(this)};let o=!1;function s(d={}){o=!0;const h=d.status_code||403,_=d.reason_phrase||"",g=ke.cloneArray(d.extraHeaders);if(this._status!==te.STATUS_CONFIRMED)return!1;if(h<300||h>=700)throw new TypeError(`Invalid status_code: ${h}`);t.reply(h,_,g)}if(this.emit("update",a),o)return;if(!t.body){r.call(this,null);return}if(n!=="application/sdp"){z.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(d=>{this._status!==te.STATUS_TERMINATED&&r.call(this,d)}).catch(d=>{z.warn(d)});function r(d){const h=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,h),t.reply(200,null,h,d),typeof a.callback=="function"&&a.callback()}}_processInDialogSdpOffer(t){z.debug("_processInDialogSdpOffer()");const n=t.parseSDP();let a=!1;for(const r of n.media){if(ca.indexOf(r.type)===-1)continue;const d=r.direction||n.direction||"sendrecv";if(d==="sendonly"||d==="inactive")a=!0;else{a=!1;break}}const o={originator:"remote",type:"offer",sdp:t.body};z.debug('emit "sdp"'),this.emit("sdp",o);const s=new RTCSessionDescription({type:"offer",sdp:o.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._connection.setRemoteDescription(s).catch(r=>{throw t.reply(488),z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',r),this.emit("peerconnection:setremotedescriptionfailed",r),r})}).then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._remoteHold===!0&&a===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&a===!0&&(this._remoteHold=!0,this._onhold("remote"))}).then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._createLocalDescription("answer",this._rtcAnswerConstraints).catch(r=>{throw t.reply(500),z.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',r),r})}).catch(r=>{z.warn("_processInDialogSdpOffer() failed [error: %o]",r)}),this._connectionPromiseQueue}_receiveRefer(t){if(z.debug("receiveRefer()"),!t.refer_to){z.debug("no Refer-To header field present in REFER"),t.reply(400);return}if(t.refer_to.uri.scheme!==L.SIP){z.debug("Refer-To header field points to a non-SIP URI scheme"),t.reply(416);return}t.reply(202);const n=new bg(this,t.cseq);z.debug('emit "refer"'),this.emit("refer",{request:t,accept:(s,r)=>{a.call(this,s,r)},reject:()=>{o.call(this)}});function a(s,r={}){if(s=typeof s=="function"?s:null,this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;const d=new $a(this._ua);if(d.on("progress",({response:h})=>{n.notify(h.status_code,h.reason_phrase)}),d.on("accepted",({response:h})=>{n.notify(h.status_code,h.reason_phrase)}),d.on("_failed",({message:h,cause:_})=>{h?n.notify(h.status_code,h.reason_phrase):n.notify(487,_)}),t.refer_to.uri.hasHeader("replaces")){const h=decodeURIComponent(t.refer_to.uri.getHeader("replaces"));r.extraHeaders=ke.cloneArray(r.extraHeaders),r.extraHeaders.push(`Replaces: ${h}`)}d.connect(t.refer_to.uri.toAor(),r,s)}function o(){n.notify(603)}}_receiveNotify(t){switch(z.debug("receiveNotify()"),t.event||t.reply(400),t.event.event){case"refer":{let n,a;if(t.event.params&&t.event.params.id)n=t.event.params.id,a=this._referSubscribers[n];else if(Object.keys(this._referSubscribers).length===1)a=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{t.reply(400,"Missing event id parameter");return}if(!a){t.reply(481,"Subscription does not exist");return}a.receiveNotify(t),t.reply(200);break}default:t.reply(489)}}_receiveReplaces(t){z.debug("receiveReplaces()");function n(o){if(this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;const s=new $a(this._ua);s.on("confirmed",()=>{this.terminate()}),s.init_incoming(t,o)}function a(){z.debug("Replaced INVITE rejected by the user"),t.reply(486)}this.emit("replaces",{request:t,accept:o=>{n.call(this,o)},reject:()=>{a.call(this)}})}_getNextTransactionId(){return(this.lastTransaction+1).toString()}_sendInitialRequest(t,n,a){this.ackSent=!1,this.publisherSubscribeSent=!1;const o=new sl(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});Promise.resolve().then(()=>{if(a)return a;if(t.audio||t.video)return this._localMediaStreamLocallyGenerated=!0,this.loadStream().catch(s=>{throw this._status===te.STATUS_TERMINATED?new Error("terminated"):(this._failed("local",null,L.causes.USER_DENIED_MEDIA_ACCESS),z.warn('emit "getusermediafailed" [error:%o]',s),this.emit("getusermediafailed",s),s)})}).then(s=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._localMediaStream=s,s&&s.getTracks().forEach(r=>{this._connection.addTrack(r,s)}),this._connecting(this._request),this._createLocalDescription("offer",n).catch(r=>{throw this._failed("local",null,L.causes.WEBRTC_ERROR),r})}).then(s=>{if(this._is_canceled||this._status===te.STATUS_TERMINATED)throw new Error("terminated");const r={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaque_id},d=JSON.stringify(r);this._request.body=d,this._status=te.STATUS_INVITE_SENT,z.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),o.send()}).catch(s=>{this._status!==te.STATUS_TERMINATED&&z.warn(s)})}async requestAudioAndVideoPermissions(){this.stream=await this.loadStream()}async setupMediaStream(){await this.requestAudioAndVideoPermissions(),await this.processPlugins()}async changeMediaConstraints(t){this.mediaConstraints={...t},await this.processPlugins(),this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream})}async loadStream(){const t={};this.isAudioOn?this.mediaConstraints.audio?t.audio=this.mediaConstraints.audio:t.audio=!0:t.audio=!1,this.isVideoOn?this.mediaConstraints.video?t.video=this.mediaConstraints.video:t.video=!0:t.video=!1;let n=null;try{n=await navigator.mediaDevices.getUserMedia(t)}catch{try{t.video=!1,n=await navigator.mediaDevices.getUserMedia(t)}catch{t.audio=!1,t.video=!1,n=await navigator.mediaDevices.getUserMedia(t)}}return n}addTracks(t){this._connection.getSenders().forEach(n=>{this._connection.removeTrack(n)}),t.forEach(n=>{this._connection.addTrack(n)})}getRecordFileName(){return kT+this.room_id+btoa(unescape(encodeURIComponent(this.displayName)))+Date.now()}async processIceCandidates(){for(let t=0;t<this.iceCandidates.length;t++)await this._connection.addIceCandidate(this.iceCandidates[t]);this.iceCandidates=[]}async _sendConfigureMessage(t){const n=this._candidates.map(r=>({janus:"trickle",candidate:r,handle_id:this.handle_id,session_id:this.session_id})),o={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.getRecordFileName(),...t},jsep:this.jsepOffer,handle_id:this.handle_id,session_id:this.session_id},trickles:[...n]},s=["Content-Type: application/json",this.getPTypeHeader(Pt.ICE)];this.sendRequest(L.INFO,{extraHeaders:s,body:JSON.stringify(o),eventHandlers:{onSuccessResponse:async r=>{this.isConfigureSent=!0;const h=r.data.split(`\r
|
134
|
+
`,Rh.send(a)}const pT=ze(Ih);var rl={};const hr=At(),An=De,Jo=Zt(),Rf=ys(),zo=qu,Xo=As;rl.settings={authorization_user:null,password:null,realm:null,ha1:null,authorization_jwt:null,display_name:null,uri:null,contact_uri:null,instance_id:null,use_preloaded_route:!1,session_timers:!0,session_timers_refresh_method:An.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:An.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:An.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:`${hr.createRandomToken(12)}.invalid`};const la={mandatory:{sockets(c){const t=[];if(zo.isSocket(c))t.push({socket:c});else if(Array.isArray(c)&&c.length)for(const n of c)Object.prototype.hasOwnProperty.call(n,"socket")&&zo.isSocket(n.socket)?t.push(n):zo.isSocket(n)&&t.push({socket:n});else return;return t},uri(c){/^sip:/i.test(c)||(c=`${An.SIP}:${c}`);const t=Rf.parse(c);if(t)return t.user?t:void 0}},optional:{authorization_user(c){if(Jo.parse(`"${c}"`,"quoted_string")!==-1)return c},authorization_jwt(c){if(typeof c=="string")return c},user_agent(c){if(typeof c=="string")return c},connection_recovery_max_interval(c){if(hr.isDecimal(c)){const t=Number(c);if(t>0)return t}},connection_recovery_min_interval(c){if(hr.isDecimal(c)){const t=Number(c);if(t>0)return t}},contact_uri(c){if(typeof c=="string"){const t=Jo.parse(c,"SIP_URI");if(t!==-1)return t}},display_name(c){return c},instance_id(c){if(/^uuid:/i.test(c)&&(c=c.substr(5)),Jo.parse(c,"uuid")!==-1)return c},no_answer_timeout(c){if(hr.isDecimal(c)){const t=Number(c);if(t>0)return t}},session_timers(c){if(typeof c=="boolean")return c},session_timers_refresh_method(c){if(typeof c=="string"&&(c=c.toUpperCase(),c===An.INVITE||c===An.UPDATE))return c},session_timers_force_refresher(c){if(typeof c=="boolean")return c},password(c){return String(c)},realm(c){return String(c)},ha1(c){return String(c)},register(c){if(typeof c=="boolean")return c},register_expires(c){if(hr.isDecimal(c)){const t=Number(c);if(t>0)return t}},registrar_server(c){/^sip:/i.test(c)||(c=`${An.SIP}:${c}`);const t=Rf.parse(c);if(t)return t.user?void 0:t},use_preloaded_route(c){if(typeof c=="boolean")return c},extra_headers(c){const t=[];if(Array.isArray(c)&&c.length)for(const n of c)typeof n=="string"&&t.push(n);else return;return t}}};rl.load=(c,t)=>{for(const n in la.mandatory)if(t.hasOwnProperty(n)){const a=t[n],o=la.mandatory[n](a);if(o!==void 0)c[n]=o;else throw new Xo.ConfigurationError(n,a)}else throw new Xo.ConfigurationError(n);for(const n in la.optional)if(t.hasOwnProperty(n)){const a=t[n];if(hr.isEmpty(a))continue;const o=la.optional[n](a);if(o!==void 0)c[n]=o;else throw new Xo.ConfigurationError(n,a)}};const mT=ft.EventEmitter,gT=ut,mt=De,TT=lg,If=Sh,bf=Bg,wf=Jg,Qo=Tr,vT=yh,aa=At(),ET=As,ST=ys(),yT=Ah,Zo=yt,AT=Ih,eu=rl,He=new gT("UA"),vt={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2};var bh=class extends mT{static get C(){return vt}constructor(t){if(He.debug("new() [configuration:%o]",t),super(),this._cache={credentials:{}},this._configuration=Object.assign({},eu.settings),this._dynConfiguration={},this._dialogs={},this._applicants={},this._sessions={},this._transport=null,this._contact=null,this._status=vt.STATUS_INIT,this._error=null,this._transactions={nist:{},nict:{},ist:{},ict:{}},this._data={},this._closeTimer=null,t===void 0)throw new TypeError("Not enough arguments");try{this._loadConfig(t)}catch(n){throw this._status=vt.STATUS_NOT_READY,this._error=vt.CONFIGURATION_ERROR,n}this._registrator=new TT(this)}get C(){return vt}get status(){return this._status}get contact(){return this._contact}get configuration(){return this._configuration}get transport(){return this._transport}start(){He.debug("start()"),this._status===vt.STATUS_INIT?this._transport.connect():this._status===vt.STATUS_USER_CLOSED?(He.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=vt.STATUS_INIT,this._transport.connect()):this._status===vt.STATUS_READY?He.debug("UA is in READY status, not restarted"):He.debug("ERROR: connection is down, Auto-Recovery system is trying to reconnect"),this._dynConfiguration.register=this._configuration.register}register(){He.debug("register()"),this._dynConfiguration.register=!0,this._registrator.register()}unregister(t){He.debug("unregister()"),this._dynConfiguration.register=!1,this._registrator.unregister(t)}registrator(){return this._registrator}isRegistered(){return this._registrator.registered}isConnected(){return this._transport.isConnected()}call(t,n){He.debug("call()");const a=new If(this);return a.connect(t,n),a}sendMessage(t,n,a){He.debug("sendMessage()");const o=new bf(this);return o.send(t,n,a),o}sendOptions(t,n,a){He.debug("sendOptions()");const o=new wf(this);return o.send(t,n,a),o}terminateSessions(t){He.debug("terminateSessions()");for(const n in this._sessions)this._sessions[n].isEnded()||this._sessions[n].terminate(t)}stop(){if(He.debug("stop()"),this._dynConfiguration={},this._status===vt.STATUS_USER_CLOSED){He.debug("UA already closed");return}this._registrator.close();const t=Object.keys(this._sessions).length;for(const a in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,a)){He.debug(`closing session ${a}`);try{this._sessions[a].terminate()}catch{}}for(const a in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,a))try{this._applicants[a].close()}catch{}this._status=vt.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&t===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}normalizeTarget(t){return aa.normalizeTarget(t,this._configuration.hostport_params)}get(t){switch(t){case"authorization_user":return this._configuration.authorization_user;case"realm":return this._configuration.realm;case"ha1":return this._configuration.ha1;case"authorization_jwt":return this._configuration.authorization_jwt;default:He.warn('get() | cannot get "%s" parameter in runtime',t);return}}set(t,n){switch(t){case"authorization_user":{this._configuration.authorization_user=String(n);break}case"password":{this._configuration.password=String(n);break}case"realm":{this._configuration.realm=String(n);break}case"ha1":{this._configuration.ha1=String(n),this._configuration.password=null;break}case"authorization_jwt":{this._configuration.authorization_jwt=String(n);break}case"display_name":{this._configuration.display_name=n;break}default:return He.warn('set() | cannot set "%s" parameter in runtime',t),!1}return!0}newTransaction(t){this._transactions[t.type][t.id]=t,this.emit("newTransaction",{transaction:t})}destroyTransaction(t){delete this._transactions[t.type][t.id],this.emit("transactionDestroyed",{transaction:t})}newDialog(t){this._dialogs[t.id]=t}destroyDialog(t){delete this._dialogs[t.id]}newMessage(t,n){this._applicants[t]=t,this.emit("newMessage",n)}newOptions(t,n){this._applicants[t]=t,this.emit("newOptions",n)}destroyMessage(t){delete this._applicants[t]}newRTCSession(t,n){this._sessions[t.id]=t,this.emit("newRTCSession",n)}destroyRTCSession(t){delete this._sessions[t.id]}registered(t){this.emit("registered",t)}unregistered(t){this.emit("unregistered",t)}registrationFailed(t){this.emit("registrationFailed",t)}receiveRequest(t){console.log("receiveRequest");const n=t.method;if(t.ruri.user!==this._configuration.uri.user&&t.ruri.user!==this._contact.uri.user){He.debug("Request-URI does not point to us"),t.method!==mt.ACK&&t.reply_sl(404);return}if(t.ruri.scheme===mt.SIPS){t.reply_sl(416);return}if(Qo.checkTransaction(this,t))return;if(n===mt.INVITE?new Qo.InviteServerTransaction(this,this._transport,t):n!==mt.ACK&&n!==mt.CANCEL&&new Qo.NonInviteServerTransaction(this,this._transport,t),n===mt.OPTIONS){if(console.log("OPPP in option"),this.listeners("newOptions").length===0){t.reply(200);return}new wf(this).init_incoming(t)}else if(n===mt.MESSAGE){if(this.listeners("newMessage").length===0){t.reply(405);return}new bf(this).init_incoming(t)}else if(n===mt.INVITE&&!t.to_tag&&this.listeners("newRTCSession").length===0){t.reply(405);return}let a,o;if(t.to_tag)a=this._findDialog(t.call_id,t.from_tag,t.to_tag),a?a.receiveRequest(t):n===mt.NOTIFY?(o=this._findSession(t),o?o.receiveRequest(t):(He.debug("received NOTIFY request for a non existent subscription"),t.reply(481,"Subscription does not exist"))):n!==mt.ACK&&t.reply(481);else switch(n){case mt.INVITE:if(window.RTCPeerConnection)if(t.hasHeader("replaces")){const s=t.replaces;a=this._findDialog(s.call_id,s.from_tag,s.to_tag),a?(o=a.owner,o.isEnded()?t.reply(603):o.receiveRequest(t)):t.reply(481)}else o=new If(this),o.init_incoming(t);else He.warn("INVITE received but WebRTC is not supported"),t.reply(488);break;case mt.BYE:t.reply(481);break;case mt.CANCEL:o=this._findSession(t),o?o.receiveRequest(t):He.debug("received CANCEL request for a non existent session");break;case mt.ACK:break;case mt.NOTIFY:this.emit("sipEvent",{event:t.event,request:t}),t.reply(200);break;default:t.reply(405);break}}_findSession({call_id:t,from_tag:n,to_tag:a}){const o=t+n,s=this._sessions[o],r=t+a,d=this._sessions[r];return s||d||null}_findDialog(t,n,a){let o=t+n+a,s=this._dialogs[o];return s||(o=t+a+n,s=this._dialogs[o],s||null)}_loadConfig(t){console.log("in _loadConfig");try{console.log("config.load"),eu.load(this._configuration,t)}catch(o){throw console.log("throw in _loadConfig",o),o}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=aa.newUUID()),this._configuration.jssip_id=aa.createRandomToken(5);const n=this._configuration.uri.clone();n.user=null,this._configuration.hostport_params=n.toString().replace(/^sip:/i,"");try{console.log("new transport"),this._transport=new vT(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=CT.bind(this),this._transport.onconnect=RT.bind(this),this._transport.ondisconnect=IT.bind(this),this._transport.ondata=bT.bind(this)}catch(o){throw He.warn(o),new ET.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const o=this._configuration.uri.clone();o.user=null,o.clearParams(),o.clearHeaders(),this._configuration.registrar_server=o}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:(console.log("this._configuration.contact_uri 1"),this._configuration.contact_uri=new ST("sip",aa.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),console.log("this._configuration.contact_uri 2",this._configuration.contact_uri)),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(o={}){const s=o.anonymous||null,r=o.outbound||null;let d="<";return s?d+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":d+=this.pub_gruu||this.uri.toString(),r&&(s?!this.temp_gruu:!this.pub_gruu)&&(d+=";ob"),d+=">",console.log("contact",d),d}};const a=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const o in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,o)&&(a.indexOf(o)!==-1?Object.defineProperty(this._configuration,o,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,o,{writable:!1,configurable:!1}));He.debug("configuration parameters after validation:"),He.debug("this._contact.toString:",this._contact.toString());for(const o in this._configuration)if(Object.prototype.hasOwnProperty.call(eu.settings,o))switch(o){case"uri":case"registrar_server":He.debug(`- ${o}: ${this._configuration[o]}`);break;case"password":case"ha1":case"authorization_jwt":He.debug(`- ${o}: NOT SHOWN`);break;default:He.debug(`- ${o}: ${JSON.stringify(this._configuration[o])}`)}console.log("_loadConfig retun")}};function CT(c){this.emit("connecting",c)}function RT(c){this._status!==vt.STATUS_USER_CLOSED&&(this._status=vt.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function IT(c){const t=["nict","ict","nist","ist"];for(const n of t)for(const a in this._transactions[n])Object.prototype.hasOwnProperty.call(this._transactions[n],a)&&this._transactions[n][a].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==vt.STATUS_USER_CLOSED&&(this._status=vt.STATUS_NOT_READY,this._error=vt.NETWORK_ERROR)}function bT(c){console.log("onTransportData",c);const t=c.transport;let n=c.message;if(n=yT.parseMessage(n,this),!!n&&!(this._status===vt.STATUS_USER_CLOSED&&n instanceof Zo.IncomingRequest)&&AT(n,this,t)){if(n instanceof Zo.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof Zo.IncomingResponse){let a;switch(n.method){case mt.INVITE:a=this._transactions.ict[n.via_branch],a&&a.receiveResponse(n);break;case mt.ACK:break;default:a=this._transactions.nict[n.via_branch],a&&a.receiveResponse(n);break}}}}const wT=ze(bh);var _t=[];for(var tu=0;tu<256;++tu)_t.push((tu+256).toString(16).slice(1));function OT(c,t=0){return(_t[c[t+0]]+_t[c[t+1]]+_t[c[t+2]]+_t[c[t+3]]+"-"+_t[c[t+4]]+_t[c[t+5]]+"-"+_t[c[t+6]]+_t[c[t+7]]+"-"+_t[c[t+8]]+_t[c[t+9]]+"-"+_t[c[t+10]]+_t[c[t+11]]+_t[c[t+12]]+_t[c[t+13]]+_t[c[t+14]]+_t[c[t+15]]).toLowerCase()}var oa,DT=new Uint8Array(16);function NT(){if(!oa&&(oa=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!oa))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return oa(DT)}var UT=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Of={randomUUID:UT};function Df(c,t,n){if(Of.randomUUID&&!t&&!c)return Of.randomUUID();c=c||{};var a=c.random||(c.rng||NT)();if(a[6]=a[6]&15|64,a[8]=a[8]&63|128,t){n=n||0;for(var o=0;o<16;++o)t[n+o]=a[o];return t}return OT(a)}var ke=At();const Ts=ze(ke),su=new Ga("Dialog"),Fs={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};class ua{static get C(){return Fs}constructor(t,n,a,o=Fs.STATUS_CONFIRMED){if(this._owner=t,this._ua=t._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,n instanceof yt.IncomingResponse&&(o=n.status_code<200?Fs.STATUS_EARLY:Fs.STATUS_CONFIRMED),a==="UAS"){this._id={call_id:n.call_id,local_tag:n.to_tag,remote_tag:n.from_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=o,this._remote_seqnum=n.cseq,this._local_uri=n.parseHeader("to").uri,this._remote_uri=n.parseHeader("from").uri;let s=n.getHeaders("to")[0].split(";")[0];s=s.match(/<([^>]*)>/)[1],this._remote_target=s,this._route_set=n.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum}else if(a==="UAC"){this._id={call_id:n.call_id,local_tag:n.from_tag,remote_tag:n.to_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=o,this._local_seqnum=n.cseq,this._local_uri=n.parseHeader("from").uri,this._remote_uri=n.parseHeader("to").uri;let s=n.getHeaders("to")[0].split(";")[0];s=s.match(/<([^>]*)>/)[1],this._remote_target=s,this._route_set=n.getHeaders("record-route").reverse(),this._ack_seqnum=null}this._ua.newDialog(this),su.debug(`new ${a} dialog created with status ${this._state===Fs.STATUS_EARLY?"EARLY":"CONFIRMED"}`)}get id(){return this._id}get local_seqnum(){return this._local_seqnum}set local_seqnum(t){this._local_seqnum=t}get owner(){return this._owner}get uac_pending_reply(){return this._uac_pending_reply}set uac_pending_reply(t){this._uac_pending_reply=t}get uas_pending_reply(){return this._uas_pending_reply}isTerminated(){return this._status===Fs.STATUS_TERMINATED}update(t,n){this._state=Fs.STATUS_CONFIRMED,su.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),n==="UAC"&&(this._route_set=t.getHeaders("record-route").reverse())}terminate(){su.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=Fs.STATUS_TERMINATED}sendRequest(t,n={}){const a=Ts.cloneArray(n.extraHeaders),o=Ts.cloneObject(n.eventHandlers),s=n.body||null,r=this._createRequest(t,a,s);return o.onAuthenticated=()=>{this._local_seqnum+=1},new hg(this,r,o).send(),r}receiveRequest(t){this._checkInDialogRequest(t)&&(t.method===L.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:t.method===L.INVITE&&(this._ack_seqnum=t.cseq),this._owner.receiveRequest(t))}_createRequest(t,n,a){n=Ts.cloneArray(n),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));const o=t===L.CANCEL||t===L.ACK?this._local_seqnum:this._local_seqnum+=1;return new yt.OutgoingRequest(t,this._remote_target,this._ua,{cseq:o,call_id:this._id.call_id,from_uri:this._local_uri,from_tag:this._id.local_tag,to_uri:this._remote_uri,to_tag:this._id.remote_tag,route_set:this._route_set},n,a)}_checkInDialogRequest(t){if(!this._remote_seqnum)this._remote_seqnum=t.cseq;else if(t.cseq<this._remote_seqnum)if(t.method===L.ACK){if(this._ack_seqnum===null||t.cseq!==this._ack_seqnum)return!1}else return t.reply(500),!1;else t.cseq>this._remote_seqnum&&(this._remote_seqnum=t.cseq);if(t.method===L.INVITE||t.method===L.UPDATE&&t.body){if(this._uac_pending_reply===!0)t.reply(491);else if(this._uas_pending_reply===!0){const n=(Math.random()*10|0)+1;return t.reply(500,null,[`Retry-After:${n}`]),!1}else{this._uas_pending_reply=!0;const n=()=>{(t.server_transaction.state===Gt.C.STATUS_ACCEPTED||t.server_transaction.state===Gt.C.STATUS_COMPLETED||t.server_transaction.state===Gt.C.STATUS_TERMINATED)&&(t.server_transaction.removeListener("stateChanged",n),this._uas_pending_reply=!1)};t.server_transaction.on("stateChanged",n)}t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===Gt.C.STATUS_ACCEPTED&&(this._remote_target=t.parseHeader("contact").uri)})}else t.method===L.NOTIFY&&t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===Gt.C.STATUS_COMPLETED&&(this._remote_target=t.parseHeader("contact").uri)});return!0}}class PT{constructor(t,n){Kt(this,"plugin",null);Kt(this,"rtcpPeer",null);Kt(this,"handleId",0);Kt(this,"info",null);Kt(this,"joinResult",null);Kt(this,"state",{});Kt(this,"stream",null);Kt(this,"loaded",!1);Kt(this,"aTracks",[]);Kt(this,"vTracks",[]);this.info=t,this.plugin=n,this.rtcpPeer=new RTCPeerConnection({iceServers:[]})}get memberInfo(){return{stream:this.stream,joinResult:this.joinResult,sender:this.handleId,type:"subscriber",name:this.info.display,state:this.state,id:this.handleId}}updateMemberState(t){var n;this.state={...this.state,...t||{}},(n=this.plugin)==null||n.session.emit("member:update",this.memberInfo)}updateMemberStateFromMessage(t){var s,r,d,h;const n=(r=(s=t==null?void 0:t.plugindata)==null?void 0:s.data)==null?void 0:r.newStatePublisher,o=((h=(d=t==null?void 0:t.plugindata)==null?void 0:d.data)==null?void 0:h.publisher_state).find(_=>_.id===n);this.updateMemberState(o==null?void 0:o.state)}hangup(){this.rtcpPeer&&(this.rtcpPeer.close(),this.rtcpPeer=null),this.stream&&this.stream.getTracks().forEach(t=>{t.stop()})}}class Qt{static canGetMediaDevices(){return!(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)}static async getDevices(t){return Qt.canGetMediaDevices()?(await navigator.mediaDevices.enumerateDevices()).filter(a=>a.kind===t):[]}static async getMicrophoneList(){return(await Qt.getDevices("audioinput")).map((n,a)=>({...n,deviceId:n.deviceId,label:n.label||`microphone ${a+1}`,kind:n.kind,groupId:n.groupId}))}static async getSpeakerList(){return(await Qt.getDevices("audiooutput")).map((n,a)=>({...n,deviceId:n.deviceId,label:n.label||`speaker ${a+1}`,kind:n.kind,groupId:n.groupId}))}static async getCameraList(){return(await Qt.getDevices("videoinput")).map((n,a)=>({...n,deviceId:n.deviceId,label:n.label||`camera ${a+1}`,kind:n.kind,groupId:n.groupId}))}static stopStreamTracks(t){t&&t.getTracks().forEach(n=>{n.stop()})}static async getMediaFromInputs({videoInput:t,audioInput:n}){let a,o;t==="default"?a=!0:t&&t!=="default"&&(a={deviceId:{exact:t}}),n==="default"?o=!0:n&&n!=="default"&&(o={deviceId:{exact:n}});const s={audio:o,video:a};return Qt.getUserMedia(s)}static async getUserMedia(t){return await navigator.mediaDevices.getUserMedia(t)}static async changeAudioOutput(t,n){if(!(!t||!n))if(typeof t.sinkId<"u")try{await t.setSinkId(n)}catch(a){let o=a;a.name==="SecurityError"&&(o=`You need to use HTTPS for selecting audio output device: ${a}`),console.error(o)}else console.warn("Browser does not support output device selection.")}static toggleAudioMute(t){const n=t.getAudioTracks();if(n.length!==0)return n.forEach(a=>{a.enabled=!a.enabled}),n[0].enabled}static toggleVideoMute(t){const n=t.getVideoTracks();if(n.length!==0)return n.forEach(a=>{a.enabled=!a.enabled}),n[0].enabled}static async getStream(t={video:!0,audio:!0}){try{const n=await navigator.mediaDevices.getUserMedia(t);let a=n.getTracks();return t.video?a=n.getVideoTracks():t.audio&&(a=n.getAudioTracks()),a.length===0?{stream:n,track:null}:{stream:n,track:a[0]}}catch(n){return console.warn(n),{stream:null,track:null}}}}var xT=ys();const In=ze(xT),Pt={LEAVE:"Leave",DETACH:"Detach",AUDIO_CHANGE:"AudioChange",VIDEO_CHANGE:"VideoChange",STATE:"State",ICE:"Ice",CONFIGURE:"Configure",TRICKLE:"Trickle",SUBSCRIBER:"Subscriber",PUBLISHER:"Publisher"},z=new Ga("JanusSession"),kT="/opt/recordings/",te={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},ca=["audio","video"];class $a extends ft.EventEmitter{static get C(){return te}constructor(t){z.debug("new"),super(),this._id=null,this._ua=t,this._status=te.STATUS_NULL,this._dialog=null,this._earlyDialogs={},this._contact=null,this._from_tag=null,this._to_tag=null,this.lastTransaction=0,this._connection=null,this._connectionPromiseQueue=Promise.resolve(),this._request=null,this._is_canceled=!1,this._cancel_reason="",this._is_confirmed=!1,this._late_sdp=!1,this._rtcOfferConstraints=null,this._rtcAnswerConstraints=null,this._localMediaStream=null,this._localMediaStreamLocallyGenerated=!1,this._rtcReady=!0,this._iceReady=!1,this._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},this._direction=null,this._local_identity=null,this._remote_identity=null,this._start_time=null,this._end_time=null,this._audioMuted=!1,this._videoMuted=!1,this._localHold=!1,this._remoteHold=!1,this._sessionTimers={enabled:this._ua.configuration.session_timers,refreshMethod:this._ua.configuration.session_timers_refresh_method,defaultExpires:L.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._candidates=[],this.publishers=[],this.private_id=null,this.memberList={},this.myFeedList=[],this.display_name="",this.stunServers=[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}],this.opaque_id=this.generateOpaqueId(),this.screen_share_opaque_id=this.generateOpaqueId(),this._data={},this.isAudioOn=!0,this.isVideoOn=!0,this.mediaConstraints={}}get C(){return te}get causes(){return L.causes}get id(){return this._id}get connection(){return this._connection}get contact(){return this._contact}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}get start_time(){return this._start_time}get end_time(){return this._end_time}get data(){return this._data}set data(t){this._data=t}get status(){return this._status}isInProgress(){switch(this._status){case te.STATUS_NULL:case te.STATUS_INVITE_SENT:case te.STATUS_1XX_RECEIVED:case te.STATUS_INVITE_RECEIVED:case te.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case te.STATUS_ANSWERED:case te.STATUS_WAITING_FOR_ACK:case te.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case te.STATUS_CANCELED:case te.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}getPTypeHeader(t){return`PTYPE: ${t}`}generateOpaqueId(){return`videoroomtest-${Df().replace(/-/g,"").slice(0,12)}`}connect(t,n,a={},o){z.debug("connect()"),this.display_name=n;const s=t,r=ke.cloneObject(a.eventHandlers),d=ke.cloneArray(a.extraHeaders),h=ke.cloneObject(a.mediaConstraints,{audio:!0,video:!0});this.mediaConstraints={...h};const _=a.mediaStream||null,g=ke.cloneObject(a.pcConfig,{iceServers:[]}),T=a.rtcConstraints||null,E=a.rtcOfferConstraints||null;if(this._rtcOfferConstraints=E,this._rtcAnswerConstraints=a.rtcAnswerConstraints||null,this._data=a.data||this._data,t===void 0)throw new TypeError("Not enough arguments");if(this._status!==te.STATUS_NULL)throw new qs.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new qs.NotSupportedError("WebRTC not supported");if(t=this._ua.normalizeTarget(t),this.room_id=t.user,this.target=t,!t)throw new TypeError(`Invalid target: ${s}`);this._sessionTimers.enabled&&ke.isDecimal(a.sessionTimersExpires)&&(a.sessionTimersExpires>=L.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=a.sessionTimersExpires:this._sessionTimers.defaultExpires=L.SESSION_EXPIRES);for(const C in r)Object.prototype.hasOwnProperty.call(r,C)&&this.on(C,r[C]);this._from_tag=ke.newTag();const y=a.anonymous||!1,A={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:y,outbound:!0}),y?(A.from_display_name="Anonymous",A.from_uri=new In("sip","anonymous","anonymous.invalid"),d.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),d.push("Privacy: id")):a.fromUserName&&(A.from_uri=new In("sip",a.fromUserName,this._ua.configuration.uri.host),d.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),a.fromDisplayName&&(A.from_display_name=a.fromDisplayName),d.push(`Contact: ${this._contact}`),d.push("Content-Type: application/json"),this._sessionTimers.enabled&&d.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new yt.InitialOutgoingInviteRequest(t,this._ua,A,d),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(g,T),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,o&&o(this),this._newJanusSession("local",this._request),this._sendInitialRequest(h,E,_)}_overrideSenderTracks(t,n){t.getTracks().forEach(a=>{n.getSenders().forEach(async s=>{s.track.kind===a.kind&&(a.kind==="audio"&&!this.isAudioOn&&(a.enabled=!1),a.kind==="video"&&!this.isVideoOn&&(a.enabled=!1),await s.replaceTrack(a))})})}init_incoming(t,n){z.debug("init_incoming()");let a;const o=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;if(t.body&&o!=="application/sdp"){t.reply(415);return}if(this._status=te.STATUS_INVITE_RECEIVED,this._from_tag=t.from_tag,this._id=t.call_id+this._from_tag,this._request=t,this._contact=this._ua.contact.toString(),t.hasHeader("expires")&&(a=t.getHeader("expires")*1e3),t.to_tag=ke.newTag(),!this._createDialog(t,"UAS",!0)){t.reply(500,"Missing Contact header field");return}t.body?this._late_sdp=!1:this._late_sdp=!0,this._status=te.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{t.reply(408),this._failed("local",null,L.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),a&&(this._timers.expiresTimer=setTimeout(()=>{this._status===te.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),this._failed("system",null,L.causes.EXPIRES))},a)),this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from,n&&n(this),this._newJanusSession("remote",t),this._status!==te.STATUS_TERMINATED&&(t.reply(180,null,[`Contact: ${this._contact}`]),this._progress("local",null))}answer(t={}){z.debug("answer()");const n=this._request,a=ke.cloneArray(t.extraHeaders),o=ke.cloneObject(t.mediaConstraints),s=t.mediaStream||null,r=ke.cloneObject(t.pcConfig,{iceServers:[]}),d=t.rtcConstraints||null,h=t.rtcAnswerConstraints||null,_=ke.cloneObject(t.rtcOfferConstraints);let g,T=!1,E=!1,y=!1,A=!1;if(this._rtcAnswerConstraints=h,this._rtcOfferConstraints=t.rtcOfferConstraints||null,this._data=t.data||this._data,this._direction!=="incoming")throw new qs.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==te.STATUS_WAITING_FOR_ANSWER)throw new qs.InvalidStateError(this._status);if(this._sessionTimers.enabled&&ke.isDecimal(t.sessionTimersExpires)&&(t.sessionTimersExpires>=L.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=t.sessionTimersExpires:this._sessionTimers.defaultExpires=L.SESSION_EXPIRES),this._status=te.STATUS_ANSWERED,!this._createDialog(n,"UAS")){n.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),a.unshift(`Contact: ${this._contact}`);const C=n.parseSDP();Array.isArray(C.media)||(C.media=[C.media]);for(const I of C.media)I.type==="audio"&&(T=!0,(!I.direction||I.direction==="sendrecv")&&(y=!0)),I.type==="video"&&(E=!0,(!I.direction||I.direction==="sendrecv")&&(A=!0));if(s&&o.audio===!1){g=s.getAudioTracks();for(const I of g)s.removeTrack(I)}if(s&&o.video===!1){g=s.getVideoTracks();for(const I of g)s.removeTrack(I)}!s&&o.audio===void 0&&(o.audio=y),!s&&o.video===void 0&&(o.video=A),!s&&!T&&!_.offerToReceiveAudio&&(o.audio=!1),!s&&!E&&!_.offerToReceiveVideo&&(o.video=!1),this._createRTCConnection(r,d),Promise.resolve().then(()=>{if(s)return s;if(o.audio||o.video)return this._localMediaStreamLocallyGenerated=!0,this.loadStream().catch(I=>{throw this._status===te.STATUS_TERMINATED?new Error("terminated"):(n.reply(480),this._failed("local",null,L.causes.USER_DENIED_MEDIA_ACCESS),z.warn('emit "getusermediafailed" [error:%o]',I),this.emit("getusermediafailed",I),new Error("getUserMedia() failed"))})}).then(I=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=I,I&&I.getTracks().forEach(H=>{this._connection.addTrack(H,I)})}).then(()=>{if(this._late_sdp)return;const I={originator:"remote",type:"offer",sdp:n.body};z.debug('emit "sdp"'),this.emit("sdp",I);const H=new RTCSessionDescription({type:"offer",sdp:I.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(H)).catch($=>{throw n.reply(488),this._failed("system",null,L.causes.WEBRTC_ERROR),z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',$),this.emit("peerconnection:setremotedescriptionfailed",$),new Error("peerconnection.setRemoteDescription() failed")}),this._connectionPromiseQueue}).then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._connecting(n),this._late_sdp?this._createLocalDescription("offer",this._rtcOfferConstraints).catch(()=>{throw n.reply(500),new Error("_createLocalDescription() failed")}):this._createLocalDescription("answer",h).catch(()=>{throw n.reply(500),new Error("_createLocalDescription() failed")})}).then(I=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(n,a),n.reply(200,null,a,I,()=>{this._status=te.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(n,I),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,L.causes.CONNECTION_ERROR)})}).catch(I=>{this._status!==te.STATUS_TERMINATED&&z.warn(I)})}terminate(t={}){z.debug("terminate()");const n=t.cause||L.causes.BYE,a=ke.cloneArray(t.extraHeaders),o=t.body;let s,r=t.status_code,d=t.reason_phrase;if(this._status===te.STATUS_TERMINATED)throw new qs.InvalidStateError(this._status);switch(this._status){case te.STATUS_NULL:case te.STATUS_INVITE_SENT:case te.STATUS_1XX_RECEIVED:if(z.debug("canceling session"),r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);r&&(d=d||L.REASON_PHRASE[r]||"",s=`SIP ;cause=${r} ;text="${d}"`),this._status===te.STATUS_NULL||this._status===te.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=s):this._status===te.STATUS_1XX_RECEIVED&&this._request.cancel(s),this._status=te.STATUS_CANCELED,this._failed("local",null,L.causes.CANCELED);break;case te.STATUS_WAITING_FOR_ANSWER:case te.STATUS_ANSWERED:if(z.debug("rejecting session"),r=r||480,r<300||r>=700)throw new TypeError(`Invalid status_code: ${r}`);this._request.reply(r,d,a,o),this._failed("local",null,L.causes.REJECTED);break;case te.STATUS_WAITING_FOR_ACK:case te.STATUS_CONFIRMED:if(z.debug("terminating session"),d=t.reason_phrase||L.REASON_PHRASE[r]||"",r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);if(r&&a.push(`Reason: SIP ;cause=${r}; text="${d}"`),this._status===te.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Gt.C.STATUS_TERMINATED){const h=this._dialog;this.receiveRequest=({method:_})=>{_===L.ACK&&(this.sendRequest(L.BYE,{extraHeaders:a,body:o}),h.terminate(),this.closeSession())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Gt.C.STATUS_TERMINATED&&(this.sendRequest(L.BYE,{extraHeaders:a,body:o}),h.terminate(),this.closeSession())}),this._ended("local",null,n),this._dialog=h,this._ua.newDialog(h)}else{const h={janus:"leave"},_=["Content-Type: application/json",this.getPTypeHeader(Pt.LEAVE)];this.sendRequest(L.BYE,{extraHeaders:_,body:JSON.stringify(h)}),this.closeSession(),this._ended("local",null,n)}}}configureMedia(t){this.isAudioOn=t.audio,this.isVideoOn=t.video}enableAudio(t){const n={janus:"message",body:{audio:t},handle_id:this.handle_id,session_id:this.session_id},a=["Content-Type: application/json",this.getPTypeHeader(Pt.AUDIO_CHANGE)];this.sendRequest(L.INFO,{extraHeaders:a,body:JSON.stringify(n),eventHandlers:{onSuccessResponse:async o=>{o.status_code===200&&(this._ua.emit("changeAudioState",t),this.sendStateMessage({audio:t}))}}})}startAudio(){Qt.toggleAudioMute(this.stream),this._toggleMuteAudio(!1),this.enableAudio(!0),this.isAudioOn=!0}stopAudio(){Qt.toggleAudioMute(this.stream),this._toggleMuteAudio(!0),this.enableAudio(!1),this.isAudioOn=!1}enableVideo(t){const n={janus:"message",body:{video:t},handle_id:this.handle_id,session_id:this.session_id},a=["Content-Type: application/json",this.getPTypeHeader(Pt.VIDEO_CHANGE)];this.sendRequest(L.INFO,{extraHeaders:a,body:JSON.stringify(n),eventHandlers:{onSuccessResponse:async o=>{o.status_code===200&&(this._ua.emit("changeVideoState",t),this.sendStateMessage({video:t}))}}})}startVideo(){Qt.toggleVideoMute(this.stream),this._toggleMuteVideo(!1),this.enableVideo(!0),this.isVideoOn=!0}stopVideo(){Qt.toggleVideoMute(this.stream),this._toggleMuteVideo(!0),this.enableVideo(!1),this.isVideoOn=!1}sendStateMessage(t){const n={janus:"message",body:{request:"state",data:t},handle_id:this.handle_id,session_id:this.session_id},a=["Content-Type: application/json",this.getPTypeHeader(Pt.STATE)];this.sendRequest(L.INFO,{extraHeaders:a,body:JSON.stringify(n)})}sendInfo(t,n,a={}){if(z.debug("sendInfo()"),this._status!==te.STATUS_CONFIRMED&&this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_1XX_RECEIVED)throw new qs.InvalidStateError(this._status);new yu(this).send(t,n,a)}mute(t={audio:!0,video:!1}){z.debug("mute()");let n=!1,a=!1;this._audioMuted===!1&&t.audio&&(n=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&t.video&&(a=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(n===!0||a===!0)&&this._onmute({audio:n,video:a})}unmute(t={audio:!0,video:!0}){z.debug("unmute()");let n=!1,a=!1;this._audioMuted===!0&&t.audio&&(n=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&t.video&&(a=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(n===!0||a===!0)&&this._onunmute({audio:n,video:a})}hold(t={},n){if(z.debug("hold()"),this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");const a={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:L.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:a,extraHeaders:t.extraHeaders}),!0}unhold(t={},n){if(z.debug("unhold()"),this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");const a={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:L.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:a,extraHeaders:t.extraHeaders}),!0}renegotiate(t={},n){z.debug("renegotiate()");const a=t.rtcOfferConstraints||null;if(this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;const o={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:L.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:o,rtcOfferConstraints:a,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:o,rtcOfferConstraints:a,extraHeaders:t.extraHeaders}),!0}refer(t,n){z.debug("refer()");const a=t;if(this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${a}`);const o=new Ng(this);o.sendRefer(t,n);const s=o.id;return this._referSubscribers[s]=o,o.on("requestFailed",()=>{delete this._referSubscribers[s]}),o.on("accepted",()=>{delete this._referSubscribers[s]}),o.on("failed",()=>{delete this._referSubscribers[s]}),o}sendRequest(t,n){return z.debug("sendRequest()"),this._dialog.sendRequest(t,n)}receiveNotify(t){z.debug("receiveRequest()")}receiveRequest(t){if(z.debug("receiveRequest()"),t.method===L.CANCEL)(this._status===te.STATUS_WAITING_FOR_ANSWER||this._status===te.STATUS_ANSWERED)&&(this._status=te.STATUS_CANCELED,this._request.reply(487),this._failed("remote",t,L.causes.CANCELED));else switch(t.method){case L.ACK:if(this._status!==te.STATUS_WAITING_FOR_ACK)return;if(this._status=te.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!t.body){this.terminate({cause:L.causes.MISSING_SDP,status_code:400});break}const n={originator:"remote",type:"answer",sdp:t.body};z.debug('emit "sdp"'),this.emit("sdp",n);const a=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>{this._is_confirmed||this._confirmed("remote",t)}).catch(o=>{this.terminate({cause:L.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',o),this.emit("peerconnection:setremotedescriptionfailed",o)})}else this._is_confirmed||this._confirmed("remote",t);break;case L.BYE:this._status===te.STATUS_CONFIRMED||this._status===te.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,L.causes.BYE)):this._status===te.STATUS_INVITE_RECEIVED||this._status===te.STATUS_WAITING_FOR_ANSWER?(t.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",t,L.causes.BYE)):t.reply(403,"Wrong Status");break;case L.INVITE:this._status===te.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case L.INFO:if(this._status===te.STATUS_1XX_RECEIVED||this._status===te.STATUS_WAITING_FOR_ANSWER||this._status===te.STATUS_ANSWERED||this._status===te.STATUS_WAITING_FOR_ACK||this._status===te.STATUS_CONFIRMED){const n=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;n&&n.match(/^application\/dtmf-relay/i)?new Eg(this).init_incoming(t):n!==void 0?new yu(this).init_incoming(t):t.reply(415)}else t.reply(403,"Wrong Status");break;case L.UPDATE:this._status===te.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case L.REFER:this._status===te.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case L.NOTIFY:this._status===te.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){z.warn("onTransportError()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:L.causes.CONNECTION_ERROR,cause:L.causes.CONNECTION_ERROR})}onRequestTimeout(){z.warn("onRequestTimeout()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:L.causes.REQUEST_TIMEOUT,cause:L.causes.REQUEST_TIMEOUT})}onDialogError(){z.warn("onDialogError()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:L.causes.DIALOG_ERROR,cause:L.causes.DIALOG_ERROR})}newDTMF(t){z.debug("newDTMF()"),this.emit("newDTMF",t)}newInfo(t){z.debug("newInfo()"),this.emit("newInfo",t)}_isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(z.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(z.debug("_isReadyToReOffer() | session not established yet"),!1):(z.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}_close(){if(z.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(z.debug("close() | closing local MediaStream"),ke.closeMediaStream(this._localMediaStream)),this._status!==te.STATUS_TERMINATED){if(this._status=te.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(t){z.warn("close() | error closing the RTCPeerConnection: %o",t)}for(const t in this._timers)Object.prototype.hasOwnProperty.call(this._timers,t)&&clearTimeout(this._timers[t]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const t in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,t)&&(this._earlyDialogs[t].terminate(),delete this._earlyDialogs[t]);for(const t in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,t)&&delete this._referSubscribers[t];this._ua.destroyRTCSession(this)}}_setInvite2xxTimer(t,n){let a=$i.T1;function o(){this._status===te.STATUS_WAITING_FOR_ACK&&(t.reply(200,null,[`Contact: ${this._contact}`],n),a<$i.T2&&(a=a*2,a>$i.T2&&(a=$i.T2)),this._timers.invite2xxTimer=setTimeout(o.bind(this),a))}this._timers.invite2xxTimer=setTimeout(o.bind(this),a)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===te.STATUS_WAITING_FOR_ACK&&(z.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(L.BYE),this._ended("remote",null,L.causes.NO_ACK))},$i.TIMER_H)}_createRTCConnection(t,n){this.stunServers,this._connection=new RTCPeerConnection(t,n),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:L.causes.RTP_TIMEOUT,status_code:408,reason_phrase:L.causes.RTP_TIMEOUT})});let a;const o=s=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||s.candidate&&(this._candidates.push(s.candidate),clearTimeout(a),a=setTimeout(()=>{this.lastTrickleReceived=!0,this.subscribeSent&&!this.isConfigureSent&&(this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream}),this._sendConfigureMessage({audio:!0,video:!0}).then(()=>{}))},500))};this._connection.onicecandidate=o,z.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(t,n){if(z.debug("createLocalDescription()"),t!=="offer"&&t!=="answer")throw new Error(`createLocalDescription() | invalid type "${t}"`);const a=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>t==="offer"?a.createOffer(n).catch(o=>(z.warn('emit "peerconnection:createofferfailed" [error:%o]',o),this.emit("peerconnection:createofferfailed",o),Promise.reject(o))):a.createAnswer(n).catch(o=>(z.warn('emit "peerconnection:createanswerfailed" [error:%o]',o),this.emit("peerconnection:createanswerfailed",o),Promise.reject(o)))).then(o=>(this.jsepOffer=o,a.setLocalDescription(o).catch(s=>(this._rtcReady=!0,z.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',s),this.emit("peerconnection:setlocaldescriptionfailed",s),Promise.reject(s))))).then(()=>{const o=n&&n.iceRestart;if(a.iceGatheringState==="complete"&&!o||a.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const s={originator:"local",type:t,sdp:a.localDescription.sdp};return z.debug('emit "sdp"'),this.emit("sdp",s),Promise.resolve(s.sdp)}return new Promise(s=>{let r=!1,d,h;this._iceReady=!1;const _=()=>{a.removeEventListener("icecandidate",d),a.removeEventListener("icegatheringstatechange",h),r=!0,this._rtcReady=!0,this._iceReady=!0;const g={originator:"local",type:t,sdp:a.localDescription.sdp};z.debug('emit "sdp"'),this.emit("sdp",g),s(g.sdp)};a.addEventListener("icecandidate",d=g=>{const T=g.candidate;T?this.emit("icecandidate",{candidate:T,ready:_}):r||_()}),a.addEventListener("icegatheringstatechange",h=()=>{a.iceGatheringState==="complete"&&!r&&_()})})})}_createDialog(t,n,a){const o=n==="UAS"?t.to_tag:t.from_tag,s=n==="UAS"?t.from_tag:t.to_tag,r=t.call_id+o+s;let d=this._earlyDialogs[r];if(a)return d?!0:(d=new ua(this,t,n,ua.C.STATUS_EARLY),d.error?(z.debug(d.error),this._failed("remote",t,L.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[r]=d,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,d)return d.update(t,n),this._dialog=d,delete this._earlyDialogs[r],!0;const h=new ua(this,t,n);return h.error?(z.debug(h.error),this._failed("remote",t,L.causes.INTERNAL_ERROR),!1):(this._dialog=h,!0)}}_receiveReinvite(t){z.debug("receiveReinvite()");const n=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,a={request:t,callback:void 0,reject:s.bind(this)};let o=!1;function s(d={}){o=!0;const h=d.status_code||403,_=d.reason_phrase||"",g=ke.cloneArray(d.extraHeaders);if(this._status!==te.STATUS_CONFIRMED)return!1;if(h<300||h>=700)throw new TypeError(`Invalid status_code: ${h}`);t.reply(h,_,g)}if(this.emit("reinvite",a),o)return;if(this._late_sdp=!1,!t.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",this._rtcOfferConstraints)).then(d=>{r.call(this,d)}).catch(()=>{t.reply(500)});return}if(n!=="application/sdp"){z.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(d=>{this._status!==te.STATUS_TERMINATED&&r.call(this,d)}).catch(d=>{z.warn(d)});function r(d){const h=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,h),this._late_sdp&&(d=this._mangleOffer(d)),t.reply(200,null,h,d,()=>{this._status=te.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(t,d),this._setACKTimer()}),typeof a.callback=="function"&&a.callback()}}_receiveUpdate(t){z.debug("receiveUpdate()");const n=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,a={request:t,callback:void 0,reject:s.bind(this)};let o=!1;function s(d={}){o=!0;const h=d.status_code||403,_=d.reason_phrase||"",g=ke.cloneArray(d.extraHeaders);if(this._status!==te.STATUS_CONFIRMED)return!1;if(h<300||h>=700)throw new TypeError(`Invalid status_code: ${h}`);t.reply(h,_,g)}if(this.emit("update",a),o)return;if(!t.body){r.call(this,null);return}if(n!=="application/sdp"){z.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(d=>{this._status!==te.STATUS_TERMINATED&&r.call(this,d)}).catch(d=>{z.warn(d)});function r(d){const h=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,h),t.reply(200,null,h,d),typeof a.callback=="function"&&a.callback()}}_processInDialogSdpOffer(t){z.debug("_processInDialogSdpOffer()");const n=t.parseSDP();let a=!1;for(const r of n.media){if(ca.indexOf(r.type)===-1)continue;const d=r.direction||n.direction||"sendrecv";if(d==="sendonly"||d==="inactive")a=!0;else{a=!1;break}}const o={originator:"remote",type:"offer",sdp:t.body};z.debug('emit "sdp"'),this.emit("sdp",o);const s=new RTCSessionDescription({type:"offer",sdp:o.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._connection.setRemoteDescription(s).catch(r=>{throw t.reply(488),z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',r),this.emit("peerconnection:setremotedescriptionfailed",r),r})}).then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._remoteHold===!0&&a===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&a===!0&&(this._remoteHold=!0,this._onhold("remote"))}).then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._createLocalDescription("answer",this._rtcAnswerConstraints).catch(r=>{throw t.reply(500),z.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',r),r})}).catch(r=>{z.warn("_processInDialogSdpOffer() failed [error: %o]",r)}),this._connectionPromiseQueue}_receiveRefer(t){if(z.debug("receiveRefer()"),!t.refer_to){z.debug("no Refer-To header field present in REFER"),t.reply(400);return}if(t.refer_to.uri.scheme!==L.SIP){z.debug("Refer-To header field points to a non-SIP URI scheme"),t.reply(416);return}t.reply(202);const n=new bg(this,t.cseq);z.debug('emit "refer"'),this.emit("refer",{request:t,accept:(s,r)=>{a.call(this,s,r)},reject:()=>{o.call(this)}});function a(s,r={}){if(s=typeof s=="function"?s:null,this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;const d=new $a(this._ua);if(d.on("progress",({response:h})=>{n.notify(h.status_code,h.reason_phrase)}),d.on("accepted",({response:h})=>{n.notify(h.status_code,h.reason_phrase)}),d.on("_failed",({message:h,cause:_})=>{h?n.notify(h.status_code,h.reason_phrase):n.notify(487,_)}),t.refer_to.uri.hasHeader("replaces")){const h=decodeURIComponent(t.refer_to.uri.getHeader("replaces"));r.extraHeaders=ke.cloneArray(r.extraHeaders),r.extraHeaders.push(`Replaces: ${h}`)}d.connect(t.refer_to.uri.toAor(),r,s)}function o(){n.notify(603)}}_receiveNotify(t){switch(z.debug("receiveNotify()"),t.event||t.reply(400),t.event.event){case"refer":{let n,a;if(t.event.params&&t.event.params.id)n=t.event.params.id,a=this._referSubscribers[n];else if(Object.keys(this._referSubscribers).length===1)a=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{t.reply(400,"Missing event id parameter");return}if(!a){t.reply(481,"Subscription does not exist");return}a.receiveNotify(t),t.reply(200);break}default:t.reply(489)}}_receiveReplaces(t){z.debug("receiveReplaces()");function n(o){if(this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;const s=new $a(this._ua);s.on("confirmed",()=>{this.terminate()}),s.init_incoming(t,o)}function a(){z.debug("Replaced INVITE rejected by the user"),t.reply(486)}this.emit("replaces",{request:t,accept:o=>{n.call(this,o)},reject:()=>{a.call(this)}})}_getNextTransactionId(){return(this.lastTransaction+1).toString()}_sendInitialRequest(t,n,a){this.ackSent=!1,this.publisherSubscribeSent=!1;const o=new sl(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});Promise.resolve().then(()=>{if(a)return a;if(t.audio||t.video)return this._localMediaStreamLocallyGenerated=!0,this.loadStream().catch(s=>{throw this._status===te.STATUS_TERMINATED?new Error("terminated"):(this._failed("local",null,L.causes.USER_DENIED_MEDIA_ACCESS),z.warn('emit "getusermediafailed" [error:%o]',s),this.emit("getusermediafailed",s),s)})}).then(s=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._localMediaStream=s,s&&s.getTracks().forEach(r=>{this._connection.addTrack(r,s)}),this._connecting(this._request),this._createLocalDescription("offer",n).catch(r=>{throw this._failed("local",null,L.causes.WEBRTC_ERROR),r})}).then(s=>{if(this._is_canceled||this._status===te.STATUS_TERMINATED)throw new Error("terminated");const r={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaque_id},d=JSON.stringify(r);this._request.body=d,this._status=te.STATUS_INVITE_SENT,z.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),o.send()}).catch(s=>{this._status!==te.STATUS_TERMINATED&&z.warn(s)})}async requestAudioAndVideoPermissions(){this.stream=await this.loadStream()}async setupMediaStream(){await this.requestAudioAndVideoPermissions(),await this.processPlugins()}async changeMediaConstraints(t){this.mediaConstraints={...t},await this.processPlugins(),this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream})}async loadStream(){const t={};this.isAudioOn?this.mediaConstraints.audio?t.audio=this.mediaConstraints.audio:t.audio=!0:t.audio=!1,this.isVideoOn?this.mediaConstraints.video?t.video=this.mediaConstraints.video:t.video=!0:t.video=!1;let n=null;try{n=await navigator.mediaDevices.getUserMedia(t)}catch{try{t.video=!1,n=await navigator.mediaDevices.getUserMedia(t)}catch{t.audio=!1,t.video=!1,n=await navigator.mediaDevices.getUserMedia(t)}}return n}addTracks(t){this._connection.getSenders().forEach(n=>{this._connection.removeTrack(n)}),t.forEach(n=>{this._connection.addTrack(n)})}getRecordFileName(){return kT+this.room_id+btoa(unescape(encodeURIComponent(this.displayName)))+Date.now()}async processIceCandidates(){for(let t=0;t<this.iceCandidates.length;t++)await this._connection.addIceCandidate(this.iceCandidates[t]);this.iceCandidates=[]}async _sendConfigureMessage(t){const n=this._candidates.map(r=>({janus:"trickle",candidate:r,handle_id:this.handle_id,session_id:this.session_id})),o={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.getRecordFileName(),...t},jsep:this.jsepOffer,handle_id:this.handle_id,session_id:this.session_id},trickles:[...n]},s=["Content-Type: application/json",this.getPTypeHeader(Pt.ICE)];this.sendRequest(L.INFO,{extraHeaders:s,body:JSON.stringify(o),eventHandlers:{onSuccessResponse:async r=>{this.isConfigureSent=!0;const h=r.data.split(`\r
|
135
135
|
`),_=h[h.length-1],g=JSON.parse(_);await this._connection.setRemoteDescription(g.jsep),this._candidates=[]}}})}_sendMemberStartMessage(t,n){const a={janus:"message",body:{request:"start",room:this.room_id},handle_id:t.handleId,session_id:this.session_id,jsep:n},o=["Content-Type: application/json",this.getPTypeHeader(Pt.CONFIGURE)];this.sendRequest(L.INFO,{extraHeaders:o,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async s=>{s.status_code===200&&await t.rtcpPeer.setLocalDescription(n)}}})}_sendTrickleMessage(t){const a={trickles:[...t.map(s=>({janus:"trickle",candidate:s,handle_id:this.handle_id,session_id:this.session_id}))]},o=[this.getPTypeHeader(Pt.TRICKLE)];this.sendRequest(L.INFO,{extraHeaders:o,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async s=>{}}})}async _answerAttachedStream(t,n){let a=null;const o=async h=>{if(!t.rtcpPeer||t.loaded)return;{t.loaded=!0;const y={audio:!0,video:!0};await new Promise(A=>{setTimeout(A,100)}),a=await t.rtcpPeer.createAnswer(y),this._sendMemberStartMessage(t,a)}const _=h.streams[0].getAudioTracks(),g=h.streams[0].getVideoTracks(),T=[];_[0]&&T.push(_[0]),g[0]&&T.push(g[0]);const E=new MediaStream(T);t.stream=E,this._ua.emit("memberJoin",t.memberInfo)};let s,r=[];const d=h=>{t.rtcpPeer.signalingState!=="stable"&&t.rtcpPeer.signalingState!=="have-local-offer"||(r.push(h.candidate||null),clearTimeout(s),s=setTimeout(()=>{this._sendTrickleMessage(r)},500))};t.rtcpPeer=new RTCPeerConnection,t.rtcpPeer.ontrack=o,t.rtcpPeer.onicecandidate=d,t.rtcpPeer.sender=n.sender,await t.rtcpPeer.setRemoteDescription(n.jsep)}_sendJoinMemberRequest(t){const n={janus:"message",body:{request:"join",room:this.room_id,feed:t.info.id,ptype:"subscriber"},handle_id:t.handleId,session_id:this.session_id},a=[this.getPTypeHeader(Pt.SUBSCRIBER)];this.sendRequest(L.SUBSCRIBE,{extraHeaders:a,body:JSON.stringify(n),eventHandlers:{onSuccessResponse:async o=>{var s,r;if(o.status_code===200){const d=JSON.parse(o.body);(r=(s=d==null?void 0:d.plugindata)==null?void 0:s.data)!=null&&r.id&&await this._answerAttachedStream(t,d)}}}})}_attachMember(t){const n={janus:"attach",opaque_id:this.opaque_id,plugin:"janus.plugin.videoroom",session_id:this.session_id},a=[this.getPTypeHeader(Pt.SUBSCRIBER)];this.sendRequest(L.INFO,{extraHeaders:a,body:JSON.stringify(n),eventHandlers:{onSuccessResponse:async o=>{if(o.status_code===200){const r=JSON.parse(o.body).data.id;t.handleId=r,this._sendJoinMemberRequest(t)}}}})}_detachMember(t){const n={janus:"detach",handle_id:t.handleId,session_id:this.session_id},a=[this.getPTypeHeader(Pt.SUBSCRIBER)];this.sendRequest(L.INFO,{extraHeaders:a,body:JSON.stringify(n)}),Qt.stopStreamTracks(t.memberInfo.stream),this._ua.emit("memberHangup",t.memberInfo)}receivePublishers(t){var a,o,s,r,d,h,_,g;const n={...this.memberList};(o=(a=t==null?void 0:t.plugindata)==null?void 0:a.data)==null||o.publishers.forEach(T=>{delete n[T.id],!this.memberList[T.id]&&!this.myFeedList.includes(T.id)&&T.clientID!==this.client_id&&(this.memberList[T.id]=new PT(T,this),this._attachMember(this.memberList[T.id]))}),((r=(s=t==null?void 0:t.plugindata)==null?void 0:s.data)==null?void 0:r.videoroom)==="synced"&&Object.keys(n).forEach(T=>{n[T].hangup(),delete this.memberList[T]}),this.publishers=(h=(d=t==null?void 0:t.plugindata)==null?void 0:d.data)==null?void 0:h.publishers,this.private_id=(g=(_=t==null?void 0:t.plugindata)==null?void 0:_.data)==null?void 0:g.private_id}receiveUnpublished(t){const n=this.memberList[t];n&&(n.hangup(),this._detachMember(n),delete this.memberList[t])}closeSession(){this.stream&&this.stream.getTracks().forEach(n=>{n.stop()}),Object.values(this.memberList).forEach(n=>{n.hangup(),this._detachMember(n)}),this._ua.emit("conferenceEnd",this.id)}async processPlugins(){const t=this._ua.processStreamPlugins;let n=await this.loadStream();for(const a of t)n=await a.process(n);this.stream.getTracks().forEach(a=>{this.stream.removeTrack(a),a.stop()}),n.getTracks().forEach(a=>{this.stream.addTrack(a)})}async resyncPlugins(t){const n=this._ua.processStreamPlugins.filter(a=>a.type===t);for(const a of n)a.running&&a.terminate();if(t==="video"){let a=await this.loadStream();for(const o of n)o.running&&(a=await o.start(a));this.stream.getTracks().forEach(o=>{this.stream.removeTrack(o),o.stop()}),a.getTracks().forEach(o=>{this.stream.addTrack(o)}),this._overrideSenderTracks(this.stream,this._connection),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream})}else{const a=this._ua.newStreamPlugins.find(d=>d.type===t);let s=a.getStream().clone();for(const d of n)d.running&&(s=await d.start(s));const r=a.getConnection();this._overrideSenderTracks(s,r),this._ua.emit("changePluginStream",{type:t,stream:s})}}stopProcessPlugins(t){const n=this._ua.processStreamPlugins.filter(a=>a.type===t);for(const a of n)a.running&&a.kill()}_receiveInviteResponse(t){if(z.debug("receiveInviteResponse()"),this._dialog&&t.status_code>=200&&t.status_code<=299&&!this.ackSent)if(this._dialog.id.call_id===t.call_id&&this._dialog.id.local_tag===t.from_tag&&this._dialog.id.remote_tag===t.to_tag){this.ackSent=!0,this.sendRequest(L.ACK);return}else{const n=new ua(this,t,"UAC");if(n.error!==void 0){z.debug(n.error);return}this.sendRequest(L.ACK),this.sendRequest(L.BYE);return}if(this.ackSent&&!this.publisherSubscribeSent){const n=JSON.parse(t.body);this.setupMediaStream().then(()=>{this.session_id=n.session_id,this.handle_id=n.data.id,this.client_id=Df();const a={janus:"message",body:{request:"join",room:this.room_id,ptype:"publisher",display:this.display_name,clientID:this.client_id,opaque_id:this.opaque_id},handle_id:this.handle_id},o=[this.getPTypeHeader(Pt.PUBLISHER)];this.sendRequest(L.SUBSCRIBE,{extraHeaders:o,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async s=>{var r,d,h,_;if(s.status_code===200){if(this.subscribeSent=!0,s.body)try{const g=JSON.parse(s.body)||{};((d=(r=g.plugindata)==null?void 0:r.data)==null?void 0:d.videoroom)==="joined"&&this.myFeedList.push(g.plugindata.data.id),(_=(h=g.plugindata)==null?void 0:h.data)!=null&&_.publishers&&this.receivePublishers(g)}catch(g){console.error(g)}this.lastTrickleReceived&&!this.isConfigureSent&&(this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream}),this._sendConfigureMessage({audio:!0,video:!0}).then(()=>{})),this._ua.emit("conferenceStart")}}}}),this.publisherSubscribeSent=!0})}if(this._is_canceled){t.status_code>=100&&t.status_code<200?this._request.cancel(this._cancel_reason):t.status_code>=200&&t.status_code<299&&this._acceptAndTerminate(t);return}if(!(this._status!==te.STATUS_INVITE_SENT&&this._status!==te.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(t.status_code):this._status=te.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(t.status_code):{if(!t.to_tag){z.debug("1xx response received without to tag");break}if(t.hasHeader("contact")&&!this._createDialog(t,"UAC",!0))break;if(this._status=te.STATUS_1XX_RECEIVED,!t.body){this._progress("remote",t);break}const n={originator:"remote",type:"answer",sdp:t.body};z.debug('emit "sdp"'),this.emit("sdp",n);const a=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>this._progress("remote",t)).catch(o=>{z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',o),this.emit("peerconnection:setremotedescriptionfailed",o)});break}case/^2[0-9]{2}$/.test(t.status_code):{if(this._status=te.STATUS_CONFIRMED,!t.body){this._acceptAndTerminate(t,400,L.causes.MISSING_SDP),this._failed("remote",t,L.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(t,"UAC"))break;break}default:{const n=ke.sipErrorCause(t.status_code);this._failed("remote",t,n)}}}_sendReinvite(t={}){z.debug("sendReinvite()");const n=ke.cloneArray(t.extraHeaders),a=ke.cloneObject(t.eventHandlers),o=t.rtcOfferConstraints||this._rtcOfferConstraints||null;let s=!1;n.push(`Contact: ${this._contact}`),n.push("Content-Type: application/sdp"),this._sessionTimers.running&&n.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",o)).then(h=>{h=this._mangleOffer(h);const _={originator:"local",type:"offer",sdp:h};z.debug('emit "sdp"'),this.emit("sdp",_),this.sendRequest(L.INVITE,{extraHeaders:n,body:h,eventHandlers:{onSuccessResponse:g=>{r.call(this,g),s=!0},onErrorResponse:g=>{d.call(this,g)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{d()});function r(h){if(this._status===te.STATUS_TERMINATED||(this.sendRequest(L.ACK),s))return;if(this._handleSessionTimersInIncomingResponse(h),h.body){if(!h.hasHeader("Content-Type")||h.getHeader("Content-Type").toLowerCase()!=="application/sdp"){d.call(this);return}}else{d.call(this);return}const _={originator:"remote",type:"answer",sdp:h.body};z.debug('emit "sdp"'),this.emit("sdp",_);const g=new RTCSessionDescription({type:"answer",sdp:_.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(g)).then(()=>{a.succeeded&&a.succeeded(h)}).catch(T=>{d.call(this),z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',T),this.emit("peerconnection:setremotedescriptionfailed",T)})}function d(h){a.failed&&a.failed(h)}}_sendUpdate(t={}){z.debug("sendUpdate()");const n=ke.cloneArray(t.extraHeaders),a=ke.cloneObject(t.eventHandlers),o=t.rtcOfferConstraints||this._rtcOfferConstraints||null,s=t.sdpOffer||!1;let r=!1;n.push(`Contact: ${this._contact}`),this._sessionTimers.running&&n.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),s?(n.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",o)).then(_=>{_=this._mangleOffer(_);const g={originator:"local",type:"offer",sdp:_};z.debug('emit "sdp"'),this.emit("sdp",g),this.sendRequest(L.UPDATE,{extraHeaders:n,body:_,eventHandlers:{onSuccessResponse:T=>{d.call(this,T),r=!0},onErrorResponse:T=>{h.call(this,T)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{h.call(this)})):this.sendRequest(L.UPDATE,{extraHeaders:n,eventHandlers:{onSuccessResponse:_=>{d.call(this,_)},onErrorResponse:_=>{h.call(this,_)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function d(_){if(this._status!==te.STATUS_TERMINATED&&!r)if(this._handleSessionTimersInIncomingResponse(_),s){if(_.body){if(!_.hasHeader("Content-Type")||_.getHeader("Content-Type").toLowerCase()!=="application/sdp"){h.call(this);return}}else{h.call(this);return}const g={originator:"remote",type:"answer",sdp:_.body};z.debug('emit "sdp"'),this.emit("sdp",g);const T=new RTCSessionDescription({type:"answer",sdp:g.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(T)).then(()=>{a.succeeded&&a.succeeded(_)}).catch(E=>{h.call(this),z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',E),this.emit("peerconnection:setremotedescriptionfailed",E)})}else a.succeeded&&a.succeeded(_)}function h(_){a.failed&&a.failed(_)}}_acceptAndTerminate(t,n,a){z.debug("acceptAndTerminate()");const o=[];n&&(a=a||L.REASON_PHRASE[n]||"",o.push(`Reason: SIP ;cause=${n}; text="${a}"`)),(this._dialog||this._createDialog(t,"UAC"))&&(this.sendRequest(L.ACK),this.sendRequest(L.BYE,{extraHeaders:o})),this._status=te.STATUS_TERMINATED}_mangleOffer(t){if(!this._localHold&&!this._remoteHold)return t;if(t=xt.parse(t),this._localHold&&!this._remoteHold){z.debug("mangleOffer() | me on hold, mangling offer");for(const n of t.media)ca.indexOf(n.type)!==-1&&(n.direction?n.direction==="sendrecv"?n.direction="sendonly":n.direction==="recvonly"&&(n.direction="inactive"):n.direction="sendonly")}else if(this._localHold&&this._remoteHold){z.debug("mangleOffer() | both on hold, mangling offer");for(const n of t.media)ca.indexOf(n.type)!==-1&&(n.direction="inactive")}else if(this._remoteHold){z.debug("mangleOffer() | remote on hold, mangling offer");for(const n of t.media)ca.indexOf(n.type)!==-1&&(n.direction?n.direction==="sendrecv"?n.direction="recvonly":n.direction==="recvonly"&&(n.direction="inactive"):n.direction="recvonly")}return xt.write(t)}_setLocalMediaStatus(){let t=!0,n=!0;(this._localHold||this._remoteHold)&&(t=!1,n=!1),this._audioMuted&&(t=!1),this._videoMuted&&(n=!1),this._toggleMuteAudio(!t),this._toggleMuteVideo(!n)}_handleSessionTimersInIncomingRequest(t,n){if(!this._sessionTimers.enabled)return;let a;t.session_expires&&t.session_expires>=L.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,a=t.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,a="uas"),n.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${a}`),this._sessionTimers.refresher=a==="uas",this._runSessionTimer()}_handleSessionTimersInIncomingResponse(t){if(!this._sessionTimers.enabled)return;let n;t.session_expires&&t.session_expires>=L.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,n=t.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,n="uac"),this._sessionTimers.refresher=n==="uac",this._runSessionTimer()}_runSessionTimer(){const t=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(()=>{this._status!==te.STATUS_TERMINATED&&this._isReadyToReOffer()&&(z.debug("runSessionTimer() | sending session refresh request"),this._sessionTimers.refreshMethod===L.UPDATE?this._sendUpdate():this._sendReinvite())},t*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==te.STATUS_TERMINATED&&(z.warn("runSessionTimer() | timer expired, terminating the session"),this.terminate({cause:L.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},t*1100)}_toggleMuteAudio(t){const n=this._connection.getSenders().filter(a=>a.track&&a.track.kind==="audio");for(const a of n)a.track.enabled=!t}_toggleMuteVideo(t){const n=this._connection.getSenders().filter(a=>a.track&&a.track.kind==="video");for(const a of n)a.track.enabled=!t}_newJanusSession(t,n){z.debug("newRTCSession()"),this._ua.newJanusSession(this,{originator:t,session:this,request:n})}_connecting(t){z.debug("session connecting"),z.debug('emit "connecting"'),this.emit("connecting",{request:t})}_progress(t,n){z.debug("session progress"),z.debug('emit "progress"'),this.emit("progress",{originator:t,response:n||null})}_accepted(t,n){z.debug("session accepted"),this._start_time=new Date,z.debug('emit "accepted"'),this.emit("accepted",{originator:t,response:n||null})}_confirmed(t,n){z.debug("session confirmed"),this._is_confirmed=!0,z.debug('emit "confirmed"'),this.emit("confirmed",{originator:t,ack:n||null})}_ended(t,n,a){z.debug("session ended"),this._end_time=new Date,this._close(),z.debug('emit "ended"'),this.emit("ended",{originator:t,message:n||null,cause:a})}_failed(t,n,a){z.debug("session failed"),z.debug('emit "_failed"'),this.emit("_failed",{originator:t,message:n||null,cause:a}),this._close(),z.debug('emit "failed"'),this.emit("failed",{originator:t,message:n||null,cause:a})}_onhold(t){z.debug("session onhold"),this._setLocalMediaStatus(),z.debug('emit "hold"'),this.emit("hold",{originator:t})}_onunhold(t){z.debug("session onunhold"),this._setLocalMediaStatus(),z.debug('emit "unhold"'),this.emit("unhold",{originator:t})}_onmute({audio:t,video:n}){z.debug("session onmute"),this._setLocalMediaStatus(),z.debug('emit "muted"'),this.emit("muted",{audio:t,video:n})}_onunmute({audio:t,video:n}){z.debug("session onunmute"),this._setLocalMediaStatus(),z.debug('emit "unmuted"'),this.emit("unmuted",{audio:t,video:n})}}class cr{constructor(t){if(this.headers={},t.length>0){let n=!1;const a=t.split(`\r
|
136
136
|
`),o=a.shift().split(/\s/);this.protocol=o[0],this.ident=o[1],this.code=o.length>3?parseInt(o[2]):0,this.method=o.length>3?o[3]:o[2],this.body="";for(const s of a){if(s==`-------${this.ident}$`)break;if(s===""){n=!0;continue}if(s&&n)this.body+=`${s}\r
|
137
137
|
`;else{const r=s.split(": ");this.addHeader(r[0],r[1].trim())}}}else this.ident=ke.createRandomToken(12),this.protocol="MSRP"}addHeader(t,n){this.headers[t]=n}getHeader(t){return this.headers[t]}toString(){let t=`${this.protocol} ${this.ident} ${this.code} ${this.method}`.replaceAll(/null\s|undefined\s/ig,"")+`\r
|
@@ -155,5 +155,5 @@ a=accept-types:text/plain text/html
|
|
155
155
|
a=path:${t.getHeader("Use-Path")} msrp://${this._ua._configuration.authorization_user}.${this._ua._configuration.realm}:2856/${this.auth_id};ws
|
156
156
|
`),this._newMSRPSession("local",this._request),this._id=this._request.call_id+this._from_tag,new sl(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:s=>{this.onTransportError(),console.log(s)},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s),s.status_code===200&&(s.parseSDP(!0),this._status=Re.STATUS_CONFIRMED,this.target_addr=s.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=Re.STATUS_INVITE_SENT}terminate(t={}){const n=t.cause||L.causes.BYE,a=ke.cloneArray(t.extraHeaders),o=t.body;let s,r=t.status_code,d=t.reason_phrase;if(this._status===Re.STATUS_TERMINATED)throw new qs.InvalidStateError(this._status);switch(this.status="terminated",this._status){case Re.STATUS_NULL:case Re.STATUS_INVITE_SENT:case Re.STATUS_1XX_RECEIVED:if(r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);r&&(d=d||L.REASON_PHRASE[r]||"",s=`SIP ;cause=${r} ;text="${d}"`),this._status===Re.STATUS_NULL||this._status===Re.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=s):this._status===Re.STATUS_1XX_RECEIVED&&this._request.cancel(s),this._status=Re.STATUS_CANCELED,this._failed("local",null,L.causes.CANCELED);break;case Re.STATUS_WAITING_FOR_ANSWER:case Re.STATUS_ANSWERED:if(r=r||480,r<300||r>=700)throw new TypeError(`Invalid status_code: ${r}`);this._request.reply(r,d,a,o),this._failed("local",null,L.causes.REJECTED);break;case Re.STATUS_WAITING_FOR_ACK:case Re.STATUS_CONFIRMED:if(d=t.reason_phrase||L.REASON_PHRASE[r]||"",r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);if(r&&a.push(`Reason: SIP ;cause=${r}; text="${d}"`),this._status===Re.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Gt.C.STATUS_TERMINATED){const h=this._dialog;this.receiveRequest=({method:_})=>{_===L.ACK&&(this.sendRequest(L.BYE,{extraHeaders:a,body:o}),h.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Gt.C.STATUS_TERMINATED&&(this.sendRequest(L.BYE,{extraHeaders:a,body:o}),h.terminate())}),this._ended("local",null,n),this._dialog=h,this._ua.newDialog(h)}else this.sendRequest(L.BYE,{extraHeaders:a,body:o}),this._ended("local",null,n)}}sendRequest(t,n){return this._dialog.sendRequest(t,n)}authenticate(t){this.status="auth";let n=new cr("");n.method="AUTH",n.addHeader("To-Path",`msrp://${this._ua._configuration.realm}:2856;ws`),n.addHeader("From-Path",`msrp://${this.credentials.username}.${this.credentials.realm}:2856/${this.auth_id};ws`),t&&n.addHeader("Authorization",t.toString());let a=n.toString(),o=[];for(var s=0;s<a.length;s++)o.push(a.charCodeAt(s).toString(16));this._connection.send(n.toString())}onmessage(t){const n=new cr(t.data);if(this.status==="auth"&&n.code===401){const a=this.parseAuth(n.getHeader("WWW-Authenticate")),o=new Km(this.credentials);o.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},a,ke.createRandomToken(12)),this.authenticate(o)}this.status==="auth"&&n.code===200&&this._direction==="outgoing"?(this.my_addr.push(n.getHeader("To-Path")),this.my_addr.push(n.getHeader("Use-Path")),this.status="active",this.inviteParty(n)):this.status==="auth"&&n.code===200&&this._direction==="incoming"?(this.my_addr.push(n.getHeader("To-Path")),this.my_addr.push(n.getHeader("Use-Path")),this.status="active",this.acceptParty(n),this.emit("confirmed")):n.method==="SEND"&&(this._sendOk(n),this._sendReport(n),n.direction="incoming",this.emit("newMessage",n),this._msgHistory.push(n),this.emit("msgHistoryUpdate",this._msgHistory)),n.code===480&&this._close()}onclose(){console.log("close")}onopen(){const t=new RTCPeerConnection({iceServers:[]});t.createDataChannel(""),t.createOffer().then(t.setLocalDescription.bind(t)),t.onicecandidate=n=>{if(!n||!n.candidate||!n.candidate.candidate)return;const a=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,o=n.candidate.candidate.match(a);this.my_ip=o&&o[1],t.onicecandidate=()=>{},this.authenticate(null)}}onerror(t){console.log(t)}_receiveInviteResponse(t){if(console.log("resp0000000000000",t),this._dialog&&t.status_code>=200&&t.status_code<=299)if(console.log("200000000000000"),this._dialog.id.call_id===t.call_id&&this._dialog.id.local_tag===t.from_tag&&this._dialog.id.remote_tag===t.to_tag){this.sendRequest(L.ACK);return}else{const n=new ea(this,t,"UAC");if(n.error!==void 0){console.log(n.error);return}this.sendRequest(L.ACK),this.sendRequest(L.BYE);return}if(this._is_canceled){t.status_code>=100&&t.status_code<200?this._request.cancel(this._cancel_reason):t.status_code>=200&&t.status_code<299&&this._acceptAndTerminate(t);return}if(!(this._status!==Re.STATUS_INVITE_SENT&&this._status!==Re.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(t.status_code):this._status=Re.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(t.status_code):{if(!t.to_tag){console.log("1xx response received without to tag");break}if(t.hasHeader("contact")&&!this._createDialog(t,"UAC",!0))break;if(this._status=Re.STATUS_1XX_RECEIVED,!t.body){this._progress("remote",t);break}const n={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",n);const a=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>this._progress("remote",t)).catch(o=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',o),this.emit("peerconnection:setremotedescriptionfailed",o)});break}case/^2[0-9]{2}$/.test(t.status_code):{if(console.log("maybe here???"),this._status=Re.STATUS_CONFIRMED,!t.body){this._acceptAndTerminate(t,400,L.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",t,L.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(t,"UAC"))break;const n={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",n),new RTCSessionDescription({type:"answer",sdp:n.sdp}),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(a=>this._connection.setLocalDescription(a)).catch(a=>{this._acceptAndTerminate(t,500,a.toString()),console.log("failed 4"),this._failed("local",t,L.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(t),this._accepted("remote",t),this.sendRequest(L.ACK),this._confirmed("local",null)});break}default:{const n=ke.sipErrorCause(t.status_code);console.log("failed 5"),this._failed("remote",t,n)}}}sendMSRP(t){const n=new cr("");n.method="SEND",n.addHeader("To-Path",`${this.my_addr[1]} ${this.target_addr[1]} ${this.target_addr[0]}`),n.addHeader("From-Path",`${this.my_addr[0]}`),n.addHeader("Message-ID",ke.createRandomToken(10)),n.addHeader("Byte-Range","1-25/25"),n.addHeader("Content-Type","text/plain"),n.addHeader("Success-Report","yes"),n.addHeader("Failure-Report","yes"),n.body=t;let a=n.toString();console.log(a);let o=[];for(var s=0;s<a.length;s++)o.push(a.charCodeAt(s).toString(16));console.log(o),this._connection.send(n.toString()),n.direction="outgoing",this.emit("newMessage",n),this._msgHistory.push(n),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(t){let n=t.ident,a=t.getHeader("Message-ID"),o=new cr("");o.method="200 OK",o.addHeader("To-Path",`${this.my_addr[1]}`),o.addHeader("From-Path",`${this.my_addr[0]}`),o.addHeader("Message-ID",a),o.ident=n;let s=o.toString();console.log(s);let r=[];for(var d=0;d<s.length;d++)r.push(s.charCodeAt(d).toString(16));console.log(r),this._connection.send(o.toString())}_sendReport(t){let n=t.ident,a=t.getHeader("Message-ID"),o=new cr("");o.method="REPORT",o.addHeader("To-Path",`${t.getHeader("From-Path")}`),o.addHeader("From-Path",`${this.my_addr[0]}`),o.addHeader("Message-ID",a),o.addHeader("Byte-Range","1-25/25"),o.addHeader("Status","000 200 OK"),o.ident=n;let s=o.toString();console.log(s);let r=[];for(var d=0;d<s.length;d++)r.push(s.charCodeAt(d).toString(16));console.log(r),this._connection.send(o.toString())}parseAuth(t){const n={},a=t.replace("Digest","").split(",");for(const o of a){const s=o.trim().split("=");n[s[0]]=s[1].match('^"(.+)"$')[1]}return n}init_incoming(t,n){let a;const o=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;if(t.body&&o!=="application/sdp"){t.reply(415);return}if(this._status=Re.STATUS_INVITE_RECEIVED,this._from_tag=t.from_tag,this._id=t.call_id+this._from_tag,this._request=t,this._contact=this._ua.contact.toString(),t.hasHeader("expires")&&(a=t.getHeader("expires")*1e3),t.to_tag=ke.newTag(),!this._createDialog(t,"UAS",!0)){t.reply(500,"Missing Contact header field");return}t.body?this._late_sdp=!1:this._late_sdp=!0,this._status=Re.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{t.reply(408),console.log("failed 6"),this._failed("local",null,L.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),a&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Re.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),console.log("failed 7"),this._failed("system",null,L.causes.EXPIRES))},a)),this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from,n&&n(this),t.parseSDP(!0),this.target_addr=t.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",t),this._status!==Re.STATUS_TERMINATED&&(t.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(t,n,a){this.emit("_failed",{originator:t,message:n||null,cause:a}),this._close(),this.emit("failed",{originator:t,message:n||null,cause:a})}_close(){if(console.log("CLOSE SESSION"),this._status!==Re.STATUS_TERMINATED){if(this._status=Re.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(t){console.log("close() | error closing the RTCPeerConnection: %o",t)}for(const t in this._timers)Object.prototype.hasOwnProperty.call(this._timers,t)&&clearTimeout(this._timers[t]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const t in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,t)&&(this._earlyDialogs[t].terminate(),delete this._earlyDialogs[t]);for(const t in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,t)&&delete this._referSubscribers[t];this._ua.destroyMSRPSession(this)}}_createDialog(t,n,a){const o=n==="UAS"?t.to_tag:t.from_tag,s=n==="UAS"?t.from_tag:t.to_tag,r=t.call_id+o+s;let d=this._earlyDialogs[r];if(a)return d?!0:(d=new ea(this,t,n,ea.C.STATUS_EARLY),d.error?(console.log("failed 8"),this._failed("remote",t,L.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[r]=d,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,d)return d.update(t,n),this._dialog=d,delete this._earlyDialogs[r],!0;const h=new ea(this,t,n);return h.error?(console.log("failed 9"),this._failed("remote",t,L.causes.INTERNAL_ERROR),!1):(this._dialog=h,!0)}}_newMSRPSession(t,n){this._ua.newMSRPSession(this,{originator:t,session:this,request:n})}_progress(t,n){this.emit("progress",{originator:t,response:n||null})}isEnded(){switch(this._status){case Re.STATUS_CANCELED:case Re.STATUS_TERMINATED:return!0;default:return!1}}_accepted(t,n){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:t,response:n||null})}_confirmed(t,n){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:t,ack:n||null})}_ended(t,n,a){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:t,message:n||null,cause:a})}_handleSessionTimersInIncomingResponse(t){if(!this._sessionTimers.enabled)return;let n;t.session_expires&&t.session_expires>=L.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,n=t.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,n="uac"),this._sessionTimers.refresher=n==="uac",this._runSessionTimer()}receiveRequest(t){if(console.log("receiveRequest()"),t.method===L.CANCEL)(this._status===Re.STATUS_WAITING_FOR_ANSWER||this._status===Re.STATUS_ANSWERED)&&(this._status=Re.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",t,L.causes.CANCELED));else switch(t.method){case L.ACK:if(this._status!==Re.STATUS_WAITING_FOR_ACK)return;if(this._status=Re.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!t.body){this.terminate({cause:L.causes.MISSING_SDP,status_code:400});break}const n={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",n);const a=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>{this._is_confirmed||this._confirmed("remote",t)}).catch(o=>{this.terminate({cause:L.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',o),this.emit("peerconnection:setremotedescriptionfailed",o)})}else this._is_confirmed||this._confirmed("remote",t);break;case L.BYE:this._status===Re.STATUS_CONFIRMED||this._status===Re.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,L.causes.BYE)):this._status===Re.STATUS_INVITE_RECEIVED||this._status===Re.STATUS_WAITING_FOR_ANSWER?(t.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",t,L.causes.BYE)):t.reply(403,"Wrong Status");break;case L.INVITE:this._status===Re.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case L.INFO:this._status===Re.STATUS_1XX_RECEIVED||this._status===Re.STATUS_WAITING_FOR_ANSWER||this._status===Re.STATUS_ANSWERED||this._status===Re.STATUS_WAITING_FOR_ACK||this._status===Re.STATUS_CONFIRMED?(t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new yu(this).init_incoming(t):t.reply(415):t.reply(403,"Wrong Status");break;case L.UPDATE:this._status===Re.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case L.REFER:this._status===Re.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case L.NOTIFY:this._status===Re.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==Re.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:L.causes.CONNECTION_ERROR,cause:L.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==Re.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:L.causes.REQUEST_TIMEOUT,cause:L.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==Re.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:L.causes.DIALOG_ERROR,cause:L.causes.DIALOG_ERROR})}}var MT=Zt();const Iu=ze(MT),fa=new Ga("Parser"),LT=(c,t)=>{let n,a,o=c.indexOf(`\r
|
157
157
|
`);if(o===-1){fa.warn("parseMessage() | no CRLF found, not a SIP message");return}const s=c.substring(0,o);let r=Iu.parse(s,"Request_Response");if(r===-1){fa.warn(`parseMessage() | error parsing first line of SIP message: "${s}"`);return}else r.status_code?(n=new pr.IncomingResponse,n.status_code=r.status_code,n.reason_phrase=r.reason_phrase):(n=new pr.IncomingRequest(t),n.method=r.method,n.ruri=r.uri);n.data=c;let d=o+2;for(;;){if(o=$T(c,d),o===-2){a=d+2;break}else if(o===-1){fa.warn("parseMessage() | malformed message");return}if(r=HT(n,c,d,o),r!==!0){fa.warn("parseMessage() |",r.error);return}d=o+2}if(n.hasHeader("content-length")){const h=n.getHeader("content-length");n.body=c.substr(a,h)}else n.body=c.substring(a);return n};function $T(c,t){let n=t,a=0,o=0;if(c.substring(n,n+2).match(/(^\r\n)/))return-2;for(;a===0;){if(o=c.indexOf(`\r
|
158
|
-
`,n),o===-1)return o;!c.substring(o+2,o+4).match(/(^\r\n)/)&&c.charAt(o+2).match(/(^\s+)/)?n=o+2:a=o}return a}function HT(c,t,n,a){let o;const s=t.indexOf(":",n),r=t.substring(n,s).trim(),d=t.substring(s+1,a).trim();switch(r.toLowerCase()){case"via":case"v":c.addHeader("via",d),c.getHeaders("via").length===1?(o=c.parseHeader("Via"),o&&(c.via=o,c.via_branch=o.branch)):o=0;break;case"from":case"f":c.setHeader("from",d),o=c.parseHeader("from"),o&&(c.from=o,c.from_tag=o.getParam("tag"));break;case"to":case"t":c.setHeader("to",d),o=c.parseHeader("to"),o&&(c.to=o,c.to_tag=o.getParam("tag"));break;case"record-route":if(o=Iu.parse(d,"Record_Route"),o===-1)o=void 0;else for(const h of o)c.addHeader("record-route",d.substring(h.possition,h.offset)),c.headers["Record-Route"][c.getHeaders("record-route").length-1].parsed=h.parsed;break;case"call-id":case"i":c.setHeader("call-id",d),o=c.parseHeader("call-id"),o&&(c.call_id=d);break;case"contact":case"m":if(o=Iu.parse(d,"Contact"),o===-1)o=void 0;else for(const h of o)c.addHeader("contact",d.substring(h.possition,h.offset)),c.headers.Contact[c.getHeaders("contact").length-1].parsed=h.parsed;break;case"content-length":case"l":c.setHeader("content-length",d),o=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",d),o=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",d),o=c.parseHeader("cseq"),o&&(c.cseq=o.value),c instanceof pr.IncomingResponse&&(c.method=o.method);break;case"max-forwards":c.setHeader("max-forwards",d),o=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",d),o=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",d),o=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",d),o=c.parseHeader("session-expires"),o&&(c.session_expires=o.expires,c.session_expires_refresher=o.refresher);break;case"refer-to":case"r":c.setHeader("refer-to",d),o=c.parseHeader("refer-to"),o&&(c.refer_to=o);break;case"replaces":c.setHeader("replaces",d),o=c.parseHeader("replaces"),o&&(c.replaces=o);break;case"event":case"o":c.setHeader("event",d),o=c.parseHeader("event"),o&&(c.event=o);break;default:c.addHeader(r,d),o=0}return o===void 0?{error:`error parsing header "${r}"`}:!0}const FT={parseMessage:LT},Wi=new Ga("Registrator"),ha=10;class jT{constructor(t,n){this._reg_id=1,this._ua=t,this._transport=n,this._registrar=t.configuration.registrar_server,this._expires=t.configuration.register_expires,this._call_id=Ts.createRandomToken(22),this._cseq=0,this._to_uri=t.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const a=this._contact.indexOf(">");if(a!==-1){const o=this._contact.slice(0,a)+this._contact.slice(a+1,this._contact.length);this._contact=o}this._extra_contact="",this._extraContactParams="",this._extra_contact+=";+sip.ice",this._extraHeaders=[],this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._extra_contact+=`;reg-id=${this._reg_id}`,this._extra_contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(t){Array.isArray(t)||(t=[]),this._extraHeaders=t.slice()}setExtraContactParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const a=t[n];this._extraContactParams+=`;${n}`,a&&(this._extraContactParams+=`=${a}`)}}setExtraContactUriParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const a=t[n];this._extraContactParams+=`;${n}`,a&&(this._extraContactParams+=`=${a}`)}}register(){if(this._registering){Wi.debug("Register request in progress...");return}const t=this._extraHeaders.slice();t.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),t.push(`Expires: ${this._expires}`);const n=new yt.OutgoingRequest(L.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t),a=new sl(this._ua,n,{onRequestTimeout:()=>{this._registrationFailure(null,L.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,L.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:o=>{if(o.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(o.status_code):break;case/^2[0-9]{2}$/.test(o.status_code):{if(this._registering=!1,!o.hasHeader("Contact")){Wi.debug("no Contact header in response to REGISTER, response ignored");break}const s=o.headers.Contact.reduce((_,g)=>_.concat(g.parsed),[]);let r=s.find(_=>this._sipInstance===_.getParam("+sip.instance")&&this._reg_id===parseInt(_.getParam("reg-id")));if(r||(r=s.find(_=>_.uri.user===this._ua.contact.uri.user)),!r){Wi.debug("no Contact header pointing to us, response ignored");break}let d=r.getParam("expires");!d&&o.hasHeader("expires")&&(d=o.getHeader("expires")),d||(d=this._expires),d=Number(d),d<ha&&(d=ha);const h=d>64?d*1e3/2+Math.floor((d/2-32)*1e3*Math.random()):d*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},h),r.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=r.getParam("temp-gruu").replace(/"/g,"")),r.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=r.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:o}));break}case/^423$/.test(o.status_code):{o.hasHeader("min-expires")?(this._expires=Number(o.getHeader("min-expires")),this._expires<ha&&(this._expires=ha),this.register()):(Wi.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(o,L.causes.SIP_FAILURE_CODE));break}default:{const s=Ts.sipErrorCause(o.status_code);this._registrationFailure(o,s)}}}});this._registering=!0,a.send()}unregister(t={}){if(!this._registered){Wi.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const n=this._extraHeaders.slice();t.all?n.push(`Contact: *${this._extraContactParams}`):n.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),n.push("Expires: 0");const a=new yt.OutgoingRequest(L.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n);new sl(this._ua,a,{onRequestTimeout:()=>{this._unregistered(null,L.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,L.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:s=>{switch(!0){case/^1[0-9]{2}$/.test(s.status_code):break;case/^2[0-9]{2}$/.test(s.status_code):this._unregistered(s);break;default:{const r=Ts.sipErrorCause(s.status_code);this._unregistered(s,r)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(t,n){this._registering=!1,this._ua.registrationFailed({response:t||null,cause:n}),this._registered&&(this._registered=!1,this._ua.unregistered({response:t||null,cause:n}))}_unregistered(t,n){this._registering=!1,this._registered=!1,this._ua.unregistered({response:t||null,cause:n||null})}}const tt=console,Vs={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},qT=wT;class VT extends qT{constructor(t){super(t),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this.newStreamPlugins=[],this.processStreamPlugins=[],this._registrator=new jT(this)}call(t,n){return super.call(t,n)}joinVideoCall(t,n,a){tt.debug("call()");const o=new $a(this);return o.configureMedia({audio:!0,video:!0}),o.connect(t,n,a),o}startScreenShare(){tt.debug("startScreenShare()");for(const t in this._janus_sessions)this._janus_sessions[t].connectScreenShare()}changeMediaConstraints(t){for(const n in this._janus_sessions)this._janus_sessions[n].changeMediaConstraints(t)}startBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].connectBlur()}stopBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].stopBlur()}_loadConfig(t){try{rl.load(this._configuration,t)}catch(s){throw s}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=Ts.newUUID());let n;typeof window<"u"&&typeof window.document<"u"?n=window==null?void 0:window.navigator.userAgent:typeof self<"u"&&self.navigator&&(n=self.navigator.userAgent),n+=" "+De.USER_AGENT,this._configuration.user_agent=t.overrideUserAgent&&typeof t.overrideUserAgent=="function"?t.overrideUserAgent(n):n,this._configuration.jssip_id=Ts.createRandomToken(5);const a=this._configuration.uri.clone();a.user=null,this._configuration.hostport_params=a.toString().replace(/^sip:/i,"");try{this._transport=new eT(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=BT.bind(this),this._transport.onconnect=GT.bind(this),this._transport.ondisconnect=WT.bind(this),this._transport.ondata=KT.bind(this)}catch(s){throw tt.warn(s),new qs.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const s=this._configuration.uri.clone();s.user=null,s.clearParams(),s.clearHeaders(),this._configuration.registrar_server=s}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new In("sip",Ts.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(s={}){const r=s.anonymous||null,d=s.outbound||null;let h="<";return r?h+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":h+=this.pub_gruu||this.uri.toString(),d&&(r?!this.temp_gruu:!this.pub_gruu)&&(h+=";ob"),h+=">",h}};const o=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const s in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,s)&&(o.indexOf(s)!==-1?Object.defineProperty(this._configuration,s,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,s,{writable:!1,configurable:!1}));tt.debug("configuration parameters after validation:");for(const s in this._configuration)if(Object.prototype.hasOwnProperty.call(rl.settings,s))switch(s){case"uri":case"registrar_server":tt.debug(`- ${s}: ${this._configuration[s]}`);break;case"password":case"ha1":case"authorization_jwt":tt.debug(`- ${s}: NOT SHOWN`);break;default:tt.debug(`- ${s}: ${JSON.stringify(this._configuration[s])}`)}}newMSRPSession(t,n){t.on("msgHistoryUpdate",a=>{console.log(a)}),this._msrp_sessions[t.id]=t,this.emit("newMSRPSession",n)}newJanusSession(t,n){this._janus_sessions[t.id]=t,this.newStreamPlugins.forEach(a=>{a.setSession(t)}),this.processStreamPlugins.forEach(a=>{a.setSession(t)}),this.emit("newJanusSession",n)}kill(){}destroyMSRPSession(t){delete this._msrp_sessions[t.id]}destroyJanusSession(t){delete this._janus_sessions[t.id]}receiveRequest(t){var s,r,d,h;const n=t.method;if(t.ruri.user!==this._configuration.uri.user&&t.ruri.user!==this._contact.uri.user){tt.debug("Request-URI does not point to us"),t.method!==De.ACK&&t.reply_sl(404);return}if(t.ruri.scheme===De.SIPS){t.reply_sl(416);return}if(Gt.checkTransaction(this,t))return;if(n===De.INVITE?new Gt.InviteServerTransaction(this,this._transport,t):n!==De.ACK&&n!==De.CANCEL&&new Gt.NonInviteServerTransaction(this,this._transport,t),n===De.OPTIONS){if(this.listeners("newOptions").length===0){t.reply(200);return}new Qc.Options(this).init_incoming(t)}else if(n===De.MESSAGE){if(this.listeners("newMessage").length===0){t.reply(405);return}new Qc.Message(this).init_incoming(t)}else if(n===De.INVITE&&!t.to_tag&&this.listeners("newRTCSession").length===0){t.reply(405);return}let a,o;if(t.to_tag)if(a=this._findDialog(t.call_id,t.from_tag,t.to_tag),a)a.receiveRequest(t);else if(n===De.NOTIFY)if(o=this._findSession(t),o)o.receiveRequest(t);else{if(t.body)try{const _=JSON.parse(t.body)||{};(r=(s=_.plugindata)==null?void 0:s.data)!=null&&r.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(_),(h=(d=_.plugindata)==null?void 0:d.data)!=null&&h.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(_.plugindata.data.unpublished)}catch(_){console.error(_)}t.reply(200)}else n!==De.ACK&&t.reply(481);else switch(n){case De.INVITE:if(window.RTCPeerConnection)if(t.hasHeader("replaces")){const _=t.replaces;a=this._findDialog(_.call_id,_.from_tag,_.to_tag),a?(o=a.owner,o.isEnded()?t.reply(603):o.receiveRequest(t)):t.reply(481)}else t.body.search(/MSRP/ig)>-1?(o=new nu(this),o.init_incoming(t)):t.body.search(/JANUS/ig)>-1||(o=new $g(this),o.init_incoming(t));else tt.warn("INVITE received but WebRTC is not supported"),t.reply(488);break;case De.BYE:t.reply(481);break;case De.CANCEL:o=this._findSession(t),o?o.receiveRequest(t):tt.debug("received CANCEL request for a non existent session");break;case De.ACK:break;case De.NOTIFY:this.emit("sipEvent",{event:t.event,request:t}),t.reply(200);break;default:t.reply(405);break}}startMSRP(t,n){tt.debug("startMSRP()",n);const a=new nu(this);return a.connect(t),a}startJanus(t,n){tt.debug("startJanus()",n);const a=new nu(this);return a.connect(t),a}terminateMSRPSessions(t){tt.debug("terminateSessions()");for(const n in this._msrp_sessions)this._msrp_sessions[n].isEnded()||this._msrp_sessions[n].terminate(t)}terminateJanusSessions(t){tt.debug("terminateSessions()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||this._janus_sessions[n].terminate(t)}enableJanusAudio(t){tt.debug("enableJanusAudio()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||(t?this._janus_sessions[n].startAudio():this._janus_sessions[n].stopAudio())}enableJanusVideo(t){tt.debug("enableJanusVideo()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||(t?this._janus_sessions[n].startVideo():this._janus_sessions[n].stopVideo())}stop(){if(tt.debug("stop()"),this._dynConfiguration={},this._status===Vs.STATUS_USER_CLOSED){tt.debug("UA already closed");return}this._registrator.close();const t=Object.keys(this._sessions).length;for(const a in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,a)){tt.debug(`closing session ${a}`);try{this._sessions[a].terminate()}catch(o){console.error(o)}}for(const a in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,a)){tt.debug(`closing session ${a}`);try{this._msrp_sessions[a].terminate()}catch(o){console.error(o)}}for(const a in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,a)){tt.debug(`closing session ${a}`);try{this._janus_sessions[a].terminate()}catch(o){console.error(o)}}for(const a in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,a))try{this._applicants[a].close()}catch(o){console.error(o)}this._status=Vs.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&t===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function BT(c){this.emit("connecting",c)}function GT(c){this._status!==Vs.STATUS_USER_CLOSED&&(this._status=Vs.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function WT(c){const t=["nict","ict","nist","ist"];for(const n of t)for(const a in this._transactions[n])Object.prototype.hasOwnProperty.call(this._transactions[n],a)&&this._transactions[n][a].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==Vs.STATUS_USER_CLOSED&&(this._status=Vs.STATUS_NOT_READY,this._error=Vs.NETWORK_ERROR)}function KT(c){const t=c.transport;let n=c.message;if(n=FT.parseMessage(n,this),!!n&&!(this._status===Vs.STATUS_USER_CLOSED&&n instanceof pr.IncomingRequest)&&pT(n,this,t)){if(n instanceof pr.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof pr.IncomingResponse){let a;switch(n.method){case De.INVITE:a=this._transactions.ict[n.via_branch],a&&a.receiveResponse(n);break;case De.ACK:break;default:a=this._transactions.nict[n.via_branch],a&&a.receiveResponse(n);break}}}}const YT=["roomId","_audioMuted","_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","_localHold","_videoMuted","status","start_time","_remote_identity","audioTag","isOnHold","localMuted","autoAnswer","putOnHoldTimestamp"],JT=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function Nf(c){const t={};return YT.forEach(n=>{c[n]!==void 0&&(t[n]=c[n])}),t.localHold=c._localHold,t}function Uf(c){const t={};return JT.forEach(n=>{c[n]!==void 0&&(t[n]=c[n])}),t}function Pf(c,t){const n=new AudioContext,a=n.createMediaStreamSource(c),o=n.createMediaStreamDestination(),s=n.createGain();return a.connect(s),s.connect(o),s.gain.value=t,o.stream}function zT(c,t,n,a){const o=document.createElement("audio");o.id=t._id,o.className="audioTag",o.srcObject=c,wh()||(o.setSinkId(n),o.volume=a),o.play(),t.audioTag=o}function XT(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}function wh(){return/Mobi|Android|iPhone/i.test(navigator.userAgent)}const QT=ut,ZT=Zt(),Dt=new QT("WebSocketInterface");var ev=class{constructor(t){Dt.debug('new() [url:"%s"]',t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;const n=ZT.parse(t,"absoluteURI");if(n===-1)throw Dt.warn(`invalid WebSocket URI: ${t}`),new TypeError(`Invalid argument: ${t}`);if(n.scheme!=="wss"&&n.scheme!=="ws")throw Dt.warn(`invalid WebSocket URI scheme: ${n.scheme}`),new TypeError(`Invalid argument: ${t}`);this._sip_uri=`sip:${n.host}${n.port?`:${n.port}`:""};transport=ws`,this._via_transport=n.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(t){this._via_transport=t.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Dt.debug("connect()"),this.isConnected()){Dt.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Dt.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Dt.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(t){this._onError(t)}}disconnect(){Dt.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(t){return Dt.debug("send()"),this.isConnected()?(this._ws.send(t),!0):(Dt.warn("unable to send message, WebSocket is not open"),!1)}isConnected(){return this._ws&&this._ws.readyState===this._ws.OPEN}isConnecting(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}_onOpen(){Dt.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:t,code:n,reason:a}){Dt.debug(`WebSocket ${this._url} closed`),t===!1&&Dt.debug("WebSocket abrupt disconnection"),this.ondisconnect(!t,n,a)}_onMessage({data:t}){Dt.debug("received WebSocket message"),this.ondata(t)}_onError(t){Dt.warn(`WebSocket ${this._url} error: `,t)}};const bu=Ha,tv=De,sv=As,nv=At(),rv=bh,iv=ys(),lv=$u(),av=Zt(),ov=ev,uv=gr("JsSIP");uv("version %s",bu.version);var cv={C:tv,Exceptions:sv,Utils:nv,UA:rv,URI:iv,NameAddrHeader:lv,WebSocketInterface:ov,Grammar:av,debug:gr,get name(){return bu.title},get version(){return bu.version}};const fv=ze(cv);function ru(c){return c<10?`0${c}`:`${c}`}function hv(c){let t=c.hours||0,n=c.minutes||0,a=c.seconds||0;a++,a===60&&(a=0,n++,n===60&&(n=0,t++));const o=`${ru(t)}:${ru(n)}:${ru(a)}`;return{seconds:a,minutes:n,hours:t,formatted:o}}var Ct={};Ct.forEach=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)if(o in c){const s=Promise.resolve(c[o]).then(r=>t.call(n||globalThis,r,o,c));a.push(s)}await Promise.all(a)};Ct.forEachSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)a in c&&await t.call(n||globalThis,await c[a],a,c)};Ct.map=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)o in c&&(a[o]=Promise.resolve(c[o]).then(s=>t.call(n||globalThis,s,o,c)));return Promise.all(a)};Ct.mapSeries=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)o in c&&(a[o]=await t.call(n||globalThis,await c[o],o,c));return a};Ct.find=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a();let s=1;for(let r=0;r<c.length;r++){const d=h=>{h?a(c[r]):s===c.length&&a(),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}});Ct.findSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(await t.call(n||globalThis,await c[a],a,c))return c[a]};Ct.findIndex=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a(-1);let s=1;for(let r=0;r<c.length;r++){const d=h=>{h?a(r):s===c.length&&a(-1),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}});Ct.findIndexSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(await t.call(n||globalThis,await c[a],a,c))return a};Ct.some=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a(!1);let s=1;for(let r=0;r<c.length;r++){if(!(r in c)){s++;continue}const d=h=>{h?a(!0):s===c.length&&a(!1),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}});Ct.someSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(a in c&&await t.call(n||globalThis,await c[a],a,c))return!0;return!1};Ct.every=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a(!0);let s=1;for(let r=0;r<c.length;r++){if(!(r in c)){s++;continue}const d=h=>{h?s===c.length&&a(!0):a(!1),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}});Ct.everySeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(a in c&&!await t.call(n||globalThis,await c[a],a,c))return!1;return!0};Ct.filter=(c,t,n)=>new Promise(async(a,o)=>{const s=[];for(let d=0;d<c.length;d++)d in c&&(s[d]=Promise.resolve(c[d]).then(h=>t.call(n||globalThis,h,d,c)).catch(o));const r=[];for(let d=0;d<s.length;d++)await s[d]&&r.push(await c[d]);a(r)});Ct.filterSeries=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)o in c&&await t.call(n||globalThis,await c[o],o,c)&&a.push(await c[o]);return a};Ct.reduce=async(c,t,n)=>{if(c.length===0&&n===void 0)throw TypeError("Reduce of empty array with no initial value");let a,o;for(n!==void 0?(o=n,a=0):(o=c[0],a=1),a;a<c.length;a++)a in c&&(o=await t(await o,await c[a],a,c));return o};var Oh={};(function(c){const t=Ct;Object.keys(t).forEach(n=>{const a=n.charAt(0).toUpperCase()+n.slice(1);c[`async${a}`]=async function(...o){return t[n](this,...o)}})})(Oh);const dv=Ct,_v=Oh;var pv=Object.assign(dv,{instanceMethods:_v});const Cn=new AudioContext,Xt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var mv={exports:{}};(function(c){var t=function(n){var a=Object.prototype,o=a.hasOwnProperty,s=Object.defineProperty||function(ee,W,G){ee[W]=G.value},r,d=typeof Symbol=="function"?Symbol:{},h=d.iterator||"@@iterator",_=d.asyncIterator||"@@asyncIterator",g=d.toStringTag||"@@toStringTag";function T(ee,W,G){return Object.defineProperty(ee,W,{value:G,enumerable:!0,configurable:!0,writable:!0}),ee[W]}try{T({},"")}catch{T=function(W,G,re){return W[G]=re}}function E(ee,W,G,re){var ge=W&&W.prototype instanceof oe?W:oe,be=Object.create(ge.prototype),xe=new P(re||[]);return s(be,"_invoke",{value:J(ee,G,xe)}),be}n.wrap=E;function y(ee,W,G){try{return{type:"normal",arg:ee.call(W,G)}}catch(re){return{type:"throw",arg:re}}}var A="suspendedStart",C="suspendedYield",I="executing",H="completed",$={};function oe(){}function N(){}function j(){}var Se={};T(Se,h,function(){return this});var ve=Object.getPrototypeOf,k=ve&&ve(ve(se([])));k&&k!==a&&o.call(k,h)&&(Se=k);var D=j.prototype=oe.prototype=Object.create(Se);N.prototype=j,s(D,"constructor",{value:j,configurable:!0}),s(j,"constructor",{value:N,configurable:!0}),N.displayName=T(j,g,"GeneratorFunction");function B(ee){["next","throw","return"].forEach(function(W){T(ee,W,function(G){return this._invoke(W,G)})})}n.isGeneratorFunction=function(ee){var W=typeof ee=="function"&&ee.constructor;return W?W===N||(W.displayName||W.name)==="GeneratorFunction":!1},n.mark=function(ee){return Object.setPrototypeOf?Object.setPrototypeOf(ee,j):(ee.__proto__=j,T(ee,g,"GeneratorFunction")),ee.prototype=Object.create(D),ee},n.awrap=function(ee){return{__await:ee}};function V(ee,W){function G(be,xe,Ce,le){var ye=y(ee[be],ee,xe);if(ye.type==="throw")le(ye.arg);else{var nt=ye.arg,at=nt.value;return at&&typeof at=="object"&&o.call(at,"__await")?W.resolve(at.__await).then(function(Ee){G("next",Ee,Ce,le)},function(Ee){G("throw",Ee,Ce,le)}):W.resolve(at).then(function(Ee){nt.value=Ee,Ce(nt)},function(Ee){return G("throw",Ee,Ce,le)})}}var re;function ge(be,xe){function Ce(){return new W(function(le,ye){G(be,xe,le,ye)})}return re=re?re.then(Ce,Ce):Ce()}s(this,"_invoke",{value:ge})}B(V.prototype),T(V.prototype,_,function(){return this}),n.AsyncIterator=V,n.async=function(ee,W,G,re,ge){ge===void 0&&(ge=Promise);var be=new V(E(ee,W,G,re),ge);return n.isGeneratorFunction(W)?be:be.next().then(function(xe){return xe.done?xe.value:be.next()})};function J(ee,W,G){var re=A;return function(be,xe){if(re===I)throw new Error("Generator is already running");if(re===H){if(be==="throw")throw xe;return st()}for(G.method=be,G.arg=xe;;){var Ce=G.delegate;if(Ce){var le=F(Ce,G);if(le){if(le===$)continue;return le}}if(G.method==="next")G.sent=G._sent=G.arg;else if(G.method==="throw"){if(re===A)throw re=H,G.arg;G.dispatchException(G.arg)}else G.method==="return"&&G.abrupt("return",G.arg);re=I;var ye=y(ee,W,G);if(ye.type==="normal"){if(re=G.done?H:C,ye.arg===$)continue;return{value:ye.arg,done:G.done}}else ye.type==="throw"&&(re=H,G.method="throw",G.arg=ye.arg)}}}function F(ee,W){var G=W.method,re=ee.iterator[G];if(re===r)return W.delegate=null,G==="throw"&&ee.iterator.return&&(W.method="return",W.arg=r,F(ee,W),W.method==="throw")||G!=="return"&&(W.method="throw",W.arg=new TypeError("The iterator does not provide a '"+G+"' method")),$;var ge=y(re,ee.iterator,W.arg);if(ge.type==="throw")return W.method="throw",W.arg=ge.arg,W.delegate=null,$;var be=ge.arg;if(!be)return W.method="throw",W.arg=new TypeError("iterator result is not an object"),W.delegate=null,$;if(be.done)W[ee.resultName]=be.value,W.next=ee.nextLoc,W.method!=="return"&&(W.method="next",W.arg=r);else return be;return W.delegate=null,$}B(D),T(D,g,"Generator"),T(D,h,function(){return this}),T(D,"toString",function(){return"[object Generator]"});function X(ee){var W={tryLoc:ee[0]};1 in ee&&(W.catchLoc=ee[1]),2 in ee&&(W.finallyLoc=ee[2],W.afterLoc=ee[3]),this.tryEntries.push(W)}function U(ee){var W=ee.completion||{};W.type="normal",delete W.arg,ee.completion=W}function P(ee){this.tryEntries=[{tryLoc:"root"}],ee.forEach(X,this),this.reset(!0)}n.keys=function(ee){var W=Object(ee),G=[];for(var re in W)G.push(re);return G.reverse(),function ge(){for(;G.length;){var be=G.pop();if(be in W)return ge.value=be,ge.done=!1,ge}return ge.done=!0,ge}};function se(ee){if(ee){var W=ee[h];if(W)return W.call(ee);if(typeof ee.next=="function")return ee;if(!isNaN(ee.length)){var G=-1,re=function ge(){for(;++G<ee.length;)if(o.call(ee,G))return ge.value=ee[G],ge.done=!1,ge;return ge.value=r,ge.done=!0,ge};return re.next=re}}return{next:st}}n.values=se;function st(){return{value:r,done:!0}}return P.prototype={constructor:P,reset:function(ee){if(this.prev=0,this.next=0,this.sent=this._sent=r,this.done=!1,this.delegate=null,this.method="next",this.arg=r,this.tryEntries.forEach(U),!ee)for(var W in this)W.charAt(0)==="t"&&o.call(this,W)&&!isNaN(+W.slice(1))&&(this[W]=r)},stop:function(){this.done=!0;var ee=this.tryEntries[0],W=ee.completion;if(W.type==="throw")throw W.arg;return this.rval},dispatchException:function(ee){if(this.done)throw ee;var W=this;function G(le,ye){return be.type="throw",be.arg=ee,W.next=le,ye&&(W.method="next",W.arg=r),!!ye}for(var re=this.tryEntries.length-1;re>=0;--re){var ge=this.tryEntries[re],be=ge.completion;if(ge.tryLoc==="root")return G("end");if(ge.tryLoc<=this.prev){var xe=o.call(ge,"catchLoc"),Ce=o.call(ge,"finallyLoc");if(xe&&Ce){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0);if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else if(xe){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0)}else if(Ce){if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(ee,W){for(var G=this.tryEntries.length-1;G>=0;--G){var re=this.tryEntries[G];if(re.tryLoc<=this.prev&&o.call(re,"finallyLoc")&&this.prev<re.finallyLoc){var ge=re;break}}ge&&(ee==="break"||ee==="continue")&&ge.tryLoc<=W&&W<=ge.finallyLoc&&(ge=null);var be=ge?ge.completion:{};return be.type=ee,be.arg=W,ge?(this.method="next",this.next=ge.finallyLoc,$):this.complete(be)},complete:function(ee,W){if(ee.type==="throw")throw ee.arg;return ee.type==="break"||ee.type==="continue"?this.next=ee.arg:ee.type==="return"?(this.rval=this.arg=ee.arg,this.method="return",this.next="end"):ee.type==="normal"&&W&&(this.next=W),$},finish:function(ee){for(var W=this.tryEntries.length-1;W>=0;--W){var G=this.tryEntries[W];if(G.finallyLoc===ee)return this.complete(G.completion,G.afterLoc),U(G),$}},catch:function(ee){for(var W=this.tryEntries.length-1;W>=0;--W){var G=this.tryEntries[W];if(G.tryLoc===ee){var re=G.completion;if(re.type==="throw"){var ge=re.arg;U(G)}return ge}}throw new Error("illegal catch attempt")},delegateYield:function(ee,W,G){return this.delegate={iterator:se(ee),resultName:W,nextLoc:G},this.method==="next"&&(this.arg=r),$}},n}(c.exports);try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}})(mv);var Dh={exports:{}};(function(c){(function(t,n){c.exports?c.exports=n():t.log=n()})(jh,function(){var t=function(){},n="undefined",a=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),o=["trace","debug","info","warn","error"];function s(C,I){var H=C[I];if(typeof H.bind=="function")return H.bind(C);try{return Function.prototype.bind.call(H,C)}catch{return function(){return Function.prototype.apply.apply(H,[C,arguments])}}}function r(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function d(C){return C==="debug"&&(C="log"),typeof console===n?!1:C==="trace"&&a?r:console[C]!==void 0?s(console,C):console.log!==void 0?s(console,"log"):t}function h(C,I){for(var H=0;H<o.length;H++){var $=o[H];this[$]=H<C?t:this.methodFactory($,C,I)}this.log=this.debug}function _(C,I,H){return function(){typeof console!==n&&(h.call(this,I,H),this[C].apply(this,arguments))}}function g(C,I,H){return d(C)||_.apply(this,arguments)}function T(C,I,H){var $=this,oe;I=I??"WARN";var N="loglevel";typeof C=="string"?N+=":"+C:typeof C=="symbol"&&(N=void 0);function j(D){var B=(o[D]||"silent").toUpperCase();if(!(typeof window===n||!N)){try{window.localStorage[N]=B;return}catch{}try{window.document.cookie=encodeURIComponent(N)+"="+B+";"}catch{}}}function Se(){var D;if(!(typeof window===n||!N)){try{D=window.localStorage[N]}catch{}if(typeof D===n)try{var B=window.document.cookie,V=B.indexOf(encodeURIComponent(N)+"=");V!==-1&&(D=/^([^;]+)/.exec(B.slice(V))[1])}catch{}return $.levels[D]===void 0&&(D=void 0),D}}function ve(){if(!(typeof window===n||!N)){try{window.localStorage.removeItem(N);return}catch{}try{window.document.cookie=encodeURIComponent(N)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}$.name=C,$.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},$.methodFactory=H||g,$.getLevel=function(){return oe},$.setLevel=function(D,B){if(typeof D=="string"&&$.levels[D.toUpperCase()]!==void 0&&(D=$.levels[D.toUpperCase()]),typeof D=="number"&&D>=0&&D<=$.levels.SILENT){if(oe=D,B!==!1&&j(D),h.call($,D,C),typeof console===n&&D<$.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+D},$.setDefaultLevel=function(D){I=D,Se()||$.setLevel(D,!1)},$.resetLevel=function(){$.setLevel(I,!1),ve()},$.enableAll=function(D){$.setLevel($.levels.TRACE,D)},$.disableAll=function(D){$.setLevel($.levels.SILENT,D)};var k=Se();k==null&&(k=I),$.setLevel(k,!1)}var E=new T,y={};E.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var H=y[I];return H||(H=y[I]=new T(I,E.getLevel(),E.methodFactory)),H};var A=typeof window!==n?window.log:void 0;return E.noConflict=function(){return typeof window!==n&&window.log===E&&(window.log=A),E},E.getLoggers=function(){return y},E.default=E,E})})(Dh);var It=Dh.exports;const vs=()=>`${new Date().toISOString()} | metrics`,Es=(c,t,n)=>`${c} | ${t} | ${n}`;It.setDefaultLevel(It.levels.TRACE);const gv=c=>{It.info(Es(vs(),"log ",`set log level to ${c?"verbose":"info"}`)),It.setLevel(c?It.levels.TRACE:It.levels.INFO)},Tv=c=>{const t=[...Object.keys(It.levels)];t.includes(c)?(It.info(Es(vs(),"log ",`update log level to ${c.toLowerCase()}`)),It.setLevel(c)):It.warn(Es(vs(),"log ","Incorrect log level please choose one of "),t)},Pe=(c,t,n)=>{n?It.debug(Es(vs(),c,t),n):It.debug(Es(vs(),c,t))},iu=(c,t)=>{It.info(Es(vs(),c,t))},Rn=(c,t)=>{It.info(Es(vs(),c,t))},wa=(c,t)=>{It.warn(Es(vs(),c,t))},dr=(c,t)=>{It.error(Es(vs(),c,t))};function vv(c){return Math.floor(Math.random()*c).toString()}function xf(c,t){let n=t;return c.forEach(a=>{n=n.replace(a,"")}),n}function Ev(c,t){let n="";for(let a=0;a<t;a+=1)n+=c[vv(c.length)];return n}function Sv({length:c=20,useLetters:t=!0,useNumbers:n=!0,includeSymbols:a=[],excludeSymbols:o=[]}={}){let s="abcdefghijklmnopqrstuvwxyz",r="0123456789",d=[],h=[],_=[];return t&&(o.length&&(s=xf(o,s)),h=s.split("")),n&&(o.length&&(r=xf(o,r)),_=r.split("")),d=[...h,..._,...a],Ev(d,c)}var yv=Sv;const Qi=ze(yv),Av=()=>"WebRTCMetrics",Cv=()=>"5.0.3",$e={INBOUND:"inbound",OUTBOUND:"outbound"},gs={IDLE:"idle",RUNNING:"running",MUTED:"muted"},Ki={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},Rv=()=>({...{delta_time_to_measure_probes_ms:0,delta_time_consumed_to_measure_ms:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,total_time_decoded_in:0,total_time_encoded_out:0,probes:[]}}),Nh={level_in:0,codec_id_in:"",codec_in:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,mos_in:0,mos_emodel_in:0,ssrc:"",direction:$e.INBOUND},Uh={level_out:0,codec_id_out:"",codec_out:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,timestamp_out:null,mos_out:0,mos_emodel_out:0,ssrc:"",direction:$e.OUTBOUND},Ph={codec_id_in:"",size_in:{width:null,height:null,framerate:null},codec_in:{mime_type:null,clock_rate:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,decoder_in:null,delta_ms_decode_frame_in:0,total_frames_decoded_in:0,total_time_decoded_in:0,delta_nack_sent_in:0,delta_pli_sent_in:0,total_nack_sent_in:0,total_pli_sent_in:0,ssrc:"",direction:$e.INBOUND},xh={codec_id_out:"",size_out:{width:null,height:null,framerate:null},codec_out:{mime_type:null,clock_rate:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,encoder_out:null,delta_ms_encode_frame_out:0,total_time_encoded_out:0,total_frames_encoded_out:0,delta_nack_received_out:0,delta_pli_received_out:0,total_nack_received_out:0,total_pli_received_out:0,limitation_out:{reason:null,durations:null,resolutionChanges:0},timestamp_out:null,ssrc:"",direction:$e.OUTBOUND},Iv=c=>{const t={pname:"",call_id:"",user_id:"",timestamp:null,count:0,audio:{},video:{},network:{infrastructure:3,local_candidate_id:"",local_candidate_type:"",local_candidate_protocol:"",local_candidate_relay_protocol:"",remote_candidate_id:"",remote_candidate_type:"",remote_candidate_protocol:""},data:{total_KBytes_in:0,total_KBytes_out:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,delta_kbs_bandwidth_in:0,delta_kbs_bandwidth_out:0,delta_rtt_connectivity_ms:null,total_rtt_connectivity_ms:0,total_rtt_connectivity_measure:0},experimental:{time_to_measure_ms:0}};if(c){const n={...c,audio:{},video:{},data:{...c.data},network:{...c.network},experimental:{...c.experimental}};return Object.keys(c.audio).forEach(a=>{n.audio[a]={...c.audio[a]}}),Object.keys(c.video).forEach(a=>{n.video[a]={...c.video[a]}}),n}return{...t,audio:{},video:{},data:{...t.data},network:{...t.network},experimental:{...t.experimental}}},bv={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${Qi()}`,cid:`c-${Qi()}`,uid:`u-${Qi()}`,record:!1,ticket:!0},zt={CANDIDATE_PAIR:"candidate-pair",CODEC:"codec",INBOUND_RTP:"inbound-rtp",LOCAL_CANDIDATE:"local-candidate",MEDIA_SOURCE:"media-source",OUTBOUND_RTP:"outbound-rtp",REMOTE_CANDIDATE:"remote-candidate",REMOTE_INBOUND_RTP:"remote-inbound-rtp",TRACK:"track"},q={AUDIO_LEVEL:"audioLevel",AVAILABLE_OUTGOING_BITRATE:"availableOutgoingBitrate",AVAILABLE_INCOMING_BITRATE:"availableIncomingBitrate",BYTES_RECEIVED:"bytesReceived",BYTES_SENT:"bytesSent",CANDIDATE_TYPE:"candidateType",CHANNELS:"channels",CLOCK_RATE:"clockRate",CODEC_ID:"codecId",CURRENT_ROUND_TRIP_TIME:"currentRoundTripTime",ROUND_TRIP_TIME:"roundTripTime",FRACTION_LOST:"fractionLost",FRAME_HEIGHT:"frameHeight",FRAME_WIDTH:"frameWidth",QUALITY_LIMITATION_REASON:"qualityLimitationReason",QUALITY_LIMITATION_DURATIONS:"qualityLimitationDurations",QUALITY_LIMITATION_RESOLUTION_CHANGES:"qualityLimitationResolutionChanges",ID:"id",JITTER:"jitter",KIND:"kind",MEDIA_TYPE:"mediaType",MIME_TYPE:"mimeType",LOCAL_CANDIDATE_ID:"localCandidateId",NETWORK_TYPE:"networkType",RELAY_PROTOCOL:"relayProtocol",NOMINATED:"nominated",PACKETS_LOST:"packetsLost",PACKETS_RECEIVED:"packetsReceived",PACKETS_SENT:"packetsSent",PROTOCOL:"protocol",PORT:"port",REMOTE_CANDIDATE_ID:"remoteCandidateId",REMOTE_SOURCE:"remoteSource",RESPONSES_RECEIVED:"responsesReceived",SDP_FMTP_LINE:"sdpFmtpLine",SSRC:"ssrc",SELECTED:"selected",STATE:"state",TIMESTAMP:"timestamp",TOTAL_ROUND_TRIP_TIME:"totalRoundTripTime",TOTAL_ROUND_TRIP_TIME_MEASUREMENTS:"roundTripTimeMeasurements",TYPE:"type",DECODER_IMPLEMENTATION:"decoderImplementation",ENCODER_IMPLEMENTATION:"encoderImplementation",FRAMES_DECODED:"framesDecoded",FRAMES_ENCODED:"framesEncoded",FRAMES_PER_SECOND:"framesPerSecond",TOTAL_DECODE_TIME:"totalDecodeTime",TOTAL_ENCODE_TIME:"totalEncodeTime",PLI:"pliCount",NACK:"nackCount"},x={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},Yi={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},lu={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ne={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},au="config ",wv=(c,t={},n)=>{const a={...n,...t};return t.pname||wa(au,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${n.pname}'`),t.cid||wa(au,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${n.cid}'`),t.uid||wa(au,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${n.uid}'`),a.pc=c,a},Ov=(c={})=>{const t={...bv,...c};return t.name=Av(),t.version=Cv(),t},ml=(c,t,n,a=!1,o)=>{let s=c.map(r=>{if(!n)return r[t];if(!o)return r[t][n];const d=r[t][o];return d?d[n]:null});return s=s.filter(r=>a?Number.isFinite(r)&&r>0:Number.isFinite(r)),s.length===0?[]:s},Gs=c=>c.reduce((t,n)=>t+n,0)/c.length,Dv=()=>`probe-${Qi()}`,Nv=()=>`coltr-${Qi()}`,kf=c=>new Promise(t=>setTimeout(t,c)),wu=(c,t,n)=>{t?c.call(t,n):c(n)},Ke=(c,t,n,a)=>{const o=ml(c,t,n,!0,a);if(o.length===0)return null;const s=o.reduce((_,g)=>_+g,0)/o.length;return s===0?null:o.map(_=>Math.abs(s-_)).reduce((_,g)=>_+g,0)/o.length*100/s},Xe=(c,t,n,a=!1,o)=>{const s=ml(c,t,n,a,o);return s.length===0?null:s.reduce((r,d)=>r+d,0)/s.length},Sn=(c,t,n)=>ml(c,t,n).reduce((o,s)=>o+s,0),Ye=(c,t,n,a)=>{const o=ml(c,t,n,!0,a);return o.length===0?null:Math.min(...o)},Je=(c,t,n,a)=>{const o=ml(c,t,n,!1,a);return o.length===0?null:Math.max(...o)},gt=(c,t,n,a)=>{const o=c.slice().pop();if(!o)return null;if(!n)return o[t];if(!a)return o[t][n];const s=o[t][a];return s?s[n]:null},Uv=c=>c.slice().pop(),ct=(c,t,n)=>{if(!t)return null;const a={};let o=t[x.AUDIO][c];o||(o=n===$e.INBOUND?{...Nh}:{...Uh}),a[x.AUDIO]=o;let s=t[x.VIDEO][c];return s||(s=n===$e.INBOUND?{...Ph}:{...xh}),a[x.VIDEO]=s,a},Ji="exporter ",Pv="2.0",Mf=(c,t,n)=>{if(!c||c.length===0)return 0;const a=c[c.length-1];if(!a)return 0;const o=a[t][n];if(o){const s=o.total_rtt_ms_out,r=o.total_rtt_measure_out;return!r||!s?Xe(c,t,"delta_rtt_ms_out",!1,n):Number(s/r)}return null},xv=(c,t)=>{if(!c||c.length===0)return 0;const n=c[c.length-1];if(!n)return 0;const a=n[t].total_rtt_connectivity_ms,o=n[t].total_rtt_connectivity_measure;return!o||!a?Xe(c,t,"delta_rtt_connectivity_ms"):Number(a/o)},kv=c=>gt(c,"network","local_candidate_type")!=="relay"?`direct/${gt(c,"network","local_candidate_protocol")}`:`turn/${gt(c,"network","local_candidate_relay_protocol")}`,Mv=c=>{const t=gt(c,"network","remote_candidate_type"),n=gt(c,"network","remote_candidate_protocol");return t!=="relay"?`direct/${n}`:`turn/${n}`};class Lv{constructor(t){this._start=null,this._end=null,this._cfg=t,this._referenceReport=null,this._reports=[],this._events=[]}start(){iu(Ji,"start() - start exporter...");const t=new Date;return this._start=t.toJSON(),t}stop(){iu(Ji,"stop() - stop exporter...");const t=new Date;return this._end=t.toJSON(),t}saveReferenceReport(t){this._referenceReport=t}getReferenceReport(){return this._referenceReport}addReport(t){this._cfg.ticket&&(Pe(Ji,`addReport() - add report to exporter at ${t.timestamp}`),this._reports.push(t))}addCustomEvent(t){this._events.push(t)}reset(){iu(Ji,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Pe(Ji,"ticket() - generate ticket");const t=gt(this._reports,"audio","total_packets_lost_in"),n=gt(this._reports,"audio","total_packets_in"),a=gt(this._reports,"video","total_packets_lost_in"),o=gt(this._reports,"video","total_packets_in"),s={},r=Uv(this._reports);return r&&(Object.keys(r[x.AUDIO]).forEach(d=>{const h=r[x.AUDIO][d];if(s[h.ssrc]={type:x.AUDIO,direction:h.direction},h.direction===$e.INBOUND){const _={avg:Xe(this._reports,x.AUDIO,"delta_jitter_ms_in",!1,d),min:Ye(this._reports,x.AUDIO,"delta_jitter_ms_in",d),max:Je(this._reports,x.AUDIO,"delta_jitter_ms_in",d),volatility:Ke(this._reports,x.AUDIO,"delta_jitter_ms_in",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.AUDIO,"delta_kbs_in",!1,d),min:Ye(this._reports,x.AUDIO,"delta_kbs_in",d),max:Je(this._reports,x.AUDIO,"delta_kbs_in",d),volatility:Ke(this._reports,x.AUDIO,"delta_kbs_in",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.AUDIO,"delta_KBytes_in",!1,d),min:Ye(this._reports,x.AUDIO,"delta_KBytes_in",d),max:Je(this._reports,x.AUDIO,"delta_KBytes_in",d),volatility:Ke(this._reports,x.AUDIO,"delta_KBytes_in",d),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={emodel:{avg:Xe(this._reports,x.AUDIO,"mos_emodel_in",!1,d),min:Ye(this._reports,x.AUDIO,"mos_emodel_in",d),max:Je(this._reports,x.AUDIO,"mos_emodel_in",d),volatility:Ke(this._reports,x.AUDIO,"mos_emodel_in",d)},effective:{avg:Xe(this._reports,x.AUDIO,"mos_in",!1,d),min:Ye(this._reports,x.AUDIO,"mos_in",d),max:Je(this._reports,x.AUDIO,"mos_in",d),volatility:Ke(this._reports,x.AUDIO,"mos_in",d)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},y=gt(this._reports,x.AUDIO,"total_packets_lost_in",d),A=gt(this._reports,x.AUDIO,"total_packets_in",d),C={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[d].jitter=_,s[d].mos=E,s[d].traffic=T,s[d].bitrate=g,s[d].loss=C}else{const _={avg:Xe(this._reports,x.AUDIO,"delta_jitter_ms_out",!1,d),min:Ye(this._reports,x.AUDIO,"delta_jitter_ms_out",d),max:Je(this._reports,x.AUDIO,"delta_jitter_ms_out",d),volatility:Ke(this._reports,x.AUDIO,"delta_jitter_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.AUDIO,"delta_kbs_out",!1,d),min:Ye(this._reports,x.AUDIO,"delta_kbs_out",d),max:Je(this._reports,x.AUDIO,"delta_kbs_out",d),volatility:Ke(this._reports,x.AUDIO,"delta_kbs_out",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.AUDIO,"delta_KBytes_out",!1,d),min:Ye(this._reports,x.AUDIO,"delta_KBytes_out",d),max:Je(this._reports,x.AUDIO,"delta_KBytes_out",d),volatility:Ke(this._reports,x.AUDIO,"delta_KBytes_out",d),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},E={avg:Mf(this._reports,x.AUDIO,d),min:Ye(this._reports,x.AUDIO,"delta_rtt_ms_out",d),max:Je(this._reports,x.AUDIO,"delta_rtt_ms_out",d),volatility:Ke(this._reports,x.AUDIO,"delta_rtt_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=gt(this._reports,x.AUDIO,"total_packets_lost_out",d),A=gt(this._reports,x.AUDIO,"total_packets_out",d),C={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},I={emodel:{avg:Xe(this._reports,x.AUDIO,"mos_emodel_out",!1,d),min:Ye(this._reports,x.AUDIO,"mos_emodel_out",d),max:Je(this._reports,x.AUDIO,"mos_emodel_out",d),volatility:Ke(this._reports,x.AUDIO,"mos_emodel_out",d)},effective:{avg:Xe(this._reports,x.AUDIO,"mos_out",!1,d),min:Ye(this._reports,x.AUDIO,"mos_out",d),max:Je(this._reports,x.AUDIO,"mos_out",d),volatility:Ke(this._reports,x.AUDIO,"mos_out",d)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};s[d].jitter=_,s[d].rtt=E,s[d].traffic=T,s[d].bitrate=g,s[d].loss=C,s[d].mos=I}}),Object.keys(r[x.VIDEO]).forEach(d=>{const h=r[x.VIDEO][d];if(s[d]={type:x.VIDEO,direction:h.direction},h.direction===$e.INBOUND){const _={avg:Xe(this._reports,x.VIDEO,"delta_jitter_ms_in",!1,d),min:Ye(this._reports,x.VIDEO,"delta_jitter_ms_in",d),max:Je(this._reports,x.VIDEO,"delta_jitter_ms_in",d),volatility:Ke(this._reports,x.VIDEO,"delta_jitter_ms_in",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.VIDEO,"delta_kbs_in",!1,d),min:Ye(this._reports,x.VIDEO,"delta_kbs_in",d),max:Je(this._reports,x.VIDEO,"delta_kbs_in",d),volatility:Ke(this._reports,x.VIDEO,"delta_kbs_in",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.VIDEO,"delta_KBytes_in",!1,d),min:Ye(this._reports,x.VIDEO,"delta_KBytes_in",d),max:Je(this._reports,x.VIDEO,"delta_KBytes_in",d),volatility:Ke(this._reports,x.VIDEO,"delta_KBytes_in",d),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E=gt(this._reports,x.VIDEO,"total_packets_lost_in",d),y=gt(this._reports,x.VIDEO,"total_packets_in",d),A={lost:E,avg:Math.round((E/(E+y)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[d].jitter=_,s[d].traffic=T,s[d].bitrate=g,s[d].loss=A}else{const _={avg:Xe(this._reports,x.VIDEO,"delta_jitter_ms_out",!1,d),min:Ye(this._reports,x.VIDEO,"delta_jitter_ms_out",d),max:Je(this._reports,x.VIDEO,"delta_jitter_ms_out",d),volatility:Ke(this._reports,x.VIDEO,"delta_jitter_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.VIDEO,"delta_kbs_out",!1,d),min:Ye(this._reports,x.VIDEO,"delta_kbs_out",d),max:Je(this._reports,x.VIDEO,"delta_kbs_out",d),volatility:Ke(this._reports,x.VIDEO,"delta_kbs_out",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.VIDEO,"delta_KBytes_out",!1,d),min:Ye(this._reports,x.VIDEO,"delta_KBytes_out",d),max:Je(this._reports,x.VIDEO,"delta_KBytes_out",d),volatility:Ke(this._reports,x.VIDEO,"delta_KBytes_out",d),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={avg:Mf(this._reports,x.VIDEO,d),min:Ye(this._reports,x.VIDEO,"delta_rtt_ms_out",d),max:Je(this._reports,x.VIDEO,"delta_rtt_ms_out",d),volatility:Ke(this._reports,x.VIDEO,"delta_rtt_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=gt(this._reports,x.VIDEO,"total_packets_lost_out",d),A=gt(this._reports,x.VIDEO,"total_packets_out",d),C={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[d].jitter=_,s[d].rtt=E,s[d].traffic=T,s[d].bitrate=g,s[d].loss=C}})),{version:Pv,configuration:{frequency:this._cfg.refreshEvery},started:this._start,ended:this._end,ua:{agent:navigator.userAgent,pname:this._cfg.pname,user_id:this._cfg.uid},call:{call_id:this._cfg.cid,events:this._events},details:{count:this._reports.length,reports:this._cfg.record?this._reports:[],reference:this._referenceReport||null},ssrc:s,data:{rtt:{avg:xv(this._reports,"data"),min:Ye(this._reports,"data","delta_rtt_connectivity_ms"),max:Je(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Ke(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((t/(t+n)*100||0)*100)/100}},video:{in:{avg:Math.round((a/(a+o)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:Xe(this._reports,"data","delta_kbs_in"),min:Ye(this._reports,"data","delta_kbs_in"),max:Je(this._reports,"data","delta_kbs_in"),volatility:Ke(this._reports,"data","delta_kbs_in")},out:{avg:Xe(this._reports,"data","delta_kbs_out"),min:Ye(this._reports,"data","delta_kbs_out"),max:Je(this._reports,"data","delta_kbs_out"),volatility:Ke(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:Xe(this._reports,"data","delta_KBytes_in"),min:Ye(this._reports,"data","delta_KBytes_in"),max:Je(this._reports,"data","delta_KBytes_in"),volatility:Ke(this._reports,"data","delta_KBytes_in")},out:{avg:Xe(this._reports,"data","delta_KBytes_out"),min:Ye(this._reports,"data","delta_KBytes_out"),max:Je(this._reports,"data","delta_KBytes_out"),volatility:Ke(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:kv(this._reports),remoteConnection:Mv(this._reports)}}}}updateConfig(t){this._cfg=t}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const t=this._reports.slice();return t.pop(),t.pop()||null}getReportsNumber(){return this._reports.length}}const js="extractor ",Lf=(c,t,n,a)=>{let o=!1;const s=a[t].total_rtt_ms_out,r=a[t].total_rtt_measure_out,d=n?n[t].total_rtt_ms_out:0,h=n?n[t].total_rtt_measure_out:0,_={rtt:null,totalRTT:s,totalRTTMeasurements:r};if(c[q.TIMESTAMP]===a[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,q.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(o=!0,Number(c[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-h===r))return _;const g=1e3*Number(c[q.ROUND_TRIP_TIME]);let T=s+g,E=r+1;return o&&(T=1e3*Number(c[q.TOTAL_ROUND_TRIP_TIME])-d,E=Number(c[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-h),{rtt:g,totalRTT:T,totalRTTMeasurements:E}},$v=(c,t,n,a)=>{if(!Object.prototype.hasOwnProperty.call(c,q.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:a[t].total_rtt_connectivity_ms,totalRTTMeasurements:a[t].total_rtt_connectivity_measure};const o=1e3*Number(c[q.CURRENT_ROUND_TRIP_TIME]);let s=a[t].total_rtt_connectivity_ms+o,r=a[t].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,q.TOTAL_ROUND_TRIP_TIME)&&(s=1e3*Number(c[q.TOTAL_ROUND_TRIP_TIME])-(n?n[t].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,q.RESPONSES_RECEIVED)&&(r=Number(c[q.RESPONSES_RECEIVED])-(n?n[t].total_rtt_connectivity_measure:0)),{rtt:o,totalRTT:s,totalRTTMeasurements:r}},da=(c,t,n)=>c[q.TIMESTAMP]===n[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,q.JITTER)?null:1e3*(Number(c[q.JITTER])||0),Hv=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,q.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,q.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:t[x.VIDEO].delta_ms_decode_frame_in,frames_decoded:t[x.VIDEO].total_frames_decoded_in,total_decode_time:t[x.VIDEO].total_time_decoded_in};const n=c[q.FRAMES_DECODED],a=c[q.TOTAL_DECODE_TIME],o=a-t[x.VIDEO].total_time_decoded_in,s=n-t[x.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:s>0?o*1e3/s:0,frames_decoded:n,total_decode_time:a}},Fv=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,q.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,q.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:t[x.VIDEO].delta_ms_encode_frame_out,frames_encoded:t[x.VIDEO].total_frames_encoded_out,total_encode_time:t[x.VIDEO].total_time_encoded_out};const n=c[q.FRAMES_ENCODED],a=c[q.TOTAL_ENCODE_TIME],o=a-t[x.VIDEO].total_time_encoded_out,s=n-t[x.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:s>0&&o?o*1e3/s:0,frames_encoded:n,total_encode_time:a}},$f=(c,t,n,a)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,q.BYTES_SENT))return{packetsSent:n[t].total_packets_out,packetsLost:n[t].total_packets_lost_out,bytesSent:n[t].total_KBytes_out};const o=Number(c[q.PACKETS_SENT])||0-(a?a[t].total_packets_out:0),s=o-n[t].total_packets_out,r=Number(c[q.BYTES_SENT])/1024-(a?a[t].total_KBytes_out:0),d=r-n[t].total_KBytes_out,h=c[q.TIMESTAMP]||Date.now(),_=a?a.timestamp:null;let g=n.timestamp;!g&&_&&(g=_);const T=g?h-g:0,E=T>0?d*.008*1024/T*1e3:0;return{packetsSent:o,deltaPacketsSent:s,KBytesSent:r,deltaKBytesSent:d,kbsSent:E}},Hf=(c,t,n,a)=>{let o=n[t].total_packets_lost_out,s=0,r=0;return Object.prototype.hasOwnProperty.call(c,q.PACKETS_LOST)&&(o=Number(c[q.PACKETS_LOST])||0-(a?a[t].total_packets_lost_out:0),s=o-n[t].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,q.FRACTION_LOST)&&(r=Number(100*c[q.FRACTION_LOST])),{packetsLost:o,deltaPacketsLost:s,fractionLost:r}},Ff=(c,t,n,a)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,q.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,q.BYTES_RECEIVED))return{percent_packets_lost:n[t].percent_packets_lost_in,packetsReceived:n[t].total_packets_in,packetsLost:n[t].total_packets_lost_in,bytesReceived:n[t].total_KBytes_in};const o=Number(c[q.PACKETS_RECEIVED])||0-(a?a[t].total_packets_in:0),s=Number(c[q.PACKETS_LOST])||0-(a?a[t].total_packets_lost_in:0),r=s-n[t].total_packets_lost_in,d=o-n[t].total_packets_in,h=o!==n[t].total_packets_in?r*100/(r+d):0,_=Number(c[q.BYTES_RECEIVED])/1024-(a?a[t].total_KBytes_in:0),g=_-n[t].total_KBytes_in,T=c[q.TIMESTAMP]||Date.now(),E=a?a.timestamp:null;let y=n.timestamp;!y&&E&&(y=E);const A=y?T-y:0,C=A>0?g*.008*1024/A*1e3:0;return{percentPacketsLost:h,packetsReceived:o,deltaPacketsReceived:d,packetsLost:s,deltaPacketsLost:r,KBytesReceived:_,deltaKBytesReceived:g,kbsReceived:C}},jv=c=>c[q.CANDIDATE_TYPE]!=="relay"?"":c[q.RELAY_PROTOCOL]||"",qv=c=>{if(!Object.prototype.hasOwnProperty.call(c,q.NETWORK_TYPE))return Yi.WIFI;switch(c[q.NETWORK_TYPE]){case lu.ETHERNET:return Yi.ETHERNET;case lu.CELLULAR_4G:return Yi.CELLULAR_4G;case lu.WIFI:return Yi.WIFI;default:return Yi.CELLULAR}},jf=c=>!Object.prototype.hasOwnProperty.call(c,q.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,q.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[q.FRAME_WIDTH]||null,height:c[q.FRAME_HEIGHT]||null,framerate:c[q.FRAMES_PER_SECOND]},Vv=c=>{const t=Object.prototype.hasOwnProperty.call(c,q.QUALITY_LIMITATION_REASON)?c[q.QUALITY_LIMITATION_REASON]:null,n=Object.prototype.hasOwnProperty.call(c,q.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[q.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,a=Object.prototype.hasOwnProperty.call(c,q.QUALITY_LIMITATION_DURATIONS)?c[q.QUALITY_LIMITATION_DURATIONS]:null;return a&&Object.keys(a).forEach(o=>{a[o]>1e3&&(a[o]=Number(a[o]/1e3))}),{reason:t,durations:a,resolutionChanges:n}},Bv=(c,t,n)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PLI)||!Object.prototype.hasOwnProperty.call(c,q.NACK))return{pliCount:t.total_pli_sent_in,nackCount:t.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const a=(c[q.PLI]||0)-(n?n[x.VIDEO].total_pli_sent_in:0),o=(c[q.NACK]||0)-(n?n[x.VIDEO].total_nack_sent_in:0);return{pliCount:a,nackCount:o,deltaPliCount:a-t[x.VIDEO].total_pli_sent_in,deltaNackCount:o-t[x.VIDEO].total_nack_sent_in}},Gv=(c,t,n)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PLI)||!Object.prototype.hasOwnProperty.call(c,q.NACK))return{pliCount:t.total_pli_received_out,nackCount:t.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const a=(c[q.PLI]||0)-(n?n[x.VIDEO].total_pli_received_out:0),o=(c[q.NACK]||0)-(n?n[x.VIDEO].total_nack_received_out:0);return{pliCount:a,nackCount:o,deltaPliCount:a-t[x.VIDEO].total_pli_received_out,deltaNackCount:o-t[x.VIDEO].total_nack_received_out}},Wv=c=>({channels:c[q.CHANNELS]||null,clock_rate:c[q.CLOCK_RATE]||null,mime_type:c[q.MIME_TYPE]||null,sdp_fmtp_line:c[q.SDP_FMTP_LINE]||null}),Kv=c=>({clock_rate:c[q.CLOCK_RATE]||null,mime_type:c[q.MIME_TYPE]||null}),Yv=(c,t,n)=>{const a=(c[q.BYTES_RECEIVED]||0)/1024-(n?n.data.total_KBytes_in:0),o=(c[q.BYTES_SENT]||0)/1024-(n?n.data.total_KBytes_out:0),s=c[q.TIMESTAMP]||Date.now(),r=a-t.data.total_KBytes_in,d=o-t.data.total_KBytes_out,h=n?n.timestamp:null;let _=t.timestamp;!_&&h&&(_=h);const g=_?s-_:0,T=g>0?r*.008*1024/g*1e3:0,E=g>0?d*.008*1024/g*1e3:0;return{total_KBytes_received:a,total_KBytes_sent:o,delta_KBytes_received:r,delta_KBytes_sent:d,kbs_speed_received:T,kbs_speed_sent:E}},Jv=c=>{const t=c[q.AVAILABLE_INCOMING_BITRATE]/1024||0,n=c[q.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:t,kbs_outgoing_bandwidth:n}},zv=(c,t,n,a)=>{if(!c)return[];switch(c[q.TYPE]){case zt.CANDIDATE_PAIR:let o=!1;if(c[q.NOMINATED]&&c[q.STATE]===x.SUCCEEDED&&(o=!0,Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c),q.SELECTED in c&&!c[q.SELECTED]&&(o=!1)),o){const r=c[q.LOCAL_CANDIDATE_ID],d=c[q.REMOTE_CANDIDATE_ID],h=Yv(c,t,a),_=Jv(c),g=$v(c,"data",a,t);return[{type:ne.NETWORK,value:{local_candidate_id:r}},{type:ne.NETWORK,value:{remote_candidate_id:d}},{type:ne.DATA,value:{total_KBytes_in:h.total_KBytes_received}},{type:ne.DATA,value:{total_KBytes_out:h.total_KBytes_sent}},{type:ne.DATA,value:{delta_KBytes_in:h.delta_KBytes_received}},{type:ne.DATA,value:{delta_KBytes_out:h.delta_KBytes_sent}},{type:ne.DATA,value:{delta_kbs_in:h.kbs_speed_received}},{type:ne.DATA,value:{delta_kbs_out:h.kbs_speed_sent}},{type:ne.DATA,value:{delta_kbs_bandwidth_in:_.kbs_incoming_bandwidth}},{type:ne.DATA,value:{delta_kbs_bandwidth_out:_.kbs_outgoing_bandwidth}},{type:ne.DATA,value:{delta_rtt_connectivity_ms:g.rtt}},{type:ne.DATA,value:{total_rtt_connectivity_ms:g.totalRTT}},{type:ne.DATA,value:{total_rtt_connectivity_measure:g.totalRTTMeasurements}}]}break;case zt.LOCAL_CANDIDATE:if(c[q.ID]===t.network.local_candidate_id)return[{type:ne.NETWORK,value:{infrastructure:qv(c)}},{type:ne.NETWORK,value:{local_candidate_type:c[q.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{local_candidate_protocol:c[q.PROTOCOL]||""}},{type:ne.NETWORK,value:{local_candidate_relay_protocol:jv(c)}}];break;case zt.REMOTE_CANDIDATE:if(c[q.ID]===t.network.remote_candidate_id)return[{type:ne.NETWORK,value:{remote_candidate_type:c[q.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{remote_candidate_protocol:c[q.PROTOCOL]||""}}];break;case zt.INBOUND_RTP:{Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const r=c[q.SSRC],d=ct(r,t,$e.INBOUND);d&&(d.timestamp=t.timestamp);const h=ct(r,a,$e.INBOUND);if(h&&(h.timestamp=a.timestamp),c[q.MEDIA_TYPE]===x.AUDIO){const _=Ff(c,x.AUDIO,d,h),g=da(c,x.AUDIO,d),T=c[q.CODEC_ID]||"";return[{ssrc:r,type:ne.AUDIO,value:{codec_id_in:T}},{ssrc:r,type:ne.AUDIO,value:{total_packets_in:_.packetsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_in:_.deltaPacketsReceived}},{ssrc:r,type:ne.AUDIO,value:{total_packets_lost_in:_.packetsLost}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_lost_in:_.deltaPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{percent_packets_lost_in:_.percentPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{total_KBytes_in:_.KBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_KBytes_in:_.deltaKBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_kbs_in:_.kbsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_in:g}}]}if(c[q.MEDIA_TYPE]===x.VIDEO){const _=Hv(c,d),g=Ff(c,x.VIDEO,d,h),T=da(c,x.VIDEO,d),E=c[q.DECODER_IMPLEMENTATION]||null,y=c[q.CODEC_ID]||null,A=jf(c),C=Bv(c,d,h);return[{ssrc:r,type:ne.VIDEO,value:{codec_id_in:y}},{ssrc:r,type:ne.VIDEO,value:{total_packets_in:g.packetsReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_in:g.deltaPacketsReceived}},{ssrc:r,type:ne.VIDEO,value:{total_packets_lost_in:g.packetsLost}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_lost_in:g.deltaPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{percent_packets_lost_in:g.percentPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{total_KBytes_in:g.KBytesReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_KBytes_in:g.deltaKBytesReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_kbs_in:g.kbsReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_jitter_ms_in:T}},{ssrc:r,type:ne.VIDEO,value:{decoder_in:E}},{ssrc:r,type:ne.VIDEO,value:{delta_ms_decode_frame_in:_.delta_ms_decode_frame}},{ssrc:r,type:ne.VIDEO,value:{total_frames_decoded_in:_.frames_decoded}},{ssrc:r,type:ne.VIDEO,value:{total_time_decoded_in:_.total_decode_time}},{ssrc:r,type:ne.VIDEO,value:{total_nack_sent_in:C.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_sent_in:C.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_sent_in:C.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_sent_in:C.deltaPliCount}},{ssrc:r,type:ne.VIDEO,value:{size_in:A}}]}break}case zt.OUTBOUND_RTP:{Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const r=c[q.SSRC],d=ct(r,t,$e.OUTBOUND);d&&(d.timestamp=t.timestamp);const h=ct(r,a,$e.OUTBOUND);if(h&&(h.timestamp=a.timestamp),c[q.MEDIA_TYPE]===x.AUDIO){const _=c[q.CODEC_ID]||null,g=$f(c,x.AUDIO,d,h);return[{ssrc:r,type:ne.AUDIO,value:{codec_id_out:_}},{ssrc:r,type:ne.AUDIO,value:{total_packets_out:g.packetsSent}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_out:g.deltaPacketsSent}},{ssrc:r,type:ne.AUDIO,value:{total_KBytes_out:g.KBytesSent}},{ssrc:r,type:ne.AUDIO,value:{delta_KBytes_out:g.deltaKBytesSent}},{ssrc:r,type:ne.AUDIO,value:{delta_kbs_out:g.kbsSent}}]}if(c[q.MEDIA_TYPE]===x.VIDEO){const _=c[q.ENCODER_IMPLEMENTATION]||null,g=c[q.CODEC_ID]||null,T=Fv(c,d),E=jf(c),y=Vv(c),A=Gv(c,d,h),C=$f(c,x.VIDEO,d,h);return[{ssrc:r,type:ne.VIDEO,value:{codec_id_out:g}},{ssrc:r,type:ne.VIDEO,value:{total_packets_out:C.packetsSent}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_out:C.deltaPacketsSent}},{ssrc:r,type:ne.VIDEO,value:{total_KBytes_out:C.KBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_KBytes_out:C.deltaKBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_kbs_out:C.kbsSent}},{ssrc:r,type:ne.VIDEO,value:{encoder_out:_}},{ssrc:r,type:ne.VIDEO,value:{delta_ms_encode_frame_out:T.delta_ms_encode_frame}},{ssrc:r,type:ne.VIDEO,value:{total_frames_encoded_out:T.frames_encoded}},{ssrc:r,type:ne.VIDEO,value:{total_time_encoded_out:T.total_encode_time}},{ssrc:r,type:ne.VIDEO,value:{total_nack_received_out:A.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_received_out:A.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_received_out:A.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_received_out:A.deltaPliCount}},{ssrc:r,type:ne.VIDEO,value:{size_out:E}},{ssrc:r,type:ne.VIDEO,value:{limitation_out:y}}]}break}case zt.MEDIA_SOURCE:{Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);break}case zt.TRACK:{Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);break}case zt.CODEC:const s=[];return Object.keys(t[x.AUDIO]).forEach(r=>{const d=t[x.AUDIO][r];if(d.codec_id_in===c[q.ID]||d.codec_id_out===c[q.ID]){Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const h=Wv(c);c[q.ID]===d.codec_id_in?s.push({ssrc:d.ssrc,type:ne.AUDIO,value:{codec_in:h}}):s.push({ssrc:d.ssrc,type:ne.AUDIO,value:{codec_out:h}})}}),Object.keys(t[x.VIDEO]).forEach(r=>{const d=t[x.VIDEO][r];if(d.codec_id_in===c[q.ID]||d.codec_id_out===c[q.ID]){Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const h=Kv(c);c[q.ID]===d.codec_id_in?s.push({ssrc:d.ssrc,type:ne.VIDEO,value:{codec_in:h}}):s.push({ssrc:d.ssrc,type:ne.VIDEO,value:{codec_out:h}})}}),s;case zt.REMOTE_INBOUND_RTP:{Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const r=c[q.SSRC],d=ct(r,t,$e.OUTBOUND),h=ct(r,a,$e.OUTBOUND);if(c[q.KIND]===x.AUDIO){const _=Lf(c,x.AUDIO,h,d),g=da(c,x.AUDIO,d),T=Hf(c,x.AUDIO,d,h);return[{ssrc:r,type:ne.AUDIO,value:{delta_rtt_ms_out:_.rtt}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_ms_out:_.totalRTT}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_measure_out:_.totalRTTMeasurements}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_out:g}},{ssrc:r,type:ne.AUDIO,value:{timestamp_out:c[q.TIMESTAMP]}},{ssrc:r,type:ne.AUDIO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{percent_packets_lost_out:T.fractionLost}}]}if(c[q.KIND]===x.VIDEO){const _=Lf(c,x.VIDEO,h,d),g=da(c,x.VIDEO,d),T=Hf(c,x.VIDEO,d,h);return[{ssrc:r,type:ne.VIDEO,value:{delta_rtt_ms_out:_.rtt}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_ms_out:_.totalRTT}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_measure_out:_.totalRTTMeasurements}},{ssrc:r,type:ne.VIDEO,value:{delta_jitter_ms_out:g}},{ssrc:r,type:ne.VIDEO,value:{timestamp_out:c[q.TIMESTAMP]}},{ssrc:r,type:ne.VIDEO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{percent_packets_lost_out:T.fractionLost}}]}break}}return[]},Ka=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),Xv=(c,t=x.AUDIO,n,a,o)=>{const s=ct(o,c,$e.INBOUND),r=ct(o,n,$e.INBOUND),d=ct(o,a,$e.INBOUND),h=[],_=[],g=s[t].percent_packets_lost_in,T=s[t].delta_jitter_ms_in,E=r&&r[t].delta_jitter_ms_in||null,y=d&&d[t].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,C=n&&n.data.delta_rtt_connectivity_ms||null,I=a&&a.data.delta_rtt_connectivity_ms||null;A&&h.push(A),C&&h.push(C),I&&h.push(I),T&&_.push(T),n&&E&&_.push(E),a&&y&&_.push(y);const H=h.length>0?Gs(h):100,$=_.length>0?Gs(_):10,oe=93.2-g,N=.18*oe*oe-27.9*oe+1126.62,j=(H+$)/2,Se=j-177.3<0?0:1,ve=.024*j+.11*(j-177.3)*Se,k=N-ve;return Ka(k)},Qv=(c,t=x.AUDIO,n,a,o)=>{const s=ct(o,c,$e.OUTBOUND),r=ct(o,n,$e.OUTBOUND),d=ct(o,a,$e.OUTBOUND),h=[],_=[],g=s[t].percent_packets_lost_out,T=s[t].delta_rtt_ms_out,E=r&&r[t].delta_rtt_ms_out||null,y=d&&d[t].delta_rtt_ms_out||null,A=s[t].delta_jitter_ms_out,C=r&&r[t].delta_jitter_ms_out||null,I=d&&d[t].delta_jitter_ms_out||null,H=c.data.delta_rtt_connectivity_ms,$=n&&n.data.delta_rtt_connectivity_ms||null,oe=a&&a.data.delta_rtt_connectivity_ms||null;T?h.push(T):H&&h.push(H),E?h.push(E):$&&h.push($),y?h.push(y):oe&&h.push(oe),A&&_.push(A),n&&C&&_.push(C),a&&I&&_.push(I);const N=h.length>0?Gs(h):100,j=_.length>0?Gs(_):10,Se=93.2-g,ve=.18*Se*Se-27.9*Se+1126.62,k=(N+j)/2,D=k-177.3<0?0:1,B=.024*k+.11*(k-177.3)*D,V=ve-B;return Ka(V)},Zv=(c,t=x.AUDIO,n,a,o)=>{const s=ct(o,c,$e.INBOUND),r=ct(o,n,$e.INBOUND),d=ct(o,a,$e.INBOUND),h=[],_=[],g=s[t].percent_packets_lost_in/100,T=s[t].delta_jitter_ms_in,E=r&&r[t].delta_jitter_ms_in||null,y=d&&d[t].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,C=n&&n.data.delta_rtt_connectivity_ms||null,I=a&&a.data.delta_rtt_connectivity_ms||null;A&&h.push(A),C&&h.push(C),I&&h.push(I),T&&_.push(T),r&&E&&_.push(E),d&&y&&_.push(y);const H=h.length>0?Gs(h):100,$=_.length>0?Gs(_):10,oe=0,N=19.8,j=29.7,Se=30,ve=(H+$)/2+Se,k=ve-177.3<0?0:1,D=.024*ve+.11*(ve-177.3)*k,V=93.2-(oe+N*Math.log(1+j*g)+D);return Ka(V)},eE=(c,t=x.AUDIO,n,a,o)=>{const s=ct(o,c,$e.OUTBOUND),r=ct(o,n,$e.OUTBOUND),d=ct(o,a,$e.OUTBOUND),h=[],_=[],g=s[t].percent_packets_lost_out/100,T=s[t].delta_rtt_ms_out,E=r&&r[t].delta_rtt_ms_out||null,y=d&&d[t].delta_rtt_ms_out||null,A=s[t].delta_jitter_ms_out,C=r&&r[t].delta_jitter_ms_out||null,I=d&&d[t].delta_jitter_ms_out||null,H=c.data.delta_rtt_connectivity_ms,$=n&&n.data.delta_rtt_connectivity_ms||null,oe=a&&a.data.delta_rtt_connectivity_ms||null;T?h.push(T):H&&h.push(H),E?h.push(E):$&&h.push($),y?h.push(y):oe&&h.push(oe),A&&_.push(A),r&&C&&_.push(C),d&&I&&_.push(I);const N=h.length>0?Gs(h):100,j=_.length>0?Gs(_):10,Se=0,ve=19.8,k=29.7,D=30,B=(N+j)/2+D,V=B-177.3<0?0:1,J=.024*B+.11*(B-177.3)*V,X=93.2-(Se+ve*Math.log(1+k*g)+J);return Ka(X)};class tE{constructor(t,n){this._callbacks={onreport:null,onticket:null},this._id=Nv(),this._moduleName=this._id,this._probeId=n,this._config=t,this._exporter=new Lv(t),this._state=gs.IDLE,this.registerToPCEvents(),Rn(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(t,n,a,o){const s=(h,_)=>h===x.AUDIO?_===zt.INBOUND_RTP?{...Nh}:{...Uh}:_===zt.INBOUND_RTP?{...Ph}:{...xh},r=Iv(n);r.pname=this._config.pname,r.call_id=this._config.cid,r.user_id=this._config.uid,r.count=n?n.count+1:1;let d=null;return t.forEach(h=>{!d&&h.timestamp&&(d=h.timestamp),zv(h,r,r.pname,o).forEach(g=>{if(g.value&&g.type)if(g.ssrc){let T=r[g.type][g.ssrc];T||(T=s(g.type,h.type),T.ssrc=g.ssrc,r[g.type][g.ssrc]=T),Object.keys(g.value).forEach(E=>{T[E]=g.value[E]})}else Object.keys(g.value).forEach(T=>{r[g.type][T]=g.value[T]})})}),r.timestamp=d,Object.keys(r[x.AUDIO]).forEach(h=>{const _=r[x.AUDIO][h];_.direction===$e.INBOUND?(_.mos_emodel_in=Xv(r,x.AUDIO,n,a,_.ssrc),_.mos_in=Zv(r,x.AUDIO,n,a,_.ssrc)):(_.mos_emodel_out=Qv(r,x.AUDIO,n,a,_.ssrc),_.mos_out=eE(r,x.AUDIO,n,a,_.ssrc))}),r}async takeReferenceStats(){return new Promise((t,n)=>{const a=Date.now();setTimeout(async()=>{try{const o=Date.now()-a,s=Date.now(),r=await this._config.pc.getStats(),d=this.analyze(r,null,null,null),h=Date.now();d.experimental.time_to_measure_ms=h-s,d.experimental.time_to_wait_ms=o,this._exporter.saveReferenceReport(d),Pe(this._moduleName,`got reference report for probe ${this._probeId}`),t()}catch(o){n(o)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==gs.RUNNING||!this._config.pc)return Pe(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const t=Date.now(),n=await this._config.pc.getStats(),a=this.analyze(n,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),o=Date.now();return a.experimental.time_to_measure_ms=o-t,this._exporter.addReport(a),Pe(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(a),a}catch(t){return dr(this._moduleName,`got error ${t}`),null}}async start(){Pe(this._moduleName,"starting"),this.state=gs.RUNNING,this._startedTime=this._exporter.start(),Pe(this._moduleName,"started")}async mute(){this.state=gs.MUTED,Pe(this._moduleName,"muted")}async unmute(){this.state=gs.RUNNING,Pe(this._moduleName,"unmuted")}async stop(t){if(Pe(this._moduleName,`stopping${t?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=gs.IDLE,this._config.ticket){const{ticket:n}=this._exporter;this.fireOnTicket(n)}this._exporter.reset(),Pe(this._moduleName,"stopped")}registerCallback(t,n,a){t in this._callbacks?(this._callbacks[t]={callback:n,context:a},Pe(this._moduleName,`registered callback '${t}'`)):dr(this._moduleName,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],Pe(this._moduleName,`unregistered callback '${t}'`)):dr(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReport(t){this._callbacks.onreport&&wu(this._callbacks.onreport.callback,this._callbacks.onreport.context,t)}fireOnTicket(t){this._callbacks.onticket&&wu(this._callbacks.onticket.callback,this._callbacks.onticket.context,t)}updateConfig(t){this._config=t,this._exporter.updateConfig(t)}get state(){return this._state}set state(t){this._state=t,Pe(this._moduleName,`state changed to ${t}`)}addCustomEvent(t,n,a,o){this._exporter.addCustomEvent({at:typeof t=="object"?t.toJSON():t,category:n,name:a,description:o})}async registerToPCEvents(){const{pc:t}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const n=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${n.length} devices found`,"Media Devices state")}catch{dr(this._moduleName,"can't get devices")}},t){t.oniceconnectionstatechange=()=>{const a=t.iceConnectionState;a===Ki.CONNECTED||a===Ki.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===Ki.DISCONNECTED||a===Ki.FAILED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===Ki.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},t.onicegatheringstatechange=()=>{const a=t.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",a,"ICE gathering state")},t.ontrack=a=>{this.addCustomEvent(new Date().toJSON(),"call",`${a.track.kind}track`,"MediaStreamTrack received")},t.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const n=t.getReceivers();if(n&&n.length>0){const a=n[0],{transport:o}=a;if(o){const{iceTransport:s}=o;s&&(s.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class sE{constructor(t){this._id=t.pname&&t.pname.substr(0,12).padEnd(12," ")||Dv(),this._moduleName=this._id,Rn(this._moduleName,"probe created"),this._config=t,this._collector=new tE(this._config,this._id)}set onreport(t){t?this._collector.registerCallback("onreport",t):this._collector.unregisterCallback("onreport")}set onticket(t){t?this._collector.registerCallback("onticket",t):this._collector.unregisterCallback("onticket")}get id(){return this._id}get pname(){return this._config.pname}get cid(){return this._config.cid}get uid(){return this._config.uid}get state(){return this._collector.state}set state(t){this._collector.state=t}addCustomEvent(t,n,a,o=new Date().toJSON()){this._collector.addCustomEvent(o,n,t,a)}get isRunning(){return this._collector.state===gs.RUNNING}get isIdle(){return this._collector.state===gs.IDLE}updateUserId(t){this._config.uid=t,this._collector.updateConfig(this._config)}updateCallId(t){this._config.cid=t,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){wa(this._moduleName,"probe is already running");return}this._collector.start()}stop(t=!1){this.isRunning&&this._collector.stop(t)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const Rt="engine ";class nE{constructor(t){this._config=t,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},Rn(Rt,`configured for probing every ${this._config.refreshEvery}ms`),Rn(Rt,`configured for starting after ${this._config.startAfter}ms`),Rn(Rt,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Pe(Rt,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(t=>t.isRunning)}get isIdle(){return this._probes.every(t=>t.isIdle)}addNewProbe(t,n){if(!t)throw new Error("undefined peer connection");const a=wv(t,n,this._config),o=new sE(a);return this._probes.push(o),Pe(Rt,`${this._probes.length} probes registered`),o}removeExistingProbe(t){if(!t)throw new Error("undefined probe");t.state===gs.RUNNING&&t.stop(),this._probes=this._probes.filter(n=>t.id!==n.id)}async start(){const t=()=>{this._probes.forEach(s=>s.start())},n=async()=>Promise.all(this._probes.map(s=>s.takeReferenceStats())),a=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,o=async()=>{const s=Rv(),r=this._probes.filter(d=>d.isRunning);for(const d of r){const h=await d.collectStats();h&&s.probes.push(h),Pe(Rt,`got probe ${d.id}`),await kf(0)}return s.delta_time_to_measure_probes_ms=Sn(s.probes,"experimental","time_to_measure_ms"),s.delta_KBytes_in=Sn(s.probes,"data","delta_KBytes_in"),s.delta_KBytes_out=Sn(s.probes,"data","delta_KBytes_out"),s.delta_kbs_in=Sn(s.probes,"data","delta_kbs_in"),s.delta_kbs_out=Sn(s.probes,"data","delta_kbs_out"),s.total_time_decoded_in=Sn(s.probes,"video","total_time_decoded_in"),s.total_time_encoded_out=Sn(s.probes,"video","total_time_encoded_out"),s};for(Pe(Rt,"starting to collect"),t(),Pe(Rt,"generating reference reports..."),await n(),Pe(Rt,"reference reports generated"),this._startedTime=Date.now();a();)if(Pe(Rt,`wait ${this._config.refreshEvery}ms before collecting`),await kf(this._config.refreshEvery),a()){Pe(Rt,"collecting...");const s=Date.now(),r=await o(),d=Date.now();r.delta_time_consumed_to_measure_ms=d-s,this.fireOnReports(r),Pe(Rt,"collected")}Pe(Rt,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(t){const n=a=>{this._probes.forEach(o=>{o.stop(a)})};Rn(Rt,"stop collecting"),n(t)}registerCallback(t,n,a){t in this._callbacks?(this._callbacks[t]={callback:n,context:a},Pe(Rt,`registered callback '${t}'`)):dr(Rt,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],Pe(this._moduleName,`unregistered callback '${t}'`)):dr(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReports(t){this._callbacks.onresult&&t.probes.length>0&&wu(this._callbacks.onresult.callback,this._callbacks.onresult.context,t)}}const rE="interface ";class iE{constructor(t){this._config=Ov(t),Rn(rE,`welcome to ${this._config.name} version ${this._config.version}`),gv(this._config.verbose||!1),this._engine=new nE(this._config)}setupLogLevel(t){Tv(t)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(t,n){return this._engine.addNewProbe(t,n)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(t){this._engine.removeExistingProbe(t)}set onresult(t){t?this._engine.registerCallback("onresult",t):this._engine.unregisterCallback("onresult")}}function lE(c,t){return Object.keys(c).filter(n=>t.includes(n)).reduce((n,a)=>{const o=a;return{...n,[o]:c[o]}},{})}const aE=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"];class oE{constructor(t){this.intervals={},this.emitInterval=t.emitInterval||200,this.onChangeFunction=t.onChangeFunction}start(t,n){t&&t.getTracks().length&&requestAnimationFrame(()=>this.beginCalculation(t,n))}stop(t){this.clearVolumeInterval(t)}clearVolumeInterval(t){clearInterval(this.intervals[t]),delete this.intervals[t]}clearAllIntervals(){Object.keys(this.intervals).forEach(t=>{clearInterval(this.intervals[t])}),this.intervals={}}beginCalculation(t,n){this.clearVolumeInterval(n);const a=Cn.createAnalyser(),o=Cn.createMediaStreamSource(t),s=Cn.createScriptProcessor(2048,1,1);a.smoothingTimeConstant=.8,a.fftSize=1024,o.connect(a),a.connect(s),s.connect(Cn.destination),this.intervals[n]=setInterval(()=>{const r=new Uint8Array(a.frequencyBinCount);a.getByteFrequencyData(r);let d=0;const h=r.length;for(let g=0;g<h;g++)d+=r[g];const _=d/h;this.onChangeFunction(n,_)},this.emitInterval)}}const _a={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},uE=0;class cE{constructor(t){this.isAutoAnswer=!1,this.muteWhenJoinEnabled=!1,this.isDNDEnabled=!1,this.muted=!1,this.microphoneInputLevelValue=1,this.speakerVolumeValue=1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.availableMediaDevices=[],this.selectedMediaDevices={input:"default",output:"default"},this.callStatus={},this.callTime={},this.callMetrics={},this.timeIntervals={},this.metricConfig={refreshEvery:1e3},this.activeStreamValue=null,this.initialStreamValue=null,this.context=t,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new oE({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices()}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(t){this.currentActiveRoomIdValue=t,this.context.emit("currentActiveRoomChanged",t)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(t){this.isCallAddingInProgress=t,this.context.emit("callAddingInProgressChanged",t)}get muteWhenJoin(){return this.muteWhenJoinEnabled}get isDND(){return this.isDNDEnabled}get speakerVolume(){return this.speakerVolumeValue}get microphoneInputLevel(){return this.microphoneInputLevelValue}get getActiveCalls(){return this.activeCalls}get hasActiveCalls(){return Object.values(this.extendedCalls).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audiooutput")}get getUserMediaConstraints(){return wh()?{video:!1,audio:!0}:{audio:{deviceId:{exact:this.selectedMediaDevices.input}},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(t){this.availableMediaDevices=t,this.context.emit("changeAvailableDeviceList",t)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const t=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(t)}async initializeMediaDevices(){const t=localStorage.getItem(_a.SELECTED_INPUT_DEVICE)||"default",n=localStorage.getItem(_a.SELECTED_OUTPUT_DEVICE)||"default";try{const a=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),o=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(o),await this.setMicrophone(t),await this.setSpeaker(n),navigator.mediaDevices.addEventListener("devicechange",async()=>{const s=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(s)}),a.getTracks().forEach(s=>s.stop())}catch(a){console.error(a)}}setCallTime(t){const n={...t};delete n.callId,this.callTime={...this.callTime,[t.callId]:n},this.context.emit("changeCallTime",this.callTime)}removeCallTime(t){const n={...this.callTime};delete n[t],this.callTime={...n},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(t,n){this.timeIntervals={...this.timeIntervals,[t]:n}}removeTimeInterval(t){const n={...this.timeIntervals};n[t]&&(clearInterval(n[t]),delete n[t],this.timeIntervals={...n})}stopCallTimer(t){this.removeTimeInterval(t),this.removeCallTime(t)}emitVolumeChange(t,n){this.context.emit("changeCallVolume",{callId:t,volume:n})}setMetricsConfig(t){this.metricConfig={...this.metricConfig,...t}}sendDTMF(t,n){if(!/^[A-D0-9]+$/g.test(n))throw new Error("Not allowed character in DTMF input");this.extendedCalls[t].sendDTMF(n)}setIsMuted(t){this.muted=t,this.context.emit("changeIsMuted",t)}processMute(t){const n=this.currentActiveRoomId;this.setIsMuted(t),this.initialStreamValue.getTracks().forEach(a=>a.enabled=!t),this.roomReconfigure(n)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:t,toHold:n,automatic:a}){const o=this.extendedCalls[t];o._automaticHold=a??!1,await new Promise(d=>{const h=()=>{o.putOnHoldTimestamp=n?Date.now():void 0,d()};n?o.hold({},h):o.unhold({},h)}),this.updateCall(o);const r=Object.values(this.extendedCalls).filter(d=>d.roomId===this.currentActiveRoomId&&(n?t!==d._id:!0));r.length>1&&await this.doConference(r)}holdCall(t,n=!1){return this.processHold({callId:t,automatic:n,toHold:!0})}unholdCall(t){return this.processHold({callId:t,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(t=>t.direction==="outgoing"&&t.status===uE).forEach(t=>this.terminateCall(t._id))}answerCall(t){const n=this.extendedCalls[t];this.cancelAllOutgoingUnanswered(),n.answer(this.sipOptions),this.updateCall(n),this.setActiveRoom(n.roomId),n.connection.addEventListener("track",a=>{this.triggerAddStream(a,n)})}async moveCall(t,n){this.updateCallStatus({callId:t,isMoving:!0}),await this.processRoomChange({callId:t,roomId:n}),this.updateCallStatus({callId:t,isMoving:!1})}updateCall(t){this.activeCalls[t._id]=Nf(t),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(t){const a={...this.activeRooms[t.roomId],...t};this.activeRooms={...this.activeRooms,[t.roomId]:{...a}},this.context.emit("updateRoom",{room:a,roomList:this.activeRooms})}hasAutoAnswerHeaders(t){const n=/answer-after=0/,o=t.request.getHeader("Call-Info");return o&&n.test(o)}addCall(t,n=!0){this.activeCalls={...this.activeCalls,[t._id]:Nf(t)},this.extendedCalls[t._id]=t,n&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(t){this.callStatus={...this.callStatus,[t]:{isMoving:!1,isTransferring:!1,isMerging:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(t){const a={...{...this.callStatus[t.callId]}};t.isMoving!==void 0&&(a.isMoving=t.isMoving),t.isTransferring!==void 0&&(a.isTransferring=t.isTransferring),t.isMerging!==void 0&&(a.isMerging=t.isMerging),this.callStatus={...this.callStatus,[t.callId]:{...a}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(t){const n={...this.callStatus};delete n[t],this.callStatus={...n},this.context.emit("changeCallStatus",this.callStatus)}addRoom(t){this.activeRooms={...this.activeRooms,[t.roomId]:t},this.context.emit("addRoom",{room:t,roomList:this.activeRooms})}getActiveStream(){const t=Pf(this.initialStreamValue,this.microphoneInputLevel*2);return t.getTracks().forEach(n=>n.enabled=!this.isMuted),this.setActiveStream(t),t}async setMicrophone(t){if(!this.getInputDeviceList.find(({deviceId:a})=>a===t)||(this.setSelectedInputDevice(t),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const n=Object.values(this.extendedCalls).filter(a=>a.roomId===this.currentActiveRoomId);n.length===1?Object.values(n).forEach(async a=>{const o=this.getActiveStream();a.connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.updateCall(a)}):await this.doConference(n)}setActiveStream(t){this.activeStream&&this.stopVUMeter("origin"),this.setupVUMeter(t,"origin"),this.activeStreamValue=t,this.context.emit("changeActiveStream",t)}async setSpeaker(t){if(!this.getOutputDeviceList.find(({deviceId:o})=>o===t))return;this.setSelectedOutputDevice(t);const n=Object.values(this.extendedCalls);if(n.length===0)return;const a=n.filter(o=>o.roomId===this.currentActiveRoomId);a.length===1?n.forEach(o=>{var s;(s=o.audioTag)==null||s.setSinkId(t),this.updateCall(o)}):await this.doConference(a)}removeRoom(t){const n={...this.activeRooms},a={...n[t]};delete n[t],this.activeRooms={...n},this.context.emit("removeRoom",{room:a,roomList:this.activeRooms})}deleteRoomIfEmpty(t){t!==void 0&&Object.values(this.extendedCalls).filter(n=>n.roomId===t).length===0&&(this.removeRoom(t),this.currentActiveRoomId===t&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(t){this.muted?t.mute({audio:!0}):t.unmute({audio:!0})}async roomReconfigure(t){var a;if(t===void 0)return;const n=Object.values(this.extendedCalls).filter(o=>o.roomId===t);if(this.currentActiveRoomId===t?n.forEach(o=>{o.audioTag&&(this.muteReconfigure(o),o.audioTag.muted=!1,this.updateCall(o))}):n.forEach(o=>{o.audioTag&&(o.audioTag.muted=!0,this.updateCall(o))}),n.length===0)this.deleteRoomIfEmpty(t);else if(n.length===1&&this.currentActiveRoomId!==t)n[0].isOnHold().local||await this.holdCall(n[0].id,!0);else if(n.length===1&&this.currentActiveRoomId===t){if(n[0].isOnHold().local&&n[0]._automaticHold&&await this.unholdCall(n[0].id),n[0].connection&&((a=n[0].connection)!=null&&a.getSenders()[0])){const o=this.getActiveStream();await n[0].connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.muteReconfigure(n[0])}}else n.length>1&&await this.doConference(n)}async doConference(t){const n=[];t.forEach(a=>{a!=null&&a.connection.getReceivers().forEach(o=>{n.push(o.track)})}),await pv.forEach(t,async a=>{var r;if(a==null)return;const o=new MediaStream,s=Cn.createMediaStreamDestination();if(a.connection.getReceivers().forEach(d=>{n.forEach(h=>{o.addTrack(d.track),d.track.id!==h.id&&Cn.createMediaStreamSource(new MediaStream([h])).connect(s)})}),t[0].roomId===this.currentActiveRoomId){const d=this.getActiveStream();Cn.createMediaStreamSource(d).connect(s)}(r=a.connection)!=null&&r.getSenders()[0]&&(await a.connection.getSenders()[0].replaceTrack(s.stream.getTracks()[0]),this.muteReconfigure(a))})}processCallerMute(t,n){const a=this.extendedCalls[t];a&&a.connection.getReceivers().length&&(a.localMuted=n,a.connection.getReceivers().forEach(o=>{o.track.enabled=!n}),this.updateCall(a))}muteCaller(t){this.processCallerMute(t,!0)}unmuteCaller(t){this.processCallerMute(t,!1)}terminateCall(t){const n=this.extendedCalls[t];n._status!==8&&n.terminate()}transferCall(t,n){if(n.toString().length===0)return new Error("Target must be passed");const a=this.extendedCalls[t];if(!a._is_confirmed&&!a._is_canceled){const o=`sip:${n}@${this.context.sipDomain}`;a.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${o}`]});return}this.updateCallStatus({callId:t,isTransferring:!0}),a.refer(`sip:${n}@${this.context.sipDomain}`),this.updateCall(a)}mergeCall(t){const n=Object.values(this.extendedCalls).filter(s=>s.roomId===t);if(n.length!==2)return;const a=n[0],o=n[1];!a||!o||(this.updateCallStatus({callId:a._id,isMerging:!0}),this.updateCallStatus({callId:o._id,isMerging:!0}),a.refer(o.remote_identity.uri.toString(),{replaces:o}),this.updateCall(a))}mergeCallByIds(t,n){const a=Object.values(this.extendedCalls).find(s=>s._id===t),o=Object.values(this.extendedCalls).find(s=>s._id===n);if(!a||!o)throw new Error("Call ID is not provided");this.updateCallStatus({callId:t,isMerging:!0}),this.updateCallStatus({callId:n,isMerging:!0}),a.refer(o.remote_identity.uri.toString(),{replaces:o}),this.updateCall(a)}setDND(t){this.isDNDEnabled=t,this.context.emit("changeIsDND",t)}startCallTimer(t){this.removeTimeInterval(t);const n={callId:t,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(n);const a=setInterval(()=>{const o={...this.callTime[t]},s=hv(o);this.setCallTime({callId:t,...s})},1e3);this.setTimeInterval(t,a)}async setActiveRoom(t){const n=this.currentActiveRoomId;t!==n&&(this.currentActiveRoomId=t,await this.roomReconfigure(n),await this.roomReconfigure(t))}getNewRoomId(){const t=Object.keys(this.activeRooms);return t.length===0?1:parseInt(t.sort()[t.length-1])+1}async setupCall(t){var _,g;const n=t.session;if(this.getActiveCalls[n.id]!==void 0)return;const o=this.getNewRoomId(),s={started:new Date,incomingInProgress:!1,roomId:o};n.direction==="incoming"?(this.context.logger.log("New incoming call from",(g=(_=n._remote_identity)==null?void 0:_._uri)==null?void 0:g._user),s.incomingInProgress=!0,this.context.subscribe(Xt.CALL_CONFIRMED,T=>{n.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:o}),this.startCallTimer(n.id))}),this.context.subscribe(Xt.CALL_FAILED,T=>{n.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:o}),this.deleteRoomIfEmpty(o))})):n.direction==="outgoing"&&(n.once("confirmed",()=>{this.startCallTimer(n.id)}),this.startCallTimer(n.id));const r=n,d=this.hasAutoAnswerHeaders(t),h=r.direction==="incoming"&&!this.hasActiveCalls&&(d||this.autoAnswer);r.roomId=o,r.localMuted=!1,r.autoAnswer=h,h?this.addCall(r,!1):this.addCall(r),this.addCallStatus(n.id),this.addRoom(s),h&&this.answerCall(r._id)}removeCall(t){const n={...this.activeCalls};delete n[t],this.activeCalls={...n};const a={...this.extendedCalls};delete a[t],this.extendedCalls={...a},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(t){var o;const n=this.extendedCalls[t._id];this.stopVUMeter("origin"),(o=n.connection)==null||o.getSenders().forEach(s=>{s.track.stop()});const a=n.roomId;this.removeCall(t._id),this.roomReconfigure(a)}async newRTCSessionCallback(t){const n=t.session;if(this.isDND){n.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(this.context.triggerListener({listenerType:Xt.NEW_CALL,session:n,event:t}),n.on("ended",a=>{var s,r,d;this.stopVUMeter(n.id),this.context.logger.log("Session ended for",(r=(s=n._remote_identity)==null?void 0:s._uri)==null?void 0:r._user),this.context.triggerListener({listenerType:Xt.CALL_ENDED,session:n,event:a});const o=this.getActiveCalls[n.id];o&&this.activeCallListRemove(o),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null)}),n.on("progress",a=>{var o,s;this.context.logger.log("Session in progress for",(s=(o=n._remote_identity)==null?void 0:o._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:Xt.CALL_PROGRESS,session:n,event:a})}),n.on("failed",a=>{var s,r,d;this.stopVUMeter(n.id),this.context.logger.log("Session failed for",(r=(s=n._remote_identity)==null?void 0:s._uri)==null?void 0:r._user),this.context.triggerListener({listenerType:Xt.CALL_FAILED,session:n,event:a}),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const o=this.getActiveCalls[n.id];o&&this.activeCallListRemove(o),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null)}),n.on("confirmed",a=>{var o,s;this.context.logger.log("Session confirmed for",(s=(o=n._remote_identity)==null?void 0:o._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:Xt.CALL_CONFIRMED,session:n,event:a}),this.updateCall(n),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(t),n.direction==="outgoing"){const a=this.getActiveCalls[n.id].roomId;this.setActiveRoom(a)}}setMuteWhenJoin(t){this.muteWhenJoinEnabled=t,this.context.emit("changeMuteWhenJoin",t)}setMicrophoneSensitivity(t){if(t<0||t>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=t,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(t){this.speakerVolumeValue=t,Object.values(this.extendedCalls).forEach(n=>{n.audioTag&&(n.audioTag.volume=t,this.updateCall(n))})}setAutoAnswer(t){this.isAutoAnswer=t}setSelectedInputDevice(t){localStorage.setItem(_a.SELECTED_INPUT_DEVICE,t),this.selectedMediaDevices.input=t,this.context.emit("changeActiveInputMediaDevice",t)}setSelectedOutputDevice(t){localStorage.setItem(_a.SELECTED_OUTPUT_DEVICE,t),this.selectedMediaDevices.output=t,this.context.emit("changeActiveOutputMediaDevice",t)}setCallMetrics(t){const n={...t};delete n.callId,this.callMetrics={...this.callMetrics,[t.callId]:n},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(t){const n={...this.callMetrics};delete n[t],this.callMetrics={...n},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(t){const n=new iE(this.metricConfig),a=n.createProbe(t.connection,{cid:t._id}),o=[];let s;a.onreport=r=>{Object.entries(r.audio).forEach(([_,g])=>{g.direction==="inbound"&&!o.includes(_)&&(o.push(_),s=_)});const d=r.audio[s];if(!d)return;const h=lE(d,aE);h.callId=t._id,this.setCallMetrics(h)},this.context.subscribe(Xt.CALL_ENDED,r=>{r._id===t._id&&n.stopAllProbes()}),n.startAllProbes()}setupVUMeter(t,n){this.VUMeter.start(t,n)}stopVUMeter(t){this.VUMeter.stop(t)}async setupStream(){const t=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach(n=>n.stop()),this.initialStreamValue=null),this.initialStreamValue=t}async triggerAddStream(t,n){this.setIsMuted(this.muteWhenJoin||this.isMuted),this.initialStreamValue||await this.setupStream();const a=Pf(this.initialStreamValue,this.microphoneInputLevel*2),o=this.isMuted||this.muteWhenJoin;a.getTracks().forEach(r=>r.enabled=!o),this.setActiveStream(a),await n.connection.getSenders()[0].replaceTrack(a.getTracks()[0]);const s=new MediaStream([t.track]);zT(s,n,this.selectedOutputDevice,this.speakerVolume),this.setupVUMeter(s,n._id),this.getCallQuality(n),this.updateCall(n)}initCall(t,n,a=!1){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`);const o=this.context.call(`sip:${t}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=o.id,n&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:o.id,roomId:this.currentActiveRoomId}),a)){const s=Object.values(this.extendedCalls).filter(r=>r.roomId===this.currentActiveRoomId&&r._id!==o.id);for(const r of s)this.holdCall(r._id,!0)}o.connection.addEventListener("track",s=>{this.triggerAddStream(s,o)})}async processRoomChange({callId:t,roomId:n}){const a=this.extendedCalls[t].roomId;this.extendedCalls[t].roomId=n;const o=this.extendedCalls[t];return this.updateCall(o),await this.setActiveRoom(n),Promise.all([this.roomReconfigure(a),this.roomReconfigure(n)]).then(()=>{this.deleteRoomIfEmpty(a),this.deleteRoomIfEmpty(n)})}}class fE{constructor(t){this.context=t}get sipOptions(){return{...this.context.options.sipOptions}}initCall(t,n){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${t}@${this.context.sipDomain}`,n,this.sipOptions)}stop(t={}){this.context.terminateJanusSessions(t)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(t){this.context.changeMediaConstraints(t)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class hE{constructor(t){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=t,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this.context))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(t){const n=this.extendedMessages[t];this.updateMSRPSession(n)}updateMSRPSession(t){this.activeMessages[t._id]=Uf(t),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(t){this.activeMessages={...this.activeMessages,[t._id]:Uf(t)},this.extendedMessages[t._id]=t,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(t,n){const a=this.msrpHistory[n.id]||[];a.push(t),this.msrpHistory={...this.msrpHistory,[n.id]:[...a]},this.context.emit("newMSRPMessage",{message:t,session:n})}messageTerminate(t){const n=this.extendedMessages[t];n._status!==8&&n.terminate()}addMessageSession(t){if(!t._id||this.getActiveMessages[t._id]!==void 0)return;const a=t;this.addMMSRPSession(a)}triggerMSRPListener({listenerType:t,session:n,event:a}){const o=this.context.listenersList[t];!o||!o.length||o.forEach(s=>{s(n,a)})}removeMMSRPSession(t){const n={...this.activeMessages};delete n[t],this.activeMessages={...n};const a={...this.extendedMessages};delete a[t],this.extendedMessages={...a},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(t){this.removeMMSRPSession(t._id)}newMSRPSessionCallback(t){const n=t.session;n.on("ended",a=>{this.triggerMSRPListener({listenerType:Xt.CALL_ENDED,session:n,event:a});const o=this.getActiveMessages[n.id];this.activeMessageListRemove(o)}),n.on("failed",a=>{this.triggerMSRPListener({listenerType:Xt.CALL_FAILED,session:n,event:a});const o=this.getActiveMessages[n.id];this.activeMessageListRemove(o)}),n.on("confirmed",a=>{this.triggerMSRPListener({listenerType:Xt.CALL_CONFIRMED,session:n,event:a}),this.updateMSRPSession(n)}),n.on("newMessage",a=>{this.addMSRPMessage(a,n)}),this.addMessageSession(n)}setIsMSRPInitializing(t){this.isMSRPInitializingValue=t,this.context.emit("isMSRPInitializingChanged",t)}initMSRP(t,n,a){if(t.length===0)return console.error("Target must be a valid string");const o=this.context.startMSRP(t,a);o.on("active",()=>{this.addMessageSession(o),o.sendMSRP(n),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(t,n){const a=this.extendedMessages[t];if(!a)throw new Error(`MSRP session with id ${t} doesn't exist!`);a.sendMSRP(n)}}const ou={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class kh{constructor(t){this.opensips=null,this.session=null,this.name=null,this.name=t}setOpensips(t){this.opensips=t}setSession(t){this.session=t}kill(){this.opensips.kill(this.name)}}class Mh extends kh{constructor(t,n){super(t),this._candidates=[],this._subscribeSent=!1,this._configureSent=!1,this._lastTrickleReceived=!1,this.type=n}connect(t={}){this.opaqueId=this.session.generateOpaqueId();const n=ke.cloneArray(t.extraHeaders),a={from_tag:this.session._from_tag};t.fromUserName&&(a.from_uri=new In("sip",t.fromUserName,this.session._ua.configuration.uri.host),n.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),t.fromDisplayName&&(a.from_display_name=t.fromDisplayName),n.push(`Contact: ${this.session._contact}`),n.push("Content-Type: application/json"),this.session._sessionTimers.enabled&&n.push(`Session-Expires: ${this.session._sessionTimers.defaultExpires}${this.session._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new yt.InitialOutgoingInviteRequest(this.session.target,this.session._ua,a,n),this._createRTCConnection(),this._sendInitialRequest()}getStream(){return this.stream}getConnection(){return this._connection}_createRTCConnection(){this._connection=new RTCPeerConnection({iceServers:[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}]});let t;this._connection.onicecandidate=n=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||n.candidate&&(this._candidates.push(n.candidate),clearTimeout(t),t=setTimeout(()=>{this._lastTrickleReceived=!0,this._subscribeSent&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})},500))}}addTracks(t){t.forEach(n=>{this._connection.addTrack(n)})}async _sendInitialRequest(){const t=new sl(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});if(await this.generateStream(),!this.stream||!this.stream.getTracks().length)return;this.addTracks(this.stream.getTracks());const n={audio:!1,video:!0};this.jsep_offer=await this._connection.createOffer(n),await this._connection.setLocalDescription(this.jsep_offer);const a={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},o=JSON.stringify(a);this._request.body=o,t.send()}_receiveInviteResponse(t){if(this._publisherSubscribeSent||!t.body)return;const n=JSON.parse(t.body);this.handleId=n.data.id;const a={janus:"message",body:{request:"join",room:this.session.room_id,ptype:"publisher",display:this.session.display_name+" (Screen Share)",opaque_id:this.opaqueId},handle_id:this.handleId},o=[this.session.getPTypeHeader(Pt.PUBLISHER)];this.session.sendRequest(L.SUBSCRIBE,{extraHeaders:o,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async s=>{var r,d,h,_;if(s.status_code===200){if(this._subscribeSent=!0,s.body)try{const g=JSON.parse(s.body)||{};((d=(r=g.plugindata)==null?void 0:r.data)==null?void 0:d.videoroom)==="joined"&&this.session.myFeedList.push(g.plugindata.data.id),(_=(h=g.plugindata)==null?void 0:h.data)!=null&&_.publishers&&this.session.receivePublishers(g)}catch(g){console.error(g)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}}}}),this._publisherSubscribeSent=!0}async _sendConfigureMessage(t){const n=this._candidates.map(r=>({janus:"trickle",candidate:r,handle_id:this.handleId,session_id:this.session.session_id})),o={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.session.getRecordFileName(),...t},jsep:this.jsep_offer,handle_id:this.handleId,session_id:this.session.session_id},trickles:[...n]},s=["Content-Type: application/json",this.session.getPTypeHeader(Pt.ICE)];this.session.sendRequest(L.INFO,{extraHeaders:s,body:JSON.stringify(o),eventHandlers:{onSuccessResponse:async r=>{this._configureSent=!0;const h=r.data.split(`\r
|
158
|
+
`,n),o===-1)return o;!c.substring(o+2,o+4).match(/(^\r\n)/)&&c.charAt(o+2).match(/(^\s+)/)?n=o+2:a=o}return a}function HT(c,t,n,a){let o;const s=t.indexOf(":",n),r=t.substring(n,s).trim(),d=t.substring(s+1,a).trim();switch(r.toLowerCase()){case"via":case"v":c.addHeader("via",d),c.getHeaders("via").length===1?(o=c.parseHeader("Via"),o&&(c.via=o,c.via_branch=o.branch)):o=0;break;case"from":case"f":c.setHeader("from",d),o=c.parseHeader("from"),o&&(c.from=o,c.from_tag=o.getParam("tag"));break;case"to":case"t":c.setHeader("to",d),o=c.parseHeader("to"),o&&(c.to=o,c.to_tag=o.getParam("tag"));break;case"record-route":if(o=Iu.parse(d,"Record_Route"),o===-1)o=void 0;else for(const h of o)c.addHeader("record-route",d.substring(h.possition,h.offset)),c.headers["Record-Route"][c.getHeaders("record-route").length-1].parsed=h.parsed;break;case"call-id":case"i":c.setHeader("call-id",d),o=c.parseHeader("call-id"),o&&(c.call_id=d);break;case"contact":case"m":if(o=Iu.parse(d,"Contact"),o===-1)o=void 0;else for(const h of o)c.addHeader("contact",d.substring(h.possition,h.offset)),c.headers.Contact[c.getHeaders("contact").length-1].parsed=h.parsed;break;case"content-length":case"l":c.setHeader("content-length",d),o=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",d),o=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",d),o=c.parseHeader("cseq"),o&&(c.cseq=o.value),c instanceof pr.IncomingResponse&&(c.method=o.method);break;case"max-forwards":c.setHeader("max-forwards",d),o=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",d),o=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",d),o=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",d),o=c.parseHeader("session-expires"),o&&(c.session_expires=o.expires,c.session_expires_refresher=o.refresher);break;case"refer-to":case"r":c.setHeader("refer-to",d),o=c.parseHeader("refer-to"),o&&(c.refer_to=o);break;case"replaces":c.setHeader("replaces",d),o=c.parseHeader("replaces"),o&&(c.replaces=o);break;case"event":case"o":c.setHeader("event",d),o=c.parseHeader("event"),o&&(c.event=o);break;default:c.addHeader(r,d),o=0}return o===void 0?{error:`error parsing header "${r}"`}:!0}const FT={parseMessage:LT},Wi=new Ga("Registrator"),ha=10;class jT{constructor(t,n){this._reg_id=1,this._ua=t,this._transport=n,this._registrar=t.configuration.registrar_server,this._expires=t.configuration.register_expires,this._call_id=Ts.createRandomToken(22),this._cseq=0,this._to_uri=t.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const a=this._contact.indexOf(">");if(a!==-1){const o=this._contact.slice(0,a)+this._contact.slice(a+1,this._contact.length);this._contact=o}this._extra_contact="",this._extraContactParams="",this._extra_contact+=";+sip.ice",this._extraHeaders=[],this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._extra_contact+=`;reg-id=${this._reg_id}`,this._extra_contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(t){Array.isArray(t)||(t=[]),this._extraHeaders=t.slice()}setExtraContactParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const a=t[n];this._extraContactParams+=`;${n}`,a&&(this._extraContactParams+=`=${a}`)}}setExtraContactUriParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const a=t[n];this._extraContactParams+=`;${n}`,a&&(this._extraContactParams+=`=${a}`)}}register(){if(this._registering){Wi.debug("Register request in progress...");return}const t=this._extraHeaders.slice();t.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),t.push(`Expires: ${this._expires}`);const n=new yt.OutgoingRequest(L.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t),a=new sl(this._ua,n,{onRequestTimeout:()=>{this._registrationFailure(null,L.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,L.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:o=>{if(o.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(o.status_code):break;case/^2[0-9]{2}$/.test(o.status_code):{if(this._registering=!1,!o.hasHeader("Contact")){Wi.debug("no Contact header in response to REGISTER, response ignored");break}const s=o.headers.Contact.reduce((_,g)=>_.concat(g.parsed),[]);let r=s.find(_=>this._sipInstance===_.getParam("+sip.instance")&&this._reg_id===parseInt(_.getParam("reg-id")));if(r||(r=s.find(_=>_.uri.user===this._ua.contact.uri.user)),!r){Wi.debug("no Contact header pointing to us, response ignored");break}let d=r.getParam("expires");!d&&o.hasHeader("expires")&&(d=o.getHeader("expires")),d||(d=this._expires),d=Number(d),d<ha&&(d=ha);const h=d>64?d*1e3/2+Math.floor((d/2-32)*1e3*Math.random()):d*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},h),r.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=r.getParam("temp-gruu").replace(/"/g,"")),r.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=r.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:o}));break}case/^423$/.test(o.status_code):{o.hasHeader("min-expires")?(this._expires=Number(o.getHeader("min-expires")),this._expires<ha&&(this._expires=ha),this.register()):(Wi.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(o,L.causes.SIP_FAILURE_CODE));break}default:{const s=Ts.sipErrorCause(o.status_code);this._registrationFailure(o,s)}}}});this._registering=!0,a.send()}unregister(t={}){if(!this._registered){Wi.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const n=this._extraHeaders.slice();t.all?n.push(`Contact: *${this._extraContactParams}`):n.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),n.push("Expires: 0");const a=new yt.OutgoingRequest(L.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n);new sl(this._ua,a,{onRequestTimeout:()=>{this._unregistered(null,L.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,L.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:s=>{switch(!0){case/^1[0-9]{2}$/.test(s.status_code):break;case/^2[0-9]{2}$/.test(s.status_code):this._unregistered(s);break;default:{const r=Ts.sipErrorCause(s.status_code);this._unregistered(s,r)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(t,n){this._registering=!1,this._ua.registrationFailed({response:t||null,cause:n}),this._registered&&(this._registered=!1,this._ua.unregistered({response:t||null,cause:n}))}_unregistered(t,n){this._registering=!1,this._registered=!1,this._ua.unregistered({response:t||null,cause:n||null})}}const tt=console,Vs={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},qT=wT;class VT extends qT{constructor(t){super(t),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this.newStreamPlugins=[],this.processStreamPlugins=[],this._registrator=new jT(this)}call(t,n){return super.call(t,n)}joinVideoCall(t,n,a){tt.debug("call()");const o=new $a(this);return o.configureMedia({audio:!0,video:!0}),o.connect(t,n,a),o}startScreenShare(){tt.debug("startScreenShare()");for(const t in this._janus_sessions)this._janus_sessions[t].connectScreenShare()}changeMediaConstraints(t){for(const n in this._janus_sessions)this._janus_sessions[n].changeMediaConstraints(t)}startBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].connectBlur()}stopBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].stopBlur()}_loadConfig(t){try{rl.load(this._configuration,t)}catch(s){throw s}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=Ts.newUUID());let n;typeof window<"u"&&typeof window.document<"u"?n=window==null?void 0:window.navigator.userAgent:typeof self<"u"&&self.navigator&&(n=self.navigator.userAgent),n+=" "+De.USER_AGENT,this._configuration.user_agent=t.overrideUserAgent&&typeof t.overrideUserAgent=="function"?t.overrideUserAgent(n):n,this._configuration.jssip_id=Ts.createRandomToken(5);const a=this._configuration.uri.clone();a.user=null,this._configuration.hostport_params=a.toString().replace(/^sip:/i,"");try{this._transport=new eT(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=BT.bind(this),this._transport.onconnect=GT.bind(this),this._transport.ondisconnect=WT.bind(this),this._transport.ondata=KT.bind(this)}catch(s){throw tt.warn(s),new qs.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const s=this._configuration.uri.clone();s.user=null,s.clearParams(),s.clearHeaders(),this._configuration.registrar_server=s}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new In("sip",Ts.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(s={}){const r=s.anonymous||null,d=s.outbound||null;let h="<";return r?h+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":h+=this.pub_gruu||this.uri.toString(),d&&(r?!this.temp_gruu:!this.pub_gruu)&&(h+=";ob"),h+=">",h}};const o=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const s in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,s)&&(o.indexOf(s)!==-1?Object.defineProperty(this._configuration,s,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,s,{writable:!1,configurable:!1}));tt.debug("configuration parameters after validation:");for(const s in this._configuration)if(Object.prototype.hasOwnProperty.call(rl.settings,s))switch(s){case"uri":case"registrar_server":tt.debug(`- ${s}: ${this._configuration[s]}`);break;case"password":case"ha1":case"authorization_jwt":tt.debug(`- ${s}: NOT SHOWN`);break;default:tt.debug(`- ${s}: ${JSON.stringify(this._configuration[s])}`)}}newMSRPSession(t,n){t.on("msgHistoryUpdate",a=>{console.log(a)}),this._msrp_sessions[t.id]=t,this.emit("newMSRPSession",n)}newJanusSession(t,n){this._janus_sessions[t.id]=t,this.newStreamPlugins.forEach(a=>{a.setSession(t)}),this.processStreamPlugins.forEach(a=>{a.setSession(t)}),this.emit("newJanusSession",n)}kill(){}destroyMSRPSession(t){delete this._msrp_sessions[t.id]}destroyJanusSession(t){delete this._janus_sessions[t.id]}receiveRequest(t){var s,r,d,h;const n=t.method;if(t.ruri.user!==this._configuration.uri.user&&t.ruri.user!==this._contact.uri.user){tt.debug("Request-URI does not point to us"),t.method!==De.ACK&&t.reply_sl(404);return}if(t.ruri.scheme===De.SIPS){t.reply_sl(416);return}if(Gt.checkTransaction(this,t))return;if(n===De.INVITE?new Gt.InviteServerTransaction(this,this._transport,t):n!==De.ACK&&n!==De.CANCEL&&new Gt.NonInviteServerTransaction(this,this._transport,t),n===De.OPTIONS){if(this.listeners("newOptions").length===0){t.reply(200);return}new Qc.Options(this).init_incoming(t)}else if(n===De.MESSAGE){if(this.listeners("newMessage").length===0){t.reply(405);return}new Qc.Message(this).init_incoming(t)}else if(n===De.INVITE&&!t.to_tag&&this.listeners("newRTCSession").length===0){t.reply(405);return}let a,o;if(t.to_tag)if(a=this._findDialog(t.call_id,t.from_tag,t.to_tag),a)a.receiveRequest(t);else if(n===De.NOTIFY)if(o=this._findSession(t),o)o.receiveRequest(t);else{if(t.body)try{const _=JSON.parse(t.body)||{};(r=(s=_.plugindata)==null?void 0:s.data)!=null&&r.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(_),(h=(d=_.plugindata)==null?void 0:d.data)!=null&&h.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(_.plugindata.data.unpublished)}catch(_){console.error(_)}t.reply(200)}else n!==De.ACK&&t.reply(481);else switch(n){case De.INVITE:if(window.RTCPeerConnection)if(t.hasHeader("replaces")){const _=t.replaces;a=this._findDialog(_.call_id,_.from_tag,_.to_tag),a?(o=a.owner,o.isEnded()?t.reply(603):o.receiveRequest(t)):t.reply(481)}else t.body.search(/MSRP/ig)>-1?(o=new nu(this),o.init_incoming(t)):t.body.search(/JANUS/ig)>-1||(o=new $g(this),o.init_incoming(t));else tt.warn("INVITE received but WebRTC is not supported"),t.reply(488);break;case De.BYE:t.reply(481);break;case De.CANCEL:o=this._findSession(t),o?o.receiveRequest(t):tt.debug("received CANCEL request for a non existent session");break;case De.ACK:break;case De.NOTIFY:this.emit("sipEvent",{event:t.event,request:t}),t.reply(200);break;default:t.reply(405);break}}startMSRP(t,n){tt.debug("startMSRP()",n);const a=new nu(this);return a.connect(t),a}startJanus(t,n){tt.debug("startJanus()",n);const a=new nu(this);return a.connect(t),a}terminateMSRPSessions(t){tt.debug("terminateSessions()");for(const n in this._msrp_sessions)this._msrp_sessions[n].isEnded()||this._msrp_sessions[n].terminate(t)}terminateJanusSessions(t){tt.debug("terminateSessions()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||this._janus_sessions[n].terminate(t)}enableJanusAudio(t){tt.debug("enableJanusAudio()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||(t?this._janus_sessions[n].startAudio():this._janus_sessions[n].stopAudio())}enableJanusVideo(t){tt.debug("enableJanusVideo()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||(t?this._janus_sessions[n].startVideo():this._janus_sessions[n].stopVideo())}stop(){if(tt.debug("stop()"),this._dynConfiguration={},this._status===Vs.STATUS_USER_CLOSED){tt.debug("UA already closed");return}this._registrator.close();const t=Object.keys(this._sessions).length;for(const a in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,a)){tt.debug(`closing session ${a}`);try{this._sessions[a].terminate()}catch(o){console.error(o)}}for(const a in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,a)){tt.debug(`closing session ${a}`);try{this._msrp_sessions[a].terminate()}catch(o){console.error(o)}}for(const a in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,a)){tt.debug(`closing session ${a}`);try{this._janus_sessions[a].terminate()}catch(o){console.error(o)}}for(const a in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,a))try{this._applicants[a].close()}catch(o){console.error(o)}this._status=Vs.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&t===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function BT(c){this.emit("connecting",c)}function GT(c){this._status!==Vs.STATUS_USER_CLOSED&&(this._status=Vs.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function WT(c){const t=["nict","ict","nist","ist"];for(const n of t)for(const a in this._transactions[n])Object.prototype.hasOwnProperty.call(this._transactions[n],a)&&this._transactions[n][a].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==Vs.STATUS_USER_CLOSED&&(this._status=Vs.STATUS_NOT_READY,this._error=Vs.NETWORK_ERROR)}function KT(c){const t=c.transport;let n=c.message;if(n=FT.parseMessage(n,this),!!n&&!(this._status===Vs.STATUS_USER_CLOSED&&n instanceof pr.IncomingRequest)&&pT(n,this,t)){if(n instanceof pr.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof pr.IncomingResponse){let a;switch(n.method){case De.INVITE:a=this._transactions.ict[n.via_branch],a&&a.receiveResponse(n);break;case De.ACK:break;default:a=this._transactions.nict[n.via_branch],a&&a.receiveResponse(n);break}}}}const YT=["roomId","_audioMuted","_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","_localHold","_videoMuted","status","start_time","_remote_identity","audioTag","isOnHold","localMuted","autoAnswer","putOnHoldTimestamp"],JT=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function Nf(c){const t={};return YT.forEach(n=>{c[n]!==void 0&&(t[n]=c[n])}),t.localHold=c._localHold,t}function Uf(c){const t={};return JT.forEach(n=>{c[n]!==void 0&&(t[n]=c[n])}),t}function Pf(c,t){const n=new AudioContext,a=n.createMediaStreamSource(c),o=n.createMediaStreamDestination(),s=n.createGain();return a.connect(s),s.connect(o),s.gain.value=t,o.stream}function zT(c,t,n,a){const o=document.createElement("audio");o.id=t._id,o.className="audioTag",o.srcObject=c,wh()||(o.setSinkId(n),o.volume=a),o.play(),t.audioTag=o}function XT(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}function wh(){return/Mobi|Android|iPhone/i.test(navigator.userAgent)}const QT=ut,ZT=Zt(),Dt=new QT("WebSocketInterface");var ev=class{constructor(t){Dt.debug('new() [url:"%s"]',t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;const n=ZT.parse(t,"absoluteURI");if(n===-1)throw Dt.warn(`invalid WebSocket URI: ${t}`),new TypeError(`Invalid argument: ${t}`);if(n.scheme!=="wss"&&n.scheme!=="ws")throw Dt.warn(`invalid WebSocket URI scheme: ${n.scheme}`),new TypeError(`Invalid argument: ${t}`);this._sip_uri=`sip:${n.host}${n.port?`:${n.port}`:""};transport=ws`,this._via_transport=n.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(t){this._via_transport=t.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Dt.debug("connect()"),this.isConnected()){Dt.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Dt.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Dt.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(t){this._onError(t)}}disconnect(){Dt.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(t){return Dt.debug("send()"),this.isConnected()?(this._ws.send(t),!0):(Dt.warn("unable to send message, WebSocket is not open"),!1)}isConnected(){return this._ws&&this._ws.readyState===this._ws.OPEN}isConnecting(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}_onOpen(){Dt.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:t,code:n,reason:a}){Dt.debug(`WebSocket ${this._url} closed`),t===!1&&Dt.debug("WebSocket abrupt disconnection"),this.ondisconnect(!t,n,a)}_onMessage({data:t}){Dt.debug("received WebSocket message"),this.ondata(t)}_onError(t){Dt.warn(`WebSocket ${this._url} error: `,t)}};const bu=Ha,tv=De,sv=As,nv=At(),rv=bh,iv=ys(),lv=$u(),av=Zt(),ov=ev,uv=gr("JsSIP");uv("version %s",bu.version);var cv={C:tv,Exceptions:sv,Utils:nv,UA:rv,URI:iv,NameAddrHeader:lv,WebSocketInterface:ov,Grammar:av,debug:gr,get name(){return bu.title},get version(){return bu.version}};const fv=ze(cv);function ru(c){return c<10?`0${c}`:`${c}`}function hv(c){let t=c.hours||0,n=c.minutes||0,a=c.seconds||0;a++,a===60&&(a=0,n++,n===60&&(n=0,t++));const o=`${ru(t)}:${ru(n)}:${ru(a)}`;return{seconds:a,minutes:n,hours:t,formatted:o}}var Ct={};Ct.forEach=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)if(o in c){const s=Promise.resolve(c[o]).then(r=>t.call(n||globalThis,r,o,c));a.push(s)}await Promise.all(a)};Ct.forEachSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)a in c&&await t.call(n||globalThis,await c[a],a,c)};Ct.map=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)o in c&&(a[o]=Promise.resolve(c[o]).then(s=>t.call(n||globalThis,s,o,c)));return Promise.all(a)};Ct.mapSeries=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)o in c&&(a[o]=await t.call(n||globalThis,await c[o],o,c));return a};Ct.find=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a();let s=1;for(let r=0;r<c.length;r++){const d=h=>{h?a(c[r]):s===c.length&&a(),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}});Ct.findSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(await t.call(n||globalThis,await c[a],a,c))return c[a]};Ct.findIndex=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a(-1);let s=1;for(let r=0;r<c.length;r++){const d=h=>{h?a(r):s===c.length&&a(-1),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}});Ct.findIndexSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(await t.call(n||globalThis,await c[a],a,c))return a};Ct.some=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a(!1);let s=1;for(let r=0;r<c.length;r++){if(!(r in c)){s++;continue}const d=h=>{h?a(!0):s===c.length&&a(!1),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}});Ct.someSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(a in c&&await t.call(n||globalThis,await c[a],a,c))return!0;return!1};Ct.every=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a(!0);let s=1;for(let r=0;r<c.length;r++){if(!(r in c)){s++;continue}const d=h=>{h?s===c.length&&a(!0):a(!1),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}});Ct.everySeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(a in c&&!await t.call(n||globalThis,await c[a],a,c))return!1;return!0};Ct.filter=(c,t,n)=>new Promise(async(a,o)=>{const s=[];for(let d=0;d<c.length;d++)d in c&&(s[d]=Promise.resolve(c[d]).then(h=>t.call(n||globalThis,h,d,c)).catch(o));const r=[];for(let d=0;d<s.length;d++)await s[d]&&r.push(await c[d]);a(r)});Ct.filterSeries=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)o in c&&await t.call(n||globalThis,await c[o],o,c)&&a.push(await c[o]);return a};Ct.reduce=async(c,t,n)=>{if(c.length===0&&n===void 0)throw TypeError("Reduce of empty array with no initial value");let a,o;for(n!==void 0?(o=n,a=0):(o=c[0],a=1),a;a<c.length;a++)a in c&&(o=await t(await o,await c[a],a,c));return o};var Oh={};(function(c){const t=Ct;Object.keys(t).forEach(n=>{const a=n.charAt(0).toUpperCase()+n.slice(1);c[`async${a}`]=async function(...o){return t[n](this,...o)}})})(Oh);const dv=Ct,_v=Oh;var pv=Object.assign(dv,{instanceMethods:_v});const Cn=new AudioContext,Xt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var mv={exports:{}};(function(c){var t=function(n){var a=Object.prototype,o=a.hasOwnProperty,s=Object.defineProperty||function(ee,W,G){ee[W]=G.value},r,d=typeof Symbol=="function"?Symbol:{},h=d.iterator||"@@iterator",_=d.asyncIterator||"@@asyncIterator",g=d.toStringTag||"@@toStringTag";function T(ee,W,G){return Object.defineProperty(ee,W,{value:G,enumerable:!0,configurable:!0,writable:!0}),ee[W]}try{T({},"")}catch{T=function(W,G,re){return W[G]=re}}function E(ee,W,G,re){var ge=W&&W.prototype instanceof oe?W:oe,be=Object.create(ge.prototype),xe=new P(re||[]);return s(be,"_invoke",{value:J(ee,G,xe)}),be}n.wrap=E;function y(ee,W,G){try{return{type:"normal",arg:ee.call(W,G)}}catch(re){return{type:"throw",arg:re}}}var A="suspendedStart",C="suspendedYield",I="executing",H="completed",$={};function oe(){}function N(){}function j(){}var Se={};T(Se,h,function(){return this});var ve=Object.getPrototypeOf,k=ve&&ve(ve(se([])));k&&k!==a&&o.call(k,h)&&(Se=k);var D=j.prototype=oe.prototype=Object.create(Se);N.prototype=j,s(D,"constructor",{value:j,configurable:!0}),s(j,"constructor",{value:N,configurable:!0}),N.displayName=T(j,g,"GeneratorFunction");function B(ee){["next","throw","return"].forEach(function(W){T(ee,W,function(G){return this._invoke(W,G)})})}n.isGeneratorFunction=function(ee){var W=typeof ee=="function"&&ee.constructor;return W?W===N||(W.displayName||W.name)==="GeneratorFunction":!1},n.mark=function(ee){return Object.setPrototypeOf?Object.setPrototypeOf(ee,j):(ee.__proto__=j,T(ee,g,"GeneratorFunction")),ee.prototype=Object.create(D),ee},n.awrap=function(ee){return{__await:ee}};function V(ee,W){function G(be,xe,Ce,le){var ye=y(ee[be],ee,xe);if(ye.type==="throw")le(ye.arg);else{var nt=ye.arg,at=nt.value;return at&&typeof at=="object"&&o.call(at,"__await")?W.resolve(at.__await).then(function(Ee){G("next",Ee,Ce,le)},function(Ee){G("throw",Ee,Ce,le)}):W.resolve(at).then(function(Ee){nt.value=Ee,Ce(nt)},function(Ee){return G("throw",Ee,Ce,le)})}}var re;function ge(be,xe){function Ce(){return new W(function(le,ye){G(be,xe,le,ye)})}return re=re?re.then(Ce,Ce):Ce()}s(this,"_invoke",{value:ge})}B(V.prototype),T(V.prototype,_,function(){return this}),n.AsyncIterator=V,n.async=function(ee,W,G,re,ge){ge===void 0&&(ge=Promise);var be=new V(E(ee,W,G,re),ge);return n.isGeneratorFunction(W)?be:be.next().then(function(xe){return xe.done?xe.value:be.next()})};function J(ee,W,G){var re=A;return function(be,xe){if(re===I)throw new Error("Generator is already running");if(re===H){if(be==="throw")throw xe;return st()}for(G.method=be,G.arg=xe;;){var Ce=G.delegate;if(Ce){var le=F(Ce,G);if(le){if(le===$)continue;return le}}if(G.method==="next")G.sent=G._sent=G.arg;else if(G.method==="throw"){if(re===A)throw re=H,G.arg;G.dispatchException(G.arg)}else G.method==="return"&&G.abrupt("return",G.arg);re=I;var ye=y(ee,W,G);if(ye.type==="normal"){if(re=G.done?H:C,ye.arg===$)continue;return{value:ye.arg,done:G.done}}else ye.type==="throw"&&(re=H,G.method="throw",G.arg=ye.arg)}}}function F(ee,W){var G=W.method,re=ee.iterator[G];if(re===r)return W.delegate=null,G==="throw"&&ee.iterator.return&&(W.method="return",W.arg=r,F(ee,W),W.method==="throw")||G!=="return"&&(W.method="throw",W.arg=new TypeError("The iterator does not provide a '"+G+"' method")),$;var ge=y(re,ee.iterator,W.arg);if(ge.type==="throw")return W.method="throw",W.arg=ge.arg,W.delegate=null,$;var be=ge.arg;if(!be)return W.method="throw",W.arg=new TypeError("iterator result is not an object"),W.delegate=null,$;if(be.done)W[ee.resultName]=be.value,W.next=ee.nextLoc,W.method!=="return"&&(W.method="next",W.arg=r);else return be;return W.delegate=null,$}B(D),T(D,g,"Generator"),T(D,h,function(){return this}),T(D,"toString",function(){return"[object Generator]"});function X(ee){var W={tryLoc:ee[0]};1 in ee&&(W.catchLoc=ee[1]),2 in ee&&(W.finallyLoc=ee[2],W.afterLoc=ee[3]),this.tryEntries.push(W)}function U(ee){var W=ee.completion||{};W.type="normal",delete W.arg,ee.completion=W}function P(ee){this.tryEntries=[{tryLoc:"root"}],ee.forEach(X,this),this.reset(!0)}n.keys=function(ee){var W=Object(ee),G=[];for(var re in W)G.push(re);return G.reverse(),function ge(){for(;G.length;){var be=G.pop();if(be in W)return ge.value=be,ge.done=!1,ge}return ge.done=!0,ge}};function se(ee){if(ee){var W=ee[h];if(W)return W.call(ee);if(typeof ee.next=="function")return ee;if(!isNaN(ee.length)){var G=-1,re=function ge(){for(;++G<ee.length;)if(o.call(ee,G))return ge.value=ee[G],ge.done=!1,ge;return ge.value=r,ge.done=!0,ge};return re.next=re}}return{next:st}}n.values=se;function st(){return{value:r,done:!0}}return P.prototype={constructor:P,reset:function(ee){if(this.prev=0,this.next=0,this.sent=this._sent=r,this.done=!1,this.delegate=null,this.method="next",this.arg=r,this.tryEntries.forEach(U),!ee)for(var W in this)W.charAt(0)==="t"&&o.call(this,W)&&!isNaN(+W.slice(1))&&(this[W]=r)},stop:function(){this.done=!0;var ee=this.tryEntries[0],W=ee.completion;if(W.type==="throw")throw W.arg;return this.rval},dispatchException:function(ee){if(this.done)throw ee;var W=this;function G(le,ye){return be.type="throw",be.arg=ee,W.next=le,ye&&(W.method="next",W.arg=r),!!ye}for(var re=this.tryEntries.length-1;re>=0;--re){var ge=this.tryEntries[re],be=ge.completion;if(ge.tryLoc==="root")return G("end");if(ge.tryLoc<=this.prev){var xe=o.call(ge,"catchLoc"),Ce=o.call(ge,"finallyLoc");if(xe&&Ce){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0);if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else if(xe){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0)}else if(Ce){if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(ee,W){for(var G=this.tryEntries.length-1;G>=0;--G){var re=this.tryEntries[G];if(re.tryLoc<=this.prev&&o.call(re,"finallyLoc")&&this.prev<re.finallyLoc){var ge=re;break}}ge&&(ee==="break"||ee==="continue")&&ge.tryLoc<=W&&W<=ge.finallyLoc&&(ge=null);var be=ge?ge.completion:{};return be.type=ee,be.arg=W,ge?(this.method="next",this.next=ge.finallyLoc,$):this.complete(be)},complete:function(ee,W){if(ee.type==="throw")throw ee.arg;return ee.type==="break"||ee.type==="continue"?this.next=ee.arg:ee.type==="return"?(this.rval=this.arg=ee.arg,this.method="return",this.next="end"):ee.type==="normal"&&W&&(this.next=W),$},finish:function(ee){for(var W=this.tryEntries.length-1;W>=0;--W){var G=this.tryEntries[W];if(G.finallyLoc===ee)return this.complete(G.completion,G.afterLoc),U(G),$}},catch:function(ee){for(var W=this.tryEntries.length-1;W>=0;--W){var G=this.tryEntries[W];if(G.tryLoc===ee){var re=G.completion;if(re.type==="throw"){var ge=re.arg;U(G)}return ge}}throw new Error("illegal catch attempt")},delegateYield:function(ee,W,G){return this.delegate={iterator:se(ee),resultName:W,nextLoc:G},this.method==="next"&&(this.arg=r),$}},n}(c.exports);try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}})(mv);var Dh={exports:{}};(function(c){(function(t,n){c.exports?c.exports=n():t.log=n()})(jh,function(){var t=function(){},n="undefined",a=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),o=["trace","debug","info","warn","error"];function s(C,I){var H=C[I];if(typeof H.bind=="function")return H.bind(C);try{return Function.prototype.bind.call(H,C)}catch{return function(){return Function.prototype.apply.apply(H,[C,arguments])}}}function r(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function d(C){return C==="debug"&&(C="log"),typeof console===n?!1:C==="trace"&&a?r:console[C]!==void 0?s(console,C):console.log!==void 0?s(console,"log"):t}function h(C,I){for(var H=0;H<o.length;H++){var $=o[H];this[$]=H<C?t:this.methodFactory($,C,I)}this.log=this.debug}function _(C,I,H){return function(){typeof console!==n&&(h.call(this,I,H),this[C].apply(this,arguments))}}function g(C,I,H){return d(C)||_.apply(this,arguments)}function T(C,I,H){var $=this,oe;I=I??"WARN";var N="loglevel";typeof C=="string"?N+=":"+C:typeof C=="symbol"&&(N=void 0);function j(D){var B=(o[D]||"silent").toUpperCase();if(!(typeof window===n||!N)){try{window.localStorage[N]=B;return}catch{}try{window.document.cookie=encodeURIComponent(N)+"="+B+";"}catch{}}}function Se(){var D;if(!(typeof window===n||!N)){try{D=window.localStorage[N]}catch{}if(typeof D===n)try{var B=window.document.cookie,V=B.indexOf(encodeURIComponent(N)+"=");V!==-1&&(D=/^([^;]+)/.exec(B.slice(V))[1])}catch{}return $.levels[D]===void 0&&(D=void 0),D}}function ve(){if(!(typeof window===n||!N)){try{window.localStorage.removeItem(N);return}catch{}try{window.document.cookie=encodeURIComponent(N)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}$.name=C,$.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},$.methodFactory=H||g,$.getLevel=function(){return oe},$.setLevel=function(D,B){if(typeof D=="string"&&$.levels[D.toUpperCase()]!==void 0&&(D=$.levels[D.toUpperCase()]),typeof D=="number"&&D>=0&&D<=$.levels.SILENT){if(oe=D,B!==!1&&j(D),h.call($,D,C),typeof console===n&&D<$.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+D},$.setDefaultLevel=function(D){I=D,Se()||$.setLevel(D,!1)},$.resetLevel=function(){$.setLevel(I,!1),ve()},$.enableAll=function(D){$.setLevel($.levels.TRACE,D)},$.disableAll=function(D){$.setLevel($.levels.SILENT,D)};var k=Se();k==null&&(k=I),$.setLevel(k,!1)}var E=new T,y={};E.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var H=y[I];return H||(H=y[I]=new T(I,E.getLevel(),E.methodFactory)),H};var A=typeof window!==n?window.log:void 0;return E.noConflict=function(){return typeof window!==n&&window.log===E&&(window.log=A),E},E.getLoggers=function(){return y},E.default=E,E})})(Dh);var It=Dh.exports;const vs=()=>`${new Date().toISOString()} | metrics`,Es=(c,t,n)=>`${c} | ${t} | ${n}`;It.setDefaultLevel(It.levels.TRACE);const gv=c=>{It.info(Es(vs(),"log ",`set log level to ${c?"verbose":"info"}`)),It.setLevel(c?It.levels.TRACE:It.levels.INFO)},Tv=c=>{const t=[...Object.keys(It.levels)];t.includes(c)?(It.info(Es(vs(),"log ",`update log level to ${c.toLowerCase()}`)),It.setLevel(c)):It.warn(Es(vs(),"log ","Incorrect log level please choose one of "),t)},Pe=(c,t,n)=>{n?It.debug(Es(vs(),c,t),n):It.debug(Es(vs(),c,t))},iu=(c,t)=>{It.info(Es(vs(),c,t))},Rn=(c,t)=>{It.info(Es(vs(),c,t))},wa=(c,t)=>{It.warn(Es(vs(),c,t))},dr=(c,t)=>{It.error(Es(vs(),c,t))};function vv(c){return Math.floor(Math.random()*c).toString()}function xf(c,t){let n=t;return c.forEach(a=>{n=n.replace(a,"")}),n}function Ev(c,t){let n="";for(let a=0;a<t;a+=1)n+=c[vv(c.length)];return n}function Sv({length:c=20,useLetters:t=!0,useNumbers:n=!0,includeSymbols:a=[],excludeSymbols:o=[]}={}){let s="abcdefghijklmnopqrstuvwxyz",r="0123456789",d=[],h=[],_=[];return t&&(o.length&&(s=xf(o,s)),h=s.split("")),n&&(o.length&&(r=xf(o,r)),_=r.split("")),d=[...h,..._,...a],Ev(d,c)}var yv=Sv;const Qi=ze(yv),Av=()=>"WebRTCMetrics",Cv=()=>"5.0.3",$e={INBOUND:"inbound",OUTBOUND:"outbound"},gs={IDLE:"idle",RUNNING:"running",MUTED:"muted"},Ki={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},Rv=()=>({...{delta_time_to_measure_probes_ms:0,delta_time_consumed_to_measure_ms:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,total_time_decoded_in:0,total_time_encoded_out:0,probes:[]}}),Nh={level_in:0,codec_id_in:"",codec_in:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,mos_in:0,mos_emodel_in:0,ssrc:"",direction:$e.INBOUND},Uh={level_out:0,codec_id_out:"",codec_out:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,timestamp_out:null,mos_out:0,mos_emodel_out:0,ssrc:"",direction:$e.OUTBOUND},Ph={codec_id_in:"",size_in:{width:null,height:null,framerate:null},codec_in:{mime_type:null,clock_rate:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,decoder_in:null,delta_ms_decode_frame_in:0,total_frames_decoded_in:0,total_time_decoded_in:0,delta_nack_sent_in:0,delta_pli_sent_in:0,total_nack_sent_in:0,total_pli_sent_in:0,ssrc:"",direction:$e.INBOUND},xh={codec_id_out:"",size_out:{width:null,height:null,framerate:null},codec_out:{mime_type:null,clock_rate:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,encoder_out:null,delta_ms_encode_frame_out:0,total_time_encoded_out:0,total_frames_encoded_out:0,delta_nack_received_out:0,delta_pli_received_out:0,total_nack_received_out:0,total_pli_received_out:0,limitation_out:{reason:null,durations:null,resolutionChanges:0},timestamp_out:null,ssrc:"",direction:$e.OUTBOUND},Iv=c=>{const t={pname:"",call_id:"",user_id:"",timestamp:null,count:0,audio:{},video:{},network:{infrastructure:3,local_candidate_id:"",local_candidate_type:"",local_candidate_protocol:"",local_candidate_relay_protocol:"",remote_candidate_id:"",remote_candidate_type:"",remote_candidate_protocol:""},data:{total_KBytes_in:0,total_KBytes_out:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,delta_kbs_bandwidth_in:0,delta_kbs_bandwidth_out:0,delta_rtt_connectivity_ms:null,total_rtt_connectivity_ms:0,total_rtt_connectivity_measure:0},experimental:{time_to_measure_ms:0}};if(c){const n={...c,audio:{},video:{},data:{...c.data},network:{...c.network},experimental:{...c.experimental}};return Object.keys(c.audio).forEach(a=>{n.audio[a]={...c.audio[a]}}),Object.keys(c.video).forEach(a=>{n.video[a]={...c.video[a]}}),n}return{...t,audio:{},video:{},data:{...t.data},network:{...t.network},experimental:{...t.experimental}}},bv={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${Qi()}`,cid:`c-${Qi()}`,uid:`u-${Qi()}`,record:!1,ticket:!0},zt={CANDIDATE_PAIR:"candidate-pair",CODEC:"codec",INBOUND_RTP:"inbound-rtp",LOCAL_CANDIDATE:"local-candidate",MEDIA_SOURCE:"media-source",OUTBOUND_RTP:"outbound-rtp",REMOTE_CANDIDATE:"remote-candidate",REMOTE_INBOUND_RTP:"remote-inbound-rtp",TRACK:"track"},q={AUDIO_LEVEL:"audioLevel",AVAILABLE_OUTGOING_BITRATE:"availableOutgoingBitrate",AVAILABLE_INCOMING_BITRATE:"availableIncomingBitrate",BYTES_RECEIVED:"bytesReceived",BYTES_SENT:"bytesSent",CANDIDATE_TYPE:"candidateType",CHANNELS:"channels",CLOCK_RATE:"clockRate",CODEC_ID:"codecId",CURRENT_ROUND_TRIP_TIME:"currentRoundTripTime",ROUND_TRIP_TIME:"roundTripTime",FRACTION_LOST:"fractionLost",FRAME_HEIGHT:"frameHeight",FRAME_WIDTH:"frameWidth",QUALITY_LIMITATION_REASON:"qualityLimitationReason",QUALITY_LIMITATION_DURATIONS:"qualityLimitationDurations",QUALITY_LIMITATION_RESOLUTION_CHANGES:"qualityLimitationResolutionChanges",ID:"id",JITTER:"jitter",KIND:"kind",MEDIA_TYPE:"mediaType",MIME_TYPE:"mimeType",LOCAL_CANDIDATE_ID:"localCandidateId",NETWORK_TYPE:"networkType",RELAY_PROTOCOL:"relayProtocol",NOMINATED:"nominated",PACKETS_LOST:"packetsLost",PACKETS_RECEIVED:"packetsReceived",PACKETS_SENT:"packetsSent",PROTOCOL:"protocol",PORT:"port",REMOTE_CANDIDATE_ID:"remoteCandidateId",REMOTE_SOURCE:"remoteSource",RESPONSES_RECEIVED:"responsesReceived",SDP_FMTP_LINE:"sdpFmtpLine",SSRC:"ssrc",SELECTED:"selected",STATE:"state",TIMESTAMP:"timestamp",TOTAL_ROUND_TRIP_TIME:"totalRoundTripTime",TOTAL_ROUND_TRIP_TIME_MEASUREMENTS:"roundTripTimeMeasurements",TYPE:"type",DECODER_IMPLEMENTATION:"decoderImplementation",ENCODER_IMPLEMENTATION:"encoderImplementation",FRAMES_DECODED:"framesDecoded",FRAMES_ENCODED:"framesEncoded",FRAMES_PER_SECOND:"framesPerSecond",TOTAL_DECODE_TIME:"totalDecodeTime",TOTAL_ENCODE_TIME:"totalEncodeTime",PLI:"pliCount",NACK:"nackCount"},x={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},Yi={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},lu={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ne={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},au="config ",wv=(c,t={},n)=>{const a={...n,...t};return t.pname||wa(au,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${n.pname}'`),t.cid||wa(au,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${n.cid}'`),t.uid||wa(au,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${n.uid}'`),a.pc=c,a},Ov=(c={})=>{const t={...bv,...c};return t.name=Av(),t.version=Cv(),t},ml=(c,t,n,a=!1,o)=>{let s=c.map(r=>{if(!n)return r[t];if(!o)return r[t][n];const d=r[t][o];return d?d[n]:null});return s=s.filter(r=>a?Number.isFinite(r)&&r>0:Number.isFinite(r)),s.length===0?[]:s},Gs=c=>c.reduce((t,n)=>t+n,0)/c.length,Dv=()=>`probe-${Qi()}`,Nv=()=>`coltr-${Qi()}`,kf=c=>new Promise(t=>setTimeout(t,c)),wu=(c,t,n)=>{t?c.call(t,n):c(n)},Ke=(c,t,n,a)=>{const o=ml(c,t,n,!0,a);if(o.length===0)return null;const s=o.reduce((_,g)=>_+g,0)/o.length;return s===0?null:o.map(_=>Math.abs(s-_)).reduce((_,g)=>_+g,0)/o.length*100/s},Xe=(c,t,n,a=!1,o)=>{const s=ml(c,t,n,a,o);return s.length===0?null:s.reduce((r,d)=>r+d,0)/s.length},Sn=(c,t,n)=>ml(c,t,n).reduce((o,s)=>o+s,0),Ye=(c,t,n,a)=>{const o=ml(c,t,n,!0,a);return o.length===0?null:Math.min(...o)},Je=(c,t,n,a)=>{const o=ml(c,t,n,!1,a);return o.length===0?null:Math.max(...o)},gt=(c,t,n,a)=>{const o=c.slice().pop();if(!o)return null;if(!n)return o[t];if(!a)return o[t][n];const s=o[t][a];return s?s[n]:null},Uv=c=>c.slice().pop(),ct=(c,t,n)=>{if(!t)return null;const a={};let o=t[x.AUDIO][c];o||(o=n===$e.INBOUND?{...Nh}:{...Uh}),a[x.AUDIO]=o;let s=t[x.VIDEO][c];return s||(s=n===$e.INBOUND?{...Ph}:{...xh}),a[x.VIDEO]=s,a},Ji="exporter ",Pv="2.0",Mf=(c,t,n)=>{if(!c||c.length===0)return 0;const a=c[c.length-1];if(!a)return 0;const o=a[t][n];if(o){const s=o.total_rtt_ms_out,r=o.total_rtt_measure_out;return!r||!s?Xe(c,t,"delta_rtt_ms_out",!1,n):Number(s/r)}return null},xv=(c,t)=>{if(!c||c.length===0)return 0;const n=c[c.length-1];if(!n)return 0;const a=n[t].total_rtt_connectivity_ms,o=n[t].total_rtt_connectivity_measure;return!o||!a?Xe(c,t,"delta_rtt_connectivity_ms"):Number(a/o)},kv=c=>gt(c,"network","local_candidate_type")!=="relay"?`direct/${gt(c,"network","local_candidate_protocol")}`:`turn/${gt(c,"network","local_candidate_relay_protocol")}`,Mv=c=>{const t=gt(c,"network","remote_candidate_type"),n=gt(c,"network","remote_candidate_protocol");return t!=="relay"?`direct/${n}`:`turn/${n}`};class Lv{constructor(t){this._start=null,this._end=null,this._cfg=t,this._referenceReport=null,this._reports=[],this._events=[]}start(){iu(Ji,"start() - start exporter...");const t=new Date;return this._start=t.toJSON(),t}stop(){iu(Ji,"stop() - stop exporter...");const t=new Date;return this._end=t.toJSON(),t}saveReferenceReport(t){this._referenceReport=t}getReferenceReport(){return this._referenceReport}addReport(t){this._cfg.ticket&&(Pe(Ji,`addReport() - add report to exporter at ${t.timestamp}`),this._reports.push(t))}addCustomEvent(t){this._events.push(t)}reset(){iu(Ji,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Pe(Ji,"ticket() - generate ticket");const t=gt(this._reports,"audio","total_packets_lost_in"),n=gt(this._reports,"audio","total_packets_in"),a=gt(this._reports,"video","total_packets_lost_in"),o=gt(this._reports,"video","total_packets_in"),s={},r=Uv(this._reports);return r&&(Object.keys(r[x.AUDIO]).forEach(d=>{const h=r[x.AUDIO][d];if(s[h.ssrc]={type:x.AUDIO,direction:h.direction},h.direction===$e.INBOUND){const _={avg:Xe(this._reports,x.AUDIO,"delta_jitter_ms_in",!1,d),min:Ye(this._reports,x.AUDIO,"delta_jitter_ms_in",d),max:Je(this._reports,x.AUDIO,"delta_jitter_ms_in",d),volatility:Ke(this._reports,x.AUDIO,"delta_jitter_ms_in",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.AUDIO,"delta_kbs_in",!1,d),min:Ye(this._reports,x.AUDIO,"delta_kbs_in",d),max:Je(this._reports,x.AUDIO,"delta_kbs_in",d),volatility:Ke(this._reports,x.AUDIO,"delta_kbs_in",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.AUDIO,"delta_KBytes_in",!1,d),min:Ye(this._reports,x.AUDIO,"delta_KBytes_in",d),max:Je(this._reports,x.AUDIO,"delta_KBytes_in",d),volatility:Ke(this._reports,x.AUDIO,"delta_KBytes_in",d),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={emodel:{avg:Xe(this._reports,x.AUDIO,"mos_emodel_in",!1,d),min:Ye(this._reports,x.AUDIO,"mos_emodel_in",d),max:Je(this._reports,x.AUDIO,"mos_emodel_in",d),volatility:Ke(this._reports,x.AUDIO,"mos_emodel_in",d)},effective:{avg:Xe(this._reports,x.AUDIO,"mos_in",!1,d),min:Ye(this._reports,x.AUDIO,"mos_in",d),max:Je(this._reports,x.AUDIO,"mos_in",d),volatility:Ke(this._reports,x.AUDIO,"mos_in",d)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},y=gt(this._reports,x.AUDIO,"total_packets_lost_in",d),A=gt(this._reports,x.AUDIO,"total_packets_in",d),C={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[d].jitter=_,s[d].mos=E,s[d].traffic=T,s[d].bitrate=g,s[d].loss=C}else{const _={avg:Xe(this._reports,x.AUDIO,"delta_jitter_ms_out",!1,d),min:Ye(this._reports,x.AUDIO,"delta_jitter_ms_out",d),max:Je(this._reports,x.AUDIO,"delta_jitter_ms_out",d),volatility:Ke(this._reports,x.AUDIO,"delta_jitter_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.AUDIO,"delta_kbs_out",!1,d),min:Ye(this._reports,x.AUDIO,"delta_kbs_out",d),max:Je(this._reports,x.AUDIO,"delta_kbs_out",d),volatility:Ke(this._reports,x.AUDIO,"delta_kbs_out",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.AUDIO,"delta_KBytes_out",!1,d),min:Ye(this._reports,x.AUDIO,"delta_KBytes_out",d),max:Je(this._reports,x.AUDIO,"delta_KBytes_out",d),volatility:Ke(this._reports,x.AUDIO,"delta_KBytes_out",d),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},E={avg:Mf(this._reports,x.AUDIO,d),min:Ye(this._reports,x.AUDIO,"delta_rtt_ms_out",d),max:Je(this._reports,x.AUDIO,"delta_rtt_ms_out",d),volatility:Ke(this._reports,x.AUDIO,"delta_rtt_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=gt(this._reports,x.AUDIO,"total_packets_lost_out",d),A=gt(this._reports,x.AUDIO,"total_packets_out",d),C={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},I={emodel:{avg:Xe(this._reports,x.AUDIO,"mos_emodel_out",!1,d),min:Ye(this._reports,x.AUDIO,"mos_emodel_out",d),max:Je(this._reports,x.AUDIO,"mos_emodel_out",d),volatility:Ke(this._reports,x.AUDIO,"mos_emodel_out",d)},effective:{avg:Xe(this._reports,x.AUDIO,"mos_out",!1,d),min:Ye(this._reports,x.AUDIO,"mos_out",d),max:Je(this._reports,x.AUDIO,"mos_out",d),volatility:Ke(this._reports,x.AUDIO,"mos_out",d)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};s[d].jitter=_,s[d].rtt=E,s[d].traffic=T,s[d].bitrate=g,s[d].loss=C,s[d].mos=I}}),Object.keys(r[x.VIDEO]).forEach(d=>{const h=r[x.VIDEO][d];if(s[d]={type:x.VIDEO,direction:h.direction},h.direction===$e.INBOUND){const _={avg:Xe(this._reports,x.VIDEO,"delta_jitter_ms_in",!1,d),min:Ye(this._reports,x.VIDEO,"delta_jitter_ms_in",d),max:Je(this._reports,x.VIDEO,"delta_jitter_ms_in",d),volatility:Ke(this._reports,x.VIDEO,"delta_jitter_ms_in",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.VIDEO,"delta_kbs_in",!1,d),min:Ye(this._reports,x.VIDEO,"delta_kbs_in",d),max:Je(this._reports,x.VIDEO,"delta_kbs_in",d),volatility:Ke(this._reports,x.VIDEO,"delta_kbs_in",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.VIDEO,"delta_KBytes_in",!1,d),min:Ye(this._reports,x.VIDEO,"delta_KBytes_in",d),max:Je(this._reports,x.VIDEO,"delta_KBytes_in",d),volatility:Ke(this._reports,x.VIDEO,"delta_KBytes_in",d),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E=gt(this._reports,x.VIDEO,"total_packets_lost_in",d),y=gt(this._reports,x.VIDEO,"total_packets_in",d),A={lost:E,avg:Math.round((E/(E+y)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[d].jitter=_,s[d].traffic=T,s[d].bitrate=g,s[d].loss=A}else{const _={avg:Xe(this._reports,x.VIDEO,"delta_jitter_ms_out",!1,d),min:Ye(this._reports,x.VIDEO,"delta_jitter_ms_out",d),max:Je(this._reports,x.VIDEO,"delta_jitter_ms_out",d),volatility:Ke(this._reports,x.VIDEO,"delta_jitter_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.VIDEO,"delta_kbs_out",!1,d),min:Ye(this._reports,x.VIDEO,"delta_kbs_out",d),max:Je(this._reports,x.VIDEO,"delta_kbs_out",d),volatility:Ke(this._reports,x.VIDEO,"delta_kbs_out",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.VIDEO,"delta_KBytes_out",!1,d),min:Ye(this._reports,x.VIDEO,"delta_KBytes_out",d),max:Je(this._reports,x.VIDEO,"delta_KBytes_out",d),volatility:Ke(this._reports,x.VIDEO,"delta_KBytes_out",d),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={avg:Mf(this._reports,x.VIDEO,d),min:Ye(this._reports,x.VIDEO,"delta_rtt_ms_out",d),max:Je(this._reports,x.VIDEO,"delta_rtt_ms_out",d),volatility:Ke(this._reports,x.VIDEO,"delta_rtt_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=gt(this._reports,x.VIDEO,"total_packets_lost_out",d),A=gt(this._reports,x.VIDEO,"total_packets_out",d),C={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[d].jitter=_,s[d].rtt=E,s[d].traffic=T,s[d].bitrate=g,s[d].loss=C}})),{version:Pv,configuration:{frequency:this._cfg.refreshEvery},started:this._start,ended:this._end,ua:{agent:navigator.userAgent,pname:this._cfg.pname,user_id:this._cfg.uid},call:{call_id:this._cfg.cid,events:this._events},details:{count:this._reports.length,reports:this._cfg.record?this._reports:[],reference:this._referenceReport||null},ssrc:s,data:{rtt:{avg:xv(this._reports,"data"),min:Ye(this._reports,"data","delta_rtt_connectivity_ms"),max:Je(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Ke(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((t/(t+n)*100||0)*100)/100}},video:{in:{avg:Math.round((a/(a+o)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:Xe(this._reports,"data","delta_kbs_in"),min:Ye(this._reports,"data","delta_kbs_in"),max:Je(this._reports,"data","delta_kbs_in"),volatility:Ke(this._reports,"data","delta_kbs_in")},out:{avg:Xe(this._reports,"data","delta_kbs_out"),min:Ye(this._reports,"data","delta_kbs_out"),max:Je(this._reports,"data","delta_kbs_out"),volatility:Ke(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:Xe(this._reports,"data","delta_KBytes_in"),min:Ye(this._reports,"data","delta_KBytes_in"),max:Je(this._reports,"data","delta_KBytes_in"),volatility:Ke(this._reports,"data","delta_KBytes_in")},out:{avg:Xe(this._reports,"data","delta_KBytes_out"),min:Ye(this._reports,"data","delta_KBytes_out"),max:Je(this._reports,"data","delta_KBytes_out"),volatility:Ke(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:kv(this._reports),remoteConnection:Mv(this._reports)}}}}updateConfig(t){this._cfg=t}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const t=this._reports.slice();return t.pop(),t.pop()||null}getReportsNumber(){return this._reports.length}}const js="extractor ",Lf=(c,t,n,a)=>{let o=!1;const s=a[t].total_rtt_ms_out,r=a[t].total_rtt_measure_out,d=n?n[t].total_rtt_ms_out:0,h=n?n[t].total_rtt_measure_out:0,_={rtt:null,totalRTT:s,totalRTTMeasurements:r};if(c[q.TIMESTAMP]===a[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,q.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(o=!0,Number(c[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-h===r))return _;const g=1e3*Number(c[q.ROUND_TRIP_TIME]);let T=s+g,E=r+1;return o&&(T=1e3*Number(c[q.TOTAL_ROUND_TRIP_TIME])-d,E=Number(c[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-h),{rtt:g,totalRTT:T,totalRTTMeasurements:E}},$v=(c,t,n,a)=>{if(!Object.prototype.hasOwnProperty.call(c,q.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:a[t].total_rtt_connectivity_ms,totalRTTMeasurements:a[t].total_rtt_connectivity_measure};const o=1e3*Number(c[q.CURRENT_ROUND_TRIP_TIME]);let s=a[t].total_rtt_connectivity_ms+o,r=a[t].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,q.TOTAL_ROUND_TRIP_TIME)&&(s=1e3*Number(c[q.TOTAL_ROUND_TRIP_TIME])-(n?n[t].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,q.RESPONSES_RECEIVED)&&(r=Number(c[q.RESPONSES_RECEIVED])-(n?n[t].total_rtt_connectivity_measure:0)),{rtt:o,totalRTT:s,totalRTTMeasurements:r}},da=(c,t,n)=>c[q.TIMESTAMP]===n[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,q.JITTER)?null:1e3*(Number(c[q.JITTER])||0),Hv=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,q.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,q.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:t[x.VIDEO].delta_ms_decode_frame_in,frames_decoded:t[x.VIDEO].total_frames_decoded_in,total_decode_time:t[x.VIDEO].total_time_decoded_in};const n=c[q.FRAMES_DECODED],a=c[q.TOTAL_DECODE_TIME],o=a-t[x.VIDEO].total_time_decoded_in,s=n-t[x.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:s>0?o*1e3/s:0,frames_decoded:n,total_decode_time:a}},Fv=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,q.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,q.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:t[x.VIDEO].delta_ms_encode_frame_out,frames_encoded:t[x.VIDEO].total_frames_encoded_out,total_encode_time:t[x.VIDEO].total_time_encoded_out};const n=c[q.FRAMES_ENCODED],a=c[q.TOTAL_ENCODE_TIME],o=a-t[x.VIDEO].total_time_encoded_out,s=n-t[x.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:s>0&&o?o*1e3/s:0,frames_encoded:n,total_encode_time:a}},$f=(c,t,n,a)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,q.BYTES_SENT))return{packetsSent:n[t].total_packets_out,packetsLost:n[t].total_packets_lost_out,bytesSent:n[t].total_KBytes_out};const o=Number(c[q.PACKETS_SENT])||0-(a?a[t].total_packets_out:0),s=o-n[t].total_packets_out,r=Number(c[q.BYTES_SENT])/1024-(a?a[t].total_KBytes_out:0),d=r-n[t].total_KBytes_out,h=c[q.TIMESTAMP]||Date.now(),_=a?a.timestamp:null;let g=n.timestamp;!g&&_&&(g=_);const T=g?h-g:0,E=T>0?d*.008*1024/T*1e3:0;return{packetsSent:o,deltaPacketsSent:s,KBytesSent:r,deltaKBytesSent:d,kbsSent:E}},Hf=(c,t,n,a)=>{let o=n[t].total_packets_lost_out,s=0,r=0;return Object.prototype.hasOwnProperty.call(c,q.PACKETS_LOST)&&(o=Number(c[q.PACKETS_LOST])||0-(a?a[t].total_packets_lost_out:0),s=o-n[t].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,q.FRACTION_LOST)&&(r=Number(100*c[q.FRACTION_LOST])),{packetsLost:o,deltaPacketsLost:s,fractionLost:r}},Ff=(c,t,n,a)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,q.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,q.BYTES_RECEIVED))return{percent_packets_lost:n[t].percent_packets_lost_in,packetsReceived:n[t].total_packets_in,packetsLost:n[t].total_packets_lost_in,bytesReceived:n[t].total_KBytes_in};const o=Number(c[q.PACKETS_RECEIVED])||0-(a?a[t].total_packets_in:0),s=Number(c[q.PACKETS_LOST])||0-(a?a[t].total_packets_lost_in:0),r=s-n[t].total_packets_lost_in,d=o-n[t].total_packets_in,h=o!==n[t].total_packets_in?r*100/(r+d):0,_=Number(c[q.BYTES_RECEIVED])/1024-(a?a[t].total_KBytes_in:0),g=_-n[t].total_KBytes_in,T=c[q.TIMESTAMP]||Date.now(),E=a?a.timestamp:null;let y=n.timestamp;!y&&E&&(y=E);const A=y?T-y:0,C=A>0?g*.008*1024/A*1e3:0;return{percentPacketsLost:h,packetsReceived:o,deltaPacketsReceived:d,packetsLost:s,deltaPacketsLost:r,KBytesReceived:_,deltaKBytesReceived:g,kbsReceived:C}},jv=c=>c[q.CANDIDATE_TYPE]!=="relay"?"":c[q.RELAY_PROTOCOL]||"",qv=c=>{if(!Object.prototype.hasOwnProperty.call(c,q.NETWORK_TYPE))return Yi.WIFI;switch(c[q.NETWORK_TYPE]){case lu.ETHERNET:return Yi.ETHERNET;case lu.CELLULAR_4G:return Yi.CELLULAR_4G;case lu.WIFI:return Yi.WIFI;default:return Yi.CELLULAR}},jf=c=>!Object.prototype.hasOwnProperty.call(c,q.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,q.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[q.FRAME_WIDTH]||null,height:c[q.FRAME_HEIGHT]||null,framerate:c[q.FRAMES_PER_SECOND]},Vv=c=>{const t=Object.prototype.hasOwnProperty.call(c,q.QUALITY_LIMITATION_REASON)?c[q.QUALITY_LIMITATION_REASON]:null,n=Object.prototype.hasOwnProperty.call(c,q.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[q.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,a=Object.prototype.hasOwnProperty.call(c,q.QUALITY_LIMITATION_DURATIONS)?c[q.QUALITY_LIMITATION_DURATIONS]:null;return a&&Object.keys(a).forEach(o=>{a[o]>1e3&&(a[o]=Number(a[o]/1e3))}),{reason:t,durations:a,resolutionChanges:n}},Bv=(c,t,n)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PLI)||!Object.prototype.hasOwnProperty.call(c,q.NACK))return{pliCount:t.total_pli_sent_in,nackCount:t.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const a=(c[q.PLI]||0)-(n?n[x.VIDEO].total_pli_sent_in:0),o=(c[q.NACK]||0)-(n?n[x.VIDEO].total_nack_sent_in:0);return{pliCount:a,nackCount:o,deltaPliCount:a-t[x.VIDEO].total_pli_sent_in,deltaNackCount:o-t[x.VIDEO].total_nack_sent_in}},Gv=(c,t,n)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PLI)||!Object.prototype.hasOwnProperty.call(c,q.NACK))return{pliCount:t.total_pli_received_out,nackCount:t.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const a=(c[q.PLI]||0)-(n?n[x.VIDEO].total_pli_received_out:0),o=(c[q.NACK]||0)-(n?n[x.VIDEO].total_nack_received_out:0);return{pliCount:a,nackCount:o,deltaPliCount:a-t[x.VIDEO].total_pli_received_out,deltaNackCount:o-t[x.VIDEO].total_nack_received_out}},Wv=c=>({channels:c[q.CHANNELS]||null,clock_rate:c[q.CLOCK_RATE]||null,mime_type:c[q.MIME_TYPE]||null,sdp_fmtp_line:c[q.SDP_FMTP_LINE]||null}),Kv=c=>({clock_rate:c[q.CLOCK_RATE]||null,mime_type:c[q.MIME_TYPE]||null}),Yv=(c,t,n)=>{const a=(c[q.BYTES_RECEIVED]||0)/1024-(n?n.data.total_KBytes_in:0),o=(c[q.BYTES_SENT]||0)/1024-(n?n.data.total_KBytes_out:0),s=c[q.TIMESTAMP]||Date.now(),r=a-t.data.total_KBytes_in,d=o-t.data.total_KBytes_out,h=n?n.timestamp:null;let _=t.timestamp;!_&&h&&(_=h);const g=_?s-_:0,T=g>0?r*.008*1024/g*1e3:0,E=g>0?d*.008*1024/g*1e3:0;return{total_KBytes_received:a,total_KBytes_sent:o,delta_KBytes_received:r,delta_KBytes_sent:d,kbs_speed_received:T,kbs_speed_sent:E}},Jv=c=>{const t=c[q.AVAILABLE_INCOMING_BITRATE]/1024||0,n=c[q.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:t,kbs_outgoing_bandwidth:n}},zv=(c,t,n,a)=>{if(!c)return[];switch(c[q.TYPE]){case zt.CANDIDATE_PAIR:let o=!1;if(c[q.NOMINATED]&&c[q.STATE]===x.SUCCEEDED&&(o=!0,Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c),q.SELECTED in c&&!c[q.SELECTED]&&(o=!1)),o){const r=c[q.LOCAL_CANDIDATE_ID],d=c[q.REMOTE_CANDIDATE_ID],h=Yv(c,t,a),_=Jv(c),g=$v(c,"data",a,t);return[{type:ne.NETWORK,value:{local_candidate_id:r}},{type:ne.NETWORK,value:{remote_candidate_id:d}},{type:ne.DATA,value:{total_KBytes_in:h.total_KBytes_received}},{type:ne.DATA,value:{total_KBytes_out:h.total_KBytes_sent}},{type:ne.DATA,value:{delta_KBytes_in:h.delta_KBytes_received}},{type:ne.DATA,value:{delta_KBytes_out:h.delta_KBytes_sent}},{type:ne.DATA,value:{delta_kbs_in:h.kbs_speed_received}},{type:ne.DATA,value:{delta_kbs_out:h.kbs_speed_sent}},{type:ne.DATA,value:{delta_kbs_bandwidth_in:_.kbs_incoming_bandwidth}},{type:ne.DATA,value:{delta_kbs_bandwidth_out:_.kbs_outgoing_bandwidth}},{type:ne.DATA,value:{delta_rtt_connectivity_ms:g.rtt}},{type:ne.DATA,value:{total_rtt_connectivity_ms:g.totalRTT}},{type:ne.DATA,value:{total_rtt_connectivity_measure:g.totalRTTMeasurements}}]}break;case zt.LOCAL_CANDIDATE:if(c[q.ID]===t.network.local_candidate_id)return[{type:ne.NETWORK,value:{infrastructure:qv(c)}},{type:ne.NETWORK,value:{local_candidate_type:c[q.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{local_candidate_protocol:c[q.PROTOCOL]||""}},{type:ne.NETWORK,value:{local_candidate_relay_protocol:jv(c)}}];break;case zt.REMOTE_CANDIDATE:if(c[q.ID]===t.network.remote_candidate_id)return[{type:ne.NETWORK,value:{remote_candidate_type:c[q.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{remote_candidate_protocol:c[q.PROTOCOL]||""}}];break;case zt.INBOUND_RTP:{Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const r=c[q.SSRC],d=ct(r,t,$e.INBOUND);d&&(d.timestamp=t.timestamp);const h=ct(r,a,$e.INBOUND);if(h&&(h.timestamp=a.timestamp),c[q.MEDIA_TYPE]===x.AUDIO){const _=Ff(c,x.AUDIO,d,h),g=da(c,x.AUDIO,d),T=c[q.CODEC_ID]||"";return[{ssrc:r,type:ne.AUDIO,value:{codec_id_in:T}},{ssrc:r,type:ne.AUDIO,value:{total_packets_in:_.packetsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_in:_.deltaPacketsReceived}},{ssrc:r,type:ne.AUDIO,value:{total_packets_lost_in:_.packetsLost}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_lost_in:_.deltaPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{percent_packets_lost_in:_.percentPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{total_KBytes_in:_.KBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_KBytes_in:_.deltaKBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_kbs_in:_.kbsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_in:g}}]}if(c[q.MEDIA_TYPE]===x.VIDEO){const _=Hv(c,d),g=Ff(c,x.VIDEO,d,h),T=da(c,x.VIDEO,d),E=c[q.DECODER_IMPLEMENTATION]||null,y=c[q.CODEC_ID]||null,A=jf(c),C=Bv(c,d,h);return[{ssrc:r,type:ne.VIDEO,value:{codec_id_in:y}},{ssrc:r,type:ne.VIDEO,value:{total_packets_in:g.packetsReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_in:g.deltaPacketsReceived}},{ssrc:r,type:ne.VIDEO,value:{total_packets_lost_in:g.packetsLost}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_lost_in:g.deltaPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{percent_packets_lost_in:g.percentPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{total_KBytes_in:g.KBytesReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_KBytes_in:g.deltaKBytesReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_kbs_in:g.kbsReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_jitter_ms_in:T}},{ssrc:r,type:ne.VIDEO,value:{decoder_in:E}},{ssrc:r,type:ne.VIDEO,value:{delta_ms_decode_frame_in:_.delta_ms_decode_frame}},{ssrc:r,type:ne.VIDEO,value:{total_frames_decoded_in:_.frames_decoded}},{ssrc:r,type:ne.VIDEO,value:{total_time_decoded_in:_.total_decode_time}},{ssrc:r,type:ne.VIDEO,value:{total_nack_sent_in:C.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_sent_in:C.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_sent_in:C.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_sent_in:C.deltaPliCount}},{ssrc:r,type:ne.VIDEO,value:{size_in:A}}]}break}case zt.OUTBOUND_RTP:{Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const r=c[q.SSRC],d=ct(r,t,$e.OUTBOUND);d&&(d.timestamp=t.timestamp);const h=ct(r,a,$e.OUTBOUND);if(h&&(h.timestamp=a.timestamp),c[q.MEDIA_TYPE]===x.AUDIO){const _=c[q.CODEC_ID]||null,g=$f(c,x.AUDIO,d,h);return[{ssrc:r,type:ne.AUDIO,value:{codec_id_out:_}},{ssrc:r,type:ne.AUDIO,value:{total_packets_out:g.packetsSent}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_out:g.deltaPacketsSent}},{ssrc:r,type:ne.AUDIO,value:{total_KBytes_out:g.KBytesSent}},{ssrc:r,type:ne.AUDIO,value:{delta_KBytes_out:g.deltaKBytesSent}},{ssrc:r,type:ne.AUDIO,value:{delta_kbs_out:g.kbsSent}}]}if(c[q.MEDIA_TYPE]===x.VIDEO){const _=c[q.ENCODER_IMPLEMENTATION]||null,g=c[q.CODEC_ID]||null,T=Fv(c,d),E=jf(c),y=Vv(c),A=Gv(c,d,h),C=$f(c,x.VIDEO,d,h);return[{ssrc:r,type:ne.VIDEO,value:{codec_id_out:g}},{ssrc:r,type:ne.VIDEO,value:{total_packets_out:C.packetsSent}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_out:C.deltaPacketsSent}},{ssrc:r,type:ne.VIDEO,value:{total_KBytes_out:C.KBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_KBytes_out:C.deltaKBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_kbs_out:C.kbsSent}},{ssrc:r,type:ne.VIDEO,value:{encoder_out:_}},{ssrc:r,type:ne.VIDEO,value:{delta_ms_encode_frame_out:T.delta_ms_encode_frame}},{ssrc:r,type:ne.VIDEO,value:{total_frames_encoded_out:T.frames_encoded}},{ssrc:r,type:ne.VIDEO,value:{total_time_encoded_out:T.total_encode_time}},{ssrc:r,type:ne.VIDEO,value:{total_nack_received_out:A.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_received_out:A.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_received_out:A.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_received_out:A.deltaPliCount}},{ssrc:r,type:ne.VIDEO,value:{size_out:E}},{ssrc:r,type:ne.VIDEO,value:{limitation_out:y}}]}break}case zt.MEDIA_SOURCE:{Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);break}case zt.TRACK:{Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);break}case zt.CODEC:const s=[];return Object.keys(t[x.AUDIO]).forEach(r=>{const d=t[x.AUDIO][r];if(d.codec_id_in===c[q.ID]||d.codec_id_out===c[q.ID]){Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const h=Wv(c);c[q.ID]===d.codec_id_in?s.push({ssrc:d.ssrc,type:ne.AUDIO,value:{codec_in:h}}):s.push({ssrc:d.ssrc,type:ne.AUDIO,value:{codec_out:h}})}}),Object.keys(t[x.VIDEO]).forEach(r=>{const d=t[x.VIDEO][r];if(d.codec_id_in===c[q.ID]||d.codec_id_out===c[q.ID]){Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const h=Kv(c);c[q.ID]===d.codec_id_in?s.push({ssrc:d.ssrc,type:ne.VIDEO,value:{codec_in:h}}):s.push({ssrc:d.ssrc,type:ne.VIDEO,value:{codec_out:h}})}}),s;case zt.REMOTE_INBOUND_RTP:{Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const r=c[q.SSRC],d=ct(r,t,$e.OUTBOUND),h=ct(r,a,$e.OUTBOUND);if(c[q.KIND]===x.AUDIO){const _=Lf(c,x.AUDIO,h,d),g=da(c,x.AUDIO,d),T=Hf(c,x.AUDIO,d,h);return[{ssrc:r,type:ne.AUDIO,value:{delta_rtt_ms_out:_.rtt}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_ms_out:_.totalRTT}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_measure_out:_.totalRTTMeasurements}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_out:g}},{ssrc:r,type:ne.AUDIO,value:{timestamp_out:c[q.TIMESTAMP]}},{ssrc:r,type:ne.AUDIO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{percent_packets_lost_out:T.fractionLost}}]}if(c[q.KIND]===x.VIDEO){const _=Lf(c,x.VIDEO,h,d),g=da(c,x.VIDEO,d),T=Hf(c,x.VIDEO,d,h);return[{ssrc:r,type:ne.VIDEO,value:{delta_rtt_ms_out:_.rtt}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_ms_out:_.totalRTT}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_measure_out:_.totalRTTMeasurements}},{ssrc:r,type:ne.VIDEO,value:{delta_jitter_ms_out:g}},{ssrc:r,type:ne.VIDEO,value:{timestamp_out:c[q.TIMESTAMP]}},{ssrc:r,type:ne.VIDEO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{percent_packets_lost_out:T.fractionLost}}]}break}}return[]},Ka=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),Xv=(c,t=x.AUDIO,n,a,o)=>{const s=ct(o,c,$e.INBOUND),r=ct(o,n,$e.INBOUND),d=ct(o,a,$e.INBOUND),h=[],_=[],g=s[t].percent_packets_lost_in,T=s[t].delta_jitter_ms_in,E=r&&r[t].delta_jitter_ms_in||null,y=d&&d[t].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,C=n&&n.data.delta_rtt_connectivity_ms||null,I=a&&a.data.delta_rtt_connectivity_ms||null;A&&h.push(A),C&&h.push(C),I&&h.push(I),T&&_.push(T),n&&E&&_.push(E),a&&y&&_.push(y);const H=h.length>0?Gs(h):100,$=_.length>0?Gs(_):10,oe=93.2-g,N=.18*oe*oe-27.9*oe+1126.62,j=(H+$)/2,Se=j-177.3<0?0:1,ve=.024*j+.11*(j-177.3)*Se,k=N-ve;return Ka(k)},Qv=(c,t=x.AUDIO,n,a,o)=>{const s=ct(o,c,$e.OUTBOUND),r=ct(o,n,$e.OUTBOUND),d=ct(o,a,$e.OUTBOUND),h=[],_=[],g=s[t].percent_packets_lost_out,T=s[t].delta_rtt_ms_out,E=r&&r[t].delta_rtt_ms_out||null,y=d&&d[t].delta_rtt_ms_out||null,A=s[t].delta_jitter_ms_out,C=r&&r[t].delta_jitter_ms_out||null,I=d&&d[t].delta_jitter_ms_out||null,H=c.data.delta_rtt_connectivity_ms,$=n&&n.data.delta_rtt_connectivity_ms||null,oe=a&&a.data.delta_rtt_connectivity_ms||null;T?h.push(T):H&&h.push(H),E?h.push(E):$&&h.push($),y?h.push(y):oe&&h.push(oe),A&&_.push(A),n&&C&&_.push(C),a&&I&&_.push(I);const N=h.length>0?Gs(h):100,j=_.length>0?Gs(_):10,Se=93.2-g,ve=.18*Se*Se-27.9*Se+1126.62,k=(N+j)/2,D=k-177.3<0?0:1,B=.024*k+.11*(k-177.3)*D,V=ve-B;return Ka(V)},Zv=(c,t=x.AUDIO,n,a,o)=>{const s=ct(o,c,$e.INBOUND),r=ct(o,n,$e.INBOUND),d=ct(o,a,$e.INBOUND),h=[],_=[],g=s[t].percent_packets_lost_in/100,T=s[t].delta_jitter_ms_in,E=r&&r[t].delta_jitter_ms_in||null,y=d&&d[t].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,C=n&&n.data.delta_rtt_connectivity_ms||null,I=a&&a.data.delta_rtt_connectivity_ms||null;A&&h.push(A),C&&h.push(C),I&&h.push(I),T&&_.push(T),r&&E&&_.push(E),d&&y&&_.push(y);const H=h.length>0?Gs(h):100,$=_.length>0?Gs(_):10,oe=0,N=19.8,j=29.7,Se=30,ve=(H+$)/2+Se,k=ve-177.3<0?0:1,D=.024*ve+.11*(ve-177.3)*k,V=93.2-(oe+N*Math.log(1+j*g)+D);return Ka(V)},eE=(c,t=x.AUDIO,n,a,o)=>{const s=ct(o,c,$e.OUTBOUND),r=ct(o,n,$e.OUTBOUND),d=ct(o,a,$e.OUTBOUND),h=[],_=[],g=s[t].percent_packets_lost_out/100,T=s[t].delta_rtt_ms_out,E=r&&r[t].delta_rtt_ms_out||null,y=d&&d[t].delta_rtt_ms_out||null,A=s[t].delta_jitter_ms_out,C=r&&r[t].delta_jitter_ms_out||null,I=d&&d[t].delta_jitter_ms_out||null,H=c.data.delta_rtt_connectivity_ms,$=n&&n.data.delta_rtt_connectivity_ms||null,oe=a&&a.data.delta_rtt_connectivity_ms||null;T?h.push(T):H&&h.push(H),E?h.push(E):$&&h.push($),y?h.push(y):oe&&h.push(oe),A&&_.push(A),r&&C&&_.push(C),d&&I&&_.push(I);const N=h.length>0?Gs(h):100,j=_.length>0?Gs(_):10,Se=0,ve=19.8,k=29.7,D=30,B=(N+j)/2+D,V=B-177.3<0?0:1,J=.024*B+.11*(B-177.3)*V,X=93.2-(Se+ve*Math.log(1+k*g)+J);return Ka(X)};class tE{constructor(t,n){this._callbacks={onreport:null,onticket:null},this._id=Nv(),this._moduleName=this._id,this._probeId=n,this._config=t,this._exporter=new Lv(t),this._state=gs.IDLE,this.registerToPCEvents(),Rn(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(t,n,a,o){const s=(h,_)=>h===x.AUDIO?_===zt.INBOUND_RTP?{...Nh}:{...Uh}:_===zt.INBOUND_RTP?{...Ph}:{...xh},r=Iv(n);r.pname=this._config.pname,r.call_id=this._config.cid,r.user_id=this._config.uid,r.count=n?n.count+1:1;let d=null;return t.forEach(h=>{!d&&h.timestamp&&(d=h.timestamp),zv(h,r,r.pname,o).forEach(g=>{if(g.value&&g.type)if(g.ssrc){let T=r[g.type][g.ssrc];T||(T=s(g.type,h.type),T.ssrc=g.ssrc,r[g.type][g.ssrc]=T),Object.keys(g.value).forEach(E=>{T[E]=g.value[E]})}else Object.keys(g.value).forEach(T=>{r[g.type][T]=g.value[T]})})}),r.timestamp=d,Object.keys(r[x.AUDIO]).forEach(h=>{const _=r[x.AUDIO][h];_.direction===$e.INBOUND?(_.mos_emodel_in=Xv(r,x.AUDIO,n,a,_.ssrc),_.mos_in=Zv(r,x.AUDIO,n,a,_.ssrc)):(_.mos_emodel_out=Qv(r,x.AUDIO,n,a,_.ssrc),_.mos_out=eE(r,x.AUDIO,n,a,_.ssrc))}),r}async takeReferenceStats(){return new Promise((t,n)=>{const a=Date.now();setTimeout(async()=>{try{const o=Date.now()-a,s=Date.now(),r=await this._config.pc.getStats(),d=this.analyze(r,null,null,null),h=Date.now();d.experimental.time_to_measure_ms=h-s,d.experimental.time_to_wait_ms=o,this._exporter.saveReferenceReport(d),Pe(this._moduleName,`got reference report for probe ${this._probeId}`),t()}catch(o){n(o)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==gs.RUNNING||!this._config.pc)return Pe(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const t=Date.now(),n=await this._config.pc.getStats(),a=this.analyze(n,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),o=Date.now();return a.experimental.time_to_measure_ms=o-t,this._exporter.addReport(a),Pe(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(a),a}catch(t){return dr(this._moduleName,`got error ${t}`),null}}async start(){Pe(this._moduleName,"starting"),this.state=gs.RUNNING,this._startedTime=this._exporter.start(),Pe(this._moduleName,"started")}async mute(){this.state=gs.MUTED,Pe(this._moduleName,"muted")}async unmute(){this.state=gs.RUNNING,Pe(this._moduleName,"unmuted")}async stop(t){if(Pe(this._moduleName,`stopping${t?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=gs.IDLE,this._config.ticket){const{ticket:n}=this._exporter;this.fireOnTicket(n)}this._exporter.reset(),Pe(this._moduleName,"stopped")}registerCallback(t,n,a){t in this._callbacks?(this._callbacks[t]={callback:n,context:a},Pe(this._moduleName,`registered callback '${t}'`)):dr(this._moduleName,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],Pe(this._moduleName,`unregistered callback '${t}'`)):dr(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReport(t){this._callbacks.onreport&&wu(this._callbacks.onreport.callback,this._callbacks.onreport.context,t)}fireOnTicket(t){this._callbacks.onticket&&wu(this._callbacks.onticket.callback,this._callbacks.onticket.context,t)}updateConfig(t){this._config=t,this._exporter.updateConfig(t)}get state(){return this._state}set state(t){this._state=t,Pe(this._moduleName,`state changed to ${t}`)}addCustomEvent(t,n,a,o){this._exporter.addCustomEvent({at:typeof t=="object"?t.toJSON():t,category:n,name:a,description:o})}async registerToPCEvents(){const{pc:t}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const n=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${n.length} devices found`,"Media Devices state")}catch{dr(this._moduleName,"can't get devices")}},t){t.oniceconnectionstatechange=()=>{const a=t.iceConnectionState;a===Ki.CONNECTED||a===Ki.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===Ki.DISCONNECTED||a===Ki.FAILED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===Ki.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},t.onicegatheringstatechange=()=>{const a=t.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",a,"ICE gathering state")},t.ontrack=a=>{this.addCustomEvent(new Date().toJSON(),"call",`${a.track.kind}track`,"MediaStreamTrack received")},t.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const n=t.getReceivers();if(n&&n.length>0){const a=n[0],{transport:o}=a;if(o){const{iceTransport:s}=o;s&&(s.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class sE{constructor(t){this._id=t.pname&&t.pname.substr(0,12).padEnd(12," ")||Dv(),this._moduleName=this._id,Rn(this._moduleName,"probe created"),this._config=t,this._collector=new tE(this._config,this._id)}set onreport(t){t?this._collector.registerCallback("onreport",t):this._collector.unregisterCallback("onreport")}set onticket(t){t?this._collector.registerCallback("onticket",t):this._collector.unregisterCallback("onticket")}get id(){return this._id}get pname(){return this._config.pname}get cid(){return this._config.cid}get uid(){return this._config.uid}get state(){return this._collector.state}set state(t){this._collector.state=t}addCustomEvent(t,n,a,o=new Date().toJSON()){this._collector.addCustomEvent(o,n,t,a)}get isRunning(){return this._collector.state===gs.RUNNING}get isIdle(){return this._collector.state===gs.IDLE}updateUserId(t){this._config.uid=t,this._collector.updateConfig(this._config)}updateCallId(t){this._config.cid=t,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){wa(this._moduleName,"probe is already running");return}this._collector.start()}stop(t=!1){this.isRunning&&this._collector.stop(t)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const Rt="engine ";class nE{constructor(t){this._config=t,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},Rn(Rt,`configured for probing every ${this._config.refreshEvery}ms`),Rn(Rt,`configured for starting after ${this._config.startAfter}ms`),Rn(Rt,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Pe(Rt,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(t=>t.isRunning)}get isIdle(){return this._probes.every(t=>t.isIdle)}addNewProbe(t,n){if(!t)throw new Error("undefined peer connection");const a=wv(t,n,this._config),o=new sE(a);return this._probes.push(o),Pe(Rt,`${this._probes.length} probes registered`),o}removeExistingProbe(t){if(!t)throw new Error("undefined probe");t.state===gs.RUNNING&&t.stop(),this._probes=this._probes.filter(n=>t.id!==n.id)}async start(){const t=()=>{this._probes.forEach(s=>s.start())},n=async()=>Promise.all(this._probes.map(s=>s.takeReferenceStats())),a=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,o=async()=>{const s=Rv(),r=this._probes.filter(d=>d.isRunning);for(const d of r){const h=await d.collectStats();h&&s.probes.push(h),Pe(Rt,`got probe ${d.id}`),await kf(0)}return s.delta_time_to_measure_probes_ms=Sn(s.probes,"experimental","time_to_measure_ms"),s.delta_KBytes_in=Sn(s.probes,"data","delta_KBytes_in"),s.delta_KBytes_out=Sn(s.probes,"data","delta_KBytes_out"),s.delta_kbs_in=Sn(s.probes,"data","delta_kbs_in"),s.delta_kbs_out=Sn(s.probes,"data","delta_kbs_out"),s.total_time_decoded_in=Sn(s.probes,"video","total_time_decoded_in"),s.total_time_encoded_out=Sn(s.probes,"video","total_time_encoded_out"),s};for(Pe(Rt,"starting to collect"),t(),Pe(Rt,"generating reference reports..."),await n(),Pe(Rt,"reference reports generated"),this._startedTime=Date.now();a();)if(Pe(Rt,`wait ${this._config.refreshEvery}ms before collecting`),await kf(this._config.refreshEvery),a()){Pe(Rt,"collecting...");const s=Date.now(),r=await o(),d=Date.now();r.delta_time_consumed_to_measure_ms=d-s,this.fireOnReports(r),Pe(Rt,"collected")}Pe(Rt,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(t){const n=a=>{this._probes.forEach(o=>{o.stop(a)})};Rn(Rt,"stop collecting"),n(t)}registerCallback(t,n,a){t in this._callbacks?(this._callbacks[t]={callback:n,context:a},Pe(Rt,`registered callback '${t}'`)):dr(Rt,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],Pe(this._moduleName,`unregistered callback '${t}'`)):dr(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReports(t){this._callbacks.onresult&&t.probes.length>0&&wu(this._callbacks.onresult.callback,this._callbacks.onresult.context,t)}}const rE="interface ";class iE{constructor(t){this._config=Ov(t),Rn(rE,`welcome to ${this._config.name} version ${this._config.version}`),gv(this._config.verbose||!1),this._engine=new nE(this._config)}setupLogLevel(t){Tv(t)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(t,n){return this._engine.addNewProbe(t,n)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(t){this._engine.removeExistingProbe(t)}set onresult(t){t?this._engine.registerCallback("onresult",t):this._engine.unregisterCallback("onresult")}}function lE(c,t){return Object.keys(c).filter(n=>t.includes(n)).reduce((n,a)=>{const o=a;return{...n,[o]:c[o]}},{})}const aE=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"];class oE{constructor(t){this.intervals={},this.emitInterval=t.emitInterval||200,this.onChangeFunction=t.onChangeFunction}start(t,n){t&&t.getTracks().length&&requestAnimationFrame(()=>this.beginCalculation(t,n))}stop(t){this.clearVolumeInterval(t)}clearVolumeInterval(t){clearInterval(this.intervals[t]),delete this.intervals[t]}clearAllIntervals(){Object.keys(this.intervals).forEach(t=>{clearInterval(this.intervals[t])}),this.intervals={}}beginCalculation(t,n){this.clearVolumeInterval(n);const a=Cn.createAnalyser(),o=Cn.createMediaStreamSource(t),s=Cn.createScriptProcessor(2048,1,1);a.smoothingTimeConstant=.8,a.fftSize=1024,o.connect(a),a.connect(s),s.connect(Cn.destination),this.intervals[n]=setInterval(()=>{const r=new Uint8Array(a.frequencyBinCount);a.getByteFrequencyData(r);let d=0;const h=r.length;for(let g=0;g<h;g++)d+=r[g];const _=d/h;this.onChangeFunction(n,_)},this.emitInterval)}}const _a={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},uE=0;class cE{constructor(t){this.isAutoAnswer=!1,this.muteWhenJoinEnabled=!1,this.isDNDEnabled=!1,this.muted=!1,this.microphoneInputLevelValue=1,this.speakerVolumeValue=1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.availableMediaDevices=[],this.selectedMediaDevices={input:"default",output:"default"},this.callStatus={},this.callTime={},this.callMetrics={},this.timeIntervals={},this.metricConfig={refreshEvery:1e3},this.activeStreamValue=null,this.initialStreamValue=null,this.context=t,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new oE({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices()}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(t){this.currentActiveRoomIdValue=t,this.context.emit("currentActiveRoomChanged",t)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(t){this.isCallAddingInProgress=t,this.context.emit("callAddingInProgressChanged",t)}get muteWhenJoin(){return this.muteWhenJoinEnabled}get isDND(){return this.isDNDEnabled}get speakerVolume(){return this.speakerVolumeValue}get microphoneInputLevel(){return this.microphoneInputLevelValue}get getActiveCalls(){return this.activeCalls}get hasActiveCalls(){return Object.values(this.extendedCalls).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audiooutput")}get getUserMediaConstraints(){return wh()?{video:!1,audio:!0}:{audio:{deviceId:{exact:this.selectedMediaDevices.input}},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(t){this.availableMediaDevices=t,this.context.emit("changeAvailableDeviceList",t)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const t=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(t)}async initializeMediaDevices(){const t=localStorage.getItem(_a.SELECTED_INPUT_DEVICE)||"default",n=localStorage.getItem(_a.SELECTED_OUTPUT_DEVICE)||"default";try{const a=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),o=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(o),await this.setMicrophone(t),await this.setSpeaker(n),navigator.mediaDevices.addEventListener("devicechange",async()=>{const s=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(s)}),a.getTracks().forEach(s=>s.stop())}catch(a){console.error(a)}}setCallTime(t){const n={...t};delete n.callId,this.callTime={...this.callTime,[t.callId]:n},this.context.emit("changeCallTime",this.callTime)}removeCallTime(t){const n={...this.callTime};delete n[t],this.callTime={...n},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(t,n){this.timeIntervals={...this.timeIntervals,[t]:n}}removeTimeInterval(t){const n={...this.timeIntervals};n[t]&&(clearInterval(n[t]),delete n[t],this.timeIntervals={...n})}stopCallTimer(t){this.removeTimeInterval(t),this.removeCallTime(t)}emitVolumeChange(t,n){this.context.emit("changeCallVolume",{callId:t,volume:n})}setMetricsConfig(t){this.metricConfig={...this.metricConfig,...t}}sendDTMF(t,n){if(!/^[A-D0-9]+$/g.test(n))throw new Error("Not allowed character in DTMF input");this.extendedCalls[t].sendDTMF(n)}setIsMuted(t){this.muted=t,this.context.emit("changeIsMuted",t)}processMute(t){const n=this.currentActiveRoomId;this.setIsMuted(t),this.initialStreamValue.getTracks().forEach(a=>a.enabled=!t),this.roomReconfigure(n)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:t,toHold:n,automatic:a}){const o=this.extendedCalls[t];o._automaticHold=a??!1,await new Promise(d=>{const h=()=>{o.putOnHoldTimestamp=n?Date.now():void 0,d()};n?o.hold({},h):o.unhold({},h)}),this.updateCall(o);const r=Object.values(this.extendedCalls).filter(d=>d.roomId===this.currentActiveRoomId&&(n?t!==d._id:!0));r.length>1&&await this.doConference(r)}holdCall(t,n=!1){return this.processHold({callId:t,automatic:n,toHold:!0})}unholdCall(t){return this.processHold({callId:t,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(t=>t.direction==="outgoing"&&t.status===uE).forEach(t=>this.terminateCall(t._id))}answerCall(t){const n=this.extendedCalls[t];this.cancelAllOutgoingUnanswered(),n.answer(this.sipOptions),this.updateCall(n),this.setActiveRoom(n.roomId),n.connection.addEventListener("track",a=>{this.triggerAddStream(a,n)})}async moveCall(t,n){this.updateCallStatus({callId:t,isMoving:!0}),await this.processRoomChange({callId:t,roomId:n}),this.updateCallStatus({callId:t,isMoving:!1})}updateCall(t){this.activeCalls[t._id]=Nf(t),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(t){const a={...this.activeRooms[t.roomId],...t};this.activeRooms={...this.activeRooms,[t.roomId]:{...a}},this.context.emit("updateRoom",{room:a,roomList:this.activeRooms})}hasAutoAnswerHeaders(t){const n=/answer-after=0/,o=t.request.getHeader("Call-Info");return o&&n.test(o)}addCall(t,n=!0){this.activeCalls={...this.activeCalls,[t._id]:Nf(t)},this.extendedCalls[t._id]=t,n&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(t){this.callStatus={...this.callStatus,[t]:{isMoving:!1,isTransferring:!1,isMerging:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(t){const a={...{...this.callStatus[t.callId]}};t.isMoving!==void 0&&(a.isMoving=t.isMoving),t.isTransferring!==void 0&&(a.isTransferring=t.isTransferring),t.isMerging!==void 0&&(a.isMerging=t.isMerging),this.callStatus={...this.callStatus,[t.callId]:{...a}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(t){const n={...this.callStatus};delete n[t],this.callStatus={...n},this.context.emit("changeCallStatus",this.callStatus)}addRoom(t){this.activeRooms={...this.activeRooms,[t.roomId]:t},this.context.emit("addRoom",{room:t,roomList:this.activeRooms})}getActiveStream(){const t=Pf(this.initialStreamValue,this.microphoneInputLevel*2);return t.getTracks().forEach(n=>n.enabled=!this.isMuted),this.setActiveStream(t),t}async setMicrophone(t){if(!this.getInputDeviceList.find(({deviceId:a})=>a===t)||(this.setSelectedInputDevice(t),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const n=Object.values(this.extendedCalls).filter(a=>a.roomId===this.currentActiveRoomId);n.length===1?Object.values(n).forEach(async a=>{const o=this.getActiveStream();a.connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.updateCall(a)}):await this.doConference(n)}setActiveStream(t){this.activeStream&&this.stopVUMeter("origin"),this.setupVUMeter(t,"origin"),this.activeStreamValue=t,this.context.emit("changeActiveStream",t)}async setSpeaker(t){if(!this.getOutputDeviceList.find(({deviceId:o})=>o===t))return;this.setSelectedOutputDevice(t);const n=Object.values(this.extendedCalls);if(n.length===0)return;const a=n.filter(o=>o.roomId===this.currentActiveRoomId);a.length===1?n.forEach(o=>{var s;(s=o.audioTag)==null||s.setSinkId(t),this.updateCall(o)}):await this.doConference(a)}removeRoom(t){const n={...this.activeRooms},a={...n[t]};delete n[t],this.activeRooms={...n},this.context.emit("removeRoom",{room:a,roomList:this.activeRooms})}deleteRoomIfEmpty(t){t!==void 0&&Object.values(this.extendedCalls).filter(n=>n.roomId===t).length===0&&(this.removeRoom(t),this.currentActiveRoomId===t&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(t){this.muted?t.mute({audio:!0}):t.unmute({audio:!0})}async roomReconfigure(t){var a;if(t===void 0)return;const n=Object.values(this.extendedCalls).filter(o=>o.roomId===t);if(this.currentActiveRoomId===t?n.forEach(o=>{o.audioTag&&(this.muteReconfigure(o),o.audioTag.muted=!1,this.updateCall(o))}):n.forEach(o=>{o.audioTag&&(o.audioTag.muted=!0,this.updateCall(o))}),n.length===0)this.deleteRoomIfEmpty(t);else if(n.length===1&&this.currentActiveRoomId!==t)n[0].isOnHold().local||await this.holdCall(n[0].id,!0);else if(n.length===1&&this.currentActiveRoomId===t){if(n[0].isOnHold().local&&n[0]._automaticHold&&await this.unholdCall(n[0].id),n[0].connection&&((a=n[0].connection)!=null&&a.getSenders()[0])){const o=this.getActiveStream();await n[0].connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.muteReconfigure(n[0])}}else n.length>1&&await this.doConference(n)}async doConference(t){const n=[];t.forEach(a=>{a!=null&&a.connection.getReceivers().forEach(o=>{n.push(o.track)})}),await pv.forEach(t,async a=>{var r;if(a==null)return;const o=new MediaStream,s=Cn.createMediaStreamDestination();if(a.connection.getReceivers().forEach(d=>{n.forEach(h=>{o.addTrack(d.track),d.track.id!==h.id&&Cn.createMediaStreamSource(new MediaStream([h])).connect(s)})}),t[0].roomId===this.currentActiveRoomId){const d=this.getActiveStream();Cn.createMediaStreamSource(d).connect(s)}(r=a.connection)!=null&&r.getSenders()[0]&&(await a.connection.getSenders()[0].replaceTrack(s.stream.getTracks()[0]),this.muteReconfigure(a))})}processCallerMute(t,n){const a=this.extendedCalls[t];a&&a.connection.getReceivers().length&&(a.localMuted=n,a.connection.getReceivers().forEach(o=>{o.track.enabled=!n}),this.updateCall(a))}muteCaller(t){this.processCallerMute(t,!0)}unmuteCaller(t){this.processCallerMute(t,!1)}terminateCall(t){const n=this.extendedCalls[t];n._status!==8&&n.terminate()}transferCall(t,n){if(n.toString().length===0)return new Error("Target must be passed");const a=this.extendedCalls[t];if(!a._is_confirmed&&!a._is_canceled){const o=`sip:${n}@${this.context.sipDomain}`;a.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${o}`]});return}this.updateCallStatus({callId:t,isTransferring:!0}),a.refer(`sip:${n}@${this.context.sipDomain}`),this.updateCall(a)}mergeCall(t){const n=Object.values(this.extendedCalls).filter(s=>s.roomId===t);if(n.length!==2)return;const a=n[0],o=n[1];!a||!o||(this.updateCallStatus({callId:a._id,isMerging:!0}),this.updateCallStatus({callId:o._id,isMerging:!0}),a.refer(o.remote_identity.uri.toString(),{replaces:o}),this.updateCall(a))}mergeCallByIds(t,n){const a=Object.values(this.extendedCalls).find(s=>s._id===t),o=Object.values(this.extendedCalls).find(s=>s._id===n);if(!a||!o)throw new Error("Call ID is not provided");this.updateCallStatus({callId:t,isMerging:!0}),this.updateCallStatus({callId:n,isMerging:!0}),a.refer(o.remote_identity.uri.toString(),{replaces:o}),this.updateCall(a)}setDND(t){this.isDNDEnabled=t,this.context.emit("changeIsDND",t)}startCallTimer(t){this.removeTimeInterval(t);const n={callId:t,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(n);const a=setInterval(()=>{const o={...this.callTime[t]},s=hv(o);this.setCallTime({callId:t,...s})},1e3);this.setTimeInterval(t,a)}async setActiveRoom(t){const n=this.currentActiveRoomId;t!==n&&(this.currentActiveRoomId=t,await this.roomReconfigure(n),await this.roomReconfigure(t))}getNewRoomId(){const t=Object.keys(this.activeRooms);return t.length===0?1:parseInt(t.sort()[t.length-1])+1}async setupCall(t){var _,g;const n=t.session;if(this.getActiveCalls[n.id]!==void 0)return;const o=this.getNewRoomId(),s={started:new Date,incomingInProgress:!1,roomId:o};n.direction==="incoming"?(this.context.logger.log("New incoming call from",(g=(_=n._remote_identity)==null?void 0:_._uri)==null?void 0:g._user),s.incomingInProgress=!0,this.context.subscribe(Xt.CALL_CONFIRMED,T=>{n.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:o}),this.startCallTimer(n.id))}),this.context.subscribe(Xt.CALL_FAILED,T=>{n.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:o}),this.deleteRoomIfEmpty(o))})):n.direction==="outgoing"&&(n.once("confirmed",()=>{this.startCallTimer(n.id)}),this.startCallTimer(n.id));const r=n,d=this.hasAutoAnswerHeaders(t),h=r.direction==="incoming"&&!this.hasActiveCalls&&(d||this.autoAnswer);r.roomId=o,r.localMuted=!1,r.autoAnswer=h,h?this.addCall(r,!1):this.addCall(r),this.addCallStatus(n.id),this.addRoom(s),h&&this.answerCall(r._id)}removeCall(t){const n={...this.activeCalls};delete n[t],this.activeCalls={...n};const a={...this.extendedCalls};delete a[t],this.extendedCalls={...a},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(t){var o;const n=this.extendedCalls[t._id];this.stopVUMeter("origin"),(o=n.connection)==null||o.getSenders().forEach(s=>{s.track.stop()});const a=n.roomId;this.removeCall(t._id),this.roomReconfigure(a)}async newRTCSessionCallback(t){const n=t.session;if(this.isDND){n.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(this.context.triggerListener({listenerType:Xt.NEW_CALL,session:n,event:t}),n.on("ended",a=>{var s,r,d;this.stopVUMeter(n.id),this.context.logger.log("Session ended for",(r=(s=n._remote_identity)==null?void 0:s._uri)==null?void 0:r._user),this.context.triggerListener({listenerType:Xt.CALL_ENDED,session:n,event:a});const o=this.getActiveCalls[n.id];o&&this.activeCallListRemove(o),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null)}),n.on("progress",a=>{var o,s;this.context.logger.log("Session in progress for",(s=(o=n._remote_identity)==null?void 0:o._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:Xt.CALL_PROGRESS,session:n,event:a})}),n.on("failed",a=>{var s,r,d;this.stopVUMeter(n.id),this.context.logger.log("Session failed for",(r=(s=n._remote_identity)==null?void 0:s._uri)==null?void 0:r._user),this.context.triggerListener({listenerType:Xt.CALL_FAILED,session:n,event:a}),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const o=this.getActiveCalls[n.id];o&&this.activeCallListRemove(o),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null)}),n.on("confirmed",a=>{var o,s;this.context.logger.log("Session confirmed for",(s=(o=n._remote_identity)==null?void 0:o._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:Xt.CALL_CONFIRMED,session:n,event:a}),this.updateCall(n),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(t),n.direction==="outgoing"){const a=this.getActiveCalls[n.id].roomId;this.setActiveRoom(a)}}setMuteWhenJoin(t){this.muteWhenJoinEnabled=t,this.context.emit("changeMuteWhenJoin",t)}setMicrophoneSensitivity(t){if(t<0||t>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=t,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(t){this.speakerVolumeValue=t,Object.values(this.extendedCalls).forEach(n=>{n.audioTag&&(n.audioTag.volume=t,this.updateCall(n))})}setAutoAnswer(t){this.isAutoAnswer=t}setSelectedInputDevice(t){localStorage.setItem(_a.SELECTED_INPUT_DEVICE,t),this.selectedMediaDevices.input=t,this.context.emit("changeActiveInputMediaDevice",t)}setSelectedOutputDevice(t){localStorage.setItem(_a.SELECTED_OUTPUT_DEVICE,t),this.selectedMediaDevices.output=t,this.context.emit("changeActiveOutputMediaDevice",t)}setCallMetrics(t){const n={...t};delete n.callId,this.callMetrics={...this.callMetrics,[t.callId]:n},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(t){const n={...this.callMetrics};delete n[t],this.callMetrics={...n},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(t){this.context.logger.log("LOG 1 before createProbe");const n=new iE(this.metricConfig),a=n.createProbe(t.connection,{cid:t._id});this.context.logger.log("LOG 2 after createProbe");const o=[];let s;a.onreport=r=>{this.context.logger.log("LOG 3 in onreport"),Object.entries(r.audio).forEach(([_,g])=>{g.direction==="inbound"&&!o.includes(_)&&(o.push(_),s=_)});const d=r.audio[s];if(!d)return;const h=lE(d,aE);h.callId=t._id,this.setCallMetrics(h)},this.context.subscribe(Xt.CALL_ENDED,r=>{r._id===t._id&&n.stopAllProbes()}),n.startAllProbes()}setupVUMeter(t,n){this.VUMeter.start(t,n)}stopVUMeter(t){this.VUMeter.stop(t)}async setupStream(){const t=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach(n=>n.stop()),this.initialStreamValue=null),this.initialStreamValue=t}async triggerAddStream(t,n){this.context.logger.log("LOG triggerAddStream 1"),this.setIsMuted(this.muteWhenJoin||this.isMuted),this.initialStreamValue||await this.setupStream();const a=Pf(this.initialStreamValue,this.microphoneInputLevel*2),o=this.isMuted||this.muteWhenJoin;a.getTracks().forEach(r=>r.enabled=!o),this.setActiveStream(a),await n.connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.context.logger.log("LOG triggerAddStream 2");const s=new MediaStream([t.track]);zT(s,n,this.selectedOutputDevice,this.speakerVolume),this.setupVUMeter(s,n._id),this.context.logger.log("LOG triggerAddStream 3"),this.getCallQuality(n),this.updateCall(n)}initCall(t,n,a=!1){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`);const o=this.context.call(`sip:${t}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=o.id,n&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:o.id,roomId:this.currentActiveRoomId}),a)){const s=Object.values(this.extendedCalls).filter(r=>r.roomId===this.currentActiveRoomId&&r._id!==o.id);for(const r of s)this.holdCall(r._id,!0)}o.connection.addEventListener("track",s=>{this.triggerAddStream(s,o)})}async processRoomChange({callId:t,roomId:n}){const a=this.extendedCalls[t].roomId;this.extendedCalls[t].roomId=n;const o=this.extendedCalls[t];return this.updateCall(o),await this.setActiveRoom(n),Promise.all([this.roomReconfigure(a),this.roomReconfigure(n)]).then(()=>{this.deleteRoomIfEmpty(a),this.deleteRoomIfEmpty(n)})}}class fE{constructor(t){this.context=t}get sipOptions(){return{...this.context.options.sipOptions}}initCall(t,n){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${t}@${this.context.sipDomain}`,n,this.sipOptions)}stop(t={}){this.context.terminateJanusSessions(t)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(t){this.context.changeMediaConstraints(t)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class hE{constructor(t){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=t,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this.context))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(t){const n=this.extendedMessages[t];this.updateMSRPSession(n)}updateMSRPSession(t){this.activeMessages[t._id]=Uf(t),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(t){this.activeMessages={...this.activeMessages,[t._id]:Uf(t)},this.extendedMessages[t._id]=t,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(t,n){const a=this.msrpHistory[n.id]||[];a.push(t),this.msrpHistory={...this.msrpHistory,[n.id]:[...a]},this.context.emit("newMSRPMessage",{message:t,session:n})}messageTerminate(t){const n=this.extendedMessages[t];n._status!==8&&n.terminate()}addMessageSession(t){if(!t._id||this.getActiveMessages[t._id]!==void 0)return;const a=t;this.addMMSRPSession(a)}triggerMSRPListener({listenerType:t,session:n,event:a}){const o=this.context.listenersList[t];!o||!o.length||o.forEach(s=>{s(n,a)})}removeMMSRPSession(t){const n={...this.activeMessages};delete n[t],this.activeMessages={...n};const a={...this.extendedMessages};delete a[t],this.extendedMessages={...a},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(t){this.removeMMSRPSession(t._id)}newMSRPSessionCallback(t){const n=t.session;n.on("ended",a=>{this.triggerMSRPListener({listenerType:Xt.CALL_ENDED,session:n,event:a});const o=this.getActiveMessages[n.id];this.activeMessageListRemove(o)}),n.on("failed",a=>{this.triggerMSRPListener({listenerType:Xt.CALL_FAILED,session:n,event:a});const o=this.getActiveMessages[n.id];this.activeMessageListRemove(o)}),n.on("confirmed",a=>{this.triggerMSRPListener({listenerType:Xt.CALL_CONFIRMED,session:n,event:a}),this.updateMSRPSession(n)}),n.on("newMessage",a=>{this.addMSRPMessage(a,n)}),this.addMessageSession(n)}setIsMSRPInitializing(t){this.isMSRPInitializingValue=t,this.context.emit("isMSRPInitializingChanged",t)}initMSRP(t,n,a){if(t.length===0)return console.error("Target must be a valid string");const o=this.context.startMSRP(t,a);o.on("active",()=>{this.addMessageSession(o),o.sendMSRP(n),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(t,n){const a=this.extendedMessages[t];if(!a)throw new Error(`MSRP session with id ${t} doesn't exist!`);a.sendMSRP(n)}}const ou={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class kh{constructor(t){this.opensips=null,this.session=null,this.name=null,this.name=t}setOpensips(t){this.opensips=t}setSession(t){this.session=t}kill(){this.opensips.kill(this.name)}}class Mh extends kh{constructor(t,n){super(t),this._candidates=[],this._subscribeSent=!1,this._configureSent=!1,this._lastTrickleReceived=!1,this.type=n}connect(t={}){this.opaqueId=this.session.generateOpaqueId();const n=ke.cloneArray(t.extraHeaders),a={from_tag:this.session._from_tag};t.fromUserName&&(a.from_uri=new In("sip",t.fromUserName,this.session._ua.configuration.uri.host),n.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),t.fromDisplayName&&(a.from_display_name=t.fromDisplayName),n.push(`Contact: ${this.session._contact}`),n.push("Content-Type: application/json"),this.session._sessionTimers.enabled&&n.push(`Session-Expires: ${this.session._sessionTimers.defaultExpires}${this.session._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new yt.InitialOutgoingInviteRequest(this.session.target,this.session._ua,a,n),this._createRTCConnection(),this._sendInitialRequest()}getStream(){return this.stream}getConnection(){return this._connection}_createRTCConnection(){this._connection=new RTCPeerConnection({iceServers:[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}]});let t;this._connection.onicecandidate=n=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||n.candidate&&(this._candidates.push(n.candidate),clearTimeout(t),t=setTimeout(()=>{this._lastTrickleReceived=!0,this._subscribeSent&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})},500))}}addTracks(t){t.forEach(n=>{this._connection.addTrack(n)})}async _sendInitialRequest(){const t=new sl(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});if(await this.generateStream(),!this.stream||!this.stream.getTracks().length)return;this.addTracks(this.stream.getTracks());const n={audio:!1,video:!0};this.jsep_offer=await this._connection.createOffer(n),await this._connection.setLocalDescription(this.jsep_offer);const a={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},o=JSON.stringify(a);this._request.body=o,t.send()}_receiveInviteResponse(t){if(this._publisherSubscribeSent||!t.body)return;const n=JSON.parse(t.body);this.handleId=n.data.id;const a={janus:"message",body:{request:"join",room:this.session.room_id,ptype:"publisher",display:this.session.display_name+" (Screen Share)",opaque_id:this.opaqueId},handle_id:this.handleId},o=[this.session.getPTypeHeader(Pt.PUBLISHER)];this.session.sendRequest(L.SUBSCRIBE,{extraHeaders:o,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async s=>{var r,d,h,_;if(s.status_code===200){if(this._subscribeSent=!0,s.body)try{const g=JSON.parse(s.body)||{};((d=(r=g.plugindata)==null?void 0:r.data)==null?void 0:d.videoroom)==="joined"&&this.session.myFeedList.push(g.plugindata.data.id),(_=(h=g.plugindata)==null?void 0:h.data)!=null&&_.publishers&&this.session.receivePublishers(g)}catch(g){console.error(g)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}}}}),this._publisherSubscribeSent=!0}async _sendConfigureMessage(t){const n=this._candidates.map(r=>({janus:"trickle",candidate:r,handle_id:this.handleId,session_id:this.session.session_id})),o={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.session.getRecordFileName(),...t},jsep:this.jsep_offer,handle_id:this.handleId,session_id:this.session.session_id},trickles:[...n]},s=["Content-Type: application/json",this.session.getPTypeHeader(Pt.ICE)];this.session.sendRequest(L.INFO,{extraHeaders:s,body:JSON.stringify(o),eventHandlers:{onSuccessResponse:async r=>{this._configureSent=!0;const h=r.data.split(`\r
|
159
159
|
`),_=h[h.length-1],g=JSON.parse(_);await this._connection.setRemoteDescription(g.jsep),this._candidates=[]}}})}_sendDetach(){const t={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},n=[this.session.getPTypeHeader(Pt.DETACH)];this.session.sendRequest(L.INFO,{extraHeaders:n,body:JSON.stringify(t)}),this.session._ua.emit("pluginDetach",this.name)}async stopMedia(){this._connection&&(this._connection.close(),this._connection=null),this.stream&&(this.stream=null)}async stop(){await this.session.stopProcessPlugins(this.type);const t=this._connection.getSenders();t.forEach(n=>{const a=n.track;a&&a.stop()}),t.forEach(n=>{this._connection.removeTrack(n)}),await this.stopMedia(),this._sendDetach()}async generateStream(){throw new Error("generateStream method is not implemented")}}class Lh extends kh{constructor(t,n,a={}){super(t),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=a.immediate||!1,this.type=n}start(t){return t}stop(){throw new Error("stop method is not implemented")}async process(t){if(this.immediate){const n=await this.start(t);return this.running=!0,n}return t}async connect(){this.running=!0,await this.session.resyncPlugins(this.type)}terminate(){this.stop()}async kill(){this.stop(),this.running=!1,await this.session.resyncPlugins(this.type)}}class dE extends VT{constructor(t,n){if(!t.modules.length)throw new Error("options.modules should include at least 1 module");const a={...t.configuration,sockets:t.socketInterfaces.map(o=>new fv.WebSocketInterface(o))};super(a),this.initialized=!1,this.connected=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.activeConnection=!1,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],t.pnExtraHeaders&&Object.keys(t.pnExtraHeaders).length&&this.registrator().setExtraContactUriParams(t.pnExtraHeaders),this.options=t,this.modules=t.modules,n&&XT(n)&&(this.logger=n)}on(t,n){return super.on(t,n)}off(t,n){return super.off(t,n)}emit(t,n){return super.emit(t,n)}get sipDomain(){return this.options.sipDomain}use(t){if(this.newStreamPlugins.find(n=>n.name===t.name)||this.processStreamPlugins.find(n=>n.name===t.name))throw new Error(`Plugin with name ${t.name} already exists`);if(t instanceof Mh)t.setOpensips(this),this.newStreamPlugins.push(t);else if(t instanceof Lh)t.setOpensips(this),this.processStreamPlugins.push(t);else throw new Error("Wrong plugin instance")}getPlugin(t){return this.newStreamPlugins.find(n=>n.name===t)||this.processStreamPlugins.find(n=>n.name===t)}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(ou.AUDIO)&&(this.audio=new cE(this)),this.modules.includes(ou.MSRP)&&(this.msrp=new hE(this)),this.modules.includes(ou.VIDEO)&&(this.video=new fE(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.setConnected(!0),this.setReconnecting(!1),this.activeConnection=!0}),this.on(this.disconnectedEventName,()=>{this.isReconnecting||(this.setReconnecting(!0),this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.stop(),this.setInitialized(!1),this.setConnected(!1),this.activeConnection&&setTimeout(this.start.bind(this),5e3))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}disconnect(){this.activeConnection=!1,this.stop()}subscribe(t,n){const o=!this.listenersList[t]||!this.listenersList[t].length?[n]:[...this.listenersList[t],n];this.listenersList={...this.listenersList,[t]:o}}removeIListener(t){const n={...this.listenersList};delete n[t],this.listenersList={...n}}triggerListener({listenerType:t,session:n,event:a}){const o=this.listenersList[t];!o||!o.length||o.forEach(s=>{s(n,a)})}setInitialized(t){this.initialized=t,this.emit("ready",t)}setConnected(t){this.connected=t,this.emit("connection",t)}setReconnecting(t){this.isReconnecting=t,this.emit("reconnecting",t)}}exports.BaseNewStreamPlugin=Mh;exports.BaseProcessStreamPlugin=Lh;exports.default=dE;
|