opensips-js-vue 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -156,5 +156,5 @@ a=path:${s.getHeader("Use-Path")} msrp://${this._ua._configuration.authorization
156
156
  `),this._newMSRPSession("local",this._request),this._id=this._request.call_id+this._from_tag,new Ir(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:a=>{this.onTransportError(),console.log(a)},onAuthenticated:a=>{this._request=a},onReceiveResponse:a=>{this._receiveInviteResponse(a),a.status_code===200&&(a.parseSDP(!0),this._status=Ae.STATUS_CONFIRMED,this.target_addr=a.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=Ae.STATUS_INVITE_SENT}terminate(s={}){const n=s.cause||U.causes.BYE,i=Me.cloneArray(s.extraHeaders),a=s.body;let e,d=s.status_code,_=s.reason_phrase;if(this._status===Ae.STATUS_TERMINATED)throw new Xn.InvalidStateError(this._status);switch(this.status="terminated",this._status){case Ae.STATUS_NULL:case Ae.STATUS_INVITE_SENT:case Ae.STATUS_1XX_RECEIVED:if(d&&(d<200||d>=700))throw new TypeError(`Invalid status_code: ${d}`);d&&(_=_||U.REASON_PHRASE[d]||"",e=`SIP ;cause=${d} ;text="${_}"`),this._status===Ae.STATUS_NULL||this._status===Ae.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=e):this._status===Ae.STATUS_1XX_RECEIVED&&this._request.cancel(e),this._status=Ae.STATUS_CANCELED,this._failed("local",null,U.causes.CANCELED);break;case Ae.STATUS_WAITING_FOR_ANSWER:case Ae.STATUS_ANSWERED:if(d=d||480,d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);this._request.reply(d,_,i,a),this._failed("local",null,U.causes.REJECTED);break;case Ae.STATUS_WAITING_FOR_ACK:case Ae.STATUS_CONFIRMED:if(_=s.reason_phrase||U.REASON_PHRASE[d]||"",d&&(d<200||d>=700))throw new TypeError(`Invalid status_code: ${d}`);if(d&&i.push(`Reason: SIP ;cause=${d}; text="${_}"`),this._status===Ae.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Wt.C.STATUS_TERMINATED){const u=this._dialog;this.receiveRequest=({method:g})=>{g===U.ACK&&(this.sendRequest(U.BYE,{extraHeaders:i,body:a}),u.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Wt.C.STATUS_TERMINATED&&(this.sendRequest(U.BYE,{extraHeaders:i,body:a}),u.terminate())}),this._ended("local",null,n),this._dialog=u,this._ua.newDialog(u)}else this.sendRequest(U.BYE,{extraHeaders:i,body:a}),this._ended("local",null,n)}}sendRequest(s,n){return this._dialog.sendRequest(s,n)}authenticate(s){this.status="auth";let n=new Qs("");n.method="AUTH",n.addHeader("To-Path",`msrp://${this._ua._configuration.realm}:2856;ws`),n.addHeader("From-Path",`msrp://${this.credentials.username}.${this.credentials.realm}:2856/${this.auth_id};ws`),s&&n.addHeader("Authorization",s.toString());let i=n.toString(),a=[];for(var e=0;e<i.length;e++)a.push(i.charCodeAt(e).toString(16));this._connection.send(n.toString())}onmessage(s){const n=new Qs(s.data);if(this.status==="auth"&&n.code===401){const i=this.parseAuth(n.getHeader("WWW-Authenticate")),a=new bg(this.credentials);a.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},i,Me.createRandomToken(12)),this.authenticate(a)}this.status==="auth"&&n.code===200&&this._direction==="outgoing"?(this.my_addr.push(n.getHeader("To-Path")),this.my_addr.push(n.getHeader("Use-Path")),this.status="active",this.inviteParty(n)):this.status==="auth"&&n.code===200&&this._direction==="incoming"?(this.my_addr.push(n.getHeader("To-Path")),this.my_addr.push(n.getHeader("Use-Path")),this.status="active",this.acceptParty(n),this.emit("confirmed")):n.method==="SEND"&&(this._sendOk(n),this._sendReport(n),n.direction="incoming",this.emit("newMessage",n),this._msgHistory.push(n),this.emit("msgHistoryUpdate",this._msgHistory)),n.code===480&&this._close()}onclose(){console.log("close")}onopen(){const s=new RTCPeerConnection({iceServers:[]});s.createDataChannel(""),s.createOffer().then(s.setLocalDescription.bind(s)),s.onicecandidate=n=>{if(!n||!n.candidate||!n.candidate.candidate)return;const i=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,a=n.candidate.candidate.match(i);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(U.ACK);return}else{const n=new yl(this,s,"UAC");if(n.error!==void 0){console.log(n.error);return}this.sendRequest(U.ACK),this.sendRequest(U.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!==Ae.STATUS_INVITE_SENT&&this._status!==Ae.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(s.status_code):this._status=Ae.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=Ae.STATUS_1XX_RECEIVED,!s.body){this._progress("remote",s);break}const n={originator:"remote",type:"answer",sdp:s.body};console.log('emit "sdp"'),this.emit("sdp",n);const i=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(i)).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=Ae.STATUS_CONFIRMED,!s.body){this._acceptAndTerminate(s,400,U.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",s,U.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(s,"UAC"))break;const n={originator:"remote",type:"answer",sdp:s.body};console.log('emit "sdp"'),this.emit("sdp",n),new RTCSessionDescription({type:"answer",sdp:n.sdp}),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(i=>this._connection.setLocalDescription(i)).catch(i=>{this._acceptAndTerminate(s,500,i.toString()),console.log("failed 4"),this._failed("local",s,U.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(s),this._accepted("remote",s),this.sendRequest(U.ACK),this._confirmed("local",null)});break}default:{const n=Me.sipErrorCause(s.status_code);console.log("failed 5"),this._failed("remote",s,n)}}}sendMSRP(s){const n=new Qs("");n.method="SEND",n.addHeader("To-Path",`${this.my_addr[1]} ${this.target_addr[1]} ${this.target_addr[0]}`),n.addHeader("From-Path",`${this.my_addr[0]}`),n.addHeader("Message-ID",Me.createRandomToken(10)),n.addHeader("Byte-Range","1-25/25"),n.addHeader("Content-Type","text/plain"),n.addHeader("Success-Report","yes"),n.addHeader("Failure-Report","yes"),n.body=s;let i=n.toString();console.log(i);let a=[];for(var e=0;e<i.length;e++)a.push(i.charCodeAt(e).toString(16));console.log(a),this._connection.send(n.toString()),n.direction="outgoing",this.emit("newMessage",n),this._msgHistory.push(n),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(s){let n=s.ident,i=s.getHeader("Message-ID"),a=new Qs("");a.method="200 OK",a.addHeader("To-Path",`${this.my_addr[1]}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",i),a.ident=n;let e=a.toString();console.log(e);let d=[];for(var _=0;_<e.length;_++)d.push(e.charCodeAt(_).toString(16));console.log(d),this._connection.send(a.toString())}_sendReport(s){let n=s.ident,i=s.getHeader("Message-ID"),a=new Qs("");a.method="REPORT",a.addHeader("To-Path",`${s.getHeader("From-Path")}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",i),a.addHeader("Byte-Range","1-25/25"),a.addHeader("Status","000 200 OK"),a.ident=n;let e=a.toString();console.log(e);let d=[];for(var _=0;_<e.length;_++)d.push(e.charCodeAt(_).toString(16));console.log(d),this._connection.send(a.toString())}parseAuth(s){const n={},i=s.replace("Digest","").split(",");for(const a of i){const e=a.trim().split("=");n[e[0]]=e[1].match('^"(.+)"$')[1]}return n}init_incoming(s,n){let i;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=Ae.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")&&(i=s.getHeader("expires")*1e3),s.to_tag=Me.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=Ae.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{s.reply(408),console.log("failed 6"),this._failed("local",null,U.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),i&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Ae.STATUS_WAITING_FOR_ANSWER&&(s.reply(487),console.log("failed 7"),this._failed("system",null,U.causes.EXPIRES))},i)),this._direction="incoming",this._local_identity=s.to,this._remote_identity=s.from,n&&n(this),s.parseSDP(!0),this.target_addr=s.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",s),this._status!==Ae.STATUS_TERMINATED&&(s.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(s,n,i){this.emit("_failed",{originator:s,message:n||null,cause:i}),this._close(),this.emit("failed",{originator:s,message:n||null,cause:i})}_close(){if(console.log("CLOSE SESSION"),this._status!==Ae.STATUS_TERMINATED){if(this._status=Ae.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,n,i){const a=n==="UAS"?s.to_tag:s.from_tag,e=n==="UAS"?s.from_tag:s.to_tag,d=s.call_id+a+e;let _=this._earlyDialogs[d];if(i)return _?!0:(_=new yl(this,s,n,yl.C.STATUS_EARLY),_.error?(console.log("failed 8"),this._failed("remote",s,U.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[d]=_,!0));{if(this._from_tag=s.from_tag,this._to_tag=s.to_tag,_)return _.update(s,n),this._dialog=_,delete this._earlyDialogs[d],!0;const u=new yl(this,s,n);return u.error?(console.log("failed 9"),this._failed("remote",s,U.causes.INTERNAL_ERROR),!1):(this._dialog=u,!0)}}_newMSRPSession(s,n){this._ua.newMSRPSession(this,{originator:s,session:this,request:n})}_progress(s,n){this.emit("progress",{originator:s,response:n||null})}isEnded(){switch(this._status){case Ae.STATUS_CANCELED:case Ae.STATUS_TERMINATED:return!0;default:return!1}}_accepted(s,n){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:s,response:n||null})}_confirmed(s,n){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:s,ack:n||null})}_ended(s,n,i){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:s,message:n||null,cause:i})}_handleSessionTimersInIncomingResponse(s){if(!this._sessionTimers.enabled)return;let n;s.session_expires&&s.session_expires>=U.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=s.session_expires,n=s.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,n="uac"),this._sessionTimers.refresher=n==="uac",this._runSessionTimer()}receiveRequest(s){if(console.log("receiveRequest()"),s.method===U.CANCEL)(this._status===Ae.STATUS_WAITING_FOR_ANSWER||this._status===Ae.STATUS_ANSWERED)&&(this._status=Ae.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",s,U.causes.CANCELED));else switch(s.method){case U.ACK:if(this._status!==Ae.STATUS_WAITING_FOR_ACK)return;if(this._status=Ae.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!s.body){this.terminate({cause:U.causes.MISSING_SDP,status_code:400});break}const n={originator:"remote",type:"answer",sdp:s.body};console.log('emit "sdp"'),this.emit("sdp",n);const i=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(i)).then(()=>{this._is_confirmed||this._confirmed("remote",s)}).catch(a=>{this.terminate({cause:U.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 U.BYE:this._status===Ae.STATUS_CONFIRMED||this._status===Ae.STATUS_WAITING_FOR_ACK?(s.reply(200),this._ended("remote",s,U.causes.BYE)):this._status===Ae.STATUS_INVITE_RECEIVED||this._status===Ae.STATUS_WAITING_FOR_ANSWER?(s.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",s,U.causes.BYE)):s.reply(403,"Wrong Status");break;case U.INVITE:this._status===Ae.STATUS_CONFIRMED?s.hasHeader("replaces")?this._receiveReplaces(s):this._receiveReinvite(s):s.reply(403,"Wrong Status");break;case U.INFO:this._status===Ae.STATUS_1XX_RECEIVED||this._status===Ae.STATUS_WAITING_FOR_ANSWER||this._status===Ae.STATUS_ANSWERED||this._status===Ae.STATUS_WAITING_FOR_ACK||this._status===Ae.STATUS_CONFIRMED?(s.hasHeader("Content-Type")?s.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new Wa(this).init_incoming(s):s.reply(415):s.reply(403,"Wrong Status");break;case U.UPDATE:this._status===Ae.STATUS_CONFIRMED?this._receiveUpdate(s):s.reply(403,"Wrong Status");break;case U.REFER:this._status===Ae.STATUS_CONFIRMED?this._receiveRefer(s):s.reply(403,"Wrong Status");break;case U.NOTIFY:this._status===Ae.STATUS_CONFIRMED?this._receiveNotify(s):s.reply(403,"Wrong Status");break;default:s.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==Ae.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:U.causes.CONNECTION_ERROR,cause:U.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==Ae.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:U.causes.REQUEST_TIMEOUT,cause:U.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==Ae.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:U.causes.DIALOG_ERROR,cause:U.causes.DIALOG_ERROR})}}var fv=Xt();const du=$e(fv),kl=new fl("Parser"),pv=(l,s)=>{let n,i,a=l.indexOf(`\r
157
157
  `);if(a===-1){kl.warn("parseMessage() | no CRLF found, not a SIP message");return}const e=l.substring(0,a);let d=du.parse(e,"Request_Response");if(d===-1){kl.warn(`parseMessage() | error parsing first line of SIP message: "${e}"`);return}else d.status_code?(n=new Ws.IncomingResponse,n.status_code=d.status_code,n.reason_phrase=d.reason_phrase):(n=new Ws.IncomingRequest(s),n.method=d.method,n.ruri=d.uri);n.data=l;let _=a+2;for(;;){if(a=mv(l,_),a===-2){i=_+2;break}else if(a===-1){kl.warn("parseMessage() | malformed message");return}if(d=gv(n,l,_,a),d!==!0){kl.warn("parseMessage() |",d.error);return}_=a+2}if(n.hasHeader("content-length")){const u=n.getHeader("content-length");n.body=l.substr(i,u)}else n.body=l.substring(i);return n};function mv(l,s){let n=s,i=0,a=0;if(l.substring(n,n+2).match(/(^\r\n)/))return-2;for(;i===0;){if(a=l.indexOf(`\r
