@voicenter-team/opensips-js 1.0.87 → 1.0.88

Sign up to get free protection for your applications and to get access to all the features.
@@ -153,4 +153,4 @@ t=0 0
153
153
  m=message 2856 TCP/TLS/MSRP *
154
154
  a=accept-types:text/plain text/html
155
155
  a=path:${s.getHeader("Use-Path")} msrp://${this._ua._configuration.authorization_user}.${this._ua._configuration.realm}:2856/${this.auth_id};ws
156
- `),this._newMSRPSession("local",this._request),this._id=this._request.call_id+this._from_tag,console.log("dialog be",this._dialog),new Nf(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:t=>{this.onTransportError(),console.log(t)},onAuthenticated:t=>{this._request=t},onReceiveResponse:t=>{this._receiveInviteResponse(t),console.log("dialog af",this._dialog),t.status_code===200&&(t.parseSDP(!0),this._status=Ce.STATUS_CONFIRMED,this.target_addr=t.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=Ce.STATUS_INVITE_SENT}terminate(s={}){console.log("terminate",this);const r=s.cause||j.causes.BYE,o=ke.cloneArray(s.extraHeaders),a=s.body;let t,n=s.status_code,p=s.reason_phrase;if(this._status===Ce.STATUS_TERMINATED)throw new bs.InvalidStateError(this._status);switch(this.status="terminated",this._status){case Ce.STATUS_NULL:case Ce.STATUS_INVITE_SENT:case Ce.STATUS_1XX_RECEIVED:if(n&&(n<200||n>=700))throw new TypeError(`Invalid status_code: ${n}`);n&&(p=p||j.REASON_PHRASE[n]||"",t=`SIP ;cause=${n} ;text="${p}"`),this._status===Ce.STATUS_NULL||this._status===Ce.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=t):this._status===Ce.STATUS_1XX_RECEIVED&&this._request.cancel(t),this._status=Ce.STATUS_CANCELED,console.log("failed 1"),this._failed("local",null,j.causes.CANCELED);break;case Ce.STATUS_WAITING_FOR_ANSWER:case Ce.STATUS_ANSWERED:if(n=n||480,console.log("REPLY 480"),n<300||n>=700)throw new TypeError(`Invalid status_code: ${n}`);this._request.reply(n,p,o,a),console.log("failed 2"),this._failed("local",null,j.causes.REJECTED);break;case Ce.STATUS_WAITING_FOR_ACK:case Ce.STATUS_CONFIRMED:if(p=s.reason_phrase||j.REASON_PHRASE[n]||"",n&&(n<200||n>=700))throw new TypeError(`Invalid status_code: ${n}`);if(n&&o.push(`Reason: SIP ;cause=${n}; text="${p}"`),this._status===Ce.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==$t.C.STATUS_TERMINATED){const _=this._dialog;this.receiveRequest=({method:d})=>{d===j.ACK&&(this.sendRequest(j.BYE,{extraHeaders:o,body:a}),_.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===$t.C.STATUS_TERMINATED&&(this.sendRequest(j.BYE,{extraHeaders:o,body:a}),_.terminate())}),this._ended("local",null,r),this._dialog=_,this._ua.newDialog(_)}else console.log("here it is"),this.sendRequest(j.BYE,{extraHeaders:o,body:a}),this._ended("local",null,r)}}sendRequest(s,r){return this._dialog.sendRequest(s,r)}authenticate(s){this.status="auth";let r=new Hn("");r.method="AUTH",r.addHeader("To-Path",`msrp://${this._ua._configuration.realm}:2856;ws`),r.addHeader("From-Path",`msrp://${this.credentials.username}.${this.credentials.realm}:2856/${this.auth_id};ws`),s&&r.addHeader("Authorization",s.toString());let o=r.toString();console.log(o);let a=[];for(var t=0;t<o.length;t++)a.push(o.charCodeAt(t).toString(16));console.log(a),this._connection.send(r.toString())}onmessage(s){console.log("onmessage",s);const r=new Hn(s.data);if(this.status==="auth"&&r.code===401){const o=this.parseAuth(r.getHeader("WWW-Authenticate")),a=new ym(this.credentials);a.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},o,ke.createRandomToken(12)),this.authenticate(a)}this.status==="auth"&&r.code===200&&this._direction==="outgoing"?(this.my_addr.push(r.getHeader("To-Path")),this.my_addr.push(r.getHeader("Use-Path")),this.status="active",this.inviteParty(r)):this.status==="auth"&&r.code===200&&this._direction==="incoming"?(this.my_addr.push(r.getHeader("To-Path")),this.my_addr.push(r.getHeader("Use-Path")),this.status="active",this.acceptParty(r),this.emit("confirmed")):r.method==="SEND"&&(this._sendOk(r),this._sendReport(r),r.direction="incoming",this.emit("newMessage",r),this._msgHistory.push(r),this.emit("msgHistoryUpdate",this._msgHistory),console.log("======================================================================")),r.code===480&&this._close()}onclose(){console.log("close")}onopen(){const s=new RTCPeerConnection({iceServers:[]});s.createDataChannel(""),s.createOffer().then(s.setLocalDescription.bind(s)),s.onicecandidate=r=>{if(!r||!r.candidate||!r.candidate.candidate)return;const o=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,a=r.candidate.candidate.match(o);this.my_ip=a&&a[1],s.onicecandidate=()=>{},this.authenticate(null)}}onerror(s){console.log(s)}_receiveInviteResponse(s){if(console.log("resp0000000000000",s),this._dialog&&s.status_code>=200&&s.status_code<=299)if(console.log("200000000000000"),this._dialog.id.call_id===s.call_id&&this._dialog.id.local_tag===s.from_tag&&this._dialog.id.remote_tag===s.to_tag){this.sendRequest(j.ACK);return}else{const r=new io(this,s,"UAC");if(r.error!==void 0){console.log(r.error);return}this.sendRequest(j.ACK),this.sendRequest(j.BYE);return}if(this._is_canceled){s.status_code>=100&&s.status_code<200?this._request.cancel(this._cancel_reason):s.status_code>=200&&s.status_code<299&&this._acceptAndTerminate(s);return}if(!(this._status!==Ce.STATUS_INVITE_SENT&&this._status!==Ce.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(s.status_code):this._status=Ce.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(s.status_code):{if(!s.to_tag){console.log("1xx response received without to tag");break}if(s.hasHeader("contact")&&!this._createDialog(s,"UAC",!0))break;if(this._status=Ce.STATUS_1XX_RECEIVED,!s.body){this._progress("remote",s);break}const r={originator:"remote",type:"answer",sdp:s.body};console.log('emit "sdp"'),this.emit("sdp",r);const o=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>this._progress("remote",s)).catch(a=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)});break}case/^2[0-9]{2}$/.test(s.status_code):{if(console.log("maybe here???"),this._status=Ce.STATUS_CONFIRMED,!s.body){this._acceptAndTerminate(s,400,j.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",s,j.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(s,"UAC"))break;const r={originator:"remote",type:"answer",sdp:s.body};console.log('emit "sdp"'),this.emit("sdp",r),new RTCSessionDescription({type:"answer",sdp:r.sdp}),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(o=>this._connection.setLocalDescription(o)).catch(o=>{this._acceptAndTerminate(s,500,o.toString()),console.log("failed 4"),this._failed("local",s,j.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(s),this._accepted("remote",s),this.sendRequest(j.ACK),this._confirmed("local",null)});break}default:{const r=ke.sipErrorCause(s.status_code);console.log("failed 5"),this._failed("remote",s,r)}}}sendMSRP(s){const r=new Hn("");r.method="SEND",r.addHeader("To-Path",`${this.my_addr[1]} ${this.target_addr[1]} ${this.target_addr[0]}`),r.addHeader("From-Path",`${this.my_addr[0]}`),r.addHeader("Message-ID",ke.createRandomToken(10)),r.addHeader("Byte-Range","1-25/25"),r.addHeader("Content-Type","text/plain"),r.addHeader("Success-Report","yes"),r.addHeader("Failure-Report","yes"),r.body=s;let o=r.toString();console.log(o);let a=[];for(var t=0;t<o.length;t++)a.push(o.charCodeAt(t).toString(16));console.log(a),this._connection.send(r.toString()),r.direction="outgoing",this.emit("newMessage",r),this._msgHistory.push(r),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(s){let r=s.ident,o=s.getHeader("Message-ID"),a=new Hn("");a.method="200 OK",a.addHeader("To-Path",`${this.my_addr[1]}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",o),a.ident=r;let t=a.toString();console.log(t);let n=[];for(var p=0;p<t.length;p++)n.push(t.charCodeAt(p).toString(16));console.log(n),this._connection.send(a.toString())}_sendReport(s){let r=s.ident,o=s.getHeader("Message-ID"),a=new Hn("");a.method="REPORT",a.addHeader("To-Path",`${s.getHeader("From-Path")}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",o),a.addHeader("Byte-Range","1-25/25"),a.addHeader("Status","000 200 OK"),a.ident=r;let t=a.toString();console.log(t);let n=[];for(var p=0;p<t.length;p++)n.push(t.charCodeAt(p).toString(16));console.log(n),this._connection.send(a.toString())}parseAuth(s){const r={},o=s.replace("Digest","").split(",");for(const a of o){const t=a.trim().split("=");r[t[0]]=t[1].match('^"(.+)"$')[1]}return r}init_incoming(s,r){let o;const a=s.hasHeader("Content-Type")?s.getHeader("Content-Type").toLowerCase():void 0;if(s.body&&a!=="application/sdp"){s.reply(415);return}if(this._status=Ce.STATUS_INVITE_RECEIVED,this._from_tag=s.from_tag,this._id=s.call_id+this._from_tag,this._request=s,this._contact=this._ua.contact.toString(),s.hasHeader("expires")&&(o=s.getHeader("expires")*1e3),s.to_tag=ke.newTag(),!this._createDialog(s,"UAS",!0)){s.reply(500,"Missing Contact header field");return}s.body?this._late_sdp=!1:this._late_sdp=!0,this._status=Ce.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{s.reply(408),console.log("failed 6"),this._failed("local",null,j.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),o&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Ce.STATUS_WAITING_FOR_ANSWER&&(s.reply(487),console.log("failed 7"),this._failed("system",null,j.causes.EXPIRES))},o)),this._direction="incoming",this._local_identity=s.to,this._remote_identity=s.from,r&&r(this),s.parseSDP(!0),this.target_addr=s.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",s),this._status!==Ce.STATUS_TERMINATED&&(s.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(s,r,o){this.emit("_failed",{originator:s,message:r||null,cause:o}),this._close(),this.emit("failed",{originator:s,message:r||null,cause:o})}_close(){if(console.log("CLOSE SESSION"),this._status!==Ce.STATUS_TERMINATED){if(this._status=Ce.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(s){console.log("close() | error closing the RTCPeerConnection: %o",s)}for(const s in this._timers)Object.prototype.hasOwnProperty.call(this._timers,s)&&clearTimeout(this._timers[s]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const s in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,s)&&(this._earlyDialogs[s].terminate(),delete this._earlyDialogs[s]);for(const s in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,s)&&delete this._referSubscribers[s];this._ua.destroyMSRPSession(this)}}_createDialog(s,r,o){const a=r==="UAS"?s.to_tag:s.from_tag,t=r==="UAS"?s.from_tag:s.to_tag,n=s.call_id+a+t;let p=this._earlyDialogs[n];if(o)return p?!0:(p=new io(this,s,r,io.C.STATUS_EARLY),p.error?(console.log("failed 8"),this._failed("remote",s,j.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[n]=p,!0));{if(this._from_tag=s.from_tag,this._to_tag=s.to_tag,p)return p.update(s,r),this._dialog=p,delete this._earlyDialogs[n],!0;const _=new io(this,s,r);return _.error?(console.log("failed 9"),this._failed("remote",s,j.causes.INTERNAL_ERROR),!1):(this._dialog=_,!0)}}_newMSRPSession(s,r){this._ua.newMSRPSession(this,{originator:s,session:this,request:r})}_progress(s,r){this.emit("progress",{originator:s,response:r||null})}isEnded(){switch(this._status){case Ce.STATUS_CANCELED:case Ce.STATUS_TERMINATED:return!0;default:return!1}}_accepted(s,r){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:s,response:r||null})}_confirmed(s,r){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:s,ack:r||null})}_ended(s,r,o){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:s,message:r||null,cause:o})}_handleSessionTimersInIncomingResponse(s){if(!this._sessionTimers.enabled)return;let r;s.session_expires&&s.session_expires>=j.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=s.session_expires,r=s.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,r="uac"),this._sessionTimers.refresher=r==="uac",this._runSessionTimer()}receiveRequest(s){if(console.log("receiveRequest()"),s.method===j.CANCEL)(this._status===Ce.STATUS_WAITING_FOR_ANSWER||this._status===Ce.STATUS_ANSWERED)&&(this._status=Ce.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",s,j.causes.CANCELED));else switch(s.method){case j.ACK:if(this._status!==Ce.STATUS_WAITING_FOR_ACK)return;if(this._status=Ce.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!s.body){this.terminate({cause:j.causes.MISSING_SDP,status_code:400});break}const r={originator:"remote",type:"answer",sdp:s.body};console.log('emit "sdp"'),this.emit("sdp",r);const o=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>{this._is_confirmed||this._confirmed("remote",s)}).catch(a=>{this.terminate({cause:j.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})}else this._is_confirmed||this._confirmed("remote",s);break;case j.BYE:this._status===Ce.STATUS_CONFIRMED||this._status===Ce.STATUS_WAITING_FOR_ACK?(s.reply(200),this._ended("remote",s,j.causes.BYE)):this._status===Ce.STATUS_INVITE_RECEIVED||this._status===Ce.STATUS_WAITING_FOR_ANSWER?(s.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",s,j.causes.BYE)):s.reply(403,"Wrong Status");break;case j.INVITE:this._status===Ce.STATUS_CONFIRMED?s.hasHeader("replaces")?this._receiveReplaces(s):this._receiveReinvite(s):s.reply(403,"Wrong Status");break;case j.INFO:this._status===Ce.STATUS_1XX_RECEIVED||this._status===Ce.STATUS_WAITING_FOR_ANSWER||this._status===Ce.STATUS_ANSWERED||this._status===Ce.STATUS_WAITING_FOR_ACK||this._status===Ce.STATUS_CONFIRMED?(s.hasHeader("Content-Type")?s.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new Ja(this).init_incoming(s):s.reply(415):s.reply(403,"Wrong Status");break;case j.UPDATE:this._status===Ce.STATUS_CONFIRMED?this._receiveUpdate(s):s.reply(403,"Wrong Status");break;case j.REFER:this._status===Ce.STATUS_CONFIRMED?this._receiveRefer(s):s.reply(403,"Wrong Status");break;case j.NOTIFY:this._status===Ce.STATUS_CONFIRMED?this._receiveNotify(s):s.reply(403,"Wrong Status");break;default:s.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:j.causes.CONNECTION_ERROR,cause:j.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:j.causes.REQUEST_TIMEOUT,cause:j.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:j.causes.DIALOG_ERROR,cause:j.causes.DIALOG_ERROR})}}const ft=console,Ns={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},fT=nT;class _T extends fT{constructor(s){super(s),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[]}call(s,r){return super.call(s,r)}joinVideoCall(s,r,o){ft.debug("call()");const a=new go(this);return a.connect(s,r,o),a}_loadConfig(s){try{Qr.load(this._configuration,s)}catch(a){throw a}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=Ln.newUUID()),this._configuration.jssip_id=Ln.createRandomToken(5);const r=this._configuration.uri.clone();r.user=null,this._configuration.hostport_params=r.toString().replace(/^sip:/i,"");try{this._transport=new Og(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=hT.bind(this),this._transport.onconnect=dT.bind(this),this._transport.ondisconnect=pT.bind(this),this._transport.ondata=mT.bind(this)}catch(a){throw ft.warn(a),new bs.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 a=this._configuration.uri.clone();a.user=null,a.clearParams(),a.clearHeaders(),this._configuration.registrar_server=a}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new $n("sip",Ln.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(a={}){const t=a.anonymous||null,n=a.outbound||null;let p="<";return t?p+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":p+=this.pub_gruu||this.uri.toString(),n&&(t?!this.temp_gruu:!this.pub_gruu)&&(p+=";ob"),p+=">",p}};const o=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const a in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,a)&&(o.indexOf(a)!==-1?Object.defineProperty(this._configuration,a,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,a,{writable:!1,configurable:!1}));ft.debug("configuration parameters after validation:");for(const a in this._configuration)if(Object.prototype.hasOwnProperty.call(Qr.settings,a))switch(a){case"uri":case"registrar_server":ft.debug(`- ${a}: ${this._configuration[a]}`);break;case"password":case"ha1":case"authorization_jwt":ft.debug(`- ${a}: NOT SHOWN`);break;default:ft.debug(`- ${a}: ${JSON.stringify(this._configuration[a])}`)}}newMSRPSession(s,r){s.on("msgHistoryUpdate",o=>{console.log(o)}),this._msrp_sessions[s.id]=s,this.emit("newMSRPSession",r)}newJanusSession(s,r){this._janus_sessions[s.id]=s,this.emit("newJanusSession",r)}destroyMSRPSession(s){delete this._msrp_sessions[s.id]}destroyJanusSession(s){delete this._janus_sessions[s.id]}receiveRequest(s){var t,n;const r=s.method;if(console.log("-----------"),s.ruri.user!==this._configuration.uri.user&&s.ruri.user!==this._contact.uri.user){ft.debug("Request-URI does not point to us"),s.method!==De.ACK&&s.reply_sl(404);return}if(s.ruri.scheme===De.SIPS){s.reply_sl(416);return}if($t.checkTransaction(this,s))return;if(r===De.INVITE?new $t.InviteServerTransaction(this,this._transport,s):r!==De.ACK&&r!==De.CANCEL&&new $t.NonInviteServerTransaction(this,this._transport,s),r===De.OPTIONS){if(this.listeners("newOptions").length===0){s.reply(200);return}new pf.Options(this).init_incoming(s)}else if(r===De.MESSAGE){if(this.listeners("newMessage").length===0){s.reply(405);return}new pf.Message(this).init_incoming(s)}else if(r===De.INVITE&&!s.to_tag&&this.listeners("newRTCSession").length===0){s.reply(405);return}let o,a;if(s.to_tag)if(o=this._findDialog(s.call_id,s.from_tag,s.to_tag),o)o.receiveRequest(s);else if(r===De.NOTIFY)if(a=this._findSession(s),a)a.receiveRequest(s);else{if(s.body){const p=JSON.parse(s.body)||{};(n=(t=p.plugindata)==null?void 0:t.data)!=null&&n.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(p)}s.reply(200)}else r!==De.ACK&&s.reply(481);else switch(r){case De.INVITE:if(window.RTCPeerConnection)if(s.hasHeader("replaces")){const p=s.replaces;o=this._findDialog(p.call_id,p.from_tag,p.to_tag),o?(a=o.owner,a.isEnded()?s.reply(603):a.receiveRequest(s)):s.reply(481)}else s.body.search(/MSRP/ig)>-1?(a=new pu(this),a.init_incoming(s)):s.body.search(/JANUS/ig)>-1||(a=new hg(this),a.init_incoming(s));else ft.warn("INVITE received but WebRTC is not supported"),s.reply(488);break;case De.BYE:s.reply(481);break;case De.CANCEL:a=this._findSession(s),a?a.receiveRequest(s):ft.debug("received CANCEL request for a non existent session");break;case De.ACK:break;case De.NOTIFY:this.emit("sipEvent",{event:s.event,request:s}),s.reply(200);break;default:s.reply(405);break}}startMSRP(s,r){ft.debug("startMSRP()",r);const o=new pu(this);return o.connect(s),o}startJanus(s,r){ft.debug("startJanus()",r);const o=new pu(this);return o.connect(s),o}terminateMSRPSessions(s){ft.debug("terminateSessions()");for(const r in this._msrp_sessions)this._msrp_sessions[r].isEnded()||this._msrp_sessions[r].terminate(s)}terminateJanusSessions(s){ft.debug("terminateSessions()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||this._janus_sessions[r].terminate(s)}stop(){if(ft.debug("stop()"),this._dynConfiguration={},this._status===Ns.STATUS_USER_CLOSED){ft.debug("UA already closed");return}this._registrator.close();const s=Object.keys(this._sessions).length;for(const o in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,o)){ft.debug(`closing session ${o}`);try{this._sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,o)){ft.debug(`closing session ${o}`);try{this._msrp_sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,o)){ft.debug(`closing session ${o}`);try{this._janus_sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,o))try{this._applicants[o].close()}catch(a){console.error(a)}this._status=Ns.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&&s===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function hT(c){this.emit("connecting",c)}function dT(c){this._status!==Ns.STATUS_USER_CLOSED&&(this._status=Ns.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function pT(c){const s=["nict","ict","nist","ist"];for(const r of s)for(const o in this._transactions[r])Object.prototype.hasOwnProperty.call(this._transactions[r],o)&&this._transactions[r][o].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==Ns.STATUS_USER_CLOSED&&(this._status=Ns.STATUS_NOT_READY,this._error=Ns.NETWORK_ERROR)}function mT(c){console.log("onTransportData",c);const s=c.transport;let r=c.message;if(r=su.parseMessage(r,this),!r){console.log("if 1 return");return}if(this._status===Ns.STATUS_USER_CLOSED&&r instanceof eo.IncomingRequest){console.log("if 2 return");return}if(!Bg(r,this,s)){console.log("if 3 return");return}if(console.log("onTransportData message",r),console.log("onTransportData instanceof",r instanceof eo.IncomingRequest),r instanceof eo.IncomingRequest)r.transport=s,console.log("onTransportData receiveRequest"),this.receiveRequest(r);else if(r instanceof eo.IncomingResponse){let o;switch(r.method){case De.INVITE:o=this._transactions.ict[r.via_branch],o&&o.receiveResponse(r);break;case De.ACK:break;default:o=this._transactions.nict[r.via_branch],o&&o.receiveResponse(r);break}}}const gT=["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"],TT=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function f_(c){const s={};return gT.forEach(r=>{c[r]!==void 0&&(s[r]=c[r])}),s.localHold=c._localHold,s}function __(c){const s={};return TT.forEach(r=>{c[r]!==void 0&&(s[r]=c[r])}),s}function h_(c,s){const r=new AudioContext,o=r.createMediaStreamSource(c),a=r.createMediaStreamDestination(),t=r.createGain();return o.connect(t),t.connect(a),t.gain.value=s,a.stream}function vT(c,s,r,o){const a=document.createElement("audio");a.id=s._id,a.className="audioTag",a.srcObject=c,d_()||(a.setSinkId(r),a.volume=o),a.play(),s.audioTag=a}function ET(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}function d_(){return/Mobi|Android|iPhone/i.test(navigator.userAgent)}const ST=lt,yT=ts(),wt=new ST("WebSocketInterface");var AT=class{constructor(s){wt.debug('new() [url:"%s"]',s),this._url=s,this._sip_uri=null,this._via_transport=null,this._ws=null;const r=yT.parse(s,"absoluteURI");if(r===-1)throw wt.warn(`invalid WebSocket URI: ${s}`),new TypeError(`Invalid argument: ${s}`);if(r.scheme!=="wss"&&r.scheme!=="ws")throw wt.warn(`invalid WebSocket URI scheme: ${r.scheme}`),new TypeError(`Invalid argument: ${s}`);this._sip_uri=`sip:${r.host}${r.port?`:${r.port}`:""};transport=ws`,this._via_transport=r.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(s){this._via_transport=s.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(wt.debug("connect()"),this.isConnected()){wt.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){wt.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),wt.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(s){this._onError(s)}}disconnect(){wt.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(s){return wt.debug("send()"),this.isConnected()?(this._ws.send(s),!0):(wt.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(){wt.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:s,code:r,reason:o}){wt.debug(`WebSocket ${this._url} closed`),s===!1&&wt.debug("WebSocket abrupt disconnection"),this.ondisconnect(!s,r,o)}_onMessage({data:s}){wt.debug("received WebSocket message"),this.ondata(s)}_onError(s){wt.warn(`WebSocket ${this._url} error: `,s)}};const mu=dl,CT=De,RT=ps,IT=mt(),bT=a_,wT=_s(),OT=ka(),DT=ts(),NT=AT;wn("JsSIP")("version %s",mu.version);var UT={C:CT,Exceptions:RT,Utils:IT,UA:bT,URI:wT,NameAddrHeader:OT,WebSocketInterface:NT,Grammar:DT,debug:wn,get name(){return mu.title},get version(){return mu.version}};const PT=Pe(UT);function gu(c){return c<10?`0${c}`:`${c}`}function xT(c){let s=c.hours||0,r=c.minutes||0,o=c.seconds||0;o++,o===60&&(o=0,r++,r===60&&(r=0,s++));const a=`${gu(s)}:${gu(r)}:${gu(o)}`;return{seconds:o,minutes:r,hours:s,formatted:a}}var St={};St.forEach=async(c,s,r)=>{const o=[];for(let a=0;a<c.length;a++)if(a in c){const t=Promise.resolve(c[a]).then(n=>s.call(r||globalThis,n,a,c));o.push(t)}await Promise.all(o)},St.forEachSeries=async(c,s,r)=>{for(let o=0;o<c.length;o++)o in c&&await s.call(r||globalThis,await c[o],o,c)},St.map=async(c,s,r)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&(o[a]=Promise.resolve(c[a]).then(t=>s.call(r||globalThis,t,a,c)));return Promise.all(o)},St.mapSeries=async(c,s,r)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&(o[a]=await s.call(r||globalThis,await c[a],a,c));return o},St.find=(c,s,r)=>new Promise((o,a)=>{if(c.length===0)return o();let t=1;for(let n=0;n<c.length;n++){const p=_=>{_?o(c[n]):t===c.length&&o(),t++};Promise.resolve(c[n]).then(_=>s.call(r||globalThis,_,n,c)).then(p).catch(a)}}),St.findSeries=async(c,s,r)=>{for(let o=0;o<c.length;o++)if(await s.call(r||globalThis,await c[o],o,c))return c[o]},St.findIndex=(c,s,r)=>new Promise((o,a)=>{if(c.length===0)return o(-1);let t=1;for(let n=0;n<c.length;n++){const p=_=>{_?o(n):t===c.length&&o(-1),t++};Promise.resolve(c[n]).then(_=>s.call(r||globalThis,_,n,c)).then(p).catch(a)}}),St.findIndexSeries=async(c,s,r)=>{for(let o=0;o<c.length;o++)if(await s.call(r||globalThis,await c[o],o,c))return o},St.some=(c,s,r)=>new Promise((o,a)=>{if(c.length===0)return o(!1);let t=1;for(let n=0;n<c.length;n++){if(!(n in c)){t++;continue}const p=_=>{_?o(!0):t===c.length&&o(!1),t++};Promise.resolve(c[n]).then(_=>s.call(r||globalThis,_,n,c)).then(p).catch(a)}}),St.someSeries=async(c,s,r)=>{for(let o=0;o<c.length;o++)if(o in c&&await s.call(r||globalThis,await c[o],o,c))return!0;return!1},St.every=(c,s,r)=>new Promise((o,a)=>{if(c.length===0)return o(!0);let t=1;for(let n=0;n<c.length;n++){if(!(n in c)){t++;continue}const p=_=>{_?t===c.length&&o(!0):o(!1),t++};Promise.resolve(c[n]).then(_=>s.call(r||globalThis,_,n,c)).then(p).catch(a)}}),St.everySeries=async(c,s,r)=>{for(let o=0;o<c.length;o++)if(o in c&&!await s.call(r||globalThis,await c[o],o,c))return!1;return!0},St.filter=(c,s,r)=>new Promise(async(o,a)=>{const t=[];for(let p=0;p<c.length;p++)p in c&&(t[p]=Promise.resolve(c[p]).then(_=>s.call(r||globalThis,_,p,c)).catch(a));const n=[];for(let p=0;p<t.length;p++)await t[p]&&n.push(await c[p]);o(n)}),St.filterSeries=async(c,s,r)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&await s.call(r||globalThis,await c[a],a,c)&&o.push(await c[a]);return o},St.reduce=async(c,s,r)=>{if(c.length===0&&r===void 0)throw TypeError("Reduce of empty array with no initial value");let o,a;for(r!==void 0?(a=r,o=0):(a=c[0],o=1),o;o<c.length;o++)o in c&&(a=await s(await a,await c[o],o,c));return a};var p_={};(function(c){const s=St;Object.keys(s).forEach(r=>{const o=r.charAt(0).toUpperCase()+r.slice(1);c[`async${o}`]=async function(...a){return s[r](this,...a)}})})(p_);var m_=Object.assign(St,{instanceMethods:p_});const tn=new AudioContext,Yt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var MT={exports:{}};(function(c){var s=function(r){var o=Object.prototype,a=o.hasOwnProperty,t=Object.defineProperty||function(ee,Y,G){ee[Y]=G.value},n,p=typeof Symbol=="function"?Symbol:{},_=p.iterator||"@@iterator",d=p.asyncIterator||"@@asyncIterator",g=p.toStringTag||"@@toStringTag";function T(ee,Y,G){return Object.defineProperty(ee,Y,{value:G,enumerable:!0,configurable:!0,writable:!0}),ee[Y]}try{T({},"")}catch{T=function(Y,G,re){return Y[G]=re}}function E(ee,Y,G,re){var ge=Y&&Y.prototype instanceof ae?Y:ae,be=Object.create(ge.prototype),Me=new P(re||[]);return t(be,"_invoke",{value:z(ee,G,Me)}),be}r.wrap=E;function y(ee,Y,G){try{return{type:"normal",arg:ee.call(Y,G)}}catch(re){return{type:"throw",arg:re}}}var A="suspendedStart",C="suspendedYield",I="executing",$="completed",L={};function ae(){}function N(){}function F(){}var Se={};T(Se,_,function(){return this});var ve=Object.getPrototypeOf,M=ve&&ve(ve(se([])));M&&M!==o&&a.call(M,_)&&(Se=M);var D=F.prototype=ae.prototype=Object.create(Se);N.prototype=F,t(D,"constructor",{value:F,configurable:!0}),t(F,"constructor",{value:N,configurable:!0}),N.displayName=T(F,g,"GeneratorFunction");function B(ee){["next","throw","return"].forEach(function(Y){T(ee,Y,function(G){return this._invoke(Y,G)})})}r.isGeneratorFunction=function(ee){var Y=typeof ee=="function"&&ee.constructor;return Y?Y===N||(Y.displayName||Y.name)==="GeneratorFunction":!1},r.mark=function(ee){return Object.setPrototypeOf?Object.setPrototypeOf(ee,F):(ee.__proto__=F,T(ee,g,"GeneratorFunction")),ee.prototype=Object.create(D),ee},r.awrap=function(ee){return{__await:ee}};function q(ee,Y){function G(be,Me,Re,le){var ye=y(ee[be],ee,Me);if(ye.type==="throw")le(ye.arg);else{var it=ye.arg,ot=it.value;return ot&&typeof ot=="object"&&a.call(ot,"__await")?Y.resolve(ot.__await).then(function(Ee){G("next",Ee,Re,le)},function(Ee){G("throw",Ee,Re,le)}):Y.resolve(ot).then(function(Ee){it.value=Ee,Re(it)},function(Ee){return G("throw",Ee,Re,le)})}}var re;function ge(be,Me){function Re(){return new Y(function(le,ye){G(be,Me,le,ye)})}return re=re?re.then(Re,Re):Re()}t(this,"_invoke",{value:ge})}B(q.prototype),T(q.prototype,d,function(){return this}),r.AsyncIterator=q,r.async=function(ee,Y,G,re,ge){ge===void 0&&(ge=Promise);var be=new q(E(ee,Y,G,re),ge);return r.isGeneratorFunction(Y)?be:be.next().then(function(Me){return Me.done?Me.value:be.next()})};function z(ee,Y,G){var re=A;return function(be,Me){if(re===I)throw new Error("Generator is already running");if(re===$){if(be==="throw")throw Me;return rt()}for(G.method=be,G.arg=Me;;){var Re=G.delegate;if(Re){var le=H(Re,G);if(le){if(le===L)continue;return le}}if(G.method==="next")G.sent=G._sent=G.arg;else if(G.method==="throw"){if(re===A)throw re=$,G.arg;G.dispatchException(G.arg)}else G.method==="return"&&G.abrupt("return",G.arg);re=I;var ye=y(ee,Y,G);if(ye.type==="normal"){if(re=G.done?$:C,ye.arg===L)continue;return{value:ye.arg,done:G.done}}else ye.type==="throw"&&(re=$,G.method="throw",G.arg=ye.arg)}}}function H(ee,Y){var G=Y.method,re=ee.iterator[G];if(re===n)return Y.delegate=null,G==="throw"&&ee.iterator.return&&(Y.method="return",Y.arg=n,H(ee,Y),Y.method==="throw")||G!=="return"&&(Y.method="throw",Y.arg=new TypeError("The iterator does not provide a '"+G+"' method")),L;var ge=y(re,ee.iterator,Y.arg);if(ge.type==="throw")return Y.method="throw",Y.arg=ge.arg,Y.delegate=null,L;var be=ge.arg;if(!be)return Y.method="throw",Y.arg=new TypeError("iterator result is not an object"),Y.delegate=null,L;if(be.done)Y[ee.resultName]=be.value,Y.next=ee.nextLoc,Y.method!=="return"&&(Y.method="next",Y.arg=n);else return be;return Y.delegate=null,L}B(D),T(D,g,"Generator"),T(D,_,function(){return this}),T(D,"toString",function(){return"[object Generator]"});function Z(ee){var Y={tryLoc:ee[0]};1 in ee&&(Y.catchLoc=ee[1]),2 in ee&&(Y.finallyLoc=ee[2],Y.afterLoc=ee[3]),this.tryEntries.push(Y)}function U(ee){var Y=ee.completion||{};Y.type="normal",delete Y.arg,ee.completion=Y}function P(ee){this.tryEntries=[{tryLoc:"root"}],ee.forEach(Z,this),this.reset(!0)}r.keys=function(ee){var Y=Object(ee),G=[];for(var re in Y)G.push(re);return G.reverse(),function ge(){for(;G.length;){var be=G.pop();if(be in Y)return ge.value=be,ge.done=!1,ge}return ge.done=!0,ge}};function se(ee){if(ee){var Y=ee[_];if(Y)return Y.call(ee);if(typeof ee.next=="function")return ee;if(!isNaN(ee.length)){var G=-1,re=function ge(){for(;++G<ee.length;)if(a.call(ee,G))return ge.value=ee[G],ge.done=!1,ge;return ge.value=n,ge.done=!0,ge};return re.next=re}}return{next:rt}}r.values=se;function rt(){return{value:n,done:!0}}return P.prototype={constructor:P,reset:function(ee){if(this.prev=0,this.next=0,this.sent=this._sent=n,this.done=!1,this.delegate=null,this.method="next",this.arg=n,this.tryEntries.forEach(U),!ee)for(var Y in this)Y.charAt(0)==="t"&&a.call(this,Y)&&!isNaN(+Y.slice(1))&&(this[Y]=n)},stop:function(){this.done=!0;var ee=this.tryEntries[0],Y=ee.completion;if(Y.type==="throw")throw Y.arg;return this.rval},dispatchException:function(ee){if(this.done)throw ee;var Y=this;function G(le,ye){return be.type="throw",be.arg=ee,Y.next=le,ye&&(Y.method="next",Y.arg=n),!!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 Me=a.call(ge,"catchLoc"),Re=a.call(ge,"finallyLoc");if(Me&&Re){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0);if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else if(Me){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0)}else if(Re){if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(ee,Y){for(var G=this.tryEntries.length-1;G>=0;--G){var re=this.tryEntries[G];if(re.tryLoc<=this.prev&&a.call(re,"finallyLoc")&&this.prev<re.finallyLoc){var ge=re;break}}ge&&(ee==="break"||ee==="continue")&&ge.tryLoc<=Y&&Y<=ge.finallyLoc&&(ge=null);var be=ge?ge.completion:{};return be.type=ee,be.arg=Y,ge?(this.method="next",this.next=ge.finallyLoc,L):this.complete(be)},complete:function(ee,Y){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"&&Y&&(this.next=Y),L},finish:function(ee){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var G=this.tryEntries[Y];if(G.finallyLoc===ee)return this.complete(G.completion,G.afterLoc),U(G),L}},catch:function(ee){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var G=this.tryEntries[Y];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,Y,G){return this.delegate={iterator:se(ee),resultName:Y,nextLoc:G},this.method==="next"&&(this.arg=n),L}},r}(c.exports);try{regeneratorRuntime=s}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=s:Function("r","regeneratorRuntime = r")(s)}})(MT);var g_={exports:{}};(function(c){(function(s,r){c.exports?c.exports=r():s.log=r()})(Gt,function(){var s=function(){},r="undefined",o=typeof window!==r&&typeof window.navigator!==r&&/Trident\/|MSIE /.test(window.navigator.userAgent),a=["trace","debug","info","warn","error"];function t(C,I){var $=C[I];if(typeof $.bind=="function")return $.bind(C);try{return Function.prototype.bind.call($,C)}catch{return function(){return Function.prototype.apply.apply($,[C,arguments])}}}function n(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function p(C){return C==="debug"&&(C="log"),typeof console===r?!1:C==="trace"&&o?n:console[C]!==void 0?t(console,C):console.log!==void 0?t(console,"log"):s}function _(C,I){for(var $=0;$<a.length;$++){var L=a[$];this[L]=$<C?s:this.methodFactory(L,C,I)}this.log=this.debug}function d(C,I,$){return function(){typeof console!==r&&(_.call(this,I,$),this[C].apply(this,arguments))}}function g(C,I,$){return p(C)||d.apply(this,arguments)}function T(C,I,$){var L=this,ae;I=I??"WARN";var N="loglevel";typeof C=="string"?N+=":"+C:typeof C=="symbol"&&(N=void 0);function F(D){var B=(a[D]||"silent").toUpperCase();if(!(typeof window===r||!N)){try{window.localStorage[N]=B;return}catch{}try{window.document.cookie=encodeURIComponent(N)+"="+B+";"}catch{}}}function Se(){var D;if(!(typeof window===r||!N)){try{D=window.localStorage[N]}catch{}if(typeof D===r)try{var B=window.document.cookie,q=B.indexOf(encodeURIComponent(N)+"=");q!==-1&&(D=/^([^;]+)/.exec(B.slice(q))[1])}catch{}return L.levels[D]===void 0&&(D=void 0),D}}function ve(){if(!(typeof window===r||!N)){try{window.localStorage.removeItem(N);return}catch{}try{window.document.cookie=encodeURIComponent(N)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}L.name=C,L.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},L.methodFactory=$||g,L.getLevel=function(){return ae},L.setLevel=function(D,B){if(typeof D=="string"&&L.levels[D.toUpperCase()]!==void 0&&(D=L.levels[D.toUpperCase()]),typeof D=="number"&&D>=0&&D<=L.levels.SILENT){if(ae=D,B!==!1&&F(D),_.call(L,D,C),typeof console===r&&D<L.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+D},L.setDefaultLevel=function(D){I=D,Se()||L.setLevel(D,!1)},L.resetLevel=function(){L.setLevel(I,!1),ve()},L.enableAll=function(D){L.setLevel(L.levels.TRACE,D)},L.disableAll=function(D){L.setLevel(L.levels.SILENT,D)};var M=Se();M==null&&(M=I),L.setLevel(M,!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 $=y[I];return $||($=y[I]=new T(I,E.getLevel(),E.methodFactory)),$};var A=typeof window!==r?window.log:void 0;return E.noConflict=function(){return typeof window!==r&&window.log===E&&(window.log=A),E},E.getLoggers=function(){return y},E.default=E,E})})(g_);var Rt=g_.exports;const ms=()=>`${new Date().toISOString()} | metrics`,gs=(c,s,r)=>`${c} | ${s} | ${r}`;Rt.setDefaultLevel(Rt.levels.TRACE);const kT=c=>{Rt.info(gs(ms(),"log ",`set log level to ${c?"verbose":"info"}`)),Rt.setLevel(c?Rt.levels.TRACE:Rt.levels.INFO)},LT=c=>{const s=[...Object.keys(Rt.levels)];s.includes(c)?(Rt.info(gs(ms(),"log ",`update log level to ${c.toLowerCase()}`)),Rt.setLevel(c)):Rt.warn(gs(ms(),"log ","Incorrect log level please choose one of "),s)},xe=(c,s,r)=>{r?Rt.debug(gs(ms(),c,s),r):Rt.debug(gs(ms(),c,s))},Tu=(c,s)=>{Rt.info(gs(ms(),c,s))},sn=(c,s)=>{Rt.info(gs(ms(),c,s))},To=(c,s)=>{Rt.warn(gs(ms(),c,s))},Fn=(c,s)=>{Rt.error(gs(ms(),c,s))};function $T(c){return Math.floor(Math.random()*c).toString()}function T_(c,s){let r=s;return c.forEach(o=>{r=r.replace(o,"")}),r}function HT(c,s){let r="";for(let o=0;o<s;o+=1)r+=c[$T(c.length)];return r}function FT({length:c=20,useLetters:s=!0,useNumbers:r=!0,includeSymbols:o=[],excludeSymbols:a=[]}={}){let t="abcdefghijklmnopqrstuvwxyz",n="0123456789",p=[],_=[],d=[];return s&&(a.length&&(t=T_(a,t)),_=t.split("")),r&&(a.length&&(n=T_(a,n)),d=n.split("")),p=[..._,...d,...o],HT(p,c)}var jT=FT;const Zr=Pe(jT),VT=()=>"WebRTCMetrics",qT=()=>"5.0.3",$e={INBOUND:"inbound",OUTBOUND:"outbound"},Ts={IDLE:"idle",RUNNING:"running",MUTED:"muted"},ei={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},BT=()=>({...{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:[]}}),v_={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},E_={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},S_={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},y_={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},GT=c=>{const s={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 r={...c,audio:{},video:{},data:{...c.data},network:{...c.network},experimental:{...c.experimental}};return Object.keys(c.audio).forEach(o=>{r.audio[o]={...c.audio[o]}}),Object.keys(c.video).forEach(o=>{r.video[o]={...c.video[o]}}),r}return{...s,audio:{},video:{},data:{...s.data},network:{...s.network},experimental:{...s.experimental}}},WT={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${Zr()}`,cid:`c-${Zr()}`,uid:`u-${Zr()}`,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"},V={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"},ti={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},vu={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ne={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},Eu="config ",KT=(c,s={},r)=>{const o={...r,...s};return s.pname||To(Eu,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${r.pname}'`),s.cid||To(Eu,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${r.cid}'`),s.uid||To(Eu,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${r.uid}'`),o.pc=c,o},YT=(c={})=>{const s={...WT,...c};return s.name=VT(),s.version=qT(),s},si=(c,s,r,o=!1,a)=>{let t=c.map(n=>{if(!r)return n[s];if(!a)return n[s][r];const p=n[s][a];return p?p[r]:null});return t=t.filter(n=>o?Number.isFinite(n)&&n>0:Number.isFinite(n)),t.length===0?[]:t},Us=c=>c.reduce((s,r)=>s+r,0)/c.length,zT=()=>`probe-${Zr()}`,JT=()=>`coltr-${Zr()}`,A_=c=>new Promise(s=>setTimeout(s,c)),Su=(c,s,r)=>{s?c.call(s,r):c(r)},We=(c,s,r,o)=>{const a=si(c,s,r,!0,o);if(a.length===0)return null;const t=a.reduce((d,g)=>d+g,0)/a.length;return t===0?null:a.map(d=>Math.abs(t-d)).reduce((d,g)=>d+g,0)/a.length*100/t},Xe=(c,s,r,o=!1,a)=>{const t=si(c,s,r,o,a);return t.length===0?null:t.reduce((n,p)=>n+p,0)/t.length},nn=(c,s,r)=>si(c,s,r).reduce((a,t)=>a+t,0),Ke=(c,s,r,o)=>{const a=si(c,s,r,!0,o);return a.length===0?null:Math.min(...a)},Ye=(c,s,r,o)=>{const a=si(c,s,r,!1,o);return a.length===0?null:Math.max(...a)},yt=(c,s,r,o)=>{const a=c.slice().pop();if(!a)return null;if(!r)return a[s];if(!o)return a[s][r];const t=a[s][o];return t?t[r]:null},XT=c=>c.slice().pop(),_t=(c,s,r)=>{if(!s)return null;const o={};let a=s[x.AUDIO][c];a||(a=r===$e.INBOUND?{...v_}:{...E_}),o[x.AUDIO]=a;let t=s[x.VIDEO][c];return t||(t=r===$e.INBOUND?{...S_}:{...y_}),o[x.VIDEO]=t,o},ni="exporter ",QT="2.0",C_=(c,s,r)=>{if(!c||c.length===0)return 0;const o=c[c.length-1];if(!o)return 0;const a=o[s][r];if(a){const t=a.total_rtt_ms_out,n=a.total_rtt_measure_out;return!n||!t?Xe(c,s,"delta_rtt_ms_out",!1,r):Number(t/n)}return null},ZT=(c,s)=>{if(!c||c.length===0)return 0;const r=c[c.length-1];if(!r)return 0;const o=r[s].total_rtt_connectivity_ms,a=r[s].total_rtt_connectivity_measure;return!a||!o?Xe(c,s,"delta_rtt_connectivity_ms"):Number(o/a)},ev=c=>yt(c,"network","local_candidate_type")!=="relay"?`direct/${yt(c,"network","local_candidate_protocol")}`:`turn/${yt(c,"network","local_candidate_relay_protocol")}`,tv=c=>{const s=yt(c,"network","remote_candidate_type"),r=yt(c,"network","remote_candidate_protocol");return s!=="relay"?`direct/${r}`:`turn/${r}`};class sv{constructor(s){this._start=null,this._end=null,this._cfg=s,this._referenceReport=null,this._reports=[],this._events=[]}start(){Tu(ni,"start() - start exporter...");const s=new Date;return this._start=s.toJSON(),s}stop(){Tu(ni,"stop() - stop exporter...");const s=new Date;return this._end=s.toJSON(),s}saveReferenceReport(s){this._referenceReport=s}getReferenceReport(){return this._referenceReport}addReport(s){this._cfg.ticket&&(xe(ni,`addReport() - add report to exporter at ${s.timestamp}`),this._reports.push(s))}addCustomEvent(s){this._events.push(s)}reset(){Tu(ni,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){xe(ni,"ticket() - generate ticket");const s=yt(this._reports,"audio","total_packets_lost_in"),r=yt(this._reports,"audio","total_packets_in"),o=yt(this._reports,"video","total_packets_lost_in"),a=yt(this._reports,"video","total_packets_in"),t={},n=XT(this._reports);return n&&(Object.keys(n[x.AUDIO]).forEach(p=>{const _=n[x.AUDIO][p];if(t[_.ssrc]={type:x.AUDIO,direction:_.direction},_.direction===$e.INBOUND){const d={avg:Xe(this._reports,x.AUDIO,"delta_jitter_ms_in",!1,p),min:Ke(this._reports,x.AUDIO,"delta_jitter_ms_in",p),max:Ye(this._reports,x.AUDIO,"delta_jitter_ms_in",p),volatility:We(this._reports,x.AUDIO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.AUDIO,"delta_kbs_in",!1,p),min:Ke(this._reports,x.AUDIO,"delta_kbs_in",p),max:Ye(this._reports,x.AUDIO,"delta_kbs_in",p),volatility:We(this._reports,x.AUDIO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.AUDIO,"delta_KBytes_in",!1,p),min:Ke(this._reports,x.AUDIO,"delta_KBytes_in",p),max:Ye(this._reports,x.AUDIO,"delta_KBytes_in",p),volatility:We(this._reports,x.AUDIO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={emodel:{avg:Xe(this._reports,x.AUDIO,"mos_emodel_in",!1,p),min:Ke(this._reports,x.AUDIO,"mos_emodel_in",p),max:Ye(this._reports,x.AUDIO,"mos_emodel_in",p),volatility:We(this._reports,x.AUDIO,"mos_emodel_in",p)},effective:{avg:Xe(this._reports,x.AUDIO,"mos_in",!1,p),min:Ke(this._reports,x.AUDIO,"mos_in",p),max:Ye(this._reports,x.AUDIO,"mos_in",p),volatility:We(this._reports,x.AUDIO,"mos_in",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},y=yt(this._reports,x.AUDIO,"total_packets_lost_in",p),A=yt(this._reports,x.AUDIO,"total_packets_in",p),C={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].mos=E,t[p].traffic=T,t[p].bitrate=g,t[p].loss=C}else{const d={avg:Xe(this._reports,x.AUDIO,"delta_jitter_ms_out",!1,p),min:Ke(this._reports,x.AUDIO,"delta_jitter_ms_out",p),max:Ye(this._reports,x.AUDIO,"delta_jitter_ms_out",p),volatility:We(this._reports,x.AUDIO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.AUDIO,"delta_kbs_out",!1,p),min:Ke(this._reports,x.AUDIO,"delta_kbs_out",p),max:Ye(this._reports,x.AUDIO,"delta_kbs_out",p),volatility:We(this._reports,x.AUDIO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.AUDIO,"delta_KBytes_out",!1,p),min:Ke(this._reports,x.AUDIO,"delta_KBytes_out",p),max:Ye(this._reports,x.AUDIO,"delta_KBytes_out",p),volatility:We(this._reports,x.AUDIO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},E={avg:C_(this._reports,x.AUDIO,p),min:Ke(this._reports,x.AUDIO,"delta_rtt_ms_out",p),max:Ye(this._reports,x.AUDIO,"delta_rtt_ms_out",p),volatility:We(this._reports,x.AUDIO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=yt(this._reports,x.AUDIO,"total_packets_lost_out",p),A=yt(this._reports,x.AUDIO,"total_packets_out",p),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,p),min:Ke(this._reports,x.AUDIO,"mos_emodel_out",p),max:Ye(this._reports,x.AUDIO,"mos_emodel_out",p),volatility:We(this._reports,x.AUDIO,"mos_emodel_out",p)},effective:{avg:Xe(this._reports,x.AUDIO,"mos_out",!1,p),min:Ke(this._reports,x.AUDIO,"mos_out",p),max:Ye(this._reports,x.AUDIO,"mos_out",p),volatility:We(this._reports,x.AUDIO,"mos_out",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};t[p].jitter=d,t[p].rtt=E,t[p].traffic=T,t[p].bitrate=g,t[p].loss=C,t[p].mos=I}}),Object.keys(n[x.VIDEO]).forEach(p=>{const _=n[x.VIDEO][p];if(t[p]={type:x.VIDEO,direction:_.direction},_.direction===$e.INBOUND){const d={avg:Xe(this._reports,x.VIDEO,"delta_jitter_ms_in",!1,p),min:Ke(this._reports,x.VIDEO,"delta_jitter_ms_in",p),max:Ye(this._reports,x.VIDEO,"delta_jitter_ms_in",p),volatility:We(this._reports,x.VIDEO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.VIDEO,"delta_kbs_in",!1,p),min:Ke(this._reports,x.VIDEO,"delta_kbs_in",p),max:Ye(this._reports,x.VIDEO,"delta_kbs_in",p),volatility:We(this._reports,x.VIDEO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.VIDEO,"delta_KBytes_in",!1,p),min:Ke(this._reports,x.VIDEO,"delta_KBytes_in",p),max:Ye(this._reports,x.VIDEO,"delta_KBytes_in",p),volatility:We(this._reports,x.VIDEO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E=yt(this._reports,x.VIDEO,"total_packets_lost_in",p),y=yt(this._reports,x.VIDEO,"total_packets_in",p),A={lost:E,avg:Math.round((E/(E+y)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].traffic=T,t[p].bitrate=g,t[p].loss=A}else{const d={avg:Xe(this._reports,x.VIDEO,"delta_jitter_ms_out",!1,p),min:Ke(this._reports,x.VIDEO,"delta_jitter_ms_out",p),max:Ye(this._reports,x.VIDEO,"delta_jitter_ms_out",p),volatility:We(this._reports,x.VIDEO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.VIDEO,"delta_kbs_out",!1,p),min:Ke(this._reports,x.VIDEO,"delta_kbs_out",p),max:Ye(this._reports,x.VIDEO,"delta_kbs_out",p),volatility:We(this._reports,x.VIDEO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.VIDEO,"delta_KBytes_out",!1,p),min:Ke(this._reports,x.VIDEO,"delta_KBytes_out",p),max:Ye(this._reports,x.VIDEO,"delta_KBytes_out",p),volatility:We(this._reports,x.VIDEO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={avg:C_(this._reports,x.VIDEO,p),min:Ke(this._reports,x.VIDEO,"delta_rtt_ms_out",p),max:Ye(this._reports,x.VIDEO,"delta_rtt_ms_out",p),volatility:We(this._reports,x.VIDEO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=yt(this._reports,x.VIDEO,"total_packets_lost_out",p),A=yt(this._reports,x.VIDEO,"total_packets_out",p),C={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].rtt=E,t[p].traffic=T,t[p].bitrate=g,t[p].loss=C}})),{version:QT,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:t,data:{rtt:{avg:ZT(this._reports,"data"),min:Ke(this._reports,"data","delta_rtt_connectivity_ms"),max:Ye(this._reports,"data","delta_rtt_connectivity_ms"),volatility:We(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((s/(s+r)*100||0)*100)/100}},video:{in:{avg:Math.round((o/(o+a)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:Xe(this._reports,"data","delta_kbs_in"),min:Ke(this._reports,"data","delta_kbs_in"),max:Ye(this._reports,"data","delta_kbs_in"),volatility:We(this._reports,"data","delta_kbs_in")},out:{avg:Xe(this._reports,"data","delta_kbs_out"),min:Ke(this._reports,"data","delta_kbs_out"),max:Ye(this._reports,"data","delta_kbs_out"),volatility:We(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:Ke(this._reports,"data","delta_KBytes_in"),max:Ye(this._reports,"data","delta_KBytes_in"),volatility:We(this._reports,"data","delta_KBytes_in")},out:{avg:Xe(this._reports,"data","delta_KBytes_out"),min:Ke(this._reports,"data","delta_KBytes_out"),max:Ye(this._reports,"data","delta_KBytes_out"),volatility:We(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:ev(this._reports),remoteConnection:tv(this._reports)}}}}updateConfig(s){this._cfg=s}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const s=this._reports.slice();return s.pop(),s.pop()||null}getReportsNumber(){return this._reports.length}}const Ps="extractor ",R_=(c,s,r,o)=>{let a=!1;const t=o[s].total_rtt_ms_out,n=o[s].total_rtt_measure_out,p=r?r[s].total_rtt_ms_out:0,_=r?r[s].total_rtt_measure_out:0,d={rtt:null,totalRTT:t,totalRTTMeasurements:n};if(c[V.TIMESTAMP]===o[s].timestamp_out||!Object.prototype.hasOwnProperty.call(c,V.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(a=!0,Number(c[V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-_===n))return d;const g=1e3*Number(c[V.ROUND_TRIP_TIME]);let T=t+g,E=n+1;return a&&(T=1e3*Number(c[V.TOTAL_ROUND_TRIP_TIME])-p,E=Number(c[V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-_),{rtt:g,totalRTT:T,totalRTTMeasurements:E}},nv=(c,s,r,o)=>{if(!Object.prototype.hasOwnProperty.call(c,V.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:o[s].total_rtt_connectivity_ms,totalRTTMeasurements:o[s].total_rtt_connectivity_measure};const a=1e3*Number(c[V.CURRENT_ROUND_TRIP_TIME]);let t=o[s].total_rtt_connectivity_ms+a,n=o[s].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,V.TOTAL_ROUND_TRIP_TIME)&&(t=1e3*Number(c[V.TOTAL_ROUND_TRIP_TIME])-(r?r[s].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,V.RESPONSES_RECEIVED)&&(n=Number(c[V.RESPONSES_RECEIVED])-(r?r[s].total_rtt_connectivity_measure:0)),{rtt:a,totalRTT:t,totalRTTMeasurements:n}},vo=(c,s,r)=>c[V.TIMESTAMP]===r[s].timestamp_out||!Object.prototype.hasOwnProperty.call(c,V.JITTER)?null:1e3*(Number(c[V.JITTER])||0),rv=(c,s)=>{if(!Object.prototype.hasOwnProperty.call(c,V.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,V.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:s[x.VIDEO].delta_ms_decode_frame_in,frames_decoded:s[x.VIDEO].total_frames_decoded_in,total_decode_time:s[x.VIDEO].total_time_decoded_in};const r=c[V.FRAMES_DECODED],o=c[V.TOTAL_DECODE_TIME],a=o-s[x.VIDEO].total_time_decoded_in,t=r-s[x.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:t>0?a*1e3/t:0,frames_decoded:r,total_decode_time:o}},iv=(c,s)=>{if(!Object.prototype.hasOwnProperty.call(c,V.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,V.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:s[x.VIDEO].delta_ms_encode_frame_out,frames_encoded:s[x.VIDEO].total_frames_encoded_out,total_encode_time:s[x.VIDEO].total_time_encoded_out};const r=c[V.FRAMES_ENCODED],o=c[V.TOTAL_ENCODE_TIME],a=o-s[x.VIDEO].total_time_encoded_out,t=r-s[x.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:t>0&&a?a*1e3/t:0,frames_encoded:r,total_encode_time:o}},I_=(c,s,r,o)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,V.BYTES_SENT))return{packetsSent:r[s].total_packets_out,packetsLost:r[s].total_packets_lost_out,bytesSent:r[s].total_KBytes_out};const a=Number(c[V.PACKETS_SENT])||0-(o?o[s].total_packets_out:0),t=a-r[s].total_packets_out,n=Number(c[V.BYTES_SENT])/1024-(o?o[s].total_KBytes_out:0),p=n-r[s].total_KBytes_out,_=c[V.TIMESTAMP]||Date.now(),d=o?o.timestamp:null;let g=r.timestamp;!g&&d&&(g=d);const T=g?_-g:0,E=T>0?p*.008*1024/T*1e3:0;return{packetsSent:a,deltaPacketsSent:t,KBytesSent:n,deltaKBytesSent:p,kbsSent:E}},b_=(c,s,r,o)=>{let a=r[s].total_packets_lost_out,t=0,n=0;return Object.prototype.hasOwnProperty.call(c,V.PACKETS_LOST)&&(a=Number(c[V.PACKETS_LOST])||0-(o?o[s].total_packets_lost_out:0),t=a-r[s].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,V.FRACTION_LOST)&&(n=Number(100*c[V.FRACTION_LOST])),{packetsLost:a,deltaPacketsLost:t,fractionLost:n}},w_=(c,s,r,o)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,V.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,V.BYTES_RECEIVED))return{percent_packets_lost:r[s].percent_packets_lost_in,packetsReceived:r[s].total_packets_in,packetsLost:r[s].total_packets_lost_in,bytesReceived:r[s].total_KBytes_in};const a=Number(c[V.PACKETS_RECEIVED])||0-(o?o[s].total_packets_in:0),t=Number(c[V.PACKETS_LOST])||0-(o?o[s].total_packets_lost_in:0),n=t-r[s].total_packets_lost_in,p=a-r[s].total_packets_in,_=a!==r[s].total_packets_in?n*100/(n+p):0,d=Number(c[V.BYTES_RECEIVED])/1024-(o?o[s].total_KBytes_in:0),g=d-r[s].total_KBytes_in,T=c[V.TIMESTAMP]||Date.now(),E=o?o.timestamp:null;let y=r.timestamp;!y&&E&&(y=E);const A=y?T-y:0,C=A>0?g*.008*1024/A*1e3:0;return{percentPacketsLost:_,packetsReceived:a,deltaPacketsReceived:p,packetsLost:t,deltaPacketsLost:n,KBytesReceived:d,deltaKBytesReceived:g,kbsReceived:C}},lv=c=>c[V.CANDIDATE_TYPE]!=="relay"?"":c[V.RELAY_PROTOCOL]||"",ov=c=>{if(!Object.prototype.hasOwnProperty.call(c,V.NETWORK_TYPE))return ti.WIFI;switch(c[V.NETWORK_TYPE]){case vu.ETHERNET:return ti.ETHERNET;case vu.CELLULAR_4G:return ti.CELLULAR_4G;case vu.WIFI:return ti.WIFI;default:return ti.CELLULAR}},O_=c=>!Object.prototype.hasOwnProperty.call(c,V.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,V.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[V.FRAME_WIDTH]||null,height:c[V.FRAME_HEIGHT]||null,framerate:c[V.FRAMES_PER_SECOND]},av=c=>{const s=Object.prototype.hasOwnProperty.call(c,V.QUALITY_LIMITATION_REASON)?c[V.QUALITY_LIMITATION_REASON]:null,r=Object.prototype.hasOwnProperty.call(c,V.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[V.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,o=Object.prototype.hasOwnProperty.call(c,V.QUALITY_LIMITATION_DURATIONS)?c[V.QUALITY_LIMITATION_DURATIONS]:null;return o&&Object.keys(o).forEach(a=>{o[a]>1e3&&(o[a]=Number(o[a]/1e3))}),{reason:s,durations:o,resolutionChanges:r}},uv=(c,s,r)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PLI)||!Object.prototype.hasOwnProperty.call(c,V.NACK))return{pliCount:s.total_pli_sent_in,nackCount:s.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const o=(c[V.PLI]||0)-(r?r[x.VIDEO].total_pli_sent_in:0),a=(c[V.NACK]||0)-(r?r[x.VIDEO].total_nack_sent_in:0);return{pliCount:o,nackCount:a,deltaPliCount:o-s[x.VIDEO].total_pli_sent_in,deltaNackCount:a-s[x.VIDEO].total_nack_sent_in}},cv=(c,s,r)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PLI)||!Object.prototype.hasOwnProperty.call(c,V.NACK))return{pliCount:s.total_pli_received_out,nackCount:s.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const o=(c[V.PLI]||0)-(r?r[x.VIDEO].total_pli_received_out:0),a=(c[V.NACK]||0)-(r?r[x.VIDEO].total_nack_received_out:0);return{pliCount:o,nackCount:a,deltaPliCount:o-s[x.VIDEO].total_pli_received_out,deltaNackCount:a-s[x.VIDEO].total_nack_received_out}},fv=c=>({channels:c[V.CHANNELS]||null,clock_rate:c[V.CLOCK_RATE]||null,mime_type:c[V.MIME_TYPE]||null,sdp_fmtp_line:c[V.SDP_FMTP_LINE]||null}),_v=c=>({clock_rate:c[V.CLOCK_RATE]||null,mime_type:c[V.MIME_TYPE]||null}),hv=(c,s,r)=>{const o=(c[V.BYTES_RECEIVED]||0)/1024-(r?r.data.total_KBytes_in:0),a=(c[V.BYTES_SENT]||0)/1024-(r?r.data.total_KBytes_out:0),t=c[V.TIMESTAMP]||Date.now(),n=o-s.data.total_KBytes_in,p=a-s.data.total_KBytes_out,_=r?r.timestamp:null;let d=s.timestamp;!d&&_&&(d=_);const g=d?t-d:0,T=g>0?n*.008*1024/g*1e3:0,E=g>0?p*.008*1024/g*1e3:0;return{total_KBytes_received:o,total_KBytes_sent:a,delta_KBytes_received:n,delta_KBytes_sent:p,kbs_speed_received:T,kbs_speed_sent:E}},dv=c=>{const s=c[V.AVAILABLE_INCOMING_BITRATE]/1024||0,r=c[V.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:s,kbs_outgoing_bandwidth:r}},pv=(c,s,r,o)=>{if(!c)return[];switch(c[V.TYPE]){case zt.CANDIDATE_PAIR:let a=!1;if(c[V.NOMINATED]&&c[V.STATE]===x.SUCCEEDED&&(a=!0,xe(Ps,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c),V.SELECTED in c&&!c[V.SELECTED]&&(a=!1)),a){const n=c[V.LOCAL_CANDIDATE_ID],p=c[V.REMOTE_CANDIDATE_ID],_=hv(c,s,o),d=dv(c),g=nv(c,"data",o,s);return[{type:ne.NETWORK,value:{local_candidate_id:n}},{type:ne.NETWORK,value:{remote_candidate_id:p}},{type:ne.DATA,value:{total_KBytes_in:_.total_KBytes_received}},{type:ne.DATA,value:{total_KBytes_out:_.total_KBytes_sent}},{type:ne.DATA,value:{delta_KBytes_in:_.delta_KBytes_received}},{type:ne.DATA,value:{delta_KBytes_out:_.delta_KBytes_sent}},{type:ne.DATA,value:{delta_kbs_in:_.kbs_speed_received}},{type:ne.DATA,value:{delta_kbs_out:_.kbs_speed_sent}},{type:ne.DATA,value:{delta_kbs_bandwidth_in:d.kbs_incoming_bandwidth}},{type:ne.DATA,value:{delta_kbs_bandwidth_out:d.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[V.ID]===s.network.local_candidate_id)return[{type:ne.NETWORK,value:{infrastructure:ov(c)}},{type:ne.NETWORK,value:{local_candidate_type:c[V.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{local_candidate_protocol:c[V.PROTOCOL]||""}},{type:ne.NETWORK,value:{local_candidate_relay_protocol:lv(c)}}];break;case zt.REMOTE_CANDIDATE:if(c[V.ID]===s.network.remote_candidate_id)return[{type:ne.NETWORK,value:{remote_candidate_type:c[V.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{remote_candidate_protocol:c[V.PROTOCOL]||""}}];break;case zt.INBOUND_RTP:{xe(Ps,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const n=c[V.SSRC],p=_t(n,s,$e.INBOUND);p&&(p.timestamp=s.timestamp);const _=_t(n,o,$e.INBOUND);if(_&&(_.timestamp=o.timestamp),c[V.MEDIA_TYPE]===x.AUDIO){const d=w_(c,x.AUDIO,p,_),g=vo(c,x.AUDIO,p),T=c[V.CODEC_ID]||"";return[{ssrc:n,type:ne.AUDIO,value:{codec_id_in:T}},{ssrc:n,type:ne.AUDIO,value:{total_packets_in:d.packetsReceived}},{ssrc:n,type:ne.AUDIO,value:{delta_packets_in:d.deltaPacketsReceived}},{ssrc:n,type:ne.AUDIO,value:{total_packets_lost_in:d.packetsLost}},{ssrc:n,type:ne.AUDIO,value:{delta_packets_lost_in:d.deltaPacketsLost}},{ssrc:n,type:ne.AUDIO,value:{percent_packets_lost_in:d.percentPacketsLost}},{ssrc:n,type:ne.AUDIO,value:{total_KBytes_in:d.KBytesReceived}},{ssrc:n,type:ne.AUDIO,value:{delta_KBytes_in:d.deltaKBytesReceived}},{ssrc:n,type:ne.AUDIO,value:{delta_kbs_in:d.kbsReceived}},{ssrc:n,type:ne.AUDIO,value:{delta_jitter_ms_in:g}}]}if(c[V.MEDIA_TYPE]===x.VIDEO){const d=rv(c,p),g=w_(c,x.VIDEO,p,_),T=vo(c,x.VIDEO,p),E=c[V.DECODER_IMPLEMENTATION]||null,y=c[V.CODEC_ID]||null,A=O_(c),C=uv(c,p,_);return[{ssrc:n,type:ne.VIDEO,value:{codec_id_in:y}},{ssrc:n,type:ne.VIDEO,value:{total_packets_in:g.packetsReceived}},{ssrc:n,type:ne.VIDEO,value:{delta_packets_in:g.deltaPacketsReceived}},{ssrc:n,type:ne.VIDEO,value:{total_packets_lost_in:g.packetsLost}},{ssrc:n,type:ne.VIDEO,value:{delta_packets_lost_in:g.deltaPacketsLost}},{ssrc:n,type:ne.VIDEO,value:{percent_packets_lost_in:g.percentPacketsLost}},{ssrc:n,type:ne.VIDEO,value:{total_KBytes_in:g.KBytesReceived}},{ssrc:n,type:ne.VIDEO,value:{delta_KBytes_in:g.deltaKBytesReceived}},{ssrc:n,type:ne.VIDEO,value:{delta_kbs_in:g.kbsReceived}},{ssrc:n,type:ne.VIDEO,value:{delta_jitter_ms_in:T}},{ssrc:n,type:ne.VIDEO,value:{decoder_in:E}},{ssrc:n,type:ne.VIDEO,value:{delta_ms_decode_frame_in:d.delta_ms_decode_frame}},{ssrc:n,type:ne.VIDEO,value:{total_frames_decoded_in:d.frames_decoded}},{ssrc:n,type:ne.VIDEO,value:{total_time_decoded_in:d.total_decode_time}},{ssrc:n,type:ne.VIDEO,value:{total_nack_sent_in:C.nackCount}},{ssrc:n,type:ne.VIDEO,value:{delta_nack_sent_in:C.deltaNackCount}},{ssrc:n,type:ne.VIDEO,value:{total_pli_sent_in:C.pliCount}},{ssrc:n,type:ne.VIDEO,value:{delta_pli_sent_in:C.deltaPliCount}},{ssrc:n,type:ne.VIDEO,value:{size_in:A}}]}break}case zt.OUTBOUND_RTP:{xe(Ps,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const n=c[V.SSRC],p=_t(n,s,$e.OUTBOUND);p&&(p.timestamp=s.timestamp);const _=_t(n,o,$e.OUTBOUND);if(_&&(_.timestamp=o.timestamp),c[V.MEDIA_TYPE]===x.AUDIO){const d=c[V.CODEC_ID]||null,g=I_(c,x.AUDIO,p,_);return[{ssrc:n,type:ne.AUDIO,value:{codec_id_out:d}},{ssrc:n,type:ne.AUDIO,value:{total_packets_out:g.packetsSent}},{ssrc:n,type:ne.AUDIO,value:{delta_packets_out:g.deltaPacketsSent}},{ssrc:n,type:ne.AUDIO,value:{total_KBytes_out:g.KBytesSent}},{ssrc:n,type:ne.AUDIO,value:{delta_KBytes_out:g.deltaKBytesSent}},{ssrc:n,type:ne.AUDIO,value:{delta_kbs_out:g.kbsSent}}]}if(c[V.MEDIA_TYPE]===x.VIDEO){const d=c[V.ENCODER_IMPLEMENTATION]||null,g=c[V.CODEC_ID]||null,T=iv(c,p),E=O_(c),y=av(c),A=cv(c,p,_),C=I_(c,x.VIDEO,p,_);return[{ssrc:n,type:ne.VIDEO,value:{codec_id_out:g}},{ssrc:n,type:ne.VIDEO,value:{total_packets_out:C.packetsSent}},{ssrc:n,type:ne.VIDEO,value:{delta_packets_out:C.deltaPacketsSent}},{ssrc:n,type:ne.VIDEO,value:{total_KBytes_out:C.KBytesSent}},{ssrc:n,type:ne.VIDEO,value:{delta_KBytes_out:C.deltaKBytesSent}},{ssrc:n,type:ne.VIDEO,value:{delta_kbs_out:C.kbsSent}},{ssrc:n,type:ne.VIDEO,value:{encoder_out:d}},{ssrc:n,type:ne.VIDEO,value:{delta_ms_encode_frame_out:T.delta_ms_encode_frame}},{ssrc:n,type:ne.VIDEO,value:{total_frames_encoded_out:T.frames_encoded}},{ssrc:n,type:ne.VIDEO,value:{total_time_encoded_out:T.total_encode_time}},{ssrc:n,type:ne.VIDEO,value:{total_nack_received_out:A.nackCount}},{ssrc:n,type:ne.VIDEO,value:{delta_nack_received_out:A.deltaNackCount}},{ssrc:n,type:ne.VIDEO,value:{total_pli_received_out:A.pliCount}},{ssrc:n,type:ne.VIDEO,value:{delta_pli_received_out:A.deltaPliCount}},{ssrc:n,type:ne.VIDEO,value:{size_out:E}},{ssrc:n,type:ne.VIDEO,value:{limitation_out:y}}]}break}case zt.MEDIA_SOURCE:{xe(Ps,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);break}case zt.TRACK:{xe(Ps,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);break}case zt.CODEC:const t=[];return Object.keys(s[x.AUDIO]).forEach(n=>{const p=s[x.AUDIO][n];if(p.codec_id_in===c[V.ID]||p.codec_id_out===c[V.ID]){xe(Ps,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const _=fv(c);c[V.ID]===p.codec_id_in?t.push({ssrc:p.ssrc,type:ne.AUDIO,value:{codec_in:_}}):t.push({ssrc:p.ssrc,type:ne.AUDIO,value:{codec_out:_}})}}),Object.keys(s[x.VIDEO]).forEach(n=>{const p=s[x.VIDEO][n];if(p.codec_id_in===c[V.ID]||p.codec_id_out===c[V.ID]){xe(Ps,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const _=_v(c);c[V.ID]===p.codec_id_in?t.push({ssrc:p.ssrc,type:ne.VIDEO,value:{codec_in:_}}):t.push({ssrc:p.ssrc,type:ne.VIDEO,value:{codec_out:_}})}}),t;case zt.REMOTE_INBOUND_RTP:{xe(Ps,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const n=c[V.SSRC],p=_t(n,s,$e.OUTBOUND),_=_t(n,o,$e.OUTBOUND);if(c[V.KIND]===x.AUDIO){const d=R_(c,x.AUDIO,_,p),g=vo(c,x.AUDIO,p),T=b_(c,x.AUDIO,p,_);return[{ssrc:n,type:ne.AUDIO,value:{delta_rtt_ms_out:d.rtt}},{ssrc:n,type:ne.AUDIO,value:{total_rtt_ms_out:d.totalRTT}},{ssrc:n,type:ne.AUDIO,value:{total_rtt_measure_out:d.totalRTTMeasurements}},{ssrc:n,type:ne.AUDIO,value:{delta_jitter_ms_out:g}},{ssrc:n,type:ne.AUDIO,value:{timestamp_out:c[V.TIMESTAMP]}},{ssrc:n,type:ne.AUDIO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:n,type:ne.AUDIO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:n,type:ne.AUDIO,value:{percent_packets_lost_out:T.fractionLost}}]}if(c[V.KIND]===x.VIDEO){const d=R_(c,x.VIDEO,_,p),g=vo(c,x.VIDEO,p),T=b_(c,x.VIDEO,p,_);return[{ssrc:n,type:ne.VIDEO,value:{delta_rtt_ms_out:d.rtt}},{ssrc:n,type:ne.VIDEO,value:{total_rtt_ms_out:d.totalRTT}},{ssrc:n,type:ne.VIDEO,value:{total_rtt_measure_out:d.totalRTTMeasurements}},{ssrc:n,type:ne.VIDEO,value:{delta_jitter_ms_out:g}},{ssrc:n,type:ne.VIDEO,value:{timestamp_out:c[V.TIMESTAMP]}},{ssrc:n,type:ne.VIDEO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:n,type:ne.VIDEO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:n,type:ne.VIDEO,value:{percent_packets_lost_out:T.fractionLost}}]}break}}return[]},Eo=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),mv=(c,s=x.AUDIO,r,o,a)=>{const t=_t(a,c,$e.INBOUND),n=_t(a,r,$e.INBOUND),p=_t(a,o,$e.INBOUND),_=[],d=[],g=t[s].percent_packets_lost_in,T=t[s].delta_jitter_ms_in,E=n&&n[s].delta_jitter_ms_in||null,y=p&&p[s].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,C=r&&r.data.delta_rtt_connectivity_ms||null,I=o&&o.data.delta_rtt_connectivity_ms||null;A&&_.push(A),C&&_.push(C),I&&_.push(I),T&&d.push(T),r&&E&&d.push(E),o&&y&&d.push(y);const $=_.length>0?Us(_):100,L=d.length>0?Us(d):10,ae=93.2-g,N=.18*ae*ae-27.9*ae+1126.62,F=($+L)/2,Se=F-177.3<0?0:1,ve=.024*F+.11*(F-177.3)*Se,M=N-ve;return Eo(M)},gv=(c,s=x.AUDIO,r,o,a)=>{const t=_t(a,c,$e.OUTBOUND),n=_t(a,r,$e.OUTBOUND),p=_t(a,o,$e.OUTBOUND),_=[],d=[],g=t[s].percent_packets_lost_out,T=t[s].delta_rtt_ms_out,E=n&&n[s].delta_rtt_ms_out||null,y=p&&p[s].delta_rtt_ms_out||null,A=t[s].delta_jitter_ms_out,C=n&&n[s].delta_jitter_ms_out||null,I=p&&p[s].delta_jitter_ms_out||null,$=c.data.delta_rtt_connectivity_ms,L=r&&r.data.delta_rtt_connectivity_ms||null,ae=o&&o.data.delta_rtt_connectivity_ms||null;T?_.push(T):$&&_.push($),E?_.push(E):L&&_.push(L),y?_.push(y):ae&&_.push(ae),A&&d.push(A),r&&C&&d.push(C),o&&I&&d.push(I);const N=_.length>0?Us(_):100,F=d.length>0?Us(d):10,Se=93.2-g,ve=.18*Se*Se-27.9*Se+1126.62,M=(N+F)/2,D=M-177.3<0?0:1,B=.024*M+.11*(M-177.3)*D,q=ve-B;return Eo(q)},Tv=(c,s=x.AUDIO,r,o,a)=>{const t=_t(a,c,$e.INBOUND),n=_t(a,r,$e.INBOUND),p=_t(a,o,$e.INBOUND),_=[],d=[],g=t[s].percent_packets_lost_in/100,T=t[s].delta_jitter_ms_in,E=n&&n[s].delta_jitter_ms_in||null,y=p&&p[s].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,C=r&&r.data.delta_rtt_connectivity_ms||null,I=o&&o.data.delta_rtt_connectivity_ms||null;A&&_.push(A),C&&_.push(C),I&&_.push(I),T&&d.push(T),n&&E&&d.push(E),p&&y&&d.push(y);const $=_.length>0?Us(_):100,L=d.length>0?Us(d):10,ae=0,N=19.8,F=29.7,Se=30,ve=($+L)/2+Se,M=ve-177.3<0?0:1,D=.024*ve+.11*(ve-177.3)*M,q=93.2-(ae+N*Math.log(1+F*g)+D);return Eo(q)},vv=(c,s=x.AUDIO,r,o,a)=>{const t=_t(a,c,$e.OUTBOUND),n=_t(a,r,$e.OUTBOUND),p=_t(a,o,$e.OUTBOUND),_=[],d=[],g=t[s].percent_packets_lost_out/100,T=t[s].delta_rtt_ms_out,E=n&&n[s].delta_rtt_ms_out||null,y=p&&p[s].delta_rtt_ms_out||null,A=t[s].delta_jitter_ms_out,C=n&&n[s].delta_jitter_ms_out||null,I=p&&p[s].delta_jitter_ms_out||null,$=c.data.delta_rtt_connectivity_ms,L=r&&r.data.delta_rtt_connectivity_ms||null,ae=o&&o.data.delta_rtt_connectivity_ms||null;T?_.push(T):$&&_.push($),E?_.push(E):L&&_.push(L),y?_.push(y):ae&&_.push(ae),A&&d.push(A),n&&C&&d.push(C),p&&I&&d.push(I);const N=_.length>0?Us(_):100,F=d.length>0?Us(d):10,Se=0,ve=19.8,M=29.7,D=30,B=(N+F)/2+D,q=B-177.3<0?0:1,z=.024*B+.11*(B-177.3)*q,Z=93.2-(Se+ve*Math.log(1+M*g)+z);return Eo(Z)};class Ev{constructor(s,r){this._callbacks={onreport:null,onticket:null},this._id=JT(),this._moduleName=this._id,this._probeId=r,this._config=s,this._exporter=new sv(s),this._state=Ts.IDLE,this.registerToPCEvents(),sn(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(s,r,o,a){const t=(_,d)=>_===x.AUDIO?d===zt.INBOUND_RTP?{...v_}:{...E_}:d===zt.INBOUND_RTP?{...S_}:{...y_},n=GT(r);n.pname=this._config.pname,n.call_id=this._config.cid,n.user_id=this._config.uid,n.count=r?r.count+1:1;let p=null;return s.forEach(_=>{!p&&_.timestamp&&(p=_.timestamp),pv(_,n,n.pname,a).forEach(g=>{if(g.value&&g.type)if(g.ssrc){let T=n[g.type][g.ssrc];T||(T=t(g.type,_.type),T.ssrc=g.ssrc,n[g.type][g.ssrc]=T),Object.keys(g.value).forEach(E=>{T[E]=g.value[E]})}else Object.keys(g.value).forEach(T=>{n[g.type][T]=g.value[T]})})}),n.timestamp=p,Object.keys(n[x.AUDIO]).forEach(_=>{const d=n[x.AUDIO][_];d.direction===$e.INBOUND?(d.mos_emodel_in=mv(n,x.AUDIO,r,o,d.ssrc),d.mos_in=Tv(n,x.AUDIO,r,o,d.ssrc)):(d.mos_emodel_out=gv(n,x.AUDIO,r,o,d.ssrc),d.mos_out=vv(n,x.AUDIO,r,o,d.ssrc))}),n}async takeReferenceStats(){return new Promise((s,r)=>{const o=Date.now();setTimeout(async()=>{try{const a=Date.now()-o,t=Date.now(),n=await this._config.pc.getStats(),p=this.analyze(n,null,null,null),_=Date.now();p.experimental.time_to_measure_ms=_-t,p.experimental.time_to_wait_ms=a,this._exporter.saveReferenceReport(p),xe(this._moduleName,`got reference report for probe ${this._probeId}`),s()}catch(a){r(a)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==Ts.RUNNING||!this._config.pc)return xe(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const s=Date.now(),r=await this._config.pc.getStats(),o=this.analyze(r,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),a=Date.now();return o.experimental.time_to_measure_ms=a-s,this._exporter.addReport(o),xe(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(o),o}catch(s){return Fn(this._moduleName,`got error ${s}`),null}}async start(){xe(this._moduleName,"starting"),this.state=Ts.RUNNING,this._startedTime=this._exporter.start(),xe(this._moduleName,"started")}async mute(){this.state=Ts.MUTED,xe(this._moduleName,"muted")}async unmute(){this.state=Ts.RUNNING,xe(this._moduleName,"unmuted")}async stop(s){if(xe(this._moduleName,`stopping${s?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=Ts.IDLE,this._config.ticket){const{ticket:r}=this._exporter;this.fireOnTicket(r)}this._exporter.reset(),xe(this._moduleName,"stopped")}registerCallback(s,r,o){s in this._callbacks?(this._callbacks[s]={callback:r,context:o},xe(this._moduleName,`registered callback '${s}'`)):Fn(this._moduleName,`can't register callback for '${s}' - not found`)}unregisterCallback(s){s in this._callbacks?(this._callbacks[s]=null,delete this._callbacks[s],xe(this._moduleName,`unregistered callback '${s}'`)):Fn(this._moduleName,`can't unregister callback for '${s}' - not found`)}fireOnReport(s){this._callbacks.onreport&&Su(this._callbacks.onreport.callback,this._callbacks.onreport.context,s)}fireOnTicket(s){this._callbacks.onticket&&Su(this._callbacks.onticket.callback,this._callbacks.onticket.context,s)}updateConfig(s){this._config=s,this._exporter.updateConfig(s)}get state(){return this._state}set state(s){this._state=s,xe(this._moduleName,`state changed to ${s}`)}addCustomEvent(s,r,o,a){this._exporter.addCustomEvent({at:typeof s=="object"?s.toJSON():s,category:r,name:o,description:a})}async registerToPCEvents(){const{pc:s}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const r=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${r.length} devices found`,"Media Devices state")}catch{Fn(this._moduleName,"can't get devices")}},s){s.oniceconnectionstatechange=()=>{const o=s.iceConnectionState;o===ei.CONNECTED||o===ei.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===ei.DISCONNECTED||o===ei.FAILED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===ei.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},s.onicegatheringstatechange=()=>{const o=s.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",o,"ICE gathering state")},s.ontrack=o=>{this.addCustomEvent(new Date().toJSON(),"call",`${o.track.kind}track`,"MediaStreamTrack received")},s.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const r=s.getReceivers();if(r&&r.length>0){const o=r[0],{transport:a}=o;if(a){const{iceTransport:t}=a;t&&(t.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class Sv{constructor(s){this._id=s.pname&&s.pname.substr(0,12).padEnd(12," ")||zT(),this._moduleName=this._id,sn(this._moduleName,"probe created"),this._config=s,this._collector=new Ev(this._config,this._id)}set onreport(s){s?this._collector.registerCallback("onreport",s):this._collector.unregisterCallback("onreport")}set onticket(s){s?this._collector.registerCallback("onticket",s):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(s){this._collector.state=s}addCustomEvent(s,r,o,a=new Date().toJSON()){this._collector.addCustomEvent(a,r,s,o)}get isRunning(){return this._collector.state===Ts.RUNNING}get isIdle(){return this._collector.state===Ts.IDLE}updateUserId(s){this._config.uid=s,this._collector.updateConfig(this._config)}updateCallId(s){this._config.cid=s,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){To(this._moduleName,"probe is already running");return}this._collector.start()}stop(s=!1){this.isRunning&&this._collector.stop(s)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const It="engine ";class yv{constructor(s){this._config=s,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},sn(It,`configured for probing every ${this._config.refreshEvery}ms`),sn(It,`configured for starting after ${this._config.startAfter}ms`),sn(It,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),xe(It,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(s=>s.isRunning)}get isIdle(){return this._probes.every(s=>s.isIdle)}addNewProbe(s,r){if(!s)throw new Error("undefined peer connection");const o=KT(s,r,this._config),a=new Sv(o);return this._probes.push(a),xe(It,`${this._probes.length} probes registered`),a}removeExistingProbe(s){if(!s)throw new Error("undefined probe");s.state===Ts.RUNNING&&s.stop(),this._probes=this._probes.filter(r=>s.id!==r.id)}async start(){const s=()=>{this._probes.forEach(t=>t.start())},r=async()=>Promise.all(this._probes.map(t=>t.takeReferenceStats())),o=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,a=async()=>{const t=BT(),n=this._probes.filter(p=>p.isRunning);for(const p of n){const _=await p.collectStats();_&&t.probes.push(_),xe(It,`got probe ${p.id}`),await A_(0)}return t.delta_time_to_measure_probes_ms=nn(t.probes,"experimental","time_to_measure_ms"),t.delta_KBytes_in=nn(t.probes,"data","delta_KBytes_in"),t.delta_KBytes_out=nn(t.probes,"data","delta_KBytes_out"),t.delta_kbs_in=nn(t.probes,"data","delta_kbs_in"),t.delta_kbs_out=nn(t.probes,"data","delta_kbs_out"),t.total_time_decoded_in=nn(t.probes,"video","total_time_decoded_in"),t.total_time_encoded_out=nn(t.probes,"video","total_time_encoded_out"),t};for(xe(It,"starting to collect"),s(),xe(It,"generating reference reports..."),await r(),xe(It,"reference reports generated"),this._startedTime=Date.now();o();)if(xe(It,`wait ${this._config.refreshEvery}ms before collecting`),await A_(this._config.refreshEvery),o()){xe(It,"collecting...");const t=Date.now(),n=await a(),p=Date.now();n.delta_time_consumed_to_measure_ms=p-t,this.fireOnReports(n),xe(It,"collected")}xe(It,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(s){const r=o=>{this._probes.forEach(a=>{a.stop(o)})};sn(It,"stop collecting"),r(s)}registerCallback(s,r,o){s in this._callbacks?(this._callbacks[s]={callback:r,context:o},xe(It,`registered callback '${s}'`)):Fn(It,`can't register callback for '${s}' - not found`)}unregisterCallback(s){s in this._callbacks?(this._callbacks[s]=null,delete this._callbacks[s],xe(this._moduleName,`unregistered callback '${s}'`)):Fn(this._moduleName,`can't unregister callback for '${s}' - not found`)}fireOnReports(s){this._callbacks.onresult&&s.probes.length>0&&Su(this._callbacks.onresult.callback,this._callbacks.onresult.context,s)}}const Av="interface ";class Cv{constructor(s){this._config=YT(s),sn(Av,`welcome to ${this._config.name} version ${this._config.version}`),kT(this._config.verbose||!1),this._engine=new yv(this._config)}setupLogLevel(s){LT(s)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(s,r){return this._engine.addNewProbe(s,r)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(s){this._engine.removeExistingProbe(s)}set onresult(s){s?this._engine.registerCallback("onresult",s):this._engine.unregisterCallback("onresult")}}function Rv(c,s){return Object.keys(c).filter(r=>s.includes(r)).reduce((r,o)=>{const a=o;return{...r,[a]:c[a]}},{})}const Iv=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"];class bv{constructor(s){this.intervals={},this.emitInterval=s.emitInterval||200,this.onChangeFunction=s.onChangeFunction}start(s,r){s&&s.getTracks().length&&requestAnimationFrame(()=>this.beginCalculation(s,r))}stop(s){this.clearVolumeInterval(s)}clearVolumeInterval(s){console.log("clearVolumeInterval",s),clearInterval(this.intervals[s]),delete this.intervals[s]}clearAllIntervals(){Object.keys(this.intervals).forEach(s=>{clearInterval(this.intervals[s])}),this.intervals={}}beginCalculation(s,r){this.clearVolumeInterval(r);const o=tn.createAnalyser(),a=tn.createMediaStreamSource(s),t=tn.createScriptProcessor(2048,1,1);o.smoothingTimeConstant=.8,o.fftSize=1024,a.connect(o),o.connect(t),t.connect(tn.destination),this.intervals[r]=setInterval(()=>{const n=new Uint8Array(o.frequencyBinCount);o.getByteFrequencyData(n);let p=0;const _=n.length;for(let g=0;g<_;g++)p+=n[g];const d=p/_;this.onChangeFunction(r,d)},this.emitInterval)}}const So={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},wv=0;class Ov{constructor(s){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=s,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new bv({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices()}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(s){this.currentActiveRoomIdValue=s,this.context.emit("currentActiveRoomChanged",s)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(s){this.isCallAddingInProgress=s,this.context.emit("callAddingInProgressChanged",s)}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(s=>s.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(s=>s.kind==="audiooutput")}get getUserMediaConstraints(){return d_()?{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(s){this.availableMediaDevices=s,this.context.emit("changeAvailableDeviceList",s)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const s=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(s)}async initializeMediaDevices(){const s=localStorage.getItem(So.SELECTED_INPUT_DEVICE)||"default",r=localStorage.getItem(So.SELECTED_OUTPUT_DEVICE)||"default";try{const o=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),a=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(a),await this.setMicrophone(s),await this.setSpeaker(r),navigator.mediaDevices.addEventListener("devicechange",async()=>{const t=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(t)}),o.getTracks().forEach(t=>t.stop())}catch(o){console.error(o)}}setCallTime(s){const r={...s};delete r.callId,this.callTime={...this.callTime,[s.callId]:r},this.context.emit("changeCallTime",this.callTime)}removeCallTime(s){const r={...this.callTime};delete r[s],this.callTime={...r},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(s,r){this.timeIntervals={...this.timeIntervals,[s]:r}}removeTimeInterval(s){const r={...this.timeIntervals};r[s]&&(clearInterval(r[s]),delete r[s],this.timeIntervals={...r})}stopCallTimer(s){this.removeTimeInterval(s),this.removeCallTime(s)}emitVolumeChange(s,r){this.context.emit("changeCallVolume",{callId:s,volume:r})}setMetricsConfig(s){this.metricConfig={...this.metricConfig,...s}}sendDTMF(s,r){if(!/^[A-D0-9]+$/g.test(r))throw new Error("Not allowed character in DTMF input");this.extendedCalls[s].sendDTMF(r)}setIsMuted(s){this.muted=s,this.context.emit("changeIsMuted",s)}processMute(s){const r=this.currentActiveRoomId;this.setIsMuted(s),this.initialStreamValue.getTracks().forEach(o=>o.enabled=!s),this.roomReconfigure(r)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:s,toHold:r,automatic:o}){const a=this.extendedCalls[s];a._automaticHold=o??!1,await new Promise(p=>{const _=()=>{p()};r?a.hold({},_):a.unhold({},_)}),this.updateCall(a);const n=Object.values(this.extendedCalls).filter(p=>p.roomId===this.currentActiveRoomId&&(r?s!==p._id:!0));n.length>1&&await this.doConference(n)}holdCall(s,r=!1){return this.processHold({callId:s,automatic:r,toHold:!0})}unholdCall(s){return this.processHold({callId:s,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(s=>s.direction==="outgoing"&&s.status===wv).forEach(s=>this.terminateCall(s._id))}answerCall(s){const r=this.extendedCalls[s];this.cancelAllOutgoingUnanswered(),r.answer(this.sipOptions),this.updateCall(r),this.setActiveRoom(r.roomId),r.connection.addEventListener("track",o=>{this.triggerAddStream(o,r)})}async moveCall(s,r){this.updateCallStatus({callId:s,isMoving:!0}),await this.processRoomChange({callId:s,roomId:r}),this.updateCallStatus({callId:s,isMoving:!1})}updateCall(s){this.activeCalls[s._id]=f_(s),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(s){const o={...this.activeRooms[s.roomId],...s};this.activeRooms={...this.activeRooms,[s.roomId]:{...o}},this.context.emit("updateRoom",{room:o,roomList:this.activeRooms})}hasAutoAnswerHeaders(s){const r=/answer-after=0/,a=s.request.getHeader("Call-Info");return a&&r.test(a)}addCall(s,r=!0){this.activeCalls={...this.activeCalls,[s._id]:f_(s)},this.extendedCalls[s._id]=s,r&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(s){this.callStatus={...this.callStatus,[s]:{isMoving:!1,isTransferring:!1,isMerging:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(s){const o={...{...this.callStatus[s.callId]}};s.isMoving!==void 0&&(o.isMoving=s.isMoving),s.isTransferring!==void 0&&(o.isTransferring=s.isTransferring),s.isMerging!==void 0&&(o.isMerging=s.isMerging),this.callStatus={...this.callStatus,[s.callId]:{...o}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(s){const r={...this.callStatus};delete r[s],this.callStatus={...r},this.context.emit("changeCallStatus",this.callStatus)}addRoom(s){this.activeRooms={...this.activeRooms,[s.roomId]:s},this.context.emit("addRoom",{room:s,roomList:this.activeRooms})}getActiveStream(){const s=h_(this.initialStreamValue,this.microphoneInputLevel*2);return s.getTracks().forEach(r=>r.enabled=!this.isMuted),this.setActiveStream(s),s}async setMicrophone(s){if(!this.getInputDeviceList.find(({deviceId:o})=>o===s)||(this.setSelectedInputDevice(s),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const r=Object.values(this.extendedCalls).filter(o=>o.roomId===this.currentActiveRoomId);r.length===1?Object.values(r).forEach(async o=>{const a=this.getActiveStream();o.connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.updateCall(o)}):await this.doConference(r)}setActiveStream(s){this.activeStream&&this.stopVUMeter("origin"),this.setupVUMeter(s,"origin"),this.activeStreamValue=s,this.context.emit("changeActiveStream",s)}async setSpeaker(s){if(!this.getOutputDeviceList.find(({deviceId:a})=>a===s))return;this.setSelectedOutputDevice(s);const r=Object.values(this.extendedCalls);if(r.length===0)return;const o=r.filter(a=>a.roomId===this.currentActiveRoomId);o.length===1?r.forEach(a=>{var t;(t=a.audioTag)==null||t.setSinkId(s),this.updateCall(a)}):await this.doConference(o)}removeRoom(s){const r={...this.activeRooms},o={...r[s]};delete r[s],this.activeRooms={...r},this.context.emit("removeRoom",{room:o,roomList:this.activeRooms})}deleteRoomIfEmpty(s){s!==void 0&&Object.values(this.extendedCalls).filter(r=>r.roomId===s).length===0&&(this.removeRoom(s),this.currentActiveRoomId===s&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(s){this.muted?s.mute({audio:!0}):s.unmute({audio:!0})}async roomReconfigure(s){var o;if(s===void 0)return;const r=Object.values(this.extendedCalls).filter(a=>a.roomId===s);if(this.currentActiveRoomId===s?r.forEach(a=>{a.audioTag&&(this.muteReconfigure(a),a.audioTag.muted=!1,this.updateCall(a))}):r.forEach(a=>{a.audioTag&&(a.audioTag.muted=!0,this.updateCall(a))}),r.length===0)this.deleteRoomIfEmpty(s);else if(r.length===1&&this.currentActiveRoomId!==s)r[0].isOnHold().local||await this.holdCall(r[0].id,!0);else if(r.length===1&&this.currentActiveRoomId===s){if(r[0].isOnHold().local&&r[0]._automaticHold&&await this.unholdCall(r[0].id),r[0].connection&&((o=r[0].connection)!=null&&o.getSenders()[0])){const a=this.getActiveStream();await r[0].connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.muteReconfigure(r[0])}}else r.length>1&&await this.doConference(r)}async doConference(s){await m_.forEach(s,async o=>{o._localHold&&await this.unholdCall(o._id)});const r=[];s.forEach(o=>{o!=null&&o.connection.getReceivers().forEach(a=>{r.push(a.track)})}),await m_.forEach(s,async o=>{var n;if(o==null)return;const a=new MediaStream,t=tn.createMediaStreamDestination();if(o.connection.getReceivers().forEach(p=>{r.forEach(_=>{a.addTrack(p.track),p.track.id!==_.id&&tn.createMediaStreamSource(new MediaStream([_])).connect(t)})}),s[0].roomId===this.currentActiveRoomId){const p=this.getActiveStream();tn.createMediaStreamSource(p).connect(t)}(n=o.connection)!=null&&n.getSenders()[0]&&(await o.connection.getSenders()[0].replaceTrack(t.stream.getTracks()[0]),this.muteReconfigure(o))})}processCallerMute(s,r){const o=this.extendedCalls[s];o&&o.connection.getReceivers().length&&(o.localMuted=r,o.connection.getReceivers().forEach(a=>{a.track.enabled=!r}),this.updateCall(o))}muteCaller(s){this.processCallerMute(s,!0)}unmuteCaller(s){this.processCallerMute(s,!1)}terminateCall(s){const r=this.extendedCalls[s];r._status!==8&&r.terminate()}transferCall(s,r){if(r.toString().length===0)return new Error("Target must be passed");const o=this.extendedCalls[s];if(!o._is_confirmed&&!o._is_canceled){const a=`sip:${r}@${this.context.sipDomain}`;o.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${a}`]});return}this.updateCallStatus({callId:s,isTransferring:!0}),o.refer(`sip:${r}@${this.context.sipDomain}`),this.updateCall(o)}mergeCall(s){const r=Object.values(this.extendedCalls).filter(t=>t.roomId===s);if(r.length!==2)return;const o=r[0],a=r[1];!o||!a||(this.updateCallStatus({callId:o._id,isMerging:!0}),this.updateCallStatus({callId:a._id,isMerging:!0}),o.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(o))}setDND(s){this.isDNDEnabled=s,this.context.emit("changeIsDND",s)}startCallTimer(s){this.removeTimeInterval(s);const r={callId:s,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(r);const o=setInterval(()=>{const a={...this.callTime[s]},t=xT(a);this.setCallTime({callId:s,...t})},1e3);this.setTimeInterval(s,o)}async setActiveRoom(s){const r=this.currentActiveRoomId;s!==r&&(this.currentActiveRoomId=s,await this.roomReconfigure(r),await this.roomReconfigure(s))}getNewRoomId(){const s=Object.keys(this.activeRooms);return s.length===0?1:parseInt(s.sort()[s.length-1])+1}async setupCall(s){var d,g;const r=s.session;if(this.getActiveCalls[r.id]!==void 0)return;const a=this.getNewRoomId(),t={started:new Date,incomingInProgress:!1,roomId:a};r.direction==="incoming"?(this.context.logger.log("New incoming call from",(g=(d=r._remote_identity)==null?void 0:d._uri)==null?void 0:g._user),t.incomingInProgress=!0,this.context.subscribe(Yt.CALL_CONFIRMED,T=>{r.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.startCallTimer(r.id))}),this.context.subscribe(Yt.CALL_FAILED,T=>{r.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.deleteRoomIfEmpty(a))})):r.direction==="outgoing"&&(r.once("confirmed",()=>{this.startCallTimer(r.id)}),this.startCallTimer(r.id));const n=r,p=this.hasAutoAnswerHeaders(s),_=n.direction==="incoming"&&!this.hasActiveCalls&&(p||this.autoAnswer);n.roomId=a,n.localMuted=!1,n.autoAnswer=_,_?this.addCall(n,!1):this.addCall(n),this.addCallStatus(r.id),this.addRoom(t),_&&this.answerCall(n._id)}removeCall(s){const r={...this.activeCalls};delete r[s],this.activeCalls={...r};const o={...this.extendedCalls};delete o[s],this.extendedCalls={...o},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(s){var a;const r=this.extendedCalls[s._id];this.stopVUMeter("origin"),(a=r.connection)==null||a.getSenders().forEach(t=>{t.track.stop()});const o=r.roomId;this.removeCall(s._id),this.roomReconfigure(o)}async newRTCSessionCallback(s){const r=s.session;if(this.isDND){r.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(this.context.triggerListener({listenerType:Yt.NEW_CALL,session:r,event:s}),r.on("ended",o=>{var t,n,p;this.stopVUMeter(r.id),this.context.logger.log("Session ended for",(n=(t=r._remote_identity)==null?void 0:t._uri)==null?void 0:n._user),this.context.triggerListener({listenerType:Yt.CALL_ENDED,session:r,event:o});const a=this.getActiveCalls[r.id];a&&this.activeCallListRemove(a),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(p=this.initialStreamValue)==null||p.getTracks().forEach(_=>_.stop()),this.initialStreamValue=null)}),r.on("progress",o=>{var a,t;this.context.logger.log("Session in progress for",(t=(a=r._remote_identity)==null?void 0:a._uri)==null?void 0:t._user),this.context.triggerListener({listenerType:Yt.CALL_PROGRESS,session:r,event:o})}),r.on("failed",o=>{var t,n,p;this.stopVUMeter(r.id),this.context.logger.log("Session failed for",(n=(t=r._remote_identity)==null?void 0:t._uri)==null?void 0:n._user),this.context.triggerListener({listenerType:Yt.CALL_FAILED,session:r,event:o}),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const a=this.getActiveCalls[r.id];a&&this.activeCallListRemove(a),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(p=this.initialStreamValue)==null||p.getTracks().forEach(_=>_.stop()),this.initialStreamValue=null)}),r.on("confirmed",o=>{var a,t;this.context.logger.log("Session confirmed for",(t=(a=r._remote_identity)==null?void 0:a._uri)==null?void 0:t._user),this.context.triggerListener({listenerType:Yt.CALL_CONFIRMED,session:r,event:o}),this.updateCall(r),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(s),r.direction==="outgoing"){const o=this.getActiveCalls[r.id].roomId;this.setActiveRoom(o)}}setMuteWhenJoin(s){this.muteWhenJoinEnabled=s,this.context.emit("changeMuteWhenJoin",s)}setMicrophoneSensitivity(s){if(s<0||s>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=s,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(s){this.speakerVolumeValue=s,Object.values(this.extendedCalls).forEach(r=>{r.audioTag&&(r.audioTag.volume=s,this.updateCall(r))})}setAutoAnswer(s){this.isAutoAnswer=s}setSelectedInputDevice(s){localStorage.setItem(So.SELECTED_INPUT_DEVICE,s),this.selectedMediaDevices.input=s,this.context.emit("changeActiveInputMediaDevice",s)}setSelectedOutputDevice(s){localStorage.setItem(So.SELECTED_OUTPUT_DEVICE,s),this.selectedMediaDevices.output=s,this.context.emit("changeActiveOutputMediaDevice",s)}setCallMetrics(s){const r={...s};delete r.callId,this.callMetrics={...this.callMetrics,[s.callId]:r},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(s){const r={...this.callMetrics};delete r[s],this.callMetrics={...r},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(s){const r=new Cv(this.metricConfig),o=r.createProbe(s.connection,{cid:s._id}),a=[];let t;o.onreport=n=>{Object.entries(n.audio).forEach(([d,g])=>{g.direction==="inbound"&&!a.includes(d)&&(a.push(d),t=d)});const p=n.audio[t];if(!p)return;const _=Rv(p,Iv);_.callId=s._id,this.setCallMetrics(_)},this.context.subscribe(Yt.CALL_ENDED,n=>{n._id===s._id&&r.stopAllProbes()}),r.startAllProbes()}setupVUMeter(s,r){this.VUMeter.start(s,r)}stopVUMeter(s){this.VUMeter.stop(s)}async setupStream(){const s=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach(r=>r.stop()),this.initialStreamValue=null),this.initialStreamValue=s}async triggerAddStream(s,r){this.setIsMuted(this.muteWhenJoin||this.isMuted),this.initialStreamValue||await this.setupStream();const o=h_(this.initialStreamValue,this.microphoneInputLevel*2),a=this.isMuted||this.muteWhenJoin;o.getTracks().forEach(n=>n.enabled=!a),this.setActiveStream(o),await r.connection.getSenders()[0].replaceTrack(o.getTracks()[0]);const t=new MediaStream([s.track]);vT(t,r,this.selectedOutputDevice,this.speakerVolume),this.setupVUMeter(t,r._id),this.getCallQuality(r),this.updateCall(r)}initCall(s,r){if(this.checkInitialized(),s.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${s}@${this.context.sipDomain}...`);const o=this.context.call(`sip:${s}@${this.context.sipDomain}`,this.sipOptions);this.callAddingInProgress=o.id,r&&this.currentActiveRoomId!==void 0&&this.processRoomChange({callId:o.id,roomId:this.currentActiveRoomId}),o.connection.addEventListener("track",a=>{this.triggerAddStream(a,o)})}async processRoomChange({callId:s,roomId:r}){const o=this.extendedCalls[s].roomId;this.extendedCalls[s].roomId=r;const a=this.extendedCalls[s];return this.updateCall(a),await this.setActiveRoom(r),Promise.all([this.roomReconfigure(o),this.roomReconfigure(r)]).then(()=>{this.deleteRoomIfEmpty(o),this.deleteRoomIfEmpty(r)})}}class Dv{constructor(s){this.context=s}get sipOptions(){return{...this.context.options.sipOptions}}initCall(s,r){if(s.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${s}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${s}@${this.context.sipDomain}`,r,this.sipOptions),console.log("video call")}stop(s={}){this.context.terminateJanusSessions(s)}}class Nv{constructor(s){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=s,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this.context))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(s){const r=this.extendedMessages[s];this.updateMSRPSession(r)}updateMSRPSession(s){this.activeMessages[s._id]=__(s),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(s){this.activeMessages={...this.activeMessages,[s._id]:__(s)},this.extendedMessages[s._id]=s,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(s,r){const o=this.msrpHistory[r.id]||[];o.push(s),this.msrpHistory={...this.msrpHistory,[r.id]:[...o]},this.context.emit("newMSRPMessage",{message:s,session:r})}messageTerminate(s){const r=this.extendedMessages[s];r._status!==8&&r.terminate()}addMessageSession(s){if(!s._id||this.getActiveMessages[s._id]!==void 0)return;const o=s;this.addMMSRPSession(o)}triggerMSRPListener({listenerType:s,session:r,event:o}){const a=this.context.listenersList[s];!a||!a.length||a.forEach(t=>{t(r,o)})}removeMMSRPSession(s){const r={...this.activeMessages};delete r[s],this.activeMessages={...r};const o={...this.extendedMessages};delete o[s],this.extendedMessages={...o},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(s){this.removeMMSRPSession(s._id)}newMSRPSessionCallback(s){const r=s.session;r.on("ended",o=>{this.triggerMSRPListener({listenerType:Yt.CALL_ENDED,session:r,event:o});const a=this.getActiveMessages[r.id];this.activeMessageListRemove(a)}),r.on("failed",o=>{this.triggerMSRPListener({listenerType:Yt.CALL_FAILED,session:r,event:o});const a=this.getActiveMessages[r.id];this.activeMessageListRemove(a)}),r.on("confirmed",o=>{this.triggerMSRPListener({listenerType:Yt.CALL_CONFIRMED,session:r,event:o}),this.updateMSRPSession(r)}),r.on("newMessage",o=>{this.addMSRPMessage(o,r)}),this.addMessageSession(r)}setIsMSRPInitializing(s){this.isMSRPInitializingValue=s,this.context.emit("isMSRPInitializingChanged",s)}initMSRP(s,r,o){if(s.length===0)return console.error("Target must be a valid string");const a=this.context.startMSRP(s,o);a.on("active",()=>{this.addMessageSession(a),a.sendMSRP(r),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(s,r){const o=this.extendedMessages[s];if(!o)throw new Error(`MSRP session with id ${s} doesn't exist!`);o.sendMSRP(r)}}const yu={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Uv extends _T{constructor(s,r){if(!s.modules.length)throw new Error("options.modules should include at least 1 module");const o={...s.configuration,sockets:s.socketInterfaces.map(a=>new PT.WebSocketInterface(a))};super(o),this.initialized=!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.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],s.pnExtraHeaders&&Object.keys(s.pnExtraHeaders).length&&this.registrator().setExtraContactParams(s.pnExtraHeaders),this.options=s,this.modules=s.modules,r&&ET(r)&&(this.logger=r)}on(s,r){return super.on(s,r)}off(s,r){return super.off(s,r)}emit(s,r){return super.emit(s,r)}get sipDomain(){return this.options.sipDomain}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(yu.AUDIO)&&(this.audio=new Ov(this)),this.modules.includes(yu.MSRP)&&(this.msrp=new Nv(this)),this.modules.includes(yu.VIDEO)&&(this.video=new Dv(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.isReconnecting=!1}),this.on(this.disconnectedEventName,()=>{this.isReconnecting||(this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.isReconnecting=!0,this.stop(),this.setInitialized(!1),setTimeout(this.start.bind(this),5e3))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}subscribe(s,r){const a=!this.listenersList[s]||!this.listenersList[s].length?[r]:[...this.listenersList[s],r];this.listenersList={...this.listenersList,[s]:a}}removeIListener(s){const r={...this.listenersList};delete r[s],this.listenersList={...r}}triggerListener({listenerType:s,session:r,event:o}){const a=this.listenersList[s];!a||!a.length||a.forEach(t=>{t(r,o)})}setInitialized(s){this.initialized=s,this.emit("ready",s)}}return Uv});
156
+ `),this._newMSRPSession("local",this._request),this._id=this._request.call_id+this._from_tag,console.log("dialog be",this._dialog),new Nf(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:t=>{this.onTransportError(),console.log(t)},onAuthenticated:t=>{this._request=t},onReceiveResponse:t=>{this._receiveInviteResponse(t),console.log("dialog af",this._dialog),t.status_code===200&&(t.parseSDP(!0),this._status=Ce.STATUS_CONFIRMED,this.target_addr=t.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=Ce.STATUS_INVITE_SENT}terminate(s={}){console.log("terminate",this);const r=s.cause||j.causes.BYE,o=ke.cloneArray(s.extraHeaders),a=s.body;let t,n=s.status_code,p=s.reason_phrase;if(this._status===Ce.STATUS_TERMINATED)throw new bs.InvalidStateError(this._status);switch(this.status="terminated",this._status){case Ce.STATUS_NULL:case Ce.STATUS_INVITE_SENT:case Ce.STATUS_1XX_RECEIVED:if(n&&(n<200||n>=700))throw new TypeError(`Invalid status_code: ${n}`);n&&(p=p||j.REASON_PHRASE[n]||"",t=`SIP ;cause=${n} ;text="${p}"`),this._status===Ce.STATUS_NULL||this._status===Ce.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=t):this._status===Ce.STATUS_1XX_RECEIVED&&this._request.cancel(t),this._status=Ce.STATUS_CANCELED,console.log("failed 1"),this._failed("local",null,j.causes.CANCELED);break;case Ce.STATUS_WAITING_FOR_ANSWER:case Ce.STATUS_ANSWERED:if(n=n||480,console.log("REPLY 480"),n<300||n>=700)throw new TypeError(`Invalid status_code: ${n}`);this._request.reply(n,p,o,a),console.log("failed 2"),this._failed("local",null,j.causes.REJECTED);break;case Ce.STATUS_WAITING_FOR_ACK:case Ce.STATUS_CONFIRMED:if(p=s.reason_phrase||j.REASON_PHRASE[n]||"",n&&(n<200||n>=700))throw new TypeError(`Invalid status_code: ${n}`);if(n&&o.push(`Reason: SIP ;cause=${n}; text="${p}"`),this._status===Ce.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==$t.C.STATUS_TERMINATED){const _=this._dialog;this.receiveRequest=({method:d})=>{d===j.ACK&&(this.sendRequest(j.BYE,{extraHeaders:o,body:a}),_.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===$t.C.STATUS_TERMINATED&&(this.sendRequest(j.BYE,{extraHeaders:o,body:a}),_.terminate())}),this._ended("local",null,r),this._dialog=_,this._ua.newDialog(_)}else console.log("here it is"),this.sendRequest(j.BYE,{extraHeaders:o,body:a}),this._ended("local",null,r)}}sendRequest(s,r){return this._dialog.sendRequest(s,r)}authenticate(s){this.status="auth";let r=new Hn("");r.method="AUTH",r.addHeader("To-Path",`msrp://${this._ua._configuration.realm}:2856;ws`),r.addHeader("From-Path",`msrp://${this.credentials.username}.${this.credentials.realm}:2856/${this.auth_id};ws`),s&&r.addHeader("Authorization",s.toString());let o=r.toString();console.log(o);let a=[];for(var t=0;t<o.length;t++)a.push(o.charCodeAt(t).toString(16));console.log(a),this._connection.send(r.toString())}onmessage(s){console.log("onmessage",s);const r=new Hn(s.data);if(this.status==="auth"&&r.code===401){const o=this.parseAuth(r.getHeader("WWW-Authenticate")),a=new ym(this.credentials);a.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},o,ke.createRandomToken(12)),this.authenticate(a)}this.status==="auth"&&r.code===200&&this._direction==="outgoing"?(this.my_addr.push(r.getHeader("To-Path")),this.my_addr.push(r.getHeader("Use-Path")),this.status="active",this.inviteParty(r)):this.status==="auth"&&r.code===200&&this._direction==="incoming"?(this.my_addr.push(r.getHeader("To-Path")),this.my_addr.push(r.getHeader("Use-Path")),this.status="active",this.acceptParty(r),this.emit("confirmed")):r.method==="SEND"&&(this._sendOk(r),this._sendReport(r),r.direction="incoming",this.emit("newMessage",r),this._msgHistory.push(r),this.emit("msgHistoryUpdate",this._msgHistory),console.log("======================================================================")),r.code===480&&this._close()}onclose(){console.log("close")}onopen(){const s=new RTCPeerConnection({iceServers:[]});s.createDataChannel(""),s.createOffer().then(s.setLocalDescription.bind(s)),s.onicecandidate=r=>{if(!r||!r.candidate||!r.candidate.candidate)return;const o=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,a=r.candidate.candidate.match(o);this.my_ip=a&&a[1],s.onicecandidate=()=>{},this.authenticate(null)}}onerror(s){console.log(s)}_receiveInviteResponse(s){if(console.log("resp0000000000000",s),this._dialog&&s.status_code>=200&&s.status_code<=299)if(console.log("200000000000000"),this._dialog.id.call_id===s.call_id&&this._dialog.id.local_tag===s.from_tag&&this._dialog.id.remote_tag===s.to_tag){this.sendRequest(j.ACK);return}else{const r=new io(this,s,"UAC");if(r.error!==void 0){console.log(r.error);return}this.sendRequest(j.ACK),this.sendRequest(j.BYE);return}if(this._is_canceled){s.status_code>=100&&s.status_code<200?this._request.cancel(this._cancel_reason):s.status_code>=200&&s.status_code<299&&this._acceptAndTerminate(s);return}if(!(this._status!==Ce.STATUS_INVITE_SENT&&this._status!==Ce.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(s.status_code):this._status=Ce.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(s.status_code):{if(!s.to_tag){console.log("1xx response received without to tag");break}if(s.hasHeader("contact")&&!this._createDialog(s,"UAC",!0))break;if(this._status=Ce.STATUS_1XX_RECEIVED,!s.body){this._progress("remote",s);break}const r={originator:"remote",type:"answer",sdp:s.body};console.log('emit "sdp"'),this.emit("sdp",r);const o=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>this._progress("remote",s)).catch(a=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)});break}case/^2[0-9]{2}$/.test(s.status_code):{if(console.log("maybe here???"),this._status=Ce.STATUS_CONFIRMED,!s.body){this._acceptAndTerminate(s,400,j.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",s,j.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(s,"UAC"))break;const r={originator:"remote",type:"answer",sdp:s.body};console.log('emit "sdp"'),this.emit("sdp",r),new RTCSessionDescription({type:"answer",sdp:r.sdp}),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(o=>this._connection.setLocalDescription(o)).catch(o=>{this._acceptAndTerminate(s,500,o.toString()),console.log("failed 4"),this._failed("local",s,j.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(s),this._accepted("remote",s),this.sendRequest(j.ACK),this._confirmed("local",null)});break}default:{const r=ke.sipErrorCause(s.status_code);console.log("failed 5"),this._failed("remote",s,r)}}}sendMSRP(s){const r=new Hn("");r.method="SEND",r.addHeader("To-Path",`${this.my_addr[1]} ${this.target_addr[1]} ${this.target_addr[0]}`),r.addHeader("From-Path",`${this.my_addr[0]}`),r.addHeader("Message-ID",ke.createRandomToken(10)),r.addHeader("Byte-Range","1-25/25"),r.addHeader("Content-Type","text/plain"),r.addHeader("Success-Report","yes"),r.addHeader("Failure-Report","yes"),r.body=s;let o=r.toString();console.log(o);let a=[];for(var t=0;t<o.length;t++)a.push(o.charCodeAt(t).toString(16));console.log(a),this._connection.send(r.toString()),r.direction="outgoing",this.emit("newMessage",r),this._msgHistory.push(r),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(s){let r=s.ident,o=s.getHeader("Message-ID"),a=new Hn("");a.method="200 OK",a.addHeader("To-Path",`${this.my_addr[1]}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",o),a.ident=r;let t=a.toString();console.log(t);let n=[];for(var p=0;p<t.length;p++)n.push(t.charCodeAt(p).toString(16));console.log(n),this._connection.send(a.toString())}_sendReport(s){let r=s.ident,o=s.getHeader("Message-ID"),a=new Hn("");a.method="REPORT",a.addHeader("To-Path",`${s.getHeader("From-Path")}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",o),a.addHeader("Byte-Range","1-25/25"),a.addHeader("Status","000 200 OK"),a.ident=r;let t=a.toString();console.log(t);let n=[];for(var p=0;p<t.length;p++)n.push(t.charCodeAt(p).toString(16));console.log(n),this._connection.send(a.toString())}parseAuth(s){const r={},o=s.replace("Digest","").split(",");for(const a of o){const t=a.trim().split("=");r[t[0]]=t[1].match('^"(.+)"$')[1]}return r}init_incoming(s,r){let o;const a=s.hasHeader("Content-Type")?s.getHeader("Content-Type").toLowerCase():void 0;if(s.body&&a!=="application/sdp"){s.reply(415);return}if(this._status=Ce.STATUS_INVITE_RECEIVED,this._from_tag=s.from_tag,this._id=s.call_id+this._from_tag,this._request=s,this._contact=this._ua.contact.toString(),s.hasHeader("expires")&&(o=s.getHeader("expires")*1e3),s.to_tag=ke.newTag(),!this._createDialog(s,"UAS",!0)){s.reply(500,"Missing Contact header field");return}s.body?this._late_sdp=!1:this._late_sdp=!0,this._status=Ce.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{s.reply(408),console.log("failed 6"),this._failed("local",null,j.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),o&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Ce.STATUS_WAITING_FOR_ANSWER&&(s.reply(487),console.log("failed 7"),this._failed("system",null,j.causes.EXPIRES))},o)),this._direction="incoming",this._local_identity=s.to,this._remote_identity=s.from,r&&r(this),s.parseSDP(!0),this.target_addr=s.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",s),this._status!==Ce.STATUS_TERMINATED&&(s.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(s,r,o){this.emit("_failed",{originator:s,message:r||null,cause:o}),this._close(),this.emit("failed",{originator:s,message:r||null,cause:o})}_close(){if(console.log("CLOSE SESSION"),this._status!==Ce.STATUS_TERMINATED){if(this._status=Ce.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(s){console.log("close() | error closing the RTCPeerConnection: %o",s)}for(const s in this._timers)Object.prototype.hasOwnProperty.call(this._timers,s)&&clearTimeout(this._timers[s]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const s in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,s)&&(this._earlyDialogs[s].terminate(),delete this._earlyDialogs[s]);for(const s in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,s)&&delete this._referSubscribers[s];this._ua.destroyMSRPSession(this)}}_createDialog(s,r,o){const a=r==="UAS"?s.to_tag:s.from_tag,t=r==="UAS"?s.from_tag:s.to_tag,n=s.call_id+a+t;let p=this._earlyDialogs[n];if(o)return p?!0:(p=new io(this,s,r,io.C.STATUS_EARLY),p.error?(console.log("failed 8"),this._failed("remote",s,j.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[n]=p,!0));{if(this._from_tag=s.from_tag,this._to_tag=s.to_tag,p)return p.update(s,r),this._dialog=p,delete this._earlyDialogs[n],!0;const _=new io(this,s,r);return _.error?(console.log("failed 9"),this._failed("remote",s,j.causes.INTERNAL_ERROR),!1):(this._dialog=_,!0)}}_newMSRPSession(s,r){this._ua.newMSRPSession(this,{originator:s,session:this,request:r})}_progress(s,r){this.emit("progress",{originator:s,response:r||null})}isEnded(){switch(this._status){case Ce.STATUS_CANCELED:case Ce.STATUS_TERMINATED:return!0;default:return!1}}_accepted(s,r){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:s,response:r||null})}_confirmed(s,r){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:s,ack:r||null})}_ended(s,r,o){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:s,message:r||null,cause:o})}_handleSessionTimersInIncomingResponse(s){if(!this._sessionTimers.enabled)return;let r;s.session_expires&&s.session_expires>=j.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=s.session_expires,r=s.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,r="uac"),this._sessionTimers.refresher=r==="uac",this._runSessionTimer()}receiveRequest(s){if(console.log("receiveRequest()"),s.method===j.CANCEL)(this._status===Ce.STATUS_WAITING_FOR_ANSWER||this._status===Ce.STATUS_ANSWERED)&&(this._status=Ce.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",s,j.causes.CANCELED));else switch(s.method){case j.ACK:if(this._status!==Ce.STATUS_WAITING_FOR_ACK)return;if(this._status=Ce.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!s.body){this.terminate({cause:j.causes.MISSING_SDP,status_code:400});break}const r={originator:"remote",type:"answer",sdp:s.body};console.log('emit "sdp"'),this.emit("sdp",r);const o=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>{this._is_confirmed||this._confirmed("remote",s)}).catch(a=>{this.terminate({cause:j.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})}else this._is_confirmed||this._confirmed("remote",s);break;case j.BYE:this._status===Ce.STATUS_CONFIRMED||this._status===Ce.STATUS_WAITING_FOR_ACK?(s.reply(200),this._ended("remote",s,j.causes.BYE)):this._status===Ce.STATUS_INVITE_RECEIVED||this._status===Ce.STATUS_WAITING_FOR_ANSWER?(s.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",s,j.causes.BYE)):s.reply(403,"Wrong Status");break;case j.INVITE:this._status===Ce.STATUS_CONFIRMED?s.hasHeader("replaces")?this._receiveReplaces(s):this._receiveReinvite(s):s.reply(403,"Wrong Status");break;case j.INFO:this._status===Ce.STATUS_1XX_RECEIVED||this._status===Ce.STATUS_WAITING_FOR_ANSWER||this._status===Ce.STATUS_ANSWERED||this._status===Ce.STATUS_WAITING_FOR_ACK||this._status===Ce.STATUS_CONFIRMED?(s.hasHeader("Content-Type")?s.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new Ja(this).init_incoming(s):s.reply(415):s.reply(403,"Wrong Status");break;case j.UPDATE:this._status===Ce.STATUS_CONFIRMED?this._receiveUpdate(s):s.reply(403,"Wrong Status");break;case j.REFER:this._status===Ce.STATUS_CONFIRMED?this._receiveRefer(s):s.reply(403,"Wrong Status");break;case j.NOTIFY:this._status===Ce.STATUS_CONFIRMED?this._receiveNotify(s):s.reply(403,"Wrong Status");break;default:s.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:j.causes.CONNECTION_ERROR,cause:j.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:j.causes.REQUEST_TIMEOUT,cause:j.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:j.causes.DIALOG_ERROR,cause:j.causes.DIALOG_ERROR})}}const ft=console,Ns={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},fT=nT;class _T extends fT{constructor(s){super(s),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[]}call(s,r){return super.call(s,r)}joinVideoCall(s,r,o){ft.debug("call()");const a=new go(this);return a.connect(s,r,o),a}_loadConfig(s){try{Qr.load(this._configuration,s)}catch(a){throw a}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=Ln.newUUID()),this._configuration.jssip_id=Ln.createRandomToken(5);const r=this._configuration.uri.clone();r.user=null,this._configuration.hostport_params=r.toString().replace(/^sip:/i,"");try{this._transport=new Og(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=hT.bind(this),this._transport.onconnect=dT.bind(this),this._transport.ondisconnect=pT.bind(this),this._transport.ondata=mT.bind(this)}catch(a){throw ft.warn(a),new bs.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 a=this._configuration.uri.clone();a.user=null,a.clearParams(),a.clearHeaders(),this._configuration.registrar_server=a}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new $n("sip",Ln.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(a={}){const t=a.anonymous||null,n=a.outbound||null;let p="<";return t?p+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":p+=this.pub_gruu||this.uri.toString(),n&&(t?!this.temp_gruu:!this.pub_gruu)&&(p+=";ob"),p+=">",p}};const o=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const a in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,a)&&(o.indexOf(a)!==-1?Object.defineProperty(this._configuration,a,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,a,{writable:!1,configurable:!1}));ft.debug("configuration parameters after validation:");for(const a in this._configuration)if(Object.prototype.hasOwnProperty.call(Qr.settings,a))switch(a){case"uri":case"registrar_server":ft.debug(`- ${a}: ${this._configuration[a]}`);break;case"password":case"ha1":case"authorization_jwt":ft.debug(`- ${a}: NOT SHOWN`);break;default:ft.debug(`- ${a}: ${JSON.stringify(this._configuration[a])}`)}}newMSRPSession(s,r){s.on("msgHistoryUpdate",o=>{console.log(o)}),this._msrp_sessions[s.id]=s,this.emit("newMSRPSession",r)}newJanusSession(s,r){this._janus_sessions[s.id]=s,this.emit("newJanusSession",r)}destroyMSRPSession(s){delete this._msrp_sessions[s.id]}destroyJanusSession(s){delete this._janus_sessions[s.id]}receiveRequest(s){var t,n;const r=s.method;if(console.log("-----------"),s.ruri.user!==this._configuration.uri.user&&s.ruri.user!==this._contact.uri.user){ft.debug("Request-URI does not point to us"),s.method!==De.ACK&&s.reply_sl(404);return}if(s.ruri.scheme===De.SIPS){s.reply_sl(416);return}if($t.checkTransaction(this,s))return;if(r===De.INVITE?new $t.InviteServerTransaction(this,this._transport,s):r!==De.ACK&&r!==De.CANCEL&&new $t.NonInviteServerTransaction(this,this._transport,s),r===De.OPTIONS){if(this.listeners("newOptions").length===0){s.reply(200);return}new pf.Options(this).init_incoming(s)}else if(r===De.MESSAGE){if(this.listeners("newMessage").length===0){s.reply(405);return}new pf.Message(this).init_incoming(s)}else if(r===De.INVITE&&!s.to_tag&&this.listeners("newRTCSession").length===0){s.reply(405);return}let o,a;if(s.to_tag)if(o=this._findDialog(s.call_id,s.from_tag,s.to_tag),o)o.receiveRequest(s);else if(r===De.NOTIFY)if(a=this._findSession(s),a)a.receiveRequest(s);else{if(s.body){const p=JSON.parse(s.body)||{};(n=(t=p.plugindata)==null?void 0:t.data)!=null&&n.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(p)}s.reply(200)}else r!==De.ACK&&s.reply(481);else switch(r){case De.INVITE:if(window.RTCPeerConnection)if(s.hasHeader("replaces")){const p=s.replaces;o=this._findDialog(p.call_id,p.from_tag,p.to_tag),o?(a=o.owner,a.isEnded()?s.reply(603):a.receiveRequest(s)):s.reply(481)}else s.body.search(/MSRP/ig)>-1?(a=new pu(this),a.init_incoming(s)):s.body.search(/JANUS/ig)>-1||(a=new hg(this),a.init_incoming(s));else ft.warn("INVITE received but WebRTC is not supported"),s.reply(488);break;case De.BYE:s.reply(481);break;case De.CANCEL:a=this._findSession(s),a?a.receiveRequest(s):ft.debug("received CANCEL request for a non existent session");break;case De.ACK:break;case De.NOTIFY:this.emit("sipEvent",{event:s.event,request:s}),s.reply(200);break;default:s.reply(405);break}}startMSRP(s,r){ft.debug("startMSRP()",r);const o=new pu(this);return o.connect(s),o}startJanus(s,r){ft.debug("startJanus()",r);const o=new pu(this);return o.connect(s),o}terminateMSRPSessions(s){ft.debug("terminateSessions()");for(const r in this._msrp_sessions)this._msrp_sessions[r].isEnded()||this._msrp_sessions[r].terminate(s)}terminateJanusSessions(s){ft.debug("terminateSessions()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||this._janus_sessions[r].terminate(s)}stop(){if(ft.debug("stop()"),this._dynConfiguration={},this._status===Ns.STATUS_USER_CLOSED){ft.debug("UA already closed");return}this._registrator.close();const s=Object.keys(this._sessions).length;for(const o in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,o)){ft.debug(`closing session ${o}`);try{this._sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,o)){ft.debug(`closing session ${o}`);try{this._msrp_sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,o)){ft.debug(`closing session ${o}`);try{this._janus_sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,o))try{this._applicants[o].close()}catch(a){console.error(a)}this._status=Ns.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&&s===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function hT(c){this.emit("connecting",c)}function dT(c){this._status!==Ns.STATUS_USER_CLOSED&&(this._status=Ns.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function pT(c){const s=["nict","ict","nist","ist"];for(const r of s)for(const o in this._transactions[r])Object.prototype.hasOwnProperty.call(this._transactions[r],o)&&this._transactions[r][o].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==Ns.STATUS_USER_CLOSED&&(this._status=Ns.STATUS_NOT_READY,this._error=Ns.NETWORK_ERROR)}function mT(c){console.log("onTransportData",c);const s=c.transport;let r=c.message;if(r=su.parseMessage(r,this),!r){console.log("if 1 return");return}if(this._status===Ns.STATUS_USER_CLOSED&&r instanceof eo.IncomingRequest){console.log("if 2 return");return}if(!Bg(r,this,s)){console.log("if 3 return");return}if(console.log("onTransportData message",r),console.log("onTransportData instanceof",r instanceof eo.IncomingRequest),r instanceof eo.IncomingRequest)r.transport=s,console.log("onTransportData receiveRequest"),this.receiveRequest(r);else if(r instanceof eo.IncomingResponse){let o;switch(r.method){case De.INVITE:o=this._transactions.ict[r.via_branch],o&&o.receiveResponse(r);break;case De.ACK:break;default:o=this._transactions.nict[r.via_branch],o&&o.receiveResponse(r);break}}}const gT=["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"],TT=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function f_(c){const s={};return gT.forEach(r=>{c[r]!==void 0&&(s[r]=c[r])}),s.localHold=c._localHold,s}function __(c){const s={};return TT.forEach(r=>{c[r]!==void 0&&(s[r]=c[r])}),s}function h_(c,s){const r=new AudioContext,o=r.createMediaStreamSource(c),a=r.createMediaStreamDestination(),t=r.createGain();return o.connect(t),t.connect(a),t.gain.value=s,a.stream}function vT(c,s,r,o){const a=document.createElement("audio");a.id=s._id,a.className="audioTag",a.srcObject=c,d_()||(a.setSinkId(r),a.volume=o),a.play(),s.audioTag=a}function ET(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}function d_(){return/Mobi|Android|iPhone/i.test(navigator.userAgent)}const ST=lt,yT=ts(),wt=new ST("WebSocketInterface");var AT=class{constructor(s){wt.debug('new() [url:"%s"]',s),this._url=s,this._sip_uri=null,this._via_transport=null,this._ws=null;const r=yT.parse(s,"absoluteURI");if(r===-1)throw wt.warn(`invalid WebSocket URI: ${s}`),new TypeError(`Invalid argument: ${s}`);if(r.scheme!=="wss"&&r.scheme!=="ws")throw wt.warn(`invalid WebSocket URI scheme: ${r.scheme}`),new TypeError(`Invalid argument: ${s}`);this._sip_uri=`sip:${r.host}${r.port?`:${r.port}`:""};transport=ws`,this._via_transport=r.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(s){this._via_transport=s.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(wt.debug("connect()"),this.isConnected()){wt.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){wt.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),wt.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(s){this._onError(s)}}disconnect(){wt.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(s){return wt.debug("send()"),this.isConnected()?(this._ws.send(s),!0):(wt.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(){wt.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:s,code:r,reason:o}){wt.debug(`WebSocket ${this._url} closed`),s===!1&&wt.debug("WebSocket abrupt disconnection"),this.ondisconnect(!s,r,o)}_onMessage({data:s}){wt.debug("received WebSocket message"),this.ondata(s)}_onError(s){wt.warn(`WebSocket ${this._url} error: `,s)}};const mu=dl,CT=De,RT=ps,IT=mt(),bT=a_,wT=_s(),OT=ka(),DT=ts(),NT=AT;wn("JsSIP")("version %s",mu.version);var UT={C:CT,Exceptions:RT,Utils:IT,UA:bT,URI:wT,NameAddrHeader:OT,WebSocketInterface:NT,Grammar:DT,debug:wn,get name(){return mu.title},get version(){return mu.version}};const PT=Pe(UT);function gu(c){return c<10?`0${c}`:`${c}`}function xT(c){let s=c.hours||0,r=c.minutes||0,o=c.seconds||0;o++,o===60&&(o=0,r++,r===60&&(r=0,s++));const a=`${gu(s)}:${gu(r)}:${gu(o)}`;return{seconds:o,minutes:r,hours:s,formatted:a}}var St={};St.forEach=async(c,s,r)=>{const o=[];for(let a=0;a<c.length;a++)if(a in c){const t=Promise.resolve(c[a]).then(n=>s.call(r||globalThis,n,a,c));o.push(t)}await Promise.all(o)},St.forEachSeries=async(c,s,r)=>{for(let o=0;o<c.length;o++)o in c&&await s.call(r||globalThis,await c[o],o,c)},St.map=async(c,s,r)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&(o[a]=Promise.resolve(c[a]).then(t=>s.call(r||globalThis,t,a,c)));return Promise.all(o)},St.mapSeries=async(c,s,r)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&(o[a]=await s.call(r||globalThis,await c[a],a,c));return o},St.find=(c,s,r)=>new Promise((o,a)=>{if(c.length===0)return o();let t=1;for(let n=0;n<c.length;n++){const p=_=>{_?o(c[n]):t===c.length&&o(),t++};Promise.resolve(c[n]).then(_=>s.call(r||globalThis,_,n,c)).then(p).catch(a)}}),St.findSeries=async(c,s,r)=>{for(let o=0;o<c.length;o++)if(await s.call(r||globalThis,await c[o],o,c))return c[o]},St.findIndex=(c,s,r)=>new Promise((o,a)=>{if(c.length===0)return o(-1);let t=1;for(let n=0;n<c.length;n++){const p=_=>{_?o(n):t===c.length&&o(-1),t++};Promise.resolve(c[n]).then(_=>s.call(r||globalThis,_,n,c)).then(p).catch(a)}}),St.findIndexSeries=async(c,s,r)=>{for(let o=0;o<c.length;o++)if(await s.call(r||globalThis,await c[o],o,c))return o},St.some=(c,s,r)=>new Promise((o,a)=>{if(c.length===0)return o(!1);let t=1;for(let n=0;n<c.length;n++){if(!(n in c)){t++;continue}const p=_=>{_?o(!0):t===c.length&&o(!1),t++};Promise.resolve(c[n]).then(_=>s.call(r||globalThis,_,n,c)).then(p).catch(a)}}),St.someSeries=async(c,s,r)=>{for(let o=0;o<c.length;o++)if(o in c&&await s.call(r||globalThis,await c[o],o,c))return!0;return!1},St.every=(c,s,r)=>new Promise((o,a)=>{if(c.length===0)return o(!0);let t=1;for(let n=0;n<c.length;n++){if(!(n in c)){t++;continue}const p=_=>{_?t===c.length&&o(!0):o(!1),t++};Promise.resolve(c[n]).then(_=>s.call(r||globalThis,_,n,c)).then(p).catch(a)}}),St.everySeries=async(c,s,r)=>{for(let o=0;o<c.length;o++)if(o in c&&!await s.call(r||globalThis,await c[o],o,c))return!1;return!0},St.filter=(c,s,r)=>new Promise(async(o,a)=>{const t=[];for(let p=0;p<c.length;p++)p in c&&(t[p]=Promise.resolve(c[p]).then(_=>s.call(r||globalThis,_,p,c)).catch(a));const n=[];for(let p=0;p<t.length;p++)await t[p]&&n.push(await c[p]);o(n)}),St.filterSeries=async(c,s,r)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&await s.call(r||globalThis,await c[a],a,c)&&o.push(await c[a]);return o},St.reduce=async(c,s,r)=>{if(c.length===0&&r===void 0)throw TypeError("Reduce of empty array with no initial value");let o,a;for(r!==void 0?(a=r,o=0):(a=c[0],o=1),o;o<c.length;o++)o in c&&(a=await s(await a,await c[o],o,c));return a};var p_={};(function(c){const s=St;Object.keys(s).forEach(r=>{const o=r.charAt(0).toUpperCase()+r.slice(1);c[`async${o}`]=async function(...a){return s[r](this,...a)}})})(p_);var m_=Object.assign(St,{instanceMethods:p_});const tn=new AudioContext,Yt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var MT={exports:{}};(function(c){var s=function(r){var o=Object.prototype,a=o.hasOwnProperty,t=Object.defineProperty||function(ee,Y,G){ee[Y]=G.value},n,p=typeof Symbol=="function"?Symbol:{},_=p.iterator||"@@iterator",d=p.asyncIterator||"@@asyncIterator",g=p.toStringTag||"@@toStringTag";function T(ee,Y,G){return Object.defineProperty(ee,Y,{value:G,enumerable:!0,configurable:!0,writable:!0}),ee[Y]}try{T({},"")}catch{T=function(Y,G,re){return Y[G]=re}}function E(ee,Y,G,re){var ge=Y&&Y.prototype instanceof ae?Y:ae,be=Object.create(ge.prototype),Me=new P(re||[]);return t(be,"_invoke",{value:z(ee,G,Me)}),be}r.wrap=E;function y(ee,Y,G){try{return{type:"normal",arg:ee.call(Y,G)}}catch(re){return{type:"throw",arg:re}}}var A="suspendedStart",C="suspendedYield",I="executing",$="completed",L={};function ae(){}function N(){}function F(){}var Se={};T(Se,_,function(){return this});var ve=Object.getPrototypeOf,M=ve&&ve(ve(se([])));M&&M!==o&&a.call(M,_)&&(Se=M);var D=F.prototype=ae.prototype=Object.create(Se);N.prototype=F,t(D,"constructor",{value:F,configurable:!0}),t(F,"constructor",{value:N,configurable:!0}),N.displayName=T(F,g,"GeneratorFunction");function B(ee){["next","throw","return"].forEach(function(Y){T(ee,Y,function(G){return this._invoke(Y,G)})})}r.isGeneratorFunction=function(ee){var Y=typeof ee=="function"&&ee.constructor;return Y?Y===N||(Y.displayName||Y.name)==="GeneratorFunction":!1},r.mark=function(ee){return Object.setPrototypeOf?Object.setPrototypeOf(ee,F):(ee.__proto__=F,T(ee,g,"GeneratorFunction")),ee.prototype=Object.create(D),ee},r.awrap=function(ee){return{__await:ee}};function q(ee,Y){function G(be,Me,Re,le){var ye=y(ee[be],ee,Me);if(ye.type==="throw")le(ye.arg);else{var it=ye.arg,ot=it.value;return ot&&typeof ot=="object"&&a.call(ot,"__await")?Y.resolve(ot.__await).then(function(Ee){G("next",Ee,Re,le)},function(Ee){G("throw",Ee,Re,le)}):Y.resolve(ot).then(function(Ee){it.value=Ee,Re(it)},function(Ee){return G("throw",Ee,Re,le)})}}var re;function ge(be,Me){function Re(){return new Y(function(le,ye){G(be,Me,le,ye)})}return re=re?re.then(Re,Re):Re()}t(this,"_invoke",{value:ge})}B(q.prototype),T(q.prototype,d,function(){return this}),r.AsyncIterator=q,r.async=function(ee,Y,G,re,ge){ge===void 0&&(ge=Promise);var be=new q(E(ee,Y,G,re),ge);return r.isGeneratorFunction(Y)?be:be.next().then(function(Me){return Me.done?Me.value:be.next()})};function z(ee,Y,G){var re=A;return function(be,Me){if(re===I)throw new Error("Generator is already running");if(re===$){if(be==="throw")throw Me;return rt()}for(G.method=be,G.arg=Me;;){var Re=G.delegate;if(Re){var le=H(Re,G);if(le){if(le===L)continue;return le}}if(G.method==="next")G.sent=G._sent=G.arg;else if(G.method==="throw"){if(re===A)throw re=$,G.arg;G.dispatchException(G.arg)}else G.method==="return"&&G.abrupt("return",G.arg);re=I;var ye=y(ee,Y,G);if(ye.type==="normal"){if(re=G.done?$:C,ye.arg===L)continue;return{value:ye.arg,done:G.done}}else ye.type==="throw"&&(re=$,G.method="throw",G.arg=ye.arg)}}}function H(ee,Y){var G=Y.method,re=ee.iterator[G];if(re===n)return Y.delegate=null,G==="throw"&&ee.iterator.return&&(Y.method="return",Y.arg=n,H(ee,Y),Y.method==="throw")||G!=="return"&&(Y.method="throw",Y.arg=new TypeError("The iterator does not provide a '"+G+"' method")),L;var ge=y(re,ee.iterator,Y.arg);if(ge.type==="throw")return Y.method="throw",Y.arg=ge.arg,Y.delegate=null,L;var be=ge.arg;if(!be)return Y.method="throw",Y.arg=new TypeError("iterator result is not an object"),Y.delegate=null,L;if(be.done)Y[ee.resultName]=be.value,Y.next=ee.nextLoc,Y.method!=="return"&&(Y.method="next",Y.arg=n);else return be;return Y.delegate=null,L}B(D),T(D,g,"Generator"),T(D,_,function(){return this}),T(D,"toString",function(){return"[object Generator]"});function Z(ee){var Y={tryLoc:ee[0]};1 in ee&&(Y.catchLoc=ee[1]),2 in ee&&(Y.finallyLoc=ee[2],Y.afterLoc=ee[3]),this.tryEntries.push(Y)}function U(ee){var Y=ee.completion||{};Y.type="normal",delete Y.arg,ee.completion=Y}function P(ee){this.tryEntries=[{tryLoc:"root"}],ee.forEach(Z,this),this.reset(!0)}r.keys=function(ee){var Y=Object(ee),G=[];for(var re in Y)G.push(re);return G.reverse(),function ge(){for(;G.length;){var be=G.pop();if(be in Y)return ge.value=be,ge.done=!1,ge}return ge.done=!0,ge}};function se(ee){if(ee){var Y=ee[_];if(Y)return Y.call(ee);if(typeof ee.next=="function")return ee;if(!isNaN(ee.length)){var G=-1,re=function ge(){for(;++G<ee.length;)if(a.call(ee,G))return ge.value=ee[G],ge.done=!1,ge;return ge.value=n,ge.done=!0,ge};return re.next=re}}return{next:rt}}r.values=se;function rt(){return{value:n,done:!0}}return P.prototype={constructor:P,reset:function(ee){if(this.prev=0,this.next=0,this.sent=this._sent=n,this.done=!1,this.delegate=null,this.method="next",this.arg=n,this.tryEntries.forEach(U),!ee)for(var Y in this)Y.charAt(0)==="t"&&a.call(this,Y)&&!isNaN(+Y.slice(1))&&(this[Y]=n)},stop:function(){this.done=!0;var ee=this.tryEntries[0],Y=ee.completion;if(Y.type==="throw")throw Y.arg;return this.rval},dispatchException:function(ee){if(this.done)throw ee;var Y=this;function G(le,ye){return be.type="throw",be.arg=ee,Y.next=le,ye&&(Y.method="next",Y.arg=n),!!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 Me=a.call(ge,"catchLoc"),Re=a.call(ge,"finallyLoc");if(Me&&Re){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0);if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else if(Me){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0)}else if(Re){if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(ee,Y){for(var G=this.tryEntries.length-1;G>=0;--G){var re=this.tryEntries[G];if(re.tryLoc<=this.prev&&a.call(re,"finallyLoc")&&this.prev<re.finallyLoc){var ge=re;break}}ge&&(ee==="break"||ee==="continue")&&ge.tryLoc<=Y&&Y<=ge.finallyLoc&&(ge=null);var be=ge?ge.completion:{};return be.type=ee,be.arg=Y,ge?(this.method="next",this.next=ge.finallyLoc,L):this.complete(be)},complete:function(ee,Y){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"&&Y&&(this.next=Y),L},finish:function(ee){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var G=this.tryEntries[Y];if(G.finallyLoc===ee)return this.complete(G.completion,G.afterLoc),U(G),L}},catch:function(ee){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var G=this.tryEntries[Y];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,Y,G){return this.delegate={iterator:se(ee),resultName:Y,nextLoc:G},this.method==="next"&&(this.arg=n),L}},r}(c.exports);try{regeneratorRuntime=s}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=s:Function("r","regeneratorRuntime = r")(s)}})(MT);var g_={exports:{}};(function(c){(function(s,r){c.exports?c.exports=r():s.log=r()})(Gt,function(){var s=function(){},r="undefined",o=typeof window!==r&&typeof window.navigator!==r&&/Trident\/|MSIE /.test(window.navigator.userAgent),a=["trace","debug","info","warn","error"];function t(C,I){var $=C[I];if(typeof $.bind=="function")return $.bind(C);try{return Function.prototype.bind.call($,C)}catch{return function(){return Function.prototype.apply.apply($,[C,arguments])}}}function n(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function p(C){return C==="debug"&&(C="log"),typeof console===r?!1:C==="trace"&&o?n:console[C]!==void 0?t(console,C):console.log!==void 0?t(console,"log"):s}function _(C,I){for(var $=0;$<a.length;$++){var L=a[$];this[L]=$<C?s:this.methodFactory(L,C,I)}this.log=this.debug}function d(C,I,$){return function(){typeof console!==r&&(_.call(this,I,$),this[C].apply(this,arguments))}}function g(C,I,$){return p(C)||d.apply(this,arguments)}function T(C,I,$){var L=this,ae;I=I??"WARN";var N="loglevel";typeof C=="string"?N+=":"+C:typeof C=="symbol"&&(N=void 0);function F(D){var B=(a[D]||"silent").toUpperCase();if(!(typeof window===r||!N)){try{window.localStorage[N]=B;return}catch{}try{window.document.cookie=encodeURIComponent(N)+"="+B+";"}catch{}}}function Se(){var D;if(!(typeof window===r||!N)){try{D=window.localStorage[N]}catch{}if(typeof D===r)try{var B=window.document.cookie,q=B.indexOf(encodeURIComponent(N)+"=");q!==-1&&(D=/^([^;]+)/.exec(B.slice(q))[1])}catch{}return L.levels[D]===void 0&&(D=void 0),D}}function ve(){if(!(typeof window===r||!N)){try{window.localStorage.removeItem(N);return}catch{}try{window.document.cookie=encodeURIComponent(N)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}L.name=C,L.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},L.methodFactory=$||g,L.getLevel=function(){return ae},L.setLevel=function(D,B){if(typeof D=="string"&&L.levels[D.toUpperCase()]!==void 0&&(D=L.levels[D.toUpperCase()]),typeof D=="number"&&D>=0&&D<=L.levels.SILENT){if(ae=D,B!==!1&&F(D),_.call(L,D,C),typeof console===r&&D<L.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+D},L.setDefaultLevel=function(D){I=D,Se()||L.setLevel(D,!1)},L.resetLevel=function(){L.setLevel(I,!1),ve()},L.enableAll=function(D){L.setLevel(L.levels.TRACE,D)},L.disableAll=function(D){L.setLevel(L.levels.SILENT,D)};var M=Se();M==null&&(M=I),L.setLevel(M,!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 $=y[I];return $||($=y[I]=new T(I,E.getLevel(),E.methodFactory)),$};var A=typeof window!==r?window.log:void 0;return E.noConflict=function(){return typeof window!==r&&window.log===E&&(window.log=A),E},E.getLoggers=function(){return y},E.default=E,E})})(g_);var Rt=g_.exports;const ms=()=>`${new Date().toISOString()} | metrics`,gs=(c,s,r)=>`${c} | ${s} | ${r}`;Rt.setDefaultLevel(Rt.levels.TRACE);const kT=c=>{Rt.info(gs(ms(),"log ",`set log level to ${c?"verbose":"info"}`)),Rt.setLevel(c?Rt.levels.TRACE:Rt.levels.INFO)},LT=c=>{const s=[...Object.keys(Rt.levels)];s.includes(c)?(Rt.info(gs(ms(),"log ",`update log level to ${c.toLowerCase()}`)),Rt.setLevel(c)):Rt.warn(gs(ms(),"log ","Incorrect log level please choose one of "),s)},xe=(c,s,r)=>{r?Rt.debug(gs(ms(),c,s),r):Rt.debug(gs(ms(),c,s))},Tu=(c,s)=>{Rt.info(gs(ms(),c,s))},sn=(c,s)=>{Rt.info(gs(ms(),c,s))},To=(c,s)=>{Rt.warn(gs(ms(),c,s))},Fn=(c,s)=>{Rt.error(gs(ms(),c,s))};function $T(c){return Math.floor(Math.random()*c).toString()}function T_(c,s){let r=s;return c.forEach(o=>{r=r.replace(o,"")}),r}function HT(c,s){let r="";for(let o=0;o<s;o+=1)r+=c[$T(c.length)];return r}function FT({length:c=20,useLetters:s=!0,useNumbers:r=!0,includeSymbols:o=[],excludeSymbols:a=[]}={}){let t="abcdefghijklmnopqrstuvwxyz",n="0123456789",p=[],_=[],d=[];return s&&(a.length&&(t=T_(a,t)),_=t.split("")),r&&(a.length&&(n=T_(a,n)),d=n.split("")),p=[..._,...d,...o],HT(p,c)}var jT=FT;const Zr=Pe(jT),VT=()=>"WebRTCMetrics",qT=()=>"5.0.3",$e={INBOUND:"inbound",OUTBOUND:"outbound"},Ts={IDLE:"idle",RUNNING:"running",MUTED:"muted"},ei={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},BT=()=>({...{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:[]}}),v_={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},E_={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},S_={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},y_={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},GT=c=>{const s={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 r={...c,audio:{},video:{},data:{...c.data},network:{...c.network},experimental:{...c.experimental}};return Object.keys(c.audio).forEach(o=>{r.audio[o]={...c.audio[o]}}),Object.keys(c.video).forEach(o=>{r.video[o]={...c.video[o]}}),r}return{...s,audio:{},video:{},data:{...s.data},network:{...s.network},experimental:{...s.experimental}}},WT={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${Zr()}`,cid:`c-${Zr()}`,uid:`u-${Zr()}`,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"},V={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"},ti={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},vu={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ne={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},Eu="config ",KT=(c,s={},r)=>{const o={...r,...s};return s.pname||To(Eu,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${r.pname}'`),s.cid||To(Eu,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${r.cid}'`),s.uid||To(Eu,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${r.uid}'`),o.pc=c,o},YT=(c={})=>{const s={...WT,...c};return s.name=VT(),s.version=qT(),s},si=(c,s,r,o=!1,a)=>{let t=c.map(n=>{if(!r)return n[s];if(!a)return n[s][r];const p=n[s][a];return p?p[r]:null});return t=t.filter(n=>o?Number.isFinite(n)&&n>0:Number.isFinite(n)),t.length===0?[]:t},Us=c=>c.reduce((s,r)=>s+r,0)/c.length,zT=()=>`probe-${Zr()}`,JT=()=>`coltr-${Zr()}`,A_=c=>new Promise(s=>setTimeout(s,c)),Su=(c,s,r)=>{s?c.call(s,r):c(r)},We=(c,s,r,o)=>{const a=si(c,s,r,!0,o);if(a.length===0)return null;const t=a.reduce((d,g)=>d+g,0)/a.length;return t===0?null:a.map(d=>Math.abs(t-d)).reduce((d,g)=>d+g,0)/a.length*100/t},Xe=(c,s,r,o=!1,a)=>{const t=si(c,s,r,o,a);return t.length===0?null:t.reduce((n,p)=>n+p,0)/t.length},nn=(c,s,r)=>si(c,s,r).reduce((a,t)=>a+t,0),Ke=(c,s,r,o)=>{const a=si(c,s,r,!0,o);return a.length===0?null:Math.min(...a)},Ye=(c,s,r,o)=>{const a=si(c,s,r,!1,o);return a.length===0?null:Math.max(...a)},yt=(c,s,r,o)=>{const a=c.slice().pop();if(!a)return null;if(!r)return a[s];if(!o)return a[s][r];const t=a[s][o];return t?t[r]:null},XT=c=>c.slice().pop(),_t=(c,s,r)=>{if(!s)return null;const o={};let a=s[x.AUDIO][c];a||(a=r===$e.INBOUND?{...v_}:{...E_}),o[x.AUDIO]=a;let t=s[x.VIDEO][c];return t||(t=r===$e.INBOUND?{...S_}:{...y_}),o[x.VIDEO]=t,o},ni="exporter ",QT="2.0",C_=(c,s,r)=>{if(!c||c.length===0)return 0;const o=c[c.length-1];if(!o)return 0;const a=o[s][r];if(a){const t=a.total_rtt_ms_out,n=a.total_rtt_measure_out;return!n||!t?Xe(c,s,"delta_rtt_ms_out",!1,r):Number(t/n)}return null},ZT=(c,s)=>{if(!c||c.length===0)return 0;const r=c[c.length-1];if(!r)return 0;const o=r[s].total_rtt_connectivity_ms,a=r[s].total_rtt_connectivity_measure;return!a||!o?Xe(c,s,"delta_rtt_connectivity_ms"):Number(o/a)},ev=c=>yt(c,"network","local_candidate_type")!=="relay"?`direct/${yt(c,"network","local_candidate_protocol")}`:`turn/${yt(c,"network","local_candidate_relay_protocol")}`,tv=c=>{const s=yt(c,"network","remote_candidate_type"),r=yt(c,"network","remote_candidate_protocol");return s!=="relay"?`direct/${r}`:`turn/${r}`};class sv{constructor(s){this._start=null,this._end=null,this._cfg=s,this._referenceReport=null,this._reports=[],this._events=[]}start(){Tu(ni,"start() - start exporter...");const s=new Date;return this._start=s.toJSON(),s}stop(){Tu(ni,"stop() - stop exporter...");const s=new Date;return this._end=s.toJSON(),s}saveReferenceReport(s){this._referenceReport=s}getReferenceReport(){return this._referenceReport}addReport(s){this._cfg.ticket&&(xe(ni,`addReport() - add report to exporter at ${s.timestamp}`),this._reports.push(s))}addCustomEvent(s){this._events.push(s)}reset(){Tu(ni,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){xe(ni,"ticket() - generate ticket");const s=yt(this._reports,"audio","total_packets_lost_in"),r=yt(this._reports,"audio","total_packets_in"),o=yt(this._reports,"video","total_packets_lost_in"),a=yt(this._reports,"video","total_packets_in"),t={},n=XT(this._reports);return n&&(Object.keys(n[x.AUDIO]).forEach(p=>{const _=n[x.AUDIO][p];if(t[_.ssrc]={type:x.AUDIO,direction:_.direction},_.direction===$e.INBOUND){const d={avg:Xe(this._reports,x.AUDIO,"delta_jitter_ms_in",!1,p),min:Ke(this._reports,x.AUDIO,"delta_jitter_ms_in",p),max:Ye(this._reports,x.AUDIO,"delta_jitter_ms_in",p),volatility:We(this._reports,x.AUDIO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.AUDIO,"delta_kbs_in",!1,p),min:Ke(this._reports,x.AUDIO,"delta_kbs_in",p),max:Ye(this._reports,x.AUDIO,"delta_kbs_in",p),volatility:We(this._reports,x.AUDIO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.AUDIO,"delta_KBytes_in",!1,p),min:Ke(this._reports,x.AUDIO,"delta_KBytes_in",p),max:Ye(this._reports,x.AUDIO,"delta_KBytes_in",p),volatility:We(this._reports,x.AUDIO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={emodel:{avg:Xe(this._reports,x.AUDIO,"mos_emodel_in",!1,p),min:Ke(this._reports,x.AUDIO,"mos_emodel_in",p),max:Ye(this._reports,x.AUDIO,"mos_emodel_in",p),volatility:We(this._reports,x.AUDIO,"mos_emodel_in",p)},effective:{avg:Xe(this._reports,x.AUDIO,"mos_in",!1,p),min:Ke(this._reports,x.AUDIO,"mos_in",p),max:Ye(this._reports,x.AUDIO,"mos_in",p),volatility:We(this._reports,x.AUDIO,"mos_in",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},y=yt(this._reports,x.AUDIO,"total_packets_lost_in",p),A=yt(this._reports,x.AUDIO,"total_packets_in",p),C={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].mos=E,t[p].traffic=T,t[p].bitrate=g,t[p].loss=C}else{const d={avg:Xe(this._reports,x.AUDIO,"delta_jitter_ms_out",!1,p),min:Ke(this._reports,x.AUDIO,"delta_jitter_ms_out",p),max:Ye(this._reports,x.AUDIO,"delta_jitter_ms_out",p),volatility:We(this._reports,x.AUDIO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.AUDIO,"delta_kbs_out",!1,p),min:Ke(this._reports,x.AUDIO,"delta_kbs_out",p),max:Ye(this._reports,x.AUDIO,"delta_kbs_out",p),volatility:We(this._reports,x.AUDIO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.AUDIO,"delta_KBytes_out",!1,p),min:Ke(this._reports,x.AUDIO,"delta_KBytes_out",p),max:Ye(this._reports,x.AUDIO,"delta_KBytes_out",p),volatility:We(this._reports,x.AUDIO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},E={avg:C_(this._reports,x.AUDIO,p),min:Ke(this._reports,x.AUDIO,"delta_rtt_ms_out",p),max:Ye(this._reports,x.AUDIO,"delta_rtt_ms_out",p),volatility:We(this._reports,x.AUDIO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=yt(this._reports,x.AUDIO,"total_packets_lost_out",p),A=yt(this._reports,x.AUDIO,"total_packets_out",p),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,p),min:Ke(this._reports,x.AUDIO,"mos_emodel_out",p),max:Ye(this._reports,x.AUDIO,"mos_emodel_out",p),volatility:We(this._reports,x.AUDIO,"mos_emodel_out",p)},effective:{avg:Xe(this._reports,x.AUDIO,"mos_out",!1,p),min:Ke(this._reports,x.AUDIO,"mos_out",p),max:Ye(this._reports,x.AUDIO,"mos_out",p),volatility:We(this._reports,x.AUDIO,"mos_out",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};t[p].jitter=d,t[p].rtt=E,t[p].traffic=T,t[p].bitrate=g,t[p].loss=C,t[p].mos=I}}),Object.keys(n[x.VIDEO]).forEach(p=>{const _=n[x.VIDEO][p];if(t[p]={type:x.VIDEO,direction:_.direction},_.direction===$e.INBOUND){const d={avg:Xe(this._reports,x.VIDEO,"delta_jitter_ms_in",!1,p),min:Ke(this._reports,x.VIDEO,"delta_jitter_ms_in",p),max:Ye(this._reports,x.VIDEO,"delta_jitter_ms_in",p),volatility:We(this._reports,x.VIDEO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.VIDEO,"delta_kbs_in",!1,p),min:Ke(this._reports,x.VIDEO,"delta_kbs_in",p),max:Ye(this._reports,x.VIDEO,"delta_kbs_in",p),volatility:We(this._reports,x.VIDEO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.VIDEO,"delta_KBytes_in",!1,p),min:Ke(this._reports,x.VIDEO,"delta_KBytes_in",p),max:Ye(this._reports,x.VIDEO,"delta_KBytes_in",p),volatility:We(this._reports,x.VIDEO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E=yt(this._reports,x.VIDEO,"total_packets_lost_in",p),y=yt(this._reports,x.VIDEO,"total_packets_in",p),A={lost:E,avg:Math.round((E/(E+y)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].traffic=T,t[p].bitrate=g,t[p].loss=A}else{const d={avg:Xe(this._reports,x.VIDEO,"delta_jitter_ms_out",!1,p),min:Ke(this._reports,x.VIDEO,"delta_jitter_ms_out",p),max:Ye(this._reports,x.VIDEO,"delta_jitter_ms_out",p),volatility:We(this._reports,x.VIDEO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.VIDEO,"delta_kbs_out",!1,p),min:Ke(this._reports,x.VIDEO,"delta_kbs_out",p),max:Ye(this._reports,x.VIDEO,"delta_kbs_out",p),volatility:We(this._reports,x.VIDEO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.VIDEO,"delta_KBytes_out",!1,p),min:Ke(this._reports,x.VIDEO,"delta_KBytes_out",p),max:Ye(this._reports,x.VIDEO,"delta_KBytes_out",p),volatility:We(this._reports,x.VIDEO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={avg:C_(this._reports,x.VIDEO,p),min:Ke(this._reports,x.VIDEO,"delta_rtt_ms_out",p),max:Ye(this._reports,x.VIDEO,"delta_rtt_ms_out",p),volatility:We(this._reports,x.VIDEO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=yt(this._reports,x.VIDEO,"total_packets_lost_out",p),A=yt(this._reports,x.VIDEO,"total_packets_out",p),C={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].rtt=E,t[p].traffic=T,t[p].bitrate=g,t[p].loss=C}})),{version:QT,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:t,data:{rtt:{avg:ZT(this._reports,"data"),min:Ke(this._reports,"data","delta_rtt_connectivity_ms"),max:Ye(this._reports,"data","delta_rtt_connectivity_ms"),volatility:We(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((s/(s+r)*100||0)*100)/100}},video:{in:{avg:Math.round((o/(o+a)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:Xe(this._reports,"data","delta_kbs_in"),min:Ke(this._reports,"data","delta_kbs_in"),max:Ye(this._reports,"data","delta_kbs_in"),volatility:We(this._reports,"data","delta_kbs_in")},out:{avg:Xe(this._reports,"data","delta_kbs_out"),min:Ke(this._reports,"data","delta_kbs_out"),max:Ye(this._reports,"data","delta_kbs_out"),volatility:We(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:Ke(this._reports,"data","delta_KBytes_in"),max:Ye(this._reports,"data","delta_KBytes_in"),volatility:We(this._reports,"data","delta_KBytes_in")},out:{avg:Xe(this._reports,"data","delta_KBytes_out"),min:Ke(this._reports,"data","delta_KBytes_out"),max:Ye(this._reports,"data","delta_KBytes_out"),volatility:We(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:ev(this._reports),remoteConnection:tv(this._reports)}}}}updateConfig(s){this._cfg=s}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const s=this._reports.slice();return s.pop(),s.pop()||null}getReportsNumber(){return this._reports.length}}const Ps="extractor ",R_=(c,s,r,o)=>{let a=!1;const t=o[s].total_rtt_ms_out,n=o[s].total_rtt_measure_out,p=r?r[s].total_rtt_ms_out:0,_=r?r[s].total_rtt_measure_out:0,d={rtt:null,totalRTT:t,totalRTTMeasurements:n};if(c[V.TIMESTAMP]===o[s].timestamp_out||!Object.prototype.hasOwnProperty.call(c,V.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(a=!0,Number(c[V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-_===n))return d;const g=1e3*Number(c[V.ROUND_TRIP_TIME]);let T=t+g,E=n+1;return a&&(T=1e3*Number(c[V.TOTAL_ROUND_TRIP_TIME])-p,E=Number(c[V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-_),{rtt:g,totalRTT:T,totalRTTMeasurements:E}},nv=(c,s,r,o)=>{if(!Object.prototype.hasOwnProperty.call(c,V.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:o[s].total_rtt_connectivity_ms,totalRTTMeasurements:o[s].total_rtt_connectivity_measure};const a=1e3*Number(c[V.CURRENT_ROUND_TRIP_TIME]);let t=o[s].total_rtt_connectivity_ms+a,n=o[s].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,V.TOTAL_ROUND_TRIP_TIME)&&(t=1e3*Number(c[V.TOTAL_ROUND_TRIP_TIME])-(r?r[s].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,V.RESPONSES_RECEIVED)&&(n=Number(c[V.RESPONSES_RECEIVED])-(r?r[s].total_rtt_connectivity_measure:0)),{rtt:a,totalRTT:t,totalRTTMeasurements:n}},vo=(c,s,r)=>c[V.TIMESTAMP]===r[s].timestamp_out||!Object.prototype.hasOwnProperty.call(c,V.JITTER)?null:1e3*(Number(c[V.JITTER])||0),rv=(c,s)=>{if(!Object.prototype.hasOwnProperty.call(c,V.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,V.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:s[x.VIDEO].delta_ms_decode_frame_in,frames_decoded:s[x.VIDEO].total_frames_decoded_in,total_decode_time:s[x.VIDEO].total_time_decoded_in};const r=c[V.FRAMES_DECODED],o=c[V.TOTAL_DECODE_TIME],a=o-s[x.VIDEO].total_time_decoded_in,t=r-s[x.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:t>0?a*1e3/t:0,frames_decoded:r,total_decode_time:o}},iv=(c,s)=>{if(!Object.prototype.hasOwnProperty.call(c,V.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,V.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:s[x.VIDEO].delta_ms_encode_frame_out,frames_encoded:s[x.VIDEO].total_frames_encoded_out,total_encode_time:s[x.VIDEO].total_time_encoded_out};const r=c[V.FRAMES_ENCODED],o=c[V.TOTAL_ENCODE_TIME],a=o-s[x.VIDEO].total_time_encoded_out,t=r-s[x.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:t>0&&a?a*1e3/t:0,frames_encoded:r,total_encode_time:o}},I_=(c,s,r,o)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,V.BYTES_SENT))return{packetsSent:r[s].total_packets_out,packetsLost:r[s].total_packets_lost_out,bytesSent:r[s].total_KBytes_out};const a=Number(c[V.PACKETS_SENT])||0-(o?o[s].total_packets_out:0),t=a-r[s].total_packets_out,n=Number(c[V.BYTES_SENT])/1024-(o?o[s].total_KBytes_out:0),p=n-r[s].total_KBytes_out,_=c[V.TIMESTAMP]||Date.now(),d=o?o.timestamp:null;let g=r.timestamp;!g&&d&&(g=d);const T=g?_-g:0,E=T>0?p*.008*1024/T*1e3:0;return{packetsSent:a,deltaPacketsSent:t,KBytesSent:n,deltaKBytesSent:p,kbsSent:E}},b_=(c,s,r,o)=>{let a=r[s].total_packets_lost_out,t=0,n=0;return Object.prototype.hasOwnProperty.call(c,V.PACKETS_LOST)&&(a=Number(c[V.PACKETS_LOST])||0-(o?o[s].total_packets_lost_out:0),t=a-r[s].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,V.FRACTION_LOST)&&(n=Number(100*c[V.FRACTION_LOST])),{packetsLost:a,deltaPacketsLost:t,fractionLost:n}},w_=(c,s,r,o)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,V.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,V.BYTES_RECEIVED))return{percent_packets_lost:r[s].percent_packets_lost_in,packetsReceived:r[s].total_packets_in,packetsLost:r[s].total_packets_lost_in,bytesReceived:r[s].total_KBytes_in};const a=Number(c[V.PACKETS_RECEIVED])||0-(o?o[s].total_packets_in:0),t=Number(c[V.PACKETS_LOST])||0-(o?o[s].total_packets_lost_in:0),n=t-r[s].total_packets_lost_in,p=a-r[s].total_packets_in,_=a!==r[s].total_packets_in?n*100/(n+p):0,d=Number(c[V.BYTES_RECEIVED])/1024-(o?o[s].total_KBytes_in:0),g=d-r[s].total_KBytes_in,T=c[V.TIMESTAMP]||Date.now(),E=o?o.timestamp:null;let y=r.timestamp;!y&&E&&(y=E);const A=y?T-y:0,C=A>0?g*.008*1024/A*1e3:0;return{percentPacketsLost:_,packetsReceived:a,deltaPacketsReceived:p,packetsLost:t,deltaPacketsLost:n,KBytesReceived:d,deltaKBytesReceived:g,kbsReceived:C}},lv=c=>c[V.CANDIDATE_TYPE]!=="relay"?"":c[V.RELAY_PROTOCOL]||"",ov=c=>{if(!Object.prototype.hasOwnProperty.call(c,V.NETWORK_TYPE))return ti.WIFI;switch(c[V.NETWORK_TYPE]){case vu.ETHERNET:return ti.ETHERNET;case vu.CELLULAR_4G:return ti.CELLULAR_4G;case vu.WIFI:return ti.WIFI;default:return ti.CELLULAR}},O_=c=>!Object.prototype.hasOwnProperty.call(c,V.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,V.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[V.FRAME_WIDTH]||null,height:c[V.FRAME_HEIGHT]||null,framerate:c[V.FRAMES_PER_SECOND]},av=c=>{const s=Object.prototype.hasOwnProperty.call(c,V.QUALITY_LIMITATION_REASON)?c[V.QUALITY_LIMITATION_REASON]:null,r=Object.prototype.hasOwnProperty.call(c,V.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[V.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,o=Object.prototype.hasOwnProperty.call(c,V.QUALITY_LIMITATION_DURATIONS)?c[V.QUALITY_LIMITATION_DURATIONS]:null;return o&&Object.keys(o).forEach(a=>{o[a]>1e3&&(o[a]=Number(o[a]/1e3))}),{reason:s,durations:o,resolutionChanges:r}},uv=(c,s,r)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PLI)||!Object.prototype.hasOwnProperty.call(c,V.NACK))return{pliCount:s.total_pli_sent_in,nackCount:s.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const o=(c[V.PLI]||0)-(r?r[x.VIDEO].total_pli_sent_in:0),a=(c[V.NACK]||0)-(r?r[x.VIDEO].total_nack_sent_in:0);return{pliCount:o,nackCount:a,deltaPliCount:o-s[x.VIDEO].total_pli_sent_in,deltaNackCount:a-s[x.VIDEO].total_nack_sent_in}},cv=(c,s,r)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PLI)||!Object.prototype.hasOwnProperty.call(c,V.NACK))return{pliCount:s.total_pli_received_out,nackCount:s.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const o=(c[V.PLI]||0)-(r?r[x.VIDEO].total_pli_received_out:0),a=(c[V.NACK]||0)-(r?r[x.VIDEO].total_nack_received_out:0);return{pliCount:o,nackCount:a,deltaPliCount:o-s[x.VIDEO].total_pli_received_out,deltaNackCount:a-s[x.VIDEO].total_nack_received_out}},fv=c=>({channels:c[V.CHANNELS]||null,clock_rate:c[V.CLOCK_RATE]||null,mime_type:c[V.MIME_TYPE]||null,sdp_fmtp_line:c[V.SDP_FMTP_LINE]||null}),_v=c=>({clock_rate:c[V.CLOCK_RATE]||null,mime_type:c[V.MIME_TYPE]||null}),hv=(c,s,r)=>{const o=(c[V.BYTES_RECEIVED]||0)/1024-(r?r.data.total_KBytes_in:0),a=(c[V.BYTES_SENT]||0)/1024-(r?r.data.total_KBytes_out:0),t=c[V.TIMESTAMP]||Date.now(),n=o-s.data.total_KBytes_in,p=a-s.data.total_KBytes_out,_=r?r.timestamp:null;let d=s.timestamp;!d&&_&&(d=_);const g=d?t-d:0,T=g>0?n*.008*1024/g*1e3:0,E=g>0?p*.008*1024/g*1e3:0;return{total_KBytes_received:o,total_KBytes_sent:a,delta_KBytes_received:n,delta_KBytes_sent:p,kbs_speed_received:T,kbs_speed_sent:E}},dv=c=>{const s=c[V.AVAILABLE_INCOMING_BITRATE]/1024||0,r=c[V.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:s,kbs_outgoing_bandwidth:r}},pv=(c,s,r,o)=>{if(!c)return[];switch(c[V.TYPE]){case zt.CANDIDATE_PAIR:let a=!1;if(c[V.NOMINATED]&&c[V.STATE]===x.SUCCEEDED&&(a=!0,xe(Ps,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c),V.SELECTED in c&&!c[V.SELECTED]&&(a=!1)),a){const n=c[V.LOCAL_CANDIDATE_ID],p=c[V.REMOTE_CANDIDATE_ID],_=hv(c,s,o),d=dv(c),g=nv(c,"data",o,s);return[{type:ne.NETWORK,value:{local_candidate_id:n}},{type:ne.NETWORK,value:{remote_candidate_id:p}},{type:ne.DATA,value:{total_KBytes_in:_.total_KBytes_received}},{type:ne.DATA,value:{total_KBytes_out:_.total_KBytes_sent}},{type:ne.DATA,value:{delta_KBytes_in:_.delta_KBytes_received}},{type:ne.DATA,value:{delta_KBytes_out:_.delta_KBytes_sent}},{type:ne.DATA,value:{delta_kbs_in:_.kbs_speed_received}},{type:ne.DATA,value:{delta_kbs_out:_.kbs_speed_sent}},{type:ne.DATA,value:{delta_kbs_bandwidth_in:d.kbs_incoming_bandwidth}},{type:ne.DATA,value:{delta_kbs_bandwidth_out:d.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[V.ID]===s.network.local_candidate_id)return[{type:ne.NETWORK,value:{infrastructure:ov(c)}},{type:ne.NETWORK,value:{local_candidate_type:c[V.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{local_candidate_protocol:c[V.PROTOCOL]||""}},{type:ne.NETWORK,value:{local_candidate_relay_protocol:lv(c)}}];break;case zt.REMOTE_CANDIDATE:if(c[V.ID]===s.network.remote_candidate_id)return[{type:ne.NETWORK,value:{remote_candidate_type:c[V.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{remote_candidate_protocol:c[V.PROTOCOL]||""}}];break;case zt.INBOUND_RTP:{xe(Ps,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const n=c[V.SSRC],p=_t(n,s,$e.INBOUND);p&&(p.timestamp=s.timestamp);const _=_t(n,o,$e.INBOUND);if(_&&(_.timestamp=o.timestamp),c[V.MEDIA_TYPE]===x.AUDIO){const d=w_(c,x.AUDIO,p,_),g=vo(c,x.AUDIO,p),T=c[V.CODEC_ID]||"";return[{ssrc:n,type:ne.AUDIO,value:{codec_id_in:T}},{ssrc:n,type:ne.AUDIO,value:{total_packets_in:d.packetsReceived}},{ssrc:n,type:ne.AUDIO,value:{delta_packets_in:d.deltaPacketsReceived}},{ssrc:n,type:ne.AUDIO,value:{total_packets_lost_in:d.packetsLost}},{ssrc:n,type:ne.AUDIO,value:{delta_packets_lost_in:d.deltaPacketsLost}},{ssrc:n,type:ne.AUDIO,value:{percent_packets_lost_in:d.percentPacketsLost}},{ssrc:n,type:ne.AUDIO,value:{total_KBytes_in:d.KBytesReceived}},{ssrc:n,type:ne.AUDIO,value:{delta_KBytes_in:d.deltaKBytesReceived}},{ssrc:n,type:ne.AUDIO,value:{delta_kbs_in:d.kbsReceived}},{ssrc:n,type:ne.AUDIO,value:{delta_jitter_ms_in:g}}]}if(c[V.MEDIA_TYPE]===x.VIDEO){const d=rv(c,p),g=w_(c,x.VIDEO,p,_),T=vo(c,x.VIDEO,p),E=c[V.DECODER_IMPLEMENTATION]||null,y=c[V.CODEC_ID]||null,A=O_(c),C=uv(c,p,_);return[{ssrc:n,type:ne.VIDEO,value:{codec_id_in:y}},{ssrc:n,type:ne.VIDEO,value:{total_packets_in:g.packetsReceived}},{ssrc:n,type:ne.VIDEO,value:{delta_packets_in:g.deltaPacketsReceived}},{ssrc:n,type:ne.VIDEO,value:{total_packets_lost_in:g.packetsLost}},{ssrc:n,type:ne.VIDEO,value:{delta_packets_lost_in:g.deltaPacketsLost}},{ssrc:n,type:ne.VIDEO,value:{percent_packets_lost_in:g.percentPacketsLost}},{ssrc:n,type:ne.VIDEO,value:{total_KBytes_in:g.KBytesReceived}},{ssrc:n,type:ne.VIDEO,value:{delta_KBytes_in:g.deltaKBytesReceived}},{ssrc:n,type:ne.VIDEO,value:{delta_kbs_in:g.kbsReceived}},{ssrc:n,type:ne.VIDEO,value:{delta_jitter_ms_in:T}},{ssrc:n,type:ne.VIDEO,value:{decoder_in:E}},{ssrc:n,type:ne.VIDEO,value:{delta_ms_decode_frame_in:d.delta_ms_decode_frame}},{ssrc:n,type:ne.VIDEO,value:{total_frames_decoded_in:d.frames_decoded}},{ssrc:n,type:ne.VIDEO,value:{total_time_decoded_in:d.total_decode_time}},{ssrc:n,type:ne.VIDEO,value:{total_nack_sent_in:C.nackCount}},{ssrc:n,type:ne.VIDEO,value:{delta_nack_sent_in:C.deltaNackCount}},{ssrc:n,type:ne.VIDEO,value:{total_pli_sent_in:C.pliCount}},{ssrc:n,type:ne.VIDEO,value:{delta_pli_sent_in:C.deltaPliCount}},{ssrc:n,type:ne.VIDEO,value:{size_in:A}}]}break}case zt.OUTBOUND_RTP:{xe(Ps,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const n=c[V.SSRC],p=_t(n,s,$e.OUTBOUND);p&&(p.timestamp=s.timestamp);const _=_t(n,o,$e.OUTBOUND);if(_&&(_.timestamp=o.timestamp),c[V.MEDIA_TYPE]===x.AUDIO){const d=c[V.CODEC_ID]||null,g=I_(c,x.AUDIO,p,_);return[{ssrc:n,type:ne.AUDIO,value:{codec_id_out:d}},{ssrc:n,type:ne.AUDIO,value:{total_packets_out:g.packetsSent}},{ssrc:n,type:ne.AUDIO,value:{delta_packets_out:g.deltaPacketsSent}},{ssrc:n,type:ne.AUDIO,value:{total_KBytes_out:g.KBytesSent}},{ssrc:n,type:ne.AUDIO,value:{delta_KBytes_out:g.deltaKBytesSent}},{ssrc:n,type:ne.AUDIO,value:{delta_kbs_out:g.kbsSent}}]}if(c[V.MEDIA_TYPE]===x.VIDEO){const d=c[V.ENCODER_IMPLEMENTATION]||null,g=c[V.CODEC_ID]||null,T=iv(c,p),E=O_(c),y=av(c),A=cv(c,p,_),C=I_(c,x.VIDEO,p,_);return[{ssrc:n,type:ne.VIDEO,value:{codec_id_out:g}},{ssrc:n,type:ne.VIDEO,value:{total_packets_out:C.packetsSent}},{ssrc:n,type:ne.VIDEO,value:{delta_packets_out:C.deltaPacketsSent}},{ssrc:n,type:ne.VIDEO,value:{total_KBytes_out:C.KBytesSent}},{ssrc:n,type:ne.VIDEO,value:{delta_KBytes_out:C.deltaKBytesSent}},{ssrc:n,type:ne.VIDEO,value:{delta_kbs_out:C.kbsSent}},{ssrc:n,type:ne.VIDEO,value:{encoder_out:d}},{ssrc:n,type:ne.VIDEO,value:{delta_ms_encode_frame_out:T.delta_ms_encode_frame}},{ssrc:n,type:ne.VIDEO,value:{total_frames_encoded_out:T.frames_encoded}},{ssrc:n,type:ne.VIDEO,value:{total_time_encoded_out:T.total_encode_time}},{ssrc:n,type:ne.VIDEO,value:{total_nack_received_out:A.nackCount}},{ssrc:n,type:ne.VIDEO,value:{delta_nack_received_out:A.deltaNackCount}},{ssrc:n,type:ne.VIDEO,value:{total_pli_received_out:A.pliCount}},{ssrc:n,type:ne.VIDEO,value:{delta_pli_received_out:A.deltaPliCount}},{ssrc:n,type:ne.VIDEO,value:{size_out:E}},{ssrc:n,type:ne.VIDEO,value:{limitation_out:y}}]}break}case zt.MEDIA_SOURCE:{xe(Ps,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);break}case zt.TRACK:{xe(Ps,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);break}case zt.CODEC:const t=[];return Object.keys(s[x.AUDIO]).forEach(n=>{const p=s[x.AUDIO][n];if(p.codec_id_in===c[V.ID]||p.codec_id_out===c[V.ID]){xe(Ps,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const _=fv(c);c[V.ID]===p.codec_id_in?t.push({ssrc:p.ssrc,type:ne.AUDIO,value:{codec_in:_}}):t.push({ssrc:p.ssrc,type:ne.AUDIO,value:{codec_out:_}})}}),Object.keys(s[x.VIDEO]).forEach(n=>{const p=s[x.VIDEO][n];if(p.codec_id_in===c[V.ID]||p.codec_id_out===c[V.ID]){xe(Ps,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const _=_v(c);c[V.ID]===p.codec_id_in?t.push({ssrc:p.ssrc,type:ne.VIDEO,value:{codec_in:_}}):t.push({ssrc:p.ssrc,type:ne.VIDEO,value:{codec_out:_}})}}),t;case zt.REMOTE_INBOUND_RTP:{xe(Ps,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const n=c[V.SSRC],p=_t(n,s,$e.OUTBOUND),_=_t(n,o,$e.OUTBOUND);if(c[V.KIND]===x.AUDIO){const d=R_(c,x.AUDIO,_,p),g=vo(c,x.AUDIO,p),T=b_(c,x.AUDIO,p,_);return[{ssrc:n,type:ne.AUDIO,value:{delta_rtt_ms_out:d.rtt}},{ssrc:n,type:ne.AUDIO,value:{total_rtt_ms_out:d.totalRTT}},{ssrc:n,type:ne.AUDIO,value:{total_rtt_measure_out:d.totalRTTMeasurements}},{ssrc:n,type:ne.AUDIO,value:{delta_jitter_ms_out:g}},{ssrc:n,type:ne.AUDIO,value:{timestamp_out:c[V.TIMESTAMP]}},{ssrc:n,type:ne.AUDIO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:n,type:ne.AUDIO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:n,type:ne.AUDIO,value:{percent_packets_lost_out:T.fractionLost}}]}if(c[V.KIND]===x.VIDEO){const d=R_(c,x.VIDEO,_,p),g=vo(c,x.VIDEO,p),T=b_(c,x.VIDEO,p,_);return[{ssrc:n,type:ne.VIDEO,value:{delta_rtt_ms_out:d.rtt}},{ssrc:n,type:ne.VIDEO,value:{total_rtt_ms_out:d.totalRTT}},{ssrc:n,type:ne.VIDEO,value:{total_rtt_measure_out:d.totalRTTMeasurements}},{ssrc:n,type:ne.VIDEO,value:{delta_jitter_ms_out:g}},{ssrc:n,type:ne.VIDEO,value:{timestamp_out:c[V.TIMESTAMP]}},{ssrc:n,type:ne.VIDEO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:n,type:ne.VIDEO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:n,type:ne.VIDEO,value:{percent_packets_lost_out:T.fractionLost}}]}break}}return[]},Eo=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),mv=(c,s=x.AUDIO,r,o,a)=>{const t=_t(a,c,$e.INBOUND),n=_t(a,r,$e.INBOUND),p=_t(a,o,$e.INBOUND),_=[],d=[],g=t[s].percent_packets_lost_in,T=t[s].delta_jitter_ms_in,E=n&&n[s].delta_jitter_ms_in||null,y=p&&p[s].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,C=r&&r.data.delta_rtt_connectivity_ms||null,I=o&&o.data.delta_rtt_connectivity_ms||null;A&&_.push(A),C&&_.push(C),I&&_.push(I),T&&d.push(T),r&&E&&d.push(E),o&&y&&d.push(y);const $=_.length>0?Us(_):100,L=d.length>0?Us(d):10,ae=93.2-g,N=.18*ae*ae-27.9*ae+1126.62,F=($+L)/2,Se=F-177.3<0?0:1,ve=.024*F+.11*(F-177.3)*Se,M=N-ve;return Eo(M)},gv=(c,s=x.AUDIO,r,o,a)=>{const t=_t(a,c,$e.OUTBOUND),n=_t(a,r,$e.OUTBOUND),p=_t(a,o,$e.OUTBOUND),_=[],d=[],g=t[s].percent_packets_lost_out,T=t[s].delta_rtt_ms_out,E=n&&n[s].delta_rtt_ms_out||null,y=p&&p[s].delta_rtt_ms_out||null,A=t[s].delta_jitter_ms_out,C=n&&n[s].delta_jitter_ms_out||null,I=p&&p[s].delta_jitter_ms_out||null,$=c.data.delta_rtt_connectivity_ms,L=r&&r.data.delta_rtt_connectivity_ms||null,ae=o&&o.data.delta_rtt_connectivity_ms||null;T?_.push(T):$&&_.push($),E?_.push(E):L&&_.push(L),y?_.push(y):ae&&_.push(ae),A&&d.push(A),r&&C&&d.push(C),o&&I&&d.push(I);const N=_.length>0?Us(_):100,F=d.length>0?Us(d):10,Se=93.2-g,ve=.18*Se*Se-27.9*Se+1126.62,M=(N+F)/2,D=M-177.3<0?0:1,B=.024*M+.11*(M-177.3)*D,q=ve-B;return Eo(q)},Tv=(c,s=x.AUDIO,r,o,a)=>{const t=_t(a,c,$e.INBOUND),n=_t(a,r,$e.INBOUND),p=_t(a,o,$e.INBOUND),_=[],d=[],g=t[s].percent_packets_lost_in/100,T=t[s].delta_jitter_ms_in,E=n&&n[s].delta_jitter_ms_in||null,y=p&&p[s].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,C=r&&r.data.delta_rtt_connectivity_ms||null,I=o&&o.data.delta_rtt_connectivity_ms||null;A&&_.push(A),C&&_.push(C),I&&_.push(I),T&&d.push(T),n&&E&&d.push(E),p&&y&&d.push(y);const $=_.length>0?Us(_):100,L=d.length>0?Us(d):10,ae=0,N=19.8,F=29.7,Se=30,ve=($+L)/2+Se,M=ve-177.3<0?0:1,D=.024*ve+.11*(ve-177.3)*M,q=93.2-(ae+N*Math.log(1+F*g)+D);return Eo(q)},vv=(c,s=x.AUDIO,r,o,a)=>{const t=_t(a,c,$e.OUTBOUND),n=_t(a,r,$e.OUTBOUND),p=_t(a,o,$e.OUTBOUND),_=[],d=[],g=t[s].percent_packets_lost_out/100,T=t[s].delta_rtt_ms_out,E=n&&n[s].delta_rtt_ms_out||null,y=p&&p[s].delta_rtt_ms_out||null,A=t[s].delta_jitter_ms_out,C=n&&n[s].delta_jitter_ms_out||null,I=p&&p[s].delta_jitter_ms_out||null,$=c.data.delta_rtt_connectivity_ms,L=r&&r.data.delta_rtt_connectivity_ms||null,ae=o&&o.data.delta_rtt_connectivity_ms||null;T?_.push(T):$&&_.push($),E?_.push(E):L&&_.push(L),y?_.push(y):ae&&_.push(ae),A&&d.push(A),n&&C&&d.push(C),p&&I&&d.push(I);const N=_.length>0?Us(_):100,F=d.length>0?Us(d):10,Se=0,ve=19.8,M=29.7,D=30,B=(N+F)/2+D,q=B-177.3<0?0:1,z=.024*B+.11*(B-177.3)*q,Z=93.2-(Se+ve*Math.log(1+M*g)+z);return Eo(Z)};class Ev{constructor(s,r){this._callbacks={onreport:null,onticket:null},this._id=JT(),this._moduleName=this._id,this._probeId=r,this._config=s,this._exporter=new sv(s),this._state=Ts.IDLE,this.registerToPCEvents(),sn(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(s,r,o,a){const t=(_,d)=>_===x.AUDIO?d===zt.INBOUND_RTP?{...v_}:{...E_}:d===zt.INBOUND_RTP?{...S_}:{...y_},n=GT(r);n.pname=this._config.pname,n.call_id=this._config.cid,n.user_id=this._config.uid,n.count=r?r.count+1:1;let p=null;return s.forEach(_=>{!p&&_.timestamp&&(p=_.timestamp),pv(_,n,n.pname,a).forEach(g=>{if(g.value&&g.type)if(g.ssrc){let T=n[g.type][g.ssrc];T||(T=t(g.type,_.type),T.ssrc=g.ssrc,n[g.type][g.ssrc]=T),Object.keys(g.value).forEach(E=>{T[E]=g.value[E]})}else Object.keys(g.value).forEach(T=>{n[g.type][T]=g.value[T]})})}),n.timestamp=p,Object.keys(n[x.AUDIO]).forEach(_=>{const d=n[x.AUDIO][_];d.direction===$e.INBOUND?(d.mos_emodel_in=mv(n,x.AUDIO,r,o,d.ssrc),d.mos_in=Tv(n,x.AUDIO,r,o,d.ssrc)):(d.mos_emodel_out=gv(n,x.AUDIO,r,o,d.ssrc),d.mos_out=vv(n,x.AUDIO,r,o,d.ssrc))}),n}async takeReferenceStats(){return new Promise((s,r)=>{const o=Date.now();setTimeout(async()=>{try{const a=Date.now()-o,t=Date.now(),n=await this._config.pc.getStats(),p=this.analyze(n,null,null,null),_=Date.now();p.experimental.time_to_measure_ms=_-t,p.experimental.time_to_wait_ms=a,this._exporter.saveReferenceReport(p),xe(this._moduleName,`got reference report for probe ${this._probeId}`),s()}catch(a){r(a)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==Ts.RUNNING||!this._config.pc)return xe(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const s=Date.now(),r=await this._config.pc.getStats(),o=this.analyze(r,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),a=Date.now();return o.experimental.time_to_measure_ms=a-s,this._exporter.addReport(o),xe(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(o),o}catch(s){return Fn(this._moduleName,`got error ${s}`),null}}async start(){xe(this._moduleName,"starting"),this.state=Ts.RUNNING,this._startedTime=this._exporter.start(),xe(this._moduleName,"started")}async mute(){this.state=Ts.MUTED,xe(this._moduleName,"muted")}async unmute(){this.state=Ts.RUNNING,xe(this._moduleName,"unmuted")}async stop(s){if(xe(this._moduleName,`stopping${s?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=Ts.IDLE,this._config.ticket){const{ticket:r}=this._exporter;this.fireOnTicket(r)}this._exporter.reset(),xe(this._moduleName,"stopped")}registerCallback(s,r,o){s in this._callbacks?(this._callbacks[s]={callback:r,context:o},xe(this._moduleName,`registered callback '${s}'`)):Fn(this._moduleName,`can't register callback for '${s}' - not found`)}unregisterCallback(s){s in this._callbacks?(this._callbacks[s]=null,delete this._callbacks[s],xe(this._moduleName,`unregistered callback '${s}'`)):Fn(this._moduleName,`can't unregister callback for '${s}' - not found`)}fireOnReport(s){this._callbacks.onreport&&Su(this._callbacks.onreport.callback,this._callbacks.onreport.context,s)}fireOnTicket(s){this._callbacks.onticket&&Su(this._callbacks.onticket.callback,this._callbacks.onticket.context,s)}updateConfig(s){this._config=s,this._exporter.updateConfig(s)}get state(){return this._state}set state(s){this._state=s,xe(this._moduleName,`state changed to ${s}`)}addCustomEvent(s,r,o,a){this._exporter.addCustomEvent({at:typeof s=="object"?s.toJSON():s,category:r,name:o,description:a})}async registerToPCEvents(){const{pc:s}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const r=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${r.length} devices found`,"Media Devices state")}catch{Fn(this._moduleName,"can't get devices")}},s){s.oniceconnectionstatechange=()=>{const o=s.iceConnectionState;o===ei.CONNECTED||o===ei.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===ei.DISCONNECTED||o===ei.FAILED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===ei.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},s.onicegatheringstatechange=()=>{const o=s.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",o,"ICE gathering state")},s.ontrack=o=>{this.addCustomEvent(new Date().toJSON(),"call",`${o.track.kind}track`,"MediaStreamTrack received")},s.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const r=s.getReceivers();if(r&&r.length>0){const o=r[0],{transport:a}=o;if(a){const{iceTransport:t}=a;t&&(t.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class Sv{constructor(s){this._id=s.pname&&s.pname.substr(0,12).padEnd(12," ")||zT(),this._moduleName=this._id,sn(this._moduleName,"probe created"),this._config=s,this._collector=new Ev(this._config,this._id)}set onreport(s){s?this._collector.registerCallback("onreport",s):this._collector.unregisterCallback("onreport")}set onticket(s){s?this._collector.registerCallback("onticket",s):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(s){this._collector.state=s}addCustomEvent(s,r,o,a=new Date().toJSON()){this._collector.addCustomEvent(a,r,s,o)}get isRunning(){return this._collector.state===Ts.RUNNING}get isIdle(){return this._collector.state===Ts.IDLE}updateUserId(s){this._config.uid=s,this._collector.updateConfig(this._config)}updateCallId(s){this._config.cid=s,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){To(this._moduleName,"probe is already running");return}this._collector.start()}stop(s=!1){this.isRunning&&this._collector.stop(s)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const It="engine ";class yv{constructor(s){this._config=s,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},sn(It,`configured for probing every ${this._config.refreshEvery}ms`),sn(It,`configured for starting after ${this._config.startAfter}ms`),sn(It,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),xe(It,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(s=>s.isRunning)}get isIdle(){return this._probes.every(s=>s.isIdle)}addNewProbe(s,r){if(!s)throw new Error("undefined peer connection");const o=KT(s,r,this._config),a=new Sv(o);return this._probes.push(a),xe(It,`${this._probes.length} probes registered`),a}removeExistingProbe(s){if(!s)throw new Error("undefined probe");s.state===Ts.RUNNING&&s.stop(),this._probes=this._probes.filter(r=>s.id!==r.id)}async start(){const s=()=>{this._probes.forEach(t=>t.start())},r=async()=>Promise.all(this._probes.map(t=>t.takeReferenceStats())),o=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,a=async()=>{const t=BT(),n=this._probes.filter(p=>p.isRunning);for(const p of n){const _=await p.collectStats();_&&t.probes.push(_),xe(It,`got probe ${p.id}`),await A_(0)}return t.delta_time_to_measure_probes_ms=nn(t.probes,"experimental","time_to_measure_ms"),t.delta_KBytes_in=nn(t.probes,"data","delta_KBytes_in"),t.delta_KBytes_out=nn(t.probes,"data","delta_KBytes_out"),t.delta_kbs_in=nn(t.probes,"data","delta_kbs_in"),t.delta_kbs_out=nn(t.probes,"data","delta_kbs_out"),t.total_time_decoded_in=nn(t.probes,"video","total_time_decoded_in"),t.total_time_encoded_out=nn(t.probes,"video","total_time_encoded_out"),t};for(xe(It,"starting to collect"),s(),xe(It,"generating reference reports..."),await r(),xe(It,"reference reports generated"),this._startedTime=Date.now();o();)if(xe(It,`wait ${this._config.refreshEvery}ms before collecting`),await A_(this._config.refreshEvery),o()){xe(It,"collecting...");const t=Date.now(),n=await a(),p=Date.now();n.delta_time_consumed_to_measure_ms=p-t,this.fireOnReports(n),xe(It,"collected")}xe(It,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(s){const r=o=>{this._probes.forEach(a=>{a.stop(o)})};sn(It,"stop collecting"),r(s)}registerCallback(s,r,o){s in this._callbacks?(this._callbacks[s]={callback:r,context:o},xe(It,`registered callback '${s}'`)):Fn(It,`can't register callback for '${s}' - not found`)}unregisterCallback(s){s in this._callbacks?(this._callbacks[s]=null,delete this._callbacks[s],xe(this._moduleName,`unregistered callback '${s}'`)):Fn(this._moduleName,`can't unregister callback for '${s}' - not found`)}fireOnReports(s){this._callbacks.onresult&&s.probes.length>0&&Su(this._callbacks.onresult.callback,this._callbacks.onresult.context,s)}}const Av="interface ";class Cv{constructor(s){this._config=YT(s),sn(Av,`welcome to ${this._config.name} version ${this._config.version}`),kT(this._config.verbose||!1),this._engine=new yv(this._config)}setupLogLevel(s){LT(s)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(s,r){return this._engine.addNewProbe(s,r)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(s){this._engine.removeExistingProbe(s)}set onresult(s){s?this._engine.registerCallback("onresult",s):this._engine.unregisterCallback("onresult")}}function Rv(c,s){return Object.keys(c).filter(r=>s.includes(r)).reduce((r,o)=>{const a=o;return{...r,[a]:c[a]}},{})}const Iv=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"];class bv{constructor(s){this.intervals={},this.emitInterval=s.emitInterval||200,this.onChangeFunction=s.onChangeFunction}start(s,r){s&&s.getTracks().length&&requestAnimationFrame(()=>this.beginCalculation(s,r))}stop(s){this.clearVolumeInterval(s)}clearVolumeInterval(s){console.log("clearVolumeInterval",s),clearInterval(this.intervals[s]),delete this.intervals[s]}clearAllIntervals(){Object.keys(this.intervals).forEach(s=>{clearInterval(this.intervals[s])}),this.intervals={}}beginCalculation(s,r){this.clearVolumeInterval(r);const o=tn.createAnalyser(),a=tn.createMediaStreamSource(s),t=tn.createScriptProcessor(2048,1,1);o.smoothingTimeConstant=.8,o.fftSize=1024,a.connect(o),o.connect(t),t.connect(tn.destination),this.intervals[r]=setInterval(()=>{const n=new Uint8Array(o.frequencyBinCount);o.getByteFrequencyData(n);let p=0;const _=n.length;for(let g=0;g<_;g++)p+=n[g];const d=p/_;this.onChangeFunction(r,d)},this.emitInterval)}}const So={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},wv=0;class Ov{constructor(s){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=s,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new bv({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices()}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(s){this.currentActiveRoomIdValue=s,this.context.emit("currentActiveRoomChanged",s)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(s){this.isCallAddingInProgress=s,this.context.emit("callAddingInProgressChanged",s)}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(s=>s.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(s=>s.kind==="audiooutput")}get getUserMediaConstraints(){return d_()?{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(s){this.availableMediaDevices=s,this.context.emit("changeAvailableDeviceList",s)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const s=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(s)}async initializeMediaDevices(){const s=localStorage.getItem(So.SELECTED_INPUT_DEVICE)||"default",r=localStorage.getItem(So.SELECTED_OUTPUT_DEVICE)||"default";try{const o=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),a=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(a),await this.setMicrophone(s),await this.setSpeaker(r),navigator.mediaDevices.addEventListener("devicechange",async()=>{const t=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(t)}),o.getTracks().forEach(t=>t.stop())}catch(o){console.error(o)}}setCallTime(s){const r={...s};delete r.callId,this.callTime={...this.callTime,[s.callId]:r},this.context.emit("changeCallTime",this.callTime)}removeCallTime(s){const r={...this.callTime};delete r[s],this.callTime={...r},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(s,r){this.timeIntervals={...this.timeIntervals,[s]:r}}removeTimeInterval(s){const r={...this.timeIntervals};r[s]&&(clearInterval(r[s]),delete r[s],this.timeIntervals={...r})}stopCallTimer(s){this.removeTimeInterval(s),this.removeCallTime(s)}emitVolumeChange(s,r){this.context.emit("changeCallVolume",{callId:s,volume:r})}setMetricsConfig(s){this.metricConfig={...this.metricConfig,...s}}sendDTMF(s,r){if(!/^[A-D0-9]+$/g.test(r))throw new Error("Not allowed character in DTMF input");this.extendedCalls[s].sendDTMF(r)}setIsMuted(s){this.muted=s,this.context.emit("changeIsMuted",s)}processMute(s){const r=this.currentActiveRoomId;this.setIsMuted(s),this.initialStreamValue.getTracks().forEach(o=>o.enabled=!s),this.roomReconfigure(r)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:s,toHold:r,automatic:o}){const a=this.extendedCalls[s];a._automaticHold=o??!1,await new Promise(p=>{const _=()=>{p()};r?a.hold({},_):a.unhold({},_)}),this.updateCall(a);const n=Object.values(this.extendedCalls).filter(p=>p.roomId===this.currentActiveRoomId&&(r?s!==p._id:!0));n.length>1&&await this.doConference(n)}holdCall(s,r=!1){return this.processHold({callId:s,automatic:r,toHold:!0})}unholdCall(s){return this.processHold({callId:s,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(s=>s.direction==="outgoing"&&s.status===wv).forEach(s=>this.terminateCall(s._id))}answerCall(s){const r=this.extendedCalls[s];this.cancelAllOutgoingUnanswered(),r.answer(this.sipOptions),this.updateCall(r),this.setActiveRoom(r.roomId),r.connection.addEventListener("track",o=>{this.triggerAddStream(o,r)})}async moveCall(s,r){this.updateCallStatus({callId:s,isMoving:!0}),await this.processRoomChange({callId:s,roomId:r}),this.updateCallStatus({callId:s,isMoving:!1})}updateCall(s){this.activeCalls[s._id]=f_(s),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(s){const o={...this.activeRooms[s.roomId],...s};this.activeRooms={...this.activeRooms,[s.roomId]:{...o}},this.context.emit("updateRoom",{room:o,roomList:this.activeRooms})}hasAutoAnswerHeaders(s){const r=/answer-after=0/,a=s.request.getHeader("Call-Info");return a&&r.test(a)}addCall(s,r=!0){this.activeCalls={...this.activeCalls,[s._id]:f_(s)},this.extendedCalls[s._id]=s,r&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(s){this.callStatus={...this.callStatus,[s]:{isMoving:!1,isTransferring:!1,isMerging:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(s){const o={...{...this.callStatus[s.callId]}};s.isMoving!==void 0&&(o.isMoving=s.isMoving),s.isTransferring!==void 0&&(o.isTransferring=s.isTransferring),s.isMerging!==void 0&&(o.isMerging=s.isMerging),this.callStatus={...this.callStatus,[s.callId]:{...o}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(s){const r={...this.callStatus};delete r[s],this.callStatus={...r},this.context.emit("changeCallStatus",this.callStatus)}addRoom(s){this.activeRooms={...this.activeRooms,[s.roomId]:s},this.context.emit("addRoom",{room:s,roomList:this.activeRooms})}getActiveStream(){const s=h_(this.initialStreamValue,this.microphoneInputLevel*2);return s.getTracks().forEach(r=>r.enabled=!this.isMuted),this.setActiveStream(s),s}async setMicrophone(s){if(!this.getInputDeviceList.find(({deviceId:o})=>o===s)||(this.setSelectedInputDevice(s),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const r=Object.values(this.extendedCalls).filter(o=>o.roomId===this.currentActiveRoomId);r.length===1?Object.values(r).forEach(async o=>{const a=this.getActiveStream();o.connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.updateCall(o)}):await this.doConference(r)}setActiveStream(s){this.activeStream&&this.stopVUMeter("origin"),this.setupVUMeter(s,"origin"),this.activeStreamValue=s,this.context.emit("changeActiveStream",s)}async setSpeaker(s){if(!this.getOutputDeviceList.find(({deviceId:a})=>a===s))return;this.setSelectedOutputDevice(s);const r=Object.values(this.extendedCalls);if(r.length===0)return;const o=r.filter(a=>a.roomId===this.currentActiveRoomId);o.length===1?r.forEach(a=>{var t;(t=a.audioTag)==null||t.setSinkId(s),this.updateCall(a)}):await this.doConference(o)}removeRoom(s){const r={...this.activeRooms},o={...r[s]};delete r[s],this.activeRooms={...r},this.context.emit("removeRoom",{room:o,roomList:this.activeRooms})}deleteRoomIfEmpty(s){s!==void 0&&Object.values(this.extendedCalls).filter(r=>r.roomId===s).length===0&&(this.removeRoom(s),this.currentActiveRoomId===s&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(s){this.muted?s.mute({audio:!0}):s.unmute({audio:!0})}async roomReconfigure(s){var o;if(s===void 0)return;const r=Object.values(this.extendedCalls).filter(a=>a.roomId===s);if(this.currentActiveRoomId===s?r.forEach(a=>{a.audioTag&&(this.muteReconfigure(a),a.audioTag.muted=!1,this.updateCall(a))}):r.forEach(a=>{a.audioTag&&(a.audioTag.muted=!0,this.updateCall(a))}),r.length===0)this.deleteRoomIfEmpty(s);else if(r.length===1&&this.currentActiveRoomId!==s)r[0].isOnHold().local||await this.holdCall(r[0].id,!0);else if(r.length===1&&this.currentActiveRoomId===s){if(r[0].isOnHold().local&&r[0]._automaticHold&&await this.unholdCall(r[0].id),r[0].connection&&((o=r[0].connection)!=null&&o.getSenders()[0])){const a=this.getActiveStream();await r[0].connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.muteReconfigure(r[0])}}else r.length>1&&await this.doConference(r)}async doConference(s){await m_.forEach(s,async o=>{o._localHold&&await this.unholdCall(o._id)});const r=[];s.forEach(o=>{o!=null&&o.connection.getReceivers().forEach(a=>{r.push(a.track)})}),await m_.forEach(s,async o=>{var n;if(o==null)return;const a=new MediaStream,t=tn.createMediaStreamDestination();if(o.connection.getReceivers().forEach(p=>{r.forEach(_=>{a.addTrack(p.track),p.track.id!==_.id&&tn.createMediaStreamSource(new MediaStream([_])).connect(t)})}),s[0].roomId===this.currentActiveRoomId){const p=this.getActiveStream();tn.createMediaStreamSource(p).connect(t)}(n=o.connection)!=null&&n.getSenders()[0]&&(await o.connection.getSenders()[0].replaceTrack(t.stream.getTracks()[0]),this.muteReconfigure(o))})}processCallerMute(s,r){const o=this.extendedCalls[s];o&&o.connection.getReceivers().length&&(o.localMuted=r,o.connection.getReceivers().forEach(a=>{a.track.enabled=!r}),this.updateCall(o))}muteCaller(s){this.processCallerMute(s,!0)}unmuteCaller(s){this.processCallerMute(s,!1)}terminateCall(s){const r=this.extendedCalls[s];r._status!==8&&r.terminate()}transferCall(s,r){if(r.toString().length===0)return new Error("Target must be passed");const o=this.extendedCalls[s];if(!o._is_confirmed&&!o._is_canceled){const a=`sip:${r}@${this.context.sipDomain}`;o.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${a}`]});return}this.updateCallStatus({callId:s,isTransferring:!0}),o.refer(`sip:${r}@${this.context.sipDomain}`),this.updateCall(o)}mergeCall(s){const r=Object.values(this.extendedCalls).filter(t=>t.roomId===s);if(r.length!==2)return;const o=r[0],a=r[1];!o||!a||(this.updateCallStatus({callId:o._id,isMerging:!0}),this.updateCallStatus({callId:a._id,isMerging:!0}),o.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(o))}mergeCallByIds(s,r){const o=Object.values(this.extendedCalls).find(t=>t._id===s),a=Object.values(this.extendedCalls).find(t=>t._id===r);if(!o||!a)throw new Error("Call ID is not provided");this.updateCallStatus({callId:s,isMerging:!0}),this.updateCallStatus({callId:r,isMerging:!0}),o.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(o)}setDND(s){this.isDNDEnabled=s,this.context.emit("changeIsDND",s)}startCallTimer(s){this.removeTimeInterval(s);const r={callId:s,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(r);const o=setInterval(()=>{const a={...this.callTime[s]},t=xT(a);this.setCallTime({callId:s,...t})},1e3);this.setTimeInterval(s,o)}async setActiveRoom(s){const r=this.currentActiveRoomId;s!==r&&(this.currentActiveRoomId=s,await this.roomReconfigure(r),await this.roomReconfigure(s))}getNewRoomId(){const s=Object.keys(this.activeRooms);return s.length===0?1:parseInt(s.sort()[s.length-1])+1}async setupCall(s){var d,g;const r=s.session;if(this.getActiveCalls[r.id]!==void 0)return;const a=this.getNewRoomId(),t={started:new Date,incomingInProgress:!1,roomId:a};r.direction==="incoming"?(this.context.logger.log("New incoming call from",(g=(d=r._remote_identity)==null?void 0:d._uri)==null?void 0:g._user),t.incomingInProgress=!0,this.context.subscribe(Yt.CALL_CONFIRMED,T=>{r.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.startCallTimer(r.id))}),this.context.subscribe(Yt.CALL_FAILED,T=>{r.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.deleteRoomIfEmpty(a))})):r.direction==="outgoing"&&(r.once("confirmed",()=>{this.startCallTimer(r.id)}),this.startCallTimer(r.id));const n=r,p=this.hasAutoAnswerHeaders(s),_=n.direction==="incoming"&&!this.hasActiveCalls&&(p||this.autoAnswer);n.roomId=a,n.localMuted=!1,n.autoAnswer=_,_?this.addCall(n,!1):this.addCall(n),this.addCallStatus(r.id),this.addRoom(t),_&&this.answerCall(n._id)}removeCall(s){const r={...this.activeCalls};delete r[s],this.activeCalls={...r};const o={...this.extendedCalls};delete o[s],this.extendedCalls={...o},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(s){var a;const r=this.extendedCalls[s._id];this.stopVUMeter("origin"),(a=r.connection)==null||a.getSenders().forEach(t=>{t.track.stop()});const o=r.roomId;this.removeCall(s._id),this.roomReconfigure(o)}async newRTCSessionCallback(s){const r=s.session;if(this.isDND){r.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(this.context.triggerListener({listenerType:Yt.NEW_CALL,session:r,event:s}),r.on("ended",o=>{var t,n,p;this.stopVUMeter(r.id),this.context.logger.log("Session ended for",(n=(t=r._remote_identity)==null?void 0:t._uri)==null?void 0:n._user),this.context.triggerListener({listenerType:Yt.CALL_ENDED,session:r,event:o});const a=this.getActiveCalls[r.id];a&&this.activeCallListRemove(a),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(p=this.initialStreamValue)==null||p.getTracks().forEach(_=>_.stop()),this.initialStreamValue=null)}),r.on("progress",o=>{var a,t;this.context.logger.log("Session in progress for",(t=(a=r._remote_identity)==null?void 0:a._uri)==null?void 0:t._user),this.context.triggerListener({listenerType:Yt.CALL_PROGRESS,session:r,event:o})}),r.on("failed",o=>{var t,n,p;this.stopVUMeter(r.id),this.context.logger.log("Session failed for",(n=(t=r._remote_identity)==null?void 0:t._uri)==null?void 0:n._user),this.context.triggerListener({listenerType:Yt.CALL_FAILED,session:r,event:o}),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const a=this.getActiveCalls[r.id];a&&this.activeCallListRemove(a),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(p=this.initialStreamValue)==null||p.getTracks().forEach(_=>_.stop()),this.initialStreamValue=null)}),r.on("confirmed",o=>{var a,t;this.context.logger.log("Session confirmed for",(t=(a=r._remote_identity)==null?void 0:a._uri)==null?void 0:t._user),this.context.triggerListener({listenerType:Yt.CALL_CONFIRMED,session:r,event:o}),this.updateCall(r),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(s),r.direction==="outgoing"){const o=this.getActiveCalls[r.id].roomId;this.setActiveRoom(o)}}setMuteWhenJoin(s){this.muteWhenJoinEnabled=s,this.context.emit("changeMuteWhenJoin",s)}setMicrophoneSensitivity(s){if(s<0||s>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=s,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(s){this.speakerVolumeValue=s,Object.values(this.extendedCalls).forEach(r=>{r.audioTag&&(r.audioTag.volume=s,this.updateCall(r))})}setAutoAnswer(s){this.isAutoAnswer=s}setSelectedInputDevice(s){localStorage.setItem(So.SELECTED_INPUT_DEVICE,s),this.selectedMediaDevices.input=s,this.context.emit("changeActiveInputMediaDevice",s)}setSelectedOutputDevice(s){localStorage.setItem(So.SELECTED_OUTPUT_DEVICE,s),this.selectedMediaDevices.output=s,this.context.emit("changeActiveOutputMediaDevice",s)}setCallMetrics(s){const r={...s};delete r.callId,this.callMetrics={...this.callMetrics,[s.callId]:r},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(s){const r={...this.callMetrics};delete r[s],this.callMetrics={...r},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(s){const r=new Cv(this.metricConfig),o=r.createProbe(s.connection,{cid:s._id}),a=[];let t;o.onreport=n=>{Object.entries(n.audio).forEach(([d,g])=>{g.direction==="inbound"&&!a.includes(d)&&(a.push(d),t=d)});const p=n.audio[t];if(!p)return;const _=Rv(p,Iv);_.callId=s._id,this.setCallMetrics(_)},this.context.subscribe(Yt.CALL_ENDED,n=>{n._id===s._id&&r.stopAllProbes()}),r.startAllProbes()}setupVUMeter(s,r){this.VUMeter.start(s,r)}stopVUMeter(s){this.VUMeter.stop(s)}async setupStream(){const s=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach(r=>r.stop()),this.initialStreamValue=null),this.initialStreamValue=s}async triggerAddStream(s,r){this.setIsMuted(this.muteWhenJoin||this.isMuted),this.initialStreamValue||await this.setupStream();const o=h_(this.initialStreamValue,this.microphoneInputLevel*2),a=this.isMuted||this.muteWhenJoin;o.getTracks().forEach(n=>n.enabled=!a),this.setActiveStream(o),await r.connection.getSenders()[0].replaceTrack(o.getTracks()[0]);const t=new MediaStream([s.track]);vT(t,r,this.selectedOutputDevice,this.speakerVolume),this.setupVUMeter(t,r._id),this.getCallQuality(r),this.updateCall(r)}initCall(s,r){if(this.checkInitialized(),s.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${s}@${this.context.sipDomain}...`);const o=this.context.call(`sip:${s}@${this.context.sipDomain}`,this.sipOptions);this.callAddingInProgress=o.id,r&&this.currentActiveRoomId!==void 0&&this.processRoomChange({callId:o.id,roomId:this.currentActiveRoomId}),o.connection.addEventListener("track",a=>{this.triggerAddStream(a,o)})}async processRoomChange({callId:s,roomId:r}){const o=this.extendedCalls[s].roomId;this.extendedCalls[s].roomId=r;const a=this.extendedCalls[s];return this.updateCall(a),await this.setActiveRoom(r),Promise.all([this.roomReconfigure(o),this.roomReconfigure(r)]).then(()=>{this.deleteRoomIfEmpty(o),this.deleteRoomIfEmpty(r)})}}class Dv{constructor(s){this.context=s}get sipOptions(){return{...this.context.options.sipOptions}}initCall(s,r){if(s.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${s}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${s}@${this.context.sipDomain}`,r,this.sipOptions),console.log("video call")}stop(s={}){this.context.terminateJanusSessions(s)}}class Nv{constructor(s){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=s,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this.context))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(s){const r=this.extendedMessages[s];this.updateMSRPSession(r)}updateMSRPSession(s){this.activeMessages[s._id]=__(s),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(s){this.activeMessages={...this.activeMessages,[s._id]:__(s)},this.extendedMessages[s._id]=s,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(s,r){const o=this.msrpHistory[r.id]||[];o.push(s),this.msrpHistory={...this.msrpHistory,[r.id]:[...o]},this.context.emit("newMSRPMessage",{message:s,session:r})}messageTerminate(s){const r=this.extendedMessages[s];r._status!==8&&r.terminate()}addMessageSession(s){if(!s._id||this.getActiveMessages[s._id]!==void 0)return;const o=s;this.addMMSRPSession(o)}triggerMSRPListener({listenerType:s,session:r,event:o}){const a=this.context.listenersList[s];!a||!a.length||a.forEach(t=>{t(r,o)})}removeMMSRPSession(s){const r={...this.activeMessages};delete r[s],this.activeMessages={...r};const o={...this.extendedMessages};delete o[s],this.extendedMessages={...o},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(s){this.removeMMSRPSession(s._id)}newMSRPSessionCallback(s){const r=s.session;r.on("ended",o=>{this.triggerMSRPListener({listenerType:Yt.CALL_ENDED,session:r,event:o});const a=this.getActiveMessages[r.id];this.activeMessageListRemove(a)}),r.on("failed",o=>{this.triggerMSRPListener({listenerType:Yt.CALL_FAILED,session:r,event:o});const a=this.getActiveMessages[r.id];this.activeMessageListRemove(a)}),r.on("confirmed",o=>{this.triggerMSRPListener({listenerType:Yt.CALL_CONFIRMED,session:r,event:o}),this.updateMSRPSession(r)}),r.on("newMessage",o=>{this.addMSRPMessage(o,r)}),this.addMessageSession(r)}setIsMSRPInitializing(s){this.isMSRPInitializingValue=s,this.context.emit("isMSRPInitializingChanged",s)}initMSRP(s,r,o){if(s.length===0)return console.error("Target must be a valid string");const a=this.context.startMSRP(s,o);a.on("active",()=>{this.addMessageSession(a),a.sendMSRP(r),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(s,r){const o=this.extendedMessages[s];if(!o)throw new Error(`MSRP session with id ${s} doesn't exist!`);o.sendMSRP(r)}}const yu={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Uv extends _T{constructor(s,r){if(!s.modules.length)throw new Error("options.modules should include at least 1 module");const o={...s.configuration,sockets:s.socketInterfaces.map(a=>new PT.WebSocketInterface(a))};super(o),this.initialized=!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.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],s.pnExtraHeaders&&Object.keys(s.pnExtraHeaders).length&&this.registrator().setExtraContactParams(s.pnExtraHeaders),this.options=s,this.modules=s.modules,r&&ET(r)&&(this.logger=r)}on(s,r){return super.on(s,r)}off(s,r){return super.off(s,r)}emit(s,r){return super.emit(s,r)}get sipDomain(){return this.options.sipDomain}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(yu.AUDIO)&&(this.audio=new Ov(this)),this.modules.includes(yu.MSRP)&&(this.msrp=new Nv(this)),this.modules.includes(yu.VIDEO)&&(this.video=new Dv(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.isReconnecting=!1}),this.on(this.disconnectedEventName,()=>{this.isReconnecting||(this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.isReconnecting=!0,this.stop(),this.setInitialized(!1),setTimeout(this.start.bind(this),5e3))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}subscribe(s,r){const a=!this.listenersList[s]||!this.listenersList[s].length?[r]:[...this.listenersList[s],r];this.listenersList={...this.listenersList,[s]:a}}removeIListener(s){const r={...this.listenersList};delete r[s],this.listenersList={...r}}triggerListener({listenerType:s,session:r,event:o}){const a=this.listenersList[s];!a||!a.length||a.forEach(t=>{t(r,o)})}setInitialized(s){this.initialized=s,this.emit("ready",s)}}return Uv});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voicenter-team/opensips-js",
3
- "version": "1.0.87",
3
+ "version": "1.0.88",
4
4
  "description": "The JS package for opensips",
5
5
  "default": "src/index.ts",
6
6
  "jsdelivr": "dist/opensips-js.umd.js",