@voicenter-team/opensips-js 1.0.93 → 1.0.94
Sign up to get free protection for your applications and to get access to all the features.
package/dist/opensips-js.cjs.js
CHANGED
@@ -155,4 +155,4 @@ 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
156
|
`),this._newMSRPSession("local",this._request),this._id=this._request.call_id+this._from_tag,console.log("dialog be",this._dialog),new Ga(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:_=>{this.onTransportError(),console.log(_)},onAuthenticated:_=>{this._request=_},onReceiveResponse:_=>{this._receiveInviteResponse(_),console.log("dialog af",this._dialog),_.status_code===200&&(_.parseSDP(!0),this._status=be.STATUS_CONFIRMED,this.target_addr=_.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=be.STATUS_INVITE_SENT}terminate(s={}){console.log("terminate",this);const i=s.cause||F.causes.BYE,l=$e.cloneArray(s.extraHeaders),a=s.body;let _,e=s.status_code,p=s.reason_phrase;if(this._status===be.STATUS_TERMINATED)throw new zs.InvalidStateError(this._status);switch(this.status="terminated",this._status){case be.STATUS_NULL:case be.STATUS_INVITE_SENT:case be.STATUS_1XX_RECEIVED:if(e&&(e<200||e>=700))throw new TypeError(`Invalid status_code: ${e}`);e&&(p=p||F.REASON_PHRASE[e]||"",_=`SIP ;cause=${e} ;text="${p}"`),this._status===be.STATUS_NULL||this._status===be.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=_):this._status===be.STATUS_1XX_RECEIVED&&this._request.cancel(_),this._status=be.STATUS_CANCELED,console.log("failed 1"),this._failed("local",null,F.causes.CANCELED);break;case be.STATUS_WAITING_FOR_ANSWER:case be.STATUS_ANSWERED:if(e=e||480,console.log("REPLY 480"),e<300||e>=700)throw new TypeError(`Invalid status_code: ${e}`);this._request.reply(e,p,l,a),console.log("failed 2"),this._failed("local",null,F.causes.REJECTED);break;case be.STATUS_WAITING_FOR_ACK:case be.STATUS_CONFIRMED:if(p=s.reason_phrase||F.REASON_PHRASE[e]||"",e&&(e<200||e>=700))throw new TypeError(`Invalid status_code: ${e}`);if(e&&l.push(`Reason: SIP ;cause=${e}; text="${p}"`),this._status===be.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Vt.C.STATUS_TERMINATED){const g=this._dialog;this.receiveRequest=({method:n})=>{n===F.ACK&&(this.sendRequest(F.BYE,{extraHeaders:l,body:a}),g.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Vt.C.STATUS_TERMINATED&&(this.sendRequest(F.BYE,{extraHeaders:l,body:a}),g.terminate())}),this._ended("local",null,i),this._dialog=g,this._ua.newDialog(g)}else console.log("here it is"),this.sendRequest(F.BYE,{extraHeaders:l,body:a}),this._ended("local",null,i)}}sendRequest(s,i){return this._dialog.sendRequest(s,i)}authenticate(s){this.status="auth";let i=new sr("");i.method="AUTH",i.addHeader("To-Path",`msrp://${this._ua._configuration.realm}:2856;ws`),i.addHeader("From-Path",`msrp://${this.credentials.username}.${this.credentials.realm}:2856/${this.auth_id};ws`),s&&i.addHeader("Authorization",s.toString());let l=i.toString();console.log(l);let a=[];for(var _=0;_<l.length;_++)a.push(l.charCodeAt(_).toString(16));console.log(a),this._connection.send(i.toString())}onmessage(s){console.log("onmessage",s);const i=new sr(s.data);if(this.status==="auth"&&i.code===401){const l=this.parseAuth(i.getHeader("WWW-Authenticate")),a=new Gm(this.credentials);a.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},l,$e.createRandomToken(12)),this.authenticate(a)}this.status==="auth"&&i.code===200&&this._direction==="outgoing"?(this.my_addr.push(i.getHeader("To-Path")),this.my_addr.push(i.getHeader("Use-Path")),this.status="active",this.inviteParty(i)):this.status==="auth"&&i.code===200&&this._direction==="incoming"?(this.my_addr.push(i.getHeader("To-Path")),this.my_addr.push(i.getHeader("Use-Path")),this.status="active",this.acceptParty(i),this.emit("confirmed")):i.method==="SEND"&&(this._sendOk(i),this._sendReport(i),i.direction="incoming",this.emit("newMessage",i),this._msgHistory.push(i),this.emit("msgHistoryUpdate",this._msgHistory),console.log("======================================================================")),i.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=i=>{if(!i||!i.candidate||!i.candidate.candidate)return;const l=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,a=i.candidate.candidate.match(l);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(F.ACK);return}else{const i=new aa(this,s,"UAC");if(i.error!==void 0){console.log(i.error);return}this.sendRequest(F.ACK),this.sendRequest(F.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!==be.STATUS_INVITE_SENT&&this._status!==be.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(s.status_code):this._status=be.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=be.STATUS_1XX_RECEIVED,!s.body){this._progress("remote",s);break}const i={originator:"remote",type:"answer",sdp:s.body};console.log('emit "sdp"'),this.emit("sdp",i);const l=new RTCSessionDescription({type:"answer",sdp:i.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(l)).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=be.STATUS_CONFIRMED,!s.body){this._acceptAndTerminate(s,400,F.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",s,F.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(s,"UAC"))break;const i={originator:"remote",type:"answer",sdp:s.body};console.log('emit "sdp"'),this.emit("sdp",i),new RTCSessionDescription({type:"answer",sdp:i.sdp}),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(l=>this._connection.setLocalDescription(l)).catch(l=>{this._acceptAndTerminate(s,500,l.toString()),console.log("failed 4"),this._failed("local",s,F.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(s),this._accepted("remote",s),this.sendRequest(F.ACK),this._confirmed("local",null)});break}default:{const i=$e.sipErrorCause(s.status_code);console.log("failed 5"),this._failed("remote",s,i)}}}sendMSRP(s){const i=new sr("");i.method="SEND",i.addHeader("To-Path",`${this.my_addr[1]} ${this.target_addr[1]} ${this.target_addr[0]}`),i.addHeader("From-Path",`${this.my_addr[0]}`),i.addHeader("Message-ID",$e.createRandomToken(10)),i.addHeader("Byte-Range","1-25/25"),i.addHeader("Content-Type","text/plain"),i.addHeader("Success-Report","yes"),i.addHeader("Failure-Report","yes"),i.body=s;let l=i.toString();console.log(l);let a=[];for(var _=0;_<l.length;_++)a.push(l.charCodeAt(_).toString(16));console.log(a),this._connection.send(i.toString()),i.direction="outgoing",this.emit("newMessage",i),this._msgHistory.push(i),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(s){let i=s.ident,l=s.getHeader("Message-ID"),a=new sr("");a.method="200 OK",a.addHeader("To-Path",`${this.my_addr[1]}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",l),a.ident=i;let _=a.toString();console.log(_);let e=[];for(var p=0;p<_.length;p++)e.push(_.charCodeAt(p).toString(16));console.log(e),this._connection.send(a.toString())}_sendReport(s){let i=s.ident,l=s.getHeader("Message-ID"),a=new sr("");a.method="REPORT",a.addHeader("To-Path",`${s.getHeader("From-Path")}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",l),a.addHeader("Byte-Range","1-25/25"),a.addHeader("Status","000 200 OK"),a.ident=i;let _=a.toString();console.log(_);let e=[];for(var p=0;p<_.length;p++)e.push(_.charCodeAt(p).toString(16));console.log(e),this._connection.send(a.toString())}parseAuth(s){const i={},l=s.replace("Digest","").split(",");for(const a of l){const _=a.trim().split("=");i[_[0]]=_[1].match('^"(.+)"$')[1]}return i}init_incoming(s,i){let l;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=be.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")&&(l=s.getHeader("expires")*1e3),s.to_tag=$e.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=be.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{s.reply(408),console.log("failed 6"),this._failed("local",null,F.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),l&&(this._timers.expiresTimer=setTimeout(()=>{this._status===be.STATUS_WAITING_FOR_ANSWER&&(s.reply(487),console.log("failed 7"),this._failed("system",null,F.causes.EXPIRES))},l)),this._direction="incoming",this._local_identity=s.to,this._remote_identity=s.from,i&&i(this),s.parseSDP(!0),this.target_addr=s.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",s),this._status!==be.STATUS_TERMINATED&&(s.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(s,i,l){this.emit("_failed",{originator:s,message:i||null,cause:l}),this._close(),this.emit("failed",{originator:s,message:i||null,cause:l})}_close(){if(console.log("CLOSE SESSION"),this._status!==be.STATUS_TERMINATED){if(this._status=be.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,i,l){const a=i==="UAS"?s.to_tag:s.from_tag,_=i==="UAS"?s.from_tag:s.to_tag,e=s.call_id+a+_;let p=this._earlyDialogs[e];if(l)return p?!0:(p=new aa(this,s,i,aa.C.STATUS_EARLY),p.error?(console.log("failed 8"),this._failed("remote",s,F.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[e]=p,!0));{if(this._from_tag=s.from_tag,this._to_tag=s.to_tag,p)return p.update(s,i),this._dialog=p,delete this._earlyDialogs[e],!0;const g=new aa(this,s,i);return g.error?(console.log("failed 9"),this._failed("remote",s,F.causes.INTERNAL_ERROR),!1):(this._dialog=g,!0)}}_newMSRPSession(s,i){this._ua.newMSRPSession(this,{originator:s,session:this,request:i})}_progress(s,i){this.emit("progress",{originator:s,response:i||null})}isEnded(){switch(this._status){case be.STATUS_CANCELED:case be.STATUS_TERMINATED:return!0;default:return!1}}_accepted(s,i){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:s,response:i||null})}_confirmed(s,i){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:s,ack:i||null})}_ended(s,i,l){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:s,message:i||null,cause:l})}_handleSessionTimersInIncomingResponse(s){if(!this._sessionTimers.enabled)return;let i;s.session_expires&&s.session_expires>=F.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=s.session_expires,i=s.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,i="uac"),this._sessionTimers.refresher=i==="uac",this._runSessionTimer()}receiveRequest(s){if(console.log("receiveRequest()"),s.method===F.CANCEL)(this._status===be.STATUS_WAITING_FOR_ANSWER||this._status===be.STATUS_ANSWERED)&&(this._status=be.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",s,F.causes.CANCELED));else switch(s.method){case F.ACK:if(this._status!==be.STATUS_WAITING_FOR_ACK)return;if(this._status=be.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!s.body){this.terminate({cause:F.causes.MISSING_SDP,status_code:400});break}const i={originator:"remote",type:"answer",sdp:s.body};console.log('emit "sdp"'),this.emit("sdp",i);const l=new RTCSessionDescription({type:"answer",sdp:i.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(l)).then(()=>{this._is_confirmed||this._confirmed("remote",s)}).catch(a=>{this.terminate({cause:F.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 F.BYE:this._status===be.STATUS_CONFIRMED||this._status===be.STATUS_WAITING_FOR_ACK?(s.reply(200),this._ended("remote",s,F.causes.BYE)):this._status===be.STATUS_INVITE_RECEIVED||this._status===be.STATUS_WAITING_FOR_ANSWER?(s.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",s,F.causes.BYE)):s.reply(403,"Wrong Status");break;case F.INVITE:this._status===be.STATUS_CONFIRMED?s.hasHeader("replaces")?this._receiveReplaces(s):this._receiveReinvite(s):s.reply(403,"Wrong Status");break;case F.INFO:this._status===be.STATUS_1XX_RECEIVED||this._status===be.STATUS_WAITING_FOR_ANSWER||this._status===be.STATUS_ANSWERED||this._status===be.STATUS_WAITING_FOR_ACK||this._status===be.STATUS_CONFIRMED?(s.hasHeader("Content-Type")?s.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new yu(this).init_incoming(s):s.reply(415):s.reply(403,"Wrong Status");break;case F.UPDATE:this._status===be.STATUS_CONFIRMED?this._receiveUpdate(s):s.reply(403,"Wrong Status");break;case F.REFER:this._status===be.STATUS_CONFIRMED?this._receiveRefer(s):s.reply(403,"Wrong Status");break;case F.NOTIFY:this._status===be.STATUS_CONFIRMED?this._receiveNotify(s):s.reply(403,"Wrong Status");break;default:s.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==be.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:F.causes.CONNECTION_ERROR,cause:F.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==be.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:F.causes.REQUEST_TIMEOUT,cause:F.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==be.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:F.causes.DIALOG_ERROR,cause:F.causes.DIALOG_ERROR})}}var xT=Qt();const Iu=tt(xT),Ta=new Za("Parser"),MT=(c,s)=>{let i,l,a=c.indexOf(`\r
|
157
157
|
`);if(a===-1){Ta.warn("parseMessage() | no CRLF found, not a SIP message");return}const _=c.substring(0,a);let e=Iu.parse(_,"Request_Response");if(e===-1){Ta.warn(`parseMessage() | error parsing first line of SIP message: "${_}"`);return}else e.status_code?(i=new Dn.IncomingResponse,i.status_code=e.status_code,i.reason_phrase=e.reason_phrase):(i=new Dn.IncomingRequest(s),i.method=e.method,i.ruri=e.uri);i.data=c;let p=a+2;for(;;){if(a=kT(c,p),a===-2){l=p+2;break}else if(a===-1){Ta.warn("parseMessage() | malformed message");return}if(e=LT(i,c,p,a),e!==!0){Ta.warn("parseMessage() |",e.error);return}p=a+2}if(i.hasHeader("content-length")){const g=i.getHeader("content-length");i.body=c.substr(l,g)}else i.body=c.substring(l);return i};function kT(c,s){let i=s,l=0,a=0;if(c.substring(i,i+2).match(/(^\r\n)/))return-2;for(;l===0;){if(a=c.indexOf(`\r
|
158
|
-
`,i),a===-1)return a;!c.substring(a+2,a+4).match(/(^\r\n)/)&&c.charAt(a+2).match(/(^\s+)/)?i=a+2:l=a}return l}function LT(c,s,i,l){let a;const _=s.indexOf(":",i),e=s.substring(i,_).trim(),p=s.substring(_+1,l).trim();switch(e.toLowerCase()){case"via":case"v":c.addHeader("via",p),c.getHeaders("via").length===1?(a=c.parseHeader("Via"),a&&(c.via=a,c.via_branch=a.branch)):a=0;break;case"from":case"f":c.setHeader("from",p),a=c.parseHeader("from"),a&&(c.from=a,c.from_tag=a.getParam("tag"));break;case"to":case"t":c.setHeader("to",p),a=c.parseHeader("to"),a&&(c.to=a,c.to_tag=a.getParam("tag"));break;case"record-route":if(a=Iu.parse(p,"Record_Route"),a===-1)a=void 0;else for(const g of a)c.addHeader("record-route",p.substring(g.possition,g.offset)),c.headers["Record-Route"][c.getHeaders("record-route").length-1].parsed=g.parsed;break;case"call-id":case"i":c.setHeader("call-id",p),a=c.parseHeader("call-id"),a&&(c.call_id=p);break;case"contact":case"m":if(a=Iu.parse(p,"Contact"),a===-1)a=void 0;else for(const g of a)c.addHeader("contact",p.substring(g.possition,g.offset)),c.headers.Contact[c.getHeaders("contact").length-1].parsed=g.parsed;break;case"content-length":case"l":c.setHeader("content-length",p),a=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",p),a=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",p),a=c.parseHeader("cseq"),a&&(c.cseq=a.value),c instanceof Dn.IncomingResponse&&(c.method=a.method);break;case"max-forwards":c.setHeader("max-forwards",p),a=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",p),a=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",p),a=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",p),a=c.parseHeader("session-expires"),a&&(c.session_expires=a.expires,c.session_expires_refresher=a.refresher);break;case"refer-to":case"r":c.setHeader("refer-to",p),a=c.parseHeader("refer-to"),a&&(c.refer_to=a);break;case"replaces":c.setHeader("replaces",p),a=c.parseHeader("replaces"),a&&(c.replaces=a);break;case"event":case"o":c.setHeader("event",p),a=c.parseHeader("event"),a&&(c.event=a);break;default:c.addHeader(e,p),a=0}return a===void 0?{error:`error parsing header "${e}"`}:!0}const $T={parseMessage:MT},Vi=new Za("Registrator"),va=10;class HT{constructor(s,i){this._reg_id=1,this._ua=s,this._transport=i,this._registrar=s.configuration.registrar_server,this._expires=s.configuration.register_expires,this._call_id=ys.createRandomToken(22),this._cseq=0,this._to_uri=s.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const l=this._contact.indexOf(">");if(l!==-1){const a=this._contact.slice(0,l)+this._contact.slice(l+1,this._contact.length);this._contact=a}this._extra_contact="",this._extraContactParams="",this._extra_contact+=";+sip.ice",this._extraHeaders=[],this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._extra_contact+=`;reg-id=${this._reg_id}`,this._extra_contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(s){Array.isArray(s)||(s=[]),this._extraHeaders=s.slice()}setExtraContactParams(s){s instanceof Object||(s={}),this._extraContactParams="";for(const i in s)if(Object.prototype.hasOwnProperty.call(s,i)){const l=s[i];this._extraContactParams+=`;${i}`,l&&(this._extraContactParams+=`=${l}`)}}setExtraContactUriParams(s){s instanceof Object||(s={}),this._extraContactParams="";for(const i in s)if(Object.prototype.hasOwnProperty.call(s,i)){const l=s[i];this._extraContactParams+=`;${i}`,l&&(this._extraContactParams+=`=${l}`)}}register(){if(this._registering){Vi.debug("Register request in progress...");return}const s=this._extraHeaders.slice();s.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),s.push(`Expires: ${this._expires}`);const i=new Dt.OutgoingRequest(F.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},s),l=new Ga(this._ua,i,{onRequestTimeout:()=>{this._registrationFailure(null,F.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,F.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:a=>{if(a.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):{if(this._registering=!1,!a.hasHeader("Contact")){Vi.debug("no Contact header in response to REGISTER, response ignored");break}const _=a.headers.Contact.reduce((n,v)=>n.concat(v.parsed),[]);let e=_.find(n=>this._sipInstance===n.getParam("+sip.instance")&&this._reg_id===parseInt(n.getParam("reg-id")));if(e||(e=_.find(n=>n.uri.user===this._ua.contact.uri.user)),!e){Vi.debug("no Contact header pointing to us, response ignored");break}let p=e.getParam("expires");!p&&a.hasHeader("expires")&&(p=a.getHeader("expires")),p||(p=this._expires),p=Number(p),p<va&&(p=va);const g=p>64?p*1e3/2+Math.floor((p/2-32)*1e3*Math.random()):p*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},g),e.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=e.getParam("temp-gruu").replace(/"/g,"")),e.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=e.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:a}));break}case/^423$/.test(a.status_code):{a.hasHeader("min-expires")?(this._expires=Number(a.getHeader("min-expires")),this._expires<va&&(this._expires=va),this.register()):(Vi.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(a,F.causes.SIP_FAILURE_CODE));break}default:{const _=ys.sipErrorCause(a.status_code);this._registrationFailure(a,_)}}}});this._registering=!0,l.send()}unregister(s={}){if(!this._registered){Vi.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const i=this._extraHeaders.slice();s.all?i.push(`Contact: *${this._extraContactParams}`):i.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),i.push("Expires: 0");const l=new Dt.OutgoingRequest(F.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},i);new Ga(this._ua,l,{onRequestTimeout:()=>{this._unregistered(null,F.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,F.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:_=>{switch(!0){case/^1[0-9]{2}$/.test(_.status_code):break;case/^2[0-9]{2}$/.test(_.status_code):this._unregistered(_);break;default:{const e=ys.sipErrorCause(_.status_code);this._unregistered(_,e)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(s,i){this._registering=!1,this._ua.registrationFailed({response:s||null,cause:i}),this._registered&&(this._registered=!1,this._ua.unregistered({response:s||null,cause:i}))}_unregistered(s,i){this._registering=!1,this._registered=!1,this._ua.unregistered({response:s||null,cause:i||null})}}const ft=console,Xs={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},FT=IT;class jT extends FT{constructor(s){super(s),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this._registrator=new HT(this)}call(s,i){return super.call(s,i)}joinVideoCall(s,i,l){ft.debug("call()");const a=new Wa(this);return a.connect(s,i,l),a}_loadConfig(s){try{el.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=ys.newUUID()),this._configuration.jssip_id=ys.createRandomToken(5);const i=this._configuration.uri.clone();i.user=null,this._configuration.hostport_params=i.toString().replace(/^sip:/i,"");try{this._transport=new Qg(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=qT.bind(this),this._transport.onconnect=VT.bind(this),this._transport.ondisconnect=BT.bind(this),this._transport.ondata=GT.bind(this)}catch(a){throw ft.warn(a),new zs.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 ar("sip",ys.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 _=a.anonymous||null,e=a.outbound||null;let p="<";return _?p+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":p+=this.pub_gruu||this.uri.toString(),e&&(_?!this.temp_gruu:!this.pub_gruu)&&(p+=";ob"),p+=">",p}};const l=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const a in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,a)&&(l.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(el.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,i){s.on("msgHistoryUpdate",l=>{console.log(l)}),this._msrp_sessions[s.id]=s,this.emit("newMSRPSession",i)}newJanusSession(s,i){this._janus_sessions[s.id]=s,this.emit("newJanusSession",i)}destroyMSRPSession(s){delete this._msrp_sessions[s.id]}destroyJanusSession(s){delete this._janus_sessions[s.id]}receiveRequest(s){var _,e,p,g;const i=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!==Me.ACK&&s.reply_sl(404);return}if(s.ruri.scheme===Me.SIPS){s.reply_sl(416);return}if(Vt.checkTransaction(this,s))return;if(i===Me.INVITE?new Vt.InviteServerTransaction(this,this._transport,s):i!==Me.ACK&&i!==Me.CANCEL&&new Vt.NonInviteServerTransaction(this,this._transport,s),i===Me.OPTIONS){if(this.listeners("newOptions").length===0){s.reply(200);return}new Qc.Options(this).init_incoming(s)}else if(i===Me.MESSAGE){if(this.listeners("newMessage").length===0){s.reply(405);return}new Qc.Message(this).init_incoming(s)}else if(i===Me.INVITE&&!s.to_tag&&this.listeners("newRTCSession").length===0){s.reply(405);return}let l,a;if(s.to_tag)if(l=this._findDialog(s.call_id,s.from_tag,s.to_tag),l)l.receiveRequest(s);else if(i===Me.NOTIFY)if(a=this._findSession(s),a)a.receiveRequest(s);else{if(s.body)try{const n=JSON.parse(s.body)||{};(e=(_=n.plugindata)==null?void 0:_.data)!=null&&e.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(n),(g=(p=n.plugindata)==null?void 0:p.data)!=null&&g.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(n.plugindata.data.unpublished)}catch(n){console.error(n)}s.reply(200)}else i!==Me.ACK&&s.reply(481);else switch(i){case Me.INVITE:if(window.RTCPeerConnection)if(s.hasHeader("replaces")){const n=s.replaces;l=this._findDialog(n.call_id,n.from_tag,n.to_tag),l?(a=l.owner,a.isEnded()?s.reply(603):a.receiveRequest(s)):s.reply(481)}else s.body.search(/MSRP/ig)>-1?(a=new nu(this),a.init_incoming(s)):s.body.search(/JANUS/ig)>-1||(a=new kg(this),a.init_incoming(s));else ft.warn("INVITE received but WebRTC is not supported"),s.reply(488);break;case Me.BYE:s.reply(481);break;case Me.CANCEL:a=this._findSession(s),a?a.receiveRequest(s):ft.debug("received CANCEL request for a non existent session");break;case Me.ACK:break;case Me.NOTIFY:this.emit("sipEvent",{event:s.event,request:s}),s.reply(200);break;default:s.reply(405);break}}startMSRP(s,i){ft.debug("startMSRP()",i);const l=new nu(this);return l.connect(s),l}startJanus(s,i){ft.debug("startJanus()",i);const l=new nu(this);return l.connect(s),l}terminateMSRPSessions(s){ft.debug("terminateSessions()");for(const i in this._msrp_sessions)this._msrp_sessions[i].isEnded()||this._msrp_sessions[i].terminate(s)}terminateJanusSessions(s){ft.debug("terminateSessions()");for(const i in this._janus_sessions)this._janus_sessions[i].isEnded()||this._janus_sessions[i].terminate(s)}stop(){if(ft.debug("stop()"),this._dynConfiguration={},this._status===Xs.STATUS_USER_CLOSED){ft.debug("UA already closed");return}this._registrator.close();const s=Object.keys(this._sessions).length;for(const l in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,l)){ft.debug(`closing session ${l}`);try{this._sessions[l].terminate()}catch(a){console.error(a)}}for(const l in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,l)){ft.debug(`closing session ${l}`);try{this._msrp_sessions[l].terminate()}catch(a){console.error(a)}}for(const l in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,l)){ft.debug(`closing session ${l}`);try{this._janus_sessions[l].terminate()}catch(a){console.error(a)}}for(const l in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,l))try{this._applicants[l].close()}catch(a){console.error(a)}this._status=Xs.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 qT(c){this.emit("connecting",c)}function VT(c){this._status!==Xs.STATUS_USER_CLOSED&&(this._status=Xs.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function BT(c){const s=["nict","ict","nist","ist"];for(const i of s)for(const l in this._transactions[i])Object.prototype.hasOwnProperty.call(this._transactions[i],l)&&this._transactions[i][l].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==Xs.STATUS_USER_CLOSED&&(this._status=Xs.STATUS_NOT_READY,this._error=Xs.NETWORK_ERROR)}function GT(c){console.log("onTransportData",c);const s=c.transport;let i=c.message;if(i=$T.parseMessage(i,this),!i){console.log("if 1 return");return}if(this._status===Xs.STATUS_USER_CLOSED&&i instanceof Dn.IncomingRequest){console.log("if 2 return");return}if(!hT(i,this,s)){console.log("if 3 return");return}if(console.log("onTransportData message",i),console.log("onTransportData instanceof",i instanceof Dn.IncomingRequest),i instanceof Dn.IncomingRequest)i.transport=s,console.log("onTransportData receiveRequest"),this.receiveRequest(i);else if(i instanceof Dn.IncomingResponse){let l;switch(i.method){case Me.INVITE:l=this._transactions.ict[i.via_branch],l&&l.receiveResponse(i);break;case Me.ACK:break;default:l=this._transactions.nict[i.via_branch],l&&l.receiveResponse(i);break}}}const WT=["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"],KT=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function Uf(c){const s={};return WT.forEach(i=>{c[i]!==void 0&&(s[i]=c[i])}),s.localHold=c._localHold,s}function Pf(c){const s={};return KT.forEach(i=>{c[i]!==void 0&&(s[i]=c[i])}),s}function xf(c,s){const i=new AudioContext,l=i.createMediaStreamSource(c),a=i.createMediaStreamDestination(),_=i.createGain();return l.connect(_),_.connect(a),_.gain.value=s,a.stream}function YT(c,s,i,l){const a=document.createElement("audio");a.id=s._id,a.className="audioTag",a.srcObject=c,O_()||(a.setSinkId(i),a.volume=l),a.play(),s.audioTag=a}function JT(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}function O_(){return/Mobi|Android|iPhone/i.test(navigator.userAgent)}const zT=ut,XT=Qt(),Pt=new zT("WebSocketInterface");var QT=class{constructor(s){Pt.debug('new() [url:"%s"]',s),this._url=s,this._sip_uri=null,this._via_transport=null,this._ws=null;const i=XT.parse(s,"absoluteURI");if(i===-1)throw Pt.warn(`invalid WebSocket URI: ${s}`),new TypeError(`Invalid argument: ${s}`);if(i.scheme!=="wss"&&i.scheme!=="ws")throw Pt.warn(`invalid WebSocket URI scheme: ${i.scheme}`),new TypeError(`Invalid argument: ${s}`);this._sip_uri=`sip:${i.host}${i.port?`:${i.port}`:""};transport=ws`,this._via_transport=i.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(Pt.debug("connect()"),this.isConnected()){Pt.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Pt.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Pt.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(){Pt.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 Pt.debug("send()"),this.isConnected()?(this._ws.send(s),!0):(Pt.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(){Pt.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:s,code:i,reason:l}){Pt.debug(`WebSocket ${this._url} closed`),s===!1&&Pt.debug("WebSocket abrupt disconnection"),this.ondisconnect(!s,i,l)}_onMessage({data:s}){Pt.debug("received WebSocket message"),this.ondata(s)}_onError(s){Pt.warn(`WebSocket ${this._url} error: `,s)}};const bu=Ka,ZT=Me,ev=bs,tv=Ct(),sv=w_,nv=Is(),rv=$u(),iv=Qt(),lv=QT,av=ur("JsSIP");av("version %s",bu.version);var ov={C:ZT,Exceptions:ev,Utils:tv,UA:sv,URI:nv,NameAddrHeader:rv,WebSocketInterface:lv,Grammar:iv,debug:ur,get name(){return bu.title},get version(){return bu.version}};const uv=tt(ov);function ru(c){return c<10?`0${c}`:`${c}`}function cv(c){let s=c.hours||0,i=c.minutes||0,l=c.seconds||0;l++,l===60&&(l=0,i++,i===60&&(i=0,s++));const a=`${ru(s)}:${ru(i)}:${ru(l)}`;return{seconds:l,minutes:i,hours:s,formatted:a}}var Rt={};Rt.forEach=async(c,s,i)=>{const l=[];for(let a=0;a<c.length;a++)if(a in c){const _=Promise.resolve(c[a]).then(e=>s.call(i||globalThis,e,a,c));l.push(_)}await Promise.all(l)};Rt.forEachSeries=async(c,s,i)=>{for(let l=0;l<c.length;l++)l in c&&await s.call(i||globalThis,await c[l],l,c)};Rt.map=async(c,s,i)=>{const l=[];for(let a=0;a<c.length;a++)a in c&&(l[a]=Promise.resolve(c[a]).then(_=>s.call(i||globalThis,_,a,c)));return Promise.all(l)};Rt.mapSeries=async(c,s,i)=>{const l=[];for(let a=0;a<c.length;a++)a in c&&(l[a]=await s.call(i||globalThis,await c[a],a,c));return l};Rt.find=(c,s,i)=>new Promise((l,a)=>{if(c.length===0)return l();let _=1;for(let e=0;e<c.length;e++){const p=g=>{g?l(c[e]):_===c.length&&l(),_++};Promise.resolve(c[e]).then(g=>s.call(i||globalThis,g,e,c)).then(p).catch(a)}});Rt.findSeries=async(c,s,i)=>{for(let l=0;l<c.length;l++)if(await s.call(i||globalThis,await c[l],l,c))return c[l]};Rt.findIndex=(c,s,i)=>new Promise((l,a)=>{if(c.length===0)return l(-1);let _=1;for(let e=0;e<c.length;e++){const p=g=>{g?l(e):_===c.length&&l(-1),_++};Promise.resolve(c[e]).then(g=>s.call(i||globalThis,g,e,c)).then(p).catch(a)}});Rt.findIndexSeries=async(c,s,i)=>{for(let l=0;l<c.length;l++)if(await s.call(i||globalThis,await c[l],l,c))return l};Rt.some=(c,s,i)=>new Promise((l,a)=>{if(c.length===0)return l(!1);let _=1;for(let e=0;e<c.length;e++){if(!(e in c)){_++;continue}const p=g=>{g?l(!0):_===c.length&&l(!1),_++};Promise.resolve(c[e]).then(g=>s.call(i||globalThis,g,e,c)).then(p).catch(a)}});Rt.someSeries=async(c,s,i)=>{for(let l=0;l<c.length;l++)if(l in c&&await s.call(i||globalThis,await c[l],l,c))return!0;return!1};Rt.every=(c,s,i)=>new Promise((l,a)=>{if(c.length===0)return l(!0);let _=1;for(let e=0;e<c.length;e++){if(!(e in c)){_++;continue}const p=g=>{g?_===c.length&&l(!0):l(!1),_++};Promise.resolve(c[e]).then(g=>s.call(i||globalThis,g,e,c)).then(p).catch(a)}});Rt.everySeries=async(c,s,i)=>{for(let l=0;l<c.length;l++)if(l in c&&!await s.call(i||globalThis,await c[l],l,c))return!1;return!0};Rt.filter=(c,s,i)=>new Promise(async(l,a)=>{const _=[];for(let p=0;p<c.length;p++)p in c&&(_[p]=Promise.resolve(c[p]).then(g=>s.call(i||globalThis,g,p,c)).catch(a));const e=[];for(let p=0;p<_.length;p++)await _[p]&&e.push(await c[p]);l(e)});Rt.filterSeries=async(c,s,i)=>{const l=[];for(let a=0;a<c.length;a++)a in c&&await s.call(i||globalThis,await c[a],a,c)&&l.push(await c[a]);return l};Rt.reduce=async(c,s,i)=>{if(c.length===0&&i===void 0)throw TypeError("Reduce of empty array with no initial value");let l,a;for(i!==void 0?(a=i,l=0):(a=c[0],l=1),l;l<c.length;l++)l in c&&(a=await s(await a,await c[l],l,c));return a};var D_={};(function(c){const s=Rt;Object.keys(s).forEach(i=>{const l=i.charAt(0).toUpperCase()+i.slice(1);c[`async${l}`]=async function(...a){return s[i](this,...a)}})})(D_);const fv=Rt,_v=D_;var hv=Object.assign(fv,{instanceMethods:_v});const Un=new AudioContext,Xt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var dv={exports:{}};(function(c){var s=function(i){var l=Object.prototype,a=l.hasOwnProperty,_=Object.defineProperty||function(N,Y,re){N[Y]=re.value},e,p=typeof Symbol=="function"?Symbol:{},g=p.iterator||"@@iterator",n=p.asyncIterator||"@@asyncIterator",v=p.toStringTag||"@@toStringTag";function S(N,Y,re){return Object.defineProperty(N,Y,{value:re,enumerable:!0,configurable:!0,writable:!0}),N[Y]}try{S({},"")}catch{S=function(Y,re,ae){return Y[re]=ae}}function m(N,Y,re,ae){var Te=Y&&Y.prototype instanceof oe?Y:oe,De=Object.create(Te.prototype),Ce=new U(ae||[]);return _(De,"_invoke",{value:j(N,re,Ce)}),De}i.wrap=m;function C(N,Y,re){try{return{type:"normal",arg:N.call(Y,re)}}catch(ae){return{type:"throw",arg:ae}}}var A="suspendedStart",R="suspendedYield",I="executing",V="completed",W={};function oe(){}function x(){}function $(){}var Re={};S(Re,g,function(){return this});var Ie=Object.getPrototypeOf,H=Ie&&Ie(Ie(se([])));H&&H!==l&&a.call(H,g)&&(Re=H);var D=$.prototype=oe.prototype=Object.create(Re);x.prototype=$,_(D,"constructor",{value:$,configurable:!0}),_($,"constructor",{value:x,configurable:!0}),x.displayName=S($,v,"GeneratorFunction");function L(N){["next","throw","return"].forEach(function(Y){S(N,Y,function(re){return this._invoke(Y,re)})})}i.isGeneratorFunction=function(N){var Y=typeof N=="function"&&N.constructor;return Y?Y===x||(Y.displayName||Y.name)==="GeneratorFunction":!1},i.mark=function(N){return Object.setPrototypeOf?Object.setPrototypeOf(N,$):(N.__proto__=$,S(N,v,"GeneratorFunction")),N.prototype=Object.create(D),N},i.awrap=function(N){return{__await:N}};function q(N,Y){function re(De,Ce,Le,we){var Se=C(N[De],N,Ce);if(Se.type==="throw")we(Se.arg);else{var it=Se.arg,Ue=it.value;return Ue&&typeof Ue=="object"&&a.call(Ue,"__await")?Y.resolve(Ue.__await).then(function(le){re("next",le,Le,we)},function(le){re("throw",le,Le,we)}):Y.resolve(Ue).then(function(le){it.value=le,Le(it)},function(le){return re("throw",le,Le,we)})}}var ae;function Te(De,Ce){function Le(){return new Y(function(we,Se){re(De,Ce,we,Se)})}return ae=ae?ae.then(Le,Le):Le()}_(this,"_invoke",{value:Te})}L(q.prototype),S(q.prototype,n,function(){return this}),i.AsyncIterator=q,i.async=function(N,Y,re,ae,Te){Te===void 0&&(Te=Promise);var De=new q(m(N,Y,re,ae),Te);return i.isGeneratorFunction(Y)?De:De.next().then(function(Ce){return Ce.done?Ce.value:De.next()})};function j(N,Y,re){var ae=A;return function(De,Ce){if(ae===I)throw new Error("Generator is already running");if(ae===V){if(De==="throw")throw Ce;return It()}for(re.method=De,re.arg=Ce;;){var Le=re.delegate;if(Le){var we=B(Le,re);if(we){if(we===W)continue;return we}}if(re.method==="next")re.sent=re._sent=re.arg;else if(re.method==="throw"){if(ae===A)throw ae=V,re.arg;re.dispatchException(re.arg)}else re.method==="return"&&re.abrupt("return",re.arg);ae=I;var Se=C(N,Y,re);if(Se.type==="normal"){if(ae=re.done?V:R,Se.arg===W)continue;return{value:Se.arg,done:re.done}}else Se.type==="throw"&&(ae=V,re.method="throw",re.arg=Se.arg)}}}function B(N,Y){var re=Y.method,ae=N.iterator[re];if(ae===e)return Y.delegate=null,re==="throw"&&N.iterator.return&&(Y.method="return",Y.arg=e,B(N,Y),Y.method==="throw")||re!=="return"&&(Y.method="throw",Y.arg=new TypeError("The iterator does not provide a '"+re+"' method")),W;var Te=C(ae,N.iterator,Y.arg);if(Te.type==="throw")return Y.method="throw",Y.arg=Te.arg,Y.delegate=null,W;var De=Te.arg;if(!De)return Y.method="throw",Y.arg=new TypeError("iterator result is not an object"),Y.delegate=null,W;if(De.done)Y[N.resultName]=De.value,Y.next=N.nextLoc,Y.method!=="return"&&(Y.method="next",Y.arg=e);else return De;return Y.delegate=null,W}L(D),S(D,v,"Generator"),S(D,g,function(){return this}),S(D,"toString",function(){return"[object Generator]"});function X(N){var Y={tryLoc:N[0]};1 in N&&(Y.catchLoc=N[1]),2 in N&&(Y.finallyLoc=N[2],Y.afterLoc=N[3]),this.tryEntries.push(Y)}function Q(N){var Y=N.completion||{};Y.type="normal",delete Y.arg,N.completion=Y}function U(N){this.tryEntries=[{tryLoc:"root"}],N.forEach(X,this),this.reset(!0)}i.keys=function(N){var Y=Object(N),re=[];for(var ae in Y)re.push(ae);return re.reverse(),function Te(){for(;re.length;){var De=re.pop();if(De in Y)return Te.value=De,Te.done=!1,Te}return Te.done=!0,Te}};function se(N){if(N){var Y=N[g];if(Y)return Y.call(N);if(typeof N.next=="function")return N;if(!isNaN(N.length)){var re=-1,ae=function Te(){for(;++re<N.length;)if(a.call(N,re))return Te.value=N[re],Te.done=!1,Te;return Te.value=e,Te.done=!0,Te};return ae.next=ae}}return{next:It}}i.values=se;function It(){return{value:e,done:!0}}return U.prototype={constructor:U,reset:function(N){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method="next",this.arg=e,this.tryEntries.forEach(Q),!N)for(var Y in this)Y.charAt(0)==="t"&&a.call(this,Y)&&!isNaN(+Y.slice(1))&&(this[Y]=e)},stop:function(){this.done=!0;var N=this.tryEntries[0],Y=N.completion;if(Y.type==="throw")throw Y.arg;return this.rval},dispatchException:function(N){if(this.done)throw N;var Y=this;function re(we,Se){return De.type="throw",De.arg=N,Y.next=we,Se&&(Y.method="next",Y.arg=e),!!Se}for(var ae=this.tryEntries.length-1;ae>=0;--ae){var Te=this.tryEntries[ae],De=Te.completion;if(Te.tryLoc==="root")return re("end");if(Te.tryLoc<=this.prev){var Ce=a.call(Te,"catchLoc"),Le=a.call(Te,"finallyLoc");if(Ce&&Le){if(this.prev<Te.catchLoc)return re(Te.catchLoc,!0);if(this.prev<Te.finallyLoc)return re(Te.finallyLoc)}else if(Ce){if(this.prev<Te.catchLoc)return re(Te.catchLoc,!0)}else if(Le){if(this.prev<Te.finallyLoc)return re(Te.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(N,Y){for(var re=this.tryEntries.length-1;re>=0;--re){var ae=this.tryEntries[re];if(ae.tryLoc<=this.prev&&a.call(ae,"finallyLoc")&&this.prev<ae.finallyLoc){var Te=ae;break}}Te&&(N==="break"||N==="continue")&&Te.tryLoc<=Y&&Y<=Te.finallyLoc&&(Te=null);var De=Te?Te.completion:{};return De.type=N,De.arg=Y,Te?(this.method="next",this.next=Te.finallyLoc,W):this.complete(De)},complete:function(N,Y){if(N.type==="throw")throw N.arg;return N.type==="break"||N.type==="continue"?this.next=N.arg:N.type==="return"?(this.rval=this.arg=N.arg,this.method="return",this.next="end"):N.type==="normal"&&Y&&(this.next=Y),W},finish:function(N){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var re=this.tryEntries[Y];if(re.finallyLoc===N)return this.complete(re.completion,re.afterLoc),Q(re),W}},catch:function(N){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var re=this.tryEntries[Y];if(re.tryLoc===N){var ae=re.completion;if(ae.type==="throw"){var Te=ae.arg;Q(re)}return Te}}throw new Error("illegal catch attempt")},delegateYield:function(N,Y,re){return this.delegate={iterator:se(N),resultName:Y,nextLoc:re},this.method==="next"&&(this.arg=e),W}},i}(c.exports);try{regeneratorRuntime=s}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=s:Function("r","regeneratorRuntime = r")(s)}})(dv);var N_={exports:{}};(function(c){(function(s,i){c.exports?c.exports=i():s.log=i()})(H_,function(){var s=function(){},i="undefined",l=typeof window!==i&&typeof window.navigator!==i&&/Trident\/|MSIE /.test(window.navigator.userAgent),a=["trace","debug","info","warn","error"];function _(R,I){var V=R[I];if(typeof V.bind=="function")return V.bind(R);try{return Function.prototype.bind.call(V,R)}catch{return function(){return Function.prototype.apply.apply(V,[R,arguments])}}}function e(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function p(R){return R==="debug"&&(R="log"),typeof console===i?!1:R==="trace"&&l?e:console[R]!==void 0?_(console,R):console.log!==void 0?_(console,"log"):s}function g(R,I){for(var V=0;V<a.length;V++){var W=a[V];this[W]=V<R?s:this.methodFactory(W,R,I)}this.log=this.debug}function n(R,I,V){return function(){typeof console!==i&&(g.call(this,I,V),this[R].apply(this,arguments))}}function v(R,I,V){return p(R)||n.apply(this,arguments)}function S(R,I,V){var W=this,oe;I=I??"WARN";var x="loglevel";typeof R=="string"?x+=":"+R:typeof R=="symbol"&&(x=void 0);function $(D){var L=(a[D]||"silent").toUpperCase();if(!(typeof window===i||!x)){try{window.localStorage[x]=L;return}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+L+";"}catch{}}}function Re(){var D;if(!(typeof window===i||!x)){try{D=window.localStorage[x]}catch{}if(typeof D===i)try{var L=window.document.cookie,q=L.indexOf(encodeURIComponent(x)+"=");q!==-1&&(D=/^([^;]+)/.exec(L.slice(q))[1])}catch{}return W.levels[D]===void 0&&(D=void 0),D}}function Ie(){if(!(typeof window===i||!x)){try{window.localStorage.removeItem(x);return}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}W.name=R,W.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},W.methodFactory=V||v,W.getLevel=function(){return oe},W.setLevel=function(D,L){if(typeof D=="string"&&W.levels[D.toUpperCase()]!==void 0&&(D=W.levels[D.toUpperCase()]),typeof D=="number"&&D>=0&&D<=W.levels.SILENT){if(oe=D,L!==!1&&$(D),g.call(W,D,R),typeof console===i&&D<W.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+D},W.setDefaultLevel=function(D){I=D,Re()||W.setLevel(D,!1)},W.resetLevel=function(){W.setLevel(I,!1),Ie()},W.enableAll=function(D){W.setLevel(W.levels.TRACE,D)},W.disableAll=function(D){W.setLevel(W.levels.SILENT,D)};var H=Re();H==null&&(H=I),W.setLevel(H,!1)}var m=new S,C={};m.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var V=C[I];return V||(V=C[I]=new S(I,m.getLevel(),m.methodFactory)),V};var A=typeof window!==i?window.log:void 0;return m.noConflict=function(){return typeof window!==i&&window.log===m&&(window.log=A),m},m.getLoggers=function(){return C},m.default=m,m})})(N_);var Ot=N_.exports;const As=()=>`${new Date().toISOString()} | metrics`,Cs=(c,s,i)=>`${c} | ${s} | ${i}`;Ot.setDefaultLevel(Ot.levels.TRACE);const pv=c=>{Ot.info(Cs(As(),"log ",`set log level to ${c?"verbose":"info"}`)),Ot.setLevel(c?Ot.levels.TRACE:Ot.levels.INFO)},mv=c=>{const s=[...Object.keys(Ot.levels)];s.includes(c)?(Ot.info(Cs(As(),"log ",`update log level to ${c.toLowerCase()}`)),Ot.setLevel(c)):Ot.warn(Cs(As(),"log ","Incorrect log level please choose one of "),s)},ke=(c,s,i)=>{i?Ot.debug(Cs(As(),c,s),i):Ot.debug(Cs(As(),c,s))},iu=(c,s)=>{Ot.info(Cs(As(),c,s))},Pn=(c,s)=>{Ot.info(Cs(As(),c,s))},Ma=(c,s)=>{Ot.warn(Cs(As(),c,s))},ir=(c,s)=>{Ot.error(Cs(As(),c,s))};function gv(c){return Math.floor(Math.random()*c).toString()}function Mf(c,s){let i=s;return c.forEach(l=>{i=i.replace(l,"")}),i}function Tv(c,s){let i="";for(let l=0;l<s;l+=1)i+=c[gv(c.length)];return i}function vv({length:c=20,useLetters:s=!0,useNumbers:i=!0,includeSymbols:l=[],excludeSymbols:a=[]}={}){let _="abcdefghijklmnopqrstuvwxyz",e="0123456789",p=[],g=[],n=[];return s&&(a.length&&(_=Mf(a,_)),g=_.split("")),i&&(a.length&&(e=Mf(a,e)),n=e.split("")),p=[...g,...n,...l],Tv(p,c)}var Ev=vv;const Ji=tt(Ev),Sv=()=>"WebRTCMetrics",yv=()=>"5.0.3",qe={INBOUND:"inbound",OUTBOUND:"outbound"},Ss={IDLE:"idle",RUNNING:"running",MUTED:"muted"},Bi={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},Av=()=>({...{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:[]}}),U_={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:qe.INBOUND},P_={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:qe.OUTBOUND},x_={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:qe.INBOUND},M_={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:qe.OUTBOUND},Cv=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 i={...c,audio:{},video:{},data:{...c.data},network:{...c.network},experimental:{...c.experimental}};return Object.keys(c.audio).forEach(l=>{i.audio[l]={...c.audio[l]}}),Object.keys(c.video).forEach(l=>{i.video[l]={...c.video[l]}}),i}return{...s,audio:{},video:{},data:{...s.data},network:{...s.network},experimental:{...s.experimental}}},Rv={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${Ji()}`,cid:`c-${Ji()}`,uid:`u-${Ji()}`,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"},K={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"},M={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},Gi={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},lu={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ie={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},au="config ",Iv=(c,s={},i)=>{const l={...i,...s};return s.pname||Ma(au,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${i.pname}'`),s.cid||Ma(au,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${i.cid}'`),s.uid||Ma(au,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${i.uid}'`),l.pc=c,l},bv=(c={})=>{const s={...Rv,...c};return s.name=Sv(),s.version=yv(),s},_l=(c,s,i,l=!1,a)=>{let _=c.map(e=>{if(!i)return e[s];if(!a)return e[s][i];const p=e[s][a];return p?p[i]:null});return _=_.filter(e=>l?Number.isFinite(e)&&e>0:Number.isFinite(e)),_.length===0?[]:_},Zs=c=>c.reduce((s,i)=>s+i,0)/c.length,wv=()=>`probe-${Ji()}`,Ov=()=>`coltr-${Ji()}`,kf=c=>new Promise(s=>setTimeout(s,c)),wu=(c,s,i)=>{s?c.call(s,i):c(i)},Qe=(c,s,i,l)=>{const a=_l(c,s,i,!0,l);if(a.length===0)return null;const _=a.reduce((n,v)=>n+v,0)/a.length;return _===0?null:a.map(n=>Math.abs(_-n)).reduce((n,v)=>n+v,0)/a.length*100/_},st=(c,s,i,l=!1,a)=>{const _=_l(c,s,i,l,a);return _.length===0?null:_.reduce((e,p)=>e+p,0)/_.length},wn=(c,s,i)=>_l(c,s,i).reduce((a,_)=>a+_,0),Ze=(c,s,i,l)=>{const a=_l(c,s,i,!0,l);return a.length===0?null:Math.min(...a)},et=(c,s,i,l)=>{const a=_l(c,s,i,!1,l);return a.length===0?null:Math.max(...a)},vt=(c,s,i,l)=>{const a=c.slice().pop();if(!a)return null;if(!i)return a[s];if(!l)return a[s][i];const _=a[s][l];return _?_[i]:null},Dv=c=>c.slice().pop(),_t=(c,s,i)=>{if(!s)return null;const l={};let a=s[M.AUDIO][c];a||(a=i===qe.INBOUND?{...U_}:{...P_}),l[M.AUDIO]=a;let _=s[M.VIDEO][c];return _||(_=i===qe.INBOUND?{...x_}:{...M_}),l[M.VIDEO]=_,l},Wi="exporter ",Nv="2.0",Lf=(c,s,i)=>{if(!c||c.length===0)return 0;const l=c[c.length-1];if(!l)return 0;const a=l[s][i];if(a){const _=a.total_rtt_ms_out,e=a.total_rtt_measure_out;return!e||!_?st(c,s,"delta_rtt_ms_out",!1,i):Number(_/e)}return null},Uv=(c,s)=>{if(!c||c.length===0)return 0;const i=c[c.length-1];if(!i)return 0;const l=i[s].total_rtt_connectivity_ms,a=i[s].total_rtt_connectivity_measure;return!a||!l?st(c,s,"delta_rtt_connectivity_ms"):Number(l/a)},Pv=c=>vt(c,"network","local_candidate_type")!=="relay"?`direct/${vt(c,"network","local_candidate_protocol")}`:`turn/${vt(c,"network","local_candidate_relay_protocol")}`,xv=c=>{const s=vt(c,"network","remote_candidate_type"),i=vt(c,"network","remote_candidate_protocol");return s!=="relay"?`direct/${i}`:`turn/${i}`};class Mv{constructor(s){this._start=null,this._end=null,this._cfg=s,this._referenceReport=null,this._reports=[],this._events=[]}start(){iu(Wi,"start() - start exporter...");const s=new Date;return this._start=s.toJSON(),s}stop(){iu(Wi,"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&&(ke(Wi,`addReport() - add report to exporter at ${s.timestamp}`),this._reports.push(s))}addCustomEvent(s){this._events.push(s)}reset(){iu(Wi,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){ke(Wi,"ticket() - generate ticket");const s=vt(this._reports,"audio","total_packets_lost_in"),i=vt(this._reports,"audio","total_packets_in"),l=vt(this._reports,"video","total_packets_lost_in"),a=vt(this._reports,"video","total_packets_in"),_={},e=Dv(this._reports);return e&&(Object.keys(e[M.AUDIO]).forEach(p=>{const g=e[M.AUDIO][p];if(_[g.ssrc]={type:M.AUDIO,direction:g.direction},g.direction===qe.INBOUND){const n={avg:st(this._reports,M.AUDIO,"delta_jitter_ms_in",!1,p),min:Ze(this._reports,M.AUDIO,"delta_jitter_ms_in",p),max:et(this._reports,M.AUDIO,"delta_jitter_ms_in",p),volatility:Qe(this._reports,M.AUDIO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},v={avg:st(this._reports,M.AUDIO,"delta_kbs_in",!1,p),min:Ze(this._reports,M.AUDIO,"delta_kbs_in",p),max:et(this._reports,M.AUDIO,"delta_kbs_in",p),volatility:Qe(this._reports,M.AUDIO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},S={avg:st(this._reports,M.AUDIO,"delta_KBytes_in",!1,p),min:Ze(this._reports,M.AUDIO,"delta_KBytes_in",p),max:et(this._reports,M.AUDIO,"delta_KBytes_in",p),volatility:Qe(this._reports,M.AUDIO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},m={emodel:{avg:st(this._reports,M.AUDIO,"mos_emodel_in",!1,p),min:Ze(this._reports,M.AUDIO,"mos_emodel_in",p),max:et(this._reports,M.AUDIO,"mos_emodel_in",p),volatility:Qe(this._reports,M.AUDIO,"mos_emodel_in",p)},effective:{avg:st(this._reports,M.AUDIO,"mos_in",!1,p),min:Ze(this._reports,M.AUDIO,"mos_in",p),max:et(this._reports,M.AUDIO,"mos_in",p),volatility:Qe(this._reports,M.AUDIO,"mos_in",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},C=vt(this._reports,M.AUDIO,"total_packets_lost_in",p),A=vt(this._reports,M.AUDIO,"total_packets_in",p),R={lost:C,avg:Math.round((C/(C+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};_[p].jitter=n,_[p].mos=m,_[p].traffic=S,_[p].bitrate=v,_[p].loss=R}else{const n={avg:st(this._reports,M.AUDIO,"delta_jitter_ms_out",!1,p),min:Ze(this._reports,M.AUDIO,"delta_jitter_ms_out",p),max:et(this._reports,M.AUDIO,"delta_jitter_ms_out",p),volatility:Qe(this._reports,M.AUDIO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},v={avg:st(this._reports,M.AUDIO,"delta_kbs_out",!1,p),min:Ze(this._reports,M.AUDIO,"delta_kbs_out",p),max:et(this._reports,M.AUDIO,"delta_kbs_out",p),volatility:Qe(this._reports,M.AUDIO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},S={avg:st(this._reports,M.AUDIO,"delta_KBytes_out",!1,p),min:Ze(this._reports,M.AUDIO,"delta_KBytes_out",p),max:et(this._reports,M.AUDIO,"delta_KBytes_out",p),volatility:Qe(this._reports,M.AUDIO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},m={avg:Lf(this._reports,M.AUDIO,p),min:Ze(this._reports,M.AUDIO,"delta_rtt_ms_out",p),max:et(this._reports,M.AUDIO,"delta_rtt_ms_out",p),volatility:Qe(this._reports,M.AUDIO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},C=vt(this._reports,M.AUDIO,"total_packets_lost_out",p),A=vt(this._reports,M.AUDIO,"total_packets_out",p),R={lost:C,avg:Math.round((C/(C+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},I={emodel:{avg:st(this._reports,M.AUDIO,"mos_emodel_out",!1,p),min:Ze(this._reports,M.AUDIO,"mos_emodel_out",p),max:et(this._reports,M.AUDIO,"mos_emodel_out",p),volatility:Qe(this._reports,M.AUDIO,"mos_emodel_out",p)},effective:{avg:st(this._reports,M.AUDIO,"mos_out",!1,p),min:Ze(this._reports,M.AUDIO,"mos_out",p),max:et(this._reports,M.AUDIO,"mos_out",p),volatility:Qe(this._reports,M.AUDIO,"mos_out",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};_[p].jitter=n,_[p].rtt=m,_[p].traffic=S,_[p].bitrate=v,_[p].loss=R,_[p].mos=I}}),Object.keys(e[M.VIDEO]).forEach(p=>{const g=e[M.VIDEO][p];if(_[p]={type:M.VIDEO,direction:g.direction},g.direction===qe.INBOUND){const n={avg:st(this._reports,M.VIDEO,"delta_jitter_ms_in",!1,p),min:Ze(this._reports,M.VIDEO,"delta_jitter_ms_in",p),max:et(this._reports,M.VIDEO,"delta_jitter_ms_in",p),volatility:Qe(this._reports,M.VIDEO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},v={avg:st(this._reports,M.VIDEO,"delta_kbs_in",!1,p),min:Ze(this._reports,M.VIDEO,"delta_kbs_in",p),max:et(this._reports,M.VIDEO,"delta_kbs_in",p),volatility:Qe(this._reports,M.VIDEO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},S={avg:st(this._reports,M.VIDEO,"delta_KBytes_in",!1,p),min:Ze(this._reports,M.VIDEO,"delta_KBytes_in",p),max:et(this._reports,M.VIDEO,"delta_KBytes_in",p),volatility:Qe(this._reports,M.VIDEO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},m=vt(this._reports,M.VIDEO,"total_packets_lost_in",p),C=vt(this._reports,M.VIDEO,"total_packets_in",p),A={lost:m,avg:Math.round((m/(m+C)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};_[p].jitter=n,_[p].traffic=S,_[p].bitrate=v,_[p].loss=A}else{const n={avg:st(this._reports,M.VIDEO,"delta_jitter_ms_out",!1,p),min:Ze(this._reports,M.VIDEO,"delta_jitter_ms_out",p),max:et(this._reports,M.VIDEO,"delta_jitter_ms_out",p),volatility:Qe(this._reports,M.VIDEO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},v={avg:st(this._reports,M.VIDEO,"delta_kbs_out",!1,p),min:Ze(this._reports,M.VIDEO,"delta_kbs_out",p),max:et(this._reports,M.VIDEO,"delta_kbs_out",p),volatility:Qe(this._reports,M.VIDEO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},S={avg:st(this._reports,M.VIDEO,"delta_KBytes_out",!1,p),min:Ze(this._reports,M.VIDEO,"delta_KBytes_out",p),max:et(this._reports,M.VIDEO,"delta_KBytes_out",p),volatility:Qe(this._reports,M.VIDEO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},m={avg:Lf(this._reports,M.VIDEO,p),min:Ze(this._reports,M.VIDEO,"delta_rtt_ms_out",p),max:et(this._reports,M.VIDEO,"delta_rtt_ms_out",p),volatility:Qe(this._reports,M.VIDEO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},C=vt(this._reports,M.VIDEO,"total_packets_lost_out",p),A=vt(this._reports,M.VIDEO,"total_packets_out",p),R={lost:C,avg:Math.round((C/(C+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};_[p].jitter=n,_[p].rtt=m,_[p].traffic=S,_[p].bitrate=v,_[p].loss=R}})),{version:Nv,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:_,data:{rtt:{avg:Uv(this._reports,"data"),min:Ze(this._reports,"data","delta_rtt_connectivity_ms"),max:et(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Qe(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((s/(s+i)*100||0)*100)/100}},video:{in:{avg:Math.round((l/(l+a)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:st(this._reports,"data","delta_kbs_in"),min:Ze(this._reports,"data","delta_kbs_in"),max:et(this._reports,"data","delta_kbs_in"),volatility:Qe(this._reports,"data","delta_kbs_in")},out:{avg:st(this._reports,"data","delta_kbs_out"),min:Ze(this._reports,"data","delta_kbs_out"),max:et(this._reports,"data","delta_kbs_out"),volatility:Qe(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:st(this._reports,"data","delta_KBytes_in"),min:Ze(this._reports,"data","delta_KBytes_in"),max:et(this._reports,"data","delta_KBytes_in"),volatility:Qe(this._reports,"data","delta_KBytes_in")},out:{avg:st(this._reports,"data","delta_KBytes_out"),min:Ze(this._reports,"data","delta_KBytes_out"),max:et(this._reports,"data","delta_KBytes_out"),volatility:Qe(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:Pv(this._reports),remoteConnection:xv(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 Js="extractor ",$f=(c,s,i,l)=>{let a=!1;const _=l[s].total_rtt_ms_out,e=l[s].total_rtt_measure_out,p=i?i[s].total_rtt_ms_out:0,g=i?i[s].total_rtt_measure_out:0,n={rtt:null,totalRTT:_,totalRTTMeasurements:e};if(c[K.TIMESTAMP]===l[s].timestamp_out||!Object.prototype.hasOwnProperty.call(c,K.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(a=!0,Number(c[K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-g===e))return n;const v=1e3*Number(c[K.ROUND_TRIP_TIME]);let S=_+v,m=e+1;return a&&(S=1e3*Number(c[K.TOTAL_ROUND_TRIP_TIME])-p,m=Number(c[K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-g),{rtt:v,totalRTT:S,totalRTTMeasurements:m}},kv=(c,s,i,l)=>{if(!Object.prototype.hasOwnProperty.call(c,K.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:l[s].total_rtt_connectivity_ms,totalRTTMeasurements:l[s].total_rtt_connectivity_measure};const a=1e3*Number(c[K.CURRENT_ROUND_TRIP_TIME]);let _=l[s].total_rtt_connectivity_ms+a,e=l[s].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,K.TOTAL_ROUND_TRIP_TIME)&&(_=1e3*Number(c[K.TOTAL_ROUND_TRIP_TIME])-(i?i[s].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,K.RESPONSES_RECEIVED)&&(e=Number(c[K.RESPONSES_RECEIVED])-(i?i[s].total_rtt_connectivity_measure:0)),{rtt:a,totalRTT:_,totalRTTMeasurements:e}},Ea=(c,s,i)=>c[K.TIMESTAMP]===i[s].timestamp_out||!Object.prototype.hasOwnProperty.call(c,K.JITTER)?null:1e3*(Number(c[K.JITTER])||0),Lv=(c,s)=>{if(!Object.prototype.hasOwnProperty.call(c,K.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,K.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:s[M.VIDEO].delta_ms_decode_frame_in,frames_decoded:s[M.VIDEO].total_frames_decoded_in,total_decode_time:s[M.VIDEO].total_time_decoded_in};const i=c[K.FRAMES_DECODED],l=c[K.TOTAL_DECODE_TIME],a=l-s[M.VIDEO].total_time_decoded_in,_=i-s[M.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:_>0?a*1e3/_:0,frames_decoded:i,total_decode_time:l}},$v=(c,s)=>{if(!Object.prototype.hasOwnProperty.call(c,K.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,K.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:s[M.VIDEO].delta_ms_encode_frame_out,frames_encoded:s[M.VIDEO].total_frames_encoded_out,total_encode_time:s[M.VIDEO].total_time_encoded_out};const i=c[K.FRAMES_ENCODED],l=c[K.TOTAL_ENCODE_TIME],a=l-s[M.VIDEO].total_time_encoded_out,_=i-s[M.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:_>0&&a?a*1e3/_:0,frames_encoded:i,total_encode_time:l}},Hf=(c,s,i,l)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,K.BYTES_SENT))return{packetsSent:i[s].total_packets_out,packetsLost:i[s].total_packets_lost_out,bytesSent:i[s].total_KBytes_out};const a=Number(c[K.PACKETS_SENT])||0-(l?l[s].total_packets_out:0),_=a-i[s].total_packets_out,e=Number(c[K.BYTES_SENT])/1024-(l?l[s].total_KBytes_out:0),p=e-i[s].total_KBytes_out,g=c[K.TIMESTAMP]||Date.now(),n=l?l.timestamp:null;let v=i.timestamp;!v&&n&&(v=n);const S=v?g-v:0,m=S>0?p*.008*1024/S*1e3:0;return{packetsSent:a,deltaPacketsSent:_,KBytesSent:e,deltaKBytesSent:p,kbsSent:m}},Ff=(c,s,i,l)=>{let a=i[s].total_packets_lost_out,_=0,e=0;return Object.prototype.hasOwnProperty.call(c,K.PACKETS_LOST)&&(a=Number(c[K.PACKETS_LOST])||0-(l?l[s].total_packets_lost_out:0),_=a-i[s].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,K.FRACTION_LOST)&&(e=Number(100*c[K.FRACTION_LOST])),{packetsLost:a,deltaPacketsLost:_,fractionLost:e}},jf=(c,s,i,l)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,K.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,K.BYTES_RECEIVED))return{percent_packets_lost:i[s].percent_packets_lost_in,packetsReceived:i[s].total_packets_in,packetsLost:i[s].total_packets_lost_in,bytesReceived:i[s].total_KBytes_in};const a=Number(c[K.PACKETS_RECEIVED])||0-(l?l[s].total_packets_in:0),_=Number(c[K.PACKETS_LOST])||0-(l?l[s].total_packets_lost_in:0),e=_-i[s].total_packets_lost_in,p=a-i[s].total_packets_in,g=a!==i[s].total_packets_in?e*100/(e+p):0,n=Number(c[K.BYTES_RECEIVED])/1024-(l?l[s].total_KBytes_in:0),v=n-i[s].total_KBytes_in,S=c[K.TIMESTAMP]||Date.now(),m=l?l.timestamp:null;let C=i.timestamp;!C&&m&&(C=m);const A=C?S-C:0,R=A>0?v*.008*1024/A*1e3:0;return{percentPacketsLost:g,packetsReceived:a,deltaPacketsReceived:p,packetsLost:_,deltaPacketsLost:e,KBytesReceived:n,deltaKBytesReceived:v,kbsReceived:R}},Hv=c=>c[K.CANDIDATE_TYPE]!=="relay"?"":c[K.RELAY_PROTOCOL]||"",Fv=c=>{if(!Object.prototype.hasOwnProperty.call(c,K.NETWORK_TYPE))return Gi.WIFI;switch(c[K.NETWORK_TYPE]){case lu.ETHERNET:return Gi.ETHERNET;case lu.CELLULAR_4G:return Gi.CELLULAR_4G;case lu.WIFI:return Gi.WIFI;default:return Gi.CELLULAR}},qf=c=>!Object.prototype.hasOwnProperty.call(c,K.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,K.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[K.FRAME_WIDTH]||null,height:c[K.FRAME_HEIGHT]||null,framerate:c[K.FRAMES_PER_SECOND]},jv=c=>{const s=Object.prototype.hasOwnProperty.call(c,K.QUALITY_LIMITATION_REASON)?c[K.QUALITY_LIMITATION_REASON]:null,i=Object.prototype.hasOwnProperty.call(c,K.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[K.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,l=Object.prototype.hasOwnProperty.call(c,K.QUALITY_LIMITATION_DURATIONS)?c[K.QUALITY_LIMITATION_DURATIONS]:null;return l&&Object.keys(l).forEach(a=>{l[a]>1e3&&(l[a]=Number(l[a]/1e3))}),{reason:s,durations:l,resolutionChanges:i}},qv=(c,s,i)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PLI)||!Object.prototype.hasOwnProperty.call(c,K.NACK))return{pliCount:s.total_pli_sent_in,nackCount:s.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const l=(c[K.PLI]||0)-(i?i[M.VIDEO].total_pli_sent_in:0),a=(c[K.NACK]||0)-(i?i[M.VIDEO].total_nack_sent_in:0);return{pliCount:l,nackCount:a,deltaPliCount:l-s[M.VIDEO].total_pli_sent_in,deltaNackCount:a-s[M.VIDEO].total_nack_sent_in}},Vv=(c,s,i)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PLI)||!Object.prototype.hasOwnProperty.call(c,K.NACK))return{pliCount:s.total_pli_received_out,nackCount:s.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const l=(c[K.PLI]||0)-(i?i[M.VIDEO].total_pli_received_out:0),a=(c[K.NACK]||0)-(i?i[M.VIDEO].total_nack_received_out:0);return{pliCount:l,nackCount:a,deltaPliCount:l-s[M.VIDEO].total_pli_received_out,deltaNackCount:a-s[M.VIDEO].total_nack_received_out}},Bv=c=>({channels:c[K.CHANNELS]||null,clock_rate:c[K.CLOCK_RATE]||null,mime_type:c[K.MIME_TYPE]||null,sdp_fmtp_line:c[K.SDP_FMTP_LINE]||null}),Gv=c=>({clock_rate:c[K.CLOCK_RATE]||null,mime_type:c[K.MIME_TYPE]||null}),Wv=(c,s,i)=>{const l=(c[K.BYTES_RECEIVED]||0)/1024-(i?i.data.total_KBytes_in:0),a=(c[K.BYTES_SENT]||0)/1024-(i?i.data.total_KBytes_out:0),_=c[K.TIMESTAMP]||Date.now(),e=l-s.data.total_KBytes_in,p=a-s.data.total_KBytes_out,g=i?i.timestamp:null;let n=s.timestamp;!n&&g&&(n=g);const v=n?_-n:0,S=v>0?e*.008*1024/v*1e3:0,m=v>0?p*.008*1024/v*1e3:0;return{total_KBytes_received:l,total_KBytes_sent:a,delta_KBytes_received:e,delta_KBytes_sent:p,kbs_speed_received:S,kbs_speed_sent:m}},Kv=c=>{const s=c[K.AVAILABLE_INCOMING_BITRATE]/1024||0,i=c[K.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:s,kbs_outgoing_bandwidth:i}},Yv=(c,s,i,l)=>{if(!c)return[];switch(c[K.TYPE]){case zt.CANDIDATE_PAIR:let a=!1;if(c[K.NOMINATED]&&c[K.STATE]===M.SUCCEEDED&&(a=!0,ke(Js,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c),K.SELECTED in c&&!c[K.SELECTED]&&(a=!1)),a){const e=c[K.LOCAL_CANDIDATE_ID],p=c[K.REMOTE_CANDIDATE_ID],g=Wv(c,s,l),n=Kv(c),v=kv(c,"data",l,s);return[{type:ie.NETWORK,value:{local_candidate_id:e}},{type:ie.NETWORK,value:{remote_candidate_id:p}},{type:ie.DATA,value:{total_KBytes_in:g.total_KBytes_received}},{type:ie.DATA,value:{total_KBytes_out:g.total_KBytes_sent}},{type:ie.DATA,value:{delta_KBytes_in:g.delta_KBytes_received}},{type:ie.DATA,value:{delta_KBytes_out:g.delta_KBytes_sent}},{type:ie.DATA,value:{delta_kbs_in:g.kbs_speed_received}},{type:ie.DATA,value:{delta_kbs_out:g.kbs_speed_sent}},{type:ie.DATA,value:{delta_kbs_bandwidth_in:n.kbs_incoming_bandwidth}},{type:ie.DATA,value:{delta_kbs_bandwidth_out:n.kbs_outgoing_bandwidth}},{type:ie.DATA,value:{delta_rtt_connectivity_ms:v.rtt}},{type:ie.DATA,value:{total_rtt_connectivity_ms:v.totalRTT}},{type:ie.DATA,value:{total_rtt_connectivity_measure:v.totalRTTMeasurements}}]}break;case zt.LOCAL_CANDIDATE:if(c[K.ID]===s.network.local_candidate_id)return[{type:ie.NETWORK,value:{infrastructure:Fv(c)}},{type:ie.NETWORK,value:{local_candidate_type:c[K.CANDIDATE_TYPE]||""}},{type:ie.NETWORK,value:{local_candidate_protocol:c[K.PROTOCOL]||""}},{type:ie.NETWORK,value:{local_candidate_relay_protocol:Hv(c)}}];break;case zt.REMOTE_CANDIDATE:if(c[K.ID]===s.network.remote_candidate_id)return[{type:ie.NETWORK,value:{remote_candidate_type:c[K.CANDIDATE_TYPE]||""}},{type:ie.NETWORK,value:{remote_candidate_protocol:c[K.PROTOCOL]||""}}];break;case zt.INBOUND_RTP:{ke(Js,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);const e=c[K.SSRC],p=_t(e,s,qe.INBOUND);p&&(p.timestamp=s.timestamp);const g=_t(e,l,qe.INBOUND);if(g&&(g.timestamp=l.timestamp),c[K.MEDIA_TYPE]===M.AUDIO){const n=jf(c,M.AUDIO,p,g),v=Ea(c,M.AUDIO,p),S=c[K.CODEC_ID]||"";return[{ssrc:e,type:ie.AUDIO,value:{codec_id_in:S}},{ssrc:e,type:ie.AUDIO,value:{total_packets_in:n.packetsReceived}},{ssrc:e,type:ie.AUDIO,value:{delta_packets_in:n.deltaPacketsReceived}},{ssrc:e,type:ie.AUDIO,value:{total_packets_lost_in:n.packetsLost}},{ssrc:e,type:ie.AUDIO,value:{delta_packets_lost_in:n.deltaPacketsLost}},{ssrc:e,type:ie.AUDIO,value:{percent_packets_lost_in:n.percentPacketsLost}},{ssrc:e,type:ie.AUDIO,value:{total_KBytes_in:n.KBytesReceived}},{ssrc:e,type:ie.AUDIO,value:{delta_KBytes_in:n.deltaKBytesReceived}},{ssrc:e,type:ie.AUDIO,value:{delta_kbs_in:n.kbsReceived}},{ssrc:e,type:ie.AUDIO,value:{delta_jitter_ms_in:v}}]}if(c[K.MEDIA_TYPE]===M.VIDEO){const n=Lv(c,p),v=jf(c,M.VIDEO,p,g),S=Ea(c,M.VIDEO,p),m=c[K.DECODER_IMPLEMENTATION]||null,C=c[K.CODEC_ID]||null,A=qf(c),R=qv(c,p,g);return[{ssrc:e,type:ie.VIDEO,value:{codec_id_in:C}},{ssrc:e,type:ie.VIDEO,value:{total_packets_in:v.packetsReceived}},{ssrc:e,type:ie.VIDEO,value:{delta_packets_in:v.deltaPacketsReceived}},{ssrc:e,type:ie.VIDEO,value:{total_packets_lost_in:v.packetsLost}},{ssrc:e,type:ie.VIDEO,value:{delta_packets_lost_in:v.deltaPacketsLost}},{ssrc:e,type:ie.VIDEO,value:{percent_packets_lost_in:v.percentPacketsLost}},{ssrc:e,type:ie.VIDEO,value:{total_KBytes_in:v.KBytesReceived}},{ssrc:e,type:ie.VIDEO,value:{delta_KBytes_in:v.deltaKBytesReceived}},{ssrc:e,type:ie.VIDEO,value:{delta_kbs_in:v.kbsReceived}},{ssrc:e,type:ie.VIDEO,value:{delta_jitter_ms_in:S}},{ssrc:e,type:ie.VIDEO,value:{decoder_in:m}},{ssrc:e,type:ie.VIDEO,value:{delta_ms_decode_frame_in:n.delta_ms_decode_frame}},{ssrc:e,type:ie.VIDEO,value:{total_frames_decoded_in:n.frames_decoded}},{ssrc:e,type:ie.VIDEO,value:{total_time_decoded_in:n.total_decode_time}},{ssrc:e,type:ie.VIDEO,value:{total_nack_sent_in:R.nackCount}},{ssrc:e,type:ie.VIDEO,value:{delta_nack_sent_in:R.deltaNackCount}},{ssrc:e,type:ie.VIDEO,value:{total_pli_sent_in:R.pliCount}},{ssrc:e,type:ie.VIDEO,value:{delta_pli_sent_in:R.deltaPliCount}},{ssrc:e,type:ie.VIDEO,value:{size_in:A}}]}break}case zt.OUTBOUND_RTP:{ke(Js,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);const e=c[K.SSRC],p=_t(e,s,qe.OUTBOUND);p&&(p.timestamp=s.timestamp);const g=_t(e,l,qe.OUTBOUND);if(g&&(g.timestamp=l.timestamp),c[K.MEDIA_TYPE]===M.AUDIO){const n=c[K.CODEC_ID]||null,v=Hf(c,M.AUDIO,p,g);return[{ssrc:e,type:ie.AUDIO,value:{codec_id_out:n}},{ssrc:e,type:ie.AUDIO,value:{total_packets_out:v.packetsSent}},{ssrc:e,type:ie.AUDIO,value:{delta_packets_out:v.deltaPacketsSent}},{ssrc:e,type:ie.AUDIO,value:{total_KBytes_out:v.KBytesSent}},{ssrc:e,type:ie.AUDIO,value:{delta_KBytes_out:v.deltaKBytesSent}},{ssrc:e,type:ie.AUDIO,value:{delta_kbs_out:v.kbsSent}}]}if(c[K.MEDIA_TYPE]===M.VIDEO){const n=c[K.ENCODER_IMPLEMENTATION]||null,v=c[K.CODEC_ID]||null,S=$v(c,p),m=qf(c),C=jv(c),A=Vv(c,p,g),R=Hf(c,M.VIDEO,p,g);return[{ssrc:e,type:ie.VIDEO,value:{codec_id_out:v}},{ssrc:e,type:ie.VIDEO,value:{total_packets_out:R.packetsSent}},{ssrc:e,type:ie.VIDEO,value:{delta_packets_out:R.deltaPacketsSent}},{ssrc:e,type:ie.VIDEO,value:{total_KBytes_out:R.KBytesSent}},{ssrc:e,type:ie.VIDEO,value:{delta_KBytes_out:R.deltaKBytesSent}},{ssrc:e,type:ie.VIDEO,value:{delta_kbs_out:R.kbsSent}},{ssrc:e,type:ie.VIDEO,value:{encoder_out:n}},{ssrc:e,type:ie.VIDEO,value:{delta_ms_encode_frame_out:S.delta_ms_encode_frame}},{ssrc:e,type:ie.VIDEO,value:{total_frames_encoded_out:S.frames_encoded}},{ssrc:e,type:ie.VIDEO,value:{total_time_encoded_out:S.total_encode_time}},{ssrc:e,type:ie.VIDEO,value:{total_nack_received_out:A.nackCount}},{ssrc:e,type:ie.VIDEO,value:{delta_nack_received_out:A.deltaNackCount}},{ssrc:e,type:ie.VIDEO,value:{total_pli_received_out:A.pliCount}},{ssrc:e,type:ie.VIDEO,value:{delta_pli_received_out:A.deltaPliCount}},{ssrc:e,type:ie.VIDEO,value:{size_out:m}},{ssrc:e,type:ie.VIDEO,value:{limitation_out:C}}]}break}case zt.MEDIA_SOURCE:{ke(Js,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);break}case zt.TRACK:{ke(Js,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);break}case zt.CODEC:const _=[];return Object.keys(s[M.AUDIO]).forEach(e=>{const p=s[M.AUDIO][e];if(p.codec_id_in===c[K.ID]||p.codec_id_out===c[K.ID]){ke(Js,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);const g=Bv(c);c[K.ID]===p.codec_id_in?_.push({ssrc:p.ssrc,type:ie.AUDIO,value:{codec_in:g}}):_.push({ssrc:p.ssrc,type:ie.AUDIO,value:{codec_out:g}})}}),Object.keys(s[M.VIDEO]).forEach(e=>{const p=s[M.VIDEO][e];if(p.codec_id_in===c[K.ID]||p.codec_id_out===c[K.ID]){ke(Js,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);const g=Gv(c);c[K.ID]===p.codec_id_in?_.push({ssrc:p.ssrc,type:ie.VIDEO,value:{codec_in:g}}):_.push({ssrc:p.ssrc,type:ie.VIDEO,value:{codec_out:g}})}}),_;case zt.REMOTE_INBOUND_RTP:{ke(Js,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);const e=c[K.SSRC],p=_t(e,s,qe.OUTBOUND),g=_t(e,l,qe.OUTBOUND);if(c[K.KIND]===M.AUDIO){const n=$f(c,M.AUDIO,g,p),v=Ea(c,M.AUDIO,p),S=Ff(c,M.AUDIO,p,g);return[{ssrc:e,type:ie.AUDIO,value:{delta_rtt_ms_out:n.rtt}},{ssrc:e,type:ie.AUDIO,value:{total_rtt_ms_out:n.totalRTT}},{ssrc:e,type:ie.AUDIO,value:{total_rtt_measure_out:n.totalRTTMeasurements}},{ssrc:e,type:ie.AUDIO,value:{delta_jitter_ms_out:v}},{ssrc:e,type:ie.AUDIO,value:{timestamp_out:c[K.TIMESTAMP]}},{ssrc:e,type:ie.AUDIO,value:{total_packets_lost_out:S.packetsLost}},{ssrc:e,type:ie.AUDIO,value:{delta_packets_lost_out:S.deltaPacketsLost}},{ssrc:e,type:ie.AUDIO,value:{percent_packets_lost_out:S.fractionLost}}]}if(c[K.KIND]===M.VIDEO){const n=$f(c,M.VIDEO,g,p),v=Ea(c,M.VIDEO,p),S=Ff(c,M.VIDEO,p,g);return[{ssrc:e,type:ie.VIDEO,value:{delta_rtt_ms_out:n.rtt}},{ssrc:e,type:ie.VIDEO,value:{total_rtt_ms_out:n.totalRTT}},{ssrc:e,type:ie.VIDEO,value:{total_rtt_measure_out:n.totalRTTMeasurements}},{ssrc:e,type:ie.VIDEO,value:{delta_jitter_ms_out:v}},{ssrc:e,type:ie.VIDEO,value:{timestamp_out:c[K.TIMESTAMP]}},{ssrc:e,type:ie.VIDEO,value:{total_packets_lost_out:S.packetsLost}},{ssrc:e,type:ie.VIDEO,value:{delta_packets_lost_out:S.deltaPacketsLost}},{ssrc:e,type:ie.VIDEO,value:{percent_packets_lost_out:S.fractionLost}}]}break}}return[]},to=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),Jv=(c,s=M.AUDIO,i,l,a)=>{const _=_t(a,c,qe.INBOUND),e=_t(a,i,qe.INBOUND),p=_t(a,l,qe.INBOUND),g=[],n=[],v=_[s].percent_packets_lost_in,S=_[s].delta_jitter_ms_in,m=e&&e[s].delta_jitter_ms_in||null,C=p&&p[s].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,R=i&&i.data.delta_rtt_connectivity_ms||null,I=l&&l.data.delta_rtt_connectivity_ms||null;A&&g.push(A),R&&g.push(R),I&&g.push(I),S&&n.push(S),i&&m&&n.push(m),l&&C&&n.push(C);const V=g.length>0?Zs(g):100,W=n.length>0?Zs(n):10,oe=93.2-v,x=.18*oe*oe-27.9*oe+1126.62,$=(V+W)/2,Re=$-177.3<0?0:1,Ie=.024*$+.11*($-177.3)*Re,H=x-Ie;return to(H)},zv=(c,s=M.AUDIO,i,l,a)=>{const _=_t(a,c,qe.OUTBOUND),e=_t(a,i,qe.OUTBOUND),p=_t(a,l,qe.OUTBOUND),g=[],n=[],v=_[s].percent_packets_lost_out,S=_[s].delta_rtt_ms_out,m=e&&e[s].delta_rtt_ms_out||null,C=p&&p[s].delta_rtt_ms_out||null,A=_[s].delta_jitter_ms_out,R=e&&e[s].delta_jitter_ms_out||null,I=p&&p[s].delta_jitter_ms_out||null,V=c.data.delta_rtt_connectivity_ms,W=i&&i.data.delta_rtt_connectivity_ms||null,oe=l&&l.data.delta_rtt_connectivity_ms||null;S?g.push(S):V&&g.push(V),m?g.push(m):W&&g.push(W),C?g.push(C):oe&&g.push(oe),A&&n.push(A),i&&R&&n.push(R),l&&I&&n.push(I);const x=g.length>0?Zs(g):100,$=n.length>0?Zs(n):10,Re=93.2-v,Ie=.18*Re*Re-27.9*Re+1126.62,H=(x+$)/2,D=H-177.3<0?0:1,L=.024*H+.11*(H-177.3)*D,q=Ie-L;return to(q)},Xv=(c,s=M.AUDIO,i,l,a)=>{const _=_t(a,c,qe.INBOUND),e=_t(a,i,qe.INBOUND),p=_t(a,l,qe.INBOUND),g=[],n=[],v=_[s].percent_packets_lost_in/100,S=_[s].delta_jitter_ms_in,m=e&&e[s].delta_jitter_ms_in||null,C=p&&p[s].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,R=i&&i.data.delta_rtt_connectivity_ms||null,I=l&&l.data.delta_rtt_connectivity_ms||null;A&&g.push(A),R&&g.push(R),I&&g.push(I),S&&n.push(S),e&&m&&n.push(m),p&&C&&n.push(C);const V=g.length>0?Zs(g):100,W=n.length>0?Zs(n):10,oe=0,x=19.8,$=29.7,Re=30,Ie=(V+W)/2+Re,H=Ie-177.3<0?0:1,D=.024*Ie+.11*(Ie-177.3)*H,q=93.2-(oe+x*Math.log(1+$*v)+D);return to(q)},Qv=(c,s=M.AUDIO,i,l,a)=>{const _=_t(a,c,qe.OUTBOUND),e=_t(a,i,qe.OUTBOUND),p=_t(a,l,qe.OUTBOUND),g=[],n=[],v=_[s].percent_packets_lost_out/100,S=_[s].delta_rtt_ms_out,m=e&&e[s].delta_rtt_ms_out||null,C=p&&p[s].delta_rtt_ms_out||null,A=_[s].delta_jitter_ms_out,R=e&&e[s].delta_jitter_ms_out||null,I=p&&p[s].delta_jitter_ms_out||null,V=c.data.delta_rtt_connectivity_ms,W=i&&i.data.delta_rtt_connectivity_ms||null,oe=l&&l.data.delta_rtt_connectivity_ms||null;S?g.push(S):V&&g.push(V),m?g.push(m):W&&g.push(W),C?g.push(C):oe&&g.push(oe),A&&n.push(A),e&&R&&n.push(R),p&&I&&n.push(I);const x=g.length>0?Zs(g):100,$=n.length>0?Zs(n):10,Re=0,Ie=19.8,H=29.7,D=30,L=(x+$)/2+D,q=L-177.3<0?0:1,j=.024*L+.11*(L-177.3)*q,X=93.2-(Re+Ie*Math.log(1+H*v)+j);return to(X)};class Zv{constructor(s,i){this._callbacks={onreport:null,onticket:null},this._id=Ov(),this._moduleName=this._id,this._probeId=i,this._config=s,this._exporter=new Mv(s),this._state=Ss.IDLE,this.registerToPCEvents(),Pn(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(s,i,l,a){const _=(g,n)=>g===M.AUDIO?n===zt.INBOUND_RTP?{...U_}:{...P_}:n===zt.INBOUND_RTP?{...x_}:{...M_},e=Cv(i);e.pname=this._config.pname,e.call_id=this._config.cid,e.user_id=this._config.uid,e.count=i?i.count+1:1;let p=null;return s.forEach(g=>{!p&&g.timestamp&&(p=g.timestamp),Yv(g,e,e.pname,a).forEach(v=>{if(v.value&&v.type)if(v.ssrc){let S=e[v.type][v.ssrc];S||(S=_(v.type,g.type),S.ssrc=v.ssrc,e[v.type][v.ssrc]=S),Object.keys(v.value).forEach(m=>{S[m]=v.value[m]})}else Object.keys(v.value).forEach(S=>{e[v.type][S]=v.value[S]})})}),e.timestamp=p,Object.keys(e[M.AUDIO]).forEach(g=>{const n=e[M.AUDIO][g];n.direction===qe.INBOUND?(n.mos_emodel_in=Jv(e,M.AUDIO,i,l,n.ssrc),n.mos_in=Xv(e,M.AUDIO,i,l,n.ssrc)):(n.mos_emodel_out=zv(e,M.AUDIO,i,l,n.ssrc),n.mos_out=Qv(e,M.AUDIO,i,l,n.ssrc))}),e}async takeReferenceStats(){return new Promise((s,i)=>{const l=Date.now();setTimeout(async()=>{try{const a=Date.now()-l,_=Date.now(),e=await this._config.pc.getStats(),p=this.analyze(e,null,null,null),g=Date.now();p.experimental.time_to_measure_ms=g-_,p.experimental.time_to_wait_ms=a,this._exporter.saveReferenceReport(p),ke(this._moduleName,`got reference report for probe ${this._probeId}`),s()}catch(a){i(a)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==Ss.RUNNING||!this._config.pc)return ke(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const s=Date.now(),i=await this._config.pc.getStats(),l=this.analyze(i,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),a=Date.now();return l.experimental.time_to_measure_ms=a-s,this._exporter.addReport(l),ke(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(l),l}catch(s){return ir(this._moduleName,`got error ${s}`),null}}async start(){ke(this._moduleName,"starting"),this.state=Ss.RUNNING,this._startedTime=this._exporter.start(),ke(this._moduleName,"started")}async mute(){this.state=Ss.MUTED,ke(this._moduleName,"muted")}async unmute(){this.state=Ss.RUNNING,ke(this._moduleName,"unmuted")}async stop(s){if(ke(this._moduleName,`stopping${s?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=Ss.IDLE,this._config.ticket){const{ticket:i}=this._exporter;this.fireOnTicket(i)}this._exporter.reset(),ke(this._moduleName,"stopped")}registerCallback(s,i,l){s in this._callbacks?(this._callbacks[s]={callback:i,context:l},ke(this._moduleName,`registered callback '${s}'`)):ir(this._moduleName,`can't register callback for '${s}' - not found`)}unregisterCallback(s){s in this._callbacks?(this._callbacks[s]=null,delete this._callbacks[s],ke(this._moduleName,`unregistered callback '${s}'`)):ir(this._moduleName,`can't unregister callback for '${s}' - not found`)}fireOnReport(s){this._callbacks.onreport&&wu(this._callbacks.onreport.callback,this._callbacks.onreport.context,s)}fireOnTicket(s){this._callbacks.onticket&&wu(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,ke(this._moduleName,`state changed to ${s}`)}addCustomEvent(s,i,l,a){this._exporter.addCustomEvent({at:typeof s=="object"?s.toJSON():s,category:i,name:l,description:a})}async registerToPCEvents(){const{pc:s}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const i=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${i.length} devices found`,"Media Devices state")}catch{ir(this._moduleName,"can't get devices")}},s){s.oniceconnectionstatechange=()=>{const l=s.iceConnectionState;l===Bi.CONNECTED||l===Bi.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",l,"ICE connection state"):l===Bi.DISCONNECTED||l===Bi.FAILED?this.addCustomEvent(new Date().toJSON(),"call",l,"ICE connection state"):l===Bi.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},s.onicegatheringstatechange=()=>{const l=s.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",l,"ICE gathering state")},s.ontrack=l=>{this.addCustomEvent(new Date().toJSON(),"call",`${l.track.kind}track`,"MediaStreamTrack received")},s.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const i=s.getReceivers();if(i&&i.length>0){const l=i[0],{transport:a}=l;if(a){const{iceTransport:_}=a;_&&(_.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class eE{constructor(s){this._id=s.pname&&s.pname.substr(0,12).padEnd(12," ")||wv(),this._moduleName=this._id,Pn(this._moduleName,"probe created"),this._config=s,this._collector=new Zv(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,i,l,a=new Date().toJSON()){this._collector.addCustomEvent(a,i,s,l)}get isRunning(){return this._collector.state===Ss.RUNNING}get isIdle(){return this._collector.state===Ss.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){Ma(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 wt="engine ";class tE{constructor(s){this._config=s,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},Pn(wt,`configured for probing every ${this._config.refreshEvery}ms`),Pn(wt,`configured for starting after ${this._config.startAfter}ms`),Pn(wt,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),ke(wt,"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,i){if(!s)throw new Error("undefined peer connection");const l=Iv(s,i,this._config),a=new eE(l);return this._probes.push(a),ke(wt,`${this._probes.length} probes registered`),a}removeExistingProbe(s){if(!s)throw new Error("undefined probe");s.state===Ss.RUNNING&&s.stop(),this._probes=this._probes.filter(i=>s.id!==i.id)}async start(){const s=()=>{this._probes.forEach(_=>_.start())},i=async()=>Promise.all(this._probes.map(_=>_.takeReferenceStats())),l=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,a=async()=>{const _=Av(),e=this._probes.filter(p=>p.isRunning);for(const p of e){const g=await p.collectStats();g&&_.probes.push(g),ke(wt,`got probe ${p.id}`),await kf(0)}return _.delta_time_to_measure_probes_ms=wn(_.probes,"experimental","time_to_measure_ms"),_.delta_KBytes_in=wn(_.probes,"data","delta_KBytes_in"),_.delta_KBytes_out=wn(_.probes,"data","delta_KBytes_out"),_.delta_kbs_in=wn(_.probes,"data","delta_kbs_in"),_.delta_kbs_out=wn(_.probes,"data","delta_kbs_out"),_.total_time_decoded_in=wn(_.probes,"video","total_time_decoded_in"),_.total_time_encoded_out=wn(_.probes,"video","total_time_encoded_out"),_};for(ke(wt,"starting to collect"),s(),ke(wt,"generating reference reports..."),await i(),ke(wt,"reference reports generated"),this._startedTime=Date.now();l();)if(ke(wt,`wait ${this._config.refreshEvery}ms before collecting`),await kf(this._config.refreshEvery),l()){ke(wt,"collecting...");const _=Date.now(),e=await a(),p=Date.now();e.delta_time_consumed_to_measure_ms=p-_,this.fireOnReports(e),ke(wt,"collected")}ke(wt,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(s){const i=l=>{this._probes.forEach(a=>{a.stop(l)})};Pn(wt,"stop collecting"),i(s)}registerCallback(s,i,l){s in this._callbacks?(this._callbacks[s]={callback:i,context:l},ke(wt,`registered callback '${s}'`)):ir(wt,`can't register callback for '${s}' - not found`)}unregisterCallback(s){s in this._callbacks?(this._callbacks[s]=null,delete this._callbacks[s],ke(this._moduleName,`unregistered callback '${s}'`)):ir(this._moduleName,`can't unregister callback for '${s}' - not found`)}fireOnReports(s){this._callbacks.onresult&&s.probes.length>0&&wu(this._callbacks.onresult.callback,this._callbacks.onresult.context,s)}}const sE="interface ";class nE{constructor(s){this._config=bv(s),Pn(sE,`welcome to ${this._config.name} version ${this._config.version}`),pv(this._config.verbose||!1),this._engine=new tE(this._config)}setupLogLevel(s){mv(s)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(s,i){return this._engine.addNewProbe(s,i)}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 rE(c,s){return Object.keys(c).filter(i=>s.includes(i)).reduce((i,l)=>{const a=l;return{...i,[a]:c[a]}},{})}const iE=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"];class lE{constructor(s){this.intervals={},this.emitInterval=s.emitInterval||200,this.onChangeFunction=s.onChangeFunction}start(s,i){s&&s.getTracks().length&&requestAnimationFrame(()=>this.beginCalculation(s,i))}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,i){this.clearVolumeInterval(i);const l=Un.createAnalyser(),a=Un.createMediaStreamSource(s),_=Un.createScriptProcessor(2048,1,1);l.smoothingTimeConstant=.8,l.fftSize=1024,a.connect(l),l.connect(_),_.connect(Un.destination),this.intervals[i]=setInterval(()=>{const e=new Uint8Array(l.frequencyBinCount);l.getByteFrequencyData(e);let p=0;const g=e.length;for(let v=0;v<g;v++)p+=e[v];const n=p/g;this.onChangeFunction(i,n)},this.emitInterval)}}const Sa={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},aE=0;class oE{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 lE({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 O_()?{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(Sa.SELECTED_INPUT_DEVICE)||"default",i=localStorage.getItem(Sa.SELECTED_OUTPUT_DEVICE)||"default";try{const l=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),a=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(a),await this.setMicrophone(s),await this.setSpeaker(i),navigator.mediaDevices.addEventListener("devicechange",async()=>{const _=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(_)}),l.getTracks().forEach(_=>_.stop())}catch(l){console.error(l)}}setCallTime(s){const i={...s};delete i.callId,this.callTime={...this.callTime,[s.callId]:i},this.context.emit("changeCallTime",this.callTime)}removeCallTime(s){const i={...this.callTime};delete i[s],this.callTime={...i},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(s,i){this.timeIntervals={...this.timeIntervals,[s]:i}}removeTimeInterval(s){const i={...this.timeIntervals};i[s]&&(clearInterval(i[s]),delete i[s],this.timeIntervals={...i})}stopCallTimer(s){this.removeTimeInterval(s),this.removeCallTime(s)}emitVolumeChange(s,i){this.context.emit("changeCallVolume",{callId:s,volume:i})}setMetricsConfig(s){this.metricConfig={...this.metricConfig,...s}}sendDTMF(s,i){if(!/^[A-D0-9]+$/g.test(i))throw new Error("Not allowed character in DTMF input");this.extendedCalls[s].sendDTMF(i)}setIsMuted(s){this.muted=s,this.context.emit("changeIsMuted",s)}processMute(s){const i=this.currentActiveRoomId;this.setIsMuted(s),this.initialStreamValue.getTracks().forEach(l=>l.enabled=!s),this.roomReconfigure(i)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:s,toHold:i,automatic:l}){const a=this.extendedCalls[s];a._automaticHold=l??!1,await new Promise(p=>{const g=()=>{p()};i?a.hold({},g):a.unhold({},g)}),this.updateCall(a);const e=Object.values(this.extendedCalls).filter(p=>p.roomId===this.currentActiveRoomId&&(i?s!==p._id:!0));e.length>1&&await this.doConference(e)}holdCall(s,i=!1){return this.processHold({callId:s,automatic:i,toHold:!0})}unholdCall(s){return this.processHold({callId:s,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(s=>s.direction==="outgoing"&&s.status===aE).forEach(s=>this.terminateCall(s._id))}answerCall(s){const i=this.extendedCalls[s];this.cancelAllOutgoingUnanswered(),i.answer(this.sipOptions),this.updateCall(i),this.setActiveRoom(i.roomId),i.connection.addEventListener("track",l=>{this.triggerAddStream(l,i)})}async moveCall(s,i){this.updateCallStatus({callId:s,isMoving:!0}),await this.processRoomChange({callId:s,roomId:i}),this.updateCallStatus({callId:s,isMoving:!1})}updateCall(s){this.activeCalls[s._id]=Uf(s),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(s){const l={...this.activeRooms[s.roomId],...s};this.activeRooms={...this.activeRooms,[s.roomId]:{...l}},this.context.emit("updateRoom",{room:l,roomList:this.activeRooms})}hasAutoAnswerHeaders(s){const i=/answer-after=0/,a=s.request.getHeader("Call-Info");return a&&i.test(a)}addCall(s,i=!0){this.activeCalls={...this.activeCalls,[s._id]:Uf(s)},this.extendedCalls[s._id]=s,i&&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 l={...{...this.callStatus[s.callId]}};s.isMoving!==void 0&&(l.isMoving=s.isMoving),s.isTransferring!==void 0&&(l.isTransferring=s.isTransferring),s.isMerging!==void 0&&(l.isMerging=s.isMerging),this.callStatus={...this.callStatus,[s.callId]:{...l}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(s){const i={...this.callStatus};delete i[s],this.callStatus={...i},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=xf(this.initialStreamValue,this.microphoneInputLevel*2);return s.getTracks().forEach(i=>i.enabled=!this.isMuted),this.setActiveStream(s),s}async setMicrophone(s){if(!this.getInputDeviceList.find(({deviceId:l})=>l===s)||(this.setSelectedInputDevice(s),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const i=Object.values(this.extendedCalls).filter(l=>l.roomId===this.currentActiveRoomId);i.length===1?Object.values(i).forEach(async l=>{const a=this.getActiveStream();l.connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.updateCall(l)}):await this.doConference(i)}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 i=Object.values(this.extendedCalls);if(i.length===0)return;const l=i.filter(a=>a.roomId===this.currentActiveRoomId);l.length===1?i.forEach(a=>{var _;(_=a.audioTag)==null||_.setSinkId(s),this.updateCall(a)}):await this.doConference(l)}removeRoom(s){const i={...this.activeRooms},l={...i[s]};delete i[s],this.activeRooms={...i},this.context.emit("removeRoom",{room:l,roomList:this.activeRooms})}deleteRoomIfEmpty(s){s!==void 0&&Object.values(this.extendedCalls).filter(i=>i.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 l;if(s===void 0)return;const i=Object.values(this.extendedCalls).filter(a=>a.roomId===s);if(this.currentActiveRoomId===s?i.forEach(a=>{a.audioTag&&(this.muteReconfigure(a),a.audioTag.muted=!1,this.updateCall(a))}):i.forEach(a=>{a.audioTag&&(a.audioTag.muted=!0,this.updateCall(a))}),i.length===0)this.deleteRoomIfEmpty(s);else if(i.length===1&&this.currentActiveRoomId!==s)i[0].isOnHold().local||await this.holdCall(i[0].id,!0);else if(i.length===1&&this.currentActiveRoomId===s){if(i[0].isOnHold().local&&i[0]._automaticHold&&await this.unholdCall(i[0].id),i[0].connection&&((l=i[0].connection)!=null&&l.getSenders()[0])){const a=this.getActiveStream();await i[0].connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.muteReconfigure(i[0])}}else i.length>1&&await this.doConference(i)}async doConference(s){const i=[];s.forEach(l=>{l!=null&&l.connection.getReceivers().forEach(a=>{i.push(a.track)})}),await hv.forEach(s,async l=>{var e;if(l==null)return;const a=new MediaStream,_=Un.createMediaStreamDestination();if(l.connection.getReceivers().forEach(p=>{i.forEach(g=>{a.addTrack(p.track),p.track.id!==g.id&&Un.createMediaStreamSource(new MediaStream([g])).connect(_)})}),s[0].roomId===this.currentActiveRoomId){const p=this.getActiveStream();Un.createMediaStreamSource(p).connect(_)}(e=l.connection)!=null&&e.getSenders()[0]&&(await l.connection.getSenders()[0].replaceTrack(_.stream.getTracks()[0]),this.muteReconfigure(l))})}processCallerMute(s,i){const l=this.extendedCalls[s];l&&l.connection.getReceivers().length&&(l.localMuted=i,l.connection.getReceivers().forEach(a=>{a.track.enabled=!i}),this.updateCall(l))}muteCaller(s){this.processCallerMute(s,!0)}unmuteCaller(s){this.processCallerMute(s,!1)}terminateCall(s){const i=this.extendedCalls[s];i._status!==8&&i.terminate()}transferCall(s,i){if(i.toString().length===0)return new Error("Target must be passed");const l=this.extendedCalls[s];if(!l._is_confirmed&&!l._is_canceled){const a=`sip:${i}@${this.context.sipDomain}`;l.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${a}`]});return}this.updateCallStatus({callId:s,isTransferring:!0}),l.refer(`sip:${i}@${this.context.sipDomain}`),this.updateCall(l)}mergeCall(s){const i=Object.values(this.extendedCalls).filter(_=>_.roomId===s);if(i.length!==2)return;const l=i[0],a=i[1];!l||!a||(this.updateCallStatus({callId:l._id,isMerging:!0}),this.updateCallStatus({callId:a._id,isMerging:!0}),l.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(l))}mergeCallByIds(s,i){const l=Object.values(this.extendedCalls).find(_=>_._id===s),a=Object.values(this.extendedCalls).find(_=>_._id===i);if(!l||!a)throw new Error("Call ID is not provided");this.updateCallStatus({callId:s,isMerging:!0}),this.updateCallStatus({callId:i,isMerging:!0}),l.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(l)}setDND(s){this.isDNDEnabled=s,this.context.emit("changeIsDND",s)}startCallTimer(s){this.removeTimeInterval(s);const i={callId:s,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(i);const l=setInterval(()=>{const a={...this.callTime[s]},_=cv(a);this.setCallTime({callId:s,..._})},1e3);this.setTimeInterval(s,l)}async setActiveRoom(s){const i=this.currentActiveRoomId;s!==i&&(this.currentActiveRoomId=s,await this.roomReconfigure(i),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 n,v;const i=s.session;if(this.getActiveCalls[i.id]!==void 0)return;const a=this.getNewRoomId(),_={started:new Date,incomingInProgress:!1,roomId:a};i.direction==="incoming"?(this.context.logger.log("New incoming call from",(v=(n=i._remote_identity)==null?void 0:n._uri)==null?void 0:v._user),_.incomingInProgress=!0,this.context.subscribe(Xt.CALL_CONFIRMED,S=>{i.id===S.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.startCallTimer(i.id))}),this.context.subscribe(Xt.CALL_FAILED,S=>{i.id===S.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.deleteRoomIfEmpty(a))})):i.direction==="outgoing"&&(i.once("confirmed",()=>{this.startCallTimer(i.id)}),this.startCallTimer(i.id));const e=i,p=this.hasAutoAnswerHeaders(s),g=e.direction==="incoming"&&!this.hasActiveCalls&&(p||this.autoAnswer);e.roomId=a,e.localMuted=!1,e.autoAnswer=g,g?this.addCall(e,!1):this.addCall(e),this.addCallStatus(i.id),this.addRoom(_),g&&this.answerCall(e._id)}removeCall(s){const i={...this.activeCalls};delete i[s],this.activeCalls={...i};const l={...this.extendedCalls};delete l[s],this.extendedCalls={...l},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(s){var a;const i=this.extendedCalls[s._id];this.stopVUMeter("origin"),(a=i.connection)==null||a.getSenders().forEach(_=>{_.track.stop()});const l=i.roomId;this.removeCall(s._id),this.roomReconfigure(l)}async newRTCSessionCallback(s){const i=s.session;if(this.isDND){i.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(this.context.triggerListener({listenerType:Xt.NEW_CALL,session:i,event:s}),i.on("ended",l=>{var _,e,p;this.stopVUMeter(i.id),this.context.logger.log("Session ended for",(e=(_=i._remote_identity)==null?void 0:_._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Xt.CALL_ENDED,session:i,event:l});const a=this.getActiveCalls[i.id];a&&this.activeCallListRemove(a),this.stopCallTimer(i.id),this.removeCallStatus(i.id),this.removeCallMetrics(i.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(p=this.initialStreamValue)==null||p.getTracks().forEach(g=>g.stop()),this.initialStreamValue=null)}),i.on("progress",l=>{var a,_;this.context.logger.log("Session in progress for",(_=(a=i._remote_identity)==null?void 0:a._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Xt.CALL_PROGRESS,session:i,event:l})}),i.on("failed",l=>{var _,e,p;this.stopVUMeter(i.id),this.context.logger.log("Session failed for",(e=(_=i._remote_identity)==null?void 0:_._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Xt.CALL_FAILED,session:i,event:l}),i.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const a=this.getActiveCalls[i.id];a&&this.activeCallListRemove(a),this.stopCallTimer(i.id),this.removeCallStatus(i.id),this.removeCallMetrics(i.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(p=this.initialStreamValue)==null||p.getTracks().forEach(g=>g.stop()),this.initialStreamValue=null)}),i.on("confirmed",l=>{var a,_;this.context.logger.log("Session confirmed for",(_=(a=i._remote_identity)==null?void 0:a._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Xt.CALL_CONFIRMED,session:i,event:l}),this.updateCall(i),i.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(s),i.direction==="outgoing"){const l=this.getActiveCalls[i.id].roomId;this.setActiveRoom(l)}}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(i=>{i.audioTag&&(i.audioTag.volume=s,this.updateCall(i))})}setAutoAnswer(s){this.isAutoAnswer=s}setSelectedInputDevice(s){localStorage.setItem(Sa.SELECTED_INPUT_DEVICE,s),this.selectedMediaDevices.input=s,this.context.emit("changeActiveInputMediaDevice",s)}setSelectedOutputDevice(s){localStorage.setItem(Sa.SELECTED_OUTPUT_DEVICE,s),this.selectedMediaDevices.output=s,this.context.emit("changeActiveOutputMediaDevice",s)}setCallMetrics(s){const i={...s};delete i.callId,this.callMetrics={...this.callMetrics,[s.callId]:i},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(s){const i={...this.callMetrics};delete i[s],this.callMetrics={...i},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(s){const i=new nE(this.metricConfig),l=i.createProbe(s.connection,{cid:s._id}),a=[];let _;l.onreport=e=>{Object.entries(e.audio).forEach(([n,v])=>{v.direction==="inbound"&&!a.includes(n)&&(a.push(n),_=n)});const p=e.audio[_];if(!p)return;const g=rE(p,iE);g.callId=s._id,this.setCallMetrics(g)},this.context.subscribe(Xt.CALL_ENDED,e=>{e._id===s._id&&i.stopAllProbes()}),i.startAllProbes()}setupVUMeter(s,i){this.VUMeter.start(s,i)}stopVUMeter(s){this.VUMeter.stop(s)}async setupStream(){const s=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach(i=>i.stop()),this.initialStreamValue=null),this.initialStreamValue=s}async triggerAddStream(s,i){this.setIsMuted(this.muteWhenJoin||this.isMuted),this.initialStreamValue||await this.setupStream();const l=xf(this.initialStreamValue,this.microphoneInputLevel*2),a=this.isMuted||this.muteWhenJoin;l.getTracks().forEach(e=>e.enabled=!a),this.setActiveStream(l),await i.connection.getSenders()[0].replaceTrack(l.getTracks()[0]);const _=new MediaStream([s.track]);YT(_,i,this.selectedOutputDevice,this.speakerVolume),this.setupVUMeter(_,i._id),this.getCallQuality(i),this.updateCall(i)}initCall(s,i){if(s.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${s}@${this.context.sipDomain}...`);const l=this.context.call(`sip:${s}@${this.context.sipDomain}`,this.sipOptions);this.callAddingInProgress=l.id,i&&this.currentActiveRoomId!==void 0&&this.processRoomChange({callId:l.id,roomId:this.currentActiveRoomId}),l.connection.addEventListener("track",a=>{this.triggerAddStream(a,l)})}async processRoomChange({callId:s,roomId:i}){const l=this.extendedCalls[s].roomId;this.extendedCalls[s].roomId=i;const a=this.extendedCalls[s];return this.updateCall(a),await this.setActiveRoom(i),Promise.all([this.roomReconfigure(l),this.roomReconfigure(i)]).then(()=>{this.deleteRoomIfEmpty(l),this.deleteRoomIfEmpty(i)})}}class uE{constructor(s){this.context=s}get sipOptions(){return{...this.context.options.sipOptions}}initCall(s,i){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}`,i,this.sipOptions)}stop(s={}){this.context.terminateJanusSessions(s)}}class cE{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 i=this.extendedMessages[s];this.updateMSRPSession(i)}updateMSRPSession(s){this.activeMessages[s._id]=Pf(s),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(s){this.activeMessages={...this.activeMessages,[s._id]:Pf(s)},this.extendedMessages[s._id]=s,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(s,i){const l=this.msrpHistory[i.id]||[];l.push(s),this.msrpHistory={...this.msrpHistory,[i.id]:[...l]},this.context.emit("newMSRPMessage",{message:s,session:i})}messageTerminate(s){const i=this.extendedMessages[s];i._status!==8&&i.terminate()}addMessageSession(s){if(!s._id||this.getActiveMessages[s._id]!==void 0)return;const l=s;this.addMMSRPSession(l)}triggerMSRPListener({listenerType:s,session:i,event:l}){const a=this.context.listenersList[s];!a||!a.length||a.forEach(_=>{_(i,l)})}removeMMSRPSession(s){const i={...this.activeMessages};delete i[s],this.activeMessages={...i};const l={...this.extendedMessages};delete l[s],this.extendedMessages={...l},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(s){this.removeMMSRPSession(s._id)}newMSRPSessionCallback(s){const i=s.session;i.on("ended",l=>{this.triggerMSRPListener({listenerType:Xt.CALL_ENDED,session:i,event:l});const a=this.getActiveMessages[i.id];this.activeMessageListRemove(a)}),i.on("failed",l=>{this.triggerMSRPListener({listenerType:Xt.CALL_FAILED,session:i,event:l});const a=this.getActiveMessages[i.id];this.activeMessageListRemove(a)}),i.on("confirmed",l=>{this.triggerMSRPListener({listenerType:Xt.CALL_CONFIRMED,session:i,event:l}),this.updateMSRPSession(i)}),i.on("newMessage",l=>{this.addMSRPMessage(l,i)}),this.addMessageSession(i)}setIsMSRPInitializing(s){this.isMSRPInitializingValue=s,this.context.emit("isMSRPInitializingChanged",s)}initMSRP(s,i,l){if(s.length===0)return console.error("Target must be a valid string");const a=this.context.startMSRP(s,l);a.on("active",()=>{this.addMessageSession(a),a.sendMSRP(i),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(s,i){const l=this.extendedMessages[s];if(!l)throw new Error(`MSRP session with id ${s} doesn't exist!`);l.sendMSRP(i)}}const ou={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class fE extends jT{constructor(s,i){if(!s.modules.length)throw new Error("options.modules should include at least 1 module");const l={...s.configuration,sockets:s.socketInterfaces.map(a=>new uv.WebSocketInterface(a))};super(l),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().setExtraContactUriParams(s.pnExtraHeaders),this.options=s,this.modules=s.modules,i&&JT(i)&&(this.logger=i)}on(s,i){return super.on(s,i)}off(s,i){return super.off(s,i)}emit(s,i){return super.emit(s,i)}get sipDomain(){return this.options.sipDomain}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(ou.AUDIO)&&(this.audio=new oE(this)),this.modules.includes(ou.MSRP)&&(this.msrp=new cE(this)),this.modules.includes(ou.VIDEO)&&(this.video=new uE(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,i){const a=!this.listenersList[s]||!this.listenersList[s].length?[i]:[...this.listenersList[s],i];this.listenersList={...this.listenersList,[s]:a}}removeIListener(s){const i={...this.listenersList};delete i[s],this.listenersList={...i}}triggerListener({listenerType:s,session:i,event:l}){const a=this.listenersList[s];!a||!a.length||a.forEach(_=>{_(i,l)})}setInitialized(s){this.initialized=s,this.emit("ready",s)}}module.exports=fE;
|
158
|
+
`,i),a===-1)return a;!c.substring(a+2,a+4).match(/(^\r\n)/)&&c.charAt(a+2).match(/(^\s+)/)?i=a+2:l=a}return l}function LT(c,s,i,l){let a;const _=s.indexOf(":",i),e=s.substring(i,_).trim(),p=s.substring(_+1,l).trim();switch(e.toLowerCase()){case"via":case"v":c.addHeader("via",p),c.getHeaders("via").length===1?(a=c.parseHeader("Via"),a&&(c.via=a,c.via_branch=a.branch)):a=0;break;case"from":case"f":c.setHeader("from",p),a=c.parseHeader("from"),a&&(c.from=a,c.from_tag=a.getParam("tag"));break;case"to":case"t":c.setHeader("to",p),a=c.parseHeader("to"),a&&(c.to=a,c.to_tag=a.getParam("tag"));break;case"record-route":if(a=Iu.parse(p,"Record_Route"),a===-1)a=void 0;else for(const g of a)c.addHeader("record-route",p.substring(g.possition,g.offset)),c.headers["Record-Route"][c.getHeaders("record-route").length-1].parsed=g.parsed;break;case"call-id":case"i":c.setHeader("call-id",p),a=c.parseHeader("call-id"),a&&(c.call_id=p);break;case"contact":case"m":if(a=Iu.parse(p,"Contact"),a===-1)a=void 0;else for(const g of a)c.addHeader("contact",p.substring(g.possition,g.offset)),c.headers.Contact[c.getHeaders("contact").length-1].parsed=g.parsed;break;case"content-length":case"l":c.setHeader("content-length",p),a=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",p),a=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",p),a=c.parseHeader("cseq"),a&&(c.cseq=a.value),c instanceof Dn.IncomingResponse&&(c.method=a.method);break;case"max-forwards":c.setHeader("max-forwards",p),a=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",p),a=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",p),a=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",p),a=c.parseHeader("session-expires"),a&&(c.session_expires=a.expires,c.session_expires_refresher=a.refresher);break;case"refer-to":case"r":c.setHeader("refer-to",p),a=c.parseHeader("refer-to"),a&&(c.refer_to=a);break;case"replaces":c.setHeader("replaces",p),a=c.parseHeader("replaces"),a&&(c.replaces=a);break;case"event":case"o":c.setHeader("event",p),a=c.parseHeader("event"),a&&(c.event=a);break;default:c.addHeader(e,p),a=0}return a===void 0?{error:`error parsing header "${e}"`}:!0}const $T={parseMessage:MT},Vi=new Za("Registrator"),va=10;class HT{constructor(s,i){this._reg_id=1,this._ua=s,this._transport=i,this._registrar=s.configuration.registrar_server,this._expires=s.configuration.register_expires,this._call_id=ys.createRandomToken(22),this._cseq=0,this._to_uri=s.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const l=this._contact.indexOf(">");if(l!==-1){const a=this._contact.slice(0,l)+this._contact.slice(l+1,this._contact.length);this._contact=a}this._extra_contact="",this._extraContactParams="",this._extra_contact+=";+sip.ice",this._extraHeaders=[],this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._extra_contact+=`;reg-id=${this._reg_id}`,this._extra_contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(s){Array.isArray(s)||(s=[]),this._extraHeaders=s.slice()}setExtraContactParams(s){s instanceof Object||(s={}),this._extraContactParams="";for(const i in s)if(Object.prototype.hasOwnProperty.call(s,i)){const l=s[i];this._extraContactParams+=`;${i}`,l&&(this._extraContactParams+=`=${l}`)}}setExtraContactUriParams(s){s instanceof Object||(s={}),this._extraContactParams="";for(const i in s)if(Object.prototype.hasOwnProperty.call(s,i)){const l=s[i];this._extraContactParams+=`;${i}`,l&&(this._extraContactParams+=`=${l}`)}}register(){if(this._registering){Vi.debug("Register request in progress...");return}const s=this._extraHeaders.slice();s.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),s.push(`Expires: ${this._expires}`);const i=new Dt.OutgoingRequest(F.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},s),l=new Ga(this._ua,i,{onRequestTimeout:()=>{this._registrationFailure(null,F.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,F.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:a=>{if(a.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):{if(this._registering=!1,!a.hasHeader("Contact")){Vi.debug("no Contact header in response to REGISTER, response ignored");break}const _=a.headers.Contact.reduce((n,v)=>n.concat(v.parsed),[]);let e=_.find(n=>this._sipInstance===n.getParam("+sip.instance")&&this._reg_id===parseInt(n.getParam("reg-id")));if(e||(e=_.find(n=>n.uri.user===this._ua.contact.uri.user)),!e){Vi.debug("no Contact header pointing to us, response ignored");break}let p=e.getParam("expires");!p&&a.hasHeader("expires")&&(p=a.getHeader("expires")),p||(p=this._expires),p=Number(p),p<va&&(p=va);const g=p>64?p*1e3/2+Math.floor((p/2-32)*1e3*Math.random()):p*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},g),e.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=e.getParam("temp-gruu").replace(/"/g,"")),e.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=e.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:a}));break}case/^423$/.test(a.status_code):{a.hasHeader("min-expires")?(this._expires=Number(a.getHeader("min-expires")),this._expires<va&&(this._expires=va),this.register()):(Vi.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(a,F.causes.SIP_FAILURE_CODE));break}default:{const _=ys.sipErrorCause(a.status_code);this._registrationFailure(a,_)}}}});this._registering=!0,l.send()}unregister(s={}){if(!this._registered){Vi.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const i=this._extraHeaders.slice();s.all?i.push(`Contact: *${this._extraContactParams}`):i.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),i.push("Expires: 0");const l=new Dt.OutgoingRequest(F.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},i);new Ga(this._ua,l,{onRequestTimeout:()=>{this._unregistered(null,F.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,F.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:_=>{switch(!0){case/^1[0-9]{2}$/.test(_.status_code):break;case/^2[0-9]{2}$/.test(_.status_code):this._unregistered(_);break;default:{const e=ys.sipErrorCause(_.status_code);this._unregistered(_,e)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(s,i){this._registering=!1,this._ua.registrationFailed({response:s||null,cause:i}),this._registered&&(this._registered=!1,this._ua.unregistered({response:s||null,cause:i}))}_unregistered(s,i){this._registering=!1,this._registered=!1,this._ua.unregistered({response:s||null,cause:i||null})}}const ft=console,Xs={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},FT=IT;class jT extends FT{constructor(s){super(s),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this._registrator=new HT(this)}call(s,i){return super.call(s,i)}joinVideoCall(s,i,l){ft.debug("call()");const a=new Wa(this);return a.connect(s,i,l),a}_loadConfig(s){try{el.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=ys.newUUID()),this._configuration.jssip_id=ys.createRandomToken(5);const i=this._configuration.uri.clone();i.user=null,this._configuration.hostport_params=i.toString().replace(/^sip:/i,"");try{this._transport=new Qg(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=qT.bind(this),this._transport.onconnect=VT.bind(this),this._transport.ondisconnect=BT.bind(this),this._transport.ondata=GT.bind(this)}catch(a){throw ft.warn(a),new zs.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 ar("sip",ys.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 _=a.anonymous||null,e=a.outbound||null;let p="<";return _?p+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":p+=this.pub_gruu||this.uri.toString(),e&&(_?!this.temp_gruu:!this.pub_gruu)&&(p+=";ob"),p+=">",p}};const l=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const a in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,a)&&(l.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(el.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,i){s.on("msgHistoryUpdate",l=>{console.log(l)}),this._msrp_sessions[s.id]=s,this.emit("newMSRPSession",i)}newJanusSession(s,i){this._janus_sessions[s.id]=s,this.emit("newJanusSession",i)}destroyMSRPSession(s){delete this._msrp_sessions[s.id]}destroyJanusSession(s){delete this._janus_sessions[s.id]}receiveRequest(s){var _,e,p,g;const i=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!==Me.ACK&&s.reply_sl(404);return}if(s.ruri.scheme===Me.SIPS){s.reply_sl(416);return}if(Vt.checkTransaction(this,s))return;if(i===Me.INVITE?new Vt.InviteServerTransaction(this,this._transport,s):i!==Me.ACK&&i!==Me.CANCEL&&new Vt.NonInviteServerTransaction(this,this._transport,s),i===Me.OPTIONS){if(this.listeners("newOptions").length===0){s.reply(200);return}new Qc.Options(this).init_incoming(s)}else if(i===Me.MESSAGE){if(this.listeners("newMessage").length===0){s.reply(405);return}new Qc.Message(this).init_incoming(s)}else if(i===Me.INVITE&&!s.to_tag&&this.listeners("newRTCSession").length===0){s.reply(405);return}let l,a;if(s.to_tag)if(l=this._findDialog(s.call_id,s.from_tag,s.to_tag),l)l.receiveRequest(s);else if(i===Me.NOTIFY)if(a=this._findSession(s),a)a.receiveRequest(s);else{if(s.body)try{const n=JSON.parse(s.body)||{};(e=(_=n.plugindata)==null?void 0:_.data)!=null&&e.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(n),(g=(p=n.plugindata)==null?void 0:p.data)!=null&&g.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(n.plugindata.data.unpublished)}catch(n){console.error(n)}s.reply(200)}else i!==Me.ACK&&s.reply(481);else switch(i){case Me.INVITE:if(window.RTCPeerConnection)if(s.hasHeader("replaces")){const n=s.replaces;l=this._findDialog(n.call_id,n.from_tag,n.to_tag),l?(a=l.owner,a.isEnded()?s.reply(603):a.receiveRequest(s)):s.reply(481)}else s.body.search(/MSRP/ig)>-1?(a=new nu(this),a.init_incoming(s)):s.body.search(/JANUS/ig)>-1||(a=new kg(this),a.init_incoming(s));else ft.warn("INVITE received but WebRTC is not supported"),s.reply(488);break;case Me.BYE:s.reply(481);break;case Me.CANCEL:a=this._findSession(s),a?a.receiveRequest(s):ft.debug("received CANCEL request for a non existent session");break;case Me.ACK:break;case Me.NOTIFY:this.emit("sipEvent",{event:s.event,request:s}),s.reply(200);break;default:s.reply(405);break}}startMSRP(s,i){ft.debug("startMSRP()",i);const l=new nu(this);return l.connect(s),l}startJanus(s,i){ft.debug("startJanus()",i);const l=new nu(this);return l.connect(s),l}terminateMSRPSessions(s){ft.debug("terminateSessions()");for(const i in this._msrp_sessions)this._msrp_sessions[i].isEnded()||this._msrp_sessions[i].terminate(s)}terminateJanusSessions(s){ft.debug("terminateSessions()");for(const i in this._janus_sessions)this._janus_sessions[i].isEnded()||this._janus_sessions[i].terminate(s)}stop(){if(ft.debug("stop()"),this._dynConfiguration={},this._status===Xs.STATUS_USER_CLOSED){ft.debug("UA already closed");return}this._registrator.close();const s=Object.keys(this._sessions).length;for(const l in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,l)){ft.debug(`closing session ${l}`);try{this._sessions[l].terminate()}catch(a){console.error(a)}}for(const l in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,l)){ft.debug(`closing session ${l}`);try{this._msrp_sessions[l].terminate()}catch(a){console.error(a)}}for(const l in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,l)){ft.debug(`closing session ${l}`);try{this._janus_sessions[l].terminate()}catch(a){console.error(a)}}for(const l in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,l))try{this._applicants[l].close()}catch(a){console.error(a)}this._status=Xs.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 qT(c){this.emit("connecting",c)}function VT(c){this._status!==Xs.STATUS_USER_CLOSED&&(this._status=Xs.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function BT(c){const s=["nict","ict","nist","ist"];for(const i of s)for(const l in this._transactions[i])Object.prototype.hasOwnProperty.call(this._transactions[i],l)&&this._transactions[i][l].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==Xs.STATUS_USER_CLOSED&&(this._status=Xs.STATUS_NOT_READY,this._error=Xs.NETWORK_ERROR)}function GT(c){console.log("onTransportData",c);const s=c.transport;let i=c.message;if(i=$T.parseMessage(i,this),!i){console.log("if 1 return");return}if(this._status===Xs.STATUS_USER_CLOSED&&i instanceof Dn.IncomingRequest){console.log("if 2 return");return}if(!hT(i,this,s)){console.log("if 3 return");return}if(console.log("onTransportData message",i),console.log("onTransportData instanceof",i instanceof Dn.IncomingRequest),i instanceof Dn.IncomingRequest)i.transport=s,console.log("onTransportData receiveRequest"),this.receiveRequest(i);else if(i instanceof Dn.IncomingResponse){let l;switch(i.method){case Me.INVITE:l=this._transactions.ict[i.via_branch],l&&l.receiveResponse(i);break;case Me.ACK:break;default:l=this._transactions.nict[i.via_branch],l&&l.receiveResponse(i);break}}}const WT=["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"],KT=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function Uf(c){const s={};return WT.forEach(i=>{c[i]!==void 0&&(s[i]=c[i])}),s.localHold=c._localHold,s}function Pf(c){const s={};return KT.forEach(i=>{c[i]!==void 0&&(s[i]=c[i])}),s}function xf(c,s){const i=new AudioContext,l=i.createMediaStreamSource(c),a=i.createMediaStreamDestination(),_=i.createGain();return l.connect(_),_.connect(a),_.gain.value=s,a.stream}function YT(c,s,i,l){const a=document.createElement("audio");a.id=s._id,a.className="audioTag",a.srcObject=c,O_()||(a.setSinkId(i),a.volume=l),a.play(),s.audioTag=a}function JT(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}function O_(){return/Mobi|Android|iPhone/i.test(navigator.userAgent)}const zT=ut,XT=Qt(),Pt=new zT("WebSocketInterface");var QT=class{constructor(s){Pt.debug('new() [url:"%s"]',s),this._url=s,this._sip_uri=null,this._via_transport=null,this._ws=null;const i=XT.parse(s,"absoluteURI");if(i===-1)throw Pt.warn(`invalid WebSocket URI: ${s}`),new TypeError(`Invalid argument: ${s}`);if(i.scheme!=="wss"&&i.scheme!=="ws")throw Pt.warn(`invalid WebSocket URI scheme: ${i.scheme}`),new TypeError(`Invalid argument: ${s}`);this._sip_uri=`sip:${i.host}${i.port?`:${i.port}`:""};transport=ws`,this._via_transport=i.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(Pt.debug("connect()"),this.isConnected()){Pt.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Pt.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Pt.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(){Pt.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 Pt.debug("send()"),this.isConnected()?(this._ws.send(s),!0):(Pt.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(){Pt.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:s,code:i,reason:l}){Pt.debug(`WebSocket ${this._url} closed`),s===!1&&Pt.debug("WebSocket abrupt disconnection"),this.ondisconnect(!s,i,l)}_onMessage({data:s}){Pt.debug("received WebSocket message"),this.ondata(s)}_onError(s){Pt.warn(`WebSocket ${this._url} error: `,s)}};const bu=Ka,ZT=Me,ev=bs,tv=Ct(),sv=w_,nv=Is(),rv=$u(),iv=Qt(),lv=QT,av=ur("JsSIP");av("version %s",bu.version);var ov={C:ZT,Exceptions:ev,Utils:tv,UA:sv,URI:nv,NameAddrHeader:rv,WebSocketInterface:lv,Grammar:iv,debug:ur,get name(){return bu.title},get version(){return bu.version}};const uv=tt(ov);function ru(c){return c<10?`0${c}`:`${c}`}function cv(c){let s=c.hours||0,i=c.minutes||0,l=c.seconds||0;l++,l===60&&(l=0,i++,i===60&&(i=0,s++));const a=`${ru(s)}:${ru(i)}:${ru(l)}`;return{seconds:l,minutes:i,hours:s,formatted:a}}var Rt={};Rt.forEach=async(c,s,i)=>{const l=[];for(let a=0;a<c.length;a++)if(a in c){const _=Promise.resolve(c[a]).then(e=>s.call(i||globalThis,e,a,c));l.push(_)}await Promise.all(l)};Rt.forEachSeries=async(c,s,i)=>{for(let l=0;l<c.length;l++)l in c&&await s.call(i||globalThis,await c[l],l,c)};Rt.map=async(c,s,i)=>{const l=[];for(let a=0;a<c.length;a++)a in c&&(l[a]=Promise.resolve(c[a]).then(_=>s.call(i||globalThis,_,a,c)));return Promise.all(l)};Rt.mapSeries=async(c,s,i)=>{const l=[];for(let a=0;a<c.length;a++)a in c&&(l[a]=await s.call(i||globalThis,await c[a],a,c));return l};Rt.find=(c,s,i)=>new Promise((l,a)=>{if(c.length===0)return l();let _=1;for(let e=0;e<c.length;e++){const p=g=>{g?l(c[e]):_===c.length&&l(),_++};Promise.resolve(c[e]).then(g=>s.call(i||globalThis,g,e,c)).then(p).catch(a)}});Rt.findSeries=async(c,s,i)=>{for(let l=0;l<c.length;l++)if(await s.call(i||globalThis,await c[l],l,c))return c[l]};Rt.findIndex=(c,s,i)=>new Promise((l,a)=>{if(c.length===0)return l(-1);let _=1;for(let e=0;e<c.length;e++){const p=g=>{g?l(e):_===c.length&&l(-1),_++};Promise.resolve(c[e]).then(g=>s.call(i||globalThis,g,e,c)).then(p).catch(a)}});Rt.findIndexSeries=async(c,s,i)=>{for(let l=0;l<c.length;l++)if(await s.call(i||globalThis,await c[l],l,c))return l};Rt.some=(c,s,i)=>new Promise((l,a)=>{if(c.length===0)return l(!1);let _=1;for(let e=0;e<c.length;e++){if(!(e in c)){_++;continue}const p=g=>{g?l(!0):_===c.length&&l(!1),_++};Promise.resolve(c[e]).then(g=>s.call(i||globalThis,g,e,c)).then(p).catch(a)}});Rt.someSeries=async(c,s,i)=>{for(let l=0;l<c.length;l++)if(l in c&&await s.call(i||globalThis,await c[l],l,c))return!0;return!1};Rt.every=(c,s,i)=>new Promise((l,a)=>{if(c.length===0)return l(!0);let _=1;for(let e=0;e<c.length;e++){if(!(e in c)){_++;continue}const p=g=>{g?_===c.length&&l(!0):l(!1),_++};Promise.resolve(c[e]).then(g=>s.call(i||globalThis,g,e,c)).then(p).catch(a)}});Rt.everySeries=async(c,s,i)=>{for(let l=0;l<c.length;l++)if(l in c&&!await s.call(i||globalThis,await c[l],l,c))return!1;return!0};Rt.filter=(c,s,i)=>new Promise(async(l,a)=>{const _=[];for(let p=0;p<c.length;p++)p in c&&(_[p]=Promise.resolve(c[p]).then(g=>s.call(i||globalThis,g,p,c)).catch(a));const e=[];for(let p=0;p<_.length;p++)await _[p]&&e.push(await c[p]);l(e)});Rt.filterSeries=async(c,s,i)=>{const l=[];for(let a=0;a<c.length;a++)a in c&&await s.call(i||globalThis,await c[a],a,c)&&l.push(await c[a]);return l};Rt.reduce=async(c,s,i)=>{if(c.length===0&&i===void 0)throw TypeError("Reduce of empty array with no initial value");let l,a;for(i!==void 0?(a=i,l=0):(a=c[0],l=1),l;l<c.length;l++)l in c&&(a=await s(await a,await c[l],l,c));return a};var D_={};(function(c){const s=Rt;Object.keys(s).forEach(i=>{const l=i.charAt(0).toUpperCase()+i.slice(1);c[`async${l}`]=async function(...a){return s[i](this,...a)}})})(D_);const fv=Rt,_v=D_;var hv=Object.assign(fv,{instanceMethods:_v});const Un=new AudioContext,Xt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var dv={exports:{}};(function(c){var s=function(i){var l=Object.prototype,a=l.hasOwnProperty,_=Object.defineProperty||function(N,Y,re){N[Y]=re.value},e,p=typeof Symbol=="function"?Symbol:{},g=p.iterator||"@@iterator",n=p.asyncIterator||"@@asyncIterator",v=p.toStringTag||"@@toStringTag";function S(N,Y,re){return Object.defineProperty(N,Y,{value:re,enumerable:!0,configurable:!0,writable:!0}),N[Y]}try{S({},"")}catch{S=function(Y,re,ae){return Y[re]=ae}}function m(N,Y,re,ae){var Te=Y&&Y.prototype instanceof oe?Y:oe,De=Object.create(Te.prototype),Ce=new U(ae||[]);return _(De,"_invoke",{value:j(N,re,Ce)}),De}i.wrap=m;function C(N,Y,re){try{return{type:"normal",arg:N.call(Y,re)}}catch(ae){return{type:"throw",arg:ae}}}var A="suspendedStart",R="suspendedYield",I="executing",V="completed",W={};function oe(){}function x(){}function $(){}var Re={};S(Re,g,function(){return this});var Ie=Object.getPrototypeOf,H=Ie&&Ie(Ie(se([])));H&&H!==l&&a.call(H,g)&&(Re=H);var D=$.prototype=oe.prototype=Object.create(Re);x.prototype=$,_(D,"constructor",{value:$,configurable:!0}),_($,"constructor",{value:x,configurable:!0}),x.displayName=S($,v,"GeneratorFunction");function L(N){["next","throw","return"].forEach(function(Y){S(N,Y,function(re){return this._invoke(Y,re)})})}i.isGeneratorFunction=function(N){var Y=typeof N=="function"&&N.constructor;return Y?Y===x||(Y.displayName||Y.name)==="GeneratorFunction":!1},i.mark=function(N){return Object.setPrototypeOf?Object.setPrototypeOf(N,$):(N.__proto__=$,S(N,v,"GeneratorFunction")),N.prototype=Object.create(D),N},i.awrap=function(N){return{__await:N}};function q(N,Y){function re(De,Ce,Le,we){var Se=C(N[De],N,Ce);if(Se.type==="throw")we(Se.arg);else{var it=Se.arg,Ue=it.value;return Ue&&typeof Ue=="object"&&a.call(Ue,"__await")?Y.resolve(Ue.__await).then(function(le){re("next",le,Le,we)},function(le){re("throw",le,Le,we)}):Y.resolve(Ue).then(function(le){it.value=le,Le(it)},function(le){return re("throw",le,Le,we)})}}var ae;function Te(De,Ce){function Le(){return new Y(function(we,Se){re(De,Ce,we,Se)})}return ae=ae?ae.then(Le,Le):Le()}_(this,"_invoke",{value:Te})}L(q.prototype),S(q.prototype,n,function(){return this}),i.AsyncIterator=q,i.async=function(N,Y,re,ae,Te){Te===void 0&&(Te=Promise);var De=new q(m(N,Y,re,ae),Te);return i.isGeneratorFunction(Y)?De:De.next().then(function(Ce){return Ce.done?Ce.value:De.next()})};function j(N,Y,re){var ae=A;return function(De,Ce){if(ae===I)throw new Error("Generator is already running");if(ae===V){if(De==="throw")throw Ce;return It()}for(re.method=De,re.arg=Ce;;){var Le=re.delegate;if(Le){var we=B(Le,re);if(we){if(we===W)continue;return we}}if(re.method==="next")re.sent=re._sent=re.arg;else if(re.method==="throw"){if(ae===A)throw ae=V,re.arg;re.dispatchException(re.arg)}else re.method==="return"&&re.abrupt("return",re.arg);ae=I;var Se=C(N,Y,re);if(Se.type==="normal"){if(ae=re.done?V:R,Se.arg===W)continue;return{value:Se.arg,done:re.done}}else Se.type==="throw"&&(ae=V,re.method="throw",re.arg=Se.arg)}}}function B(N,Y){var re=Y.method,ae=N.iterator[re];if(ae===e)return Y.delegate=null,re==="throw"&&N.iterator.return&&(Y.method="return",Y.arg=e,B(N,Y),Y.method==="throw")||re!=="return"&&(Y.method="throw",Y.arg=new TypeError("The iterator does not provide a '"+re+"' method")),W;var Te=C(ae,N.iterator,Y.arg);if(Te.type==="throw")return Y.method="throw",Y.arg=Te.arg,Y.delegate=null,W;var De=Te.arg;if(!De)return Y.method="throw",Y.arg=new TypeError("iterator result is not an object"),Y.delegate=null,W;if(De.done)Y[N.resultName]=De.value,Y.next=N.nextLoc,Y.method!=="return"&&(Y.method="next",Y.arg=e);else return De;return Y.delegate=null,W}L(D),S(D,v,"Generator"),S(D,g,function(){return this}),S(D,"toString",function(){return"[object Generator]"});function X(N){var Y={tryLoc:N[0]};1 in N&&(Y.catchLoc=N[1]),2 in N&&(Y.finallyLoc=N[2],Y.afterLoc=N[3]),this.tryEntries.push(Y)}function Q(N){var Y=N.completion||{};Y.type="normal",delete Y.arg,N.completion=Y}function U(N){this.tryEntries=[{tryLoc:"root"}],N.forEach(X,this),this.reset(!0)}i.keys=function(N){var Y=Object(N),re=[];for(var ae in Y)re.push(ae);return re.reverse(),function Te(){for(;re.length;){var De=re.pop();if(De in Y)return Te.value=De,Te.done=!1,Te}return Te.done=!0,Te}};function se(N){if(N){var Y=N[g];if(Y)return Y.call(N);if(typeof N.next=="function")return N;if(!isNaN(N.length)){var re=-1,ae=function Te(){for(;++re<N.length;)if(a.call(N,re))return Te.value=N[re],Te.done=!1,Te;return Te.value=e,Te.done=!0,Te};return ae.next=ae}}return{next:It}}i.values=se;function It(){return{value:e,done:!0}}return U.prototype={constructor:U,reset:function(N){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method="next",this.arg=e,this.tryEntries.forEach(Q),!N)for(var Y in this)Y.charAt(0)==="t"&&a.call(this,Y)&&!isNaN(+Y.slice(1))&&(this[Y]=e)},stop:function(){this.done=!0;var N=this.tryEntries[0],Y=N.completion;if(Y.type==="throw")throw Y.arg;return this.rval},dispatchException:function(N){if(this.done)throw N;var Y=this;function re(we,Se){return De.type="throw",De.arg=N,Y.next=we,Se&&(Y.method="next",Y.arg=e),!!Se}for(var ae=this.tryEntries.length-1;ae>=0;--ae){var Te=this.tryEntries[ae],De=Te.completion;if(Te.tryLoc==="root")return re("end");if(Te.tryLoc<=this.prev){var Ce=a.call(Te,"catchLoc"),Le=a.call(Te,"finallyLoc");if(Ce&&Le){if(this.prev<Te.catchLoc)return re(Te.catchLoc,!0);if(this.prev<Te.finallyLoc)return re(Te.finallyLoc)}else if(Ce){if(this.prev<Te.catchLoc)return re(Te.catchLoc,!0)}else if(Le){if(this.prev<Te.finallyLoc)return re(Te.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(N,Y){for(var re=this.tryEntries.length-1;re>=0;--re){var ae=this.tryEntries[re];if(ae.tryLoc<=this.prev&&a.call(ae,"finallyLoc")&&this.prev<ae.finallyLoc){var Te=ae;break}}Te&&(N==="break"||N==="continue")&&Te.tryLoc<=Y&&Y<=Te.finallyLoc&&(Te=null);var De=Te?Te.completion:{};return De.type=N,De.arg=Y,Te?(this.method="next",this.next=Te.finallyLoc,W):this.complete(De)},complete:function(N,Y){if(N.type==="throw")throw N.arg;return N.type==="break"||N.type==="continue"?this.next=N.arg:N.type==="return"?(this.rval=this.arg=N.arg,this.method="return",this.next="end"):N.type==="normal"&&Y&&(this.next=Y),W},finish:function(N){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var re=this.tryEntries[Y];if(re.finallyLoc===N)return this.complete(re.completion,re.afterLoc),Q(re),W}},catch:function(N){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var re=this.tryEntries[Y];if(re.tryLoc===N){var ae=re.completion;if(ae.type==="throw"){var Te=ae.arg;Q(re)}return Te}}throw new Error("illegal catch attempt")},delegateYield:function(N,Y,re){return this.delegate={iterator:se(N),resultName:Y,nextLoc:re},this.method==="next"&&(this.arg=e),W}},i}(c.exports);try{regeneratorRuntime=s}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=s:Function("r","regeneratorRuntime = r")(s)}})(dv);var N_={exports:{}};(function(c){(function(s,i){c.exports?c.exports=i():s.log=i()})(H_,function(){var s=function(){},i="undefined",l=typeof window!==i&&typeof window.navigator!==i&&/Trident\/|MSIE /.test(window.navigator.userAgent),a=["trace","debug","info","warn","error"];function _(R,I){var V=R[I];if(typeof V.bind=="function")return V.bind(R);try{return Function.prototype.bind.call(V,R)}catch{return function(){return Function.prototype.apply.apply(V,[R,arguments])}}}function e(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function p(R){return R==="debug"&&(R="log"),typeof console===i?!1:R==="trace"&&l?e:console[R]!==void 0?_(console,R):console.log!==void 0?_(console,"log"):s}function g(R,I){for(var V=0;V<a.length;V++){var W=a[V];this[W]=V<R?s:this.methodFactory(W,R,I)}this.log=this.debug}function n(R,I,V){return function(){typeof console!==i&&(g.call(this,I,V),this[R].apply(this,arguments))}}function v(R,I,V){return p(R)||n.apply(this,arguments)}function S(R,I,V){var W=this,oe;I=I??"WARN";var x="loglevel";typeof R=="string"?x+=":"+R:typeof R=="symbol"&&(x=void 0);function $(D){var L=(a[D]||"silent").toUpperCase();if(!(typeof window===i||!x)){try{window.localStorage[x]=L;return}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+L+";"}catch{}}}function Re(){var D;if(!(typeof window===i||!x)){try{D=window.localStorage[x]}catch{}if(typeof D===i)try{var L=window.document.cookie,q=L.indexOf(encodeURIComponent(x)+"=");q!==-1&&(D=/^([^;]+)/.exec(L.slice(q))[1])}catch{}return W.levels[D]===void 0&&(D=void 0),D}}function Ie(){if(!(typeof window===i||!x)){try{window.localStorage.removeItem(x);return}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}W.name=R,W.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},W.methodFactory=V||v,W.getLevel=function(){return oe},W.setLevel=function(D,L){if(typeof D=="string"&&W.levels[D.toUpperCase()]!==void 0&&(D=W.levels[D.toUpperCase()]),typeof D=="number"&&D>=0&&D<=W.levels.SILENT){if(oe=D,L!==!1&&$(D),g.call(W,D,R),typeof console===i&&D<W.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+D},W.setDefaultLevel=function(D){I=D,Re()||W.setLevel(D,!1)},W.resetLevel=function(){W.setLevel(I,!1),Ie()},W.enableAll=function(D){W.setLevel(W.levels.TRACE,D)},W.disableAll=function(D){W.setLevel(W.levels.SILENT,D)};var H=Re();H==null&&(H=I),W.setLevel(H,!1)}var m=new S,C={};m.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var V=C[I];return V||(V=C[I]=new S(I,m.getLevel(),m.methodFactory)),V};var A=typeof window!==i?window.log:void 0;return m.noConflict=function(){return typeof window!==i&&window.log===m&&(window.log=A),m},m.getLoggers=function(){return C},m.default=m,m})})(N_);var Ot=N_.exports;const As=()=>`${new Date().toISOString()} | metrics`,Cs=(c,s,i)=>`${c} | ${s} | ${i}`;Ot.setDefaultLevel(Ot.levels.TRACE);const pv=c=>{Ot.info(Cs(As(),"log ",`set log level to ${c?"verbose":"info"}`)),Ot.setLevel(c?Ot.levels.TRACE:Ot.levels.INFO)},mv=c=>{const s=[...Object.keys(Ot.levels)];s.includes(c)?(Ot.info(Cs(As(),"log ",`update log level to ${c.toLowerCase()}`)),Ot.setLevel(c)):Ot.warn(Cs(As(),"log ","Incorrect log level please choose one of "),s)},ke=(c,s,i)=>{i?Ot.debug(Cs(As(),c,s),i):Ot.debug(Cs(As(),c,s))},iu=(c,s)=>{Ot.info(Cs(As(),c,s))},Pn=(c,s)=>{Ot.info(Cs(As(),c,s))},Ma=(c,s)=>{Ot.warn(Cs(As(),c,s))},ir=(c,s)=>{Ot.error(Cs(As(),c,s))};function gv(c){return Math.floor(Math.random()*c).toString()}function Mf(c,s){let i=s;return c.forEach(l=>{i=i.replace(l,"")}),i}function Tv(c,s){let i="";for(let l=0;l<s;l+=1)i+=c[gv(c.length)];return i}function vv({length:c=20,useLetters:s=!0,useNumbers:i=!0,includeSymbols:l=[],excludeSymbols:a=[]}={}){let _="abcdefghijklmnopqrstuvwxyz",e="0123456789",p=[],g=[],n=[];return s&&(a.length&&(_=Mf(a,_)),g=_.split("")),i&&(a.length&&(e=Mf(a,e)),n=e.split("")),p=[...g,...n,...l],Tv(p,c)}var Ev=vv;const Ji=tt(Ev),Sv=()=>"WebRTCMetrics",yv=()=>"5.0.3",qe={INBOUND:"inbound",OUTBOUND:"outbound"},Ss={IDLE:"idle",RUNNING:"running",MUTED:"muted"},Bi={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},Av=()=>({...{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:[]}}),U_={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:qe.INBOUND},P_={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:qe.OUTBOUND},x_={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:qe.INBOUND},M_={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:qe.OUTBOUND},Cv=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 i={...c,audio:{},video:{},data:{...c.data},network:{...c.network},experimental:{...c.experimental}};return Object.keys(c.audio).forEach(l=>{i.audio[l]={...c.audio[l]}}),Object.keys(c.video).forEach(l=>{i.video[l]={...c.video[l]}}),i}return{...s,audio:{},video:{},data:{...s.data},network:{...s.network},experimental:{...s.experimental}}},Rv={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${Ji()}`,cid:`c-${Ji()}`,uid:`u-${Ji()}`,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"},K={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"},M={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},Gi={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},lu={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ie={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},au="config ",Iv=(c,s={},i)=>{const l={...i,...s};return s.pname||Ma(au,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${i.pname}'`),s.cid||Ma(au,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${i.cid}'`),s.uid||Ma(au,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${i.uid}'`),l.pc=c,l},bv=(c={})=>{const s={...Rv,...c};return s.name=Sv(),s.version=yv(),s},_l=(c,s,i,l=!1,a)=>{let _=c.map(e=>{if(!i)return e[s];if(!a)return e[s][i];const p=e[s][a];return p?p[i]:null});return _=_.filter(e=>l?Number.isFinite(e)&&e>0:Number.isFinite(e)),_.length===0?[]:_},Zs=c=>c.reduce((s,i)=>s+i,0)/c.length,wv=()=>`probe-${Ji()}`,Ov=()=>`coltr-${Ji()}`,kf=c=>new Promise(s=>setTimeout(s,c)),wu=(c,s,i)=>{s?c.call(s,i):c(i)},Qe=(c,s,i,l)=>{const a=_l(c,s,i,!0,l);if(a.length===0)return null;const _=a.reduce((n,v)=>n+v,0)/a.length;return _===0?null:a.map(n=>Math.abs(_-n)).reduce((n,v)=>n+v,0)/a.length*100/_},st=(c,s,i,l=!1,a)=>{const _=_l(c,s,i,l,a);return _.length===0?null:_.reduce((e,p)=>e+p,0)/_.length},wn=(c,s,i)=>_l(c,s,i).reduce((a,_)=>a+_,0),Ze=(c,s,i,l)=>{const a=_l(c,s,i,!0,l);return a.length===0?null:Math.min(...a)},et=(c,s,i,l)=>{const a=_l(c,s,i,!1,l);return a.length===0?null:Math.max(...a)},vt=(c,s,i,l)=>{const a=c.slice().pop();if(!a)return null;if(!i)return a[s];if(!l)return a[s][i];const _=a[s][l];return _?_[i]:null},Dv=c=>c.slice().pop(),_t=(c,s,i)=>{if(!s)return null;const l={};let a=s[M.AUDIO][c];a||(a=i===qe.INBOUND?{...U_}:{...P_}),l[M.AUDIO]=a;let _=s[M.VIDEO][c];return _||(_=i===qe.INBOUND?{...x_}:{...M_}),l[M.VIDEO]=_,l},Wi="exporter ",Nv="2.0",Lf=(c,s,i)=>{if(!c||c.length===0)return 0;const l=c[c.length-1];if(!l)return 0;const a=l[s][i];if(a){const _=a.total_rtt_ms_out,e=a.total_rtt_measure_out;return!e||!_?st(c,s,"delta_rtt_ms_out",!1,i):Number(_/e)}return null},Uv=(c,s)=>{if(!c||c.length===0)return 0;const i=c[c.length-1];if(!i)return 0;const l=i[s].total_rtt_connectivity_ms,a=i[s].total_rtt_connectivity_measure;return!a||!l?st(c,s,"delta_rtt_connectivity_ms"):Number(l/a)},Pv=c=>vt(c,"network","local_candidate_type")!=="relay"?`direct/${vt(c,"network","local_candidate_protocol")}`:`turn/${vt(c,"network","local_candidate_relay_protocol")}`,xv=c=>{const s=vt(c,"network","remote_candidate_type"),i=vt(c,"network","remote_candidate_protocol");return s!=="relay"?`direct/${i}`:`turn/${i}`};class Mv{constructor(s){this._start=null,this._end=null,this._cfg=s,this._referenceReport=null,this._reports=[],this._events=[]}start(){iu(Wi,"start() - start exporter...");const s=new Date;return this._start=s.toJSON(),s}stop(){iu(Wi,"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&&(ke(Wi,`addReport() - add report to exporter at ${s.timestamp}`),this._reports.push(s))}addCustomEvent(s){this._events.push(s)}reset(){iu(Wi,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){ke(Wi,"ticket() - generate ticket");const s=vt(this._reports,"audio","total_packets_lost_in"),i=vt(this._reports,"audio","total_packets_in"),l=vt(this._reports,"video","total_packets_lost_in"),a=vt(this._reports,"video","total_packets_in"),_={},e=Dv(this._reports);return e&&(Object.keys(e[M.AUDIO]).forEach(p=>{const g=e[M.AUDIO][p];if(_[g.ssrc]={type:M.AUDIO,direction:g.direction},g.direction===qe.INBOUND){const n={avg:st(this._reports,M.AUDIO,"delta_jitter_ms_in",!1,p),min:Ze(this._reports,M.AUDIO,"delta_jitter_ms_in",p),max:et(this._reports,M.AUDIO,"delta_jitter_ms_in",p),volatility:Qe(this._reports,M.AUDIO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},v={avg:st(this._reports,M.AUDIO,"delta_kbs_in",!1,p),min:Ze(this._reports,M.AUDIO,"delta_kbs_in",p),max:et(this._reports,M.AUDIO,"delta_kbs_in",p),volatility:Qe(this._reports,M.AUDIO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},S={avg:st(this._reports,M.AUDIO,"delta_KBytes_in",!1,p),min:Ze(this._reports,M.AUDIO,"delta_KBytes_in",p),max:et(this._reports,M.AUDIO,"delta_KBytes_in",p),volatility:Qe(this._reports,M.AUDIO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},m={emodel:{avg:st(this._reports,M.AUDIO,"mos_emodel_in",!1,p),min:Ze(this._reports,M.AUDIO,"mos_emodel_in",p),max:et(this._reports,M.AUDIO,"mos_emodel_in",p),volatility:Qe(this._reports,M.AUDIO,"mos_emodel_in",p)},effective:{avg:st(this._reports,M.AUDIO,"mos_in",!1,p),min:Ze(this._reports,M.AUDIO,"mos_in",p),max:et(this._reports,M.AUDIO,"mos_in",p),volatility:Qe(this._reports,M.AUDIO,"mos_in",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},C=vt(this._reports,M.AUDIO,"total_packets_lost_in",p),A=vt(this._reports,M.AUDIO,"total_packets_in",p),R={lost:C,avg:Math.round((C/(C+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};_[p].jitter=n,_[p].mos=m,_[p].traffic=S,_[p].bitrate=v,_[p].loss=R}else{const n={avg:st(this._reports,M.AUDIO,"delta_jitter_ms_out",!1,p),min:Ze(this._reports,M.AUDIO,"delta_jitter_ms_out",p),max:et(this._reports,M.AUDIO,"delta_jitter_ms_out",p),volatility:Qe(this._reports,M.AUDIO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},v={avg:st(this._reports,M.AUDIO,"delta_kbs_out",!1,p),min:Ze(this._reports,M.AUDIO,"delta_kbs_out",p),max:et(this._reports,M.AUDIO,"delta_kbs_out",p),volatility:Qe(this._reports,M.AUDIO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},S={avg:st(this._reports,M.AUDIO,"delta_KBytes_out",!1,p),min:Ze(this._reports,M.AUDIO,"delta_KBytes_out",p),max:et(this._reports,M.AUDIO,"delta_KBytes_out",p),volatility:Qe(this._reports,M.AUDIO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},m={avg:Lf(this._reports,M.AUDIO,p),min:Ze(this._reports,M.AUDIO,"delta_rtt_ms_out",p),max:et(this._reports,M.AUDIO,"delta_rtt_ms_out",p),volatility:Qe(this._reports,M.AUDIO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},C=vt(this._reports,M.AUDIO,"total_packets_lost_out",p),A=vt(this._reports,M.AUDIO,"total_packets_out",p),R={lost:C,avg:Math.round((C/(C+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},I={emodel:{avg:st(this._reports,M.AUDIO,"mos_emodel_out",!1,p),min:Ze(this._reports,M.AUDIO,"mos_emodel_out",p),max:et(this._reports,M.AUDIO,"mos_emodel_out",p),volatility:Qe(this._reports,M.AUDIO,"mos_emodel_out",p)},effective:{avg:st(this._reports,M.AUDIO,"mos_out",!1,p),min:Ze(this._reports,M.AUDIO,"mos_out",p),max:et(this._reports,M.AUDIO,"mos_out",p),volatility:Qe(this._reports,M.AUDIO,"mos_out",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};_[p].jitter=n,_[p].rtt=m,_[p].traffic=S,_[p].bitrate=v,_[p].loss=R,_[p].mos=I}}),Object.keys(e[M.VIDEO]).forEach(p=>{const g=e[M.VIDEO][p];if(_[p]={type:M.VIDEO,direction:g.direction},g.direction===qe.INBOUND){const n={avg:st(this._reports,M.VIDEO,"delta_jitter_ms_in",!1,p),min:Ze(this._reports,M.VIDEO,"delta_jitter_ms_in",p),max:et(this._reports,M.VIDEO,"delta_jitter_ms_in",p),volatility:Qe(this._reports,M.VIDEO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},v={avg:st(this._reports,M.VIDEO,"delta_kbs_in",!1,p),min:Ze(this._reports,M.VIDEO,"delta_kbs_in",p),max:et(this._reports,M.VIDEO,"delta_kbs_in",p),volatility:Qe(this._reports,M.VIDEO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},S={avg:st(this._reports,M.VIDEO,"delta_KBytes_in",!1,p),min:Ze(this._reports,M.VIDEO,"delta_KBytes_in",p),max:et(this._reports,M.VIDEO,"delta_KBytes_in",p),volatility:Qe(this._reports,M.VIDEO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},m=vt(this._reports,M.VIDEO,"total_packets_lost_in",p),C=vt(this._reports,M.VIDEO,"total_packets_in",p),A={lost:m,avg:Math.round((m/(m+C)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};_[p].jitter=n,_[p].traffic=S,_[p].bitrate=v,_[p].loss=A}else{const n={avg:st(this._reports,M.VIDEO,"delta_jitter_ms_out",!1,p),min:Ze(this._reports,M.VIDEO,"delta_jitter_ms_out",p),max:et(this._reports,M.VIDEO,"delta_jitter_ms_out",p),volatility:Qe(this._reports,M.VIDEO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},v={avg:st(this._reports,M.VIDEO,"delta_kbs_out",!1,p),min:Ze(this._reports,M.VIDEO,"delta_kbs_out",p),max:et(this._reports,M.VIDEO,"delta_kbs_out",p),volatility:Qe(this._reports,M.VIDEO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},S={avg:st(this._reports,M.VIDEO,"delta_KBytes_out",!1,p),min:Ze(this._reports,M.VIDEO,"delta_KBytes_out",p),max:et(this._reports,M.VIDEO,"delta_KBytes_out",p),volatility:Qe(this._reports,M.VIDEO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},m={avg:Lf(this._reports,M.VIDEO,p),min:Ze(this._reports,M.VIDEO,"delta_rtt_ms_out",p),max:et(this._reports,M.VIDEO,"delta_rtt_ms_out",p),volatility:Qe(this._reports,M.VIDEO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},C=vt(this._reports,M.VIDEO,"total_packets_lost_out",p),A=vt(this._reports,M.VIDEO,"total_packets_out",p),R={lost:C,avg:Math.round((C/(C+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};_[p].jitter=n,_[p].rtt=m,_[p].traffic=S,_[p].bitrate=v,_[p].loss=R}})),{version:Nv,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:_,data:{rtt:{avg:Uv(this._reports,"data"),min:Ze(this._reports,"data","delta_rtt_connectivity_ms"),max:et(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Qe(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((s/(s+i)*100||0)*100)/100}},video:{in:{avg:Math.round((l/(l+a)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:st(this._reports,"data","delta_kbs_in"),min:Ze(this._reports,"data","delta_kbs_in"),max:et(this._reports,"data","delta_kbs_in"),volatility:Qe(this._reports,"data","delta_kbs_in")},out:{avg:st(this._reports,"data","delta_kbs_out"),min:Ze(this._reports,"data","delta_kbs_out"),max:et(this._reports,"data","delta_kbs_out"),volatility:Qe(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:st(this._reports,"data","delta_KBytes_in"),min:Ze(this._reports,"data","delta_KBytes_in"),max:et(this._reports,"data","delta_KBytes_in"),volatility:Qe(this._reports,"data","delta_KBytes_in")},out:{avg:st(this._reports,"data","delta_KBytes_out"),min:Ze(this._reports,"data","delta_KBytes_out"),max:et(this._reports,"data","delta_KBytes_out"),volatility:Qe(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:Pv(this._reports),remoteConnection:xv(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 Js="extractor ",$f=(c,s,i,l)=>{let a=!1;const _=l[s].total_rtt_ms_out,e=l[s].total_rtt_measure_out,p=i?i[s].total_rtt_ms_out:0,g=i?i[s].total_rtt_measure_out:0,n={rtt:null,totalRTT:_,totalRTTMeasurements:e};if(c[K.TIMESTAMP]===l[s].timestamp_out||!Object.prototype.hasOwnProperty.call(c,K.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(a=!0,Number(c[K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-g===e))return n;const v=1e3*Number(c[K.ROUND_TRIP_TIME]);let S=_+v,m=e+1;return a&&(S=1e3*Number(c[K.TOTAL_ROUND_TRIP_TIME])-p,m=Number(c[K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-g),{rtt:v,totalRTT:S,totalRTTMeasurements:m}},kv=(c,s,i,l)=>{if(!Object.prototype.hasOwnProperty.call(c,K.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:l[s].total_rtt_connectivity_ms,totalRTTMeasurements:l[s].total_rtt_connectivity_measure};const a=1e3*Number(c[K.CURRENT_ROUND_TRIP_TIME]);let _=l[s].total_rtt_connectivity_ms+a,e=l[s].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,K.TOTAL_ROUND_TRIP_TIME)&&(_=1e3*Number(c[K.TOTAL_ROUND_TRIP_TIME])-(i?i[s].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,K.RESPONSES_RECEIVED)&&(e=Number(c[K.RESPONSES_RECEIVED])-(i?i[s].total_rtt_connectivity_measure:0)),{rtt:a,totalRTT:_,totalRTTMeasurements:e}},Ea=(c,s,i)=>c[K.TIMESTAMP]===i[s].timestamp_out||!Object.prototype.hasOwnProperty.call(c,K.JITTER)?null:1e3*(Number(c[K.JITTER])||0),Lv=(c,s)=>{if(!Object.prototype.hasOwnProperty.call(c,K.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,K.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:s[M.VIDEO].delta_ms_decode_frame_in,frames_decoded:s[M.VIDEO].total_frames_decoded_in,total_decode_time:s[M.VIDEO].total_time_decoded_in};const i=c[K.FRAMES_DECODED],l=c[K.TOTAL_DECODE_TIME],a=l-s[M.VIDEO].total_time_decoded_in,_=i-s[M.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:_>0?a*1e3/_:0,frames_decoded:i,total_decode_time:l}},$v=(c,s)=>{if(!Object.prototype.hasOwnProperty.call(c,K.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,K.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:s[M.VIDEO].delta_ms_encode_frame_out,frames_encoded:s[M.VIDEO].total_frames_encoded_out,total_encode_time:s[M.VIDEO].total_time_encoded_out};const i=c[K.FRAMES_ENCODED],l=c[K.TOTAL_ENCODE_TIME],a=l-s[M.VIDEO].total_time_encoded_out,_=i-s[M.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:_>0&&a?a*1e3/_:0,frames_encoded:i,total_encode_time:l}},Hf=(c,s,i,l)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,K.BYTES_SENT))return{packetsSent:i[s].total_packets_out,packetsLost:i[s].total_packets_lost_out,bytesSent:i[s].total_KBytes_out};const a=Number(c[K.PACKETS_SENT])||0-(l?l[s].total_packets_out:0),_=a-i[s].total_packets_out,e=Number(c[K.BYTES_SENT])/1024-(l?l[s].total_KBytes_out:0),p=e-i[s].total_KBytes_out,g=c[K.TIMESTAMP]||Date.now(),n=l?l.timestamp:null;let v=i.timestamp;!v&&n&&(v=n);const S=v?g-v:0,m=S>0?p*.008*1024/S*1e3:0;return{packetsSent:a,deltaPacketsSent:_,KBytesSent:e,deltaKBytesSent:p,kbsSent:m}},Ff=(c,s,i,l)=>{let a=i[s].total_packets_lost_out,_=0,e=0;return Object.prototype.hasOwnProperty.call(c,K.PACKETS_LOST)&&(a=Number(c[K.PACKETS_LOST])||0-(l?l[s].total_packets_lost_out:0),_=a-i[s].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,K.FRACTION_LOST)&&(e=Number(100*c[K.FRACTION_LOST])),{packetsLost:a,deltaPacketsLost:_,fractionLost:e}},jf=(c,s,i,l)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,K.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,K.BYTES_RECEIVED))return{percent_packets_lost:i[s].percent_packets_lost_in,packetsReceived:i[s].total_packets_in,packetsLost:i[s].total_packets_lost_in,bytesReceived:i[s].total_KBytes_in};const a=Number(c[K.PACKETS_RECEIVED])||0-(l?l[s].total_packets_in:0),_=Number(c[K.PACKETS_LOST])||0-(l?l[s].total_packets_lost_in:0),e=_-i[s].total_packets_lost_in,p=a-i[s].total_packets_in,g=a!==i[s].total_packets_in?e*100/(e+p):0,n=Number(c[K.BYTES_RECEIVED])/1024-(l?l[s].total_KBytes_in:0),v=n-i[s].total_KBytes_in,S=c[K.TIMESTAMP]||Date.now(),m=l?l.timestamp:null;let C=i.timestamp;!C&&m&&(C=m);const A=C?S-C:0,R=A>0?v*.008*1024/A*1e3:0;return{percentPacketsLost:g,packetsReceived:a,deltaPacketsReceived:p,packetsLost:_,deltaPacketsLost:e,KBytesReceived:n,deltaKBytesReceived:v,kbsReceived:R}},Hv=c=>c[K.CANDIDATE_TYPE]!=="relay"?"":c[K.RELAY_PROTOCOL]||"",Fv=c=>{if(!Object.prototype.hasOwnProperty.call(c,K.NETWORK_TYPE))return Gi.WIFI;switch(c[K.NETWORK_TYPE]){case lu.ETHERNET:return Gi.ETHERNET;case lu.CELLULAR_4G:return Gi.CELLULAR_4G;case lu.WIFI:return Gi.WIFI;default:return Gi.CELLULAR}},qf=c=>!Object.prototype.hasOwnProperty.call(c,K.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,K.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[K.FRAME_WIDTH]||null,height:c[K.FRAME_HEIGHT]||null,framerate:c[K.FRAMES_PER_SECOND]},jv=c=>{const s=Object.prototype.hasOwnProperty.call(c,K.QUALITY_LIMITATION_REASON)?c[K.QUALITY_LIMITATION_REASON]:null,i=Object.prototype.hasOwnProperty.call(c,K.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[K.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,l=Object.prototype.hasOwnProperty.call(c,K.QUALITY_LIMITATION_DURATIONS)?c[K.QUALITY_LIMITATION_DURATIONS]:null;return l&&Object.keys(l).forEach(a=>{l[a]>1e3&&(l[a]=Number(l[a]/1e3))}),{reason:s,durations:l,resolutionChanges:i}},qv=(c,s,i)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PLI)||!Object.prototype.hasOwnProperty.call(c,K.NACK))return{pliCount:s.total_pli_sent_in,nackCount:s.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const l=(c[K.PLI]||0)-(i?i[M.VIDEO].total_pli_sent_in:0),a=(c[K.NACK]||0)-(i?i[M.VIDEO].total_nack_sent_in:0);return{pliCount:l,nackCount:a,deltaPliCount:l-s[M.VIDEO].total_pli_sent_in,deltaNackCount:a-s[M.VIDEO].total_nack_sent_in}},Vv=(c,s,i)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PLI)||!Object.prototype.hasOwnProperty.call(c,K.NACK))return{pliCount:s.total_pli_received_out,nackCount:s.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const l=(c[K.PLI]||0)-(i?i[M.VIDEO].total_pli_received_out:0),a=(c[K.NACK]||0)-(i?i[M.VIDEO].total_nack_received_out:0);return{pliCount:l,nackCount:a,deltaPliCount:l-s[M.VIDEO].total_pli_received_out,deltaNackCount:a-s[M.VIDEO].total_nack_received_out}},Bv=c=>({channels:c[K.CHANNELS]||null,clock_rate:c[K.CLOCK_RATE]||null,mime_type:c[K.MIME_TYPE]||null,sdp_fmtp_line:c[K.SDP_FMTP_LINE]||null}),Gv=c=>({clock_rate:c[K.CLOCK_RATE]||null,mime_type:c[K.MIME_TYPE]||null}),Wv=(c,s,i)=>{const l=(c[K.BYTES_RECEIVED]||0)/1024-(i?i.data.total_KBytes_in:0),a=(c[K.BYTES_SENT]||0)/1024-(i?i.data.total_KBytes_out:0),_=c[K.TIMESTAMP]||Date.now(),e=l-s.data.total_KBytes_in,p=a-s.data.total_KBytes_out,g=i?i.timestamp:null;let n=s.timestamp;!n&&g&&(n=g);const v=n?_-n:0,S=v>0?e*.008*1024/v*1e3:0,m=v>0?p*.008*1024/v*1e3:0;return{total_KBytes_received:l,total_KBytes_sent:a,delta_KBytes_received:e,delta_KBytes_sent:p,kbs_speed_received:S,kbs_speed_sent:m}},Kv=c=>{const s=c[K.AVAILABLE_INCOMING_BITRATE]/1024||0,i=c[K.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:s,kbs_outgoing_bandwidth:i}},Yv=(c,s,i,l)=>{if(!c)return[];switch(c[K.TYPE]){case zt.CANDIDATE_PAIR:let a=!1;if(c[K.NOMINATED]&&c[K.STATE]===M.SUCCEEDED&&(a=!0,ke(Js,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c),K.SELECTED in c&&!c[K.SELECTED]&&(a=!1)),a){const e=c[K.LOCAL_CANDIDATE_ID],p=c[K.REMOTE_CANDIDATE_ID],g=Wv(c,s,l),n=Kv(c),v=kv(c,"data",l,s);return[{type:ie.NETWORK,value:{local_candidate_id:e}},{type:ie.NETWORK,value:{remote_candidate_id:p}},{type:ie.DATA,value:{total_KBytes_in:g.total_KBytes_received}},{type:ie.DATA,value:{total_KBytes_out:g.total_KBytes_sent}},{type:ie.DATA,value:{delta_KBytes_in:g.delta_KBytes_received}},{type:ie.DATA,value:{delta_KBytes_out:g.delta_KBytes_sent}},{type:ie.DATA,value:{delta_kbs_in:g.kbs_speed_received}},{type:ie.DATA,value:{delta_kbs_out:g.kbs_speed_sent}},{type:ie.DATA,value:{delta_kbs_bandwidth_in:n.kbs_incoming_bandwidth}},{type:ie.DATA,value:{delta_kbs_bandwidth_out:n.kbs_outgoing_bandwidth}},{type:ie.DATA,value:{delta_rtt_connectivity_ms:v.rtt}},{type:ie.DATA,value:{total_rtt_connectivity_ms:v.totalRTT}},{type:ie.DATA,value:{total_rtt_connectivity_measure:v.totalRTTMeasurements}}]}break;case zt.LOCAL_CANDIDATE:if(c[K.ID]===s.network.local_candidate_id)return[{type:ie.NETWORK,value:{infrastructure:Fv(c)}},{type:ie.NETWORK,value:{local_candidate_type:c[K.CANDIDATE_TYPE]||""}},{type:ie.NETWORK,value:{local_candidate_protocol:c[K.PROTOCOL]||""}},{type:ie.NETWORK,value:{local_candidate_relay_protocol:Hv(c)}}];break;case zt.REMOTE_CANDIDATE:if(c[K.ID]===s.network.remote_candidate_id)return[{type:ie.NETWORK,value:{remote_candidate_type:c[K.CANDIDATE_TYPE]||""}},{type:ie.NETWORK,value:{remote_candidate_protocol:c[K.PROTOCOL]||""}}];break;case zt.INBOUND_RTP:{ke(Js,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);const e=c[K.SSRC],p=_t(e,s,qe.INBOUND);p&&(p.timestamp=s.timestamp);const g=_t(e,l,qe.INBOUND);if(g&&(g.timestamp=l.timestamp),c[K.MEDIA_TYPE]===M.AUDIO){const n=jf(c,M.AUDIO,p,g),v=Ea(c,M.AUDIO,p),S=c[K.CODEC_ID]||"";return[{ssrc:e,type:ie.AUDIO,value:{codec_id_in:S}},{ssrc:e,type:ie.AUDIO,value:{total_packets_in:n.packetsReceived}},{ssrc:e,type:ie.AUDIO,value:{delta_packets_in:n.deltaPacketsReceived}},{ssrc:e,type:ie.AUDIO,value:{total_packets_lost_in:n.packetsLost}},{ssrc:e,type:ie.AUDIO,value:{delta_packets_lost_in:n.deltaPacketsLost}},{ssrc:e,type:ie.AUDIO,value:{percent_packets_lost_in:n.percentPacketsLost}},{ssrc:e,type:ie.AUDIO,value:{total_KBytes_in:n.KBytesReceived}},{ssrc:e,type:ie.AUDIO,value:{delta_KBytes_in:n.deltaKBytesReceived}},{ssrc:e,type:ie.AUDIO,value:{delta_kbs_in:n.kbsReceived}},{ssrc:e,type:ie.AUDIO,value:{delta_jitter_ms_in:v}}]}if(c[K.MEDIA_TYPE]===M.VIDEO){const n=Lv(c,p),v=jf(c,M.VIDEO,p,g),S=Ea(c,M.VIDEO,p),m=c[K.DECODER_IMPLEMENTATION]||null,C=c[K.CODEC_ID]||null,A=qf(c),R=qv(c,p,g);return[{ssrc:e,type:ie.VIDEO,value:{codec_id_in:C}},{ssrc:e,type:ie.VIDEO,value:{total_packets_in:v.packetsReceived}},{ssrc:e,type:ie.VIDEO,value:{delta_packets_in:v.deltaPacketsReceived}},{ssrc:e,type:ie.VIDEO,value:{total_packets_lost_in:v.packetsLost}},{ssrc:e,type:ie.VIDEO,value:{delta_packets_lost_in:v.deltaPacketsLost}},{ssrc:e,type:ie.VIDEO,value:{percent_packets_lost_in:v.percentPacketsLost}},{ssrc:e,type:ie.VIDEO,value:{total_KBytes_in:v.KBytesReceived}},{ssrc:e,type:ie.VIDEO,value:{delta_KBytes_in:v.deltaKBytesReceived}},{ssrc:e,type:ie.VIDEO,value:{delta_kbs_in:v.kbsReceived}},{ssrc:e,type:ie.VIDEO,value:{delta_jitter_ms_in:S}},{ssrc:e,type:ie.VIDEO,value:{decoder_in:m}},{ssrc:e,type:ie.VIDEO,value:{delta_ms_decode_frame_in:n.delta_ms_decode_frame}},{ssrc:e,type:ie.VIDEO,value:{total_frames_decoded_in:n.frames_decoded}},{ssrc:e,type:ie.VIDEO,value:{total_time_decoded_in:n.total_decode_time}},{ssrc:e,type:ie.VIDEO,value:{total_nack_sent_in:R.nackCount}},{ssrc:e,type:ie.VIDEO,value:{delta_nack_sent_in:R.deltaNackCount}},{ssrc:e,type:ie.VIDEO,value:{total_pli_sent_in:R.pliCount}},{ssrc:e,type:ie.VIDEO,value:{delta_pli_sent_in:R.deltaPliCount}},{ssrc:e,type:ie.VIDEO,value:{size_in:A}}]}break}case zt.OUTBOUND_RTP:{ke(Js,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);const e=c[K.SSRC],p=_t(e,s,qe.OUTBOUND);p&&(p.timestamp=s.timestamp);const g=_t(e,l,qe.OUTBOUND);if(g&&(g.timestamp=l.timestamp),c[K.MEDIA_TYPE]===M.AUDIO){const n=c[K.CODEC_ID]||null,v=Hf(c,M.AUDIO,p,g);return[{ssrc:e,type:ie.AUDIO,value:{codec_id_out:n}},{ssrc:e,type:ie.AUDIO,value:{total_packets_out:v.packetsSent}},{ssrc:e,type:ie.AUDIO,value:{delta_packets_out:v.deltaPacketsSent}},{ssrc:e,type:ie.AUDIO,value:{total_KBytes_out:v.KBytesSent}},{ssrc:e,type:ie.AUDIO,value:{delta_KBytes_out:v.deltaKBytesSent}},{ssrc:e,type:ie.AUDIO,value:{delta_kbs_out:v.kbsSent}}]}if(c[K.MEDIA_TYPE]===M.VIDEO){const n=c[K.ENCODER_IMPLEMENTATION]||null,v=c[K.CODEC_ID]||null,S=$v(c,p),m=qf(c),C=jv(c),A=Vv(c,p,g),R=Hf(c,M.VIDEO,p,g);return[{ssrc:e,type:ie.VIDEO,value:{codec_id_out:v}},{ssrc:e,type:ie.VIDEO,value:{total_packets_out:R.packetsSent}},{ssrc:e,type:ie.VIDEO,value:{delta_packets_out:R.deltaPacketsSent}},{ssrc:e,type:ie.VIDEO,value:{total_KBytes_out:R.KBytesSent}},{ssrc:e,type:ie.VIDEO,value:{delta_KBytes_out:R.deltaKBytesSent}},{ssrc:e,type:ie.VIDEO,value:{delta_kbs_out:R.kbsSent}},{ssrc:e,type:ie.VIDEO,value:{encoder_out:n}},{ssrc:e,type:ie.VIDEO,value:{delta_ms_encode_frame_out:S.delta_ms_encode_frame}},{ssrc:e,type:ie.VIDEO,value:{total_frames_encoded_out:S.frames_encoded}},{ssrc:e,type:ie.VIDEO,value:{total_time_encoded_out:S.total_encode_time}},{ssrc:e,type:ie.VIDEO,value:{total_nack_received_out:A.nackCount}},{ssrc:e,type:ie.VIDEO,value:{delta_nack_received_out:A.deltaNackCount}},{ssrc:e,type:ie.VIDEO,value:{total_pli_received_out:A.pliCount}},{ssrc:e,type:ie.VIDEO,value:{delta_pli_received_out:A.deltaPliCount}},{ssrc:e,type:ie.VIDEO,value:{size_out:m}},{ssrc:e,type:ie.VIDEO,value:{limitation_out:C}}]}break}case zt.MEDIA_SOURCE:{ke(Js,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);break}case zt.TRACK:{ke(Js,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);break}case zt.CODEC:const _=[];return Object.keys(s[M.AUDIO]).forEach(e=>{const p=s[M.AUDIO][e];if(p.codec_id_in===c[K.ID]||p.codec_id_out===c[K.ID]){ke(Js,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);const g=Bv(c);c[K.ID]===p.codec_id_in?_.push({ssrc:p.ssrc,type:ie.AUDIO,value:{codec_in:g}}):_.push({ssrc:p.ssrc,type:ie.AUDIO,value:{codec_out:g}})}}),Object.keys(s[M.VIDEO]).forEach(e=>{const p=s[M.VIDEO][e];if(p.codec_id_in===c[K.ID]||p.codec_id_out===c[K.ID]){ke(Js,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);const g=Gv(c);c[K.ID]===p.codec_id_in?_.push({ssrc:p.ssrc,type:ie.VIDEO,value:{codec_in:g}}):_.push({ssrc:p.ssrc,type:ie.VIDEO,value:{codec_out:g}})}}),_;case zt.REMOTE_INBOUND_RTP:{ke(Js,`analyze() - got stats ${c[K.TYPE]} for ${i}`,c);const e=c[K.SSRC],p=_t(e,s,qe.OUTBOUND),g=_t(e,l,qe.OUTBOUND);if(c[K.KIND]===M.AUDIO){const n=$f(c,M.AUDIO,g,p),v=Ea(c,M.AUDIO,p),S=Ff(c,M.AUDIO,p,g);return[{ssrc:e,type:ie.AUDIO,value:{delta_rtt_ms_out:n.rtt}},{ssrc:e,type:ie.AUDIO,value:{total_rtt_ms_out:n.totalRTT}},{ssrc:e,type:ie.AUDIO,value:{total_rtt_measure_out:n.totalRTTMeasurements}},{ssrc:e,type:ie.AUDIO,value:{delta_jitter_ms_out:v}},{ssrc:e,type:ie.AUDIO,value:{timestamp_out:c[K.TIMESTAMP]}},{ssrc:e,type:ie.AUDIO,value:{total_packets_lost_out:S.packetsLost}},{ssrc:e,type:ie.AUDIO,value:{delta_packets_lost_out:S.deltaPacketsLost}},{ssrc:e,type:ie.AUDIO,value:{percent_packets_lost_out:S.fractionLost}}]}if(c[K.KIND]===M.VIDEO){const n=$f(c,M.VIDEO,g,p),v=Ea(c,M.VIDEO,p),S=Ff(c,M.VIDEO,p,g);return[{ssrc:e,type:ie.VIDEO,value:{delta_rtt_ms_out:n.rtt}},{ssrc:e,type:ie.VIDEO,value:{total_rtt_ms_out:n.totalRTT}},{ssrc:e,type:ie.VIDEO,value:{total_rtt_measure_out:n.totalRTTMeasurements}},{ssrc:e,type:ie.VIDEO,value:{delta_jitter_ms_out:v}},{ssrc:e,type:ie.VIDEO,value:{timestamp_out:c[K.TIMESTAMP]}},{ssrc:e,type:ie.VIDEO,value:{total_packets_lost_out:S.packetsLost}},{ssrc:e,type:ie.VIDEO,value:{delta_packets_lost_out:S.deltaPacketsLost}},{ssrc:e,type:ie.VIDEO,value:{percent_packets_lost_out:S.fractionLost}}]}break}}return[]},to=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),Jv=(c,s=M.AUDIO,i,l,a)=>{const _=_t(a,c,qe.INBOUND),e=_t(a,i,qe.INBOUND),p=_t(a,l,qe.INBOUND),g=[],n=[],v=_[s].percent_packets_lost_in,S=_[s].delta_jitter_ms_in,m=e&&e[s].delta_jitter_ms_in||null,C=p&&p[s].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,R=i&&i.data.delta_rtt_connectivity_ms||null,I=l&&l.data.delta_rtt_connectivity_ms||null;A&&g.push(A),R&&g.push(R),I&&g.push(I),S&&n.push(S),i&&m&&n.push(m),l&&C&&n.push(C);const V=g.length>0?Zs(g):100,W=n.length>0?Zs(n):10,oe=93.2-v,x=.18*oe*oe-27.9*oe+1126.62,$=(V+W)/2,Re=$-177.3<0?0:1,Ie=.024*$+.11*($-177.3)*Re,H=x-Ie;return to(H)},zv=(c,s=M.AUDIO,i,l,a)=>{const _=_t(a,c,qe.OUTBOUND),e=_t(a,i,qe.OUTBOUND),p=_t(a,l,qe.OUTBOUND),g=[],n=[],v=_[s].percent_packets_lost_out,S=_[s].delta_rtt_ms_out,m=e&&e[s].delta_rtt_ms_out||null,C=p&&p[s].delta_rtt_ms_out||null,A=_[s].delta_jitter_ms_out,R=e&&e[s].delta_jitter_ms_out||null,I=p&&p[s].delta_jitter_ms_out||null,V=c.data.delta_rtt_connectivity_ms,W=i&&i.data.delta_rtt_connectivity_ms||null,oe=l&&l.data.delta_rtt_connectivity_ms||null;S?g.push(S):V&&g.push(V),m?g.push(m):W&&g.push(W),C?g.push(C):oe&&g.push(oe),A&&n.push(A),i&&R&&n.push(R),l&&I&&n.push(I);const x=g.length>0?Zs(g):100,$=n.length>0?Zs(n):10,Re=93.2-v,Ie=.18*Re*Re-27.9*Re+1126.62,H=(x+$)/2,D=H-177.3<0?0:1,L=.024*H+.11*(H-177.3)*D,q=Ie-L;return to(q)},Xv=(c,s=M.AUDIO,i,l,a)=>{const _=_t(a,c,qe.INBOUND),e=_t(a,i,qe.INBOUND),p=_t(a,l,qe.INBOUND),g=[],n=[],v=_[s].percent_packets_lost_in/100,S=_[s].delta_jitter_ms_in,m=e&&e[s].delta_jitter_ms_in||null,C=p&&p[s].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,R=i&&i.data.delta_rtt_connectivity_ms||null,I=l&&l.data.delta_rtt_connectivity_ms||null;A&&g.push(A),R&&g.push(R),I&&g.push(I),S&&n.push(S),e&&m&&n.push(m),p&&C&&n.push(C);const V=g.length>0?Zs(g):100,W=n.length>0?Zs(n):10,oe=0,x=19.8,$=29.7,Re=30,Ie=(V+W)/2+Re,H=Ie-177.3<0?0:1,D=.024*Ie+.11*(Ie-177.3)*H,q=93.2-(oe+x*Math.log(1+$*v)+D);return to(q)},Qv=(c,s=M.AUDIO,i,l,a)=>{const _=_t(a,c,qe.OUTBOUND),e=_t(a,i,qe.OUTBOUND),p=_t(a,l,qe.OUTBOUND),g=[],n=[],v=_[s].percent_packets_lost_out/100,S=_[s].delta_rtt_ms_out,m=e&&e[s].delta_rtt_ms_out||null,C=p&&p[s].delta_rtt_ms_out||null,A=_[s].delta_jitter_ms_out,R=e&&e[s].delta_jitter_ms_out||null,I=p&&p[s].delta_jitter_ms_out||null,V=c.data.delta_rtt_connectivity_ms,W=i&&i.data.delta_rtt_connectivity_ms||null,oe=l&&l.data.delta_rtt_connectivity_ms||null;S?g.push(S):V&&g.push(V),m?g.push(m):W&&g.push(W),C?g.push(C):oe&&g.push(oe),A&&n.push(A),e&&R&&n.push(R),p&&I&&n.push(I);const x=g.length>0?Zs(g):100,$=n.length>0?Zs(n):10,Re=0,Ie=19.8,H=29.7,D=30,L=(x+$)/2+D,q=L-177.3<0?0:1,j=.024*L+.11*(L-177.3)*q,X=93.2-(Re+Ie*Math.log(1+H*v)+j);return to(X)};class Zv{constructor(s,i){this._callbacks={onreport:null,onticket:null},this._id=Ov(),this._moduleName=this._id,this._probeId=i,this._config=s,this._exporter=new Mv(s),this._state=Ss.IDLE,this.registerToPCEvents(),Pn(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(s,i,l,a){const _=(g,n)=>g===M.AUDIO?n===zt.INBOUND_RTP?{...U_}:{...P_}:n===zt.INBOUND_RTP?{...x_}:{...M_},e=Cv(i);e.pname=this._config.pname,e.call_id=this._config.cid,e.user_id=this._config.uid,e.count=i?i.count+1:1;let p=null;return s.forEach(g=>{!p&&g.timestamp&&(p=g.timestamp),Yv(g,e,e.pname,a).forEach(v=>{if(v.value&&v.type)if(v.ssrc){let S=e[v.type][v.ssrc];S||(S=_(v.type,g.type),S.ssrc=v.ssrc,e[v.type][v.ssrc]=S),Object.keys(v.value).forEach(m=>{S[m]=v.value[m]})}else Object.keys(v.value).forEach(S=>{e[v.type][S]=v.value[S]})})}),e.timestamp=p,Object.keys(e[M.AUDIO]).forEach(g=>{const n=e[M.AUDIO][g];n.direction===qe.INBOUND?(n.mos_emodel_in=Jv(e,M.AUDIO,i,l,n.ssrc),n.mos_in=Xv(e,M.AUDIO,i,l,n.ssrc)):(n.mos_emodel_out=zv(e,M.AUDIO,i,l,n.ssrc),n.mos_out=Qv(e,M.AUDIO,i,l,n.ssrc))}),e}async takeReferenceStats(){return new Promise((s,i)=>{const l=Date.now();setTimeout(async()=>{try{const a=Date.now()-l,_=Date.now(),e=await this._config.pc.getStats(),p=this.analyze(e,null,null,null),g=Date.now();p.experimental.time_to_measure_ms=g-_,p.experimental.time_to_wait_ms=a,this._exporter.saveReferenceReport(p),ke(this._moduleName,`got reference report for probe ${this._probeId}`),s()}catch(a){i(a)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==Ss.RUNNING||!this._config.pc)return ke(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const s=Date.now(),i=await this._config.pc.getStats(),l=this.analyze(i,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),a=Date.now();return l.experimental.time_to_measure_ms=a-s,this._exporter.addReport(l),ke(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(l),l}catch(s){return ir(this._moduleName,`got error ${s}`),null}}async start(){ke(this._moduleName,"starting"),this.state=Ss.RUNNING,this._startedTime=this._exporter.start(),ke(this._moduleName,"started")}async mute(){this.state=Ss.MUTED,ke(this._moduleName,"muted")}async unmute(){this.state=Ss.RUNNING,ke(this._moduleName,"unmuted")}async stop(s){if(ke(this._moduleName,`stopping${s?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=Ss.IDLE,this._config.ticket){const{ticket:i}=this._exporter;this.fireOnTicket(i)}this._exporter.reset(),ke(this._moduleName,"stopped")}registerCallback(s,i,l){s in this._callbacks?(this._callbacks[s]={callback:i,context:l},ke(this._moduleName,`registered callback '${s}'`)):ir(this._moduleName,`can't register callback for '${s}' - not found`)}unregisterCallback(s){s in this._callbacks?(this._callbacks[s]=null,delete this._callbacks[s],ke(this._moduleName,`unregistered callback '${s}'`)):ir(this._moduleName,`can't unregister callback for '${s}' - not found`)}fireOnReport(s){this._callbacks.onreport&&wu(this._callbacks.onreport.callback,this._callbacks.onreport.context,s)}fireOnTicket(s){this._callbacks.onticket&&wu(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,ke(this._moduleName,`state changed to ${s}`)}addCustomEvent(s,i,l,a){this._exporter.addCustomEvent({at:typeof s=="object"?s.toJSON():s,category:i,name:l,description:a})}async registerToPCEvents(){const{pc:s}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const i=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${i.length} devices found`,"Media Devices state")}catch{ir(this._moduleName,"can't get devices")}},s){s.oniceconnectionstatechange=()=>{const l=s.iceConnectionState;l===Bi.CONNECTED||l===Bi.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",l,"ICE connection state"):l===Bi.DISCONNECTED||l===Bi.FAILED?this.addCustomEvent(new Date().toJSON(),"call",l,"ICE connection state"):l===Bi.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},s.onicegatheringstatechange=()=>{const l=s.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",l,"ICE gathering state")},s.ontrack=l=>{this.addCustomEvent(new Date().toJSON(),"call",`${l.track.kind}track`,"MediaStreamTrack received")},s.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const i=s.getReceivers();if(i&&i.length>0){const l=i[0],{transport:a}=l;if(a){const{iceTransport:_}=a;_&&(_.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class eE{constructor(s){this._id=s.pname&&s.pname.substr(0,12).padEnd(12," ")||wv(),this._moduleName=this._id,Pn(this._moduleName,"probe created"),this._config=s,this._collector=new Zv(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,i,l,a=new Date().toJSON()){this._collector.addCustomEvent(a,i,s,l)}get isRunning(){return this._collector.state===Ss.RUNNING}get isIdle(){return this._collector.state===Ss.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){Ma(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 wt="engine ";class tE{constructor(s){this._config=s,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},Pn(wt,`configured for probing every ${this._config.refreshEvery}ms`),Pn(wt,`configured for starting after ${this._config.startAfter}ms`),Pn(wt,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),ke(wt,"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,i){if(!s)throw new Error("undefined peer connection");const l=Iv(s,i,this._config),a=new eE(l);return this._probes.push(a),ke(wt,`${this._probes.length} probes registered`),a}removeExistingProbe(s){if(!s)throw new Error("undefined probe");s.state===Ss.RUNNING&&s.stop(),this._probes=this._probes.filter(i=>s.id!==i.id)}async start(){const s=()=>{this._probes.forEach(_=>_.start())},i=async()=>Promise.all(this._probes.map(_=>_.takeReferenceStats())),l=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,a=async()=>{const _=Av(),e=this._probes.filter(p=>p.isRunning);for(const p of e){const g=await p.collectStats();g&&_.probes.push(g),ke(wt,`got probe ${p.id}`),await kf(0)}return _.delta_time_to_measure_probes_ms=wn(_.probes,"experimental","time_to_measure_ms"),_.delta_KBytes_in=wn(_.probes,"data","delta_KBytes_in"),_.delta_KBytes_out=wn(_.probes,"data","delta_KBytes_out"),_.delta_kbs_in=wn(_.probes,"data","delta_kbs_in"),_.delta_kbs_out=wn(_.probes,"data","delta_kbs_out"),_.total_time_decoded_in=wn(_.probes,"video","total_time_decoded_in"),_.total_time_encoded_out=wn(_.probes,"video","total_time_encoded_out"),_};for(ke(wt,"starting to collect"),s(),ke(wt,"generating reference reports..."),await i(),ke(wt,"reference reports generated"),this._startedTime=Date.now();l();)if(ke(wt,`wait ${this._config.refreshEvery}ms before collecting`),await kf(this._config.refreshEvery),l()){ke(wt,"collecting...");const _=Date.now(),e=await a(),p=Date.now();e.delta_time_consumed_to_measure_ms=p-_,this.fireOnReports(e),ke(wt,"collected")}ke(wt,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(s){const i=l=>{this._probes.forEach(a=>{a.stop(l)})};Pn(wt,"stop collecting"),i(s)}registerCallback(s,i,l){s in this._callbacks?(this._callbacks[s]={callback:i,context:l},ke(wt,`registered callback '${s}'`)):ir(wt,`can't register callback for '${s}' - not found`)}unregisterCallback(s){s in this._callbacks?(this._callbacks[s]=null,delete this._callbacks[s],ke(this._moduleName,`unregistered callback '${s}'`)):ir(this._moduleName,`can't unregister callback for '${s}' - not found`)}fireOnReports(s){this._callbacks.onresult&&s.probes.length>0&&wu(this._callbacks.onresult.callback,this._callbacks.onresult.context,s)}}const sE="interface ";class nE{constructor(s){this._config=bv(s),Pn(sE,`welcome to ${this._config.name} version ${this._config.version}`),pv(this._config.verbose||!1),this._engine=new tE(this._config)}setupLogLevel(s){mv(s)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(s,i){return this._engine.addNewProbe(s,i)}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 rE(c,s){return Object.keys(c).filter(i=>s.includes(i)).reduce((i,l)=>{const a=l;return{...i,[a]:c[a]}},{})}const iE=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"];class lE{constructor(s){this.intervals={},this.emitInterval=s.emitInterval||200,this.onChangeFunction=s.onChangeFunction}start(s,i){s&&s.getTracks().length&&requestAnimationFrame(()=>this.beginCalculation(s,i))}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,i){this.clearVolumeInterval(i);const l=Un.createAnalyser(),a=Un.createMediaStreamSource(s),_=Un.createScriptProcessor(2048,1,1);l.smoothingTimeConstant=.8,l.fftSize=1024,a.connect(l),l.connect(_),_.connect(Un.destination),this.intervals[i]=setInterval(()=>{const e=new Uint8Array(l.frequencyBinCount);l.getByteFrequencyData(e);let p=0;const g=e.length;for(let v=0;v<g;v++)p+=e[v];const n=p/g;this.onChangeFunction(i,n)},this.emitInterval)}}const Sa={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},aE=0;class oE{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 lE({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 O_()?{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(Sa.SELECTED_INPUT_DEVICE)||"default",i=localStorage.getItem(Sa.SELECTED_OUTPUT_DEVICE)||"default";try{const l=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),a=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(a),await this.setMicrophone(s),await this.setSpeaker(i),navigator.mediaDevices.addEventListener("devicechange",async()=>{const _=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(_)}),l.getTracks().forEach(_=>_.stop())}catch(l){console.error(l)}}setCallTime(s){const i={...s};delete i.callId,this.callTime={...this.callTime,[s.callId]:i},this.context.emit("changeCallTime",this.callTime)}removeCallTime(s){const i={...this.callTime};delete i[s],this.callTime={...i},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(s,i){this.timeIntervals={...this.timeIntervals,[s]:i}}removeTimeInterval(s){const i={...this.timeIntervals};i[s]&&(clearInterval(i[s]),delete i[s],this.timeIntervals={...i})}stopCallTimer(s){this.removeTimeInterval(s),this.removeCallTime(s)}emitVolumeChange(s,i){this.context.emit("changeCallVolume",{callId:s,volume:i})}setMetricsConfig(s){this.metricConfig={...this.metricConfig,...s}}sendDTMF(s,i){if(!/^[A-D0-9]+$/g.test(i))throw new Error("Not allowed character in DTMF input");this.extendedCalls[s].sendDTMF(i)}setIsMuted(s){this.muted=s,this.context.emit("changeIsMuted",s)}processMute(s){const i=this.currentActiveRoomId;this.setIsMuted(s),this.initialStreamValue.getTracks().forEach(l=>l.enabled=!s),this.roomReconfigure(i)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:s,toHold:i,automatic:l}){const a=this.extendedCalls[s];a._automaticHold=l??!1,await new Promise(p=>{const g=()=>{p()};i?a.hold({},g):a.unhold({},g)}),this.updateCall(a);const e=Object.values(this.extendedCalls).filter(p=>p.roomId===this.currentActiveRoomId&&(i?s!==p._id:!0));e.length>1&&await this.doConference(e)}holdCall(s,i=!1){return this.processHold({callId:s,automatic:i,toHold:!0})}unholdCall(s){return this.processHold({callId:s,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(s=>s.direction==="outgoing"&&s.status===aE).forEach(s=>this.terminateCall(s._id))}answerCall(s){const i=this.extendedCalls[s];this.cancelAllOutgoingUnanswered(),i.answer(this.sipOptions),this.updateCall(i),this.setActiveRoom(i.roomId),i.connection.addEventListener("track",l=>{this.triggerAddStream(l,i)})}async moveCall(s,i){this.updateCallStatus({callId:s,isMoving:!0}),await this.processRoomChange({callId:s,roomId:i}),this.updateCallStatus({callId:s,isMoving:!1})}updateCall(s){this.activeCalls[s._id]=Uf(s),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(s){const l={...this.activeRooms[s.roomId],...s};this.activeRooms={...this.activeRooms,[s.roomId]:{...l}},this.context.emit("updateRoom",{room:l,roomList:this.activeRooms})}hasAutoAnswerHeaders(s){const i=/answer-after=0/,a=s.request.getHeader("Call-Info");return a&&i.test(a)}addCall(s,i=!0){this.activeCalls={...this.activeCalls,[s._id]:Uf(s)},this.extendedCalls[s._id]=s,i&&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 l={...{...this.callStatus[s.callId]}};s.isMoving!==void 0&&(l.isMoving=s.isMoving),s.isTransferring!==void 0&&(l.isTransferring=s.isTransferring),s.isMerging!==void 0&&(l.isMerging=s.isMerging),this.callStatus={...this.callStatus,[s.callId]:{...l}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(s){const i={...this.callStatus};delete i[s],this.callStatus={...i},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=xf(this.initialStreamValue,this.microphoneInputLevel*2);return s.getTracks().forEach(i=>i.enabled=!this.isMuted),this.setActiveStream(s),s}async setMicrophone(s){if(!this.getInputDeviceList.find(({deviceId:l})=>l===s)||(this.setSelectedInputDevice(s),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const i=Object.values(this.extendedCalls).filter(l=>l.roomId===this.currentActiveRoomId);i.length===1?Object.values(i).forEach(async l=>{const a=this.getActiveStream();l.connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.updateCall(l)}):await this.doConference(i)}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 i=Object.values(this.extendedCalls);if(i.length===0)return;const l=i.filter(a=>a.roomId===this.currentActiveRoomId);l.length===1?i.forEach(a=>{var _;(_=a.audioTag)==null||_.setSinkId(s),this.updateCall(a)}):await this.doConference(l)}removeRoom(s){const i={...this.activeRooms},l={...i[s]};delete i[s],this.activeRooms={...i},this.context.emit("removeRoom",{room:l,roomList:this.activeRooms})}deleteRoomIfEmpty(s){s!==void 0&&Object.values(this.extendedCalls).filter(i=>i.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 l;if(s===void 0)return;const i=Object.values(this.extendedCalls).filter(a=>a.roomId===s);if(this.currentActiveRoomId===s?i.forEach(a=>{a.audioTag&&(this.muteReconfigure(a),a.audioTag.muted=!1,this.updateCall(a))}):i.forEach(a=>{a.audioTag&&(a.audioTag.muted=!0,this.updateCall(a))}),i.length===0)this.deleteRoomIfEmpty(s);else if(i.length===1&&this.currentActiveRoomId!==s)i[0].isOnHold().local||await this.holdCall(i[0].id,!0);else if(i.length===1&&this.currentActiveRoomId===s){if(i[0].isOnHold().local&&i[0]._automaticHold&&await this.unholdCall(i[0].id),i[0].connection&&((l=i[0].connection)!=null&&l.getSenders()[0])){const a=this.getActiveStream();await i[0].connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.muteReconfigure(i[0])}}else i.length>1&&await this.doConference(i)}async doConference(s){const i=[];s.forEach(l=>{l!=null&&l.connection.getReceivers().forEach(a=>{i.push(a.track)})}),await hv.forEach(s,async l=>{var e;if(l==null)return;const a=new MediaStream,_=Un.createMediaStreamDestination();if(l.connection.getReceivers().forEach(p=>{i.forEach(g=>{a.addTrack(p.track),p.track.id!==g.id&&Un.createMediaStreamSource(new MediaStream([g])).connect(_)})}),s[0].roomId===this.currentActiveRoomId){const p=this.getActiveStream();Un.createMediaStreamSource(p).connect(_)}(e=l.connection)!=null&&e.getSenders()[0]&&(await l.connection.getSenders()[0].replaceTrack(_.stream.getTracks()[0]),this.muteReconfigure(l))})}processCallerMute(s,i){const l=this.extendedCalls[s];l&&l.connection.getReceivers().length&&(l.localMuted=i,l.connection.getReceivers().forEach(a=>{a.track.enabled=!i}),this.updateCall(l))}muteCaller(s){this.processCallerMute(s,!0)}unmuteCaller(s){this.processCallerMute(s,!1)}terminateCall(s){const i=this.extendedCalls[s];i._status!==8&&i.terminate()}transferCall(s,i){if(i.toString().length===0)return new Error("Target must be passed");const l=this.extendedCalls[s];if(!l._is_confirmed&&!l._is_canceled){const a=`sip:${i}@${this.context.sipDomain}`;l.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${a}`]});return}this.updateCallStatus({callId:s,isTransferring:!0}),l.refer(`sip:${i}@${this.context.sipDomain}`),this.updateCall(l)}mergeCall(s){const i=Object.values(this.extendedCalls).filter(_=>_.roomId===s);if(i.length!==2)return;const l=i[0],a=i[1];!l||!a||(this.updateCallStatus({callId:l._id,isMerging:!0}),this.updateCallStatus({callId:a._id,isMerging:!0}),l.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(l))}mergeCallByIds(s,i){const l=Object.values(this.extendedCalls).find(_=>_._id===s),a=Object.values(this.extendedCalls).find(_=>_._id===i);if(!l||!a)throw new Error("Call ID is not provided");this.updateCallStatus({callId:s,isMerging:!0}),this.updateCallStatus({callId:i,isMerging:!0}),l.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(l)}setDND(s){this.isDNDEnabled=s,this.context.emit("changeIsDND",s)}startCallTimer(s){this.removeTimeInterval(s);const i={callId:s,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(i);const l=setInterval(()=>{const a={...this.callTime[s]},_=cv(a);this.setCallTime({callId:s,..._})},1e3);this.setTimeInterval(s,l)}async setActiveRoom(s){const i=this.currentActiveRoomId;s!==i&&(this.currentActiveRoomId=s,await this.roomReconfigure(i),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 n,v;const i=s.session;if(this.getActiveCalls[i.id]!==void 0)return;const a=this.getNewRoomId(),_={started:new Date,incomingInProgress:!1,roomId:a};i.direction==="incoming"?(this.context.logger.log("New incoming call from",(v=(n=i._remote_identity)==null?void 0:n._uri)==null?void 0:v._user),_.incomingInProgress=!0,this.context.subscribe(Xt.CALL_CONFIRMED,S=>{i.id===S.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.startCallTimer(i.id))}),this.context.subscribe(Xt.CALL_FAILED,S=>{i.id===S.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.deleteRoomIfEmpty(a))})):i.direction==="outgoing"&&(i.once("confirmed",()=>{this.startCallTimer(i.id)}),this.startCallTimer(i.id));const e=i,p=this.hasAutoAnswerHeaders(s),g=e.direction==="incoming"&&!this.hasActiveCalls&&(p||this.autoAnswer);e.roomId=a,e.localMuted=!1,e.autoAnswer=g,g?this.addCall(e,!1):this.addCall(e),this.addCallStatus(i.id),this.addRoom(_),g&&this.answerCall(e._id)}removeCall(s){const i={...this.activeCalls};delete i[s],this.activeCalls={...i};const l={...this.extendedCalls};delete l[s],this.extendedCalls={...l},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(s){var a;const i=this.extendedCalls[s._id];this.stopVUMeter("origin"),(a=i.connection)==null||a.getSenders().forEach(_=>{_.track.stop()});const l=i.roomId;this.removeCall(s._id),this.roomReconfigure(l)}async newRTCSessionCallback(s){const i=s.session;if(this.isDND){i.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(this.context.triggerListener({listenerType:Xt.NEW_CALL,session:i,event:s}),i.on("ended",l=>{var _,e,p;this.stopVUMeter(i.id),this.context.logger.log("Session ended for",(e=(_=i._remote_identity)==null?void 0:_._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Xt.CALL_ENDED,session:i,event:l});const a=this.getActiveCalls[i.id];a&&this.activeCallListRemove(a),this.stopCallTimer(i.id),this.removeCallStatus(i.id),this.removeCallMetrics(i.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(p=this.initialStreamValue)==null||p.getTracks().forEach(g=>g.stop()),this.initialStreamValue=null)}),i.on("progress",l=>{var a,_;this.context.logger.log("Session in progress for",(_=(a=i._remote_identity)==null?void 0:a._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Xt.CALL_PROGRESS,session:i,event:l})}),i.on("failed",l=>{var _,e,p;this.stopVUMeter(i.id),this.context.logger.log("Session failed for",(e=(_=i._remote_identity)==null?void 0:_._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Xt.CALL_FAILED,session:i,event:l}),i.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const a=this.getActiveCalls[i.id];a&&this.activeCallListRemove(a),this.stopCallTimer(i.id),this.removeCallStatus(i.id),this.removeCallMetrics(i.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(p=this.initialStreamValue)==null||p.getTracks().forEach(g=>g.stop()),this.initialStreamValue=null)}),i.on("confirmed",l=>{var a,_;this.context.logger.log("Session confirmed for",(_=(a=i._remote_identity)==null?void 0:a._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Xt.CALL_CONFIRMED,session:i,event:l}),this.updateCall(i),i.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(s),i.direction==="outgoing"){const l=this.getActiveCalls[i.id].roomId;this.setActiveRoom(l)}}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(i=>{i.audioTag&&(i.audioTag.volume=s,this.updateCall(i))})}setAutoAnswer(s){this.isAutoAnswer=s}setSelectedInputDevice(s){localStorage.setItem(Sa.SELECTED_INPUT_DEVICE,s),this.selectedMediaDevices.input=s,this.context.emit("changeActiveInputMediaDevice",s)}setSelectedOutputDevice(s){localStorage.setItem(Sa.SELECTED_OUTPUT_DEVICE,s),this.selectedMediaDevices.output=s,this.context.emit("changeActiveOutputMediaDevice",s)}setCallMetrics(s){const i={...s};delete i.callId,this.callMetrics={...this.callMetrics,[s.callId]:i},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(s){const i={...this.callMetrics};delete i[s],this.callMetrics={...i},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(s){const i=new nE(this.metricConfig),l=i.createProbe(s.connection,{cid:s._id}),a=[];let _;l.onreport=e=>{Object.entries(e.audio).forEach(([n,v])=>{v.direction==="inbound"&&!a.includes(n)&&(a.push(n),_=n)});const p=e.audio[_];if(!p)return;const g=rE(p,iE);g.callId=s._id,this.setCallMetrics(g)},this.context.subscribe(Xt.CALL_ENDED,e=>{e._id===s._id&&i.stopAllProbes()}),i.startAllProbes()}setupVUMeter(s,i){this.VUMeter.start(s,i)}stopVUMeter(s){this.VUMeter.stop(s)}async setupStream(){const s=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach(i=>i.stop()),this.initialStreamValue=null),this.initialStreamValue=s}async triggerAddStream(s,i){this.setIsMuted(this.muteWhenJoin||this.isMuted),this.initialStreamValue||await this.setupStream();const l=xf(this.initialStreamValue,this.microphoneInputLevel*2),a=this.isMuted||this.muteWhenJoin;l.getTracks().forEach(e=>e.enabled=!a),this.setActiveStream(l),await i.connection.getSenders()[0].replaceTrack(l.getTracks()[0]);const _=new MediaStream([s.track]);YT(_,i,this.selectedOutputDevice,this.speakerVolume),this.setupVUMeter(_,i._id),this.getCallQuality(i),this.updateCall(i)}initCall(s,i){if(s.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${s}@${this.context.sipDomain}...`);const l=this.context.call(`sip:${s}@${this.context.sipDomain}`,this.sipOptions);this.callAddingInProgress=l.id,i&&this.currentActiveRoomId!==void 0&&this.processRoomChange({callId:l.id,roomId:this.currentActiveRoomId}),l.connection.addEventListener("track",a=>{this.triggerAddStream(a,l)})}async processRoomChange({callId:s,roomId:i}){const l=this.extendedCalls[s].roomId;this.extendedCalls[s].roomId=i;const a=this.extendedCalls[s];return this.updateCall(a),await this.setActiveRoom(i),Promise.all([this.roomReconfigure(l),this.roomReconfigure(i)]).then(()=>{this.deleteRoomIfEmpty(l),this.deleteRoomIfEmpty(i)})}}class uE{constructor(s){this.context=s}get sipOptions(){return{...this.context.options.sipOptions}}initCall(s,i){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}`,i,this.sipOptions)}stop(s={}){this.context.terminateJanusSessions(s)}}class cE{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 i=this.extendedMessages[s];this.updateMSRPSession(i)}updateMSRPSession(s){this.activeMessages[s._id]=Pf(s),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(s){this.activeMessages={...this.activeMessages,[s._id]:Pf(s)},this.extendedMessages[s._id]=s,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(s,i){const l=this.msrpHistory[i.id]||[];l.push(s),this.msrpHistory={...this.msrpHistory,[i.id]:[...l]},this.context.emit("newMSRPMessage",{message:s,session:i})}messageTerminate(s){const i=this.extendedMessages[s];i._status!==8&&i.terminate()}addMessageSession(s){if(!s._id||this.getActiveMessages[s._id]!==void 0)return;const l=s;this.addMMSRPSession(l)}triggerMSRPListener({listenerType:s,session:i,event:l}){const a=this.context.listenersList[s];!a||!a.length||a.forEach(_=>{_(i,l)})}removeMMSRPSession(s){const i={...this.activeMessages};delete i[s],this.activeMessages={...i};const l={...this.extendedMessages};delete l[s],this.extendedMessages={...l},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(s){this.removeMMSRPSession(s._id)}newMSRPSessionCallback(s){const i=s.session;i.on("ended",l=>{this.triggerMSRPListener({listenerType:Xt.CALL_ENDED,session:i,event:l});const a=this.getActiveMessages[i.id];this.activeMessageListRemove(a)}),i.on("failed",l=>{this.triggerMSRPListener({listenerType:Xt.CALL_FAILED,session:i,event:l});const a=this.getActiveMessages[i.id];this.activeMessageListRemove(a)}),i.on("confirmed",l=>{this.triggerMSRPListener({listenerType:Xt.CALL_CONFIRMED,session:i,event:l}),this.updateMSRPSession(i)}),i.on("newMessage",l=>{this.addMSRPMessage(l,i)}),this.addMessageSession(i)}setIsMSRPInitializing(s){this.isMSRPInitializingValue=s,this.context.emit("isMSRPInitializingChanged",s)}initMSRP(s,i,l){if(s.length===0)return console.error("Target must be a valid string");const a=this.context.startMSRP(s,l);a.on("active",()=>{this.addMessageSession(a),a.sendMSRP(i),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(s,i){const l=this.extendedMessages[s];if(!l)throw new Error(`MSRP session with id ${s} doesn't exist!`);l.sendMSRP(i)}}const ou={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class fE extends jT{constructor(s,i){if(!s.modules.length)throw new Error("options.modules should include at least 1 module");const l={...s.configuration,sockets:s.socketInterfaces.map(a=>new uv.WebSocketInterface(a))};super(l),this.initialized=!1,this.connected=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],s.pnExtraHeaders&&Object.keys(s.pnExtraHeaders).length&&this.registrator().setExtraContactUriParams(s.pnExtraHeaders),this.options=s,this.modules=s.modules,i&&JT(i)&&(this.logger=i)}on(s,i){return super.on(s,i)}off(s,i){return super.off(s,i)}emit(s,i){return super.emit(s,i)}get sipDomain(){return this.options.sipDomain}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(ou.AUDIO)&&(this.audio=new oE(this)),this.modules.includes(ou.MSRP)&&(this.msrp=new cE(this)),this.modules.includes(ou.VIDEO)&&(this.video=new uE(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.setConnected(!0),this.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),this.setConnected(!1),setTimeout(this.start.bind(this),5e3))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}subscribe(s,i){const a=!this.listenersList[s]||!this.listenersList[s].length?[i]:[...this.listenersList[s],i];this.listenersList={...this.listenersList,[s]:a}}removeIListener(s){const i={...this.listenersList};delete i[s],this.listenersList={...i}}triggerListener({listenerType:s,session:i,event:l}){const a=this.listenersList[s];!a||!a.length||a.forEach(_=>{_(i,l)})}setInitialized(s){this.initialized=s,this.emit("ready",s)}setConnected(s){this.connected=s,this.emit("connection",s)}}module.exports=fE;
|