158
158
  `,n),a===-1)return a;!l.substring(a+2,a+4).match(/(^\r\n)/)&&l.charAt(a+2).match(/(^\s+)/)?n=a+2:i=a}return i}function gv(l,s,n,i){let a;const e=s.indexOf(":",n),d=s.substring(n,e).trim(),_=s.substring(e+1,i).trim();switch(d.toLowerCase()){case"via":case"v":l.addHeader("via",_),l.getHeaders("via").length===1?(a=l.parseHeader("Via"),a&&(l.via=a,l.via_branch=a.branch)):a=0;break;case"from":case"f":l.setHeader("from",_),a=l.parseHeader("from"),a&&(l.from=a,l.from_tag=a.getParam("tag"));break;case"to":case"t":l.setHeader("to",_),a=l.parseHeader("to"),a&&(l.to=a,l.to_tag=a.getParam("tag"));break;case"record-route":if(a=du.parse(_,"Record_Route"),a===-1)a=void 0;else for(const u of a)l.addHeader("record-route",_.substring(u.possition,u.offset)),l.headers["Record-Route"][l.getHeaders("record-route").length-1].parsed=u.parsed;break;case"call-id":case"i":l.setHeader("call-id",_),a=l.parseHeader("call-id"),a&&(l.call_id=_);break;case"contact":case"m":if(a=du.parse(_,"Contact"),a===-1)a=void 0;else for(const u of a)l.addHeader("contact",_.substring(u.possition,u.offset)),l.headers.Contact[l.getHeaders("contact").length-1].parsed=u.parsed;break;case"content-length":case"l":l.setHeader("content-length",_),a=l.parseHeader("content-length");break;case"content-type":case"c":l.setHeader("content-type",_),a=l.parseHeader("content-type");break;case"cseq":l.setHeader("cseq",_),a=l.parseHeader("cseq"),a&&(l.cseq=a.value),l instanceof Ws.IncomingResponse&&(l.method=a.method);break;case"max-forwards":l.setHeader("max-forwards",_),a=l.parseHeader("max-forwards");break;case"www-authenticate":l.setHeader("www-authenticate",_),a=l.parseHeader("www-authenticate");break;case"proxy-authenticate":l.setHeader("proxy-authenticate",_),a=l.parseHeader("proxy-authenticate");break;case"session-expires":case"x":l.setHeader("session-expires",_),a=l.parseHeader("session-expires"),a&&(l.session_expires=a.expires,l.session_expires_refresher=a.refresher);break;case"refer-to":case"r":l.setHeader("refer-to",_),a=l.parseHeader("refer-to"),a&&(l.refer_to=a);break;case"replaces":l.setHeader("replaces",_),a=l.parseHeader("replaces"),a&&(l.replaces=a);break;case"event":case"o":l.setHeader("event",_),a=l.parseHeader("event"),a&&(l.event=a);break;default:l.addHeader(d,_),a=0}return a===void 0?{error:`error parsing header "${d}"`}:!0}const Tv={parseMessage:pv},Lr=new fl("Registrator"),Ul=10;class vv{constructor(s,n){this._reg_id=1,this._ua=s,this._transport=n,this._registrar=s.configuration.registrar_server,this._expires=s.configuration.register_expires,this._call_id=Rn.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 i=this._contact.indexOf(">");if(i!==-1){const a=this._contact.slice(0,i)+this._contact.slice(i+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 n in s)if(Object.prototype.hasOwnProperty.call(s,n)){const i=s[n];this._extraContactParams+=`;${n}`,i&&(this._extraContactParams+=`=${i}`)}}setExtraContactUriParams(s){s instanceof Object||(s={}),this._extraContactParams="";for(const n in s)if(Object.prototype.hasOwnProperty.call(s,n)){const i=s[n];this._extraContactParams+=`;${n}`,i&&(this._extraContactParams+=`=${i}`)}}register(){if(this._registering){Lr.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 n=new St.OutgoingRequest(U.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},s),i=new Ir(this._ua,n,{onRequestTimeout:()=>{this._registrationFailure(null,U.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,U.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")){Lr.debug("no Contact header in response to REGISTER, response ignored");break}const e=a.headers.Contact.reduce((g,p)=>g.concat(p.parsed),[]);let d=e.find(g=>this._sipInstance===g.getParam("+sip.instance")&&this._reg_id===parseInt(g.getParam("reg-id")));if(d||(d=e.find(g=>g.uri.user===this._ua.contact.uri.user)),!d){Lr.debug("no Contact header pointing to us, response ignored");break}this._ua.clearKeepAliveInterval(),this._ua.setLastRegisterTimestamp();let _=d.getParam("expires");!_&&a.hasHeader("expires")&&(_=a.getHeader("expires")),_||(_=this._expires),_=Number(_),_<Ul&&(_=Ul);const u=_>64?_*1e3/2+Math.floor((_/2-32)*1e3*Math.random()):_*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},u),d.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=d.getParam("temp-gruu").replace(/"/g,"")),d.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=d.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<Ul&&(this._expires=Ul),this.register()):(Lr.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(a,U.causes.SIP_FAILURE_CODE));break}default:{const e=Rn.sipErrorCause(a.status_code);this._registrationFailure(a,e)}}}});this._registering=!0,i.send()}unregister(s={}){if(!this._registered){Lr.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const n=this._extraHeaders.slice();s.all?n.push(`Contact: *${this._extraContactParams}`):n.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),n.push("Expires: 0");const i=new St.OutgoingRequest(U.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n);new Ir(this._ua,i,{onRequestTimeout:()=>{this._unregistered(null,U.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,U.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:a=>{switch(!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):this._unregistered(a);break;default:{const e=Rn.sipErrorCause(a.status_code);this._unregistered(a,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,n){this._registering=!1,this._ua.registrationFailed({response:s||null,cause:n}),this._registered&&(this._registered=!1,this._ua.unregistered({response:s||null,cause:n}))}_unregistered(s,n){this._registering=!1,this._registered=!1,this._ua.unregistered({response:s||null,cause:n||null})}}const st=console,es={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},yv=ov;class Ev extends yv{constructor(s){super(s),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this.newStreamPlugins=[],this.processStreamPlugins=[],this.optionsInterval=null,this.lastOptionsTimestamp=null,this.lastRegisterTimestamp=null,this._registrator=new vv(this)}setLastRegisterTimestamp(){this.lastRegisterTimestamp=Date.now()}call(s,n){return super.call(s,n)}joinVideoCall(s,n,i){st.debug("call()");const a=new Dl(this);return a.configureMedia({audio:!0,video:!0}),a.connect(s,n,i),a}startScreenShare(){st.debug("startScreenShare()");for(const s in this._janus_sessions)this._janus_sessions[s].connectScreenShare()}changeMediaConstraints(s){for(const n in this._janus_sessions)this._janus_sessions[n].changeMediaConstraints(s)}startBlur(){for(const s in this._janus_sessions)this._janus_sessions[s].connectBlur()}stopBlur(){for(const s in this._janus_sessions)this._janus_sessions[s].stopBlur()}_loadConfig(s){try{Pr.load(this._configuration,s)}catch(e){throw e}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=Rn.newUUID());let n;typeof window<"u"&&typeof window.document<"u"?n=window==null?void 0:window.navigator.userAgent:typeof self<"u"&&self.navigator&&(n=self.navigator.userAgent),n+=" "+Ne.USER_AGENT,this._configuration.user_agent=s.overrideUserAgent&&typeof s.overrideUserAgent=="function"?s.overrideUserAgent(n):n,s.onTransportCallback&&typeof s.onTransportCallback=="function"&&(this.onTransportCallback=s.onTransportCallback),this._configuration.jssip_id=Rn.createRandomToken(5);const i=this._configuration.uri.clone();i.user=null,this._configuration.hostport_params=i.toString().replace(/^sip:/i,"");try{this._transport=new kT(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=Sv.bind(this),this._transport.onconnect=Cv.bind(this),this._transport.ondisconnect=Av.bind(this),this._transport.ondata=bv.bind(this)}catch(e){throw st.warn(e),new Xn.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 e=this._configuration.uri.clone();e.user=null,e.clearParams(),e.clearHeaders(),this._configuration.registrar_server=e}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new ds("sip",Rn.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(e={}){const d=e.anonymous||null,_=e.outbound||null;let u="<";return d?u+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":u+=this.pub_gruu||this.uri.toString(),_&&(d?!this.temp_gruu:!this.pub_gruu)&&(u+=";ob"),u+=">",u}};const a=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const e in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,e)&&(a.indexOf(e)!==-1?Object.defineProperty(this._configuration,e,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,e,{writable:!1,configurable:!1}));st.debug("configuration parameters after validation:");for(const e in this._configuration)if(Object.prototype.hasOwnProperty.call(Pr.settings,e))switch(e){case"uri":case"registrar_server":st.debug(`- ${e}: ${this._configuration[e]}`);break;case"password":case"ha1":case"authorization_jwt":st.debug(`- ${e}: NOT SHOWN`);break;default:st.debug(`- ${e}: ${JSON.stringify(this._configuration[e])}`)}}newMSRPSession(s,n){s.on("msgHistoryUpdate",i=>{console.log(i)}),this._msrp_sessions[s.id]=s,this.emit("newMSRPSession",n)}newJanusSession(s,n){this._janus_sessions[s.id]=s,this.newStreamPlugins.forEach(i=>{i.setSession(s)}),this.processStreamPlugins.forEach(i=>{i.setSession(s)}),this.emit("newJanusSession",n)}kill(){}destroyMSRPSession(s){delete this._msrp_sessions[s.id]}destroyJanusSession(s){delete this._janus_sessions[s.id]}clearKeepAliveInterval(){clearInterval(this.optionsInterval),this.optionsInterval=null}receiveRequest(s){var n,i,a,e;const d=s.method;if(s.ruri.user!==this._configuration.uri.user&&s.ruri.user!==this._contact.uri.user){st.debug("Request-URI does not point to us"),s.method!==Ne.ACK&&s.reply_sl(404);return}if(s.ruri.scheme===Ne.SIPS){s.reply_sl(416);return}if(Wt.checkTransaction(this,s))return;if(d===Ne.INVITE?new Wt.InviteServerTransaction(this,this._transport,s):d!==Ne.ACK&&d!==Ne.CANCEL&&new Wt.NonInviteServerTransaction(this,this._transport,s),d===Ne.OPTIONS){if(this.lastOptionsTimestamp=Date.now(),this.optionsInterval||(this.emit("initKeepAliveInterval"),this.optionsInterval=setInterval(()=>{const g=Date.now(),p=this.lastOptionsTimestamp>g-35e3,T=this.lastRegisterTimestamp+this._configuration.register_expires*1e3>g;p&&T&&this.emit("keepAliveInterval")},35e3)),this.listeners("newOptions").length===0){s.reply(200);return}new Vh.Options(this).init_incoming(s)}else if(d===Ne.MESSAGE){if(this.listeners("newMessage").length===0){s.reply(405);return}new Vh.Message(this).init_incoming(s)}else if(d===Ne.INVITE&&!s.to_tag&&this.listeners("newRTCSession").length===0){s.reply(405);return}let _,u;if(s.to_tag)if(_=this._findDialog(s.call_id,s.from_tag,s.to_tag),_)_.receiveRequest(s);else if(d===Ne.NOTIFY)if(u=this._findSession(s),u)u.receiveRequest(s);else{if(s.body)try{const g=JSON.parse(s.body)||{};(i=(n=g.plugindata)==null?void 0:n.data)!=null&&i.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(g),(e=(a=g.plugindata)==null?void 0:a.data)!=null&&e.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(g.plugindata.data.unpublished)}catch(g){console.error(g)}s.reply(200)}else d!==Ne.ACK&&s.reply(481);else switch(d){case Ne.INVITE:if(window.RTCPeerConnection)if(s.hasHeader("replaces")){const g=s.replaces;_=this._findDialog(g.call_id,g.from_tag,g.to_tag),_?(u=_.owner,u.isEnded()?s.reply(603):u.receiveRequest(s)):s.reply(481)}else s.body.search(/MSRP/ig)>-1?(u=new hu(this),u.init_incoming(s)):s.body.search(/JANUS/ig)>-1||(u=new mT(this),u.init_incoming(s));else st.warn("INVITE received but WebRTC is not supported"),s.reply(488);break;case Ne.BYE:s.reply(481);break;case Ne.CANCEL:u=this._findSession(s),u?u.receiveRequest(s):st.debug("received CANCEL request for a non existent session");break;case Ne.ACK:break;case Ne.NOTIFY:this.emit("sipEvent",{event:s.event,request:s}),s.reply(200);break;default:s.reply(405);break}}startMSRP(s,n){st.debug("startMSRP()",n);const i=new hu(this);return i.connect(s),i}startJanus(s,n){st.debug("startJanus()",n);const i=new hu(this);return i.connect(s),i}terminateMSRPSessions(s){st.debug("terminateSessions()");for(const n in this._msrp_sessions)this._msrp_sessions[n].isEnded()||this._msrp_sessions[n].terminate(s)}terminateJanusSessions(s){st.debug("terminateSessions()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||this._janus_sessions[n].terminate(s)}enableJanusAudio(s){st.debug("enableJanusAudio()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||(s?this._janus_sessions[n].startAudio():this._janus_sessions[n].stopAudio())}enableJanusVideo(s){st.debug("enableJanusVideo()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||(s?this._janus_sessions[n].startVideo():this._janus_sessions[n].stopVideo())}terminateAllSessions(){for(const s in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,s)){st.debug(`closing session ${s}`);try{this._sessions[s].terminate()}catch(n){console.error(n)}}}stop(s=!0){if(st.debug("stop()"),this._dynConfiguration={},this._status===es.STATUS_USER_CLOSED){st.debug("UA already closed");return}this._registrator.close();const n=Object.keys(this._sessions).length;s&&this.terminateAllSessions();for(const i in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,i)){st.debug(`closing session ${i}`);try{this._msrp_sessions[i].terminate()}catch(a){console.error(a)}}for(const i in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,i)){st.debug(`closing session ${i}`);try{this._janus_sessions[i].terminate()}catch(a){console.error(a)}}for(const i in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,i))try{this._applicants[i].close()}catch(a){console.error(a)}this._status=es.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&&n===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function Sv(l){this.emit("connecting",l)}function Cv(l){this._status!==es.STATUS_USER_CLOSED&&(this._status=es.STATUS_READY,this._error=null,this.emit("connected",l),this._dynConfiguration.register&&this._registrator.register())}function Av(l){const s=["nict","ict","nist","ist"];for(const n of s)for(const i in this._transactions[n])Object.prototype.hasOwnProperty.call(this._transactions[n],i)&&this._transactions[n][i].onTransportError();this.emit("disconnected",l),this._registrator.onTransportClosed(),this._status!==es.STATUS_USER_CLOSED&&(this._status=es.STATUS_NOT_READY,this._error=es.NETWORK_ERROR)}function bv(l){const s=l.transport;let n=l.message;const i=n;if(n=Tv.parseMessage(n,this),this.onTransportCallback&&typeof this.onTransportCallback=="function"&&this.onTransportCallback(n,i),!!n&&!(this._status===es.STATUS_USER_CLOSED&&n instanceof Ws.IncomingRequest)&&WT(n,this,s)){if(n instanceof Ws.IncomingRequest)n.transport=s,this.receiveRequest(n);else if(n instanceof Ws.IncomingResponse){let a;switch(n.method){case Ne.INVITE:a=this._transactions.ict[n.via_branch],a&&a.receiveResponse(n);break;case Ne.ACK:break;default:a=this._transactions.nict[n.via_branch],a&&a.receiveResponse(n);break}}}}const Rv=["roomId","_audioMuted","_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","_localHold","_videoMuted","status","start_time","_remote_identity","audioTag","isOnHold","localMuted","autoAnswer","putOnHoldTimestamp"],Iv=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function qd(l){const s={};return Rv.forEach(n=>{l[n]!==void 0&&(s[n]=l[n])}),s.localHold=l._localHold,s}function Fd(l){const s={};return Iv.forEach(n=>{l[n]!==void 0&&(s[n]=l[n])}),s}function jd(l,s,n){return re(this,null,function*(){const i=l.createMediaStreamSource(s),a=l.createMediaStreamDestination(),e=l.createGain();return i.connect(e),e.connect(a),e.gain.value=n,a.stream})}function wv(l,s,n,i){if($d())return;const a=document.createElement("audio");a.id=s._id,a.className="audioTag",a.srcObject=l,a.setSinkId(n),a.volume=i,a.play(),s.audioTag=a}function Ov(l){if(l&&typeof l.log=="function"&&typeof l.warn=="function"&&typeof l.error=="function")return!0}function $d(){return/Mobi|react-native|Android|iPhone/i.test(navigator.userAgent)}const Nv=ht,Dv=Xt(),kt=new Nv("WebSocketInterface");var kv=class{constructor(l){kt.debug('new() [url:"%s"]',l),this._url=l,this._sip_uri=null,this._via_transport=null,this._ws=null;const s=Dv.parse(l,"absoluteURI");if(s===-1)throw kt.warn(`invalid WebSocket URI: ${l}`),new TypeError(`Invalid argument: ${l}`);if(s.scheme!=="wss"&&s.scheme!=="ws")throw kt.warn(`invalid WebSocket URI scheme: ${s.scheme}`),new TypeError(`Invalid argument: ${l}`);this._sip_uri=`sip:${s.host}${s.port?`:${s.port}`:""};transport=ws`,this._via_transport=s.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(l){this._via_transport=l.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(kt.debug("connect()"),this.isConnected()){kt.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){kt.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),kt.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(l){this._onError(l)}}disconnect(){kt.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(l){return kt.debug("send()"),this.isConnected()?(this._ws.send(l),!0):(kt.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(){kt.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:l,code:s,reason:n}){kt.debug(`WebSocket ${this._url} closed`),l===!1&&kt.debug("WebSocket abrupt disconnection"),this.ondisconnect(!l,s,n)}_onMessage({data:l}){kt.debug("received WebSocket message"),this.ondata(l)}_onError(l){kt.warn(`WebSocket ${this._url} error: `,l)}};const _u=Oo,Uv=Ne,Mv=bn,xv=yt(),Pv=Pd,Lv=Sn(),Hv=Ma(),qv=Xt(),Fv=kv;js("JsSIP")("version %s",_u.version);var jv={C:Uv,Exceptions:Mv,Utils:xv,UA:Pv,URI:Lv,NameAddrHeader:Hv,WebSocketInterface:Fv,Grammar:qv,debug:js,get name(){return _u.title},get version(){return _u.version}};const $v=$e(jv);function fu(l){return l<10?`0${l}`:`${l}`}function Vv(l){let s=l.hours||0,n=l.minutes||0,i=l.seconds||0;i++,i===60&&(i=0,n++,n===60&&(n=0,s++));const a=`${fu(s)}:${fu(n)}:${fu(i)}`;return{seconds:i,minutes:n,hours:s,formatted:a}}var Rt={};Rt.forEach=(l,s,n)=>re(this,null,function*(){const i=[];for(let a=0;a<l.length;a++)if(a in l){const e=Promise.resolve(l[a]).then(d=>s.call(n||globalThis,d,a,l));i.push(e)}yield Promise.all(i)}),Rt.forEachSeries=(l,s,n)=>re(this,null,function*(){for(let i=0;i<l.length;i++)i in l&&(yield s.call(n||globalThis,yield l[i],i,l))}),Rt.map=(l,s,n)=>re(this,null,function*(){const i=[];for(let a=0;a<l.length;a++)a in l&&(i[a]=Promise.resolve(l[a]).then(e=>s.call(n||globalThis,e,a,l)));return Promise.all(i)}),Rt.mapSeries=(l,s,n)=>re(this,null,function*(){const i=[];for(let a=0;a<l.length;a++)a in l&&(i[a]=yield s.call(n||globalThis,yield l[a],a,l));return i}),Rt.find=(l,s,n)=>new Promise((i,a)=>{if(l.length===0)return i();let e=1;for(let d=0;d<l.length;d++){const _=u=>{u?i(l[d]):e===l.length&&i(),e++};Promise.resolve(l[d]).then(u=>s.call(n||globalThis,u,d,l)).then(_).catch(a)}}),Rt.findSeries=(l,s,n)=>re(this,null,function*(){for(let i=0;i<l.length;i++)if(yield s.call(n||globalThis,yield l[i],i,l))return l[i]}),Rt.findIndex=(l,s,n)=>new Promise((i,a)=>{if(l.length===0)return i(-1);let e=1;for(let d=0;d<l.length;d++){const _=u=>{u?i(d):e===l.length&&i(-1),e++};Promise.resolve(l[d]).then(u=>s.call(n||globalThis,u,d,l)).then(_).catch(a)}}),Rt.findIndexSeries=(l,s,n)=>re(this,null,function*(){for(let i=0;i<l.length;i++)if(yield s.call(n||globalThis,yield l[i],i,l))return i}),Rt.some=(l,s,n)=>new Promise((i,a)=>{if(l.length===0)return i(!1);let e=1;for(let d=0;d<l.length;d++){if(!(d in l)){e++;continue}const _=u=>{u?i(!0):e===l.length&&i(!1),e++};Promise.resolve(l[d]).then(u=>s.call(n||globalThis,u,d,l)).then(_).catch(a)}}),Rt.someSeries=(l,s,n)=>re(this,null,function*(){for(let i=0;i<l.length;i++)if(i in l&&(yield s.call(n||globalThis,yield l[i],i,l)))return!0;return!1}),Rt.every=(l,s,n)=>new Promise((i,a)=>{if(l.length===0)return i(!0);let e=1;for(let d=0;d<l.length;d++){if(!(d in l)){e++;continue}const _=u=>{u?e===l.length&&i(!0):i(!1),e++};Promise.resolve(l[d]).then(u=>s.call(n||globalThis,u,d,l)).then(_).catch(a)}}),Rt.everySeries=(l,s,n)=>re(this,null,function*(){for(let i=0;i<l.length;i++)if(i in l&&!(yield s.call(n||globalThis,yield l[i],i,l)))return!1;return!0}),Rt.filter=(l,s,n)=>new Promise((i,a)=>re(this,null,function*(){const e=[];for(let _=0;_<l.length;_++)_ in l&&(e[_]=Promise.resolve(l[_]).then(u=>s.call(n||globalThis,u,_,l)).catch(a));const d=[];for(let _=0;_<e.length;_++)(yield e[_])&&d.push(yield l[_]);i(d)})),Rt.filterSeries=(l,s,n)=>re(this,null,function*(){const i=[];for(let a=0;a<l.length;a++)a in l&&(yield s.call(n||globalThis,yield l[a],a,l))&&i.push(yield l[a]);return i}),Rt.reduce=(l,s,n)=>re(this,null,function*(){if(l.length===0&&n===void 0)throw TypeError("Reduce of empty array with no initial value");let i,a;for(n!==void 0?(a=n,i=0):(a=l[0],i=1),i;i<l.length;i++)i in l&&(a=yield s(yield a,yield l[i],i,l));return a});var Vd={};(function(l){const s=Rt;Object.keys(s).forEach(n=>{const i=n.charAt(0).toUpperCase()+n.slice(1);l[`async${i}`]=function(...a){return re(this,null,function*(){return s[n](this,...a)})}})})(Vd);var Bv=Object.assign(Rt,{instanceMethods:Vd});const Zt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var Kv={exports:{}};(function(l){var s=function(n){var i=Object.prototype,a=i.hasOwnProperty,e=Object.defineProperty||function(ee,V,k){ee[V]=k.value},d,_=typeof Symbol=="function"?Symbol:{},u=_.iterator||"@@iterator",g=_.asyncIterator||"@@asyncIterator",p=_.toStringTag||"@@toStringTag";function T(ee,V,k){return Object.defineProperty(ee,V,{value:k,enumerable:!0,configurable:!0,writable:!0}),ee[V]}try{T({},"")}catch(ee){T=function(V,k,Ce){return V[k]=Ce}}function y(ee,V,k,Ce){var me=V&&V.prototype instanceof ye?V:ye,Ie=Object.create(me.prototype),xe=new J(Ce||[]);return e(Ie,"_invoke",{value:M(ee,k,xe)}),Ie}n.wrap=y;function C(ee,V,k){try{return{type:"normal",arg:ee.call(V,k)}}catch(Ce){return{type:"throw",arg:Ce}}}var w="suspendedStart",R="suspendedYield",b="executing",G="completed",P={};function ye(){}function O(){}function j(){}var pe={};T(pe,u,function(){return this});var Te=Object.getPrototypeOf,N=Te&&Te(Te(ne([])));N&&N!==i&&a.call(N,u)&&(pe=N);var H=j.prototype=ye.prototype=Object.create(pe);O.prototype=j,e(H,"constructor",{value:j,configurable:!0}),e(j,"constructor",{value:O,configurable:!0}),O.displayName=T(j,p,"GeneratorFunction");function $(ee){["next","throw","return"].forEach(function(V){T(ee,V,function(k){return this._invoke(V,k)})})}n.isGeneratorFunction=function(ee){var V=typeof ee=="function"&&ee.constructor;return V?V===O||(V.displayName||V.name)==="GeneratorFunction":!1},n.mark=function(ee){return Object.setPrototypeOf?Object.setPrototypeOf(ee,j):(ee.__proto__=j,T(ee,p,"GeneratorFunction")),ee.prototype=Object.create(H),ee},n.awrap=function(ee){return{__await:ee}};function q(ee,V){function k(Ie,xe,_e,le){var ze=C(ee[Ie],ee,xe);if(ze.type==="throw")le(ze.arg);else{var rt=ze.arg,Ee=rt.value;return Ee&&typeof Ee=="object"&&a.call(Ee,"__await")?V.resolve(Ee.__await).then(function(ge){k("next",ge,_e,le)},function(ge){k("throw",ge,_e,le)}):V.resolve(Ee).then(function(ge){rt.value=ge,_e(rt)},function(ge){return k("throw",ge,_e,le)})}}var Ce;function me(Ie,xe){function _e(){return new V(function(le,ze){k(Ie,xe,le,ze)})}return Ce=Ce?Ce.then(_e,_e):_e()}e(this,"_invoke",{value:me})}$(q.prototype),T(q.prototype,g,function(){return this}),n.AsyncIterator=q,n.async=function(ee,V,k,Ce,me){me===void 0&&(me=Promise);var Ie=new q(y(ee,V,k,Ce),me);return n.isGeneratorFunction(V)?Ie:Ie.next().then(function(xe){return xe.done?xe.value:Ie.next()})};function M(ee,V,k){var Ce=w;return function(me,Ie){if(Ce===b)throw new Error("Generator is already running");if(Ce===G){if(me==="throw")throw Ie;return Ye()}for(k.method=me,k.arg=Ie;;){var xe=k.delegate;if(xe){var _e=W(xe,k);if(_e){if(_e===P)continue;return _e}}if(k.method==="next")k.sent=k._sent=k.arg;else if(k.method==="throw"){if(Ce===w)throw Ce=G,k.arg;k.dispatchException(k.arg)}else k.method==="return"&&k.abrupt("return",k.arg);Ce=b;var le=C(ee,V,k);if(le.type==="normal"){if(Ce=k.done?G:R,le.arg===P)continue;return{value:le.arg,done:k.done}}else le.type==="throw"&&(Ce=G,k.method="throw",k.arg=le.arg)}}}function W(ee,V){var k=V.method,Ce=ee.iterator[k];if(Ce===d)return V.delegate=null,k==="throw"&&ee.iterator.return&&(V.method="return",V.arg=d,W(ee,V),V.method==="throw")||k!=="return"&&(V.method="throw",V.arg=new TypeError("The iterator does not provide a '"+k+"' method")),P;var me=C(Ce,ee.iterator,V.arg);if(me.type==="throw")return V.method="throw",V.arg=me.arg,V.delegate=null,P;var Ie=me.arg;if(!Ie)return V.method="throw",V.arg=new TypeError("iterator result is not an object"),V.delegate=null,P;if(Ie.done)V[ee.resultName]=Ie.value,V.next=ee.nextLoc,V.method!=="return"&&(V.method="next",V.arg=d);else return Ie;return V.delegate=null,P}$(H),T(H,p,"Generator"),T(H,u,function(){return this}),T(H,"toString",function(){return"[object Generator]"});function te(ee){var V={tryLoc:ee[0]};1 in ee&&(V.catchLoc=ee[1]),2 in ee&&(V.finallyLoc=ee[2],V.afterLoc=ee[3]),this.tryEntries.push(V)}function I(ee){var V=ee.completion||{};V.type="normal",delete V.arg,ee.completion=V}function J(ee){this.tryEntries=[{tryLoc:"root"}],ee.forEach(te,this),this.reset(!0)}n.keys=function(ee){var V=Object(ee),k=[];for(var Ce in V)k.push(Ce);return k.reverse(),function me(){for(;k.length;){var Ie=k.pop();if(Ie in V)return me.value=Ie,me.done=!1,me}return me.done=!0,me}};function ne(ee){if(ee){var V=ee[u];if(V)return V.call(ee);if(typeof ee.next=="function")return ee;if(!isNaN(ee.length)){var k=-1,Ce=function me(){for(;++k<ee.length;)if(a.call(ee,k))return me.value=ee[k],me.done=!1,me;return me.value=d,me.done=!0,me};return Ce.next=Ce}}return{next:Ye}}n.values=ne;function Ye(){return{value:d,done:!0}}return J.prototype={constructor:J,reset:function(ee){if(this.prev=0,this.next=0,this.sent=this._sent=d,this.done=!1,this.delegate=null,this.method="next",this.arg=d,this.tryEntries.forEach(I),!ee)for(var V in this)V.charAt(0)==="t"&&a.call(this,V)&&!isNaN(+V.slice(1))&&(this[V]=d)},stop:function(){this.done=!0;var ee=this.tryEntries[0],V=ee.completion;if(V.type==="throw")throw V.arg;return this.rval},dispatchException:function(ee){if(this.done)throw ee;var V=this;function k(le,ze){return Ie.type="throw",Ie.arg=ee,V.next=le,ze&&(V.method="next",V.arg=d),!!ze}for(var Ce=this.tryEntries.length-1;Ce>=0;--Ce){var me=this.tryEntries[Ce],Ie=me.completion;if(me.tryLoc==="root")return k("end");if(me.tryLoc<=this.prev){var xe=a.call(me,"catchLoc"),_e=a.call(me,"finallyLoc");if(xe&&_e){if(this.prev<me.catchLoc)return k(me.catchLoc,!0);if(this.prev<me.finallyLoc)return k(me.finallyLoc)}else if(xe){if(this.prev<me.catchLoc)return k(me.catchLoc,!0)}else if(_e){if(this.prev<me.finallyLoc)return k(me.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(ee,V){for(var k=this.tryEntries.length-1;k>=0;--k){var Ce=this.tryEntries[k];if(Ce.tryLoc<=this.prev&&a.call(Ce,"finallyLoc")&&this.prev<Ce.finallyLoc){var me=Ce;break}}me&&(ee==="break"||ee==="continue")&&me.tryLoc<=V&&V<=me.finallyLoc&&(me=null);var Ie=me?me.completion:{};return Ie.type=ee,Ie.arg=V,me?(this.method="next",this.next=me.finallyLoc,P):this.complete(Ie)},complete:function(ee,V){if(ee.type==="throw")throw ee.arg;return ee.type==="break"||ee.type==="continue"?this.next=ee.arg:ee.type==="return"?(this.rval=this.arg=ee.arg,this.method="return",this.next="end"):ee.type==="normal"&&V&&(this.next=V),P},finish:function(ee){for(var V=this.tryEntries.length-1;V>=0;--V){var k=this.tryEntries[V];if(k.finallyLoc===ee)return this.complete(k.completion,k.afterLoc),I(k),P}},catch:function(ee){for(var V=this.tryEntries.length-1;V>=0;--V){var k=this.tryEntries[V];if(k.tryLoc===ee){var Ce=k.completion;if(Ce.type==="throw"){var me=Ce.arg;I(k)}return me}}throw new Error("illegal catch attempt")},delegateYield:function(ee,V,k){return this.delegate={iterator:ne(ee),resultName:V,nextLoc:k},this.method==="next"&&(this.arg=d),P}},n}(l.exports);try{regeneratorRuntime=s}catch(n){typeof globalThis=="object"?globalThis.regeneratorRuntime=s:Function("r","regeneratorRuntime = r")(s)}})(Kv);var Bd={exports:{}};(function(l){(function(s,n){l.exports?l.exports=n():s.log=n()})($l,function(){var s=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),a=["trace","debug","info","warn","error"];function e(R,b){var G=R[b];if(typeof G.bind=="function")return G.bind(R);try{return Function.prototype.bind.call(G,R)}catch(P){return function(){return Function.prototype.apply.apply(G,[R,arguments])}}}function d(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function _(R){return R==="debug"&&(R="log"),typeof console===n?!1:R==="trace"&&i?d:console[R]!==void 0?e(console,R):console.log!==void 0?e(console,"log"):s}function u(R,b){for(var G=0;G<a.length;G++){var P=a[G];this[P]=G<R?s:this.methodFactory(P,R,b)}this.log=this.debug}function g(R,b,G){return function(){typeof console!==n&&(u.call(this,b,G),this[R].apply(this,arguments))}}function p(R,b,G){return _(R)||g.apply(this,arguments)}function T(R,b,G){var P=this,ye;b=b!=null?b:"WARN";var O="loglevel";typeof R=="string"?O+=":"+R:typeof R=="symbol"&&(O=void 0);function j(H){var $=(a[H]||"silent").toUpperCase();if(!(typeof window===n||!O)){try{window.localStorage[O]=$;return}catch(q){}try{window.document.cookie=encodeURIComponent(O)+"="+$+";"}catch(q){}}}function pe(){var H;if(!(typeof window===n||!O)){try{H=window.localStorage[O]}catch(M){}if(typeof H===n)try{var $=window.document.cookie,q=$.indexOf(encodeURIComponent(O)+"=");q!==-1&&(H=/^([^;]+)/.exec($.slice(q))[1])}catch(M){}return P.levels[H]===void 0&&(H=void 0),H}}function Te(){if(!(typeof window===n||!O)){try{window.localStorage.removeItem(O);return}catch(H){}try{window.document.cookie=encodeURIComponent(O)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(H){}}}P.name=R,P.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},P.methodFactory=G||p,P.getLevel=function(){return ye},P.setLevel=function(H,$){if(typeof H=="string"&&P.levels[H.toUpperCase()]!==void 0&&(H=P.levels[H.toUpperCase()]),typeof H=="number"&&H>=0&&H<=P.levels.SILENT){if(ye=H,$!==!1&&j(H),u.call(P,H,R),typeof console===n&&H<P.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+H},P.setDefaultLevel=function(H){b=H,pe()||P.setLevel(H,!1)},P.resetLevel=function(){P.setLevel(b,!1),Te()},P.enableAll=function(H){P.setLevel(P.levels.TRACE,H)},P.disableAll=function(H){P.setLevel(P.levels.SILENT,H)};var N=pe();N==null&&(N=b),P.setLevel(N,!1)}var y=new T,C={};y.getLogger=function(R){if(typeof R!="symbol"&&typeof R!="string"||R==="")throw new TypeError("You must supply a name when creating a logger.");var b=C[R];return b||(b=C[R]=new T(R,y.getLevel(),y.methodFactory)),b};var w=typeof window!==n?window.log:void 0;return y.noConflict=function(){return typeof window!==n&&window.log===y&&(window.log=w),y},y.getLoggers=function(){return C},y.default=y,y})})(Bd);var Ot=Bd.exports;const In=()=>`${new Date().toISOString()} | metrics`,wn=(l,s,n)=>`${l} | ${s} | ${n}`;Ot.setDefaultLevel(Ot.levels.TRACE);const Gv=l=>{Ot.info(wn(In(),"log ",`set log level to ${l?"verbose":"info"}`)),Ot.setLevel(l?Ot.levels.TRACE:Ot.levels.INFO)},Wv=l=>{const s=[...Object.keys(Ot.levels)];s.includes(l)?(Ot.info(wn(In(),"log ",`update log level to ${l.toLowerCase()}`)),Ot.setLevel(l)):Ot.warn(wn(In(),"log ","Incorrect log level please choose one of "),s)},ke=(l,s,n)=>{n?Ot.debug(wn(In(),l,s),n):Ot.debug(wn(In(),l,s))},pu=(l,s)=>{Ot.info(wn(In(),l,s))},_s=(l,s)=>{Ot.info(wn(In(),l,s))},Ml=(l,s)=>{Ot.warn(wn(In(),l,s))},Js=(l,s)=>{Ot.error(wn(In(),l,s))};function Yv(l){return Math.floor(Math.random()*l).toString()}function Kd(l,s){let n=s;return l.forEach(i=>{n=n.replace(i,"")}),n}function zv(l,s){let n="";for(let i=0;i<s;i+=1)n+=l[Yv(l.length)];return n}function Xv({length:l=20,useLetters:s=!0,useNumbers:n=!0,includeSymbols:i=[],excludeSymbols:a=[]}={}){let e="abcdefghijklmnopqrstuvwxyz",d="0123456789",_=[],u=[],g=[];return s&&(a.length&&(e=Kd(a,e)),u=e.split("")),n&&(a.length&&(d=Kd(a,d)),g=d.split("")),_=[...u,...g,...i],zv(_,l)}var Qv=Xv;const Hr=$e(Qv),Jv=()=>"WebRTCMetrics",Zv=()=>"5.0.3",Le={INBOUND:"inbound",OUTBOUND:"outbound"},On={IDLE:"idle",RUNNING:"running",MUTED:"muted"},qr={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},ey=()=>({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:[]}),Gd={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:Le.INBOUND},Wd={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:Le.OUTBOUND},Yd={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:Le.INBOUND},zd={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:Le.OUTBOUND},ty=l=>{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(l){const n=ot(oe({},l),{audio:{},video:{},data:oe({},l.data),network:oe({},l.network),experimental:oe({},l.experimental)});return Object.keys(l.audio).forEach(i=>{n.audio[i]=oe({},l.audio[i])}),Object.keys(l.video).forEach(i=>{n.video[i]=oe({},l.video[i])}),n}return ot(oe({},s),{audio:{},video:{},data:oe({},s.data),network:oe({},s.network),experimental:oe({},s.experimental)})},ny={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${Hr()}`,cid:`c-${Hr()}`,uid:`u-${Hr()}`,record:!1,ticket:!0},en={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"},F={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"},D={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},Fr={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},mu={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ie={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},gu="config ",sy=(l,s={},n)=>{const i=oe(oe({},n),s);return s.pname||Ml(gu,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${n.pname}'`),s.cid||Ml(gu,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${n.cid}'`),s.uid||Ml(gu,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${n.uid}'`),i.pc=l,i},ry=(l={})=>{const s=oe(oe({},ny),l);return s.name=Jv(),s.version=Zv(),s},jr=(l,s,n,i=!1,a)=>{let e=l.map(d=>{if(!n)return d[s];if(!a)return d[s][n];const _=d[s][a];return _?_[n]:null});return e=e.filter(d=>i?Number.isFinite(d)&&d>0:Number.isFinite(d)),e.length===0?[]:e},ts=l=>l.reduce((s,n)=>s+n,0)/l.length,iy=()=>`probe-${Hr()}`,oy=()=>`coltr-${Hr()}`,Xd=l=>new Promise(s=>setTimeout(s,l)),Tu=(l,s,n)=>{s?l.call(s,n):l(n)},Xe=(l,s,n,i)=>{const a=jr(l,s,n,!0,i);if(a.length===0)return null;const e=a.reduce((d,_)=>d+_,0)/a.length;return e===0?null:a.map(d=>Math.abs(e-d)).reduce((d,_)=>d+_,0)/a.length*100/e},Ze=(l,s,n,i=!1,a)=>{const e=jr(l,s,n,i,a);return e.length===0?null:e.reduce((d,_)=>d+_,0)/e.length},fs=(l,s,n)=>jr(l,s,n).reduce((i,a)=>i+a,0),Qe=(l,s,n,i)=>{const a=jr(l,s,n,!0,i);return a.length===0?null:Math.min(...a)},Je=(l,s,n,i)=>{const a=jr(l,s,n,!1,i);return a.length===0?null:Math.max(...a)},It=(l,s,n,i)=>{const a=l.slice().pop();if(!a)return null;if(!n)return a[s];if(!i)return a[s][n];const e=a[s][i];return e?e[n]:null},ly=l=>l.slice().pop(),pt=(l,s,n)=>{if(!s)return null;const i={};let a=s[D.AUDIO][l];a||(a=n===Le.INBOUND?oe({},Gd):oe({},Wd)),i[D.AUDIO]=a;let e=s[D.VIDEO][l];return e||(e=n===Le.INBOUND?oe({},Yd):oe({},zd)),i[D.VIDEO]=e,i},$r="exporter ",ay="2.0",Qd=(l,s,n)=>{if(!l||l.length===0)return 0;const i=l[l.length-1];if(!i)return 0;const a=i[s][n];if(a){const e=a.total_rtt_ms_out,d=a.total_rtt_measure_out;return!d||!e?Ze(l,s,"delta_rtt_ms_out",!1,n):Number(e/d)}return null},uy=(l,s)=>{if(!l||l.length===0)return 0;const n=l[l.length-1];if(!n)return 0;const i=n[s].total_rtt_connectivity_ms,a=n[s].total_rtt_connectivity_measure;return!a||!i?Ze(l,s,"delta_rtt_connectivity_ms"):Number(i/a)},cy=l=>It(l,"network","local_candidate_type")!=="relay"?`direct/${It(l,"network","local_candidate_protocol")}`:`turn/${It(l,"network","local_candidate_relay_protocol")}`,hy=l=>{const s=It(l,"network","remote_candidate_type"),n=It(l,"network","remote_candidate_protocol");return s!=="relay"?`direct/${n}`:`turn/${n}`};class dy{constructor(s){this._start=null,this._end=null,this._cfg=s,this._referenceReport=null,this._reports=[],this._events=[]}start(){pu($r,"start() - start exporter...");const s=new Date;return this._start=s.toJSON(),s}stop(){pu($r,"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($r,`addReport() - add report to exporter at ${s.timestamp}`),this._reports.push(s))}addCustomEvent(s){this._events.push(s)}reset(){pu($r,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){ke($r,"ticket() - generate ticket");const s=It(this._reports,"audio","total_packets_lost_in"),n=It(this._reports,"audio","total_packets_in"),i=It(this._reports,"video","total_packets_lost_in"),a=It(this._reports,"video","total_packets_in"),e={},d=ly(this._reports);return d&&(Object.keys(d[D.AUDIO]).forEach(_=>{const u=d[D.AUDIO][_];if(e[u.ssrc]={type:D.AUDIO,direction:u.direction},u.direction===Le.INBOUND){const g={avg:Ze(this._reports,D.AUDIO,"delta_jitter_ms_in",!1,_),min:Qe(this._reports,D.AUDIO,"delta_jitter_ms_in",_),max:Je(this._reports,D.AUDIO,"delta_jitter_ms_in",_),volatility:Xe(this._reports,D.AUDIO,"delta_jitter_ms_in",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},p={avg:Ze(this._reports,D.AUDIO,"delta_kbs_in",!1,_),min:Qe(this._reports,D.AUDIO,"delta_kbs_in",_),max:Je(this._reports,D.AUDIO,"delta_kbs_in",_),volatility:Xe(this._reports,D.AUDIO,"delta_kbs_in",_),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Ze(this._reports,D.AUDIO,"delta_KBytes_in",!1,_),min:Qe(this._reports,D.AUDIO,"delta_KBytes_in",_),max:Je(this._reports,D.AUDIO,"delta_KBytes_in",_),volatility:Xe(this._reports,D.AUDIO,"delta_KBytes_in",_),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},y={emodel:{avg:Ze(this._reports,D.AUDIO,"mos_emodel_in",!1,_),min:Qe(this._reports,D.AUDIO,"mos_emodel_in",_),max:Je(this._reports,D.AUDIO,"mos_emodel_in",_),volatility:Xe(this._reports,D.AUDIO,"mos_emodel_in",_)},effective:{avg:Ze(this._reports,D.AUDIO,"mos_in",!1,_),min:Qe(this._reports,D.AUDIO,"mos_in",_),max:Je(this._reports,D.AUDIO,"mos_in",_),volatility:Xe(this._reports,D.AUDIO,"mos_in",_)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},C=It(this._reports,D.AUDIO,"total_packets_lost_in",_),w=It(this._reports,D.AUDIO,"total_packets_in",_),R={lost:C,avg:Math.round((C/(C+w)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[_].jitter=g,e[_].mos=y,e[_].traffic=T,e[_].bitrate=p,e[_].loss=R}else{const g={avg:Ze(this._reports,D.AUDIO,"delta_jitter_ms_out",!1,_),min:Qe(this._reports,D.AUDIO,"delta_jitter_ms_out",_),max:Je(this._reports,D.AUDIO,"delta_jitter_ms_out",_),volatility:Xe(this._reports,D.AUDIO,"delta_jitter_ms_out",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},p={avg:Ze(this._reports,D.AUDIO,"delta_kbs_out",!1,_),min:Qe(this._reports,D.AUDIO,"delta_kbs_out",_),max:Je(this._reports,D.AUDIO,"delta_kbs_out",_),volatility:Xe(this._reports,D.AUDIO,"delta_kbs_out",_),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Ze(this._reports,D.AUDIO,"delta_KBytes_out",!1,_),min:Qe(this._reports,D.AUDIO,"delta_KBytes_out",_),max:Je(this._reports,D.AUDIO,"delta_KBytes_out",_),volatility:Xe(this._reports,D.AUDIO,"delta_KBytes_out",_),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},y={avg:Qd(this._reports,D.AUDIO,_),min:Qe(this._reports,D.AUDIO,"delta_rtt_ms_out",_),max:Je(this._reports,D.AUDIO,"delta_rtt_ms_out",_),volatility:Xe(this._reports,D.AUDIO,"delta_rtt_ms_out",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},C=It(this._reports,D.AUDIO,"total_packets_lost_out",_),w=It(this._reports,D.AUDIO,"total_packets_out",_),R={lost:C,avg:Math.round((C/(C+w)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},b={emodel:{avg:Ze(this._reports,D.AUDIO,"mos_emodel_out",!1,_),min:Qe(this._reports,D.AUDIO,"mos_emodel_out",_),max:Je(this._reports,D.AUDIO,"mos_emodel_out",_),volatility:Xe(this._reports,D.AUDIO,"mos_emodel_out",_)},effective:{avg:Ze(this._reports,D.AUDIO,"mos_out",!1,_),min:Qe(this._reports,D.AUDIO,"mos_out",_),max:Je(this._reports,D.AUDIO,"mos_out",_),volatility:Xe(this._reports,D.AUDIO,"mos_out",_)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};e[_].jitter=g,e[_].rtt=y,e[_].traffic=T,e[_].bitrate=p,e[_].loss=R,e[_].mos=b}}),Object.keys(d[D.VIDEO]).forEach(_=>{const u=d[D.VIDEO][_];if(e[_]={type:D.VIDEO,direction:u.direction},u.direction===Le.INBOUND){const g={avg:Ze(this._reports,D.VIDEO,"delta_jitter_ms_in",!1,_),min:Qe(this._reports,D.VIDEO,"delta_jitter_ms_in",_),max:Je(this._reports,D.VIDEO,"delta_jitter_ms_in",_),volatility:Xe(this._reports,D.VIDEO,"delta_jitter_ms_in",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},p={avg:Ze(this._reports,D.VIDEO,"delta_kbs_in",!1,_),min:Qe(this._reports,D.VIDEO,"delta_kbs_in",_),max:Je(this._reports,D.VIDEO,"delta_kbs_in",_),volatility:Xe(this._reports,D.VIDEO,"delta_kbs_in",_),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Ze(this._reports,D.VIDEO,"delta_KBytes_in",!1,_),min:Qe(this._reports,D.VIDEO,"delta_KBytes_in",_),max:Je(this._reports,D.VIDEO,"delta_KBytes_in",_),volatility:Xe(this._reports,D.VIDEO,"delta_KBytes_in",_),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},y=It(this._reports,D.VIDEO,"total_packets_lost_in",_),C=It(this._reports,D.VIDEO,"total_packets_in",_),w={lost:y,avg:Math.round((y/(y+C)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[_].jitter=g,e[_].traffic=T,e[_].bitrate=p,e[_].loss=w}else{const g={avg:Ze(this._reports,D.VIDEO,"delta_jitter_ms_out",!1,_),min:Qe(this._reports,D.VIDEO,"delta_jitter_ms_out",_),max:Je(this._reports,D.VIDEO,"delta_jitter_ms_out",_),volatility:Xe(this._reports,D.VIDEO,"delta_jitter_ms_out",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},p={avg:Ze(this._reports,D.VIDEO,"delta_kbs_out",!1,_),min:Qe(this._reports,D.VIDEO,"delta_kbs_out",_),max:Je(this._reports,D.VIDEO,"delta_kbs_out",_),volatility:Xe(this._reports,D.VIDEO,"delta_kbs_out",_),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Ze(this._reports,D.VIDEO,"delta_KBytes_out",!1,_),min:Qe(this._reports,D.VIDEO,"delta_KBytes_out",_),max:Je(this._reports,D.VIDEO,"delta_KBytes_out",_),volatility:Xe(this._reports,D.VIDEO,"delta_KBytes_out",_),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},y={avg:Qd(this._reports,D.VIDEO,_),min:Qe(this._reports,D.VIDEO,"delta_rtt_ms_out",_),max:Je(this._reports,D.VIDEO,"delta_rtt_ms_out",_),volatility:Xe(this._reports,D.VIDEO,"delta_rtt_ms_out",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},C=It(this._reports,D.VIDEO,"total_packets_lost_out",_),w=It(this._reports,D.VIDEO,"total_packets_out",_),R={lost:C,avg:Math.round((C/(C+w)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[_].jitter=g,e[_].rtt=y,e[_].traffic=T,e[_].bitrate=p,e[_].loss=R}})),{version:ay,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:e,data:{rtt:{avg:uy(this._reports,"data"),min:Qe(this._reports,"data","delta_rtt_connectivity_ms"),max:Je(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Xe(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((s/(s+n)*100||0)*100)/100}},video:{in:{avg:Math.round((i/(i+a)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:Ze(this._reports,"data","delta_kbs_in"),min:Qe(this._reports,"data","delta_kbs_in"),max:Je(this._reports,"data","delta_kbs_in"),volatility:Xe(this._reports,"data","delta_kbs_in")},out:{avg:Ze(this._reports,"data","delta_kbs_out"),min:Qe(this._reports,"data","delta_kbs_out"),max:Je(this._reports,"data","delta_kbs_out"),volatility:Xe(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:Ze(this._reports,"data","delta_KBytes_in"),min:Qe(this._reports,"data","delta_KBytes_in"),max:Je(this._reports,"data","delta_KBytes_in"),volatility:Xe(this._reports,"data","delta_KBytes_in")},out:{avg:Ze(this._reports,"data","delta_KBytes_out"),min:Qe(this._reports,"data","delta_KBytes_out"),max:Je(this._reports,"data","delta_KBytes_out"),volatility:Xe(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:cy(this._reports),remoteConnection:hy(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 ns="extractor ",Jd=(l,s,n,i)=>{let a=!1;const e=i[s].total_rtt_ms_out,d=i[s].total_rtt_measure_out,_=n?n[s].total_rtt_ms_out:0,u=n?n[s].total_rtt_measure_out:0,g={rtt:null,totalRTT:e,totalRTTMeasurements:d};if(l[F.TIMESTAMP]===i[s].timestamp_out||!Object.prototype.hasOwnProperty.call(l,F.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(l,F.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(a=!0,Number(l[F.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(l[F.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-u===d))return g;const p=1e3*Number(l[F.ROUND_TRIP_TIME]);let T=e+p,y=d+1;return a&&(T=1e3*Number(l[F.TOTAL_ROUND_TRIP_TIME])-_,y=Number(l[F.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-u),{rtt:p,totalRTT:T,totalRTTMeasurements:y}},_y=(l,s,n,i)=>{if(!Object.prototype.hasOwnProperty.call(l,F.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:i[s].total_rtt_connectivity_ms,totalRTTMeasurements:i[s].total_rtt_connectivity_measure};const a=1e3*Number(l[F.CURRENT_ROUND_TRIP_TIME]);let e=i[s].total_rtt_connectivity_ms+a,d=i[s].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(l,F.TOTAL_ROUND_TRIP_TIME)&&(e=1e3*Number(l[F.TOTAL_ROUND_TRIP_TIME])-(n?n[s].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(l,F.RESPONSES_RECEIVED)&&(d=Number(l[F.RESPONSES_RECEIVED])-(n?n[s].total_rtt_connectivity_measure:0)),{rtt:a,totalRTT:e,totalRTTMeasurements:d}},xl=(l,s,n)=>l[F.TIMESTAMP]===n[s].timestamp_out||!Object.prototype.hasOwnProperty.call(l,F.JITTER)?null:1e3*(Number(l[F.JITTER])||0),fy=(l,s)=>{if(!Object.prototype.hasOwnProperty.call(l,F.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(l,F.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:s[D.VIDEO].delta_ms_decode_frame_in,frames_decoded:s[D.VIDEO].total_frames_decoded_in,total_decode_time:s[D.VIDEO].total_time_decoded_in};const n=l[F.FRAMES_DECODED],i=l[F.TOTAL_DECODE_TIME],a=i-s[D.VIDEO].total_time_decoded_in,e=n-s[D.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:e>0?a*1e3/e:0,frames_decoded:n,total_decode_time:i}},py=(l,s)=>{if(!Object.prototype.hasOwnProperty.call(l,F.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(l,F.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:s[D.VIDEO].delta_ms_encode_frame_out,frames_encoded:s[D.VIDEO].total_frames_encoded_out,total_encode_time:s[D.VIDEO].total_time_encoded_out};const n=l[F.FRAMES_ENCODED],i=l[F.TOTAL_ENCODE_TIME],a=i-s[D.VIDEO].total_time_encoded_out,e=n-s[D.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:e>0&&a?a*1e3/e:0,frames_encoded:n,total_encode_time:i}},Zd=(l,s,n,i)=>{if(!Object.prototype.hasOwnProperty.call(l,F.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(l,F.BYTES_SENT))return{packetsSent:n[s].total_packets_out,packetsLost:n[s].total_packets_lost_out,bytesSent:n[s].total_KBytes_out};const a=Number(l[F.PACKETS_SENT])||0-(i?i[s].total_packets_out:0),e=a-n[s].total_packets_out,d=Number(l[F.BYTES_SENT])/1024-(i?i[s].total_KBytes_out:0),_=d-n[s].total_KBytes_out,u=l[F.TIMESTAMP]||Date.now(),g=i?i.timestamp:null;let p=n.timestamp;!p&&g&&(p=g);const T=p?u-p:0,y=T>0?_*.008*1024/T*1e3:0;return{packetsSent:a,deltaPacketsSent:e,KBytesSent:d,deltaKBytesSent:_,kbsSent:y}},e_=(l,s,n,i)=>{let a=n[s].total_packets_lost_out,e=0,d=0;return Object.prototype.hasOwnProperty.call(l,F.PACKETS_LOST)&&(a=Number(l[F.PACKETS_LOST])||0-(i?i[s].total_packets_lost_out:0),e=a-n[s].total_packets_lost_out),Object.prototype.hasOwnProperty.call(l,F.FRACTION_LOST)&&(d=Number(100*l[F.FRACTION_LOST])),{packetsLost:a,deltaPacketsLost:e,fractionLost:d}},t_=(l,s,n,i)=>{if(!Object.prototype.hasOwnProperty.call(l,F.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(l,F.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(l,F.BYTES_RECEIVED))return{percent_packets_lost:n[s].percent_packets_lost_in,packetsReceived:n[s].total_packets_in,packetsLost:n[s].total_packets_lost_in,bytesReceived:n[s].total_KBytes_in};const a=Number(l[F.PACKETS_RECEIVED])||0-(i?i[s].total_packets_in:0),e=Number(l[F.PACKETS_LOST])||0-(i?i[s].total_packets_lost_in:0),d=e-n[s].total_packets_lost_in,_=a-n[s].total_packets_in,u=a!==n[s].total_packets_in?d*100/(d+_):0,g=Number(l[F.BYTES_RECEIVED])/1024-(i?i[s].total_KBytes_in:0),p=g-n[s].total_KBytes_in,T=l[F.TIMESTAMP]||Date.now(),y=i?i.timestamp:null;let C=n.timestamp;!C&&y&&(C=y);const w=C?T-C:0,R=w>0?p*.008*1024/w*1e3:0;return{percentPacketsLost:u,packetsReceived:a,deltaPacketsReceived:_,packetsLost:e,deltaPacketsLost:d,KBytesReceived:g,deltaKBytesReceived:p,kbsReceived:R}},my=l=>l[F.CANDIDATE_TYPE]!=="relay"?"":l[F.RELAY_PROTOCOL]||"",gy=l=>{if(!Object.prototype.hasOwnProperty.call(l,F.NETWORK_TYPE))return Fr.WIFI;switch(l[F.NETWORK_TYPE]){case mu.ETHERNET:return Fr.ETHERNET;case mu.CELLULAR_4G:return Fr.CELLULAR_4G;case mu.WIFI:return Fr.WIFI;default:return Fr.CELLULAR}},n_=l=>!Object.prototype.hasOwnProperty.call(l,F.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(l,F.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:l[F.FRAME_WIDTH]||null,height:l[F.FRAME_HEIGHT]||null,framerate:l[F.FRAMES_PER_SECOND]},Ty=l=>{const s=Object.prototype.hasOwnProperty.call(l,F.QUALITY_LIMITATION_REASON)?l[F.QUALITY_LIMITATION_REASON]:null,n=Object.prototype.hasOwnProperty.call(l,F.QUALITY_LIMITATION_RESOLUTION_CHANGES)?l[F.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,i=Object.prototype.hasOwnProperty.call(l,F.QUALITY_LIMITATION_DURATIONS)?l[F.QUALITY_LIMITATION_DURATIONS]:null;return i&&Object.keys(i).forEach(a=>{i[a]>1e3&&(i[a]=Number(i[a]/1e3))}),{reason:s,durations:i,resolutionChanges:n}},vy=(l,s,n)=>{if(!Object.prototype.hasOwnProperty.call(l,F.PLI)||!Object.prototype.hasOwnProperty.call(l,F.NACK))return{pliCount:s.total_pli_sent_in,nackCount:s.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const i=(l[F.PLI]||0)-(n?n[D.VIDEO].total_pli_sent_in:0),a=(l[F.NACK]||0)-(n?n[D.VIDEO].total_nack_sent_in:0);return{pliCount:i,nackCount:a,deltaPliCount:i-s[D.VIDEO].total_pli_sent_in,deltaNackCount:a-s[D.VIDEO].total_nack_sent_in}},yy=(l,s,n)=>{if(!Object.prototype.hasOwnProperty.call(l,F.PLI)||!Object.prototype.hasOwnProperty.call(l,F.NACK))return{pliCount:s.total_pli_received_out,nackCount:s.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const i=(l[F.PLI]||0)-(n?n[D.VIDEO].total_pli_received_out:0),a=(l[F.NACK]||0)-(n?n[D.VIDEO].total_nack_received_out:0);return{pliCount:i,nackCount:a,deltaPliCount:i-s[D.VIDEO].total_pli_received_out,deltaNackCount:a-s[D.VIDEO].total_nack_received_out}},Ey=l=>({channels:l[F.CHANNELS]||null,clock_rate:l[F.CLOCK_RATE]||null,mime_type:l[F.MIME_TYPE]||null,sdp_fmtp_line:l[F.SDP_FMTP_LINE]||null}),Sy=l=>({clock_rate:l[F.CLOCK_RATE]||null,mime_type:l[F.MIME_TYPE]||null}),Cy=(l,s,n)=>{const i=(l[F.BYTES_RECEIVED]||0)/1024-(n?n.data.total_KBytes_in:0),a=(l[F.BYTES_SENT]||0)/1024-(n?n.data.total_KBytes_out:0),e=l[F.TIMESTAMP]||Date.now(),d=i-s.data.total_KBytes_in,_=a-s.data.total_KBytes_out,u=n?n.timestamp:null;let g=s.timestamp;!g&&u&&(g=u);const p=g?e-g:0,T=p>0?d*.008*1024/p*1e3:0,y=p>0?_*.008*1024/p*1e3:0;return{total_KBytes_received:i,total_KBytes_sent:a,delta_KBytes_received:d,delta_KBytes_sent:_,kbs_speed_received:T,kbs_speed_sent:y}},Ay=l=>{const s=l[F.AVAILABLE_INCOMING_BITRATE]/1024||0,n=l[F.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:s,kbs_outgoing_bandwidth:n}},by=(l,s,n,i)=>{if(!l)return[];switch(l[F.TYPE]){case en.CANDIDATE_PAIR:let a=!1;if(l[F.NOMINATED]&&l[F.STATE]===D.SUCCEEDED&&(a=!0,ke(ns,`analyze() - got stats ${l[F.TYPE]} for ${n}`,l),F.SELECTED in l&&!l[F.SELECTED]&&(a=!1)),a){const d=l[F.LOCAL_CANDIDATE_ID],_=l[F.REMOTE_CANDIDATE_ID],u=Cy(l,s,i),g=Ay(l),p=_y(l,"data",i,s);return[{type:ie.NETWORK,value:{local_candidate_id:d}},{type:ie.NETWORK,value:{remote_candidate_id:_}},{type:ie.DATA,value:{total_KBytes_in:u.total_KBytes_received}},{type:ie.DATA,value:{total_KBytes_out:u.total_KBytes_sent}},{type:ie.DATA,value:{delta_KBytes_in:u.delta_KBytes_received}},{type:ie.DATA,value:{delta_KBytes_out:u.delta_KBytes_sent}},{type:ie.DATA,value:{delta_kbs_in:u.kbs_speed_received}},{type:ie.DATA,value:{delta_kbs_out:u.kbs_speed_sent}},{type:ie.DATA,value:{delta_kbs_bandwidth_in:g.kbs_incoming_bandwidth}},{type:ie.DATA,value:{delta_kbs_bandwidth_out:g.kbs_outgoing_bandwidth}},{type:ie.DATA,value:{delta_rtt_connectivity_ms:p.rtt}},{type:ie.DATA,value:{total_rtt_connectivity_ms:p.totalRTT}},{type:ie.DATA,value:{total_rtt_connectivity_measure:p.totalRTTMeasurements}}]}break;case en.LOCAL_CANDIDATE:if(l[F.ID]===s.network.local_candidate_id)return[{type:ie.NETWORK,value:{infrastructure:gy(l)}},{type:ie.NETWORK,value:{local_candidate_type:l[F.CANDIDATE_TYPE]||""}},{type:ie.NETWORK,value:{local_candidate_protocol:l[F.PROTOCOL]||""}},{type:ie.NETWORK,value:{local_candidate_relay_protocol:my(l)}}];break;case en.REMOTE_CANDIDATE:if(l[F.ID]===s.network.remote_candidate_id)return[{type:ie.NETWORK,value:{remote_candidate_type:l[F.CANDIDATE_TYPE]||""}},{type:ie.NETWORK,value:{remote_candidate_protocol:l[F.PROTOCOL]||""}}];break;case en.INBOUND_RTP:{ke(ns,`analyze() - got stats ${l[F.TYPE]} for ${n}`,l);const d=l[F.SSRC],_=pt(d,s,Le.INBOUND);_&&(_.timestamp=s.timestamp);const u=pt(d,i,Le.INBOUND);if(u&&(u.timestamp=i.timestamp),l[F.MEDIA_TYPE]===D.AUDIO){const g=t_(l,D.AUDIO,_,u),p=xl(l,D.AUDIO,_),T=l[F.CODEC_ID]||"";return[{ssrc:d,type:ie.AUDIO,value:{codec_id_in:T}},{ssrc:d,type:ie.AUDIO,value:{total_packets_in:g.packetsReceived}},{ssrc:d,type:ie.AUDIO,value:{delta_packets_in:g.deltaPacketsReceived}},{ssrc:d,type:ie.AUDIO,value:{total_packets_lost_in:g.packetsLost}},{ssrc:d,type:ie.AUDIO,value:{delta_packets_lost_in:g.deltaPacketsLost}},{ssrc:d,type:ie.AUDIO,value:{percent_packets_lost_in:g.percentPacketsLost}},{ssrc:d,type:ie.AUDIO,value:{total_KBytes_in:g.KBytesReceived}},{ssrc:d,type:ie.AUDIO,value:{delta_KBytes_in:g.deltaKBytesReceived}},{ssrc:d,type:ie.AUDIO,value:{delta_kbs_in:g.kbsReceived}},{ssrc:d,type:ie.AUDIO,value:{delta_jitter_ms_in:p}}]}if(l[F.MEDIA_TYPE]===D.VIDEO){const g=fy(l,_),p=t_(l,D.VIDEO,_,u),T=xl(l,D.VIDEO,_),y=l[F.DECODER_IMPLEMENTATION]||null,C=l[F.CODEC_ID]||null,w=n_(l),R=vy(l,_,u);return[{ssrc:d,type:ie.VIDEO,value:{codec_id_in:C}},{ssrc:d,type:ie.VIDEO,value:{total_packets_in:p.packetsReceived}},{ssrc:d,type:ie.VIDEO,value:{delta_packets_in:p.deltaPacketsReceived}},{ssrc:d,type:ie.VIDEO,value:{total_packets_lost_in:p.packetsLost}},{ssrc:d,type:ie.VIDEO,value:{delta_packets_lost_in:p.deltaPacketsLost}},{ssrc:d,type:ie.VIDEO,value:{percent_packets_lost_in:p.percentPacketsLost}},{ssrc:d,type:ie.VIDEO,value:{total_KBytes_in:p.KBytesReceived}},{ssrc:d,type:ie.VIDEO,value:{delta_KBytes_in:p.deltaKBytesReceived}},{ssrc:d,type:ie.VIDEO,value:{delta_kbs_in:p.kbsReceived}},{ssrc:d,type:ie.VIDEO,value:{delta_jitter_ms_in:T}},{ssrc:d,type:ie.VIDEO,value:{decoder_in:y}},{ssrc:d,type:ie.VIDEO,value:{delta_ms_decode_frame_in:g.delta_ms_decode_frame}},{ssrc:d,type:ie.VIDEO,value:{total_frames_decoded_in:g.frames_decoded}},{ssrc:d,type:ie.VIDEO,value:{total_time_decoded_in:g.total_decode_time}},{ssrc:d,type:ie.VIDEO,value:{total_nack_sent_in:R.nackCount}},{ssrc:d,type:ie.VIDEO,value:{delta_nack_sent_in:R.deltaNackCount}},{ssrc:d,type:ie.VIDEO,value:{total_pli_sent_in:R.pliCount}},{ssrc:d,type:ie.VIDEO,value:{delta_pli_sent_in:R.deltaPliCount}},{ssrc:d,type:ie.VIDEO,value:{size_in:w}}]}break}case en.OUTBOUND_RTP:{ke(ns,`analyze() - got stats ${l[F.TYPE]} for ${n}`,l);const d=l[F.SSRC],_=pt(d,s,Le.OUTBOUND);_&&(_.timestamp=s.timestamp);const u=pt(d,i,Le.OUTBOUND);if(u&&(u.timestamp=i.timestamp),l[F.MEDIA_TYPE]===D.AUDIO){const g=l[F.CODEC_ID]||null,p=Zd(l,D.AUDIO,_,u);return[{ssrc:d,type:ie.AUDIO,value:{codec_id_out:g}},{ssrc:d,type:ie.AUDIO,value:{total_packets_out:p.packetsSent}},{ssrc:d,type:ie.AUDIO,value:{delta_packets_out:p.deltaPacketsSent}},{ssrc:d,type:ie.AUDIO,value:{total_KBytes_out:p.KBytesSent}},{ssrc:d,type:ie.AUDIO,value:{delta_KBytes_out:p.deltaKBytesSent}},{ssrc:d,type:ie.AUDIO,value:{delta_kbs_out:p.kbsSent}}]}if(l[F.MEDIA_TYPE]===D.VIDEO){const g=l[F.ENCODER_IMPLEMENTATION]||null,p=l[F.CODEC_ID]||null,T=py(l,_),y=n_(l),C=Ty(l),w=yy(l,_,u),R=Zd(l,D.VIDEO,_,u);return[{ssrc:d,type:ie.VIDEO,value:{codec_id_out:p}},{ssrc:d,type:ie.VIDEO,value:{total_packets_out:R.packetsSent}},{ssrc:d,type:ie.VIDEO,value:{delta_packets_out:R.deltaPacketsSent}},{ssrc:d,type:ie.VIDEO,value:{total_KBytes_out:R.KBytesSent}},{ssrc:d,type:ie.VIDEO,value:{delta_KBytes_out:R.deltaKBytesSent}},{ssrc:d,type:ie.VIDEO,value:{delta_kbs_out:R.kbsSent}},{ssrc:d,type:ie.VIDEO,value:{encoder_out:g}},{ssrc:d,type:ie.VIDEO,value:{delta_ms_encode_frame_out:T.delta_ms_encode_frame}},{ssrc:d,type:ie.VIDEO,value:{total_frames_encoded_out:T.frames_encoded}},{ssrc:d,type:ie.VIDEO,value:{total_time_encoded_out:T.total_encode_time}},{ssrc:d,type:ie.VIDEO,value:{total_nack_received_out:w.nackCount}},{ssrc:d,type:ie.VIDEO,value:{delta_nack_received_out:w.deltaNackCount}},{ssrc:d,type:ie.VIDEO,value:{total_pli_received_out:w.pliCount}},{ssrc:d,type:ie.VIDEO,value:{delta_pli_received_out:w.deltaPliCount}},{ssrc:d,type:ie.VIDEO,value:{size_out:y}},{ssrc:d,type:ie.VIDEO,value:{limitation_out:C}}]}break}case en.MEDIA_SOURCE:{ke(ns,`analyze() - got stats ${l[F.TYPE]} for ${n}`,l);break}case en.TRACK:{ke(ns,`analyze() - got stats ${l[F.TYPE]} for ${n}`,l);break}case en.CODEC:const e=[];return Object.keys(s[D.AUDIO]).forEach(d=>{const _=s[D.AUDIO][d];if(_.codec_id_in===l[F.ID]||_.codec_id_out===l[F.ID]){ke(ns,`analyze() - got stats ${l[F.TYPE]} for ${n}`,l);const u=Ey(l);l[F.ID]===_.codec_id_in?e.push({ssrc:_.ssrc,type:ie.AUDIO,value:{codec_in:u}}):e.push({ssrc:_.ssrc,type:ie.AUDIO,value:{codec_out:u}})}}),Object.keys(s[D.VIDEO]).forEach(d=>{const _=s[D.VIDEO][d];if(_.codec_id_in===l[F.ID]||_.codec_id_out===l[F.ID]){ke(ns,`analyze() - got stats ${l[F.TYPE]} for ${n}`,l);const u=Sy(l);l[F.ID]===_.codec_id_in?e.push({ssrc:_.ssrc,type:ie.VIDEO,value:{codec_in:u}}):e.push({ssrc:_.ssrc,type:ie.VIDEO,value:{codec_out:u}})}}),e;case en.REMOTE_INBOUND_RTP:{ke(ns,`analyze() - got stats ${l[F.TYPE]} for ${n}`,l);const d=l[F.SSRC],_=pt(d,s,Le.OUTBOUND),u=pt(d,i,Le.OUTBOUND);if(l[F.KIND]===D.AUDIO){const g=Jd(l,D.AUDIO,u,_),p=xl(l,D.AUDIO,_),T=e_(l,D.AUDIO,_,u);return[{ssrc:d,type:ie.AUDIO,value:{delta_rtt_ms_out:g.rtt}},{ssrc:d,type:ie.AUDIO,value:{total_rtt_ms_out:g.totalRTT}},{ssrc:d,type:ie.AUDIO,value:{total_rtt_measure_out:g.totalRTTMeasurements}},{ssrc:d,type:ie.AUDIO,value:{delta_jitter_ms_out:p}},{ssrc:d,type:ie.AUDIO,value:{timestamp_out:l[F.TIMESTAMP]}},{ssrc:d,type:ie.AUDIO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:d,type:ie.AUDIO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:d,type:ie.AUDIO,value:{percent_packets_lost_out:T.fractionLost}}]}if(l[F.KIND]===D.VIDEO){const g=Jd(l,D.VIDEO,u,_),p=xl(l,D.VIDEO,_),T=e_(l,D.VIDEO,_,u);return[{ssrc:d,type:ie.VIDEO,value:{delta_rtt_ms_out:g.rtt}},{ssrc:d,type:ie.VIDEO,value:{total_rtt_ms_out:g.totalRTT}},{ssrc:d,type:ie.VIDEO,value:{total_rtt_measure_out:g.totalRTTMeasurements}},{ssrc:d,type:ie.VIDEO,value:{delta_jitter_ms_out:p}},{ssrc:d,type:ie.VIDEO,value:{timestamp_out:l[F.TIMESTAMP]}},{ssrc:d,type:ie.VIDEO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:d,type:ie.VIDEO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:d,type:ie.VIDEO,value:{percent_packets_lost_out:T.fractionLost}}]}break}}return[]},Pl=l=>l<0?1:l>100?4.5:1+.035*l+7/1e6*l*(l-60)*(100-l),Ry=(l,s=D.AUDIO,n,i,a)=>{const e=pt(a,l,Le.INBOUND),d=pt(a,n,Le.INBOUND),_=pt(a,i,Le.INBOUND),u=[],g=[],p=e[s].percent_packets_lost_in,T=e[s].delta_jitter_ms_in,y=d&&d[s].delta_jitter_ms_in||null,C=_&&_[s].delta_jitter_ms_in||null,w=l.data.delta_rtt_connectivity_ms,R=n&&n.data.delta_rtt_connectivity_ms||null,b=i&&i.data.delta_rtt_connectivity_ms||null;w&&u.push(w),R&&u.push(R),b&&u.push(b),T&&g.push(T),n&&y&&g.push(y),i&&C&&g.push(C);const G=u.length>0?ts(u):100,P=g.length>0?ts(g):10,ye=93.2-p,O=.18*ye*ye-27.9*ye+1126.62,j=(G+P)/2,pe=j-177.3<0?0:1,Te=.024*j+.11*(j-177.3)*pe,N=O-Te;return Pl(N)},Iy=(l,s=D.AUDIO,n,i,a)=>{const e=pt(a,l,Le.OUTBOUND),d=pt(a,n,Le.OUTBOUND),_=pt(a,i,Le.OUTBOUND),u=[],g=[],p=e[s].percent_packets_lost_out,T=e[s].delta_rtt_ms_out,y=d&&d[s].delta_rtt_ms_out||null,C=_&&_[s].delta_rtt_ms_out||null,w=e[s].delta_jitter_ms_out,R=d&&d[s].delta_jitter_ms_out||null,b=_&&_[s].delta_jitter_ms_out||null,G=l.data.delta_rtt_connectivity_ms,P=n&&n.data.delta_rtt_connectivity_ms||null,ye=i&&i.data.delta_rtt_connectivity_ms||null;T?u.push(T):G&&u.push(G),y?u.push(y):P&&u.push(P),C?u.push(C):ye&&u.push(ye),w&&g.push(w),n&&R&&g.push(R),i&&b&&g.push(b);const O=u.length>0?ts(u):100,j=g.length>0?ts(g):10,pe=93.2-p,Te=.18*pe*pe-27.9*pe+1126.62,N=(O+j)/2,H=N-177.3<0?0:1,$=.024*N+.11*(N-177.3)*H,q=Te-$;return Pl(q)},wy=(l,s=D.AUDIO,n,i,a)=>{const e=pt(a,l,Le.INBOUND),d=pt(a,n,Le.INBOUND),_=pt(a,i,Le.INBOUND),u=[],g=[],p=e[s].percent_packets_lost_in/100,T=e[s].delta_jitter_ms_in,y=d&&d[s].delta_jitter_ms_in||null,C=_&&_[s].delta_jitter_ms_in||null,w=l.data.delta_rtt_connectivity_ms,R=n&&n.data.delta_rtt_connectivity_ms||null,b=i&&i.data.delta_rtt_connectivity_ms||null;w&&u.push(w),R&&u.push(R),b&&u.push(b),T&&g.push(T),d&&y&&g.push(y),_&&C&&g.push(C);const G=u.length>0?ts(u):100,P=g.length>0?ts(g):10,ye=0,O=19.8,j=29.7,pe=30,Te=(G+P)/2+pe,N=Te-177.3<0?0:1,H=.024*Te+.11*(Te-177.3)*N,$=93.2-(ye+O*Math.log(1+j*p)+H);return Pl($)},Oy=(l,s=D.AUDIO,n,i,a)=>{const e=pt(a,l,Le.OUTBOUND),d=pt(a,n,Le.OUTBOUND),_=pt(a,i,Le.OUTBOUND),u=[],g=[],p=e[s].percent_packets_lost_out/100,T=e[s].delta_rtt_ms_out,y=d&&d[s].delta_rtt_ms_out||null,C=_&&_[s].delta_rtt_ms_out||null,w=e[s].delta_jitter_ms_out,R=d&&d[s].delta_jitter_ms_out||null,b=_&&_[s].delta_jitter_ms_out||null,G=l.data.delta_rtt_connectivity_ms,P=n&&n.data.delta_rtt_connectivity_ms||null,ye=i&&i.data.delta_rtt_connectivity_ms||null;T?u.push(T):G&&u.push(G),y?u.push(y):P&&u.push(P),C?u.push(C):ye&&u.push(ye),w&&g.push(w),d&&R&&g.push(R),_&&b&&g.push(b);const O=u.length>0?ts(u):100,j=g.length>0?ts(g):10,pe=0,Te=19.8,N=29.7,H=30,$=(O+j)/2+H,q=$-177.3<0?0:1,M=.024*$+.11*($-177.3)*q,W=93.2-(pe+Te*Math.log(1+N*p)+M);return Pl(W)};class Ny{constructor(s,n){this._callbacks={onreport:null,onticket:null},this._id=oy(),this._moduleName=this._id,this._probeId=n,this._config=s,this._exporter=new dy(s),this._state=On.IDLE,this.registerToPCEvents(),_s(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(s,n,i,a){const e=(u,g)=>u===D.AUDIO?g===en.INBOUND_RTP?oe({},Gd):oe({},Wd):g===en.INBOUND_RTP?oe({},Yd):oe({},zd),d=ty(n);d.pname=this._config.pname,d.call_id=this._config.cid,d.user_id=this._config.uid,d.count=n?n.count+1:1;let _=null;return s.forEach(u=>{!_&&u.timestamp&&(_=u.timestamp),by(u,d,d.pname,a).forEach(g=>{if(g.value&&g.type)if(g.ssrc){let p=d[g.type][g.ssrc];p||(p=e(g.type,u.type),p.ssrc=g.ssrc,d[g.type][g.ssrc]=p),Object.keys(g.value).forEach(T=>{p[T]=g.value[T]})}else Object.keys(g.value).forEach(p=>{d[g.type][p]=g.value[p]})})}),d.timestamp=_,Object.keys(d[D.AUDIO]).forEach(u=>{const g=d[D.AUDIO][u];g.direction===Le.INBOUND?(g.mos_emodel_in=Ry(d,D.AUDIO,n,i,g.ssrc),g.mos_in=wy(d,D.AUDIO,n,i,g.ssrc)):(g.mos_emodel_out=Iy(d,D.AUDIO,n,i,g.ssrc),g.mos_out=Oy(d,D.AUDIO,n,i,g.ssrc))}),d}takeReferenceStats(){return re(this,null,function*(){return new Promise((s,n)=>{const i=Date.now();setTimeout(()=>re(this,null,function*(){try{const a=Date.now()-i,e=Date.now(),d=yield this._config.pc.getStats(),_=this.analyze(d,null,null,null),u=Date.now();_.experimental.time_to_measure_ms=u-e,_.experimental.time_to_wait_ms=a,this._exporter.saveReferenceReport(_),ke(this._moduleName,`got reference report for probe ${this._probeId}`),s()}catch(a){n(a)}}),this._config.startAfter)})})}collectStats(){return re(this,null,function*(){try{if(this._state!==On.RUNNING||!this._config.pc)return ke(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const s=Date.now(),n=yield this._config.pc.getStats(),i=this.analyze(n,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),a=Date.now();return i.experimental.time_to_measure_ms=a-s,this._exporter.addReport(i),ke(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(i),i}catch(s){return Js(this._moduleName,`got error ${s}`),null}})}start(){return re(this,null,function*(){ke(this._moduleName,"starting"),this.state=On.RUNNING,this._startedTime=this._exporter.start(),ke(this._moduleName,"started")})}mute(){return re(this,null,function*(){this.state=On.MUTED,ke(this._moduleName,"muted")})}unmute(){return re(this,null,function*(){this.state=On.RUNNING,ke(this._moduleName,"unmuted")})}stop(s){return re(this,null,function*(){if(ke(this._moduleName,`stopping${s?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=On.IDLE,this._config.ticket){const{ticket:n}=this._exporter;this.fireOnTicket(n)}this._exporter.reset(),ke(this._moduleName,"stopped")})}registerCallback(s,n,i){s in this._callbacks?(this._callbacks[s]={callback:n,context:i},ke(this._moduleName,`registered callback '${s}'`)):Js(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}'`)):Js(this._moduleName,`can't unregister callback for '${s}' - not found`)}fireOnReport(s){this._callbacks.onreport&&Tu(this._callbacks.onreport.callback,this._callbacks.onreport.context,s)}fireOnTicket(s){this._callbacks.onticket&&Tu(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,n,i,a){this._exporter.addCustomEvent({at:typeof s=="object"?s.toJSON():s,category:n,name:i,description:a})}registerToPCEvents(){return re(this,null,function*(){const{pc:s}=this._config;if(navigator.mediaDevices.ondevicechange=()=>re(this,null,function*(){try{const n=yield navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${n.length} devices found`,"Media Devices state")}catch(n){Js(this._moduleName,"can't get devices")}}),s){s.oniceconnectionstatechange=()=>{const i=s.iceConnectionState;i===qr.CONNECTED||i===qr.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",i,"ICE connection state"):i===qr.DISCONNECTED||i===qr.FAILED?this.addCustomEvent(new Date().toJSON(),"call",i,"ICE connection state"):i===qr.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},s.onicegatheringstatechange=()=>{const i=s.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",i,"ICE gathering state")},s.ontrack=i=>{this.addCustomEvent(new Date().toJSON(),"call",`${i.track.kind}track`,"MediaStreamTrack received")},s.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const n=s.getReceivers();if(n&&n.length>0){const i=n[0],{transport:a}=i;if(a){const{iceTransport:e}=a;e&&(e.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}})}}class Dy{constructor(s){this._id=s.pname&&s.pname.substr(0,12).padEnd(12," ")||iy(),this._moduleName=this._id,_s(this._moduleName,"probe created"),this._config=s,this._collector=new Ny(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,n,i,a=new Date().toJSON()){this._collector.addCustomEvent(a,n,s,i)}get isRunning(){return this._collector.state===On.RUNNING}get isIdle(){return this._collector.state===On.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){Ml(this._moduleName,"probe is already running");return}this._collector.start()}stop(s=!1){this.isRunning&&this._collector.stop(s)}takeReferenceStats(){return re(this,null,function*(){return this._collector.takeReferenceStats()})}collectStats(){return re(this,null,function*(){return this._collector.collectStats()})}}const Nt="engine ";class ky{constructor(s){this._config=s,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},_s(Nt,`configured for probing every ${this._config.refreshEvery}ms`),_s(Nt,`configured for starting after ${this._config.startAfter}ms`),_s(Nt,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),ke(Nt,"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,n){if(!s)throw new Error("undefined peer connection");const i=sy(s,n,this._config),a=new Dy(i);return this._probes.push(a),ke(Nt,`${this._probes.length} probes registered`),a}removeExistingProbe(s){if(!s)throw new Error("undefined probe");s.state===On.RUNNING&&s.stop(),this._probes=this._probes.filter(n=>s.id!==n.id)}start(){return re(this,null,function*(){const s=()=>{this._probes.forEach(e=>e.start())},n=()=>re(this,null,function*(){return Promise.all(this._probes.map(e=>e.takeReferenceStats()))}),i=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,a=()=>re(this,null,function*(){const e=ey(),d=this._probes.filter(_=>_.isRunning);for(const _ of d){const u=yield _.collectStats();u&&e.probes.push(u),ke(Nt,`got probe ${_.id}`),yield Xd(0)}return e.delta_time_to_measure_probes_ms=fs(e.probes,"experimental","time_to_measure_ms"),e.delta_KBytes_in=fs(e.probes,"data","delta_KBytes_in"),e.delta_KBytes_out=fs(e.probes,"data","delta_KBytes_out"),e.delta_kbs_in=fs(e.probes,"data","delta_kbs_in"),e.delta_kbs_out=fs(e.probes,"data","delta_kbs_out"),e.total_time_decoded_in=fs(e.probes,"video","total_time_decoded_in"),e.total_time_encoded_out=fs(e.probes,"video","total_time_encoded_out"),e});for(ke(Nt,"starting to collect"),s(),ke(Nt,"generating reference reports..."),yield n(),ke(Nt,"reference reports generated"),this._startedTime=Date.now();i();)if(ke(Nt,`wait ${this._config.refreshEvery}ms before collecting`),yield Xd(this._config.refreshEvery),i()){ke(Nt,"collecting...");const e=Date.now(),d=yield a(),_=Date.now();d.delta_time_consumed_to_measure_ms=_-e,this.fireOnReports(d),ke(Nt,"collected")}ke(Nt,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)})}stop(s){const n=i=>{this._probes.forEach(a=>{a.stop(i)})};_s(Nt,"stop collecting"),n(s)}registerCallback(s,n,i){s in this._callbacks?(this._callbacks[s]={callback:n,context:i},ke(Nt,`registered callback '${s}'`)):Js(Nt,`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}'`)):Js(this._moduleName,`can't unregister callback for '${s}' - not found`)}fireOnReports(s){this._callbacks.onresult&&s.probes.length>0&&Tu(this._callbacks.onresult.callback,this._callbacks.onresult.context,s)}}const Uy="interface ";class My{constructor(s){this._config=ry(s),_s(Uy,`welcome to ${this._config.name} version ${this._config.version}`),Gv(this._config.verbose||!1),this._engine=new ky(this._config)}setupLogLevel(s){Wv(s)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(s,n){return this._engine.addNewProbe(s,n)}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 xy(l,s){return Object.keys(l).filter(n=>s.includes(n)).reduce((n,i)=>{const a=i;return ot(oe({},n),{[a]:l[a]})},{})}const Py=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"];class Ly{constructor(s){this.intervals={},this.analysers={},this.emitInterval=s.emitInterval||200,this.onChangeFunction=s.onChangeFunction}start(s,n,i){return re(this,null,function*(){n&&n.getTracks().length&&(yield this.beginCalculation(s,n,i))})}stop(s){this.clearVolumeInterval(s),this.analysers[s]&&(this.analysers[s].disconnect(),delete this.analysers[s])}clearVolumeInterval(s){this.intervals[s]&&(clearInterval(this.intervals[s]),delete this.intervals[s])}clearAllIntervals(){Object.keys(this.intervals).forEach(s=>{this.stop(s)}),this.intervals={},this.analysers={}}beginCalculation(s,n,i){return re(this,null,function*(){this.clearVolumeInterval(i);const a=s.createAnalyser(),e=s.createMediaStreamSource(n);a.smoothingTimeConstant=.8,a.fftSize=1024,e.connect(a),this.analysers[i]=a,this.intervals[i]=setInterval(()=>{const d=new Uint8Array(a.frequencyBinCount);a.getByteFrequencyData(d);let _=0;const u=d.length;for(let p=0;p<u;p++)_+=d[p];const g=_/u;this.onChangeFunction(i,g)},this.emitInterval)})}}class Hy{constructor(){this.resumePromise=null,this.stateChangeCount=0,this.lastStateChange=Date.now(),this.resumeAttempts=0,this.context=new AudioContext,this.context.addEventListener("statechange",()=>{this.stateChangeCount++;const s=Date.now();this.lastStateChange=s})}getContext(){return re(this,null,function*(){return this.context.state==="suspended"&&(this.resumeAttempts++,this.resumePromise||(this.resumePromise=this.context.resume().then(()=>{this.resumePromise=null}).catch(s=>{throw this.resumePromise=null,s})),yield this.resumePromise),this.context})}get rawContext(){return this.context}getDebugInfo(){return{state:this.context.state,sampleRate:this.context.sampleRate,currentTime:this.context.currentTime,stateChangeCount:this.stateChangeCount,resumeAttempts:this.resumeAttempts,lastStateChange:new Date(this.lastStateChange).toISOString(),hasResumePromise:!!this.resumePromise,documentHidden:document.hidden,documentVisibility:document.visibilityState}}}const Ll={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},qy=0;class Fy{constructor(s){this.isAutoAnswer=!1,this.muteWhenJoinEnabled=!1,this.isDNDEnabled=!1,this.isCallWaitingEnabled=!0,this.muted=!1,this.microphoneInputLevelValue=1,this.speakerVolumeValue=1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.conferenceNodes={},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.managedAudioContext=new Hy,this.context=s,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new Ly({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices()}get sipOptions(){return ot(oe({},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 isCallWaiting(){return this.isCallWaitingEnabled}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 hasActiveAnsweredCalls(){return Object.values(this.activeRooms).filter(s=>!s.incomingInProgress).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(s=>s.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(s=>s.kind==="audiooutput")}get getUserMediaConstraints(){return $d()?{video:!1,audio:!0}:{audio:{deviceId:{exact:this.selectedMediaDevices.input}},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(s){this.availableMediaDevices=s,this.context.emit("changeAvailableDeviceList",s)}updateDeviceList(){return re(this,null,function*(){yield navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const s=yield navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(s)})}initializeMediaDevices(){return re(this,null,function*(){const s=localStorage.getItem(Ll.SELECTED_INPUT_DEVICE)||"default",n=localStorage.getItem(Ll.SELECTED_OUTPUT_DEVICE)||"default";try{const i=yield navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),a=yield navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(a),yield this.setMicrophone(s),yield this.setSpeaker(n),navigator.mediaDevices.addEventListener("devicechange",()=>re(this,null,function*(){const e=yield navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(e)})),i.getTracks().forEach(e=>e.stop())}catch(i){console.error(i)}})}cleanupConferenceNodes(s){return re(this,null,function*(){const n=this.conferenceNodes[s];if(!n)return;let i=0;n.sources.forEach((d,_)=>{try{d.disconnect(),i++}catch(u){console.error(`[cleanupConferenceNodes] Error disconnecting source ${_}:`,u)}});let a=0;n.destinations.forEach((d,_)=>{try{d.disconnect(),a++}catch(u){console.error(`[cleanupConferenceNodes] Error disconnecting destination ${_}:`,u)}});let e=0;n.gains.forEach((d,_)=>{try{d.disconnect(),e++}catch(u){console.error(`[cleanupConferenceNodes] Error disconnecting gain ${_}:`,u)}}),delete this.conferenceNodes[s]})}setCallTime(s){const n=oe({},s);delete n.callId,this.callTime=ot(oe({},this.callTime),{[s.callId]:n}),this.context.emit("changeCallTime",this.callTime)}removeCallTime(s){const n=oe({},this.callTime);delete n[s],this.callTime=oe({},n),this.context.emit("changeCallTime",this.callTime)}setTimeInterval(s,n){this.timeIntervals=ot(oe({},this.timeIntervals),{[s]:n})}removeTimeInterval(s){const n=oe({},this.timeIntervals);n[s]&&(clearInterval(n[s]),delete n[s],this.timeIntervals=oe({},n))}stopCallTimer(s){this.removeTimeInterval(s),this.removeCallTime(s)}emitVolumeChange(s,n){this.context.emit("changeCallVolume",{callId:s,volume:n})}setMetricsConfig(s){this.metricConfig=oe(oe({},this.metricConfig),s)}sendDTMF(s,n){if(!/^[A-D0-9*#]+$/g.test(n))throw new Error("Not allowed character used in the DTMF input");this.extendedCalls[s].sendDTMF(n)}setIsMuted(s){this.muted=s,this.context.emit("changeIsMuted",s)}processMute(s){const n=this.currentActiveRoomId;this.setIsMuted(s),this.initialStreamValue.getTracks().forEach(i=>i.enabled=!s),this.roomReconfigure(n)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}processHold(a){return re(this,arguments,function*({callId:s,toHold:n,automatic:i}){const e=this.extendedCalls[s];if(!e)return;e._automaticHold=i!=null?i:!1;const d=new Promise((_,u)=>{const g=setTimeout(()=>{u(new Error("Hold operation timeout"))},5e3),p=()=>{clearTimeout(g),e.putOnHoldTimestamp=n?Date.now():void 0,_()},T=y=>{clearTimeout(g),u(y)};try{n?e.hold({},p):e.unhold({},p)}catch(y){T(y)}});try{yield d,this.updateCall(e);const _=Object.values(this.extendedCalls).filter(u=>u.roomId===e.roomId&&(n?s!==u._id:!0));_.length>1&&(yield this.doConference(_))}catch(_){throw console.error("Hold operation failed:",_),_}})}holdCall(s,n=!1){return this.processHold({callId:s,automatic:n,toHold:!0})}unholdCall(s){return this.processHold({callId:s,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(s=>s.direction==="outgoing"&&s.status===qy).forEach(s=>this.terminateCall(s._id))}answerCall(s){const n=this.extendedCalls[s];this.cancelAllOutgoingUnanswered(),n.answer(this.sipOptions),this.updateCall(n),this.setActiveRoom(n.roomId),n.connection.addEventListener("track",i=>{this.triggerAddStream(i,n)})}moveCall(s,n){return re(this,null,function*(){this.updateCallStatus({callId:s,isMoving:!0}),yield this.processRoomChange({callId:s,roomId:n}),this.updateCallStatus({callId:s,isMoving:!1})})}updateCall(s){this.activeCalls[s._id]=qd(s),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(s){const n=oe(oe({},this.activeRooms[s.roomId]),s);this.activeRooms=ot(oe({},this.activeRooms),{[s.roomId]:oe({},n)}),this.context.emit("updateRoom",{room:n,roomList:this.activeRooms})}hasAutoAnswerHeaders(s){const n=/answer-after=0/,i=s.request.getHeader("Call-Info");return i&&n.test(i)}addCall(s,n=!0){this.activeCalls=ot(oe({},this.activeCalls),{[s._id]:qd(s)}),this.extendedCalls[s._id]=s,n&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(s){this.callStatus=ot(oe({},this.callStatus),{[s]:{isMoving:!1,isTransferring:!1,isMerging:!1,isTransferred:!1}}),this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(s){const n=oe({},oe({},this.callStatus[s.callId]));s.isMoving!==void 0&&(n.isMoving=s.isMoving),s.isTransferring!==void 0&&(n.isTransferring=s.isTransferring),s.isMerging!==void 0&&(n.isMerging=s.isMerging),s.isTransferred!==void 0&&(n.isTransferred=s.isTransferred),this.callStatus=ot(oe({},this.callStatus),{[s.callId]:oe({},n)}),this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(s){const n=oe({},this.callStatus);delete n[s],this.callStatus=oe({},n),this.context.emit("changeCallStatus",this.callStatus)}addRoom(s){this.activeRooms=ot(oe({},this.activeRooms),{[s.roomId]:s}),this.context.emit("addRoom",{room:s,roomList:this.activeRooms})}getActiveStream(){return re(this,null,function*(){const s=yield jd(yield this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);return s.getTracks().forEach(n=>n.enabled=!this.isMuted),yield this.setActiveStream(s),s})}setMicrophone(s){return re(this,null,function*(){if(!this.getInputDeviceList.find(({deviceId:i})=>i===s)||(this.setSelectedInputDevice(s),Object.keys(this.getActiveCalls).length===0))return;yield this.setupStream();const n=Object.values(this.extendedCalls).filter(i=>i.roomId===this.currentActiveRoomId);n.length===1?Object.values(n).forEach(i=>re(this,null,function*(){const a=yield this.getActiveStream();i.connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.updateCall(i)})):yield this.doConference(n)})}setActiveStream(s){return re(this,null,function*(){this.activeStream&&this.stopVUMeter("origin"),yield this.setupVUMeter(s,"origin"),this.activeStreamValue=s,this.context.emit("changeActiveStream",s)})}setSpeaker(s){return re(this,null,function*(){if(!this.getOutputDeviceList.find(({deviceId:a})=>a===s))return;this.setSelectedOutputDevice(s);const n=Object.values(this.extendedCalls);if(n.length===0)return;const i=n.filter(a=>a.roomId===this.currentActiveRoomId);i.length===1?n.forEach(a=>{var e;(e=a.audioTag)==null||e.setSinkId(s),this.updateCall(a)}):yield this.doConference(i)})}removeRoom(s){const n=oe({},this.activeRooms),i=oe({},n[s]);delete n[s],this.activeRooms=oe({},n),this.context.emit("removeRoom",{room:i,roomList:this.activeRooms})}deleteRoomIfEmpty(s){s!==void 0&&Object.values(this.extendedCalls).filter(n=>n.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})}roomReconfigure(s){return re(this,null,function*(){var n;if(s===void 0)return;const i=Object.values(this.extendedCalls).filter(e=>e.roomId===s),a=this.currentActiveRoomId===s;if(i.forEach((e,d)=>{if(e.audioTag){e.connection.getReceivers().forEach(u=>{u.track.enabled=!e.localMuted}),a&&this.muteReconfigure(e);const _=!a;e.audioTag.muted=_,this.updateCall(e)}}),i.length===0){this.conferenceNodes[s]&&(yield this.cleanupConferenceNodes(s)),this.deleteRoomIfEmpty(s);return}if(i.length===1&&!a){const e=i[0];e.isOnHold().local||(yield this.holdCall(e._id,!0)),this.conferenceNodes[s]&&(yield this.cleanupConferenceNodes(s));return}if(i.length===1&&a){const e=i[0];e.isOnHold().local&&e._automaticHold&&(yield this.unholdCall(e._id));const d=(((n=e.connection)==null?void 0:n.getSenders())||[])[0];if(e.connection&&d)try{const _=(yield this.getActiveStream()).getTracks();yield d.replaceTrack(_[0]),this.muteReconfigure(e)}catch(_){console.error(_)}this.conferenceNodes[s]&&(yield this.cleanupConferenceNodes(s));return}i.length>1&&(yield this.doConference(i))})}doConference(s){return re(this,null,function*(){if(s.length===0)return;const n=s[0].roomId,i=this.currentActiveRoomId===n;if(s.find(_=>_.roomId!==n))return;const a=yield this.managedAudioContext.getContext();if(a.state!=="running"){console.error(`[doConference] ERROR: AudioContext is not running! State: ${a.state}`);return}yield this.cleanupConferenceNodes(n),this.conferenceNodes[n]={sources:new Map,destinations:new Map,gains:new Map};const e=this.conferenceNodes[n],d=new Map;s.forEach((_,u)=>{_&&_.connection&&_.connection.getReceivers().forEach((g,p)=>{var T,y,C;g.track.enabled=!_.localMuted;const w=(T=g.track)==null?void 0:T.id;(y=g.track)==null||y.readyState,(C=g.track)==null||C.kind;const R=`${_._id}-${w}`;g.track&&g.track.readyState==="live"&&d.set(R,g.track)})}),yield Bv.forEach(s,(_,u)=>re(this,null,function*(){if(!_||!_.connection)return;const g=a.createMediaStreamDestination();e.destinations.set(_._id,g);let p=0;if(d.forEach((C,w)=>{if(!w.startsWith(_._id))try{const R=a.createMediaStreamSource(new MediaStream([C])),b=a.createGain(),G=`${_._id}-${w}`;R.connect(b),b.connect(g),e.sources.set(G,R),e.gains.set(G,b),p++}catch(R){console.error(R)}}),i&&this.activeStreamValue)try{const C=yield this.getActiveStream(),w=a.createMediaStreamSource(C),R=a.createGain(),b=`${_._id}-local`;w.connect(R),R.connect(g),e.sources.set(b,w),e.gains.set(b,R)}catch(C){console.error(C)}else i&&console.error(`Host room but no activeStreamValue - skipping host microphone for session ${_._id}`);const T=_.connection.getSenders()[0],y=g.stream.getTracks();if(T&&y[0])try{yield T.replaceTrack(y[0]),this.muteReconfigure(_)}catch(C){console.error(C)}}))})}processCallerMute(s,n){const i=this.extendedCalls[s];i&&i.connection.getReceivers().length&&(i.localMuted=n,i.connection.getReceivers().forEach(a=>{a.track.enabled=!n}),this.updateCall(i))}muteCaller(s){this.processCallerMute(s,!0)}unmuteCaller(s){this.processCallerMute(s,!1)}terminateCall(s){const n=this.extendedCalls[s];n._status===4?n.terminate({status_code:603,reason_phrase:"Decline"}):n._status!==8&&n.terminate()}transferCall(s,n){if(n.toString().length===0)return new Error("Target must be passed");const i=this.extendedCalls[s];if(!i._is_confirmed&&!i._is_canceled){const a=`sip:${n}@${this.context.sipDomain}`;i.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${a}`]});return}this.updateCallStatus({callId:s,isTransferring:!0,isTransferred:!1}),i.refer(`sip:${n}@${this.context.sipDomain}`,{eventHandlers:{requestSucceeded:()=>{this.updateCallStatus({callId:s,isTransferring:!1,isTransferred:!0})},requestFailed:()=>{this.updateCallStatus({callId:s,isTransferring:!1,isTransferred:!1})}}}),this.updateCall(i)}mergeCall(s){const n=Object.values(this.extendedCalls).filter(e=>e.roomId===s);if(n.length!==2)return;const i=n[0],a=n[1];!i||!a||(this.updateCallStatus({callId:i._id,isMerging:!0}),this.updateCallStatus({callId:a._id,isMerging:!0}),i.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(i))}mergeCallByIds(s,n){const i=Object.values(this.extendedCalls).find(e=>e._id===s),a=Object.values(this.extendedCalls).find(e=>e._id===n);if(!i||!a)throw new Error("Call ID is not provided");this.updateCallStatus({callId:s,isMerging:!0}),this.updateCallStatus({callId:n,isMerging:!0}),i.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(i)}setDND(s){this.isDNDEnabled=s,this.context.emit("changeIsDND",s)}setCallWaiting(s){this.isCallWaitingEnabled=s,this.context.emit("changeIsCallWaiting",s)}startCallTimer(s){this.removeTimeInterval(s);const n={callId:s,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(n);const i=setInterval(()=>{const a=oe({},this.callTime[s]),e=Vv(a);this.setCallTime(oe({callId:s},e))},1e3);this.setTimeInterval(s,i)}setActiveRoom(s){return re(this,null,function*(){const n=this.currentActiveRoomId;s!==n&&(this.currentActiveRoomId=s,yield this.roomReconfigure(n),yield this.roomReconfigure(s))})}getNewRoomId(){const s=Object.keys(this.activeRooms);return s.length===0?1:parseInt(s.sort()[s.length-1])+1}setupCall(s){return re(this,null,function*(){var n,i;const a=s.session;if(this.getActiveCalls[a.id]!==void 0)return;const e=this.getNewRoomId(),d={started:new Date,incomingInProgress:!1,roomId:e};a.direction==="incoming"?(this.context.logger.log("New incoming call from",(i=(n=a._remote_identity)==null?void 0:n._uri)==null?void 0:i._user),d.incomingInProgress=!0,this.context.subscribe(Zt.CALL_CONFIRMED,p=>{a.id===p.id&&(this.updateRoom({incomingInProgress:!1,roomId:e}),this.startCallTimer(a.id))}),this.context.subscribe(Zt.CALL_FAILED,p=>{a.id===p.id&&(this.updateRoom({incomingInProgress:!1,roomId:e}),this.deleteRoomIfEmpty(e))})):a.direction==="outgoing"&&(a.once("confirmed",()=>{this.startCallTimer(a.id)}),this.startCallTimer(a.id));const _=a,u=this.hasAutoAnswerHeaders(s),g=_.direction==="incoming"&&!this.hasActiveCalls&&(u||this.autoAnswer);_.roomId=e,_.localMuted=!1,_.autoAnswer=g,g?this.addCall(_,!1):this.addCall(_),this.addCallStatus(a.id),this.addRoom(d),g&&this.answerCall(_._id)})}removeCall(s){const n=oe({},this.activeCalls);delete n[s],this.activeCalls=oe({},n);const i=oe({},this.extendedCalls);delete i[s],this.extendedCalls=oe({},i),this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(s){const n=this.extendedCalls[s._id];if(!n)return;this.stopVUMeter("origin"),this.stopVUMeter(s._id);const i=n.roomId;this.removeCall(s._id),this.roomReconfigure(i).then(()=>{}).catch(a=>{console.error("Error reconfiguring room after call removal:",a)})}shouldTerminateNewSession(s){if(s.session.direction==="outgoing")return!1;const n=!this.isCallWaiting&&this.hasActiveCalls;return this.isDND||n}newRTCSessionCallback(s){return re(this,null,function*(){const n=s.session;if(this.shouldTerminateNewSession(s)){n.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(this.context.triggerListener({listenerType:Zt.NEW_CALL,session:n,event:s}),n.on("ended",i=>{var a,e,d;this.stopVUMeter(n.id),this.context.logger.log("Session ended for",(e=(a=n._remote_identity)==null?void 0:a._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Zt.CALL_ENDED,session:n,event:i});const _=this.getActiveCalls[n.id];_&&this.activeCallListRemove(_),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(u=>u.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),n.on("progress",i=>{var a,e;this.context.logger.log("Session in progress for",(e=(a=n._remote_identity)==null?void 0:a._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Zt.CALL_PROGRESS,session:n,event:i})}),n.on("failed",i=>{var a,e,d;this.stopVUMeter(n.id),this.context.logger.log("Session failed for",(e=(a=n._remote_identity)==null?void 0:a._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Zt.CALL_FAILED,session:n,event:i}),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const _=this.getActiveCalls[n.id];_&&this.activeCallListRemove(_),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(u=>u.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),n.on("confirmed",i=>{var a,e;this.context.logger.log("Session confirmed for",(e=(a=n._remote_identity)==null?void 0:a._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Zt.CALL_CONFIRMED,session:n,event:i}),this.updateCall(n),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),yield this.setupCall(s),n.direction==="outgoing"){const i=this.getActiveCalls[n.id].roomId;yield this.setActiveRoom(i)}})}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(n=>{n.audioTag&&(n.audioTag.volume=s,this.updateCall(n))})}setAutoAnswer(s){this.isAutoAnswer=s}setSelectedInputDevice(s){localStorage.setItem(Ll.SELECTED_INPUT_DEVICE,s),this.selectedMediaDevices.input=s,this.context.emit("changeActiveInputMediaDevice",s)}setSelectedOutputDevice(s){localStorage.setItem(Ll.SELECTED_OUTPUT_DEVICE,s),this.selectedMediaDevices.output=s,this.context.emit("changeActiveOutputMediaDevice",s)}setCallMetrics(s){const n=oe({},s);delete n.callId,this.callMetrics=ot(oe({},this.callMetrics),{[s.callId]:n}),this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(s){const n=oe({},this.callMetrics);delete n[s],this.callMetrics=oe({},n),this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(s){const n=new My(this.metricConfig),i=n.createProbe(s.connection,{cid:s._id}),a=[];let e;i.onreport=d=>{Object.entries(d.audio).forEach(([g,p])=>{p.direction==="inbound"&&!a.includes(g)&&(a.push(g),e=g)});const _=d.audio[e];if(!_)return;const u=xy(_,Py);u.callId=s._id,this.setCallMetrics(u)},this.context.subscribe(Zt.CALL_ENDED,d=>{d._id===s._id&&n.stopAllProbes()}),n.startAllProbes()}setupVUMeter(s,n){return re(this,null,function*(){yield this.VUMeter.start(yield this.managedAudioContext.getContext(),s,n)})}stopVUMeter(s){this.VUMeter.stop(s)}setupStream(){return re(this,null,function*(){try{const s=Date.now(),n=yield navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach((i,a)=>{i.stop()}),this.initialStreamValue=null),this.initialStreamValue=n}catch(s){throw s}})}triggerAddStream(s,n){return re(this,null,function*(){const i=this.muteWhenJoin||this.isMuted;this.setIsMuted(i),this.initialStreamValue||(yield this.setupStream());const a=yield this.managedAudioContext.getContext(),e=yield jd(a,this.initialStreamValue,this.microphoneInputLevel*2),d=this.isMuted||this.muteWhenJoin;e.getTracks().forEach(g=>{g.enabled=!d}),yield this.setActiveStream(e),yield n.connection.getSenders()[0].replaceTrack(e.getTracks()[0]);const _=new MediaStream([s.track]);!Object.values(this.extendedCalls).find(g=>g.audioTag&&g.audioTag.id===n._id)&&wv(_,n,this.selectedOutputDevice,this.speakerVolume);const u=n.roomId===this.currentActiveRoomId;n.audioTag&&(n.audioTag.muted=!u),yield this.setupVUMeter(_,n._id),this.getCallQuality(n),this.updateCall(n)})}initCall(s,n,i=!1){if(s.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${s}@${this.context.sipDomain}...`);const a=this.context.call(`sip:${s}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=a.id,n&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:a.id,roomId:this.currentActiveRoomId}),i)){const e=Object.values(this.extendedCalls).filter(d=>d.roomId===this.currentActiveRoomId&&d._id!==a.id);for(const d of e)this.holdCall(d._id,!0)}a.connection.addEventListener("track",e=>{this.triggerAddStream(e,a)})}processRoomChange(i){return re(this,arguments,function*({callId:s,roomId:n}){const a=this.extendedCalls[s];if(!a)return;const e=a.roomId;a.roomId=n,this.updateCall(a),yield this.roomReconfigure(e),yield this.roomReconfigure(n)})}}class jy{constructor(s){this.context=s}get sipOptions(){return oe({},this.context.options.sipOptions)}initCall(s,n){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}`,n,this.sipOptions)}stop(s={}){this.context.terminateJanusSessions(s)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(s){this.context.changeMediaConstraints(s)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class $y{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 n=this.extendedMessages[s];this.updateMSRPSession(n)}updateMSRPSession(s){this.activeMessages[s._id]=Fd(s),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(s){this.activeMessages=ot(oe({},this.activeMessages),{[s._id]:Fd(s)}),this.extendedMessages[s._id]=s,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(s,n){const i=this.msrpHistory[n.id]||[];i.push(s),this.msrpHistory=ot(oe({},this.msrpHistory),{[n.id]:[...i]}),this.context.emit("newMSRPMessage",{message:s,session:n})}messageTerminate(s){const n=this.extendedMessages[s];n._status!==8&&n.terminate()}addMessageSession(s){if(!s._id||this.getActiveMessages[s._id]!==void 0)return;const n=s;this.addMMSRPSession(n)}triggerMSRPListener({listenerType:s,session:n,event:i}){const a=this.context.listenersList[s];!a||!a.length||a.forEach(e=>{e(n,i)})}removeMMSRPSession(s){const n=oe({},this.activeMessages);delete n[s],this.activeMessages=oe({},n);const i=oe({},this.extendedMessages);delete i[s],this.extendedMessages=oe({},i),this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(s){this.removeMMSRPSession(s._id)}newMSRPSessionCallback(s){const n=s.session;n.on("ended",i=>{this.triggerMSRPListener({listenerType:Zt.CALL_ENDED,session:n,event:i});const a=this.getActiveMessages[n.id];this.activeMessageListRemove(a)}),n.on("failed",i=>{this.triggerMSRPListener({listenerType:Zt.CALL_FAILED,session:n,event:i});const a=this.getActiveMessages[n.id];this.activeMessageListRemove(a)}),n.on("confirmed",i=>{this.triggerMSRPListener({listenerType:Zt.CALL_CONFIRMED,session:n,event:i}),this.updateMSRPSession(n)}),n.on("newMessage",i=>{this.addMSRPMessage(i,n)}),this.addMessageSession(n)}setIsMSRPInitializing(s){this.isMSRPInitializingValue=s,this.context.emit("isMSRPInitializingChanged",s)}initMSRP(s,n,i){if(s.length===0)return console.error("Target must be a valid string");const a=this.context.startMSRP(s,i);a.on("active",()=>{this.addMessageSession(a),a.sendMSRP(n),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(s,n){const i=this.extendedMessages[s];if(!i)throw new Error(`MSRP session with id ${s} doesn't exist!`);i.sendMSRP(n)}}const Hl={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class s_{constructor(s){this.opensips=null,this.session=null,this.name=null,this.name=s}setOpensips(s){this.opensips=s}setSession(s){this.session=s}kill(){this.opensips.kill(this.name)}}class Vy extends s_{constructor(s,n){super(s),this._candidates=[],this._subscribeSent=!1,this._configureSent=!1,this._lastTrickleReceived=!1,this.type=n}connect(s={}){this.opaqueId=this.session.generateOpaqueId();const n=Me.cloneArray(s.extraHeaders),i={from_tag:this.session._from_tag};s.fromUserName&&(i.from_uri=new ds("sip",s.fromUserName,this.session._ua.configuration.uri.host),n.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),s.fromDisplayName&&(i.from_display_name=s.fromDisplayName),n.push(`Contact: ${this.session._contact}`),n.push("Content-Type: application/json"),this.session._sessionTimers.enabled&&n.push(`Session-Expires: ${this.session._sessionTimers.defaultExpires}${this.session._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new St.InitialOutgoingInviteRequest(this.session.target,this.session._ua,i,n),this._createRTCConnection(),this._sendInitialRequest()}getStream(){return this.stream}getConnection(){return this._connection}_createRTCConnection(){this._connection=new RTCPeerConnection({iceServers:[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}]});let s;this._connection.onicecandidate=n=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||n.candidate&&(this._candidates.push(n.candidate),clearTimeout(s),s=setTimeout(()=>{this._lastTrickleReceived=!0,this._subscribeSent&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})},500))}}addTracks(s){s.forEach(n=>{this._connection.addTrack(n)})}_sendInitialRequest(){return re(this,null,function*(){const s=new Ir(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:e=>{this._request=e},onReceiveResponse:e=>{this._receiveInviteResponse(e)}});if(yield this.generateStream(),!this.stream||!this.stream.getTracks().length)return;this.addTracks(this.stream.getTracks());const n={audio:!1,video:!0};this.jsep_offer=yield this._connection.createOffer(n),yield this._connection.setLocalDescription(this.jsep_offer);const i={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},a=JSON.stringify(i);this._request.body=a,s.send()})}_receiveInviteResponse(s){if(this._publisherSubscribeSent||!s.body)return;const n=JSON.parse(s.body);this.handleId=n.data.id;const i={janus:"message",body:{request:"join",room:this.session.room_id,ptype:"publisher",display:this.session.display_name+" (Screen Share)",opaque_id:this.opaqueId},handle_id:this.handleId},a=[this.session.getPTypeHeader(qt.PUBLISHER)];this.session.sendRequest(U.SUBSCRIBE,{extraHeaders:a,body:JSON.stringify(i),eventHandlers:{onSuccessResponse:e=>re(this,null,function*(){var d,_,u,g;if(e.status_code===200){if(this._subscribeSent=!0,e.body)try{const p=JSON.parse(e.body)||{};((_=(d=p.plugindata)==null?void 0:d.data)==null?void 0:_.videoroom)==="joined"&&this.session.myFeedList.push(p.plugindata.data.id),(g=(u=p.plugindata)==null?void 0:u.data)!=null&&g.publishers&&this.session.receivePublishers(p)}catch(p){console.error(p)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}})}}),this._publisherSubscribeSent=!0}_sendConfigureMessage(s){return re(this,null,function*(){const n=this._candidates.map(e=>({janus:"trickle",candidate:e,handle_id:this.handleId,session_id:this.session.session_id})),i={configure:{janus:"message",body:oe({request:"configure",record:!0,filename:this.session.getRecordFileName()},s),jsep:this.jsep_offer,handle_id:this.handleId,session_id:this.session.session_id},trickles:[...n]},a=["Content-Type: application/json",this.session.getPTypeHeader(qt.ICE)];this.session.sendRequest(U.INFO,{extraHeaders:a,body:JSON.stringify(i),eventHandlers:{onSuccessResponse:e=>re(this,null,function*(){this._configureSent=!0;const d=e.data.split(`\r
159
- `),_=d[d.length-1],u=JSON.parse(_);yield this._connection.setRemoteDescription(u.jsep),this._candidates=[]})}})})}_sendDetach(){const s={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},n=[this.session.getPTypeHeader(qt.DETACH)];this.session.sendRequest(U.INFO,{extraHeaders:n,body:JSON.stringify(s)}),this.session._ua.emit("pluginDetach",this.name)}stopMedia(){return re(this,null,function*(){this._connection&&(this._connection.close(),this._connection=null),this.stream&&(this.stream=null)})}stop(){return re(this,null,function*(){yield this.session.stopProcessPlugins(this.type);const s=this._connection.getSenders();s.forEach(n=>{const i=n.track;i&&i.stop()}),s.forEach(n=>{this._connection.removeTrack(n)}),yield this.stopMedia(),this._sendDetach()})}generateStream(){return re(this,null,function*(){throw new Error("generateStream method is not implemented")})}}class By extends s_{constructor(s,n,i={}){super(s),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=i.immediate||!1,this.type=n}start(s){return s}stop(){throw new Error("stop method is not implemented")}process(s){return re(this,null,function*(){if(this.immediate){const n=yield this.start(s);return this.running=!0,n}return s})}connect(){return re(this,null,function*(){this.running=!0,yield this.session.resyncPlugins(this.type)})}terminate(){this.stop()}kill(){return re(this,null,function*(){this.stop(),this.running=!1,yield this.session.resyncPlugins(this.type)})}}class Ky extends Ev{constructor(s,n){if(!s.modules.length)throw new Error("options.modules should include at least 1 module");const i=ot(oe({},s.configuration),{sockets:s.socketInterfaces.map(a=>new $v.WebSocketInterface(a))});super(i),this.initialized=!1,this.connected=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.activeConnection=!1,this.waitingForSessionHangup=!1,this.waitingForSessionTimeout=null,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,n&&Ov(n)&&(this.logger=n)}isWaitingForSessionHangup(){return this.waitingForSessionHangup}stopSessionAfterWaiting(){this.setInitialized(!1),this.waitingForSessionHangup=!1,clearTimeout(this.waitingForSessionTimeout),this.waitingForSessionTimeout=null,this.activeConnection&&setTimeout(this.start.bind(this),5e3)}get hasActiveSessions(){return this.modules.includes(Hl.AUDIO)?this.audio.hasActiveAnsweredCalls:!1}on(s,n){return super.on(s,n)}off(s,n){return super.off(s,n)}emit(s,n){return super.emit(s,n)}get sipDomain(){return this.options.sipDomain}use(s){if(this.newStreamPlugins.find(n=>n.name===s.name)||this.processStreamPlugins.find(n=>n.name===s.name))throw new Error(`Plugin with name ${s.name} already exists`);if(s instanceof Vy)s.setOpensips(this),this.newStreamPlugins.push(s);else if(s instanceof By)s.setOpensips(this),this.processStreamPlugins.push(s);else throw new Error("Wrong plugin instance")}getPlugin(s){return this.newStreamPlugins.find(n=>n.name===s)||this.processStreamPlugins.find(n=>n.name===s)}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(Hl.AUDIO)&&(this.audio=new Fy(this)),this.modules.includes(Hl.MSRP)&&(this.msrp=new $y(this)),this.modules.includes(Hl.VIDEO)&&(this.video=new jy(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.setConnected(!0),this.setReconnecting(!1),this.activeConnection=!0,this.waitingForSessionHangup=!1}),this.on(this.disconnectedEventName,()=>{this.setConnected(!1),!this.isReconnecting&&(this.setReconnecting(!0),this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.hasActiveSessions?(this.waitingForSessionHangup=!0,this.stop(!1),this.waitingForSessionTimeout=setTimeout(()=>{this.terminateAllSessions(),this.setInitialized(!1),this.waitingForSessionHangup=!1,this.activeConnection&&setTimeout(this.start.bind(this),5e3)},12e5)):(this.stop(),this.setInitialized(!1),this.activeConnection&&setTimeout(this.start.bind(this),5e3)))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}disconnect(){this.activeConnection=!1,this.stop()}subscribe(s,n){const i=!this.listenersList[s]||!this.listenersList[s].length?[n]:[...this.listenersList[s],n];this.listenersList=ot(oe({},this.listenersList),{[s]:i})}removeIListener(s){const n=oe({},this.listenersList);delete n[s],this.listenersList=oe({},n)}triggerListener({listenerType:s,session:n,event:i}){const a=this.listenersList[s];!a||!a.length||a.forEach(e=>{e(n,i)})}setInitialized(s){this.initialized=s,this.emit("ready",s)}setConnected(s){this.connected=s,this.emit("connection",s)}setReconnecting(s){this.isReconnecting=s,this.emit("reconnecting",s)}}let se;const r_=ve.ref(!1),i_=ve.ref(!1),o_=ve.ref(!1),l_=ve.ref({}),a_=ve.ref({}),u_=ve.ref(!1),c_=ve.ref(void 0),ql=ve.ref({}),vu=ve.ref({}),Fl=ve.ref([]),yu=ve.ref("default"),Eu=ve.ref("default"),Su=ve.ref(!1),Cu=ve.ref(!1),Au=ve.ref(!0),h_=ve.ref(!1),d_=ve.ref(null),Zs=ve.ref(void 0),__=ve.ref(!1),bu=ve.ref(2),Ru=ve.ref(1),Iu=ve.ref({}),f_=ve.ref({}),p_=ve.ref({}),wu=ve.computed(()=>{const l={};return Object.entries(l_.value).forEach(([s,n])=>{var i;(i=Iu.value[s])!=null&&i.isTransferred||(l[s]=n)}),l}),Gy=ve.computed(()=>{const l={},s=Object.values(wu.value).map(n=>n.roomId);return Object.entries(ql.value).forEach(([n,i])=>{s.includes(i.roomId)&&(l[n]=i)}),l}),Wy=ve.computed(()=>Fl.value.filter(l=>l.kind==="audioinput").map(l=>({deviceId:l.deviceId,kind:l.kind,groupId:l.groupId,label:l.label}))),Yy=ve.computed(()=>Fl.value.filter(l=>l.kind==="audiooutput").map(l=>({deviceId:l.deviceId,kind:l.kind,groupId:l.groupId,label:l.label}))),m_=ve.computed(()=>Object.values(wu.value).filter(l=>l.roomId===Zs.value));ve.watch(m_,l=>{!l.length&&Zs.value&&(Zs.value=void 0)}),ve.watch(Eu,l=>re(this,null,function*(){yield tn.actions.setMicrophone(l)})),ve.watch(yu,l=>re(this,null,function*(){yield tn.actions.setSpeaker(l)})),ve.watch(Su,l=>{tn.actions.setMuteWhenJoin(l)}),ve.watch(Cu,l=>{tn.actions.setDND(l)}),ve.watch(Au,l=>{tn.actions.setCallWaiting(l)}),ve.watch(bu,l=>{tn.actions.setMicrophoneSensitivity(l)}),ve.watch(Ru,l=>{tn.actions.setSpeakerVolume(l)}),ve.watch(Zs,l=>re(this,null,function*(){yield tn.actions.setActiveRoom(l)}));const tn={state:{isInitialized:r_,isOpenSIPSReady:i_,isOpenSIPSReconnecting:o_,activeCalls:wu,callsInActiveRoom:m_,activeMessages:a_,addCallToCurrentRoom:u_,callAddingInProgress:c_,activeRooms:Gy,msrpHistory:vu,availableMediaDevices:Fl,inputMediaDeviceList:Wy,outputMediaDeviceList:Yy,selectedOutputDevice:yu,selectedInputDevice:Eu,muteWhenJoin:Su,isDND:Cu,isCallWaitingEnabled:Au,isMuted:h_,originalStream:d_,currentActiveRoomId:Zs,callStatus:Iu,callTime:f_,callMetrics:p_,autoAnswer:__,microphoneInputLevel:bu,speakerVolume:Ru},actions:{init(l,s,n={}){return new Promise((i,a)=>{try{se=new Ky({configuration:ot(oe({},n),{session_timers:!1,uri:`sip:${l.username}@${l.domain}`,password:l.password}),socketInterfaces:[`wss://${l.domain}`],sipDomain:`${l.domain}`,sipOptions:{session_timers:!1,extraHeaders:["X-Bar: bar"],pcConfig:{}},modules:l.modules,pnExtraHeaders:s}),se.on("connection",e=>{u_.value=!1,r_.value=!0,i_.value=e,i(se)}).on("reconnecting",e=>{o_.value=e}).on("changeActiveCalls",e=>{l_.value=oe({},e)}).on("changeActiveMessages",e=>{a_.value=oe({},e)}).on("newMSRPMessage",e=>{const d=e.session._id,_=vu.value[d]||[];_.push(e.message),vu.value[d]=[..._]}).on("callAddingInProgressChanged",e=>{c_.value=e}).on("changeAvailableDeviceList",e=>{Fl.value=[...e]}).on("changeActiveInputMediaDevice",e=>{Eu.value=e}).on("changeActiveOutputMediaDevice",e=>{yu.value=e}).on("changeMuteWhenJoin",e=>{Su.value=e}).on("changeIsCallWaiting",e=>{Au.value=e}).on("changeIsDND",e=>{Cu.value=e}).on("changeIsMuted",e=>{h_.value=e}).on("changeActiveStream",e=>{d_.value=e}).on("currentActiveRoomChanged",e=>{Zs.value=e}).on("addRoom",({roomList:e})=>{ql.value=oe({},e)}).on("updateRoom",({roomList:e})=>{ql.value=oe({},e)}).on("removeRoom",({roomList:e})=>{ql.value=oe({},e)}).on("changeCallStatus",e=>{Iu.value=oe({},e)}).on("changeCallTime",e=>{f_.value=oe({},e)}).on("changeCallMetrics",e=>{p_.value=oe({},e)}).begin(),i(se)}catch(e){console.error(e),a()}})},unregister(){se==null||se.unregister()},register(){se==null||se.register()},disconnect(){se==null||se.disconnect()},initCall(l,s=!1,n=!1){se==null||se.audio.initCall(l,s,n)},answerCall(l){se==null||se.audio.answerCall(l)},terminateCall(l){se==null||se.audio.terminateCall(l)},mute(){se==null||se.audio.mute()},unmute(){se==null||se.audio.unmute()},transferCall(l,s){se==null||se.audio.transferCall(l,s)},mergeCall(l){se==null||se.audio.mergeCall(l)},mergeCallByIds(l,s){se==null||se.audio.mergeCallByIds(l,s)},holdCall(l,s){se==null||se.audio.holdCall(l,s)},unholdCall(l){se==null||se.audio.unholdCall(l)},moveCall(l,s){return re(this,null,function*(){yield se==null?void 0:se.audio.moveCall(l,s)})},muteCaller(l){se==null||se.audio.muteCaller(l)},unmuteCaller(l){se==null||se.audio.unmuteCaller(l)},setMuteWhenJoin(l){se==null||se.audio.setMuteWhenJoin(l)},setDND(l){se==null||se.audio.setDND(l)},setCallWaiting(l){se==null||se.audio.setCallWaiting(l)},setMicrophone(l){return re(this,null,function*(){yield se==null?void 0:se.audio.setMicrophone(l)})},setSpeaker(l){return re(this,null,function*(){yield se==null?void 0:se.audio.setSpeaker(l)})},sendDTMF(l,s){se==null||se.audio.sendDTMF(l,s)},setActiveRoom(l){return re(this,null,function*(){yield se==null?void 0:se.audio.setActiveRoom(l)})},setMicrophoneSensitivity(l){bu.value=l,se==null||se.audio.setMicrophoneSensitivity(l)},setSpeakerVolume(l){Ru.value=l,se==null||se.audio.setSpeakerVolume(l)},setAutoAnswer(l){__.value=l,se==null||se.audio.setAutoAnswer(l)},setMetricsConfig(l){se==null||se.audio.setMetricsConfig(l)},msrpAnswer(l){se==null||se.msrp.msrpAnswer(l)},messageTerminate(l){se==null||se.msrp.messageTerminate(l)},sendMSRP(l,s){se==null||se.msrp.sendMSRP(l,s)},initMSRP(l,s,n){se==null||se.msrp.initMSRP(l,s,n)}}},g_=Symbol();function zy(){return ve.provide(g_,tn),tn}function Xy(){const l=ve.inject(g_);if(!l)throw new Error("useVsipInject() is called without provider, please call useVsipProvide() first");return l}et.useVsipInject=Xy,et.useVsipProvide=zy,et.vsipAPI=tn,Object.defineProperty(et,Symbol.toStringTag,{value:"Module"})});
159
+ `),_=d[d.length-1],u=JSON.parse(_);yield this._connection.setRemoteDescription(u.jsep),this._candidates=[]})}})})}_sendDetach(){const s={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},n=[this.session.getPTypeHeader(qt.DETACH)];this.session.sendRequest(U.INFO,{extraHeaders:n,body:JSON.stringify(s)}),this.session._ua.emit("pluginDetach",this.name)}stopMedia(){return re(this,null,function*(){this._connection&&(this._connection.close(),this._connection=null),this.stream&&(this.stream=null)})}stop(){return re(this,null,function*(){yield this.session.stopProcessPlugins(this.type);const s=this._connection.getSenders();s.forEach(n=>{const i=n.track;i&&i.stop()}),s.forEach(n=>{this._connection.removeTrack(n)}),yield this.stopMedia(),this._sendDetach()})}generateStream(){return re(this,null,function*(){throw new Error("generateStream method is not implemented")})}}class By extends s_{constructor(s,n,i={}){super(s),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=i.immediate||!1,this.type=n}start(s){return s}stop(){throw new Error("stop method is not implemented")}process(s){return re(this,null,function*(){if(this.immediate){const n=yield this.start(s);return this.running=!0,n}return s})}connect(){return re(this,null,function*(){this.running=!0,yield this.session.resyncPlugins(this.type)})}terminate(){this.stop()}kill(){return re(this,null,function*(){this.stop(),this.running=!1,yield this.session.resyncPlugins(this.type)})}}class Ky extends Ev{constructor(s,n){if(!s.modules.length)throw new Error("options.modules should include at least 1 module");const i=ot(oe({},s.configuration),{sockets:s.socketInterfaces.map(a=>new $v.WebSocketInterface(a))});super(i),this.initialized=!1,this.connected=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.activeConnection=!1,this.waitingForSessionHangup=!1,this.waitingForSessionTimeout=null,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,n&&Ov(n)&&(this.logger=n)}isWaitingForSessionHangup(){return this.waitingForSessionHangup}stopSessionAfterWaiting(){this.setInitialized(!1),this.waitingForSessionHangup=!1,clearTimeout(this.waitingForSessionTimeout),this.waitingForSessionTimeout=null,this.activeConnection&&setTimeout(this.start.bind(this),5e3)}get hasActiveSessions(){return this.modules.includes(Hl.AUDIO)?this.audio.hasActiveAnsweredCalls:!1}on(s,n){return super.on(s,n)}off(s,n){return super.off(s,n)}emit(s,n){return super.emit(s,n)}get sipDomain(){return this.options.sipDomain}use(s){if(this.newStreamPlugins.find(n=>n.name===s.name)||this.processStreamPlugins.find(n=>n.name===s.name))throw new Error(`Plugin with name ${s.name} already exists`);if(s instanceof Vy)s.setOpensips(this),this.newStreamPlugins.push(s);else if(s instanceof By)s.setOpensips(this),this.processStreamPlugins.push(s);else throw new Error("Wrong plugin instance")}getPlugin(s){return this.newStreamPlugins.find(n=>n.name===s)||this.processStreamPlugins.find(n=>n.name===s)}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(Hl.AUDIO)&&(this.audio=new Fy(this)),this.modules.includes(Hl.MSRP)&&(this.msrp=new $y(this)),this.modules.includes(Hl.VIDEO)&&(this.video=new jy(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.setConnected(!0),this.setReconnecting(!1),this.activeConnection=!0,this.waitingForSessionHangup=!1}),this.on(this.disconnectedEventName,()=>{this.setConnected(!1),!this.isReconnecting&&(this.setReconnecting(!0),this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.hasActiveSessions?(this.waitingForSessionHangup=!0,this.stop(!1),this.waitingForSessionTimeout=setTimeout(()=>{this.terminateAllSessions(),this.setInitialized(!1),this.waitingForSessionHangup=!1,this.activeConnection&&setTimeout(this.start.bind(this),5e3)},12e5)):(this.stop(),this.setInitialized(!1),this.activeConnection&&setTimeout(this.start.bind(this),5e3)))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}disconnect(){this.activeConnection=!1,this.stop()}subscribe(s,n){const i=!this.listenersList[s]||!this.listenersList[s].length?[n]:[...this.listenersList[s],n];this.listenersList=ot(oe({},this.listenersList),{[s]:i})}removeIListener(s){const n=oe({},this.listenersList);delete n[s],this.listenersList=oe({},n)}triggerListener({listenerType:s,session:n,event:i}){const a=this.listenersList[s];!a||!a.length||a.forEach(e=>{e(n,i)})}setInitialized(s){this.initialized=s,this.emit("ready",s)}setConnected(s){this.connected=s,this.emit("connection",s)}setReconnecting(s){this.isReconnecting=s,this.emit("reconnecting",s)}}let se;const r_=ve.ref(!1),i_=ve.ref(!1),o_=ve.ref(!1),l_=ve.ref({}),a_=ve.ref({}),u_=ve.ref(!1),c_=ve.ref(void 0),ql=ve.ref({}),vu=ve.ref({}),Fl=ve.ref([]),yu=ve.ref("default"),Eu=ve.ref("default"),Su=ve.ref(!1),Cu=ve.ref(!1),Au=ve.ref(!0),h_=ve.ref(!1),d_=ve.ref(null),Zs=ve.ref(void 0),__=ve.ref(!1),bu=ve.ref(2),Ru=ve.ref(1),Iu=ve.ref({}),f_=ve.ref({}),p_=ve.ref({}),wu=ve.computed(()=>{const l={};return Object.entries(l_.value).forEach(([s,n])=>{var i;(i=Iu.value[s])!=null&&i.isTransferred||(l[s]=n)}),l}),Gy=ve.computed(()=>{const l={},s=Object.values(wu.value).map(n=>n.roomId);return Object.entries(ql.value).forEach(([n,i])=>{s.includes(i.roomId)&&(l[n]=i)}),l}),Wy=ve.computed(()=>Fl.value.filter(l=>l.kind==="audioinput").map(l=>({deviceId:l.deviceId,kind:l.kind,groupId:l.groupId,label:l.label}))),Yy=ve.computed(()=>Fl.value.filter(l=>l.kind==="audiooutput").map(l=>({deviceId:l.deviceId,kind:l.kind,groupId:l.groupId,label:l.label}))),m_=ve.computed(()=>Object.values(wu.value).filter(l=>l.roomId===Zs.value));ve.watch(m_,l=>{!l.length&&Zs.value&&(Zs.value=void 0)}),ve.watch(Eu,l=>re(this,null,function*(){yield tn.actions.setMicrophone(l)})),ve.watch(yu,l=>re(this,null,function*(){yield tn.actions.setSpeaker(l)})),ve.watch(Su,l=>{tn.actions.setMuteWhenJoin(l)}),ve.watch(Cu,l=>{tn.actions.setDND(l)}),ve.watch(Au,l=>{tn.actions.setCallWaiting(l)}),ve.watch(bu,l=>{tn.actions.setMicrophoneSensitivity(l)}),ve.watch(Ru,l=>{tn.actions.setSpeakerVolume(l)}),ve.watch(Zs,l=>re(this,null,function*(){yield tn.actions.setActiveRoom(l)}));const tn={state:{isInitialized:r_,isOpenSIPSReady:i_,isOpenSIPSReconnecting:o_,activeCalls:wu,callsInActiveRoom:m_,activeMessages:a_,addCallToCurrentRoom:u_,callAddingInProgress:c_,activeRooms:Gy,msrpHistory:vu,availableMediaDevices:Fl,inputMediaDeviceList:Wy,outputMediaDeviceList:Yy,selectedOutputDevice:yu,selectedInputDevice:Eu,muteWhenJoin:Su,isDND:Cu,isCallWaitingEnabled:Au,isMuted:h_,originalStream:d_,currentActiveRoomId:Zs,callStatus:Iu,callTime:f_,callMetrics:p_,autoAnswer:__,microphoneInputLevel:bu,speakerVolume:Ru},actions:{init(l,s,n={}){return new Promise((i,a)=>{try{const e=ot(oe({},n),{session_timers:!1,uri:`sip:${l.username}@${l.domain}`,password:l.password});l.authorization_jwt&&(e.authorization_jwt=l.authorization_jwt),se=new Ky({configuration:e,socketInterfaces:[`wss://${l.domain}`],sipDomain:`${l.domain}`,sipOptions:{session_timers:!1,extraHeaders:["X-Bar: bar"],pcConfig:{}},modules:l.modules,pnExtraHeaders:s}),se.on("connection",d=>{u_.value=!1,r_.value=!0,i_.value=d,i(se)}).on("reconnecting",d=>{o_.value=d}).on("changeActiveCalls",d=>{l_.value=oe({},d)}).on("changeActiveMessages",d=>{a_.value=oe({},d)}).on("newMSRPMessage",d=>{const _=d.session._id,u=vu.value[_]||[];u.push(d.message),vu.value[_]=[...u]}).on("callAddingInProgressChanged",d=>{c_.value=d}).on("changeAvailableDeviceList",d=>{Fl.value=[...d]}).on("changeActiveInputMediaDevice",d=>{Eu.value=d}).on("changeActiveOutputMediaDevice",d=>{yu.value=d}).on("changeMuteWhenJoin",d=>{Su.value=d}).on("changeIsCallWaiting",d=>{Au.value=d}).on("changeIsDND",d=>{Cu.value=d}).on("changeIsMuted",d=>{h_.value=d}).on("changeActiveStream",d=>{d_.value=d}).on("currentActiveRoomChanged",d=>{Zs.value=d}).on("addRoom",({roomList:d})=>{ql.value=oe({},d)}).on("updateRoom",({roomList:d})=>{ql.value=oe({},d)}).on("removeRoom",({roomList:d})=>{ql.value=oe({},d)}).on("changeCallStatus",d=>{Iu.value=oe({},d)}).on("changeCallTime",d=>{f_.value=oe({},d)}).on("changeCallMetrics",d=>{p_.value=oe({},d)}).begin(),i(se)}catch(e){console.error(e),a()}})},unregister(){se==null||se.unregister()},register(){se==null||se.register()},disconnect(){se==null||se.disconnect()},initCall(l,s=!1,n=!1){se==null||se.audio.initCall(l,s,n)},answerCall(l){se==null||se.audio.answerCall(l)},terminateCall(l){se==null||se.audio.terminateCall(l)},mute(){se==null||se.audio.mute()},unmute(){se==null||se.audio.unmute()},transferCall(l,s){se==null||se.audio.transferCall(l,s)},mergeCall(l){se==null||se.audio.mergeCall(l)},mergeCallByIds(l,s){se==null||se.audio.mergeCallByIds(l,s)},holdCall(l,s){se==null||se.audio.holdCall(l,s)},unholdCall(l){se==null||se.audio.unholdCall(l)},moveCall(l,s){return re(this,null,function*(){yield se==null?void 0:se.audio.moveCall(l,s)})},muteCaller(l){se==null||se.audio.muteCaller(l)},unmuteCaller(l){se==null||se.audio.unmuteCaller(l)},setMuteWhenJoin(l){se==null||se.audio.setMuteWhenJoin(l)},setDND(l){se==null||se.audio.setDND(l)},setCallWaiting(l){se==null||se.audio.setCallWaiting(l)},setMicrophone(l){return re(this,null,function*(){yield se==null?void 0:se.audio.setMicrophone(l)})},setSpeaker(l){return re(this,null,function*(){yield se==null?void 0:se.audio.setSpeaker(l)})},sendDTMF(l,s){se==null||se.audio.sendDTMF(l,s)},setActiveRoom(l){return re(this,null,function*(){yield se==null?void 0:se.audio.setActiveRoom(l)})},setMicrophoneSensitivity(l){bu.value=l,se==null||se.audio.setMicrophoneSensitivity(l)},setSpeakerVolume(l){Ru.value=l,se==null||se.audio.setSpeakerVolume(l)},setAutoAnswer(l){__.value=l,se==null||se.audio.setAutoAnswer(l)},setMetricsConfig(l){se==null||se.audio.setMetricsConfig(l)},msrpAnswer(l){se==null||se.msrp.msrpAnswer(l)},messageTerminate(l){se==null||se.msrp.messageTerminate(l)},sendMSRP(l,s){se==null||se.msrp.sendMSRP(l,s)},initMSRP(l,s,n){se==null||se.msrp.initMSRP(l,s,n)}}},g_=Symbol();function zy(){return ve.provide(g_,tn),tn}function Xy(){const l=ve.inject(g_);if(!l)throw new Error("useVsipInject() is called without provider, please call useVsipProvide() first");return l}et.useVsipInject=Xy,et.useVsipProvide=zy,et.vsipAPI=tn,Object.defineProperty(et,Symbol.toStringTag,{value:"Module"})});
160
160
  //# sourceMappingURL=super.umd.js.map