@voicenter-team/opensips-js 1.0.131 → 1.0.132

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -699,6 +699,7 @@ declare type MSRPSessionListener = IncomingMSRPSessionListener | OutgoingMSRPSes
699
699
  declare interface OpenSIPSEventMap extends UAEventMap {
700
700
  ready: readyListener
701
701
  connection: connectionListener
702
+ reconnecting: reconnectionListener
702
703
  // JSSIP
703
704
  changeActiveCalls: changeActiveCallsListener
704
705
  changeActiveMessages: changeActiveMessagesListener
@@ -769,6 +770,7 @@ declare class OpenSIPSJS extends UAExtended {
769
770
  triggerListener({ listenerType, session, event }: TriggerListenerOptions): void;
770
771
  private setInitialized;
771
772
  private setConnected;
773
+ private setReconnecting;
772
774
  }
773
775
  export default OpenSIPSJS;
774
776
 
@@ -782,6 +784,8 @@ declare type OutgoingMSRPSessionListener = (event: OutgoingMSRPSessionEvent) =>
782
784
 
783
785
  declare type readyListener = (value: boolean) => void
784
786
 
787
+ declare type reconnectionListener = (value: boolean) => void
788
+
785
789
  declare interface RemoteIdentityCallType {
786
790
  _display_name: string
787
791
  _uri: {
@@ -156,4 +156,4 @@ a=path:${t.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 sl(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:s=>{this.onTransportError(),console.log(s)},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s),s.status_code===200&&(s.parseSDP(!0),this._status=Re.STATUS_CONFIRMED,this.target_addr=s.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=Re.STATUS_INVITE_SENT}terminate(t={}){const n=t.cause||L.causes.BYE,a=ke.cloneArray(t.extraHeaders),o=t.body;let s,r=t.status_code,d=t.reason_phrase;if(this._status===Re.STATUS_TERMINATED)throw new qs.InvalidStateError(this._status);switch(this.status="terminated",this._status){case Re.STATUS_NULL:case Re.STATUS_INVITE_SENT:case Re.STATUS_1XX_RECEIVED:if(r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);r&&(d=d||L.REASON_PHRASE[r]||"",s=`SIP ;cause=${r} ;text="${d}"`),this._status===Re.STATUS_NULL||this._status===Re.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=s):this._status===Re.STATUS_1XX_RECEIVED&&this._request.cancel(s),this._status=Re.STATUS_CANCELED,this._failed("local",null,L.causes.CANCELED);break;case Re.STATUS_WAITING_FOR_ANSWER:case Re.STATUS_ANSWERED:if(r=r||480,r<300||r>=700)throw new TypeError(`Invalid status_code: ${r}`);this._request.reply(r,d,a,o),this._failed("local",null,L.causes.REJECTED);break;case Re.STATUS_WAITING_FOR_ACK:case Re.STATUS_CONFIRMED:if(d=t.reason_phrase||L.REASON_PHRASE[r]||"",r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);if(r&&a.push(`Reason: SIP ;cause=${r}; text="${d}"`),this._status===Re.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Gt.C.STATUS_TERMINATED){const h=this._dialog;this.receiveRequest=({method:_})=>{_===L.ACK&&(this.sendRequest(L.BYE,{extraHeaders:a,body:o}),h.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Gt.C.STATUS_TERMINATED&&(this.sendRequest(L.BYE,{extraHeaders:a,body:o}),h.terminate())}),this._ended("local",null,n),this._dialog=h,this._ua.newDialog(h)}else this.sendRequest(L.BYE,{extraHeaders:a,body:o}),this._ended("local",null,n)}}sendRequest(t,n){return this._dialog.sendRequest(t,n)}authenticate(t){this.status="auth";let n=new cr("");n.method="AUTH",n.addHeader("To-Path",`msrp://${this._ua._configuration.realm}:2856;ws`),n.addHeader("From-Path",`msrp://${this.credentials.username}.${this.credentials.realm}:2856/${this.auth_id};ws`),t&&n.addHeader("Authorization",t.toString());let a=n.toString(),o=[];for(var s=0;s<a.length;s++)o.push(a.charCodeAt(s).toString(16));this._connection.send(n.toString())}onmessage(t){const n=new cr(t.data);if(this.status==="auth"&&n.code===401){const a=this.parseAuth(n.getHeader("WWW-Authenticate")),o=new Km(this.credentials);o.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},a,ke.createRandomToken(12)),this.authenticate(o)}this.status==="auth"&&n.code===200&&this._direction==="outgoing"?(this.my_addr.push(n.getHeader("To-Path")),this.my_addr.push(n.getHeader("Use-Path")),this.status="active",this.inviteParty(n)):this.status==="auth"&&n.code===200&&this._direction==="incoming"?(this.my_addr.push(n.getHeader("To-Path")),this.my_addr.push(n.getHeader("Use-Path")),this.status="active",this.acceptParty(n),this.emit("confirmed")):n.method==="SEND"&&(this._sendOk(n),this._sendReport(n),n.direction="incoming",this.emit("newMessage",n),this._msgHistory.push(n),this.emit("msgHistoryUpdate",this._msgHistory)),n.code===480&&this._close()}onclose(){console.log("close")}onopen(){const t=new RTCPeerConnection({iceServers:[]});t.createDataChannel(""),t.createOffer().then(t.setLocalDescription.bind(t)),t.onicecandidate=n=>{if(!n||!n.candidate||!n.candidate.candidate)return;const a=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,o=n.candidate.candidate.match(a);this.my_ip=o&&o[1],t.onicecandidate=()=>{},this.authenticate(null)}}onerror(t){console.log(t)}_receiveInviteResponse(t){if(console.log("resp0000000000000",t),this._dialog&&t.status_code>=200&&t.status_code<=299)if(console.log("200000000000000"),this._dialog.id.call_id===t.call_id&&this._dialog.id.local_tag===t.from_tag&&this._dialog.id.remote_tag===t.to_tag){this.sendRequest(L.ACK);return}else{const n=new ea(this,t,"UAC");if(n.error!==void 0){console.log(n.error);return}this.sendRequest(L.ACK),this.sendRequest(L.BYE);return}if(this._is_canceled){t.status_code>=100&&t.status_code<200?this._request.cancel(this._cancel_reason):t.status_code>=200&&t.status_code<299&&this._acceptAndTerminate(t);return}if(!(this._status!==Re.STATUS_INVITE_SENT&&this._status!==Re.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(t.status_code):this._status=Re.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(t.status_code):{if(!t.to_tag){console.log("1xx response received without to tag");break}if(t.hasHeader("contact")&&!this._createDialog(t,"UAC",!0))break;if(this._status=Re.STATUS_1XX_RECEIVED,!t.body){this._progress("remote",t);break}const n={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",n);const a=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>this._progress("remote",t)).catch(o=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',o),this.emit("peerconnection:setremotedescriptionfailed",o)});break}case/^2[0-9]{2}$/.test(t.status_code):{if(console.log("maybe here???"),this._status=Re.STATUS_CONFIRMED,!t.body){this._acceptAndTerminate(t,400,L.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",t,L.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(t,"UAC"))break;const n={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",n),new RTCSessionDescription({type:"answer",sdp:n.sdp}),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(a=>this._connection.setLocalDescription(a)).catch(a=>{this._acceptAndTerminate(t,500,a.toString()),console.log("failed 4"),this._failed("local",t,L.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(t),this._accepted("remote",t),this.sendRequest(L.ACK),this._confirmed("local",null)});break}default:{const n=ke.sipErrorCause(t.status_code);console.log("failed 5"),this._failed("remote",t,n)}}}sendMSRP(t){const n=new cr("");n.method="SEND",n.addHeader("To-Path",`${this.my_addr[1]} ${this.target_addr[1]} ${this.target_addr[0]}`),n.addHeader("From-Path",`${this.my_addr[0]}`),n.addHeader("Message-ID",ke.createRandomToken(10)),n.addHeader("Byte-Range","1-25/25"),n.addHeader("Content-Type","text/plain"),n.addHeader("Success-Report","yes"),n.addHeader("Failure-Report","yes"),n.body=t;let a=n.toString();console.log(a);let o=[];for(var s=0;s<a.length;s++)o.push(a.charCodeAt(s).toString(16));console.log(o),this._connection.send(n.toString()),n.direction="outgoing",this.emit("newMessage",n),this._msgHistory.push(n),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(t){let n=t.ident,a=t.getHeader("Message-ID"),o=new cr("");o.method="200 OK",o.addHeader("To-Path",`${this.my_addr[1]}`),o.addHeader("From-Path",`${this.my_addr[0]}`),o.addHeader("Message-ID",a),o.ident=n;let s=o.toString();console.log(s);let r=[];for(var d=0;d<s.length;d++)r.push(s.charCodeAt(d).toString(16));console.log(r),this._connection.send(o.toString())}_sendReport(t){let n=t.ident,a=t.getHeader("Message-ID"),o=new cr("");o.method="REPORT",o.addHeader("To-Path",`${t.getHeader("From-Path")}`),o.addHeader("From-Path",`${this.my_addr[0]}`),o.addHeader("Message-ID",a),o.addHeader("Byte-Range","1-25/25"),o.addHeader("Status","000 200 OK"),o.ident=n;let s=o.toString();console.log(s);let r=[];for(var d=0;d<s.length;d++)r.push(s.charCodeAt(d).toString(16));console.log(r),this._connection.send(o.toString())}parseAuth(t){const n={},a=t.replace("Digest","").split(",");for(const o of a){const s=o.trim().split("=");n[s[0]]=s[1].match('^"(.+)"$')[1]}return n}init_incoming(t,n){let a;const o=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;if(t.body&&o!=="application/sdp"){t.reply(415);return}if(this._status=Re.STATUS_INVITE_RECEIVED,this._from_tag=t.from_tag,this._id=t.call_id+this._from_tag,this._request=t,this._contact=this._ua.contact.toString(),t.hasHeader("expires")&&(a=t.getHeader("expires")*1e3),t.to_tag=ke.newTag(),!this._createDialog(t,"UAS",!0)){t.reply(500,"Missing Contact header field");return}t.body?this._late_sdp=!1:this._late_sdp=!0,this._status=Re.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{t.reply(408),console.log("failed 6"),this._failed("local",null,L.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),a&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Re.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),console.log("failed 7"),this._failed("system",null,L.causes.EXPIRES))},a)),this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from,n&&n(this),t.parseSDP(!0),this.target_addr=t.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",t),this._status!==Re.STATUS_TERMINATED&&(t.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(t,n,a){this.emit("_failed",{originator:t,message:n||null,cause:a}),this._close(),this.emit("failed",{originator:t,message:n||null,cause:a})}_close(){if(console.log("CLOSE SESSION"),this._status!==Re.STATUS_TERMINATED){if(this._status=Re.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(t){console.log("close() | error closing the RTCPeerConnection: %o",t)}for(const t in this._timers)Object.prototype.hasOwnProperty.call(this._timers,t)&&clearTimeout(this._timers[t]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const t in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,t)&&(this._earlyDialogs[t].terminate(),delete this._earlyDialogs[t]);for(const t in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,t)&&delete this._referSubscribers[t];this._ua.destroyMSRPSession(this)}}_createDialog(t,n,a){const o=n==="UAS"?t.to_tag:t.from_tag,s=n==="UAS"?t.from_tag:t.to_tag,r=t.call_id+o+s;let d=this._earlyDialogs[r];if(a)return d?!0:(d=new ea(this,t,n,ea.C.STATUS_EARLY),d.error?(console.log("failed 8"),this._failed("remote",t,L.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[r]=d,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,d)return d.update(t,n),this._dialog=d,delete this._earlyDialogs[r],!0;const h=new ea(this,t,n);return h.error?(console.log("failed 9"),this._failed("remote",t,L.causes.INTERNAL_ERROR),!1):(this._dialog=h,!0)}}_newMSRPSession(t,n){this._ua.newMSRPSession(this,{originator:t,session:this,request:n})}_progress(t,n){this.emit("progress",{originator:t,response:n||null})}isEnded(){switch(this._status){case Re.STATUS_CANCELED:case Re.STATUS_TERMINATED:return!0;default:return!1}}_accepted(t,n){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:t,response:n||null})}_confirmed(t,n){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:t,ack:n||null})}_ended(t,n,a){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:t,message:n||null,cause:a})}_handleSessionTimersInIncomingResponse(t){if(!this._sessionTimers.enabled)return;let n;t.session_expires&&t.session_expires>=L.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,n=t.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,n="uac"),this._sessionTimers.refresher=n==="uac",this._runSessionTimer()}receiveRequest(t){if(console.log("receiveRequest()"),t.method===L.CANCEL)(this._status===Re.STATUS_WAITING_FOR_ANSWER||this._status===Re.STATUS_ANSWERED)&&(this._status=Re.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",t,L.causes.CANCELED));else switch(t.method){case L.ACK:if(this._status!==Re.STATUS_WAITING_FOR_ACK)return;if(this._status=Re.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!t.body){this.terminate({cause:L.causes.MISSING_SDP,status_code:400});break}const n={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",n);const a=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>{this._is_confirmed||this._confirmed("remote",t)}).catch(o=>{this.terminate({cause:L.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',o),this.emit("peerconnection:setremotedescriptionfailed",o)})}else this._is_confirmed||this._confirmed("remote",t);break;case L.BYE:this._status===Re.STATUS_CONFIRMED||this._status===Re.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,L.causes.BYE)):this._status===Re.STATUS_INVITE_RECEIVED||this._status===Re.STATUS_WAITING_FOR_ANSWER?(t.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",t,L.causes.BYE)):t.reply(403,"Wrong Status");break;case L.INVITE:this._status===Re.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case L.INFO:this._status===Re.STATUS_1XX_RECEIVED||this._status===Re.STATUS_WAITING_FOR_ANSWER||this._status===Re.STATUS_ANSWERED||this._status===Re.STATUS_WAITING_FOR_ACK||this._status===Re.STATUS_CONFIRMED?(t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new yu(this).init_incoming(t):t.reply(415):t.reply(403,"Wrong Status");break;case L.UPDATE:this._status===Re.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case L.REFER:this._status===Re.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case L.NOTIFY:this._status===Re.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==Re.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:L.causes.CONNECTION_ERROR,cause:L.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==Re.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:L.causes.REQUEST_TIMEOUT,cause:L.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==Re.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:L.causes.DIALOG_ERROR,cause:L.causes.DIALOG_ERROR})}}var MT=Zt();const Iu=ze(MT),fa=new Ga("Parser"),LT=(c,t)=>{let n,a,o=c.indexOf(`\r
157
157
  `);if(o===-1){fa.warn("parseMessage() | no CRLF found, not a SIP message");return}const s=c.substring(0,o);let r=Iu.parse(s,"Request_Response");if(r===-1){fa.warn(`parseMessage() | error parsing first line of SIP message: "${s}"`);return}else r.status_code?(n=new pr.IncomingResponse,n.status_code=r.status_code,n.reason_phrase=r.reason_phrase):(n=new pr.IncomingRequest(t),n.method=r.method,n.ruri=r.uri);n.data=c;let d=o+2;for(;;){if(o=$T(c,d),o===-2){a=d+2;break}else if(o===-1){fa.warn("parseMessage() | malformed message");return}if(r=HT(n,c,d,o),r!==!0){fa.warn("parseMessage() |",r.error);return}d=o+2}if(n.hasHeader("content-length")){const h=n.getHeader("content-length");n.body=c.substr(a,h)}else n.body=c.substring(a);return n};function $T(c,t){let n=t,a=0,o=0;if(c.substring(n,n+2).match(/(^\r\n)/))return-2;for(;a===0;){if(o=c.indexOf(`\r
158
158
  `,n),o===-1)return o;!c.substring(o+2,o+4).match(/(^\r\n)/)&&c.charAt(o+2).match(/(^\s+)/)?n=o+2:a=o}return a}function HT(c,t,n,a){let o;const s=t.indexOf(":",n),r=t.substring(n,s).trim(),d=t.substring(s+1,a).trim();switch(r.toLowerCase()){case"via":case"v":c.addHeader("via",d),c.getHeaders("via").length===1?(o=c.parseHeader("Via"),o&&(c.via=o,c.via_branch=o.branch)):o=0;break;case"from":case"f":c.setHeader("from",d),o=c.parseHeader("from"),o&&(c.from=o,c.from_tag=o.getParam("tag"));break;case"to":case"t":c.setHeader("to",d),o=c.parseHeader("to"),o&&(c.to=o,c.to_tag=o.getParam("tag"));break;case"record-route":if(o=Iu.parse(d,"Record_Route"),o===-1)o=void 0;else for(const h of o)c.addHeader("record-route",d.substring(h.possition,h.offset)),c.headers["Record-Route"][c.getHeaders("record-route").length-1].parsed=h.parsed;break;case"call-id":case"i":c.setHeader("call-id",d),o=c.parseHeader("call-id"),o&&(c.call_id=d);break;case"contact":case"m":if(o=Iu.parse(d,"Contact"),o===-1)o=void 0;else for(const h of o)c.addHeader("contact",d.substring(h.possition,h.offset)),c.headers.Contact[c.getHeaders("contact").length-1].parsed=h.parsed;break;case"content-length":case"l":c.setHeader("content-length",d),o=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",d),o=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",d),o=c.parseHeader("cseq"),o&&(c.cseq=o.value),c instanceof pr.IncomingResponse&&(c.method=o.method);break;case"max-forwards":c.setHeader("max-forwards",d),o=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",d),o=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",d),o=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",d),o=c.parseHeader("session-expires"),o&&(c.session_expires=o.expires,c.session_expires_refresher=o.refresher);break;case"refer-to":case"r":c.setHeader("refer-to",d),o=c.parseHeader("refer-to"),o&&(c.refer_to=o);break;case"replaces":c.setHeader("replaces",d),o=c.parseHeader("replaces"),o&&(c.replaces=o);break;case"event":case"o":c.setHeader("event",d),o=c.parseHeader("event"),o&&(c.event=o);break;default:c.addHeader(r,d),o=0}return o===void 0?{error:`error parsing header "${r}"`}:!0}const FT={parseMessage:LT},Wi=new Ga("Registrator"),ha=10;class jT{constructor(t,n){this._reg_id=1,this._ua=t,this._transport=n,this._registrar=t.configuration.registrar_server,this._expires=t.configuration.register_expires,this._call_id=Ts.createRandomToken(22),this._cseq=0,this._to_uri=t.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const a=this._contact.indexOf(">");if(a!==-1){const o=this._contact.slice(0,a)+this._contact.slice(a+1,this._contact.length);this._contact=o}this._extra_contact="",this._extraContactParams="",this._extra_contact+=";+sip.ice",this._extraHeaders=[],this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._extra_contact+=`;reg-id=${this._reg_id}`,this._extra_contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(t){Array.isArray(t)||(t=[]),this._extraHeaders=t.slice()}setExtraContactParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const a=t[n];this._extraContactParams+=`;${n}`,a&&(this._extraContactParams+=`=${a}`)}}setExtraContactUriParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const a=t[n];this._extraContactParams+=`;${n}`,a&&(this._extraContactParams+=`=${a}`)}}register(){if(this._registering){Wi.debug("Register request in progress...");return}const t=this._extraHeaders.slice();t.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),t.push(`Expires: ${this._expires}`);const n=new yt.OutgoingRequest(L.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t),a=new sl(this._ua,n,{onRequestTimeout:()=>{this._registrationFailure(null,L.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,L.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:o=>{if(o.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(o.status_code):break;case/^2[0-9]{2}$/.test(o.status_code):{if(this._registering=!1,!o.hasHeader("Contact")){Wi.debug("no Contact header in response to REGISTER, response ignored");break}const s=o.headers.Contact.reduce((_,g)=>_.concat(g.parsed),[]);let r=s.find(_=>this._sipInstance===_.getParam("+sip.instance")&&this._reg_id===parseInt(_.getParam("reg-id")));if(r||(r=s.find(_=>_.uri.user===this._ua.contact.uri.user)),!r){Wi.debug("no Contact header pointing to us, response ignored");break}let d=r.getParam("expires");!d&&o.hasHeader("expires")&&(d=o.getHeader("expires")),d||(d=this._expires),d=Number(d),d<ha&&(d=ha);const h=d>64?d*1e3/2+Math.floor((d/2-32)*1e3*Math.random()):d*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},h),r.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=r.getParam("temp-gruu").replace(/"/g,"")),r.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=r.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:o}));break}case/^423$/.test(o.status_code):{o.hasHeader("min-expires")?(this._expires=Number(o.getHeader("min-expires")),this._expires<ha&&(this._expires=ha),this.register()):(Wi.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(o,L.causes.SIP_FAILURE_CODE));break}default:{const s=Ts.sipErrorCause(o.status_code);this._registrationFailure(o,s)}}}});this._registering=!0,a.send()}unregister(t={}){if(!this._registered){Wi.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const n=this._extraHeaders.slice();t.all?n.push(`Contact: *${this._extraContactParams}`):n.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),n.push("Expires: 0");const a=new yt.OutgoingRequest(L.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n);new sl(this._ua,a,{onRequestTimeout:()=>{this._unregistered(null,L.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,L.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:s=>{switch(!0){case/^1[0-9]{2}$/.test(s.status_code):break;case/^2[0-9]{2}$/.test(s.status_code):this._unregistered(s);break;default:{const r=Ts.sipErrorCause(s.status_code);this._unregistered(s,r)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(t,n){this._registering=!1,this._ua.registrationFailed({response:t||null,cause:n}),this._registered&&(this._registered=!1,this._ua.unregistered({response:t||null,cause:n}))}_unregistered(t,n){this._registering=!1,this._registered=!1,this._ua.unregistered({response:t||null,cause:n||null})}}const tt=console,Vs={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},qT=wT;class VT extends qT{constructor(t){super(t),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this.newStreamPlugins=[],this.processStreamPlugins=[],this._registrator=new jT(this)}call(t,n){return super.call(t,n)}joinVideoCall(t,n,a){tt.debug("call()");const o=new $a(this);return o.configureMedia({audio:!0,video:!0}),o.connect(t,n,a),o}startScreenShare(){tt.debug("startScreenShare()");for(const t in this._janus_sessions)this._janus_sessions[t].connectScreenShare()}changeMediaConstraints(t){for(const n in this._janus_sessions)this._janus_sessions[n].changeMediaConstraints(t)}startBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].connectBlur()}stopBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].stopBlur()}_loadConfig(t){try{rl.load(this._configuration,t)}catch(s){throw s}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=Ts.newUUID());let n;typeof window<"u"&&typeof window.document<"u"?n=window==null?void 0:window.navigator.userAgent:typeof self<"u"&&self.navigator&&(n=self.navigator.userAgent),n+=" "+De.USER_AGENT,this._configuration.user_agent=t.overrideUserAgent&&typeof t.overrideUserAgent=="function"?t.overrideUserAgent(n):n,this._configuration.jssip_id=Ts.createRandomToken(5);const a=this._configuration.uri.clone();a.user=null,this._configuration.hostport_params=a.toString().replace(/^sip:/i,"");try{this._transport=new eT(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=BT.bind(this),this._transport.onconnect=GT.bind(this),this._transport.ondisconnect=WT.bind(this),this._transport.ondata=KT.bind(this)}catch(s){throw tt.warn(s),new qs.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const s=this._configuration.uri.clone();s.user=null,s.clearParams(),s.clearHeaders(),this._configuration.registrar_server=s}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new In("sip",Ts.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(s={}){const r=s.anonymous||null,d=s.outbound||null;let h="<";return r?h+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":h+=this.pub_gruu||this.uri.toString(),d&&(r?!this.temp_gruu:!this.pub_gruu)&&(h+=";ob"),h+=">",h}};const o=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const s in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,s)&&(o.indexOf(s)!==-1?Object.defineProperty(this._configuration,s,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,s,{writable:!1,configurable:!1}));tt.debug("configuration parameters after validation:");for(const s in this._configuration)if(Object.prototype.hasOwnProperty.call(rl.settings,s))switch(s){case"uri":case"registrar_server":tt.debug(`- ${s}: ${this._configuration[s]}`);break;case"password":case"ha1":case"authorization_jwt":tt.debug(`- ${s}: NOT SHOWN`);break;default:tt.debug(`- ${s}: ${JSON.stringify(this._configuration[s])}`)}}newMSRPSession(t,n){t.on("msgHistoryUpdate",a=>{console.log(a)}),this._msrp_sessions[t.id]=t,this.emit("newMSRPSession",n)}newJanusSession(t,n){this._janus_sessions[t.id]=t,this.newStreamPlugins.forEach(a=>{a.setSession(t)}),this.processStreamPlugins.forEach(a=>{a.setSession(t)}),this.emit("newJanusSession",n)}kill(){}destroyMSRPSession(t){delete this._msrp_sessions[t.id]}destroyJanusSession(t){delete this._janus_sessions[t.id]}receiveRequest(t){var s,r,d,h;const n=t.method;if(t.ruri.user!==this._configuration.uri.user&&t.ruri.user!==this._contact.uri.user){tt.debug("Request-URI does not point to us"),t.method!==De.ACK&&t.reply_sl(404);return}if(t.ruri.scheme===De.SIPS){t.reply_sl(416);return}if(Gt.checkTransaction(this,t))return;if(n===De.INVITE?new Gt.InviteServerTransaction(this,this._transport,t):n!==De.ACK&&n!==De.CANCEL&&new Gt.NonInviteServerTransaction(this,this._transport,t),n===De.OPTIONS){if(this.listeners("newOptions").length===0){t.reply(200);return}new Qc.Options(this).init_incoming(t)}else if(n===De.MESSAGE){if(this.listeners("newMessage").length===0){t.reply(405);return}new Qc.Message(this).init_incoming(t)}else if(n===De.INVITE&&!t.to_tag&&this.listeners("newRTCSession").length===0){t.reply(405);return}let a,o;if(t.to_tag)if(a=this._findDialog(t.call_id,t.from_tag,t.to_tag),a)a.receiveRequest(t);else if(n===De.NOTIFY)if(o=this._findSession(t),o)o.receiveRequest(t);else{if(t.body)try{const _=JSON.parse(t.body)||{};(r=(s=_.plugindata)==null?void 0:s.data)!=null&&r.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(_),(h=(d=_.plugindata)==null?void 0:d.data)!=null&&h.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(_.plugindata.data.unpublished)}catch(_){console.error(_)}t.reply(200)}else n!==De.ACK&&t.reply(481);else switch(n){case De.INVITE:if(window.RTCPeerConnection)if(t.hasHeader("replaces")){const _=t.replaces;a=this._findDialog(_.call_id,_.from_tag,_.to_tag),a?(o=a.owner,o.isEnded()?t.reply(603):o.receiveRequest(t)):t.reply(481)}else t.body.search(/MSRP/ig)>-1?(o=new nu(this),o.init_incoming(t)):t.body.search(/JANUS/ig)>-1||(o=new $g(this),o.init_incoming(t));else tt.warn("INVITE received but WebRTC is not supported"),t.reply(488);break;case De.BYE:t.reply(481);break;case De.CANCEL:o=this._findSession(t),o?o.receiveRequest(t):tt.debug("received CANCEL request for a non existent session");break;case De.ACK:break;case De.NOTIFY:this.emit("sipEvent",{event:t.event,request:t}),t.reply(200);break;default:t.reply(405);break}}startMSRP(t,n){tt.debug("startMSRP()",n);const a=new nu(this);return a.connect(t),a}startJanus(t,n){tt.debug("startJanus()",n);const a=new nu(this);return a.connect(t),a}terminateMSRPSessions(t){tt.debug("terminateSessions()");for(const n in this._msrp_sessions)this._msrp_sessions[n].isEnded()||this._msrp_sessions[n].terminate(t)}terminateJanusSessions(t){tt.debug("terminateSessions()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||this._janus_sessions[n].terminate(t)}enableJanusAudio(t){tt.debug("enableJanusAudio()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||(t?this._janus_sessions[n].startAudio():this._janus_sessions[n].stopAudio())}enableJanusVideo(t){tt.debug("enableJanusVideo()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||(t?this._janus_sessions[n].startVideo():this._janus_sessions[n].stopVideo())}stop(){if(tt.debug("stop()"),this._dynConfiguration={},this._status===Vs.STATUS_USER_CLOSED){tt.debug("UA already closed");return}this._registrator.close();const t=Object.keys(this._sessions).length;for(const a in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,a)){tt.debug(`closing session ${a}`);try{this._sessions[a].terminate()}catch(o){console.error(o)}}for(const a in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,a)){tt.debug(`closing session ${a}`);try{this._msrp_sessions[a].terminate()}catch(o){console.error(o)}}for(const a in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,a)){tt.debug(`closing session ${a}`);try{this._janus_sessions[a].terminate()}catch(o){console.error(o)}}for(const a in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,a))try{this._applicants[a].close()}catch(o){console.error(o)}this._status=Vs.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&t===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function BT(c){this.emit("connecting",c)}function GT(c){this._status!==Vs.STATUS_USER_CLOSED&&(this._status=Vs.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function WT(c){const t=["nict","ict","nist","ist"];for(const n of t)for(const a in this._transactions[n])Object.prototype.hasOwnProperty.call(this._transactions[n],a)&&this._transactions[n][a].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==Vs.STATUS_USER_CLOSED&&(this._status=Vs.STATUS_NOT_READY,this._error=Vs.NETWORK_ERROR)}function KT(c){const t=c.transport;let n=c.message;if(n=FT.parseMessage(n,this),!!n&&!(this._status===Vs.STATUS_USER_CLOSED&&n instanceof pr.IncomingRequest)&&pT(n,this,t)){if(n instanceof pr.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof pr.IncomingResponse){let a;switch(n.method){case De.INVITE:a=this._transactions.ict[n.via_branch],a&&a.receiveResponse(n);break;case De.ACK:break;default:a=this._transactions.nict[n.via_branch],a&&a.receiveResponse(n);break}}}}const YT=["roomId","_audioMuted","_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","_localHold","_videoMuted","status","start_time","_remote_identity","audioTag","isOnHold","localMuted","autoAnswer","putOnHoldTimestamp"],JT=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function Nf(c){const t={};return YT.forEach(n=>{c[n]!==void 0&&(t[n]=c[n])}),t.localHold=c._localHold,t}function Uf(c){const t={};return JT.forEach(n=>{c[n]!==void 0&&(t[n]=c[n])}),t}function Pf(c,t){const n=new AudioContext,a=n.createMediaStreamSource(c),o=n.createMediaStreamDestination(),s=n.createGain();return a.connect(s),s.connect(o),s.gain.value=t,o.stream}function zT(c,t,n,a){const o=document.createElement("audio");o.id=t._id,o.className="audioTag",o.srcObject=c,wh()||(o.setSinkId(n),o.volume=a),o.play(),t.audioTag=o}function XT(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}function wh(){return/Mobi|Android|iPhone/i.test(navigator.userAgent)}const QT=ut,ZT=Zt(),Dt=new QT("WebSocketInterface");var ev=class{constructor(t){Dt.debug('new() [url:"%s"]',t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;const n=ZT.parse(t,"absoluteURI");if(n===-1)throw Dt.warn(`invalid WebSocket URI: ${t}`),new TypeError(`Invalid argument: ${t}`);if(n.scheme!=="wss"&&n.scheme!=="ws")throw Dt.warn(`invalid WebSocket URI scheme: ${n.scheme}`),new TypeError(`Invalid argument: ${t}`);this._sip_uri=`sip:${n.host}${n.port?`:${n.port}`:""};transport=ws`,this._via_transport=n.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(t){this._via_transport=t.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Dt.debug("connect()"),this.isConnected()){Dt.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Dt.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Dt.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(t){this._onError(t)}}disconnect(){Dt.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(t){return Dt.debug("send()"),this.isConnected()?(this._ws.send(t),!0):(Dt.warn("unable to send message, WebSocket is not open"),!1)}isConnected(){return this._ws&&this._ws.readyState===this._ws.OPEN}isConnecting(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}_onOpen(){Dt.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:t,code:n,reason:a}){Dt.debug(`WebSocket ${this._url} closed`),t===!1&&Dt.debug("WebSocket abrupt disconnection"),this.ondisconnect(!t,n,a)}_onMessage({data:t}){Dt.debug("received WebSocket message"),this.ondata(t)}_onError(t){Dt.warn(`WebSocket ${this._url} error: `,t)}};const bu=Ha,tv=De,sv=As,nv=At(),rv=bh,iv=ys(),lv=$u(),av=Zt(),ov=ev,uv=gr("JsSIP");uv("version %s",bu.version);var cv={C:tv,Exceptions:sv,Utils:nv,UA:rv,URI:iv,NameAddrHeader:lv,WebSocketInterface:ov,Grammar:av,debug:gr,get name(){return bu.title},get version(){return bu.version}};const fv=ze(cv);function ru(c){return c<10?`0${c}`:`${c}`}function hv(c){let t=c.hours||0,n=c.minutes||0,a=c.seconds||0;a++,a===60&&(a=0,n++,n===60&&(n=0,t++));const o=`${ru(t)}:${ru(n)}:${ru(a)}`;return{seconds:a,minutes:n,hours:t,formatted:o}}var Ct={};Ct.forEach=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)if(o in c){const s=Promise.resolve(c[o]).then(r=>t.call(n||globalThis,r,o,c));a.push(s)}await Promise.all(a)};Ct.forEachSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)a in c&&await t.call(n||globalThis,await c[a],a,c)};Ct.map=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)o in c&&(a[o]=Promise.resolve(c[o]).then(s=>t.call(n||globalThis,s,o,c)));return Promise.all(a)};Ct.mapSeries=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)o in c&&(a[o]=await t.call(n||globalThis,await c[o],o,c));return a};Ct.find=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a();let s=1;for(let r=0;r<c.length;r++){const d=h=>{h?a(c[r]):s===c.length&&a(),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}});Ct.findSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(await t.call(n||globalThis,await c[a],a,c))return c[a]};Ct.findIndex=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a(-1);let s=1;for(let r=0;r<c.length;r++){const d=h=>{h?a(r):s===c.length&&a(-1),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}});Ct.findIndexSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(await t.call(n||globalThis,await c[a],a,c))return a};Ct.some=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a(!1);let s=1;for(let r=0;r<c.length;r++){if(!(r in c)){s++;continue}const d=h=>{h?a(!0):s===c.length&&a(!1),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}});Ct.someSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(a in c&&await t.call(n||globalThis,await c[a],a,c))return!0;return!1};Ct.every=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a(!0);let s=1;for(let r=0;r<c.length;r++){if(!(r in c)){s++;continue}const d=h=>{h?s===c.length&&a(!0):a(!1),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}});Ct.everySeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(a in c&&!await t.call(n||globalThis,await c[a],a,c))return!1;return!0};Ct.filter=(c,t,n)=>new Promise(async(a,o)=>{const s=[];for(let d=0;d<c.length;d++)d in c&&(s[d]=Promise.resolve(c[d]).then(h=>t.call(n||globalThis,h,d,c)).catch(o));const r=[];for(let d=0;d<s.length;d++)await s[d]&&r.push(await c[d]);a(r)});Ct.filterSeries=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)o in c&&await t.call(n||globalThis,await c[o],o,c)&&a.push(await c[o]);return a};Ct.reduce=async(c,t,n)=>{if(c.length===0&&n===void 0)throw TypeError("Reduce of empty array with no initial value");let a,o;for(n!==void 0?(o=n,a=0):(o=c[0],a=1),a;a<c.length;a++)a in c&&(o=await t(await o,await c[a],a,c));return o};var Oh={};(function(c){const t=Ct;Object.keys(t).forEach(n=>{const a=n.charAt(0).toUpperCase()+n.slice(1);c[`async${a}`]=async function(...o){return t[n](this,...o)}})})(Oh);const dv=Ct,_v=Oh;var pv=Object.assign(dv,{instanceMethods:_v});const Cn=new AudioContext,Xt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var mv={exports:{}};(function(c){var t=function(n){var a=Object.prototype,o=a.hasOwnProperty,s=Object.defineProperty||function(ee,W,G){ee[W]=G.value},r,d=typeof Symbol=="function"?Symbol:{},h=d.iterator||"@@iterator",_=d.asyncIterator||"@@asyncIterator",g=d.toStringTag||"@@toStringTag";function T(ee,W,G){return Object.defineProperty(ee,W,{value:G,enumerable:!0,configurable:!0,writable:!0}),ee[W]}try{T({},"")}catch{T=function(W,G,re){return W[G]=re}}function E(ee,W,G,re){var ge=W&&W.prototype instanceof oe?W:oe,be=Object.create(ge.prototype),xe=new P(re||[]);return s(be,"_invoke",{value:J(ee,G,xe)}),be}n.wrap=E;function y(ee,W,G){try{return{type:"normal",arg:ee.call(W,G)}}catch(re){return{type:"throw",arg:re}}}var A="suspendedStart",C="suspendedYield",I="executing",H="completed",$={};function oe(){}function N(){}function j(){}var Se={};T(Se,h,function(){return this});var ve=Object.getPrototypeOf,k=ve&&ve(ve(se([])));k&&k!==a&&o.call(k,h)&&(Se=k);var D=j.prototype=oe.prototype=Object.create(Se);N.prototype=j,s(D,"constructor",{value:j,configurable:!0}),s(j,"constructor",{value:N,configurable:!0}),N.displayName=T(j,g,"GeneratorFunction");function B(ee){["next","throw","return"].forEach(function(W){T(ee,W,function(G){return this._invoke(W,G)})})}n.isGeneratorFunction=function(ee){var W=typeof ee=="function"&&ee.constructor;return W?W===N||(W.displayName||W.name)==="GeneratorFunction":!1},n.mark=function(ee){return Object.setPrototypeOf?Object.setPrototypeOf(ee,j):(ee.__proto__=j,T(ee,g,"GeneratorFunction")),ee.prototype=Object.create(D),ee},n.awrap=function(ee){return{__await:ee}};function V(ee,W){function G(be,xe,Ce,le){var ye=y(ee[be],ee,xe);if(ye.type==="throw")le(ye.arg);else{var nt=ye.arg,at=nt.value;return at&&typeof at=="object"&&o.call(at,"__await")?W.resolve(at.__await).then(function(Ee){G("next",Ee,Ce,le)},function(Ee){G("throw",Ee,Ce,le)}):W.resolve(at).then(function(Ee){nt.value=Ee,Ce(nt)},function(Ee){return G("throw",Ee,Ce,le)})}}var re;function ge(be,xe){function Ce(){return new W(function(le,ye){G(be,xe,le,ye)})}return re=re?re.then(Ce,Ce):Ce()}s(this,"_invoke",{value:ge})}B(V.prototype),T(V.prototype,_,function(){return this}),n.AsyncIterator=V,n.async=function(ee,W,G,re,ge){ge===void 0&&(ge=Promise);var be=new V(E(ee,W,G,re),ge);return n.isGeneratorFunction(W)?be:be.next().then(function(xe){return xe.done?xe.value:be.next()})};function J(ee,W,G){var re=A;return function(be,xe){if(re===I)throw new Error("Generator is already running");if(re===H){if(be==="throw")throw xe;return st()}for(G.method=be,G.arg=xe;;){var Ce=G.delegate;if(Ce){var le=F(Ce,G);if(le){if(le===$)continue;return le}}if(G.method==="next")G.sent=G._sent=G.arg;else if(G.method==="throw"){if(re===A)throw re=H,G.arg;G.dispatchException(G.arg)}else G.method==="return"&&G.abrupt("return",G.arg);re=I;var ye=y(ee,W,G);if(ye.type==="normal"){if(re=G.done?H:C,ye.arg===$)continue;return{value:ye.arg,done:G.done}}else ye.type==="throw"&&(re=H,G.method="throw",G.arg=ye.arg)}}}function F(ee,W){var G=W.method,re=ee.iterator[G];if(re===r)return W.delegate=null,G==="throw"&&ee.iterator.return&&(W.method="return",W.arg=r,F(ee,W),W.method==="throw")||G!=="return"&&(W.method="throw",W.arg=new TypeError("The iterator does not provide a '"+G+"' method")),$;var ge=y(re,ee.iterator,W.arg);if(ge.type==="throw")return W.method="throw",W.arg=ge.arg,W.delegate=null,$;var be=ge.arg;if(!be)return W.method="throw",W.arg=new TypeError("iterator result is not an object"),W.delegate=null,$;if(be.done)W[ee.resultName]=be.value,W.next=ee.nextLoc,W.method!=="return"&&(W.method="next",W.arg=r);else return be;return W.delegate=null,$}B(D),T(D,g,"Generator"),T(D,h,function(){return this}),T(D,"toString",function(){return"[object Generator]"});function X(ee){var W={tryLoc:ee[0]};1 in ee&&(W.catchLoc=ee[1]),2 in ee&&(W.finallyLoc=ee[2],W.afterLoc=ee[3]),this.tryEntries.push(W)}function U(ee){var W=ee.completion||{};W.type="normal",delete W.arg,ee.completion=W}function P(ee){this.tryEntries=[{tryLoc:"root"}],ee.forEach(X,this),this.reset(!0)}n.keys=function(ee){var W=Object(ee),G=[];for(var re in W)G.push(re);return G.reverse(),function ge(){for(;G.length;){var be=G.pop();if(be in W)return ge.value=be,ge.done=!1,ge}return ge.done=!0,ge}};function se(ee){if(ee){var W=ee[h];if(W)return W.call(ee);if(typeof ee.next=="function")return ee;if(!isNaN(ee.length)){var G=-1,re=function ge(){for(;++G<ee.length;)if(o.call(ee,G))return ge.value=ee[G],ge.done=!1,ge;return ge.value=r,ge.done=!0,ge};return re.next=re}}return{next:st}}n.values=se;function st(){return{value:r,done:!0}}return P.prototype={constructor:P,reset:function(ee){if(this.prev=0,this.next=0,this.sent=this._sent=r,this.done=!1,this.delegate=null,this.method="next",this.arg=r,this.tryEntries.forEach(U),!ee)for(var W in this)W.charAt(0)==="t"&&o.call(this,W)&&!isNaN(+W.slice(1))&&(this[W]=r)},stop:function(){this.done=!0;var ee=this.tryEntries[0],W=ee.completion;if(W.type==="throw")throw W.arg;return this.rval},dispatchException:function(ee){if(this.done)throw ee;var W=this;function G(le,ye){return be.type="throw",be.arg=ee,W.next=le,ye&&(W.method="next",W.arg=r),!!ye}for(var re=this.tryEntries.length-1;re>=0;--re){var ge=this.tryEntries[re],be=ge.completion;if(ge.tryLoc==="root")return G("end");if(ge.tryLoc<=this.prev){var xe=o.call(ge,"catchLoc"),Ce=o.call(ge,"finallyLoc");if(xe&&Ce){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0);if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else if(xe){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0)}else if(Ce){if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(ee,W){for(var G=this.tryEntries.length-1;G>=0;--G){var re=this.tryEntries[G];if(re.tryLoc<=this.prev&&o.call(re,"finallyLoc")&&this.prev<re.finallyLoc){var ge=re;break}}ge&&(ee==="break"||ee==="continue")&&ge.tryLoc<=W&&W<=ge.finallyLoc&&(ge=null);var be=ge?ge.completion:{};return be.type=ee,be.arg=W,ge?(this.method="next",this.next=ge.finallyLoc,$):this.complete(be)},complete:function(ee,W){if(ee.type==="throw")throw ee.arg;return ee.type==="break"||ee.type==="continue"?this.next=ee.arg:ee.type==="return"?(this.rval=this.arg=ee.arg,this.method="return",this.next="end"):ee.type==="normal"&&W&&(this.next=W),$},finish:function(ee){for(var W=this.tryEntries.length-1;W>=0;--W){var G=this.tryEntries[W];if(G.finallyLoc===ee)return this.complete(G.completion,G.afterLoc),U(G),$}},catch:function(ee){for(var W=this.tryEntries.length-1;W>=0;--W){var G=this.tryEntries[W];if(G.tryLoc===ee){var re=G.completion;if(re.type==="throw"){var ge=re.arg;U(G)}return ge}}throw new Error("illegal catch attempt")},delegateYield:function(ee,W,G){return this.delegate={iterator:se(ee),resultName:W,nextLoc:G},this.method==="next"&&(this.arg=r),$}},n}(c.exports);try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}})(mv);var Dh={exports:{}};(function(c){(function(t,n){c.exports?c.exports=n():t.log=n()})(jh,function(){var t=function(){},n="undefined",a=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),o=["trace","debug","info","warn","error"];function s(C,I){var H=C[I];if(typeof H.bind=="function")return H.bind(C);try{return Function.prototype.bind.call(H,C)}catch{return function(){return Function.prototype.apply.apply(H,[C,arguments])}}}function r(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function d(C){return C==="debug"&&(C="log"),typeof console===n?!1:C==="trace"&&a?r:console[C]!==void 0?s(console,C):console.log!==void 0?s(console,"log"):t}function h(C,I){for(var H=0;H<o.length;H++){var $=o[H];this[$]=H<C?t:this.methodFactory($,C,I)}this.log=this.debug}function _(C,I,H){return function(){typeof console!==n&&(h.call(this,I,H),this[C].apply(this,arguments))}}function g(C,I,H){return d(C)||_.apply(this,arguments)}function T(C,I,H){var $=this,oe;I=I??"WARN";var N="loglevel";typeof C=="string"?N+=":"+C:typeof C=="symbol"&&(N=void 0);function j(D){var B=(o[D]||"silent").toUpperCase();if(!(typeof window===n||!N)){try{window.localStorage[N]=B;return}catch{}try{window.document.cookie=encodeURIComponent(N)+"="+B+";"}catch{}}}function Se(){var D;if(!(typeof window===n||!N)){try{D=window.localStorage[N]}catch{}if(typeof D===n)try{var B=window.document.cookie,V=B.indexOf(encodeURIComponent(N)+"=");V!==-1&&(D=/^([^;]+)/.exec(B.slice(V))[1])}catch{}return $.levels[D]===void 0&&(D=void 0),D}}function ve(){if(!(typeof window===n||!N)){try{window.localStorage.removeItem(N);return}catch{}try{window.document.cookie=encodeURIComponent(N)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}$.name=C,$.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},$.methodFactory=H||g,$.getLevel=function(){return oe},$.setLevel=function(D,B){if(typeof D=="string"&&$.levels[D.toUpperCase()]!==void 0&&(D=$.levels[D.toUpperCase()]),typeof D=="number"&&D>=0&&D<=$.levels.SILENT){if(oe=D,B!==!1&&j(D),h.call($,D,C),typeof console===n&&D<$.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+D},$.setDefaultLevel=function(D){I=D,Se()||$.setLevel(D,!1)},$.resetLevel=function(){$.setLevel(I,!1),ve()},$.enableAll=function(D){$.setLevel($.levels.TRACE,D)},$.disableAll=function(D){$.setLevel($.levels.SILENT,D)};var k=Se();k==null&&(k=I),$.setLevel(k,!1)}var E=new T,y={};E.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var H=y[I];return H||(H=y[I]=new T(I,E.getLevel(),E.methodFactory)),H};var A=typeof window!==n?window.log:void 0;return E.noConflict=function(){return typeof window!==n&&window.log===E&&(window.log=A),E},E.getLoggers=function(){return y},E.default=E,E})})(Dh);var It=Dh.exports;const vs=()=>`${new Date().toISOString()} | metrics`,Es=(c,t,n)=>`${c} | ${t} | ${n}`;It.setDefaultLevel(It.levels.TRACE);const gv=c=>{It.info(Es(vs(),"log ",`set log level to ${c?"verbose":"info"}`)),It.setLevel(c?It.levels.TRACE:It.levels.INFO)},Tv=c=>{const t=[...Object.keys(It.levels)];t.includes(c)?(It.info(Es(vs(),"log ",`update log level to ${c.toLowerCase()}`)),It.setLevel(c)):It.warn(Es(vs(),"log ","Incorrect log level please choose one of "),t)},Pe=(c,t,n)=>{n?It.debug(Es(vs(),c,t),n):It.debug(Es(vs(),c,t))},iu=(c,t)=>{It.info(Es(vs(),c,t))},Rn=(c,t)=>{It.info(Es(vs(),c,t))},wa=(c,t)=>{It.warn(Es(vs(),c,t))},dr=(c,t)=>{It.error(Es(vs(),c,t))};function vv(c){return Math.floor(Math.random()*c).toString()}function xf(c,t){let n=t;return c.forEach(a=>{n=n.replace(a,"")}),n}function Ev(c,t){let n="";for(let a=0;a<t;a+=1)n+=c[vv(c.length)];return n}function Sv({length:c=20,useLetters:t=!0,useNumbers:n=!0,includeSymbols:a=[],excludeSymbols:o=[]}={}){let s="abcdefghijklmnopqrstuvwxyz",r="0123456789",d=[],h=[],_=[];return t&&(o.length&&(s=xf(o,s)),h=s.split("")),n&&(o.length&&(r=xf(o,r)),_=r.split("")),d=[...h,..._,...a],Ev(d,c)}var yv=Sv;const Qi=ze(yv),Av=()=>"WebRTCMetrics",Cv=()=>"5.0.3",$e={INBOUND:"inbound",OUTBOUND:"outbound"},gs={IDLE:"idle",RUNNING:"running",MUTED:"muted"},Ki={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},Rv=()=>({...{delta_time_to_measure_probes_ms:0,delta_time_consumed_to_measure_ms:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,total_time_decoded_in:0,total_time_encoded_out:0,probes:[]}}),Nh={level_in:0,codec_id_in:"",codec_in:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,mos_in:0,mos_emodel_in:0,ssrc:"",direction:$e.INBOUND},Uh={level_out:0,codec_id_out:"",codec_out:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,timestamp_out:null,mos_out:0,mos_emodel_out:0,ssrc:"",direction:$e.OUTBOUND},Ph={codec_id_in:"",size_in:{width:null,height:null,framerate:null},codec_in:{mime_type:null,clock_rate:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,decoder_in:null,delta_ms_decode_frame_in:0,total_frames_decoded_in:0,total_time_decoded_in:0,delta_nack_sent_in:0,delta_pli_sent_in:0,total_nack_sent_in:0,total_pli_sent_in:0,ssrc:"",direction:$e.INBOUND},xh={codec_id_out:"",size_out:{width:null,height:null,framerate:null},codec_out:{mime_type:null,clock_rate:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,encoder_out:null,delta_ms_encode_frame_out:0,total_time_encoded_out:0,total_frames_encoded_out:0,delta_nack_received_out:0,delta_pli_received_out:0,total_nack_received_out:0,total_pli_received_out:0,limitation_out:{reason:null,durations:null,resolutionChanges:0},timestamp_out:null,ssrc:"",direction:$e.OUTBOUND},Iv=c=>{const t={pname:"",call_id:"",user_id:"",timestamp:null,count:0,audio:{},video:{},network:{infrastructure:3,local_candidate_id:"",local_candidate_type:"",local_candidate_protocol:"",local_candidate_relay_protocol:"",remote_candidate_id:"",remote_candidate_type:"",remote_candidate_protocol:""},data:{total_KBytes_in:0,total_KBytes_out:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,delta_kbs_bandwidth_in:0,delta_kbs_bandwidth_out:0,delta_rtt_connectivity_ms:null,total_rtt_connectivity_ms:0,total_rtt_connectivity_measure:0},experimental:{time_to_measure_ms:0}};if(c){const n={...c,audio:{},video:{},data:{...c.data},network:{...c.network},experimental:{...c.experimental}};return Object.keys(c.audio).forEach(a=>{n.audio[a]={...c.audio[a]}}),Object.keys(c.video).forEach(a=>{n.video[a]={...c.video[a]}}),n}return{...t,audio:{},video:{},data:{...t.data},network:{...t.network},experimental:{...t.experimental}}},bv={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${Qi()}`,cid:`c-${Qi()}`,uid:`u-${Qi()}`,record:!1,ticket:!0},zt={CANDIDATE_PAIR:"candidate-pair",CODEC:"codec",INBOUND_RTP:"inbound-rtp",LOCAL_CANDIDATE:"local-candidate",MEDIA_SOURCE:"media-source",OUTBOUND_RTP:"outbound-rtp",REMOTE_CANDIDATE:"remote-candidate",REMOTE_INBOUND_RTP:"remote-inbound-rtp",TRACK:"track"},q={AUDIO_LEVEL:"audioLevel",AVAILABLE_OUTGOING_BITRATE:"availableOutgoingBitrate",AVAILABLE_INCOMING_BITRATE:"availableIncomingBitrate",BYTES_RECEIVED:"bytesReceived",BYTES_SENT:"bytesSent",CANDIDATE_TYPE:"candidateType",CHANNELS:"channels",CLOCK_RATE:"clockRate",CODEC_ID:"codecId",CURRENT_ROUND_TRIP_TIME:"currentRoundTripTime",ROUND_TRIP_TIME:"roundTripTime",FRACTION_LOST:"fractionLost",FRAME_HEIGHT:"frameHeight",FRAME_WIDTH:"frameWidth",QUALITY_LIMITATION_REASON:"qualityLimitationReason",QUALITY_LIMITATION_DURATIONS:"qualityLimitationDurations",QUALITY_LIMITATION_RESOLUTION_CHANGES:"qualityLimitationResolutionChanges",ID:"id",JITTER:"jitter",KIND:"kind",MEDIA_TYPE:"mediaType",MIME_TYPE:"mimeType",LOCAL_CANDIDATE_ID:"localCandidateId",NETWORK_TYPE:"networkType",RELAY_PROTOCOL:"relayProtocol",NOMINATED:"nominated",PACKETS_LOST:"packetsLost",PACKETS_RECEIVED:"packetsReceived",PACKETS_SENT:"packetsSent",PROTOCOL:"protocol",PORT:"port",REMOTE_CANDIDATE_ID:"remoteCandidateId",REMOTE_SOURCE:"remoteSource",RESPONSES_RECEIVED:"responsesReceived",SDP_FMTP_LINE:"sdpFmtpLine",SSRC:"ssrc",SELECTED:"selected",STATE:"state",TIMESTAMP:"timestamp",TOTAL_ROUND_TRIP_TIME:"totalRoundTripTime",TOTAL_ROUND_TRIP_TIME_MEASUREMENTS:"roundTripTimeMeasurements",TYPE:"type",DECODER_IMPLEMENTATION:"decoderImplementation",ENCODER_IMPLEMENTATION:"encoderImplementation",FRAMES_DECODED:"framesDecoded",FRAMES_ENCODED:"framesEncoded",FRAMES_PER_SECOND:"framesPerSecond",TOTAL_DECODE_TIME:"totalDecodeTime",TOTAL_ENCODE_TIME:"totalEncodeTime",PLI:"pliCount",NACK:"nackCount"},x={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},Yi={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},lu={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ne={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},au="config ",wv=(c,t={},n)=>{const a={...n,...t};return t.pname||wa(au,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${n.pname}'`),t.cid||wa(au,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${n.cid}'`),t.uid||wa(au,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${n.uid}'`),a.pc=c,a},Ov=(c={})=>{const t={...bv,...c};return t.name=Av(),t.version=Cv(),t},ml=(c,t,n,a=!1,o)=>{let s=c.map(r=>{if(!n)return r[t];if(!o)return r[t][n];const d=r[t][o];return d?d[n]:null});return s=s.filter(r=>a?Number.isFinite(r)&&r>0:Number.isFinite(r)),s.length===0?[]:s},Gs=c=>c.reduce((t,n)=>t+n,0)/c.length,Dv=()=>`probe-${Qi()}`,Nv=()=>`coltr-${Qi()}`,kf=c=>new Promise(t=>setTimeout(t,c)),wu=(c,t,n)=>{t?c.call(t,n):c(n)},Ke=(c,t,n,a)=>{const o=ml(c,t,n,!0,a);if(o.length===0)return null;const s=o.reduce((_,g)=>_+g,0)/o.length;return s===0?null:o.map(_=>Math.abs(s-_)).reduce((_,g)=>_+g,0)/o.length*100/s},Xe=(c,t,n,a=!1,o)=>{const s=ml(c,t,n,a,o);return s.length===0?null:s.reduce((r,d)=>r+d,0)/s.length},Sn=(c,t,n)=>ml(c,t,n).reduce((o,s)=>o+s,0),Ye=(c,t,n,a)=>{const o=ml(c,t,n,!0,a);return o.length===0?null:Math.min(...o)},Je=(c,t,n,a)=>{const o=ml(c,t,n,!1,a);return o.length===0?null:Math.max(...o)},gt=(c,t,n,a)=>{const o=c.slice().pop();if(!o)return null;if(!n)return o[t];if(!a)return o[t][n];const s=o[t][a];return s?s[n]:null},Uv=c=>c.slice().pop(),ct=(c,t,n)=>{if(!t)return null;const a={};let o=t[x.AUDIO][c];o||(o=n===$e.INBOUND?{...Nh}:{...Uh}),a[x.AUDIO]=o;let s=t[x.VIDEO][c];return s||(s=n===$e.INBOUND?{...Ph}:{...xh}),a[x.VIDEO]=s,a},Ji="exporter ",Pv="2.0",Mf=(c,t,n)=>{if(!c||c.length===0)return 0;const a=c[c.length-1];if(!a)return 0;const o=a[t][n];if(o){const s=o.total_rtt_ms_out,r=o.total_rtt_measure_out;return!r||!s?Xe(c,t,"delta_rtt_ms_out",!1,n):Number(s/r)}return null},xv=(c,t)=>{if(!c||c.length===0)return 0;const n=c[c.length-1];if(!n)return 0;const a=n[t].total_rtt_connectivity_ms,o=n[t].total_rtt_connectivity_measure;return!o||!a?Xe(c,t,"delta_rtt_connectivity_ms"):Number(a/o)},kv=c=>gt(c,"network","local_candidate_type")!=="relay"?`direct/${gt(c,"network","local_candidate_protocol")}`:`turn/${gt(c,"network","local_candidate_relay_protocol")}`,Mv=c=>{const t=gt(c,"network","remote_candidate_type"),n=gt(c,"network","remote_candidate_protocol");return t!=="relay"?`direct/${n}`:`turn/${n}`};class Lv{constructor(t){this._start=null,this._end=null,this._cfg=t,this._referenceReport=null,this._reports=[],this._events=[]}start(){iu(Ji,"start() - start exporter...");const t=new Date;return this._start=t.toJSON(),t}stop(){iu(Ji,"stop() - stop exporter...");const t=new Date;return this._end=t.toJSON(),t}saveReferenceReport(t){this._referenceReport=t}getReferenceReport(){return this._referenceReport}addReport(t){this._cfg.ticket&&(Pe(Ji,`addReport() - add report to exporter at ${t.timestamp}`),this._reports.push(t))}addCustomEvent(t){this._events.push(t)}reset(){iu(Ji,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Pe(Ji,"ticket() - generate ticket");const t=gt(this._reports,"audio","total_packets_lost_in"),n=gt(this._reports,"audio","total_packets_in"),a=gt(this._reports,"video","total_packets_lost_in"),o=gt(this._reports,"video","total_packets_in"),s={},r=Uv(this._reports);return r&&(Object.keys(r[x.AUDIO]).forEach(d=>{const h=r[x.AUDIO][d];if(s[h.ssrc]={type:x.AUDIO,direction:h.direction},h.direction===$e.INBOUND){const _={avg:Xe(this._reports,x.AUDIO,"delta_jitter_ms_in",!1,d),min:Ye(this._reports,x.AUDIO,"delta_jitter_ms_in",d),max:Je(this._reports,x.AUDIO,"delta_jitter_ms_in",d),volatility:Ke(this._reports,x.AUDIO,"delta_jitter_ms_in",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.AUDIO,"delta_kbs_in",!1,d),min:Ye(this._reports,x.AUDIO,"delta_kbs_in",d),max:Je(this._reports,x.AUDIO,"delta_kbs_in",d),volatility:Ke(this._reports,x.AUDIO,"delta_kbs_in",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.AUDIO,"delta_KBytes_in",!1,d),min:Ye(this._reports,x.AUDIO,"delta_KBytes_in",d),max:Je(this._reports,x.AUDIO,"delta_KBytes_in",d),volatility:Ke(this._reports,x.AUDIO,"delta_KBytes_in",d),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={emodel:{avg:Xe(this._reports,x.AUDIO,"mos_emodel_in",!1,d),min:Ye(this._reports,x.AUDIO,"mos_emodel_in",d),max:Je(this._reports,x.AUDIO,"mos_emodel_in",d),volatility:Ke(this._reports,x.AUDIO,"mos_emodel_in",d)},effective:{avg:Xe(this._reports,x.AUDIO,"mos_in",!1,d),min:Ye(this._reports,x.AUDIO,"mos_in",d),max:Je(this._reports,x.AUDIO,"mos_in",d),volatility:Ke(this._reports,x.AUDIO,"mos_in",d)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},y=gt(this._reports,x.AUDIO,"total_packets_lost_in",d),A=gt(this._reports,x.AUDIO,"total_packets_in",d),C={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[d].jitter=_,s[d].mos=E,s[d].traffic=T,s[d].bitrate=g,s[d].loss=C}else{const _={avg:Xe(this._reports,x.AUDIO,"delta_jitter_ms_out",!1,d),min:Ye(this._reports,x.AUDIO,"delta_jitter_ms_out",d),max:Je(this._reports,x.AUDIO,"delta_jitter_ms_out",d),volatility:Ke(this._reports,x.AUDIO,"delta_jitter_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.AUDIO,"delta_kbs_out",!1,d),min:Ye(this._reports,x.AUDIO,"delta_kbs_out",d),max:Je(this._reports,x.AUDIO,"delta_kbs_out",d),volatility:Ke(this._reports,x.AUDIO,"delta_kbs_out",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.AUDIO,"delta_KBytes_out",!1,d),min:Ye(this._reports,x.AUDIO,"delta_KBytes_out",d),max:Je(this._reports,x.AUDIO,"delta_KBytes_out",d),volatility:Ke(this._reports,x.AUDIO,"delta_KBytes_out",d),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},E={avg:Mf(this._reports,x.AUDIO,d),min:Ye(this._reports,x.AUDIO,"delta_rtt_ms_out",d),max:Je(this._reports,x.AUDIO,"delta_rtt_ms_out",d),volatility:Ke(this._reports,x.AUDIO,"delta_rtt_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=gt(this._reports,x.AUDIO,"total_packets_lost_out",d),A=gt(this._reports,x.AUDIO,"total_packets_out",d),C={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},I={emodel:{avg:Xe(this._reports,x.AUDIO,"mos_emodel_out",!1,d),min:Ye(this._reports,x.AUDIO,"mos_emodel_out",d),max:Je(this._reports,x.AUDIO,"mos_emodel_out",d),volatility:Ke(this._reports,x.AUDIO,"mos_emodel_out",d)},effective:{avg:Xe(this._reports,x.AUDIO,"mos_out",!1,d),min:Ye(this._reports,x.AUDIO,"mos_out",d),max:Je(this._reports,x.AUDIO,"mos_out",d),volatility:Ke(this._reports,x.AUDIO,"mos_out",d)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};s[d].jitter=_,s[d].rtt=E,s[d].traffic=T,s[d].bitrate=g,s[d].loss=C,s[d].mos=I}}),Object.keys(r[x.VIDEO]).forEach(d=>{const h=r[x.VIDEO][d];if(s[d]={type:x.VIDEO,direction:h.direction},h.direction===$e.INBOUND){const _={avg:Xe(this._reports,x.VIDEO,"delta_jitter_ms_in",!1,d),min:Ye(this._reports,x.VIDEO,"delta_jitter_ms_in",d),max:Je(this._reports,x.VIDEO,"delta_jitter_ms_in",d),volatility:Ke(this._reports,x.VIDEO,"delta_jitter_ms_in",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.VIDEO,"delta_kbs_in",!1,d),min:Ye(this._reports,x.VIDEO,"delta_kbs_in",d),max:Je(this._reports,x.VIDEO,"delta_kbs_in",d),volatility:Ke(this._reports,x.VIDEO,"delta_kbs_in",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.VIDEO,"delta_KBytes_in",!1,d),min:Ye(this._reports,x.VIDEO,"delta_KBytes_in",d),max:Je(this._reports,x.VIDEO,"delta_KBytes_in",d),volatility:Ke(this._reports,x.VIDEO,"delta_KBytes_in",d),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E=gt(this._reports,x.VIDEO,"total_packets_lost_in",d),y=gt(this._reports,x.VIDEO,"total_packets_in",d),A={lost:E,avg:Math.round((E/(E+y)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[d].jitter=_,s[d].traffic=T,s[d].bitrate=g,s[d].loss=A}else{const _={avg:Xe(this._reports,x.VIDEO,"delta_jitter_ms_out",!1,d),min:Ye(this._reports,x.VIDEO,"delta_jitter_ms_out",d),max:Je(this._reports,x.VIDEO,"delta_jitter_ms_out",d),volatility:Ke(this._reports,x.VIDEO,"delta_jitter_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.VIDEO,"delta_kbs_out",!1,d),min:Ye(this._reports,x.VIDEO,"delta_kbs_out",d),max:Je(this._reports,x.VIDEO,"delta_kbs_out",d),volatility:Ke(this._reports,x.VIDEO,"delta_kbs_out",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.VIDEO,"delta_KBytes_out",!1,d),min:Ye(this._reports,x.VIDEO,"delta_KBytes_out",d),max:Je(this._reports,x.VIDEO,"delta_KBytes_out",d),volatility:Ke(this._reports,x.VIDEO,"delta_KBytes_out",d),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={avg:Mf(this._reports,x.VIDEO,d),min:Ye(this._reports,x.VIDEO,"delta_rtt_ms_out",d),max:Je(this._reports,x.VIDEO,"delta_rtt_ms_out",d),volatility:Ke(this._reports,x.VIDEO,"delta_rtt_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=gt(this._reports,x.VIDEO,"total_packets_lost_out",d),A=gt(this._reports,x.VIDEO,"total_packets_out",d),C={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[d].jitter=_,s[d].rtt=E,s[d].traffic=T,s[d].bitrate=g,s[d].loss=C}})),{version:Pv,configuration:{frequency:this._cfg.refreshEvery},started:this._start,ended:this._end,ua:{agent:navigator.userAgent,pname:this._cfg.pname,user_id:this._cfg.uid},call:{call_id:this._cfg.cid,events:this._events},details:{count:this._reports.length,reports:this._cfg.record?this._reports:[],reference:this._referenceReport||null},ssrc:s,data:{rtt:{avg:xv(this._reports,"data"),min:Ye(this._reports,"data","delta_rtt_connectivity_ms"),max:Je(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Ke(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((t/(t+n)*100||0)*100)/100}},video:{in:{avg:Math.round((a/(a+o)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:Xe(this._reports,"data","delta_kbs_in"),min:Ye(this._reports,"data","delta_kbs_in"),max:Je(this._reports,"data","delta_kbs_in"),volatility:Ke(this._reports,"data","delta_kbs_in")},out:{avg:Xe(this._reports,"data","delta_kbs_out"),min:Ye(this._reports,"data","delta_kbs_out"),max:Je(this._reports,"data","delta_kbs_out"),volatility:Ke(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:Xe(this._reports,"data","delta_KBytes_in"),min:Ye(this._reports,"data","delta_KBytes_in"),max:Je(this._reports,"data","delta_KBytes_in"),volatility:Ke(this._reports,"data","delta_KBytes_in")},out:{avg:Xe(this._reports,"data","delta_KBytes_out"),min:Ye(this._reports,"data","delta_KBytes_out"),max:Je(this._reports,"data","delta_KBytes_out"),volatility:Ke(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:kv(this._reports),remoteConnection:Mv(this._reports)}}}}updateConfig(t){this._cfg=t}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const t=this._reports.slice();return t.pop(),t.pop()||null}getReportsNumber(){return this._reports.length}}const js="extractor ",Lf=(c,t,n,a)=>{let o=!1;const s=a[t].total_rtt_ms_out,r=a[t].total_rtt_measure_out,d=n?n[t].total_rtt_ms_out:0,h=n?n[t].total_rtt_measure_out:0,_={rtt:null,totalRTT:s,totalRTTMeasurements:r};if(c[q.TIMESTAMP]===a[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,q.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(o=!0,Number(c[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-h===r))return _;const g=1e3*Number(c[q.ROUND_TRIP_TIME]);let T=s+g,E=r+1;return o&&(T=1e3*Number(c[q.TOTAL_ROUND_TRIP_TIME])-d,E=Number(c[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-h),{rtt:g,totalRTT:T,totalRTTMeasurements:E}},$v=(c,t,n,a)=>{if(!Object.prototype.hasOwnProperty.call(c,q.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:a[t].total_rtt_connectivity_ms,totalRTTMeasurements:a[t].total_rtt_connectivity_measure};const o=1e3*Number(c[q.CURRENT_ROUND_TRIP_TIME]);let s=a[t].total_rtt_connectivity_ms+o,r=a[t].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,q.TOTAL_ROUND_TRIP_TIME)&&(s=1e3*Number(c[q.TOTAL_ROUND_TRIP_TIME])-(n?n[t].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,q.RESPONSES_RECEIVED)&&(r=Number(c[q.RESPONSES_RECEIVED])-(n?n[t].total_rtt_connectivity_measure:0)),{rtt:o,totalRTT:s,totalRTTMeasurements:r}},da=(c,t,n)=>c[q.TIMESTAMP]===n[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,q.JITTER)?null:1e3*(Number(c[q.JITTER])||0),Hv=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,q.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,q.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:t[x.VIDEO].delta_ms_decode_frame_in,frames_decoded:t[x.VIDEO].total_frames_decoded_in,total_decode_time:t[x.VIDEO].total_time_decoded_in};const n=c[q.FRAMES_DECODED],a=c[q.TOTAL_DECODE_TIME],o=a-t[x.VIDEO].total_time_decoded_in,s=n-t[x.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:s>0?o*1e3/s:0,frames_decoded:n,total_decode_time:a}},Fv=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,q.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,q.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:t[x.VIDEO].delta_ms_encode_frame_out,frames_encoded:t[x.VIDEO].total_frames_encoded_out,total_encode_time:t[x.VIDEO].total_time_encoded_out};const n=c[q.FRAMES_ENCODED],a=c[q.TOTAL_ENCODE_TIME],o=a-t[x.VIDEO].total_time_encoded_out,s=n-t[x.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:s>0&&o?o*1e3/s:0,frames_encoded:n,total_encode_time:a}},$f=(c,t,n,a)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,q.BYTES_SENT))return{packetsSent:n[t].total_packets_out,packetsLost:n[t].total_packets_lost_out,bytesSent:n[t].total_KBytes_out};const o=Number(c[q.PACKETS_SENT])||0-(a?a[t].total_packets_out:0),s=o-n[t].total_packets_out,r=Number(c[q.BYTES_SENT])/1024-(a?a[t].total_KBytes_out:0),d=r-n[t].total_KBytes_out,h=c[q.TIMESTAMP]||Date.now(),_=a?a.timestamp:null;let g=n.timestamp;!g&&_&&(g=_);const T=g?h-g:0,E=T>0?d*.008*1024/T*1e3:0;return{packetsSent:o,deltaPacketsSent:s,KBytesSent:r,deltaKBytesSent:d,kbsSent:E}},Hf=(c,t,n,a)=>{let o=n[t].total_packets_lost_out,s=0,r=0;return Object.prototype.hasOwnProperty.call(c,q.PACKETS_LOST)&&(o=Number(c[q.PACKETS_LOST])||0-(a?a[t].total_packets_lost_out:0),s=o-n[t].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,q.FRACTION_LOST)&&(r=Number(100*c[q.FRACTION_LOST])),{packetsLost:o,deltaPacketsLost:s,fractionLost:r}},Ff=(c,t,n,a)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,q.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,q.BYTES_RECEIVED))return{percent_packets_lost:n[t].percent_packets_lost_in,packetsReceived:n[t].total_packets_in,packetsLost:n[t].total_packets_lost_in,bytesReceived:n[t].total_KBytes_in};const o=Number(c[q.PACKETS_RECEIVED])||0-(a?a[t].total_packets_in:0),s=Number(c[q.PACKETS_LOST])||0-(a?a[t].total_packets_lost_in:0),r=s-n[t].total_packets_lost_in,d=o-n[t].total_packets_in,h=o!==n[t].total_packets_in?r*100/(r+d):0,_=Number(c[q.BYTES_RECEIVED])/1024-(a?a[t].total_KBytes_in:0),g=_-n[t].total_KBytes_in,T=c[q.TIMESTAMP]||Date.now(),E=a?a.timestamp:null;let y=n.timestamp;!y&&E&&(y=E);const A=y?T-y:0,C=A>0?g*.008*1024/A*1e3:0;return{percentPacketsLost:h,packetsReceived:o,deltaPacketsReceived:d,packetsLost:s,deltaPacketsLost:r,KBytesReceived:_,deltaKBytesReceived:g,kbsReceived:C}},jv=c=>c[q.CANDIDATE_TYPE]!=="relay"?"":c[q.RELAY_PROTOCOL]||"",qv=c=>{if(!Object.prototype.hasOwnProperty.call(c,q.NETWORK_TYPE))return Yi.WIFI;switch(c[q.NETWORK_TYPE]){case lu.ETHERNET:return Yi.ETHERNET;case lu.CELLULAR_4G:return Yi.CELLULAR_4G;case lu.WIFI:return Yi.WIFI;default:return Yi.CELLULAR}},jf=c=>!Object.prototype.hasOwnProperty.call(c,q.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,q.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[q.FRAME_WIDTH]||null,height:c[q.FRAME_HEIGHT]||null,framerate:c[q.FRAMES_PER_SECOND]},Vv=c=>{const t=Object.prototype.hasOwnProperty.call(c,q.QUALITY_LIMITATION_REASON)?c[q.QUALITY_LIMITATION_REASON]:null,n=Object.prototype.hasOwnProperty.call(c,q.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[q.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,a=Object.prototype.hasOwnProperty.call(c,q.QUALITY_LIMITATION_DURATIONS)?c[q.QUALITY_LIMITATION_DURATIONS]:null;return a&&Object.keys(a).forEach(o=>{a[o]>1e3&&(a[o]=Number(a[o]/1e3))}),{reason:t,durations:a,resolutionChanges:n}},Bv=(c,t,n)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PLI)||!Object.prototype.hasOwnProperty.call(c,q.NACK))return{pliCount:t.total_pli_sent_in,nackCount:t.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const a=(c[q.PLI]||0)-(n?n[x.VIDEO].total_pli_sent_in:0),o=(c[q.NACK]||0)-(n?n[x.VIDEO].total_nack_sent_in:0);return{pliCount:a,nackCount:o,deltaPliCount:a-t[x.VIDEO].total_pli_sent_in,deltaNackCount:o-t[x.VIDEO].total_nack_sent_in}},Gv=(c,t,n)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PLI)||!Object.prototype.hasOwnProperty.call(c,q.NACK))return{pliCount:t.total_pli_received_out,nackCount:t.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const a=(c[q.PLI]||0)-(n?n[x.VIDEO].total_pli_received_out:0),o=(c[q.NACK]||0)-(n?n[x.VIDEO].total_nack_received_out:0);return{pliCount:a,nackCount:o,deltaPliCount:a-t[x.VIDEO].total_pli_received_out,deltaNackCount:o-t[x.VIDEO].total_nack_received_out}},Wv=c=>({channels:c[q.CHANNELS]||null,clock_rate:c[q.CLOCK_RATE]||null,mime_type:c[q.MIME_TYPE]||null,sdp_fmtp_line:c[q.SDP_FMTP_LINE]||null}),Kv=c=>({clock_rate:c[q.CLOCK_RATE]||null,mime_type:c[q.MIME_TYPE]||null}),Yv=(c,t,n)=>{const a=(c[q.BYTES_RECEIVED]||0)/1024-(n?n.data.total_KBytes_in:0),o=(c[q.BYTES_SENT]||0)/1024-(n?n.data.total_KBytes_out:0),s=c[q.TIMESTAMP]||Date.now(),r=a-t.data.total_KBytes_in,d=o-t.data.total_KBytes_out,h=n?n.timestamp:null;let _=t.timestamp;!_&&h&&(_=h);const g=_?s-_:0,T=g>0?r*.008*1024/g*1e3:0,E=g>0?d*.008*1024/g*1e3:0;return{total_KBytes_received:a,total_KBytes_sent:o,delta_KBytes_received:r,delta_KBytes_sent:d,kbs_speed_received:T,kbs_speed_sent:E}},Jv=c=>{const t=c[q.AVAILABLE_INCOMING_BITRATE]/1024||0,n=c[q.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:t,kbs_outgoing_bandwidth:n}},zv=(c,t,n,a)=>{if(!c)return[];switch(c[q.TYPE]){case zt.CANDIDATE_PAIR:let o=!1;if(c[q.NOMINATED]&&c[q.STATE]===x.SUCCEEDED&&(o=!0,Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c),q.SELECTED in c&&!c[q.SELECTED]&&(o=!1)),o){const r=c[q.LOCAL_CANDIDATE_ID],d=c[q.REMOTE_CANDIDATE_ID],h=Yv(c,t,a),_=Jv(c),g=$v(c,"data",a,t);return[{type:ne.NETWORK,value:{local_candidate_id:r}},{type:ne.NETWORK,value:{remote_candidate_id:d}},{type:ne.DATA,value:{total_KBytes_in:h.total_KBytes_received}},{type:ne.DATA,value:{total_KBytes_out:h.total_KBytes_sent}},{type:ne.DATA,value:{delta_KBytes_in:h.delta_KBytes_received}},{type:ne.DATA,value:{delta_KBytes_out:h.delta_KBytes_sent}},{type:ne.DATA,value:{delta_kbs_in:h.kbs_speed_received}},{type:ne.DATA,value:{delta_kbs_out:h.kbs_speed_sent}},{type:ne.DATA,value:{delta_kbs_bandwidth_in:_.kbs_incoming_bandwidth}},{type:ne.DATA,value:{delta_kbs_bandwidth_out:_.kbs_outgoing_bandwidth}},{type:ne.DATA,value:{delta_rtt_connectivity_ms:g.rtt}},{type:ne.DATA,value:{total_rtt_connectivity_ms:g.totalRTT}},{type:ne.DATA,value:{total_rtt_connectivity_measure:g.totalRTTMeasurements}}]}break;case zt.LOCAL_CANDIDATE:if(c[q.ID]===t.network.local_candidate_id)return[{type:ne.NETWORK,value:{infrastructure:qv(c)}},{type:ne.NETWORK,value:{local_candidate_type:c[q.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{local_candidate_protocol:c[q.PROTOCOL]||""}},{type:ne.NETWORK,value:{local_candidate_relay_protocol:jv(c)}}];break;case zt.REMOTE_CANDIDATE:if(c[q.ID]===t.network.remote_candidate_id)return[{type:ne.NETWORK,value:{remote_candidate_type:c[q.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{remote_candidate_protocol:c[q.PROTOCOL]||""}}];break;case zt.INBOUND_RTP:{Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const r=c[q.SSRC],d=ct(r,t,$e.INBOUND);d&&(d.timestamp=t.timestamp);const h=ct(r,a,$e.INBOUND);if(h&&(h.timestamp=a.timestamp),c[q.MEDIA_TYPE]===x.AUDIO){const _=Ff(c,x.AUDIO,d,h),g=da(c,x.AUDIO,d),T=c[q.CODEC_ID]||"";return[{ssrc:r,type:ne.AUDIO,value:{codec_id_in:T}},{ssrc:r,type:ne.AUDIO,value:{total_packets_in:_.packetsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_in:_.deltaPacketsReceived}},{ssrc:r,type:ne.AUDIO,value:{total_packets_lost_in:_.packetsLost}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_lost_in:_.deltaPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{percent_packets_lost_in:_.percentPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{total_KBytes_in:_.KBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_KBytes_in:_.deltaKBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_kbs_in:_.kbsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_in:g}}]}if(c[q.MEDIA_TYPE]===x.VIDEO){const _=Hv(c,d),g=Ff(c,x.VIDEO,d,h),T=da(c,x.VIDEO,d),E=c[q.DECODER_IMPLEMENTATION]||null,y=c[q.CODEC_ID]||null,A=jf(c),C=Bv(c,d,h);return[{ssrc:r,type:ne.VIDEO,value:{codec_id_in:y}},{ssrc:r,type:ne.VIDEO,value:{total_packets_in:g.packetsReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_in:g.deltaPacketsReceived}},{ssrc:r,type:ne.VIDEO,value:{total_packets_lost_in:g.packetsLost}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_lost_in:g.deltaPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{percent_packets_lost_in:g.percentPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{total_KBytes_in:g.KBytesReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_KBytes_in:g.deltaKBytesReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_kbs_in:g.kbsReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_jitter_ms_in:T}},{ssrc:r,type:ne.VIDEO,value:{decoder_in:E}},{ssrc:r,type:ne.VIDEO,value:{delta_ms_decode_frame_in:_.delta_ms_decode_frame}},{ssrc:r,type:ne.VIDEO,value:{total_frames_decoded_in:_.frames_decoded}},{ssrc:r,type:ne.VIDEO,value:{total_time_decoded_in:_.total_decode_time}},{ssrc:r,type:ne.VIDEO,value:{total_nack_sent_in:C.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_sent_in:C.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_sent_in:C.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_sent_in:C.deltaPliCount}},{ssrc:r,type:ne.VIDEO,value:{size_in:A}}]}break}case zt.OUTBOUND_RTP:{Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const r=c[q.SSRC],d=ct(r,t,$e.OUTBOUND);d&&(d.timestamp=t.timestamp);const h=ct(r,a,$e.OUTBOUND);if(h&&(h.timestamp=a.timestamp),c[q.MEDIA_TYPE]===x.AUDIO){const _=c[q.CODEC_ID]||null,g=$f(c,x.AUDIO,d,h);return[{ssrc:r,type:ne.AUDIO,value:{codec_id_out:_}},{ssrc:r,type:ne.AUDIO,value:{total_packets_out:g.packetsSent}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_out:g.deltaPacketsSent}},{ssrc:r,type:ne.AUDIO,value:{total_KBytes_out:g.KBytesSent}},{ssrc:r,type:ne.AUDIO,value:{delta_KBytes_out:g.deltaKBytesSent}},{ssrc:r,type:ne.AUDIO,value:{delta_kbs_out:g.kbsSent}}]}if(c[q.MEDIA_TYPE]===x.VIDEO){const _=c[q.ENCODER_IMPLEMENTATION]||null,g=c[q.CODEC_ID]||null,T=Fv(c,d),E=jf(c),y=Vv(c),A=Gv(c,d,h),C=$f(c,x.VIDEO,d,h);return[{ssrc:r,type:ne.VIDEO,value:{codec_id_out:g}},{ssrc:r,type:ne.VIDEO,value:{total_packets_out:C.packetsSent}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_out:C.deltaPacketsSent}},{ssrc:r,type:ne.VIDEO,value:{total_KBytes_out:C.KBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_KBytes_out:C.deltaKBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_kbs_out:C.kbsSent}},{ssrc:r,type:ne.VIDEO,value:{encoder_out:_}},{ssrc:r,type:ne.VIDEO,value:{delta_ms_encode_frame_out:T.delta_ms_encode_frame}},{ssrc:r,type:ne.VIDEO,value:{total_frames_encoded_out:T.frames_encoded}},{ssrc:r,type:ne.VIDEO,value:{total_time_encoded_out:T.total_encode_time}},{ssrc:r,type:ne.VIDEO,value:{total_nack_received_out:A.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_received_out:A.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_received_out:A.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_received_out:A.deltaPliCount}},{ssrc:r,type:ne.VIDEO,value:{size_out:E}},{ssrc:r,type:ne.VIDEO,value:{limitation_out:y}}]}break}case zt.MEDIA_SOURCE:{Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);break}case zt.TRACK:{Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);break}case zt.CODEC:const s=[];return Object.keys(t[x.AUDIO]).forEach(r=>{const d=t[x.AUDIO][r];if(d.codec_id_in===c[q.ID]||d.codec_id_out===c[q.ID]){Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const h=Wv(c);c[q.ID]===d.codec_id_in?s.push({ssrc:d.ssrc,type:ne.AUDIO,value:{codec_in:h}}):s.push({ssrc:d.ssrc,type:ne.AUDIO,value:{codec_out:h}})}}),Object.keys(t[x.VIDEO]).forEach(r=>{const d=t[x.VIDEO][r];if(d.codec_id_in===c[q.ID]||d.codec_id_out===c[q.ID]){Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const h=Kv(c);c[q.ID]===d.codec_id_in?s.push({ssrc:d.ssrc,type:ne.VIDEO,value:{codec_in:h}}):s.push({ssrc:d.ssrc,type:ne.VIDEO,value:{codec_out:h}})}}),s;case zt.REMOTE_INBOUND_RTP:{Pe(js,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const r=c[q.SSRC],d=ct(r,t,$e.OUTBOUND),h=ct(r,a,$e.OUTBOUND);if(c[q.KIND]===x.AUDIO){const _=Lf(c,x.AUDIO,h,d),g=da(c,x.AUDIO,d),T=Hf(c,x.AUDIO,d,h);return[{ssrc:r,type:ne.AUDIO,value:{delta_rtt_ms_out:_.rtt}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_ms_out:_.totalRTT}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_measure_out:_.totalRTTMeasurements}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_out:g}},{ssrc:r,type:ne.AUDIO,value:{timestamp_out:c[q.TIMESTAMP]}},{ssrc:r,type:ne.AUDIO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{percent_packets_lost_out:T.fractionLost}}]}if(c[q.KIND]===x.VIDEO){const _=Lf(c,x.VIDEO,h,d),g=da(c,x.VIDEO,d),T=Hf(c,x.VIDEO,d,h);return[{ssrc:r,type:ne.VIDEO,value:{delta_rtt_ms_out:_.rtt}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_ms_out:_.totalRTT}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_measure_out:_.totalRTTMeasurements}},{ssrc:r,type:ne.VIDEO,value:{delta_jitter_ms_out:g}},{ssrc:r,type:ne.VIDEO,value:{timestamp_out:c[q.TIMESTAMP]}},{ssrc:r,type:ne.VIDEO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{percent_packets_lost_out:T.fractionLost}}]}break}}return[]},Ka=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),Xv=(c,t=x.AUDIO,n,a,o)=>{const s=ct(o,c,$e.INBOUND),r=ct(o,n,$e.INBOUND),d=ct(o,a,$e.INBOUND),h=[],_=[],g=s[t].percent_packets_lost_in,T=s[t].delta_jitter_ms_in,E=r&&r[t].delta_jitter_ms_in||null,y=d&&d[t].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,C=n&&n.data.delta_rtt_connectivity_ms||null,I=a&&a.data.delta_rtt_connectivity_ms||null;A&&h.push(A),C&&h.push(C),I&&h.push(I),T&&_.push(T),n&&E&&_.push(E),a&&y&&_.push(y);const H=h.length>0?Gs(h):100,$=_.length>0?Gs(_):10,oe=93.2-g,N=.18*oe*oe-27.9*oe+1126.62,j=(H+$)/2,Se=j-177.3<0?0:1,ve=.024*j+.11*(j-177.3)*Se,k=N-ve;return Ka(k)},Qv=(c,t=x.AUDIO,n,a,o)=>{const s=ct(o,c,$e.OUTBOUND),r=ct(o,n,$e.OUTBOUND),d=ct(o,a,$e.OUTBOUND),h=[],_=[],g=s[t].percent_packets_lost_out,T=s[t].delta_rtt_ms_out,E=r&&r[t].delta_rtt_ms_out||null,y=d&&d[t].delta_rtt_ms_out||null,A=s[t].delta_jitter_ms_out,C=r&&r[t].delta_jitter_ms_out||null,I=d&&d[t].delta_jitter_ms_out||null,H=c.data.delta_rtt_connectivity_ms,$=n&&n.data.delta_rtt_connectivity_ms||null,oe=a&&a.data.delta_rtt_connectivity_ms||null;T?h.push(T):H&&h.push(H),E?h.push(E):$&&h.push($),y?h.push(y):oe&&h.push(oe),A&&_.push(A),n&&C&&_.push(C),a&&I&&_.push(I);const N=h.length>0?Gs(h):100,j=_.length>0?Gs(_):10,Se=93.2-g,ve=.18*Se*Se-27.9*Se+1126.62,k=(N+j)/2,D=k-177.3<0?0:1,B=.024*k+.11*(k-177.3)*D,V=ve-B;return Ka(V)},Zv=(c,t=x.AUDIO,n,a,o)=>{const s=ct(o,c,$e.INBOUND),r=ct(o,n,$e.INBOUND),d=ct(o,a,$e.INBOUND),h=[],_=[],g=s[t].percent_packets_lost_in/100,T=s[t].delta_jitter_ms_in,E=r&&r[t].delta_jitter_ms_in||null,y=d&&d[t].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,C=n&&n.data.delta_rtt_connectivity_ms||null,I=a&&a.data.delta_rtt_connectivity_ms||null;A&&h.push(A),C&&h.push(C),I&&h.push(I),T&&_.push(T),r&&E&&_.push(E),d&&y&&_.push(y);const H=h.length>0?Gs(h):100,$=_.length>0?Gs(_):10,oe=0,N=19.8,j=29.7,Se=30,ve=(H+$)/2+Se,k=ve-177.3<0?0:1,D=.024*ve+.11*(ve-177.3)*k,V=93.2-(oe+N*Math.log(1+j*g)+D);return Ka(V)},eE=(c,t=x.AUDIO,n,a,o)=>{const s=ct(o,c,$e.OUTBOUND),r=ct(o,n,$e.OUTBOUND),d=ct(o,a,$e.OUTBOUND),h=[],_=[],g=s[t].percent_packets_lost_out/100,T=s[t].delta_rtt_ms_out,E=r&&r[t].delta_rtt_ms_out||null,y=d&&d[t].delta_rtt_ms_out||null,A=s[t].delta_jitter_ms_out,C=r&&r[t].delta_jitter_ms_out||null,I=d&&d[t].delta_jitter_ms_out||null,H=c.data.delta_rtt_connectivity_ms,$=n&&n.data.delta_rtt_connectivity_ms||null,oe=a&&a.data.delta_rtt_connectivity_ms||null;T?h.push(T):H&&h.push(H),E?h.push(E):$&&h.push($),y?h.push(y):oe&&h.push(oe),A&&_.push(A),r&&C&&_.push(C),d&&I&&_.push(I);const N=h.length>0?Gs(h):100,j=_.length>0?Gs(_):10,Se=0,ve=19.8,k=29.7,D=30,B=(N+j)/2+D,V=B-177.3<0?0:1,J=.024*B+.11*(B-177.3)*V,X=93.2-(Se+ve*Math.log(1+k*g)+J);return Ka(X)};class tE{constructor(t,n){this._callbacks={onreport:null,onticket:null},this._id=Nv(),this._moduleName=this._id,this._probeId=n,this._config=t,this._exporter=new Lv(t),this._state=gs.IDLE,this.registerToPCEvents(),Rn(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(t,n,a,o){const s=(h,_)=>h===x.AUDIO?_===zt.INBOUND_RTP?{...Nh}:{...Uh}:_===zt.INBOUND_RTP?{...Ph}:{...xh},r=Iv(n);r.pname=this._config.pname,r.call_id=this._config.cid,r.user_id=this._config.uid,r.count=n?n.count+1:1;let d=null;return t.forEach(h=>{!d&&h.timestamp&&(d=h.timestamp),zv(h,r,r.pname,o).forEach(g=>{if(g.value&&g.type)if(g.ssrc){let T=r[g.type][g.ssrc];T||(T=s(g.type,h.type),T.ssrc=g.ssrc,r[g.type][g.ssrc]=T),Object.keys(g.value).forEach(E=>{T[E]=g.value[E]})}else Object.keys(g.value).forEach(T=>{r[g.type][T]=g.value[T]})})}),r.timestamp=d,Object.keys(r[x.AUDIO]).forEach(h=>{const _=r[x.AUDIO][h];_.direction===$e.INBOUND?(_.mos_emodel_in=Xv(r,x.AUDIO,n,a,_.ssrc),_.mos_in=Zv(r,x.AUDIO,n,a,_.ssrc)):(_.mos_emodel_out=Qv(r,x.AUDIO,n,a,_.ssrc),_.mos_out=eE(r,x.AUDIO,n,a,_.ssrc))}),r}async takeReferenceStats(){return new Promise((t,n)=>{const a=Date.now();setTimeout(async()=>{try{const o=Date.now()-a,s=Date.now(),r=await this._config.pc.getStats(),d=this.analyze(r,null,null,null),h=Date.now();d.experimental.time_to_measure_ms=h-s,d.experimental.time_to_wait_ms=o,this._exporter.saveReferenceReport(d),Pe(this._moduleName,`got reference report for probe ${this._probeId}`),t()}catch(o){n(o)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==gs.RUNNING||!this._config.pc)return Pe(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const t=Date.now(),n=await this._config.pc.getStats(),a=this.analyze(n,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),o=Date.now();return a.experimental.time_to_measure_ms=o-t,this._exporter.addReport(a),Pe(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(a),a}catch(t){return dr(this._moduleName,`got error ${t}`),null}}async start(){Pe(this._moduleName,"starting"),this.state=gs.RUNNING,this._startedTime=this._exporter.start(),Pe(this._moduleName,"started")}async mute(){this.state=gs.MUTED,Pe(this._moduleName,"muted")}async unmute(){this.state=gs.RUNNING,Pe(this._moduleName,"unmuted")}async stop(t){if(Pe(this._moduleName,`stopping${t?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=gs.IDLE,this._config.ticket){const{ticket:n}=this._exporter;this.fireOnTicket(n)}this._exporter.reset(),Pe(this._moduleName,"stopped")}registerCallback(t,n,a){t in this._callbacks?(this._callbacks[t]={callback:n,context:a},Pe(this._moduleName,`registered callback '${t}'`)):dr(this._moduleName,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],Pe(this._moduleName,`unregistered callback '${t}'`)):dr(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReport(t){this._callbacks.onreport&&wu(this._callbacks.onreport.callback,this._callbacks.onreport.context,t)}fireOnTicket(t){this._callbacks.onticket&&wu(this._callbacks.onticket.callback,this._callbacks.onticket.context,t)}updateConfig(t){this._config=t,this._exporter.updateConfig(t)}get state(){return this._state}set state(t){this._state=t,Pe(this._moduleName,`state changed to ${t}`)}addCustomEvent(t,n,a,o){this._exporter.addCustomEvent({at:typeof t=="object"?t.toJSON():t,category:n,name:a,description:o})}async registerToPCEvents(){const{pc:t}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const n=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${n.length} devices found`,"Media Devices state")}catch{dr(this._moduleName,"can't get devices")}},t){t.oniceconnectionstatechange=()=>{const a=t.iceConnectionState;a===Ki.CONNECTED||a===Ki.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===Ki.DISCONNECTED||a===Ki.FAILED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===Ki.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},t.onicegatheringstatechange=()=>{const a=t.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",a,"ICE gathering state")},t.ontrack=a=>{this.addCustomEvent(new Date().toJSON(),"call",`${a.track.kind}track`,"MediaStreamTrack received")},t.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const n=t.getReceivers();if(n&&n.length>0){const a=n[0],{transport:o}=a;if(o){const{iceTransport:s}=o;s&&(s.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class sE{constructor(t){this._id=t.pname&&t.pname.substr(0,12).padEnd(12," ")||Dv(),this._moduleName=this._id,Rn(this._moduleName,"probe created"),this._config=t,this._collector=new tE(this._config,this._id)}set onreport(t){t?this._collector.registerCallback("onreport",t):this._collector.unregisterCallback("onreport")}set onticket(t){t?this._collector.registerCallback("onticket",t):this._collector.unregisterCallback("onticket")}get id(){return this._id}get pname(){return this._config.pname}get cid(){return this._config.cid}get uid(){return this._config.uid}get state(){return this._collector.state}set state(t){this._collector.state=t}addCustomEvent(t,n,a,o=new Date().toJSON()){this._collector.addCustomEvent(o,n,t,a)}get isRunning(){return this._collector.state===gs.RUNNING}get isIdle(){return this._collector.state===gs.IDLE}updateUserId(t){this._config.uid=t,this._collector.updateConfig(this._config)}updateCallId(t){this._config.cid=t,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){wa(this._moduleName,"probe is already running");return}this._collector.start()}stop(t=!1){this.isRunning&&this._collector.stop(t)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const Rt="engine ";class nE{constructor(t){this._config=t,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},Rn(Rt,`configured for probing every ${this._config.refreshEvery}ms`),Rn(Rt,`configured for starting after ${this._config.startAfter}ms`),Rn(Rt,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Pe(Rt,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(t=>t.isRunning)}get isIdle(){return this._probes.every(t=>t.isIdle)}addNewProbe(t,n){if(!t)throw new Error("undefined peer connection");const a=wv(t,n,this._config),o=new sE(a);return this._probes.push(o),Pe(Rt,`${this._probes.length} probes registered`),o}removeExistingProbe(t){if(!t)throw new Error("undefined probe");t.state===gs.RUNNING&&t.stop(),this._probes=this._probes.filter(n=>t.id!==n.id)}async start(){const t=()=>{this._probes.forEach(s=>s.start())},n=async()=>Promise.all(this._probes.map(s=>s.takeReferenceStats())),a=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,o=async()=>{const s=Rv(),r=this._probes.filter(d=>d.isRunning);for(const d of r){const h=await d.collectStats();h&&s.probes.push(h),Pe(Rt,`got probe ${d.id}`),await kf(0)}return s.delta_time_to_measure_probes_ms=Sn(s.probes,"experimental","time_to_measure_ms"),s.delta_KBytes_in=Sn(s.probes,"data","delta_KBytes_in"),s.delta_KBytes_out=Sn(s.probes,"data","delta_KBytes_out"),s.delta_kbs_in=Sn(s.probes,"data","delta_kbs_in"),s.delta_kbs_out=Sn(s.probes,"data","delta_kbs_out"),s.total_time_decoded_in=Sn(s.probes,"video","total_time_decoded_in"),s.total_time_encoded_out=Sn(s.probes,"video","total_time_encoded_out"),s};for(Pe(Rt,"starting to collect"),t(),Pe(Rt,"generating reference reports..."),await n(),Pe(Rt,"reference reports generated"),this._startedTime=Date.now();a();)if(Pe(Rt,`wait ${this._config.refreshEvery}ms before collecting`),await kf(this._config.refreshEvery),a()){Pe(Rt,"collecting...");const s=Date.now(),r=await o(),d=Date.now();r.delta_time_consumed_to_measure_ms=d-s,this.fireOnReports(r),Pe(Rt,"collected")}Pe(Rt,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(t){const n=a=>{this._probes.forEach(o=>{o.stop(a)})};Rn(Rt,"stop collecting"),n(t)}registerCallback(t,n,a){t in this._callbacks?(this._callbacks[t]={callback:n,context:a},Pe(Rt,`registered callback '${t}'`)):dr(Rt,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],Pe(this._moduleName,`unregistered callback '${t}'`)):dr(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReports(t){this._callbacks.onresult&&t.probes.length>0&&wu(this._callbacks.onresult.callback,this._callbacks.onresult.context,t)}}const rE="interface ";class iE{constructor(t){this._config=Ov(t),Rn(rE,`welcome to ${this._config.name} version ${this._config.version}`),gv(this._config.verbose||!1),this._engine=new nE(this._config)}setupLogLevel(t){Tv(t)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(t,n){return this._engine.addNewProbe(t,n)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(t){this._engine.removeExistingProbe(t)}set onresult(t){t?this._engine.registerCallback("onresult",t):this._engine.unregisterCallback("onresult")}}function lE(c,t){return Object.keys(c).filter(n=>t.includes(n)).reduce((n,a)=>{const o=a;return{...n,[o]:c[o]}},{})}const aE=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"];class oE{constructor(t){this.intervals={},this.emitInterval=t.emitInterval||200,this.onChangeFunction=t.onChangeFunction}start(t,n){t&&t.getTracks().length&&requestAnimationFrame(()=>this.beginCalculation(t,n))}stop(t){this.clearVolumeInterval(t)}clearVolumeInterval(t){clearInterval(this.intervals[t]),delete this.intervals[t]}clearAllIntervals(){Object.keys(this.intervals).forEach(t=>{clearInterval(this.intervals[t])}),this.intervals={}}beginCalculation(t,n){this.clearVolumeInterval(n);const a=Cn.createAnalyser(),o=Cn.createMediaStreamSource(t),s=Cn.createScriptProcessor(2048,1,1);a.smoothingTimeConstant=.8,a.fftSize=1024,o.connect(a),a.connect(s),s.connect(Cn.destination),this.intervals[n]=setInterval(()=>{const r=new Uint8Array(a.frequencyBinCount);a.getByteFrequencyData(r);let d=0;const h=r.length;for(let g=0;g<h;g++)d+=r[g];const _=d/h;this.onChangeFunction(n,_)},this.emitInterval)}}const _a={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},uE=0;class cE{constructor(t){this.isAutoAnswer=!1,this.muteWhenJoinEnabled=!1,this.isDNDEnabled=!1,this.muted=!1,this.microphoneInputLevelValue=1,this.speakerVolumeValue=1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.availableMediaDevices=[],this.selectedMediaDevices={input:"default",output:"default"},this.callStatus={},this.callTime={},this.callMetrics={},this.timeIntervals={},this.metricConfig={refreshEvery:1e3},this.activeStreamValue=null,this.initialStreamValue=null,this.context=t,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new oE({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices()}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(t){this.currentActiveRoomIdValue=t,this.context.emit("currentActiveRoomChanged",t)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(t){this.isCallAddingInProgress=t,this.context.emit("callAddingInProgressChanged",t)}get muteWhenJoin(){return this.muteWhenJoinEnabled}get isDND(){return this.isDNDEnabled}get speakerVolume(){return this.speakerVolumeValue}get microphoneInputLevel(){return this.microphoneInputLevelValue}get getActiveCalls(){return this.activeCalls}get hasActiveCalls(){return Object.values(this.extendedCalls).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audiooutput")}get getUserMediaConstraints(){return wh()?{video:!1,audio:!0}:{audio:{deviceId:{exact:this.selectedMediaDevices.input}},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(t){this.availableMediaDevices=t,this.context.emit("changeAvailableDeviceList",t)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const t=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(t)}async initializeMediaDevices(){const t=localStorage.getItem(_a.SELECTED_INPUT_DEVICE)||"default",n=localStorage.getItem(_a.SELECTED_OUTPUT_DEVICE)||"default";try{const a=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),o=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(o),await this.setMicrophone(t),await this.setSpeaker(n),navigator.mediaDevices.addEventListener("devicechange",async()=>{const s=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(s)}),a.getTracks().forEach(s=>s.stop())}catch(a){console.error(a)}}setCallTime(t){const n={...t};delete n.callId,this.callTime={...this.callTime,[t.callId]:n},this.context.emit("changeCallTime",this.callTime)}removeCallTime(t){const n={...this.callTime};delete n[t],this.callTime={...n},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(t,n){this.timeIntervals={...this.timeIntervals,[t]:n}}removeTimeInterval(t){const n={...this.timeIntervals};n[t]&&(clearInterval(n[t]),delete n[t],this.timeIntervals={...n})}stopCallTimer(t){this.removeTimeInterval(t),this.removeCallTime(t)}emitVolumeChange(t,n){this.context.emit("changeCallVolume",{callId:t,volume:n})}setMetricsConfig(t){this.metricConfig={...this.metricConfig,...t}}sendDTMF(t,n){if(!/^[A-D0-9]+$/g.test(n))throw new Error("Not allowed character in DTMF input");this.extendedCalls[t].sendDTMF(n)}setIsMuted(t){this.muted=t,this.context.emit("changeIsMuted",t)}processMute(t){const n=this.currentActiveRoomId;this.setIsMuted(t),this.initialStreamValue.getTracks().forEach(a=>a.enabled=!t),this.roomReconfigure(n)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:t,toHold:n,automatic:a}){const o=this.extendedCalls[t];o._automaticHold=a??!1,await new Promise(d=>{const h=()=>{o.putOnHoldTimestamp=n?Date.now():void 0,d()};n?o.hold({},h):o.unhold({},h)}),this.updateCall(o);const r=Object.values(this.extendedCalls).filter(d=>d.roomId===this.currentActiveRoomId&&(n?t!==d._id:!0));r.length>1&&await this.doConference(r)}holdCall(t,n=!1){return this.processHold({callId:t,automatic:n,toHold:!0})}unholdCall(t){return this.processHold({callId:t,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(t=>t.direction==="outgoing"&&t.status===uE).forEach(t=>this.terminateCall(t._id))}answerCall(t){const n=this.extendedCalls[t];this.cancelAllOutgoingUnanswered(),n.answer(this.sipOptions),this.updateCall(n),this.setActiveRoom(n.roomId),n.connection.addEventListener("track",a=>{this.triggerAddStream(a,n)})}async moveCall(t,n){this.updateCallStatus({callId:t,isMoving:!0}),await this.processRoomChange({callId:t,roomId:n}),this.updateCallStatus({callId:t,isMoving:!1})}updateCall(t){this.activeCalls[t._id]=Nf(t),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(t){const a={...this.activeRooms[t.roomId],...t};this.activeRooms={...this.activeRooms,[t.roomId]:{...a}},this.context.emit("updateRoom",{room:a,roomList:this.activeRooms})}hasAutoAnswerHeaders(t){const n=/answer-after=0/,o=t.request.getHeader("Call-Info");return o&&n.test(o)}addCall(t,n=!0){this.activeCalls={...this.activeCalls,[t._id]:Nf(t)},this.extendedCalls[t._id]=t,n&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(t){this.callStatus={...this.callStatus,[t]:{isMoving:!1,isTransferring:!1,isMerging:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(t){const a={...{...this.callStatus[t.callId]}};t.isMoving!==void 0&&(a.isMoving=t.isMoving),t.isTransferring!==void 0&&(a.isTransferring=t.isTransferring),t.isMerging!==void 0&&(a.isMerging=t.isMerging),this.callStatus={...this.callStatus,[t.callId]:{...a}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(t){const n={...this.callStatus};delete n[t],this.callStatus={...n},this.context.emit("changeCallStatus",this.callStatus)}addRoom(t){this.activeRooms={...this.activeRooms,[t.roomId]:t},this.context.emit("addRoom",{room:t,roomList:this.activeRooms})}getActiveStream(){const t=Pf(this.initialStreamValue,this.microphoneInputLevel*2);return t.getTracks().forEach(n=>n.enabled=!this.isMuted),this.setActiveStream(t),t}async setMicrophone(t){if(!this.getInputDeviceList.find(({deviceId:a})=>a===t)||(this.setSelectedInputDevice(t),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const n=Object.values(this.extendedCalls).filter(a=>a.roomId===this.currentActiveRoomId);n.length===1?Object.values(n).forEach(async a=>{const o=this.getActiveStream();a.connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.updateCall(a)}):await this.doConference(n)}setActiveStream(t){this.activeStream&&this.stopVUMeter("origin"),this.setupVUMeter(t,"origin"),this.activeStreamValue=t,this.context.emit("changeActiveStream",t)}async setSpeaker(t){if(!this.getOutputDeviceList.find(({deviceId:o})=>o===t))return;this.setSelectedOutputDevice(t);const n=Object.values(this.extendedCalls);if(n.length===0)return;const a=n.filter(o=>o.roomId===this.currentActiveRoomId);a.length===1?n.forEach(o=>{var s;(s=o.audioTag)==null||s.setSinkId(t),this.updateCall(o)}):await this.doConference(a)}removeRoom(t){const n={...this.activeRooms},a={...n[t]};delete n[t],this.activeRooms={...n},this.context.emit("removeRoom",{room:a,roomList:this.activeRooms})}deleteRoomIfEmpty(t){t!==void 0&&Object.values(this.extendedCalls).filter(n=>n.roomId===t).length===0&&(this.removeRoom(t),this.currentActiveRoomId===t&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(t){this.muted?t.mute({audio:!0}):t.unmute({audio:!0})}async roomReconfigure(t){var a;if(t===void 0)return;const n=Object.values(this.extendedCalls).filter(o=>o.roomId===t);if(this.currentActiveRoomId===t?n.forEach(o=>{o.audioTag&&(this.muteReconfigure(o),o.audioTag.muted=!1,this.updateCall(o))}):n.forEach(o=>{o.audioTag&&(o.audioTag.muted=!0,this.updateCall(o))}),n.length===0)this.deleteRoomIfEmpty(t);else if(n.length===1&&this.currentActiveRoomId!==t)n[0].isOnHold().local||await this.holdCall(n[0].id,!0);else if(n.length===1&&this.currentActiveRoomId===t){if(n[0].isOnHold().local&&n[0]._automaticHold&&await this.unholdCall(n[0].id),n[0].connection&&((a=n[0].connection)!=null&&a.getSenders()[0])){const o=this.getActiveStream();await n[0].connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.muteReconfigure(n[0])}}else n.length>1&&await this.doConference(n)}async doConference(t){const n=[];t.forEach(a=>{a!=null&&a.connection.getReceivers().forEach(o=>{n.push(o.track)})}),await pv.forEach(t,async a=>{var r;if(a==null)return;const o=new MediaStream,s=Cn.createMediaStreamDestination();if(a.connection.getReceivers().forEach(d=>{n.forEach(h=>{o.addTrack(d.track),d.track.id!==h.id&&Cn.createMediaStreamSource(new MediaStream([h])).connect(s)})}),t[0].roomId===this.currentActiveRoomId){const d=this.getActiveStream();Cn.createMediaStreamSource(d).connect(s)}(r=a.connection)!=null&&r.getSenders()[0]&&(await a.connection.getSenders()[0].replaceTrack(s.stream.getTracks()[0]),this.muteReconfigure(a))})}processCallerMute(t,n){const a=this.extendedCalls[t];a&&a.connection.getReceivers().length&&(a.localMuted=n,a.connection.getReceivers().forEach(o=>{o.track.enabled=!n}),this.updateCall(a))}muteCaller(t){this.processCallerMute(t,!0)}unmuteCaller(t){this.processCallerMute(t,!1)}terminateCall(t){const n=this.extendedCalls[t];n._status!==8&&n.terminate()}transferCall(t,n){if(n.toString().length===0)return new Error("Target must be passed");const a=this.extendedCalls[t];if(!a._is_confirmed&&!a._is_canceled){const o=`sip:${n}@${this.context.sipDomain}`;a.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${o}`]});return}this.updateCallStatus({callId:t,isTransferring:!0}),a.refer(`sip:${n}@${this.context.sipDomain}`),this.updateCall(a)}mergeCall(t){const n=Object.values(this.extendedCalls).filter(s=>s.roomId===t);if(n.length!==2)return;const a=n[0],o=n[1];!a||!o||(this.updateCallStatus({callId:a._id,isMerging:!0}),this.updateCallStatus({callId:o._id,isMerging:!0}),a.refer(o.remote_identity.uri.toString(),{replaces:o}),this.updateCall(a))}mergeCallByIds(t,n){const a=Object.values(this.extendedCalls).find(s=>s._id===t),o=Object.values(this.extendedCalls).find(s=>s._id===n);if(!a||!o)throw new Error("Call ID is not provided");this.updateCallStatus({callId:t,isMerging:!0}),this.updateCallStatus({callId:n,isMerging:!0}),a.refer(o.remote_identity.uri.toString(),{replaces:o}),this.updateCall(a)}setDND(t){this.isDNDEnabled=t,this.context.emit("changeIsDND",t)}startCallTimer(t){this.removeTimeInterval(t);const n={callId:t,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(n);const a=setInterval(()=>{const o={...this.callTime[t]},s=hv(o);this.setCallTime({callId:t,...s})},1e3);this.setTimeInterval(t,a)}async setActiveRoom(t){const n=this.currentActiveRoomId;t!==n&&(this.currentActiveRoomId=t,await this.roomReconfigure(n),await this.roomReconfigure(t))}getNewRoomId(){const t=Object.keys(this.activeRooms);return t.length===0?1:parseInt(t.sort()[t.length-1])+1}async setupCall(t){var _,g;const n=t.session;if(this.getActiveCalls[n.id]!==void 0)return;const o=this.getNewRoomId(),s={started:new Date,incomingInProgress:!1,roomId:o};n.direction==="incoming"?(this.context.logger.log("New incoming call from",(g=(_=n._remote_identity)==null?void 0:_._uri)==null?void 0:g._user),s.incomingInProgress=!0,this.context.subscribe(Xt.CALL_CONFIRMED,T=>{n.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:o}),this.startCallTimer(n.id))}),this.context.subscribe(Xt.CALL_FAILED,T=>{n.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:o}),this.deleteRoomIfEmpty(o))})):n.direction==="outgoing"&&(n.once("confirmed",()=>{this.startCallTimer(n.id)}),this.startCallTimer(n.id));const r=n,d=this.hasAutoAnswerHeaders(t),h=r.direction==="incoming"&&!this.hasActiveCalls&&(d||this.autoAnswer);r.roomId=o,r.localMuted=!1,r.autoAnswer=h,h?this.addCall(r,!1):this.addCall(r),this.addCallStatus(n.id),this.addRoom(s),h&&this.answerCall(r._id)}removeCall(t){const n={...this.activeCalls};delete n[t],this.activeCalls={...n};const a={...this.extendedCalls};delete a[t],this.extendedCalls={...a},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(t){var o;const n=this.extendedCalls[t._id];this.stopVUMeter("origin"),(o=n.connection)==null||o.getSenders().forEach(s=>{s.track.stop()});const a=n.roomId;this.removeCall(t._id),this.roomReconfigure(a)}async newRTCSessionCallback(t){const n=t.session;if(this.isDND){n.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(this.context.triggerListener({listenerType:Xt.NEW_CALL,session:n,event:t}),n.on("ended",a=>{var s,r,d;this.stopVUMeter(n.id),this.context.logger.log("Session ended for",(r=(s=n._remote_identity)==null?void 0:s._uri)==null?void 0:r._user),this.context.triggerListener({listenerType:Xt.CALL_ENDED,session:n,event:a});const o=this.getActiveCalls[n.id];o&&this.activeCallListRemove(o),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null)}),n.on("progress",a=>{var o,s;this.context.logger.log("Session in progress for",(s=(o=n._remote_identity)==null?void 0:o._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:Xt.CALL_PROGRESS,session:n,event:a})}),n.on("failed",a=>{var s,r,d;this.stopVUMeter(n.id),this.context.logger.log("Session failed for",(r=(s=n._remote_identity)==null?void 0:s._uri)==null?void 0:r._user),this.context.triggerListener({listenerType:Xt.CALL_FAILED,session:n,event:a}),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const o=this.getActiveCalls[n.id];o&&this.activeCallListRemove(o),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null)}),n.on("confirmed",a=>{var o,s;this.context.logger.log("Session confirmed for",(s=(o=n._remote_identity)==null?void 0:o._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:Xt.CALL_CONFIRMED,session:n,event:a}),this.updateCall(n),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(t),n.direction==="outgoing"){const a=this.getActiveCalls[n.id].roomId;this.setActiveRoom(a)}}setMuteWhenJoin(t){this.muteWhenJoinEnabled=t,this.context.emit("changeMuteWhenJoin",t)}setMicrophoneSensitivity(t){if(t<0||t>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=t,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(t){this.speakerVolumeValue=t,Object.values(this.extendedCalls).forEach(n=>{n.audioTag&&(n.audioTag.volume=t,this.updateCall(n))})}setAutoAnswer(t){this.isAutoAnswer=t}setSelectedInputDevice(t){localStorage.setItem(_a.SELECTED_INPUT_DEVICE,t),this.selectedMediaDevices.input=t,this.context.emit("changeActiveInputMediaDevice",t)}setSelectedOutputDevice(t){localStorage.setItem(_a.SELECTED_OUTPUT_DEVICE,t),this.selectedMediaDevices.output=t,this.context.emit("changeActiveOutputMediaDevice",t)}setCallMetrics(t){const n={...t};delete n.callId,this.callMetrics={...this.callMetrics,[t.callId]:n},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(t){const n={...this.callMetrics};delete n[t],this.callMetrics={...n},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(t){const n=new iE(this.metricConfig),a=n.createProbe(t.connection,{cid:t._id}),o=[];let s;a.onreport=r=>{Object.entries(r.audio).forEach(([_,g])=>{g.direction==="inbound"&&!o.includes(_)&&(o.push(_),s=_)});const d=r.audio[s];if(!d)return;const h=lE(d,aE);h.callId=t._id,this.setCallMetrics(h)},this.context.subscribe(Xt.CALL_ENDED,r=>{r._id===t._id&&n.stopAllProbes()}),n.startAllProbes()}setupVUMeter(t,n){this.VUMeter.start(t,n)}stopVUMeter(t){this.VUMeter.stop(t)}async setupStream(){const t=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach(n=>n.stop()),this.initialStreamValue=null),this.initialStreamValue=t}async triggerAddStream(t,n){this.setIsMuted(this.muteWhenJoin||this.isMuted),this.initialStreamValue||await this.setupStream();const a=Pf(this.initialStreamValue,this.microphoneInputLevel*2),o=this.isMuted||this.muteWhenJoin;a.getTracks().forEach(r=>r.enabled=!o),this.setActiveStream(a),await n.connection.getSenders()[0].replaceTrack(a.getTracks()[0]);const s=new MediaStream([t.track]);zT(s,n,this.selectedOutputDevice,this.speakerVolume),this.setupVUMeter(s,n._id),this.getCallQuality(n),this.updateCall(n)}initCall(t,n,a=!1){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`);const o=this.context.call(`sip:${t}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=o.id,n&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:o.id,roomId:this.currentActiveRoomId}),a)){const s=Object.values(this.extendedCalls).filter(r=>r.roomId===this.currentActiveRoomId&&r._id!==o.id);for(const r of s)this.holdCall(r._id,!0)}o.connection.addEventListener("track",s=>{this.triggerAddStream(s,o)})}async processRoomChange({callId:t,roomId:n}){const a=this.extendedCalls[t].roomId;this.extendedCalls[t].roomId=n;const o=this.extendedCalls[t];return this.updateCall(o),await this.setActiveRoom(n),Promise.all([this.roomReconfigure(a),this.roomReconfigure(n)]).then(()=>{this.deleteRoomIfEmpty(a),this.deleteRoomIfEmpty(n)})}}class fE{constructor(t){this.context=t}get sipOptions(){return{...this.context.options.sipOptions}}initCall(t,n){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${t}@${this.context.sipDomain}`,n,this.sipOptions)}stop(t={}){this.context.terminateJanusSessions(t)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(t){this.context.changeMediaConstraints(t)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class hE{constructor(t){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=t,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this.context))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(t){const n=this.extendedMessages[t];this.updateMSRPSession(n)}updateMSRPSession(t){this.activeMessages[t._id]=Uf(t),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(t){this.activeMessages={...this.activeMessages,[t._id]:Uf(t)},this.extendedMessages[t._id]=t,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(t,n){const a=this.msrpHistory[n.id]||[];a.push(t),this.msrpHistory={...this.msrpHistory,[n.id]:[...a]},this.context.emit("newMSRPMessage",{message:t,session:n})}messageTerminate(t){const n=this.extendedMessages[t];n._status!==8&&n.terminate()}addMessageSession(t){if(!t._id||this.getActiveMessages[t._id]!==void 0)return;const a=t;this.addMMSRPSession(a)}triggerMSRPListener({listenerType:t,session:n,event:a}){const o=this.context.listenersList[t];!o||!o.length||o.forEach(s=>{s(n,a)})}removeMMSRPSession(t){const n={...this.activeMessages};delete n[t],this.activeMessages={...n};const a={...this.extendedMessages};delete a[t],this.extendedMessages={...a},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(t){this.removeMMSRPSession(t._id)}newMSRPSessionCallback(t){const n=t.session;n.on("ended",a=>{this.triggerMSRPListener({listenerType:Xt.CALL_ENDED,session:n,event:a});const o=this.getActiveMessages[n.id];this.activeMessageListRemove(o)}),n.on("failed",a=>{this.triggerMSRPListener({listenerType:Xt.CALL_FAILED,session:n,event:a});const o=this.getActiveMessages[n.id];this.activeMessageListRemove(o)}),n.on("confirmed",a=>{this.triggerMSRPListener({listenerType:Xt.CALL_CONFIRMED,session:n,event:a}),this.updateMSRPSession(n)}),n.on("newMessage",a=>{this.addMSRPMessage(a,n)}),this.addMessageSession(n)}setIsMSRPInitializing(t){this.isMSRPInitializingValue=t,this.context.emit("isMSRPInitializingChanged",t)}initMSRP(t,n,a){if(t.length===0)return console.error("Target must be a valid string");const o=this.context.startMSRP(t,a);o.on("active",()=>{this.addMessageSession(o),o.sendMSRP(n),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(t,n){const a=this.extendedMessages[t];if(!a)throw new Error(`MSRP session with id ${t} doesn't exist!`);a.sendMSRP(n)}}const ou={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class kh{constructor(t){this.opensips=null,this.session=null,this.name=null,this.name=t}setOpensips(t){this.opensips=t}setSession(t){this.session=t}kill(){this.opensips.kill(this.name)}}class Mh extends kh{constructor(t,n){super(t),this._candidates=[],this._subscribeSent=!1,this._configureSent=!1,this._lastTrickleReceived=!1,this.type=n}connect(t={}){this.opaqueId=this.session.generateOpaqueId();const n=ke.cloneArray(t.extraHeaders),a={from_tag:this.session._from_tag};t.fromUserName&&(a.from_uri=new In("sip",t.fromUserName,this.session._ua.configuration.uri.host),n.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),t.fromDisplayName&&(a.from_display_name=t.fromDisplayName),n.push(`Contact: ${this.session._contact}`),n.push("Content-Type: application/json"),this.session._sessionTimers.enabled&&n.push(`Session-Expires: ${this.session._sessionTimers.defaultExpires}${this.session._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new yt.InitialOutgoingInviteRequest(this.session.target,this.session._ua,a,n),this._createRTCConnection(),this._sendInitialRequest()}getStream(){return this.stream}getConnection(){return this._connection}_createRTCConnection(){this._connection=new RTCPeerConnection({iceServers:[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}]});let t;this._connection.onicecandidate=n=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||n.candidate&&(this._candidates.push(n.candidate),clearTimeout(t),t=setTimeout(()=>{this._lastTrickleReceived=!0,this._subscribeSent&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})},500))}}addTracks(t){t.forEach(n=>{this._connection.addTrack(n)})}async _sendInitialRequest(){const t=new sl(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});if(await this.generateStream(),!this.stream||!this.stream.getTracks().length)return;this.addTracks(this.stream.getTracks());const n={audio:!1,video:!0};this.jsep_offer=await this._connection.createOffer(n),await this._connection.setLocalDescription(this.jsep_offer);const a={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},o=JSON.stringify(a);this._request.body=o,t.send()}_receiveInviteResponse(t){if(this._publisherSubscribeSent||!t.body)return;const n=JSON.parse(t.body);this.handleId=n.data.id;const a={janus:"message",body:{request:"join",room:this.session.room_id,ptype:"publisher",display:this.session.display_name+" (Screen Share)",opaque_id:this.opaqueId},handle_id:this.handleId},o=[this.session.getPTypeHeader(Pt.PUBLISHER)];this.session.sendRequest(L.SUBSCRIBE,{extraHeaders:o,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async s=>{var r,d,h,_;if(s.status_code===200){if(this._subscribeSent=!0,s.body)try{const g=JSON.parse(s.body)||{};((d=(r=g.plugindata)==null?void 0:r.data)==null?void 0:d.videoroom)==="joined"&&this.session.myFeedList.push(g.plugindata.data.id),(_=(h=g.plugindata)==null?void 0:h.data)!=null&&_.publishers&&this.session.receivePublishers(g)}catch(g){console.error(g)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}}}}),this._publisherSubscribeSent=!0}async _sendConfigureMessage(t){const n=this._candidates.map(r=>({janus:"trickle",candidate:r,handle_id:this.handleId,session_id:this.session.session_id})),o={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.session.getRecordFileName(),...t},jsep:this.jsep_offer,handle_id:this.handleId,session_id:this.session.session_id},trickles:[...n]},s=["Content-Type: application/json",this.session.getPTypeHeader(Pt.ICE)];this.session.sendRequest(L.INFO,{extraHeaders:s,body:JSON.stringify(o),eventHandlers:{onSuccessResponse:async r=>{this._configureSent=!0;const h=r.data.split(`\r
159
- `),_=h[h.length-1],g=JSON.parse(_);await this._connection.setRemoteDescription(g.jsep),this._candidates=[]}}})}_sendDetach(){const t={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},n=[this.session.getPTypeHeader(Pt.DETACH)];this.session.sendRequest(L.INFO,{extraHeaders:n,body:JSON.stringify(t)}),this.session._ua.emit("pluginDetach",this.name)}async stopMedia(){this._connection&&(this._connection.close(),this._connection=null),this.stream&&(this.stream=null)}async stop(){await this.session.stopProcessPlugins(this.type);const t=this._connection.getSenders();t.forEach(n=>{const a=n.track;a&&a.stop()}),t.forEach(n=>{this._connection.removeTrack(n)}),await this.stopMedia(),this._sendDetach()}async generateStream(){throw new Error("generateStream method is not implemented")}}class Lh extends kh{constructor(t,n,a={}){super(t),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=a.immediate||!1,this.type=n}start(t){return t}stop(){throw new Error("stop method is not implemented")}async process(t){if(this.immediate){const n=await this.start(t);return this.running=!0,n}return t}async connect(){this.running=!0,await this.session.resyncPlugins(this.type)}terminate(){this.stop()}async kill(){this.stop(),this.running=!1,await this.session.resyncPlugins(this.type)}}class dE extends VT{constructor(t,n){if(!t.modules.length)throw new Error("options.modules should include at least 1 module");const a={...t.configuration,sockets:t.socketInterfaces.map(o=>new fv.WebSocketInterface(o))};super(a),this.initialized=!1,this.connected=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.activeConnection=!1,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],t.pnExtraHeaders&&Object.keys(t.pnExtraHeaders).length&&this.registrator().setExtraContactUriParams(t.pnExtraHeaders),this.options=t,this.modules=t.modules,n&&XT(n)&&(this.logger=n)}on(t,n){return super.on(t,n)}off(t,n){return super.off(t,n)}emit(t,n){return super.emit(t,n)}get sipDomain(){return this.options.sipDomain}use(t){if(this.newStreamPlugins.find(n=>n.name===t.name)||this.processStreamPlugins.find(n=>n.name===t.name))throw new Error(`Plugin with name ${t.name} already exists`);if(t instanceof Mh)t.setOpensips(this),this.newStreamPlugins.push(t);else if(t instanceof Lh)t.setOpensips(this),this.processStreamPlugins.push(t);else throw new Error("Wrong plugin instance")}getPlugin(t){return this.newStreamPlugins.find(n=>n.name===t)||this.processStreamPlugins.find(n=>n.name===t)}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(ou.AUDIO)&&(this.audio=new cE(this)),this.modules.includes(ou.MSRP)&&(this.msrp=new hE(this)),this.modules.includes(ou.VIDEO)&&(this.video=new fE(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.setConnected(!0),this.isReconnecting=!1,this.activeConnection=!0}),this.on(this.disconnectedEventName,()=>{this.isReconnecting||(this.isReconnecting=!0,this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.stop(),this.setInitialized(!1),this.setConnected(!1),this.activeConnection&&setTimeout(this.start.bind(this),5e3))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}disconnect(){this.activeConnection=!1,this.stop()}subscribe(t,n){const o=!this.listenersList[t]||!this.listenersList[t].length?[n]:[...this.listenersList[t],n];this.listenersList={...this.listenersList,[t]:o}}removeIListener(t){const n={...this.listenersList};delete n[t],this.listenersList={...n}}triggerListener({listenerType:t,session:n,event:a}){const o=this.listenersList[t];!o||!o.length||o.forEach(s=>{s(n,a)})}setInitialized(t){this.initialized=t,this.emit("ready",t)}setConnected(t){this.connected=t,this.emit("connection",t)}}exports.BaseNewStreamPlugin=Mh;exports.BaseProcessStreamPlugin=Lh;exports.default=dE;
159
+ `),_=h[h.length-1],g=JSON.parse(_);await this._connection.setRemoteDescription(g.jsep),this._candidates=[]}}})}_sendDetach(){const t={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},n=[this.session.getPTypeHeader(Pt.DETACH)];this.session.sendRequest(L.INFO,{extraHeaders:n,body:JSON.stringify(t)}),this.session._ua.emit("pluginDetach",this.name)}async stopMedia(){this._connection&&(this._connection.close(),this._connection=null),this.stream&&(this.stream=null)}async stop(){await this.session.stopProcessPlugins(this.type);const t=this._connection.getSenders();t.forEach(n=>{const a=n.track;a&&a.stop()}),t.forEach(n=>{this._connection.removeTrack(n)}),await this.stopMedia(),this._sendDetach()}async generateStream(){throw new Error("generateStream method is not implemented")}}class Lh extends kh{constructor(t,n,a={}){super(t),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=a.immediate||!1,this.type=n}start(t){return t}stop(){throw new Error("stop method is not implemented")}async process(t){if(this.immediate){const n=await this.start(t);return this.running=!0,n}return t}async connect(){this.running=!0,await this.session.resyncPlugins(this.type)}terminate(){this.stop()}async kill(){this.stop(),this.running=!1,await this.session.resyncPlugins(this.type)}}class dE extends VT{constructor(t,n){if(!t.modules.length)throw new Error("options.modules should include at least 1 module");const a={...t.configuration,sockets:t.socketInterfaces.map(o=>new fv.WebSocketInterface(o))};super(a),this.initialized=!1,this.connected=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.activeConnection=!1,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],t.pnExtraHeaders&&Object.keys(t.pnExtraHeaders).length&&this.registrator().setExtraContactUriParams(t.pnExtraHeaders),this.options=t,this.modules=t.modules,n&&XT(n)&&(this.logger=n)}on(t,n){return super.on(t,n)}off(t,n){return super.off(t,n)}emit(t,n){return super.emit(t,n)}get sipDomain(){return this.options.sipDomain}use(t){if(this.newStreamPlugins.find(n=>n.name===t.name)||this.processStreamPlugins.find(n=>n.name===t.name))throw new Error(`Plugin with name ${t.name} already exists`);if(t instanceof Mh)t.setOpensips(this),this.newStreamPlugins.push(t);else if(t instanceof Lh)t.setOpensips(this),this.processStreamPlugins.push(t);else throw new Error("Wrong plugin instance")}getPlugin(t){return this.newStreamPlugins.find(n=>n.name===t)||this.processStreamPlugins.find(n=>n.name===t)}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(ou.AUDIO)&&(this.audio=new cE(this)),this.modules.includes(ou.MSRP)&&(this.msrp=new hE(this)),this.modules.includes(ou.VIDEO)&&(this.video=new fE(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.setConnected(!0),this.setReconnecting(!1),this.activeConnection=!0}),this.on(this.disconnectedEventName,()=>{this.isReconnecting||(this.setReconnecting(!0),this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.stop(),this.setInitialized(!1),this.setConnected(!1),this.activeConnection&&setTimeout(this.start.bind(this),5e3))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}disconnect(){this.activeConnection=!1,this.stop()}subscribe(t,n){const o=!this.listenersList[t]||!this.listenersList[t].length?[n]:[...this.listenersList[t],n];this.listenersList={...this.listenersList,[t]:o}}removeIListener(t){const n={...this.listenersList};delete n[t],this.listenersList={...n}}triggerListener({listenerType:t,session:n,event:a}){const o=this.listenersList[t];!o||!o.length||o.forEach(s=>{s(n,a)})}setInitialized(t){this.initialized=t,this.emit("ready",t)}setConnected(t){this.connected=t,this.emit("connection",t)}setReconnecting(t){this.isReconnecting=t,this.emit("reconnecting",t)}}exports.BaseNewStreamPlugin=Mh;exports.BaseProcessStreamPlugin=Lh;exports.default=dE;
@@ -24615,12 +24615,12 @@ class OE extends jT {
24615
24615
  ), this.on(
24616
24616
  this.connectedEventName,
24617
24617
  () => {
24618
- this.logger.log("Connected to", this.options.socketInterfaces[0]), this.setConnected(!0), this.isReconnecting = !1, this.activeConnection = !0;
24618
+ this.logger.log("Connected to", this.options.socketInterfaces[0]), this.setConnected(!0), this.setReconnecting(!1), this.activeConnection = !0;
24619
24619
  }
24620
24620
  ), this.on(
24621
24621
  this.disconnectedEventName,
24622
24622
  () => {
24623
- this.isReconnecting || (this.isReconnecting = !0, this.logger.log("Disconnected from", this.options.socketInterfaces[0]), this.logger.log("Reconnecting to", this.options.socketInterfaces[0]), this.stop(), this.setInitialized(!1), this.setConnected(!1), this.activeConnection && setTimeout(this.start.bind(this), 5e3));
24623
+ this.isReconnecting || (this.setReconnecting(!0), this.logger.log("Disconnected from", this.options.socketInterfaces[0]), this.logger.log("Reconnecting to", this.options.socketInterfaces[0]), this.stop(), this.setInitialized(!1), this.setConnected(!1), this.activeConnection && setTimeout(this.start.bind(this), 5e3));
24624
24624
  }
24625
24625
  ), this.logger.log("Connecting to", this.options.socketInterfaces[0]), this.start(), this;
24626
24626
  }
@@ -25602,6 +25602,9 @@ class OE extends jT {
25602
25602
  setConnected(t) {
25603
25603
  this.connected = t, this.emit("connection", t);
25604
25604
  }
25605
+ setReconnecting(t) {
25606
+ this.isReconnecting = t, this.emit("reconnecting", t);
25607
+ }
25605
25608
  /*public setMuteWhenJoin (value: boolean) {
25606
25609
  this.muteWhenJoinEnabled = value
25607
25610
  this.emit('changeMuteWhenJoin', value)
@@ -156,4 +156,4 @@ a=path:${t.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 Kr(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:s=>{this.onTransportError(),console.log(s)},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s),s.status_code===200&&(s.parseSDP(!0),this._status=Ce.STATUS_CONFIRMED,this.target_addr=s.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=Ce.STATUS_INVITE_SENT}terminate(t={}){const n=t.cause||L.causes.BYE,a=xe.cloneArray(t.extraHeaders),o=t.body;let s,r=t.status_code,d=t.reason_phrase;if(this._status===Ce.STATUS_TERMINATED)throw new Ns.InvalidStateError(this._status);switch(this.status="terminated",this._status){case Ce.STATUS_NULL:case Ce.STATUS_INVITE_SENT:case Ce.STATUS_1XX_RECEIVED:if(r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);r&&(d=d||L.REASON_PHRASE[r]||"",s=`SIP ;cause=${r} ;text="${d}"`),this._status===Ce.STATUS_NULL||this._status===Ce.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=s):this._status===Ce.STATUS_1XX_RECEIVED&&this._request.cancel(s),this._status=Ce.STATUS_CANCELED,this._failed("local",null,L.causes.CANCELED);break;case Ce.STATUS_WAITING_FOR_ANSWER:case Ce.STATUS_ANSWERED:if(r=r||480,r<300||r>=700)throw new TypeError(`Invalid status_code: ${r}`);this._request.reply(r,d,a,o),this._failed("local",null,L.causes.REJECTED);break;case Ce.STATUS_WAITING_FOR_ACK:case Ce.STATUS_CONFIRMED:if(d=t.reason_phrase||L.REASON_PHRASE[r]||"",r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);if(r&&a.push(`Reason: SIP ;cause=${r}; text="${d}"`),this._status===Ce.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Ht.C.STATUS_TERMINATED){const h=this._dialog;this.receiveRequest=({method:_})=>{_===L.ACK&&(this.sendRequest(L.BYE,{extraHeaders:a,body:o}),h.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Ht.C.STATUS_TERMINATED&&(this.sendRequest(L.BYE,{extraHeaders:a,body:o}),h.terminate())}),this._ended("local",null,n),this._dialog=h,this._ua.newDialog(h)}else this.sendRequest(L.BYE,{extraHeaders:a,body:o}),this._ended("local",null,n)}}sendRequest(t,n){return this._dialog.sendRequest(t,n)}authenticate(t){this.status="auth";let n=new qn("");n.method="AUTH",n.addHeader("To-Path",`msrp://${this._ua._configuration.realm}:2856;ws`),n.addHeader("From-Path",`msrp://${this.credentials.username}.${this.credentials.realm}:2856/${this.auth_id};ws`),t&&n.addHeader("Authorization",t.toString());let a=n.toString(),o=[];for(var s=0;s<a.length;s++)o.push(a.charCodeAt(s).toString(16));this._connection.send(n.toString())}onmessage(t){const n=new qn(t.data);if(this.status==="auth"&&n.code===401){const a=this.parseAuth(n.getHeader("WWW-Authenticate")),o=new Dm(this.credentials);o.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},a,xe.createRandomToken(12)),this.authenticate(o)}this.status==="auth"&&n.code===200&&this._direction==="outgoing"?(this.my_addr.push(n.getHeader("To-Path")),this.my_addr.push(n.getHeader("Use-Path")),this.status="active",this.inviteParty(n)):this.status==="auth"&&n.code===200&&this._direction==="incoming"?(this.my_addr.push(n.getHeader("To-Path")),this.my_addr.push(n.getHeader("Use-Path")),this.status="active",this.acceptParty(n),this.emit("confirmed")):n.method==="SEND"&&(this._sendOk(n),this._sendReport(n),n.direction="incoming",this.emit("newMessage",n),this._msgHistory.push(n),this.emit("msgHistoryUpdate",this._msgHistory)),n.code===480&&this._close()}onclose(){console.log("close")}onopen(){const t=new RTCPeerConnection({iceServers:[]});t.createDataChannel(""),t.createOffer().then(t.setLocalDescription.bind(t)),t.onicecandidate=n=>{if(!n||!n.candidate||!n.candidate.candidate)return;const a=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,o=n.candidate.candidate.match(a);this.my_ip=o&&o[1],t.onicecandidate=()=>{},this.authenticate(null)}}onerror(t){console.log(t)}_receiveInviteResponse(t){if(console.log("resp0000000000000",t),this._dialog&&t.status_code>=200&&t.status_code<=299)if(console.log("200000000000000"),this._dialog.id.call_id===t.call_id&&this._dialog.id.local_tag===t.from_tag&&this._dialog.id.remote_tag===t.to_tag){this.sendRequest(L.ACK);return}else{const n=new ca(this,t,"UAC");if(n.error!==void 0){console.log(n.error);return}this.sendRequest(L.ACK),this.sendRequest(L.BYE);return}if(this._is_canceled){t.status_code>=100&&t.status_code<200?this._request.cancel(this._cancel_reason):t.status_code>=200&&t.status_code<299&&this._acceptAndTerminate(t);return}if(!(this._status!==Ce.STATUS_INVITE_SENT&&this._status!==Ce.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(t.status_code):this._status=Ce.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(t.status_code):{if(!t.to_tag){console.log("1xx response received without to tag");break}if(t.hasHeader("contact")&&!this._createDialog(t,"UAC",!0))break;if(this._status=Ce.STATUS_1XX_RECEIVED,!t.body){this._progress("remote",t);break}const n={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",n);const a=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>this._progress("remote",t)).catch(o=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',o),this.emit("peerconnection:setremotedescriptionfailed",o)});break}case/^2[0-9]{2}$/.test(t.status_code):{if(console.log("maybe here???"),this._status=Ce.STATUS_CONFIRMED,!t.body){this._acceptAndTerminate(t,400,L.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",t,L.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(t,"UAC"))break;const n={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",n),new RTCSessionDescription({type:"answer",sdp:n.sdp}),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(a=>this._connection.setLocalDescription(a)).catch(a=>{this._acceptAndTerminate(t,500,a.toString()),console.log("failed 4"),this._failed("local",t,L.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(t),this._accepted("remote",t),this.sendRequest(L.ACK),this._confirmed("local",null)});break}default:{const n=xe.sipErrorCause(t.status_code);console.log("failed 5"),this._failed("remote",t,n)}}}sendMSRP(t){const n=new qn("");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",xe.createRandomToken(10)),n.addHeader("Byte-Range","1-25/25"),n.addHeader("Content-Type","text/plain"),n.addHeader("Success-Report","yes"),n.addHeader("Failure-Report","yes"),n.body=t;let a=n.toString();console.log(a);let o=[];for(var s=0;s<a.length;s++)o.push(a.charCodeAt(s).toString(16));console.log(o),this._connection.send(n.toString()),n.direction="outgoing",this.emit("newMessage",n),this._msgHistory.push(n),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(t){let n=t.ident,a=t.getHeader("Message-ID"),o=new qn("");o.method="200 OK",o.addHeader("To-Path",`${this.my_addr[1]}`),o.addHeader("From-Path",`${this.my_addr[0]}`),o.addHeader("Message-ID",a),o.ident=n;let s=o.toString();console.log(s);let r=[];for(var d=0;d<s.length;d++)r.push(s.charCodeAt(d).toString(16));console.log(r),this._connection.send(o.toString())}_sendReport(t){let n=t.ident,a=t.getHeader("Message-ID"),o=new qn("");o.method="REPORT",o.addHeader("To-Path",`${t.getHeader("From-Path")}`),o.addHeader("From-Path",`${this.my_addr[0]}`),o.addHeader("Message-ID",a),o.addHeader("Byte-Range","1-25/25"),o.addHeader("Status","000 200 OK"),o.ident=n;let s=o.toString();console.log(s);let r=[];for(var d=0;d<s.length;d++)r.push(s.charCodeAt(d).toString(16));console.log(r),this._connection.send(o.toString())}parseAuth(t){const n={},a=t.replace("Digest","").split(",");for(const o of a){const s=o.trim().split("=");n[s[0]]=s[1].match('^"(.+)"$')[1]}return n}init_incoming(t,n){let a;const o=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;if(t.body&&o!=="application/sdp"){t.reply(415);return}if(this._status=Ce.STATUS_INVITE_RECEIVED,this._from_tag=t.from_tag,this._id=t.call_id+this._from_tag,this._request=t,this._contact=this._ua.contact.toString(),t.hasHeader("expires")&&(a=t.getHeader("expires")*1e3),t.to_tag=xe.newTag(),!this._createDialog(t,"UAS",!0)){t.reply(500,"Missing Contact header field");return}t.body?this._late_sdp=!1:this._late_sdp=!0,this._status=Ce.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{t.reply(408),console.log("failed 6"),this._failed("local",null,L.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),a&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Ce.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),console.log("failed 7"),this._failed("system",null,L.causes.EXPIRES))},a)),this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from,n&&n(this),t.parseSDP(!0),this.target_addr=t.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",t),this._status!==Ce.STATUS_TERMINATED&&(t.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(t,n,a){this.emit("_failed",{originator:t,message:n||null,cause:a}),this._close(),this.emit("failed",{originator:t,message:n||null,cause:a})}_close(){if(console.log("CLOSE SESSION"),this._status!==Ce.STATUS_TERMINATED){if(this._status=Ce.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(t){console.log("close() | error closing the RTCPeerConnection: %o",t)}for(const t in this._timers)Object.prototype.hasOwnProperty.call(this._timers,t)&&clearTimeout(this._timers[t]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const t in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,t)&&(this._earlyDialogs[t].terminate(),delete this._earlyDialogs[t]);for(const t in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,t)&&delete this._referSubscribers[t];this._ua.destroyMSRPSession(this)}}_createDialog(t,n,a){const o=n==="UAS"?t.to_tag:t.from_tag,s=n==="UAS"?t.from_tag:t.to_tag,r=t.call_id+o+s;let d=this._earlyDialogs[r];if(a)return d?!0:(d=new ca(this,t,n,ca.C.STATUS_EARLY),d.error?(console.log("failed 8"),this._failed("remote",t,L.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[r]=d,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,d)return d.update(t,n),this._dialog=d,delete this._earlyDialogs[r],!0;const h=new ca(this,t,n);return h.error?(console.log("failed 9"),this._failed("remote",t,L.causes.INTERNAL_ERROR),!1):(this._dialog=h,!0)}}_newMSRPSession(t,n){this._ua.newMSRPSession(this,{originator:t,session:this,request:n})}_progress(t,n){this.emit("progress",{originator:t,response:n||null})}isEnded(){switch(this._status){case Ce.STATUS_CANCELED:case Ce.STATUS_TERMINATED:return!0;default:return!1}}_accepted(t,n){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:t,response:n||null})}_confirmed(t,n){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:t,ack:n||null})}_ended(t,n,a){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:t,message:n||null,cause:a})}_handleSessionTimersInIncomingResponse(t){if(!this._sessionTimers.enabled)return;let n;t.session_expires&&t.session_expires>=L.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,n=t.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,n="uac"),this._sessionTimers.refresher=n==="uac",this._runSessionTimer()}receiveRequest(t){if(console.log("receiveRequest()"),t.method===L.CANCEL)(this._status===Ce.STATUS_WAITING_FOR_ANSWER||this._status===Ce.STATUS_ANSWERED)&&(this._status=Ce.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",t,L.causes.CANCELED));else switch(t.method){case L.ACK:if(this._status!==Ce.STATUS_WAITING_FOR_ACK)return;if(this._status=Ce.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!t.body){this.terminate({cause:L.causes.MISSING_SDP,status_code:400});break}const n={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",n);const a=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>{this._is_confirmed||this._confirmed("remote",t)}).catch(o=>{this.terminate({cause:L.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',o),this.emit("peerconnection:setremotedescriptionfailed",o)})}else this._is_confirmed||this._confirmed("remote",t);break;case L.BYE:this._status===Ce.STATUS_CONFIRMED||this._status===Ce.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,L.causes.BYE)):this._status===Ce.STATUS_INVITE_RECEIVED||this._status===Ce.STATUS_WAITING_FOR_ANSWER?(t.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",t,L.causes.BYE)):t.reply(403,"Wrong Status");break;case L.INVITE:this._status===Ce.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case L.INFO:this._status===Ce.STATUS_1XX_RECEIVED||this._status===Ce.STATUS_WAITING_FOR_ANSWER||this._status===Ce.STATUS_ANSWERED||this._status===Ce.STATUS_WAITING_FOR_ACK||this._status===Ce.STATUS_CONFIRMED?(t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new nu(this).init_incoming(t):t.reply(415):t.reply(403,"Wrong Status");break;case L.UPDATE:this._status===Ce.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case L.REFER:this._status===Ce.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case L.NOTIFY:this._status===Ce.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:L.causes.CONNECTION_ERROR,cause:L.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:L.causes.REQUEST_TIMEOUT,cause:L.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:L.causes.DIALOG_ERROR,cause:L.causes.DIALOG_ERROR})}}var vT=Yt();const yu=Me(vT),ya=new ra("Parser"),ET=(c,t)=>{let n,a,o=c.indexOf(`\r
157
157
  `);if(o===-1){ya.warn("parseMessage() | no CRLF found, not a SIP message");return}const s=c.substring(0,o);let r=yu.parse(s,"Request_Response");if(r===-1){ya.warn(`parseMessage() | error parsing first line of SIP message: "${s}"`);return}else r.status_code?(n=new $n.IncomingResponse,n.status_code=r.status_code,n.reason_phrase=r.reason_phrase):(n=new $n.IncomingRequest(t),n.method=r.method,n.ruri=r.uri);n.data=c;let d=o+2;for(;;){if(o=ST(c,d),o===-2){a=d+2;break}else if(o===-1){ya.warn("parseMessage() | malformed message");return}if(r=yT(n,c,d,o),r!==!0){ya.warn("parseMessage() |",r.error);return}d=o+2}if(n.hasHeader("content-length")){const h=n.getHeader("content-length");n.body=c.substr(a,h)}else n.body=c.substring(a);return n};function ST(c,t){let n=t,a=0,o=0;if(c.substring(n,n+2).match(/(^\r\n)/))return-2;for(;a===0;){if(o=c.indexOf(`\r
158
158
  `,n),o===-1)return o;!c.substring(o+2,o+4).match(/(^\r\n)/)&&c.charAt(o+2).match(/(^\s+)/)?n=o+2:a=o}return a}function yT(c,t,n,a){let o;const s=t.indexOf(":",n),r=t.substring(n,s).trim(),d=t.substring(s+1,a).trim();switch(r.toLowerCase()){case"via":case"v":c.addHeader("via",d),c.getHeaders("via").length===1?(o=c.parseHeader("Via"),o&&(c.via=o,c.via_branch=o.branch)):o=0;break;case"from":case"f":c.setHeader("from",d),o=c.parseHeader("from"),o&&(c.from=o,c.from_tag=o.getParam("tag"));break;case"to":case"t":c.setHeader("to",d),o=c.parseHeader("to"),o&&(c.to=o,c.to_tag=o.getParam("tag"));break;case"record-route":if(o=yu.parse(d,"Record_Route"),o===-1)o=void 0;else for(const h of o)c.addHeader("record-route",d.substring(h.possition,h.offset)),c.headers["Record-Route"][c.getHeaders("record-route").length-1].parsed=h.parsed;break;case"call-id":case"i":c.setHeader("call-id",d),o=c.parseHeader("call-id"),o&&(c.call_id=d);break;case"contact":case"m":if(o=yu.parse(d,"Contact"),o===-1)o=void 0;else for(const h of o)c.addHeader("contact",d.substring(h.possition,h.offset)),c.headers.Contact[c.getHeaders("contact").length-1].parsed=h.parsed;break;case"content-length":case"l":c.setHeader("content-length",d),o=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",d),o=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",d),o=c.parseHeader("cseq"),o&&(c.cseq=o.value),c instanceof $n.IncomingResponse&&(c.method=o.method);break;case"max-forwards":c.setHeader("max-forwards",d),o=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",d),o=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",d),o=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",d),o=c.parseHeader("session-expires"),o&&(c.session_expires=o.expires,c.session_expires_refresher=o.refresher);break;case"refer-to":case"r":c.setHeader("refer-to",d),o=c.parseHeader("refer-to"),o&&(c.refer_to=o);break;case"replaces":c.setHeader("replaces",d),o=c.parseHeader("replaces"),o&&(c.replaces=o);break;case"event":case"o":c.setHeader("event",d),o=c.parseHeader("event"),o&&(c.event=o);break;default:c.addHeader(r,d),o=0}return o===void 0?{error:`error parsing header "${r}"`}:!0}const AT={parseMessage:ET},ni=new ra("Registrator"),Aa=10;class CT{constructor(t,n){this._reg_id=1,this._ua=t,this._transport=n,this._registrar=t.configuration.registrar_server,this._expires=t.configuration.register_expires,this._call_id=vs.createRandomToken(22),this._cseq=0,this._to_uri=t.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const a=this._contact.indexOf(">");if(a!==-1){const o=this._contact.slice(0,a)+this._contact.slice(a+1,this._contact.length);this._contact=o}this._extra_contact="",this._extraContactParams="",this._extra_contact+=";+sip.ice",this._extraHeaders=[],this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._extra_contact+=`;reg-id=${this._reg_id}`,this._extra_contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(t){Array.isArray(t)||(t=[]),this._extraHeaders=t.slice()}setExtraContactParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const a=t[n];this._extraContactParams+=`;${n}`,a&&(this._extraContactParams+=`=${a}`)}}setExtraContactUriParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const a=t[n];this._extraContactParams+=`;${n}`,a&&(this._extraContactParams+=`=${a}`)}}register(){if(this._registering){ni.debug("Register request in progress...");return}const t=this._extraHeaders.slice();t.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),t.push(`Expires: ${this._expires}`);const n=new Tt.OutgoingRequest(L.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t),a=new Kr(this._ua,n,{onRequestTimeout:()=>{this._registrationFailure(null,L.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,L.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:o=>{if(o.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(o.status_code):break;case/^2[0-9]{2}$/.test(o.status_code):{if(this._registering=!1,!o.hasHeader("Contact")){ni.debug("no Contact header in response to REGISTER, response ignored");break}const s=o.headers.Contact.reduce((_,g)=>_.concat(g.parsed),[]);let r=s.find(_=>this._sipInstance===_.getParam("+sip.instance")&&this._reg_id===parseInt(_.getParam("reg-id")));if(r||(r=s.find(_=>_.uri.user===this._ua.contact.uri.user)),!r){ni.debug("no Contact header pointing to us, response ignored");break}let d=r.getParam("expires");!d&&o.hasHeader("expires")&&(d=o.getHeader("expires")),d||(d=this._expires),d=Number(d),d<Aa&&(d=Aa);const h=d>64?d*1e3/2+Math.floor((d/2-32)*1e3*Math.random()):d*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},h),r.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=r.getParam("temp-gruu").replace(/"/g,"")),r.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=r.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:o}));break}case/^423$/.test(o.status_code):{o.hasHeader("min-expires")?(this._expires=Number(o.getHeader("min-expires")),this._expires<Aa&&(this._expires=Aa),this.register()):(ni.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(o,L.causes.SIP_FAILURE_CODE));break}default:{const s=vs.sipErrorCause(o.status_code);this._registrationFailure(o,s)}}}});this._registering=!0,a.send()}unregister(t={}){if(!this._registered){ni.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const n=this._extraHeaders.slice();t.all?n.push(`Contact: *${this._extraContactParams}`):n.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),n.push("Expires: 0");const a=new Tt.OutgoingRequest(L.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n);new Kr(this._ua,a,{onRequestTimeout:()=>{this._unregistered(null,L.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,L.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:s=>{switch(!0){case/^1[0-9]{2}$/.test(s.status_code):break;case/^2[0-9]{2}$/.test(s.status_code):this._unregistered(s);break;default:{const r=vs.sipErrorCause(s.status_code);this._unregistered(s,r)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(t,n){this._registering=!1,this._ua.registrationFailed({response:t||null,cause:n}),this._registered&&(this._registered=!1,this._ua.unregistered({response:t||null,cause:n}))}_unregistered(t,n){this._registering=!1,this._registered=!1,this._ua.unregistered({response:t||null,cause:n||null})}}const et=console,ks={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},RT=fT;class IT extends RT{constructor(t){super(t),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this.newStreamPlugins=[],this.processStreamPlugins=[],this._registrator=new CT(this)}call(t,n){return super.call(t,n)}joinVideoCall(t,n,a){et.debug("call()");const o=new Sa(this);return o.configureMedia({audio:!0,video:!0}),o.connect(t,n,a),o}startScreenShare(){et.debug("startScreenShare()");for(const t in this._janus_sessions)this._janus_sessions[t].connectScreenShare()}changeMediaConstraints(t){for(const n in this._janus_sessions)this._janus_sessions[n].changeMediaConstraints(t)}startBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].connectBlur()}stopBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].stopBlur()}_loadConfig(t){try{si.load(this._configuration,t)}catch(s){throw s}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=vs.newUUID());let n;typeof window<"u"&&typeof window.document<"u"?n=window==null?void 0:window.navigator.userAgent:typeof self<"u"&&self.navigator&&(n=self.navigator.userAgent),n+=" "+De.USER_AGENT,this._configuration.user_agent=t.overrideUserAgent&&typeof t.overrideUserAgent=="function"?t.overrideUserAgent(n):n,this._configuration.jssip_id=vs.createRandomToken(5);const a=this._configuration.uri.clone();a.user=null,this._configuration.hostport_params=a.toString().replace(/^sip:/i,"");try{this._transport=new Lg(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=bT.bind(this),this._transport.onconnect=wT.bind(this),this._transport.ondisconnect=OT.bind(this),this._transport.ondata=DT.bind(this)}catch(s){throw et.warn(s),new Ns.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const s=this._configuration.uri.clone();s.user=null,s.clearParams(),s.clearHeaders(),this._configuration.registrar_server=s}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new ln("sip",vs.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(s={}){const r=s.anonymous||null,d=s.outbound||null;let h="<";return r?h+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":h+=this.pub_gruu||this.uri.toString(),d&&(r?!this.temp_gruu:!this.pub_gruu)&&(h+=";ob"),h+=">",h}};const o=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const s in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,s)&&(o.indexOf(s)!==-1?Object.defineProperty(this._configuration,s,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,s,{writable:!1,configurable:!1}));et.debug("configuration parameters after validation:");for(const s in this._configuration)if(Object.prototype.hasOwnProperty.call(si.settings,s))switch(s){case"uri":case"registrar_server":et.debug(`- ${s}: ${this._configuration[s]}`);break;case"password":case"ha1":case"authorization_jwt":et.debug(`- ${s}: NOT SHOWN`);break;default:et.debug(`- ${s}: ${JSON.stringify(this._configuration[s])}`)}}newMSRPSession(t,n){t.on("msgHistoryUpdate",a=>{console.log(a)}),this._msrp_sessions[t.id]=t,this.emit("newMSRPSession",n)}newJanusSession(t,n){this._janus_sessions[t.id]=t,this.newStreamPlugins.forEach(a=>{a.setSession(t)}),this.processStreamPlugins.forEach(a=>{a.setSession(t)}),this.emit("newJanusSession",n)}kill(){}destroyMSRPSession(t){delete this._msrp_sessions[t.id]}destroyJanusSession(t){delete this._janus_sessions[t.id]}receiveRequest(t){var s,r,d,h;const n=t.method;if(t.ruri.user!==this._configuration.uri.user&&t.ruri.user!==this._contact.uri.user){et.debug("Request-URI does not point to us"),t.method!==De.ACK&&t.reply_sl(404);return}if(t.ruri.scheme===De.SIPS){t.reply_sl(416);return}if(Ht.checkTransaction(this,t))return;if(n===De.INVITE?new Ht.InviteServerTransaction(this,this._transport,t):n!==De.ACK&&n!==De.CANCEL&&new Ht.NonInviteServerTransaction(this,this._transport,t),n===De.OPTIONS){if(this.listeners("newOptions").length===0){t.reply(200);return}new yf.Options(this).init_incoming(t)}else if(n===De.MESSAGE){if(this.listeners("newMessage").length===0){t.reply(405);return}new yf.Message(this).init_incoming(t)}else if(n===De.INVITE&&!t.to_tag&&this.listeners("newRTCSession").length===0){t.reply(405);return}let a,o;if(t.to_tag)if(a=this._findDialog(t.call_id,t.from_tag,t.to_tag),a)a.receiveRequest(t);else if(n===De.NOTIFY)if(o=this._findSession(t),o)o.receiveRequest(t);else{if(t.body)try{const _=JSON.parse(t.body)||{};(r=(s=_.plugindata)==null?void 0:s.data)!=null&&r.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(_),(h=(d=_.plugindata)==null?void 0:d.data)!=null&&h.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(_.plugindata.data.unpublished)}catch(_){console.error(_)}t.reply(200)}else n!==De.ACK&&t.reply(481);else switch(n){case De.INVITE:if(window.RTCPeerConnection)if(t.hasHeader("replaces")){const _=t.replaces;a=this._findDialog(_.call_id,_.from_tag,_.to_tag),a?(o=a.owner,o.isEnded()?t.reply(603):o.receiveRequest(t)):t.reply(481)}else t.body.search(/MSRP/ig)>-1?(o=new Su(this),o.init_incoming(t)):t.body.search(/JANUS/ig)>-1||(o=new Sg(this),o.init_incoming(t));else et.warn("INVITE received but WebRTC is not supported"),t.reply(488);break;case De.BYE:t.reply(481);break;case De.CANCEL:o=this._findSession(t),o?o.receiveRequest(t):et.debug("received CANCEL request for a non existent session");break;case De.ACK:break;case De.NOTIFY:this.emit("sipEvent",{event:t.event,request:t}),t.reply(200);break;default:t.reply(405);break}}startMSRP(t,n){et.debug("startMSRP()",n);const a=new Su(this);return a.connect(t),a}startJanus(t,n){et.debug("startJanus()",n);const a=new Su(this);return a.connect(t),a}terminateMSRPSessions(t){et.debug("terminateSessions()");for(const n in this._msrp_sessions)this._msrp_sessions[n].isEnded()||this._msrp_sessions[n].terminate(t)}terminateJanusSessions(t){et.debug("terminateSessions()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||this._janus_sessions[n].terminate(t)}enableJanusAudio(t){et.debug("enableJanusAudio()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||(t?this._janus_sessions[n].startAudio():this._janus_sessions[n].stopAudio())}enableJanusVideo(t){et.debug("enableJanusVideo()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||(t?this._janus_sessions[n].startVideo():this._janus_sessions[n].stopVideo())}stop(){if(et.debug("stop()"),this._dynConfiguration={},this._status===ks.STATUS_USER_CLOSED){et.debug("UA already closed");return}this._registrator.close();const t=Object.keys(this._sessions).length;for(const a in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,a)){et.debug(`closing session ${a}`);try{this._sessions[a].terminate()}catch(o){console.error(o)}}for(const a in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,a)){et.debug(`closing session ${a}`);try{this._msrp_sessions[a].terminate()}catch(o){console.error(o)}}for(const a in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,a)){et.debug(`closing session ${a}`);try{this._janus_sessions[a].terminate()}catch(o){console.error(o)}}for(const a in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,a))try{this._applicants[a].close()}catch(o){console.error(o)}this._status=ks.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&t===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function bT(c){this.emit("connecting",c)}function wT(c){this._status!==ks.STATUS_USER_CLOSED&&(this._status=ks.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function OT(c){const t=["nict","ict","nist","ist"];for(const n of t)for(const a in this._transactions[n])Object.prototype.hasOwnProperty.call(this._transactions[n],a)&&this._transactions[n][a].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==ks.STATUS_USER_CLOSED&&(this._status=ks.STATUS_NOT_READY,this._error=ks.NETWORK_ERROR)}function DT(c){const t=c.transport;let n=c.message;if(n=AT.parseMessage(n,this),!!n&&!(this._status===ks.STATUS_USER_CLOSED&&n instanceof $n.IncomingRequest)&&Qg(n,this,t)){if(n instanceof $n.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof $n.IncomingResponse){let a;switch(n.method){case De.INVITE:a=this._transactions.ict[n.via_branch],a&&a.receiveResponse(n);break;case De.ACK:break;default:a=this._transactions.nict[n.via_branch],a&&a.receiveResponse(n);break}}}}const NT=["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"],UT=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function gh(c){const t={};return NT.forEach(n=>{c[n]!==void 0&&(t[n]=c[n])}),t.localHold=c._localHold,t}function Th(c){const t={};return UT.forEach(n=>{c[n]!==void 0&&(t[n]=c[n])}),t}function vh(c,t){const n=new AudioContext,a=n.createMediaStreamSource(c),o=n.createMediaStreamDestination(),s=n.createGain();return a.connect(s),s.connect(o),s.gain.value=t,o.stream}function PT(c,t,n,a){const o=document.createElement("audio");o.id=t._id,o.className="audioTag",o.srcObject=c,Eh()||(o.setSinkId(n),o.volume=a),o.play(),t.audioTag=o}function xT(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}function Eh(){return/Mobi|Android|iPhone/i.test(navigator.userAgent)}const kT=at,MT=Yt(),Ot=new kT("WebSocketInterface");var LT=class{constructor(t){Ot.debug('new() [url:"%s"]',t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;const n=MT.parse(t,"absoluteURI");if(n===-1)throw Ot.warn(`invalid WebSocket URI: ${t}`),new TypeError(`Invalid argument: ${t}`);if(n.scheme!=="wss"&&n.scheme!=="ws")throw Ot.warn(`invalid WebSocket URI scheme: ${n.scheme}`),new TypeError(`Invalid argument: ${t}`);this._sip_uri=`sip:${n.host}${n.port?`:${n.port}`:""};transport=ws`,this._via_transport=n.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(t){this._via_transport=t.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Ot.debug("connect()"),this.isConnected()){Ot.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Ot.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Ot.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(t){this._onError(t)}}disconnect(){Ot.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(t){return Ot.debug("send()"),this.isConnected()?(this._ws.send(t),!0):(Ot.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(){Ot.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:t,code:n,reason:a}){Ot.debug(`WebSocket ${this._url} closed`),t===!1&&Ot.debug("WebSocket abrupt disconnection"),this.ondisconnect(!t,n,a)}_onMessage({data:t}){Ot.debug("received WebSocket message"),this.ondata(t)}_onError(t){Ot.warn(`WebSocket ${this._url} error: `,t)}};const Au=vl,$T=De,HT=Ts,FT=mt(),jT=_h,qT=ps(),VT=Vo(),BT=Yt(),GT=LT;Un("JsSIP")("version %s",Au.version);var WT={C:$T,Exceptions:HT,Utils:FT,UA:jT,URI:qT,NameAddrHeader:VT,WebSocketInterface:GT,Grammar:BT,debug:Un,get name(){return Au.title},get version(){return Au.version}};const KT=Me(WT);function Cu(c){return c<10?`0${c}`:`${c}`}function YT(c){let t=c.hours||0,n=c.minutes||0,a=c.seconds||0;a++,a===60&&(a=0,n++,n===60&&(n=0,t++));const o=`${Cu(t)}:${Cu(n)}:${Cu(a)}`;return{seconds:a,minutes:n,hours:t,formatted:o}}var yt={};yt.forEach=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)if(o in c){const s=Promise.resolve(c[o]).then(r=>t.call(n||globalThis,r,o,c));a.push(s)}await Promise.all(a)},yt.forEachSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)a in c&&await t.call(n||globalThis,await c[a],a,c)},yt.map=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)o in c&&(a[o]=Promise.resolve(c[o]).then(s=>t.call(n||globalThis,s,o,c)));return Promise.all(a)},yt.mapSeries=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)o in c&&(a[o]=await t.call(n||globalThis,await c[o],o,c));return a},yt.find=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a();let s=1;for(let r=0;r<c.length;r++){const d=h=>{h?a(c[r]):s===c.length&&a(),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}}),yt.findSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(await t.call(n||globalThis,await c[a],a,c))return c[a]},yt.findIndex=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a(-1);let s=1;for(let r=0;r<c.length;r++){const d=h=>{h?a(r):s===c.length&&a(-1),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}}),yt.findIndexSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(await t.call(n||globalThis,await c[a],a,c))return a},yt.some=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a(!1);let s=1;for(let r=0;r<c.length;r++){if(!(r in c)){s++;continue}const d=h=>{h?a(!0):s===c.length&&a(!1),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}}),yt.someSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(a in c&&await t.call(n||globalThis,await c[a],a,c))return!0;return!1},yt.every=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a(!0);let s=1;for(let r=0;r<c.length;r++){if(!(r in c)){s++;continue}const d=h=>{h?s===c.length&&a(!0):a(!1),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}}),yt.everySeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(a in c&&!await t.call(n||globalThis,await c[a],a,c))return!1;return!0},yt.filter=(c,t,n)=>new Promise(async(a,o)=>{const s=[];for(let d=0;d<c.length;d++)d in c&&(s[d]=Promise.resolve(c[d]).then(h=>t.call(n||globalThis,h,d,c)).catch(o));const r=[];for(let d=0;d<s.length;d++)await s[d]&&r.push(await c[d]);a(r)}),yt.filterSeries=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)o in c&&await t.call(n||globalThis,await c[o],o,c)&&a.push(await c[o]);return a},yt.reduce=async(c,t,n)=>{if(c.length===0&&n===void 0)throw TypeError("Reduce of empty array with no initial value");let a,o;for(n!==void 0?(o=n,a=0):(o=c[0],a=1),a;a<c.length;a++)a in c&&(o=await t(await o,await c[a],a,c));return o};var Sh={};(function(c){const t=yt;Object.keys(t).forEach(n=>{const a=n.charAt(0).toUpperCase()+n.slice(1);c[`async${a}`]=async function(...o){return t[n](this,...o)}})})(Sh);var JT=Object.assign(yt,{instanceMethods:Sh});const an=new AudioContext,Xt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var zT={exports:{}};(function(c){var t=function(n){var a=Object.prototype,o=a.hasOwnProperty,s=Object.defineProperty||function(ee,Y,G){ee[Y]=G.value},r,d=typeof Symbol=="function"?Symbol:{},h=d.iterator||"@@iterator",_=d.asyncIterator||"@@asyncIterator",g=d.toStringTag||"@@toStringTag";function T(ee,Y,G){return Object.defineProperty(ee,Y,{value:G,enumerable:!0,configurable:!0,writable:!0}),ee[Y]}try{T({},"")}catch{T=function(Y,G,re){return Y[G]=re}}function E(ee,Y,G,re){var ge=Y&&Y.prototype instanceof oe?Y:oe,be=Object.create(ge.prototype),ke=new P(re||[]);return s(be,"_invoke",{value:J(ee,G,ke)}),be}n.wrap=E;function y(ee,Y,G){try{return{type:"normal",arg:ee.call(Y,G)}}catch(re){return{type:"throw",arg:re}}}var A="suspendedStart",C="suspendedYield",I="executing",H="completed",$={};function oe(){}function N(){}function j(){}var Se={};T(Se,h,function(){return this});var ve=Object.getPrototypeOf,k=ve&&ve(ve(se([])));k&&k!==a&&o.call(k,h)&&(Se=k);var D=j.prototype=oe.prototype=Object.create(Se);N.prototype=j,s(D,"constructor",{value:j,configurable:!0}),s(j,"constructor",{value:N,configurable:!0}),N.displayName=T(j,g,"GeneratorFunction");function B(ee){["next","throw","return"].forEach(function(Y){T(ee,Y,function(G){return this._invoke(Y,G)})})}n.isGeneratorFunction=function(ee){var Y=typeof ee=="function"&&ee.constructor;return Y?Y===N||(Y.displayName||Y.name)==="GeneratorFunction":!1},n.mark=function(ee){return Object.setPrototypeOf?Object.setPrototypeOf(ee,j):(ee.__proto__=j,T(ee,g,"GeneratorFunction")),ee.prototype=Object.create(D),ee},n.awrap=function(ee){return{__await:ee}};function V(ee,Y){function G(be,ke,Re,le){var ye=y(ee[be],ee,ke);if(ye.type==="throw")le(ye.arg);else{var lt=ye.arg,ot=lt.value;return ot&&typeof ot=="object"&&o.call(ot,"__await")?Y.resolve(ot.__await).then(function(Ee){G("next",Ee,Re,le)},function(Ee){G("throw",Ee,Re,le)}):Y.resolve(ot).then(function(Ee){lt.value=Ee,Re(lt)},function(Ee){return G("throw",Ee,Re,le)})}}var re;function ge(be,ke){function Re(){return new Y(function(le,ye){G(be,ke,le,ye)})}return re=re?re.then(Re,Re):Re()}s(this,"_invoke",{value:ge})}B(V.prototype),T(V.prototype,_,function(){return this}),n.AsyncIterator=V,n.async=function(ee,Y,G,re,ge){ge===void 0&&(ge=Promise);var be=new V(E(ee,Y,G,re),ge);return n.isGeneratorFunction(Y)?be:be.next().then(function(ke){return ke.done?ke.value:be.next()})};function J(ee,Y,G){var re=A;return function(be,ke){if(re===I)throw new Error("Generator is already running");if(re===H){if(be==="throw")throw ke;return it()}for(G.method=be,G.arg=ke;;){var Re=G.delegate;if(Re){var le=F(Re,G);if(le){if(le===$)continue;return le}}if(G.method==="next")G.sent=G._sent=G.arg;else if(G.method==="throw"){if(re===A)throw re=H,G.arg;G.dispatchException(G.arg)}else G.method==="return"&&G.abrupt("return",G.arg);re=I;var ye=y(ee,Y,G);if(ye.type==="normal"){if(re=G.done?H:C,ye.arg===$)continue;return{value:ye.arg,done:G.done}}else ye.type==="throw"&&(re=H,G.method="throw",G.arg=ye.arg)}}}function F(ee,Y){var G=Y.method,re=ee.iterator[G];if(re===r)return Y.delegate=null,G==="throw"&&ee.iterator.return&&(Y.method="return",Y.arg=r,F(ee,Y),Y.method==="throw")||G!=="return"&&(Y.method="throw",Y.arg=new TypeError("The iterator does not provide a '"+G+"' method")),$;var ge=y(re,ee.iterator,Y.arg);if(ge.type==="throw")return Y.method="throw",Y.arg=ge.arg,Y.delegate=null,$;var be=ge.arg;if(!be)return Y.method="throw",Y.arg=new TypeError("iterator result is not an object"),Y.delegate=null,$;if(be.done)Y[ee.resultName]=be.value,Y.next=ee.nextLoc,Y.method!=="return"&&(Y.method="next",Y.arg=r);else return be;return Y.delegate=null,$}B(D),T(D,g,"Generator"),T(D,h,function(){return this}),T(D,"toString",function(){return"[object Generator]"});function Z(ee){var Y={tryLoc:ee[0]};1 in ee&&(Y.catchLoc=ee[1]),2 in ee&&(Y.finallyLoc=ee[2],Y.afterLoc=ee[3]),this.tryEntries.push(Y)}function U(ee){var Y=ee.completion||{};Y.type="normal",delete Y.arg,ee.completion=Y}function P(ee){this.tryEntries=[{tryLoc:"root"}],ee.forEach(Z,this),this.reset(!0)}n.keys=function(ee){var Y=Object(ee),G=[];for(var re in Y)G.push(re);return G.reverse(),function ge(){for(;G.length;){var be=G.pop();if(be in Y)return ge.value=be,ge.done=!1,ge}return ge.done=!0,ge}};function se(ee){if(ee){var Y=ee[h];if(Y)return Y.call(ee);if(typeof ee.next=="function")return ee;if(!isNaN(ee.length)){var G=-1,re=function ge(){for(;++G<ee.length;)if(o.call(ee,G))return ge.value=ee[G],ge.done=!1,ge;return ge.value=r,ge.done=!0,ge};return re.next=re}}return{next:it}}n.values=se;function it(){return{value:r,done:!0}}return P.prototype={constructor:P,reset:function(ee){if(this.prev=0,this.next=0,this.sent=this._sent=r,this.done=!1,this.delegate=null,this.method="next",this.arg=r,this.tryEntries.forEach(U),!ee)for(var Y in this)Y.charAt(0)==="t"&&o.call(this,Y)&&!isNaN(+Y.slice(1))&&(this[Y]=r)},stop:function(){this.done=!0;var ee=this.tryEntries[0],Y=ee.completion;if(Y.type==="throw")throw Y.arg;return this.rval},dispatchException:function(ee){if(this.done)throw ee;var Y=this;function G(le,ye){return be.type="throw",be.arg=ee,Y.next=le,ye&&(Y.method="next",Y.arg=r),!!ye}for(var re=this.tryEntries.length-1;re>=0;--re){var ge=this.tryEntries[re],be=ge.completion;if(ge.tryLoc==="root")return G("end");if(ge.tryLoc<=this.prev){var ke=o.call(ge,"catchLoc"),Re=o.call(ge,"finallyLoc");if(ke&&Re){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0);if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else if(ke){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0)}else if(Re){if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(ee,Y){for(var G=this.tryEntries.length-1;G>=0;--G){var re=this.tryEntries[G];if(re.tryLoc<=this.prev&&o.call(re,"finallyLoc")&&this.prev<re.finallyLoc){var ge=re;break}}ge&&(ee==="break"||ee==="continue")&&ge.tryLoc<=Y&&Y<=ge.finallyLoc&&(ge=null);var be=ge?ge.completion:{};return be.type=ee,be.arg=Y,ge?(this.method="next",this.next=ge.finallyLoc,$):this.complete(be)},complete:function(ee,Y){if(ee.type==="throw")throw ee.arg;return ee.type==="break"||ee.type==="continue"?this.next=ee.arg:ee.type==="return"?(this.rval=this.arg=ee.arg,this.method="return",this.next="end"):ee.type==="normal"&&Y&&(this.next=Y),$},finish:function(ee){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var G=this.tryEntries[Y];if(G.finallyLoc===ee)return this.complete(G.completion,G.afterLoc),U(G),$}},catch:function(ee){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var G=this.tryEntries[Y];if(G.tryLoc===ee){var re=G.completion;if(re.type==="throw"){var ge=re.arg;U(G)}return ge}}throw new Error("illegal catch attempt")},delegateYield:function(ee,Y,G){return this.delegate={iterator:se(ee),resultName:Y,nextLoc:G},this.method==="next"&&(this.arg=r),$}},n}(c.exports);try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}})(zT);var yh={exports:{}};(function(c){(function(t,n){c.exports?c.exports=n():t.log=n()})(cs,function(){var t=function(){},n="undefined",a=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),o=["trace","debug","info","warn","error"];function s(C,I){var H=C[I];if(typeof H.bind=="function")return H.bind(C);try{return Function.prototype.bind.call(H,C)}catch{return function(){return Function.prototype.apply.apply(H,[C,arguments])}}}function r(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function d(C){return C==="debug"&&(C="log"),typeof console===n?!1:C==="trace"&&a?r:console[C]!==void 0?s(console,C):console.log!==void 0?s(console,"log"):t}function h(C,I){for(var H=0;H<o.length;H++){var $=o[H];this[$]=H<C?t:this.methodFactory($,C,I)}this.log=this.debug}function _(C,I,H){return function(){typeof console!==n&&(h.call(this,I,H),this[C].apply(this,arguments))}}function g(C,I,H){return d(C)||_.apply(this,arguments)}function T(C,I,H){var $=this,oe;I=I??"WARN";var N="loglevel";typeof C=="string"?N+=":"+C:typeof C=="symbol"&&(N=void 0);function j(D){var B=(o[D]||"silent").toUpperCase();if(!(typeof window===n||!N)){try{window.localStorage[N]=B;return}catch{}try{window.document.cookie=encodeURIComponent(N)+"="+B+";"}catch{}}}function Se(){var D;if(!(typeof window===n||!N)){try{D=window.localStorage[N]}catch{}if(typeof D===n)try{var B=window.document.cookie,V=B.indexOf(encodeURIComponent(N)+"=");V!==-1&&(D=/^([^;]+)/.exec(B.slice(V))[1])}catch{}return $.levels[D]===void 0&&(D=void 0),D}}function ve(){if(!(typeof window===n||!N)){try{window.localStorage.removeItem(N);return}catch{}try{window.document.cookie=encodeURIComponent(N)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}$.name=C,$.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},$.methodFactory=H||g,$.getLevel=function(){return oe},$.setLevel=function(D,B){if(typeof D=="string"&&$.levels[D.toUpperCase()]!==void 0&&(D=$.levels[D.toUpperCase()]),typeof D=="number"&&D>=0&&D<=$.levels.SILENT){if(oe=D,B!==!1&&j(D),h.call($,D,C),typeof console===n&&D<$.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+D},$.setDefaultLevel=function(D){I=D,Se()||$.setLevel(D,!1)},$.resetLevel=function(){$.setLevel(I,!1),ve()},$.enableAll=function(D){$.setLevel($.levels.TRACE,D)},$.disableAll=function(D){$.setLevel($.levels.SILENT,D)};var k=Se();k==null&&(k=I),$.setLevel(k,!1)}var E=new T,y={};E.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var H=y[I];return H||(H=y[I]=new T(I,E.getLevel(),E.methodFactory)),H};var A=typeof window!==n?window.log:void 0;return E.noConflict=function(){return typeof window!==n&&window.log===E&&(window.log=A),E},E.getLoggers=function(){return y},E.default=E,E})})(yh);var It=yh.exports;const Es=()=>`${new Date().toISOString()} | metrics`,Ss=(c,t,n)=>`${c} | ${t} | ${n}`;It.setDefaultLevel(It.levels.TRACE);const XT=c=>{It.info(Ss(Es(),"log ",`set log level to ${c?"verbose":"info"}`)),It.setLevel(c?It.levels.TRACE:It.levels.INFO)},QT=c=>{const t=[...Object.keys(It.levels)];t.includes(c)?(It.info(Ss(Es(),"log ",`update log level to ${c.toLowerCase()}`)),It.setLevel(c)):It.warn(Ss(Es(),"log ","Incorrect log level please choose one of "),t)},Pe=(c,t,n)=>{n?It.debug(Ss(Es(),c,t),n):It.debug(Ss(Es(),c,t))},Ru=(c,t)=>{It.info(Ss(Es(),c,t))},on=(c,t)=>{It.info(Ss(Es(),c,t))},Ca=(c,t)=>{It.warn(Ss(Es(),c,t))},Vn=(c,t)=>{It.error(Ss(Es(),c,t))};function ZT(c){return Math.floor(Math.random()*c).toString()}function Ah(c,t){let n=t;return c.forEach(a=>{n=n.replace(a,"")}),n}function ev(c,t){let n="";for(let a=0;a<t;a+=1)n+=c[ZT(c.length)];return n}function tv({length:c=20,useLetters:t=!0,useNumbers:n=!0,includeSymbols:a=[],excludeSymbols:o=[]}={}){let s="abcdefghijklmnopqrstuvwxyz",r="0123456789",d=[],h=[],_=[];return t&&(o.length&&(s=Ah(o,s)),h=s.split("")),n&&(o.length&&(r=Ah(o,r)),_=r.split("")),d=[...h,..._,...a],ev(d,c)}var sv=tv;const ri=Me(sv),nv=()=>"WebRTCMetrics",rv=()=>"5.0.3",$e={INBOUND:"inbound",OUTBOUND:"outbound"},ys={IDLE:"idle",RUNNING:"running",MUTED:"muted"},ii={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},iv=()=>({...{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:[]}}),Ch={level_in:0,codec_id_in:"",codec_in:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,mos_in:0,mos_emodel_in:0,ssrc:"",direction:$e.INBOUND},Rh={level_out:0,codec_id_out:"",codec_out:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,timestamp_out:null,mos_out:0,mos_emodel_out:0,ssrc:"",direction:$e.OUTBOUND},Ih={codec_id_in:"",size_in:{width:null,height:null,framerate:null},codec_in:{mime_type:null,clock_rate:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,decoder_in:null,delta_ms_decode_frame_in:0,total_frames_decoded_in:0,total_time_decoded_in:0,delta_nack_sent_in:0,delta_pli_sent_in:0,total_nack_sent_in:0,total_pli_sent_in:0,ssrc:"",direction:$e.INBOUND},bh={codec_id_out:"",size_out:{width:null,height:null,framerate:null},codec_out:{mime_type:null,clock_rate:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,encoder_out:null,delta_ms_encode_frame_out:0,total_time_encoded_out:0,total_frames_encoded_out:0,delta_nack_received_out:0,delta_pli_received_out:0,total_nack_received_out:0,total_pli_received_out:0,limitation_out:{reason:null,durations:null,resolutionChanges:0},timestamp_out:null,ssrc:"",direction:$e.OUTBOUND},lv=c=>{const t={pname:"",call_id:"",user_id:"",timestamp:null,count:0,audio:{},video:{},network:{infrastructure:3,local_candidate_id:"",local_candidate_type:"",local_candidate_protocol:"",local_candidate_relay_protocol:"",remote_candidate_id:"",remote_candidate_type:"",remote_candidate_protocol:""},data:{total_KBytes_in:0,total_KBytes_out:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,delta_kbs_bandwidth_in:0,delta_kbs_bandwidth_out:0,delta_rtt_connectivity_ms:null,total_rtt_connectivity_ms:0,total_rtt_connectivity_measure:0},experimental:{time_to_measure_ms:0}};if(c){const n={...c,audio:{},video:{},data:{...c.data},network:{...c.network},experimental:{...c.experimental}};return Object.keys(c.audio).forEach(a=>{n.audio[a]={...c.audio[a]}}),Object.keys(c.video).forEach(a=>{n.video[a]={...c.video[a]}}),n}return{...t,audio:{},video:{},data:{...t.data},network:{...t.network},experimental:{...t.experimental}}},av={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${ri()}`,cid:`c-${ri()}`,uid:`u-${ri()}`,record:!1,ticket:!0},Qt={CANDIDATE_PAIR:"candidate-pair",CODEC:"codec",INBOUND_RTP:"inbound-rtp",LOCAL_CANDIDATE:"local-candidate",MEDIA_SOURCE:"media-source",OUTBOUND_RTP:"outbound-rtp",REMOTE_CANDIDATE:"remote-candidate",REMOTE_INBOUND_RTP:"remote-inbound-rtp",TRACK:"track"},q={AUDIO_LEVEL:"audioLevel",AVAILABLE_OUTGOING_BITRATE:"availableOutgoingBitrate",AVAILABLE_INCOMING_BITRATE:"availableIncomingBitrate",BYTES_RECEIVED:"bytesReceived",BYTES_SENT:"bytesSent",CANDIDATE_TYPE:"candidateType",CHANNELS:"channels",CLOCK_RATE:"clockRate",CODEC_ID:"codecId",CURRENT_ROUND_TRIP_TIME:"currentRoundTripTime",ROUND_TRIP_TIME:"roundTripTime",FRACTION_LOST:"fractionLost",FRAME_HEIGHT:"frameHeight",FRAME_WIDTH:"frameWidth",QUALITY_LIMITATION_REASON:"qualityLimitationReason",QUALITY_LIMITATION_DURATIONS:"qualityLimitationDurations",QUALITY_LIMITATION_RESOLUTION_CHANGES:"qualityLimitationResolutionChanges",ID:"id",JITTER:"jitter",KIND:"kind",MEDIA_TYPE:"mediaType",MIME_TYPE:"mimeType",LOCAL_CANDIDATE_ID:"localCandidateId",NETWORK_TYPE:"networkType",RELAY_PROTOCOL:"relayProtocol",NOMINATED:"nominated",PACKETS_LOST:"packetsLost",PACKETS_RECEIVED:"packetsReceived",PACKETS_SENT:"packetsSent",PROTOCOL:"protocol",PORT:"port",REMOTE_CANDIDATE_ID:"remoteCandidateId",REMOTE_SOURCE:"remoteSource",RESPONSES_RECEIVED:"responsesReceived",SDP_FMTP_LINE:"sdpFmtpLine",SSRC:"ssrc",SELECTED:"selected",STATE:"state",TIMESTAMP:"timestamp",TOTAL_ROUND_TRIP_TIME:"totalRoundTripTime",TOTAL_ROUND_TRIP_TIME_MEASUREMENTS:"roundTripTimeMeasurements",TYPE:"type",DECODER_IMPLEMENTATION:"decoderImplementation",ENCODER_IMPLEMENTATION:"encoderImplementation",FRAMES_DECODED:"framesDecoded",FRAMES_ENCODED:"framesEncoded",FRAMES_PER_SECOND:"framesPerSecond",TOTAL_DECODE_TIME:"totalDecodeTime",TOTAL_ENCODE_TIME:"totalEncodeTime",PLI:"pliCount",NACK:"nackCount"},x={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},li={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},Iu={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ne={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},bu="config ",ov=(c,t={},n)=>{const a={...n,...t};return t.pname||Ca(bu,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${n.pname}'`),t.cid||Ca(bu,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${n.cid}'`),t.uid||Ca(bu,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${n.uid}'`),a.pc=c,a},uv=(c={})=>{const t={...av,...c};return t.name=nv(),t.version=rv(),t},ai=(c,t,n,a=!1,o)=>{let s=c.map(r=>{if(!n)return r[t];if(!o)return r[t][n];const d=r[t][o];return d?d[n]:null});return s=s.filter(r=>a?Number.isFinite(r)&&r>0:Number.isFinite(r)),s.length===0?[]:s},Ms=c=>c.reduce((t,n)=>t+n,0)/c.length,cv=()=>`probe-${ri()}`,fv=()=>`coltr-${ri()}`,wh=c=>new Promise(t=>setTimeout(t,c)),wu=(c,t,n)=>{t?c.call(t,n):c(n)},We=(c,t,n,a)=>{const o=ai(c,t,n,!0,a);if(o.length===0)return null;const s=o.reduce((_,g)=>_+g,0)/o.length;return s===0?null:o.map(_=>Math.abs(s-_)).reduce((_,g)=>_+g,0)/o.length*100/s},Xe=(c,t,n,a=!1,o)=>{const s=ai(c,t,n,a,o);return s.length===0?null:s.reduce((r,d)=>r+d,0)/s.length},un=(c,t,n)=>ai(c,t,n).reduce((o,s)=>o+s,0),Ke=(c,t,n,a)=>{const o=ai(c,t,n,!0,a);return o.length===0?null:Math.min(...o)},Ye=(c,t,n,a)=>{const o=ai(c,t,n,!1,a);return o.length===0?null:Math.max(...o)},At=(c,t,n,a)=>{const o=c.slice().pop();if(!o)return null;if(!n)return o[t];if(!a)return o[t][n];const s=o[t][a];return s?s[n]:null},hv=c=>c.slice().pop(),ht=(c,t,n)=>{if(!t)return null;const a={};let o=t[x.AUDIO][c];o||(o=n===$e.INBOUND?{...Ch}:{...Rh}),a[x.AUDIO]=o;let s=t[x.VIDEO][c];return s||(s=n===$e.INBOUND?{...Ih}:{...bh}),a[x.VIDEO]=s,a},oi="exporter ",dv="2.0",Oh=(c,t,n)=>{if(!c||c.length===0)return 0;const a=c[c.length-1];if(!a)return 0;const o=a[t][n];if(o){const s=o.total_rtt_ms_out,r=o.total_rtt_measure_out;return!r||!s?Xe(c,t,"delta_rtt_ms_out",!1,n):Number(s/r)}return null},_v=(c,t)=>{if(!c||c.length===0)return 0;const n=c[c.length-1];if(!n)return 0;const a=n[t].total_rtt_connectivity_ms,o=n[t].total_rtt_connectivity_measure;return!o||!a?Xe(c,t,"delta_rtt_connectivity_ms"):Number(a/o)},pv=c=>At(c,"network","local_candidate_type")!=="relay"?`direct/${At(c,"network","local_candidate_protocol")}`:`turn/${At(c,"network","local_candidate_relay_protocol")}`,mv=c=>{const t=At(c,"network","remote_candidate_type"),n=At(c,"network","remote_candidate_protocol");return t!=="relay"?`direct/${n}`:`turn/${n}`};class gv{constructor(t){this._start=null,this._end=null,this._cfg=t,this._referenceReport=null,this._reports=[],this._events=[]}start(){Ru(oi,"start() - start exporter...");const t=new Date;return this._start=t.toJSON(),t}stop(){Ru(oi,"stop() - stop exporter...");const t=new Date;return this._end=t.toJSON(),t}saveReferenceReport(t){this._referenceReport=t}getReferenceReport(){return this._referenceReport}addReport(t){this._cfg.ticket&&(Pe(oi,`addReport() - add report to exporter at ${t.timestamp}`),this._reports.push(t))}addCustomEvent(t){this._events.push(t)}reset(){Ru(oi,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Pe(oi,"ticket() - generate ticket");const t=At(this._reports,"audio","total_packets_lost_in"),n=At(this._reports,"audio","total_packets_in"),a=At(this._reports,"video","total_packets_lost_in"),o=At(this._reports,"video","total_packets_in"),s={},r=hv(this._reports);return r&&(Object.keys(r[x.AUDIO]).forEach(d=>{const h=r[x.AUDIO][d];if(s[h.ssrc]={type:x.AUDIO,direction:h.direction},h.direction===$e.INBOUND){const _={avg:Xe(this._reports,x.AUDIO,"delta_jitter_ms_in",!1,d),min:Ke(this._reports,x.AUDIO,"delta_jitter_ms_in",d),max:Ye(this._reports,x.AUDIO,"delta_jitter_ms_in",d),volatility:We(this._reports,x.AUDIO,"delta_jitter_ms_in",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.AUDIO,"delta_kbs_in",!1,d),min:Ke(this._reports,x.AUDIO,"delta_kbs_in",d),max:Ye(this._reports,x.AUDIO,"delta_kbs_in",d),volatility:We(this._reports,x.AUDIO,"delta_kbs_in",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.AUDIO,"delta_KBytes_in",!1,d),min:Ke(this._reports,x.AUDIO,"delta_KBytes_in",d),max:Ye(this._reports,x.AUDIO,"delta_KBytes_in",d),volatility:We(this._reports,x.AUDIO,"delta_KBytes_in",d),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={emodel:{avg:Xe(this._reports,x.AUDIO,"mos_emodel_in",!1,d),min:Ke(this._reports,x.AUDIO,"mos_emodel_in",d),max:Ye(this._reports,x.AUDIO,"mos_emodel_in",d),volatility:We(this._reports,x.AUDIO,"mos_emodel_in",d)},effective:{avg:Xe(this._reports,x.AUDIO,"mos_in",!1,d),min:Ke(this._reports,x.AUDIO,"mos_in",d),max:Ye(this._reports,x.AUDIO,"mos_in",d),volatility:We(this._reports,x.AUDIO,"mos_in",d)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},y=At(this._reports,x.AUDIO,"total_packets_lost_in",d),A=At(this._reports,x.AUDIO,"total_packets_in",d),C={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[d].jitter=_,s[d].mos=E,s[d].traffic=T,s[d].bitrate=g,s[d].loss=C}else{const _={avg:Xe(this._reports,x.AUDIO,"delta_jitter_ms_out",!1,d),min:Ke(this._reports,x.AUDIO,"delta_jitter_ms_out",d),max:Ye(this._reports,x.AUDIO,"delta_jitter_ms_out",d),volatility:We(this._reports,x.AUDIO,"delta_jitter_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.AUDIO,"delta_kbs_out",!1,d),min:Ke(this._reports,x.AUDIO,"delta_kbs_out",d),max:Ye(this._reports,x.AUDIO,"delta_kbs_out",d),volatility:We(this._reports,x.AUDIO,"delta_kbs_out",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.AUDIO,"delta_KBytes_out",!1,d),min:Ke(this._reports,x.AUDIO,"delta_KBytes_out",d),max:Ye(this._reports,x.AUDIO,"delta_KBytes_out",d),volatility:We(this._reports,x.AUDIO,"delta_KBytes_out",d),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},E={avg:Oh(this._reports,x.AUDIO,d),min:Ke(this._reports,x.AUDIO,"delta_rtt_ms_out",d),max:Ye(this._reports,x.AUDIO,"delta_rtt_ms_out",d),volatility:We(this._reports,x.AUDIO,"delta_rtt_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=At(this._reports,x.AUDIO,"total_packets_lost_out",d),A=At(this._reports,x.AUDIO,"total_packets_out",d),C={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},I={emodel:{avg:Xe(this._reports,x.AUDIO,"mos_emodel_out",!1,d),min:Ke(this._reports,x.AUDIO,"mos_emodel_out",d),max:Ye(this._reports,x.AUDIO,"mos_emodel_out",d),volatility:We(this._reports,x.AUDIO,"mos_emodel_out",d)},effective:{avg:Xe(this._reports,x.AUDIO,"mos_out",!1,d),min:Ke(this._reports,x.AUDIO,"mos_out",d),max:Ye(this._reports,x.AUDIO,"mos_out",d),volatility:We(this._reports,x.AUDIO,"mos_out",d)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};s[d].jitter=_,s[d].rtt=E,s[d].traffic=T,s[d].bitrate=g,s[d].loss=C,s[d].mos=I}}),Object.keys(r[x.VIDEO]).forEach(d=>{const h=r[x.VIDEO][d];if(s[d]={type:x.VIDEO,direction:h.direction},h.direction===$e.INBOUND){const _={avg:Xe(this._reports,x.VIDEO,"delta_jitter_ms_in",!1,d),min:Ke(this._reports,x.VIDEO,"delta_jitter_ms_in",d),max:Ye(this._reports,x.VIDEO,"delta_jitter_ms_in",d),volatility:We(this._reports,x.VIDEO,"delta_jitter_ms_in",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.VIDEO,"delta_kbs_in",!1,d),min:Ke(this._reports,x.VIDEO,"delta_kbs_in",d),max:Ye(this._reports,x.VIDEO,"delta_kbs_in",d),volatility:We(this._reports,x.VIDEO,"delta_kbs_in",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.VIDEO,"delta_KBytes_in",!1,d),min:Ke(this._reports,x.VIDEO,"delta_KBytes_in",d),max:Ye(this._reports,x.VIDEO,"delta_KBytes_in",d),volatility:We(this._reports,x.VIDEO,"delta_KBytes_in",d),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E=At(this._reports,x.VIDEO,"total_packets_lost_in",d),y=At(this._reports,x.VIDEO,"total_packets_in",d),A={lost:E,avg:Math.round((E/(E+y)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[d].jitter=_,s[d].traffic=T,s[d].bitrate=g,s[d].loss=A}else{const _={avg:Xe(this._reports,x.VIDEO,"delta_jitter_ms_out",!1,d),min:Ke(this._reports,x.VIDEO,"delta_jitter_ms_out",d),max:Ye(this._reports,x.VIDEO,"delta_jitter_ms_out",d),volatility:We(this._reports,x.VIDEO,"delta_jitter_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.VIDEO,"delta_kbs_out",!1,d),min:Ke(this._reports,x.VIDEO,"delta_kbs_out",d),max:Ye(this._reports,x.VIDEO,"delta_kbs_out",d),volatility:We(this._reports,x.VIDEO,"delta_kbs_out",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.VIDEO,"delta_KBytes_out",!1,d),min:Ke(this._reports,x.VIDEO,"delta_KBytes_out",d),max:Ye(this._reports,x.VIDEO,"delta_KBytes_out",d),volatility:We(this._reports,x.VIDEO,"delta_KBytes_out",d),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={avg:Oh(this._reports,x.VIDEO,d),min:Ke(this._reports,x.VIDEO,"delta_rtt_ms_out",d),max:Ye(this._reports,x.VIDEO,"delta_rtt_ms_out",d),volatility:We(this._reports,x.VIDEO,"delta_rtt_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=At(this._reports,x.VIDEO,"total_packets_lost_out",d),A=At(this._reports,x.VIDEO,"total_packets_out",d),C={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[d].jitter=_,s[d].rtt=E,s[d].traffic=T,s[d].bitrate=g,s[d].loss=C}})),{version:dv,configuration:{frequency:this._cfg.refreshEvery},started:this._start,ended:this._end,ua:{agent:navigator.userAgent,pname:this._cfg.pname,user_id:this._cfg.uid},call:{call_id:this._cfg.cid,events:this._events},details:{count:this._reports.length,reports:this._cfg.record?this._reports:[],reference:this._referenceReport||null},ssrc:s,data:{rtt:{avg:_v(this._reports,"data"),min:Ke(this._reports,"data","delta_rtt_connectivity_ms"),max:Ye(this._reports,"data","delta_rtt_connectivity_ms"),volatility:We(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((t/(t+n)*100||0)*100)/100}},video:{in:{avg:Math.round((a/(a+o)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:Xe(this._reports,"data","delta_kbs_in"),min:Ke(this._reports,"data","delta_kbs_in"),max:Ye(this._reports,"data","delta_kbs_in"),volatility:We(this._reports,"data","delta_kbs_in")},out:{avg:Xe(this._reports,"data","delta_kbs_out"),min:Ke(this._reports,"data","delta_kbs_out"),max:Ye(this._reports,"data","delta_kbs_out"),volatility:We(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:Xe(this._reports,"data","delta_KBytes_in"),min:Ke(this._reports,"data","delta_KBytes_in"),max:Ye(this._reports,"data","delta_KBytes_in"),volatility:We(this._reports,"data","delta_KBytes_in")},out:{avg:Xe(this._reports,"data","delta_KBytes_out"),min:Ke(this._reports,"data","delta_KBytes_out"),max:Ye(this._reports,"data","delta_KBytes_out"),volatility:We(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:pv(this._reports),remoteConnection:mv(this._reports)}}}}updateConfig(t){this._cfg=t}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const t=this._reports.slice();return t.pop(),t.pop()||null}getReportsNumber(){return this._reports.length}}const Ls="extractor ",Dh=(c,t,n,a)=>{let o=!1;const s=a[t].total_rtt_ms_out,r=a[t].total_rtt_measure_out,d=n?n[t].total_rtt_ms_out:0,h=n?n[t].total_rtt_measure_out:0,_={rtt:null,totalRTT:s,totalRTTMeasurements:r};if(c[q.TIMESTAMP]===a[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,q.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(o=!0,Number(c[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-h===r))return _;const g=1e3*Number(c[q.ROUND_TRIP_TIME]);let T=s+g,E=r+1;return o&&(T=1e3*Number(c[q.TOTAL_ROUND_TRIP_TIME])-d,E=Number(c[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-h),{rtt:g,totalRTT:T,totalRTTMeasurements:E}},Tv=(c,t,n,a)=>{if(!Object.prototype.hasOwnProperty.call(c,q.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:a[t].total_rtt_connectivity_ms,totalRTTMeasurements:a[t].total_rtt_connectivity_measure};const o=1e3*Number(c[q.CURRENT_ROUND_TRIP_TIME]);let s=a[t].total_rtt_connectivity_ms+o,r=a[t].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,q.TOTAL_ROUND_TRIP_TIME)&&(s=1e3*Number(c[q.TOTAL_ROUND_TRIP_TIME])-(n?n[t].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,q.RESPONSES_RECEIVED)&&(r=Number(c[q.RESPONSES_RECEIVED])-(n?n[t].total_rtt_connectivity_measure:0)),{rtt:o,totalRTT:s,totalRTTMeasurements:r}},Ra=(c,t,n)=>c[q.TIMESTAMP]===n[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,q.JITTER)?null:1e3*(Number(c[q.JITTER])||0),vv=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,q.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,q.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:t[x.VIDEO].delta_ms_decode_frame_in,frames_decoded:t[x.VIDEO].total_frames_decoded_in,total_decode_time:t[x.VIDEO].total_time_decoded_in};const n=c[q.FRAMES_DECODED],a=c[q.TOTAL_DECODE_TIME],o=a-t[x.VIDEO].total_time_decoded_in,s=n-t[x.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:s>0?o*1e3/s:0,frames_decoded:n,total_decode_time:a}},Ev=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,q.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,q.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:t[x.VIDEO].delta_ms_encode_frame_out,frames_encoded:t[x.VIDEO].total_frames_encoded_out,total_encode_time:t[x.VIDEO].total_time_encoded_out};const n=c[q.FRAMES_ENCODED],a=c[q.TOTAL_ENCODE_TIME],o=a-t[x.VIDEO].total_time_encoded_out,s=n-t[x.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:s>0&&o?o*1e3/s:0,frames_encoded:n,total_encode_time:a}},Nh=(c,t,n,a)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,q.BYTES_SENT))return{packetsSent:n[t].total_packets_out,packetsLost:n[t].total_packets_lost_out,bytesSent:n[t].total_KBytes_out};const o=Number(c[q.PACKETS_SENT])||0-(a?a[t].total_packets_out:0),s=o-n[t].total_packets_out,r=Number(c[q.BYTES_SENT])/1024-(a?a[t].total_KBytes_out:0),d=r-n[t].total_KBytes_out,h=c[q.TIMESTAMP]||Date.now(),_=a?a.timestamp:null;let g=n.timestamp;!g&&_&&(g=_);const T=g?h-g:0,E=T>0?d*.008*1024/T*1e3:0;return{packetsSent:o,deltaPacketsSent:s,KBytesSent:r,deltaKBytesSent:d,kbsSent:E}},Uh=(c,t,n,a)=>{let o=n[t].total_packets_lost_out,s=0,r=0;return Object.prototype.hasOwnProperty.call(c,q.PACKETS_LOST)&&(o=Number(c[q.PACKETS_LOST])||0-(a?a[t].total_packets_lost_out:0),s=o-n[t].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,q.FRACTION_LOST)&&(r=Number(100*c[q.FRACTION_LOST])),{packetsLost:o,deltaPacketsLost:s,fractionLost:r}},Ph=(c,t,n,a)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,q.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,q.BYTES_RECEIVED))return{percent_packets_lost:n[t].percent_packets_lost_in,packetsReceived:n[t].total_packets_in,packetsLost:n[t].total_packets_lost_in,bytesReceived:n[t].total_KBytes_in};const o=Number(c[q.PACKETS_RECEIVED])||0-(a?a[t].total_packets_in:0),s=Number(c[q.PACKETS_LOST])||0-(a?a[t].total_packets_lost_in:0),r=s-n[t].total_packets_lost_in,d=o-n[t].total_packets_in,h=o!==n[t].total_packets_in?r*100/(r+d):0,_=Number(c[q.BYTES_RECEIVED])/1024-(a?a[t].total_KBytes_in:0),g=_-n[t].total_KBytes_in,T=c[q.TIMESTAMP]||Date.now(),E=a?a.timestamp:null;let y=n.timestamp;!y&&E&&(y=E);const A=y?T-y:0,C=A>0?g*.008*1024/A*1e3:0;return{percentPacketsLost:h,packetsReceived:o,deltaPacketsReceived:d,packetsLost:s,deltaPacketsLost:r,KBytesReceived:_,deltaKBytesReceived:g,kbsReceived:C}},Sv=c=>c[q.CANDIDATE_TYPE]!=="relay"?"":c[q.RELAY_PROTOCOL]||"",yv=c=>{if(!Object.prototype.hasOwnProperty.call(c,q.NETWORK_TYPE))return li.WIFI;switch(c[q.NETWORK_TYPE]){case Iu.ETHERNET:return li.ETHERNET;case Iu.CELLULAR_4G:return li.CELLULAR_4G;case Iu.WIFI:return li.WIFI;default:return li.CELLULAR}},xh=c=>!Object.prototype.hasOwnProperty.call(c,q.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,q.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[q.FRAME_WIDTH]||null,height:c[q.FRAME_HEIGHT]||null,framerate:c[q.FRAMES_PER_SECOND]},Av=c=>{const t=Object.prototype.hasOwnProperty.call(c,q.QUALITY_LIMITATION_REASON)?c[q.QUALITY_LIMITATION_REASON]:null,n=Object.prototype.hasOwnProperty.call(c,q.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[q.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,a=Object.prototype.hasOwnProperty.call(c,q.QUALITY_LIMITATION_DURATIONS)?c[q.QUALITY_LIMITATION_DURATIONS]:null;return a&&Object.keys(a).forEach(o=>{a[o]>1e3&&(a[o]=Number(a[o]/1e3))}),{reason:t,durations:a,resolutionChanges:n}},Cv=(c,t,n)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PLI)||!Object.prototype.hasOwnProperty.call(c,q.NACK))return{pliCount:t.total_pli_sent_in,nackCount:t.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const a=(c[q.PLI]||0)-(n?n[x.VIDEO].total_pli_sent_in:0),o=(c[q.NACK]||0)-(n?n[x.VIDEO].total_nack_sent_in:0);return{pliCount:a,nackCount:o,deltaPliCount:a-t[x.VIDEO].total_pli_sent_in,deltaNackCount:o-t[x.VIDEO].total_nack_sent_in}},Rv=(c,t,n)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PLI)||!Object.prototype.hasOwnProperty.call(c,q.NACK))return{pliCount:t.total_pli_received_out,nackCount:t.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const a=(c[q.PLI]||0)-(n?n[x.VIDEO].total_pli_received_out:0),o=(c[q.NACK]||0)-(n?n[x.VIDEO].total_nack_received_out:0);return{pliCount:a,nackCount:o,deltaPliCount:a-t[x.VIDEO].total_pli_received_out,deltaNackCount:o-t[x.VIDEO].total_nack_received_out}},Iv=c=>({channels:c[q.CHANNELS]||null,clock_rate:c[q.CLOCK_RATE]||null,mime_type:c[q.MIME_TYPE]||null,sdp_fmtp_line:c[q.SDP_FMTP_LINE]||null}),bv=c=>({clock_rate:c[q.CLOCK_RATE]||null,mime_type:c[q.MIME_TYPE]||null}),wv=(c,t,n)=>{const a=(c[q.BYTES_RECEIVED]||0)/1024-(n?n.data.total_KBytes_in:0),o=(c[q.BYTES_SENT]||0)/1024-(n?n.data.total_KBytes_out:0),s=c[q.TIMESTAMP]||Date.now(),r=a-t.data.total_KBytes_in,d=o-t.data.total_KBytes_out,h=n?n.timestamp:null;let _=t.timestamp;!_&&h&&(_=h);const g=_?s-_:0,T=g>0?r*.008*1024/g*1e3:0,E=g>0?d*.008*1024/g*1e3:0;return{total_KBytes_received:a,total_KBytes_sent:o,delta_KBytes_received:r,delta_KBytes_sent:d,kbs_speed_received:T,kbs_speed_sent:E}},Ov=c=>{const t=c[q.AVAILABLE_INCOMING_BITRATE]/1024||0,n=c[q.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:t,kbs_outgoing_bandwidth:n}},Dv=(c,t,n,a)=>{if(!c)return[];switch(c[q.TYPE]){case Qt.CANDIDATE_PAIR:let o=!1;if(c[q.NOMINATED]&&c[q.STATE]===x.SUCCEEDED&&(o=!0,Pe(Ls,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c),q.SELECTED in c&&!c[q.SELECTED]&&(o=!1)),o){const r=c[q.LOCAL_CANDIDATE_ID],d=c[q.REMOTE_CANDIDATE_ID],h=wv(c,t,a),_=Ov(c),g=Tv(c,"data",a,t);return[{type:ne.NETWORK,value:{local_candidate_id:r}},{type:ne.NETWORK,value:{remote_candidate_id:d}},{type:ne.DATA,value:{total_KBytes_in:h.total_KBytes_received}},{type:ne.DATA,value:{total_KBytes_out:h.total_KBytes_sent}},{type:ne.DATA,value:{delta_KBytes_in:h.delta_KBytes_received}},{type:ne.DATA,value:{delta_KBytes_out:h.delta_KBytes_sent}},{type:ne.DATA,value:{delta_kbs_in:h.kbs_speed_received}},{type:ne.DATA,value:{delta_kbs_out:h.kbs_speed_sent}},{type:ne.DATA,value:{delta_kbs_bandwidth_in:_.kbs_incoming_bandwidth}},{type:ne.DATA,value:{delta_kbs_bandwidth_out:_.kbs_outgoing_bandwidth}},{type:ne.DATA,value:{delta_rtt_connectivity_ms:g.rtt}},{type:ne.DATA,value:{total_rtt_connectivity_ms:g.totalRTT}},{type:ne.DATA,value:{total_rtt_connectivity_measure:g.totalRTTMeasurements}}]}break;case Qt.LOCAL_CANDIDATE:if(c[q.ID]===t.network.local_candidate_id)return[{type:ne.NETWORK,value:{infrastructure:yv(c)}},{type:ne.NETWORK,value:{local_candidate_type:c[q.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{local_candidate_protocol:c[q.PROTOCOL]||""}},{type:ne.NETWORK,value:{local_candidate_relay_protocol:Sv(c)}}];break;case Qt.REMOTE_CANDIDATE:if(c[q.ID]===t.network.remote_candidate_id)return[{type:ne.NETWORK,value:{remote_candidate_type:c[q.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{remote_candidate_protocol:c[q.PROTOCOL]||""}}];break;case Qt.INBOUND_RTP:{Pe(Ls,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const r=c[q.SSRC],d=ht(r,t,$e.INBOUND);d&&(d.timestamp=t.timestamp);const h=ht(r,a,$e.INBOUND);if(h&&(h.timestamp=a.timestamp),c[q.MEDIA_TYPE]===x.AUDIO){const _=Ph(c,x.AUDIO,d,h),g=Ra(c,x.AUDIO,d),T=c[q.CODEC_ID]||"";return[{ssrc:r,type:ne.AUDIO,value:{codec_id_in:T}},{ssrc:r,type:ne.AUDIO,value:{total_packets_in:_.packetsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_in:_.deltaPacketsReceived}},{ssrc:r,type:ne.AUDIO,value:{total_packets_lost_in:_.packetsLost}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_lost_in:_.deltaPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{percent_packets_lost_in:_.percentPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{total_KBytes_in:_.KBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_KBytes_in:_.deltaKBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_kbs_in:_.kbsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_in:g}}]}if(c[q.MEDIA_TYPE]===x.VIDEO){const _=vv(c,d),g=Ph(c,x.VIDEO,d,h),T=Ra(c,x.VIDEO,d),E=c[q.DECODER_IMPLEMENTATION]||null,y=c[q.CODEC_ID]||null,A=xh(c),C=Cv(c,d,h);return[{ssrc:r,type:ne.VIDEO,value:{codec_id_in:y}},{ssrc:r,type:ne.VIDEO,value:{total_packets_in:g.packetsReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_in:g.deltaPacketsReceived}},{ssrc:r,type:ne.VIDEO,value:{total_packets_lost_in:g.packetsLost}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_lost_in:g.deltaPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{percent_packets_lost_in:g.percentPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{total_KBytes_in:g.KBytesReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_KBytes_in:g.deltaKBytesReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_kbs_in:g.kbsReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_jitter_ms_in:T}},{ssrc:r,type:ne.VIDEO,value:{decoder_in:E}},{ssrc:r,type:ne.VIDEO,value:{delta_ms_decode_frame_in:_.delta_ms_decode_frame}},{ssrc:r,type:ne.VIDEO,value:{total_frames_decoded_in:_.frames_decoded}},{ssrc:r,type:ne.VIDEO,value:{total_time_decoded_in:_.total_decode_time}},{ssrc:r,type:ne.VIDEO,value:{total_nack_sent_in:C.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_sent_in:C.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_sent_in:C.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_sent_in:C.deltaPliCount}},{ssrc:r,type:ne.VIDEO,value:{size_in:A}}]}break}case Qt.OUTBOUND_RTP:{Pe(Ls,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const r=c[q.SSRC],d=ht(r,t,$e.OUTBOUND);d&&(d.timestamp=t.timestamp);const h=ht(r,a,$e.OUTBOUND);if(h&&(h.timestamp=a.timestamp),c[q.MEDIA_TYPE]===x.AUDIO){const _=c[q.CODEC_ID]||null,g=Nh(c,x.AUDIO,d,h);return[{ssrc:r,type:ne.AUDIO,value:{codec_id_out:_}},{ssrc:r,type:ne.AUDIO,value:{total_packets_out:g.packetsSent}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_out:g.deltaPacketsSent}},{ssrc:r,type:ne.AUDIO,value:{total_KBytes_out:g.KBytesSent}},{ssrc:r,type:ne.AUDIO,value:{delta_KBytes_out:g.deltaKBytesSent}},{ssrc:r,type:ne.AUDIO,value:{delta_kbs_out:g.kbsSent}}]}if(c[q.MEDIA_TYPE]===x.VIDEO){const _=c[q.ENCODER_IMPLEMENTATION]||null,g=c[q.CODEC_ID]||null,T=Ev(c,d),E=xh(c),y=Av(c),A=Rv(c,d,h),C=Nh(c,x.VIDEO,d,h);return[{ssrc:r,type:ne.VIDEO,value:{codec_id_out:g}},{ssrc:r,type:ne.VIDEO,value:{total_packets_out:C.packetsSent}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_out:C.deltaPacketsSent}},{ssrc:r,type:ne.VIDEO,value:{total_KBytes_out:C.KBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_KBytes_out:C.deltaKBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_kbs_out:C.kbsSent}},{ssrc:r,type:ne.VIDEO,value:{encoder_out:_}},{ssrc:r,type:ne.VIDEO,value:{delta_ms_encode_frame_out:T.delta_ms_encode_frame}},{ssrc:r,type:ne.VIDEO,value:{total_frames_encoded_out:T.frames_encoded}},{ssrc:r,type:ne.VIDEO,value:{total_time_encoded_out:T.total_encode_time}},{ssrc:r,type:ne.VIDEO,value:{total_nack_received_out:A.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_received_out:A.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_received_out:A.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_received_out:A.deltaPliCount}},{ssrc:r,type:ne.VIDEO,value:{size_out:E}},{ssrc:r,type:ne.VIDEO,value:{limitation_out:y}}]}break}case Qt.MEDIA_SOURCE:{Pe(Ls,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);break}case Qt.TRACK:{Pe(Ls,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);break}case Qt.CODEC:const s=[];return Object.keys(t[x.AUDIO]).forEach(r=>{const d=t[x.AUDIO][r];if(d.codec_id_in===c[q.ID]||d.codec_id_out===c[q.ID]){Pe(Ls,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const h=Iv(c);c[q.ID]===d.codec_id_in?s.push({ssrc:d.ssrc,type:ne.AUDIO,value:{codec_in:h}}):s.push({ssrc:d.ssrc,type:ne.AUDIO,value:{codec_out:h}})}}),Object.keys(t[x.VIDEO]).forEach(r=>{const d=t[x.VIDEO][r];if(d.codec_id_in===c[q.ID]||d.codec_id_out===c[q.ID]){Pe(Ls,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const h=bv(c);c[q.ID]===d.codec_id_in?s.push({ssrc:d.ssrc,type:ne.VIDEO,value:{codec_in:h}}):s.push({ssrc:d.ssrc,type:ne.VIDEO,value:{codec_out:h}})}}),s;case Qt.REMOTE_INBOUND_RTP:{Pe(Ls,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const r=c[q.SSRC],d=ht(r,t,$e.OUTBOUND),h=ht(r,a,$e.OUTBOUND);if(c[q.KIND]===x.AUDIO){const _=Dh(c,x.AUDIO,h,d),g=Ra(c,x.AUDIO,d),T=Uh(c,x.AUDIO,d,h);return[{ssrc:r,type:ne.AUDIO,value:{delta_rtt_ms_out:_.rtt}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_ms_out:_.totalRTT}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_measure_out:_.totalRTTMeasurements}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_out:g}},{ssrc:r,type:ne.AUDIO,value:{timestamp_out:c[q.TIMESTAMP]}},{ssrc:r,type:ne.AUDIO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{percent_packets_lost_out:T.fractionLost}}]}if(c[q.KIND]===x.VIDEO){const _=Dh(c,x.VIDEO,h,d),g=Ra(c,x.VIDEO,d),T=Uh(c,x.VIDEO,d,h);return[{ssrc:r,type:ne.VIDEO,value:{delta_rtt_ms_out:_.rtt}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_ms_out:_.totalRTT}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_measure_out:_.totalRTTMeasurements}},{ssrc:r,type:ne.VIDEO,value:{delta_jitter_ms_out:g}},{ssrc:r,type:ne.VIDEO,value:{timestamp_out:c[q.TIMESTAMP]}},{ssrc:r,type:ne.VIDEO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{percent_packets_lost_out:T.fractionLost}}]}break}}return[]},Ia=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),Nv=(c,t=x.AUDIO,n,a,o)=>{const s=ht(o,c,$e.INBOUND),r=ht(o,n,$e.INBOUND),d=ht(o,a,$e.INBOUND),h=[],_=[],g=s[t].percent_packets_lost_in,T=s[t].delta_jitter_ms_in,E=r&&r[t].delta_jitter_ms_in||null,y=d&&d[t].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,C=n&&n.data.delta_rtt_connectivity_ms||null,I=a&&a.data.delta_rtt_connectivity_ms||null;A&&h.push(A),C&&h.push(C),I&&h.push(I),T&&_.push(T),n&&E&&_.push(E),a&&y&&_.push(y);const H=h.length>0?Ms(h):100,$=_.length>0?Ms(_):10,oe=93.2-g,N=.18*oe*oe-27.9*oe+1126.62,j=(H+$)/2,Se=j-177.3<0?0:1,ve=.024*j+.11*(j-177.3)*Se,k=N-ve;return Ia(k)},Uv=(c,t=x.AUDIO,n,a,o)=>{const s=ht(o,c,$e.OUTBOUND),r=ht(o,n,$e.OUTBOUND),d=ht(o,a,$e.OUTBOUND),h=[],_=[],g=s[t].percent_packets_lost_out,T=s[t].delta_rtt_ms_out,E=r&&r[t].delta_rtt_ms_out||null,y=d&&d[t].delta_rtt_ms_out||null,A=s[t].delta_jitter_ms_out,C=r&&r[t].delta_jitter_ms_out||null,I=d&&d[t].delta_jitter_ms_out||null,H=c.data.delta_rtt_connectivity_ms,$=n&&n.data.delta_rtt_connectivity_ms||null,oe=a&&a.data.delta_rtt_connectivity_ms||null;T?h.push(T):H&&h.push(H),E?h.push(E):$&&h.push($),y?h.push(y):oe&&h.push(oe),A&&_.push(A),n&&C&&_.push(C),a&&I&&_.push(I);const N=h.length>0?Ms(h):100,j=_.length>0?Ms(_):10,Se=93.2-g,ve=.18*Se*Se-27.9*Se+1126.62,k=(N+j)/2,D=k-177.3<0?0:1,B=.024*k+.11*(k-177.3)*D,V=ve-B;return Ia(V)},Pv=(c,t=x.AUDIO,n,a,o)=>{const s=ht(o,c,$e.INBOUND),r=ht(o,n,$e.INBOUND),d=ht(o,a,$e.INBOUND),h=[],_=[],g=s[t].percent_packets_lost_in/100,T=s[t].delta_jitter_ms_in,E=r&&r[t].delta_jitter_ms_in||null,y=d&&d[t].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,C=n&&n.data.delta_rtt_connectivity_ms||null,I=a&&a.data.delta_rtt_connectivity_ms||null;A&&h.push(A),C&&h.push(C),I&&h.push(I),T&&_.push(T),r&&E&&_.push(E),d&&y&&_.push(y);const H=h.length>0?Ms(h):100,$=_.length>0?Ms(_):10,oe=0,N=19.8,j=29.7,Se=30,ve=(H+$)/2+Se,k=ve-177.3<0?0:1,D=.024*ve+.11*(ve-177.3)*k,V=93.2-(oe+N*Math.log(1+j*g)+D);return Ia(V)},xv=(c,t=x.AUDIO,n,a,o)=>{const s=ht(o,c,$e.OUTBOUND),r=ht(o,n,$e.OUTBOUND),d=ht(o,a,$e.OUTBOUND),h=[],_=[],g=s[t].percent_packets_lost_out/100,T=s[t].delta_rtt_ms_out,E=r&&r[t].delta_rtt_ms_out||null,y=d&&d[t].delta_rtt_ms_out||null,A=s[t].delta_jitter_ms_out,C=r&&r[t].delta_jitter_ms_out||null,I=d&&d[t].delta_jitter_ms_out||null,H=c.data.delta_rtt_connectivity_ms,$=n&&n.data.delta_rtt_connectivity_ms||null,oe=a&&a.data.delta_rtt_connectivity_ms||null;T?h.push(T):H&&h.push(H),E?h.push(E):$&&h.push($),y?h.push(y):oe&&h.push(oe),A&&_.push(A),r&&C&&_.push(C),d&&I&&_.push(I);const N=h.length>0?Ms(h):100,j=_.length>0?Ms(_):10,Se=0,ve=19.8,k=29.7,D=30,B=(N+j)/2+D,V=B-177.3<0?0:1,J=.024*B+.11*(B-177.3)*V,Z=93.2-(Se+ve*Math.log(1+k*g)+J);return Ia(Z)};class kv{constructor(t,n){this._callbacks={onreport:null,onticket:null},this._id=fv(),this._moduleName=this._id,this._probeId=n,this._config=t,this._exporter=new gv(t),this._state=ys.IDLE,this.registerToPCEvents(),on(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(t,n,a,o){const s=(h,_)=>h===x.AUDIO?_===Qt.INBOUND_RTP?{...Ch}:{...Rh}:_===Qt.INBOUND_RTP?{...Ih}:{...bh},r=lv(n);r.pname=this._config.pname,r.call_id=this._config.cid,r.user_id=this._config.uid,r.count=n?n.count+1:1;let d=null;return t.forEach(h=>{!d&&h.timestamp&&(d=h.timestamp),Dv(h,r,r.pname,o).forEach(g=>{if(g.value&&g.type)if(g.ssrc){let T=r[g.type][g.ssrc];T||(T=s(g.type,h.type),T.ssrc=g.ssrc,r[g.type][g.ssrc]=T),Object.keys(g.value).forEach(E=>{T[E]=g.value[E]})}else Object.keys(g.value).forEach(T=>{r[g.type][T]=g.value[T]})})}),r.timestamp=d,Object.keys(r[x.AUDIO]).forEach(h=>{const _=r[x.AUDIO][h];_.direction===$e.INBOUND?(_.mos_emodel_in=Nv(r,x.AUDIO,n,a,_.ssrc),_.mos_in=Pv(r,x.AUDIO,n,a,_.ssrc)):(_.mos_emodel_out=Uv(r,x.AUDIO,n,a,_.ssrc),_.mos_out=xv(r,x.AUDIO,n,a,_.ssrc))}),r}async takeReferenceStats(){return new Promise((t,n)=>{const a=Date.now();setTimeout(async()=>{try{const o=Date.now()-a,s=Date.now(),r=await this._config.pc.getStats(),d=this.analyze(r,null,null,null),h=Date.now();d.experimental.time_to_measure_ms=h-s,d.experimental.time_to_wait_ms=o,this._exporter.saveReferenceReport(d),Pe(this._moduleName,`got reference report for probe ${this._probeId}`),t()}catch(o){n(o)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==ys.RUNNING||!this._config.pc)return Pe(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const t=Date.now(),n=await this._config.pc.getStats(),a=this.analyze(n,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),o=Date.now();return a.experimental.time_to_measure_ms=o-t,this._exporter.addReport(a),Pe(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(a),a}catch(t){return Vn(this._moduleName,`got error ${t}`),null}}async start(){Pe(this._moduleName,"starting"),this.state=ys.RUNNING,this._startedTime=this._exporter.start(),Pe(this._moduleName,"started")}async mute(){this.state=ys.MUTED,Pe(this._moduleName,"muted")}async unmute(){this.state=ys.RUNNING,Pe(this._moduleName,"unmuted")}async stop(t){if(Pe(this._moduleName,`stopping${t?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=ys.IDLE,this._config.ticket){const{ticket:n}=this._exporter;this.fireOnTicket(n)}this._exporter.reset(),Pe(this._moduleName,"stopped")}registerCallback(t,n,a){t in this._callbacks?(this._callbacks[t]={callback:n,context:a},Pe(this._moduleName,`registered callback '${t}'`)):Vn(this._moduleName,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],Pe(this._moduleName,`unregistered callback '${t}'`)):Vn(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReport(t){this._callbacks.onreport&&wu(this._callbacks.onreport.callback,this._callbacks.onreport.context,t)}fireOnTicket(t){this._callbacks.onticket&&wu(this._callbacks.onticket.callback,this._callbacks.onticket.context,t)}updateConfig(t){this._config=t,this._exporter.updateConfig(t)}get state(){return this._state}set state(t){this._state=t,Pe(this._moduleName,`state changed to ${t}`)}addCustomEvent(t,n,a,o){this._exporter.addCustomEvent({at:typeof t=="object"?t.toJSON():t,category:n,name:a,description:o})}async registerToPCEvents(){const{pc:t}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const n=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${n.length} devices found`,"Media Devices state")}catch{Vn(this._moduleName,"can't get devices")}},t){t.oniceconnectionstatechange=()=>{const a=t.iceConnectionState;a===ii.CONNECTED||a===ii.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===ii.DISCONNECTED||a===ii.FAILED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===ii.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},t.onicegatheringstatechange=()=>{const a=t.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",a,"ICE gathering state")},t.ontrack=a=>{this.addCustomEvent(new Date().toJSON(),"call",`${a.track.kind}track`,"MediaStreamTrack received")},t.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const n=t.getReceivers();if(n&&n.length>0){const a=n[0],{transport:o}=a;if(o){const{iceTransport:s}=o;s&&(s.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class Mv{constructor(t){this._id=t.pname&&t.pname.substr(0,12).padEnd(12," ")||cv(),this._moduleName=this._id,on(this._moduleName,"probe created"),this._config=t,this._collector=new kv(this._config,this._id)}set onreport(t){t?this._collector.registerCallback("onreport",t):this._collector.unregisterCallback("onreport")}set onticket(t){t?this._collector.registerCallback("onticket",t):this._collector.unregisterCallback("onticket")}get id(){return this._id}get pname(){return this._config.pname}get cid(){return this._config.cid}get uid(){return this._config.uid}get state(){return this._collector.state}set state(t){this._collector.state=t}addCustomEvent(t,n,a,o=new Date().toJSON()){this._collector.addCustomEvent(o,n,t,a)}get isRunning(){return this._collector.state===ys.RUNNING}get isIdle(){return this._collector.state===ys.IDLE}updateUserId(t){this._config.uid=t,this._collector.updateConfig(this._config)}updateCallId(t){this._config.cid=t,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){Ca(this._moduleName,"probe is already running");return}this._collector.start()}stop(t=!1){this.isRunning&&this._collector.stop(t)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const bt="engine ";class Lv{constructor(t){this._config=t,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},on(bt,`configured for probing every ${this._config.refreshEvery}ms`),on(bt,`configured for starting after ${this._config.startAfter}ms`),on(bt,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Pe(bt,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(t=>t.isRunning)}get isIdle(){return this._probes.every(t=>t.isIdle)}addNewProbe(t,n){if(!t)throw new Error("undefined peer connection");const a=ov(t,n,this._config),o=new Mv(a);return this._probes.push(o),Pe(bt,`${this._probes.length} probes registered`),o}removeExistingProbe(t){if(!t)throw new Error("undefined probe");t.state===ys.RUNNING&&t.stop(),this._probes=this._probes.filter(n=>t.id!==n.id)}async start(){const t=()=>{this._probes.forEach(s=>s.start())},n=async()=>Promise.all(this._probes.map(s=>s.takeReferenceStats())),a=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,o=async()=>{const s=iv(),r=this._probes.filter(d=>d.isRunning);for(const d of r){const h=await d.collectStats();h&&s.probes.push(h),Pe(bt,`got probe ${d.id}`),await wh(0)}return s.delta_time_to_measure_probes_ms=un(s.probes,"experimental","time_to_measure_ms"),s.delta_KBytes_in=un(s.probes,"data","delta_KBytes_in"),s.delta_KBytes_out=un(s.probes,"data","delta_KBytes_out"),s.delta_kbs_in=un(s.probes,"data","delta_kbs_in"),s.delta_kbs_out=un(s.probes,"data","delta_kbs_out"),s.total_time_decoded_in=un(s.probes,"video","total_time_decoded_in"),s.total_time_encoded_out=un(s.probes,"video","total_time_encoded_out"),s};for(Pe(bt,"starting to collect"),t(),Pe(bt,"generating reference reports..."),await n(),Pe(bt,"reference reports generated"),this._startedTime=Date.now();a();)if(Pe(bt,`wait ${this._config.refreshEvery}ms before collecting`),await wh(this._config.refreshEvery),a()){Pe(bt,"collecting...");const s=Date.now(),r=await o(),d=Date.now();r.delta_time_consumed_to_measure_ms=d-s,this.fireOnReports(r),Pe(bt,"collected")}Pe(bt,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(t){const n=a=>{this._probes.forEach(o=>{o.stop(a)})};on(bt,"stop collecting"),n(t)}registerCallback(t,n,a){t in this._callbacks?(this._callbacks[t]={callback:n,context:a},Pe(bt,`registered callback '${t}'`)):Vn(bt,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],Pe(this._moduleName,`unregistered callback '${t}'`)):Vn(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReports(t){this._callbacks.onresult&&t.probes.length>0&&wu(this._callbacks.onresult.callback,this._callbacks.onresult.context,t)}}const $v="interface ";class Hv{constructor(t){this._config=uv(t),on($v,`welcome to ${this._config.name} version ${this._config.version}`),XT(this._config.verbose||!1),this._engine=new Lv(this._config)}setupLogLevel(t){QT(t)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(t,n){return this._engine.addNewProbe(t,n)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(t){this._engine.removeExistingProbe(t)}set onresult(t){t?this._engine.registerCallback("onresult",t):this._engine.unregisterCallback("onresult")}}function Fv(c,t){return Object.keys(c).filter(n=>t.includes(n)).reduce((n,a)=>{const o=a;return{...n,[o]:c[o]}},{})}const jv=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"];class qv{constructor(t){this.intervals={},this.emitInterval=t.emitInterval||200,this.onChangeFunction=t.onChangeFunction}start(t,n){t&&t.getTracks().length&&requestAnimationFrame(()=>this.beginCalculation(t,n))}stop(t){this.clearVolumeInterval(t)}clearVolumeInterval(t){clearInterval(this.intervals[t]),delete this.intervals[t]}clearAllIntervals(){Object.keys(this.intervals).forEach(t=>{clearInterval(this.intervals[t])}),this.intervals={}}beginCalculation(t,n){this.clearVolumeInterval(n);const a=an.createAnalyser(),o=an.createMediaStreamSource(t),s=an.createScriptProcessor(2048,1,1);a.smoothingTimeConstant=.8,a.fftSize=1024,o.connect(a),a.connect(s),s.connect(an.destination),this.intervals[n]=setInterval(()=>{const r=new Uint8Array(a.frequencyBinCount);a.getByteFrequencyData(r);let d=0;const h=r.length;for(let g=0;g<h;g++)d+=r[g];const _=d/h;this.onChangeFunction(n,_)},this.emitInterval)}}const ba={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},Vv=0;class Bv{constructor(t){this.isAutoAnswer=!1,this.muteWhenJoinEnabled=!1,this.isDNDEnabled=!1,this.muted=!1,this.microphoneInputLevelValue=1,this.speakerVolumeValue=1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.availableMediaDevices=[],this.selectedMediaDevices={input:"default",output:"default"},this.callStatus={},this.callTime={},this.callMetrics={},this.timeIntervals={},this.metricConfig={refreshEvery:1e3},this.activeStreamValue=null,this.initialStreamValue=null,this.context=t,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new qv({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices()}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(t){this.currentActiveRoomIdValue=t,this.context.emit("currentActiveRoomChanged",t)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(t){this.isCallAddingInProgress=t,this.context.emit("callAddingInProgressChanged",t)}get muteWhenJoin(){return this.muteWhenJoinEnabled}get isDND(){return this.isDNDEnabled}get speakerVolume(){return this.speakerVolumeValue}get microphoneInputLevel(){return this.microphoneInputLevelValue}get getActiveCalls(){return this.activeCalls}get hasActiveCalls(){return Object.values(this.extendedCalls).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audiooutput")}get getUserMediaConstraints(){return Eh()?{video:!1,audio:!0}:{audio:{deviceId:{exact:this.selectedMediaDevices.input}},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(t){this.availableMediaDevices=t,this.context.emit("changeAvailableDeviceList",t)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const t=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(t)}async initializeMediaDevices(){const t=localStorage.getItem(ba.SELECTED_INPUT_DEVICE)||"default",n=localStorage.getItem(ba.SELECTED_OUTPUT_DEVICE)||"default";try{const a=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),o=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(o),await this.setMicrophone(t),await this.setSpeaker(n),navigator.mediaDevices.addEventListener("devicechange",async()=>{const s=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(s)}),a.getTracks().forEach(s=>s.stop())}catch(a){console.error(a)}}setCallTime(t){const n={...t};delete n.callId,this.callTime={...this.callTime,[t.callId]:n},this.context.emit("changeCallTime",this.callTime)}removeCallTime(t){const n={...this.callTime};delete n[t],this.callTime={...n},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(t,n){this.timeIntervals={...this.timeIntervals,[t]:n}}removeTimeInterval(t){const n={...this.timeIntervals};n[t]&&(clearInterval(n[t]),delete n[t],this.timeIntervals={...n})}stopCallTimer(t){this.removeTimeInterval(t),this.removeCallTime(t)}emitVolumeChange(t,n){this.context.emit("changeCallVolume",{callId:t,volume:n})}setMetricsConfig(t){this.metricConfig={...this.metricConfig,...t}}sendDTMF(t,n){if(!/^[A-D0-9]+$/g.test(n))throw new Error("Not allowed character in DTMF input");this.extendedCalls[t].sendDTMF(n)}setIsMuted(t){this.muted=t,this.context.emit("changeIsMuted",t)}processMute(t){const n=this.currentActiveRoomId;this.setIsMuted(t),this.initialStreamValue.getTracks().forEach(a=>a.enabled=!t),this.roomReconfigure(n)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:t,toHold:n,automatic:a}){const o=this.extendedCalls[t];o._automaticHold=a??!1,await new Promise(d=>{const h=()=>{o.putOnHoldTimestamp=n?Date.now():void 0,d()};n?o.hold({},h):o.unhold({},h)}),this.updateCall(o);const r=Object.values(this.extendedCalls).filter(d=>d.roomId===this.currentActiveRoomId&&(n?t!==d._id:!0));r.length>1&&await this.doConference(r)}holdCall(t,n=!1){return this.processHold({callId:t,automatic:n,toHold:!0})}unholdCall(t){return this.processHold({callId:t,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(t=>t.direction==="outgoing"&&t.status===Vv).forEach(t=>this.terminateCall(t._id))}answerCall(t){const n=this.extendedCalls[t];this.cancelAllOutgoingUnanswered(),n.answer(this.sipOptions),this.updateCall(n),this.setActiveRoom(n.roomId),n.connection.addEventListener("track",a=>{this.triggerAddStream(a,n)})}async moveCall(t,n){this.updateCallStatus({callId:t,isMoving:!0}),await this.processRoomChange({callId:t,roomId:n}),this.updateCallStatus({callId:t,isMoving:!1})}updateCall(t){this.activeCalls[t._id]=gh(t),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(t){const a={...this.activeRooms[t.roomId],...t};this.activeRooms={...this.activeRooms,[t.roomId]:{...a}},this.context.emit("updateRoom",{room:a,roomList:this.activeRooms})}hasAutoAnswerHeaders(t){const n=/answer-after=0/,o=t.request.getHeader("Call-Info");return o&&n.test(o)}addCall(t,n=!0){this.activeCalls={...this.activeCalls,[t._id]:gh(t)},this.extendedCalls[t._id]=t,n&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(t){this.callStatus={...this.callStatus,[t]:{isMoving:!1,isTransferring:!1,isMerging:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(t){const a={...{...this.callStatus[t.callId]}};t.isMoving!==void 0&&(a.isMoving=t.isMoving),t.isTransferring!==void 0&&(a.isTransferring=t.isTransferring),t.isMerging!==void 0&&(a.isMerging=t.isMerging),this.callStatus={...this.callStatus,[t.callId]:{...a}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(t){const n={...this.callStatus};delete n[t],this.callStatus={...n},this.context.emit("changeCallStatus",this.callStatus)}addRoom(t){this.activeRooms={...this.activeRooms,[t.roomId]:t},this.context.emit("addRoom",{room:t,roomList:this.activeRooms})}getActiveStream(){const t=vh(this.initialStreamValue,this.microphoneInputLevel*2);return t.getTracks().forEach(n=>n.enabled=!this.isMuted),this.setActiveStream(t),t}async setMicrophone(t){if(!this.getInputDeviceList.find(({deviceId:a})=>a===t)||(this.setSelectedInputDevice(t),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const n=Object.values(this.extendedCalls).filter(a=>a.roomId===this.currentActiveRoomId);n.length===1?Object.values(n).forEach(async a=>{const o=this.getActiveStream();a.connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.updateCall(a)}):await this.doConference(n)}setActiveStream(t){this.activeStream&&this.stopVUMeter("origin"),this.setupVUMeter(t,"origin"),this.activeStreamValue=t,this.context.emit("changeActiveStream",t)}async setSpeaker(t){if(!this.getOutputDeviceList.find(({deviceId:o})=>o===t))return;this.setSelectedOutputDevice(t);const n=Object.values(this.extendedCalls);if(n.length===0)return;const a=n.filter(o=>o.roomId===this.currentActiveRoomId);a.length===1?n.forEach(o=>{var s;(s=o.audioTag)==null||s.setSinkId(t),this.updateCall(o)}):await this.doConference(a)}removeRoom(t){const n={...this.activeRooms},a={...n[t]};delete n[t],this.activeRooms={...n},this.context.emit("removeRoom",{room:a,roomList:this.activeRooms})}deleteRoomIfEmpty(t){t!==void 0&&Object.values(this.extendedCalls).filter(n=>n.roomId===t).length===0&&(this.removeRoom(t),this.currentActiveRoomId===t&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(t){this.muted?t.mute({audio:!0}):t.unmute({audio:!0})}async roomReconfigure(t){var a;if(t===void 0)return;const n=Object.values(this.extendedCalls).filter(o=>o.roomId===t);if(this.currentActiveRoomId===t?n.forEach(o=>{o.audioTag&&(this.muteReconfigure(o),o.audioTag.muted=!1,this.updateCall(o))}):n.forEach(o=>{o.audioTag&&(o.audioTag.muted=!0,this.updateCall(o))}),n.length===0)this.deleteRoomIfEmpty(t);else if(n.length===1&&this.currentActiveRoomId!==t)n[0].isOnHold().local||await this.holdCall(n[0].id,!0);else if(n.length===1&&this.currentActiveRoomId===t){if(n[0].isOnHold().local&&n[0]._automaticHold&&await this.unholdCall(n[0].id),n[0].connection&&((a=n[0].connection)!=null&&a.getSenders()[0])){const o=this.getActiveStream();await n[0].connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.muteReconfigure(n[0])}}else n.length>1&&await this.doConference(n)}async doConference(t){const n=[];t.forEach(a=>{a!=null&&a.connection.getReceivers().forEach(o=>{n.push(o.track)})}),await JT.forEach(t,async a=>{var r;if(a==null)return;const o=new MediaStream,s=an.createMediaStreamDestination();if(a.connection.getReceivers().forEach(d=>{n.forEach(h=>{o.addTrack(d.track),d.track.id!==h.id&&an.createMediaStreamSource(new MediaStream([h])).connect(s)})}),t[0].roomId===this.currentActiveRoomId){const d=this.getActiveStream();an.createMediaStreamSource(d).connect(s)}(r=a.connection)!=null&&r.getSenders()[0]&&(await a.connection.getSenders()[0].replaceTrack(s.stream.getTracks()[0]),this.muteReconfigure(a))})}processCallerMute(t,n){const a=this.extendedCalls[t];a&&a.connection.getReceivers().length&&(a.localMuted=n,a.connection.getReceivers().forEach(o=>{o.track.enabled=!n}),this.updateCall(a))}muteCaller(t){this.processCallerMute(t,!0)}unmuteCaller(t){this.processCallerMute(t,!1)}terminateCall(t){const n=this.extendedCalls[t];n._status!==8&&n.terminate()}transferCall(t,n){if(n.toString().length===0)return new Error("Target must be passed");const a=this.extendedCalls[t];if(!a._is_confirmed&&!a._is_canceled){const o=`sip:${n}@${this.context.sipDomain}`;a.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${o}`]});return}this.updateCallStatus({callId:t,isTransferring:!0}),a.refer(`sip:${n}@${this.context.sipDomain}`),this.updateCall(a)}mergeCall(t){const n=Object.values(this.extendedCalls).filter(s=>s.roomId===t);if(n.length!==2)return;const a=n[0],o=n[1];!a||!o||(this.updateCallStatus({callId:a._id,isMerging:!0}),this.updateCallStatus({callId:o._id,isMerging:!0}),a.refer(o.remote_identity.uri.toString(),{replaces:o}),this.updateCall(a))}mergeCallByIds(t,n){const a=Object.values(this.extendedCalls).find(s=>s._id===t),o=Object.values(this.extendedCalls).find(s=>s._id===n);if(!a||!o)throw new Error("Call ID is not provided");this.updateCallStatus({callId:t,isMerging:!0}),this.updateCallStatus({callId:n,isMerging:!0}),a.refer(o.remote_identity.uri.toString(),{replaces:o}),this.updateCall(a)}setDND(t){this.isDNDEnabled=t,this.context.emit("changeIsDND",t)}startCallTimer(t){this.removeTimeInterval(t);const n={callId:t,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(n);const a=setInterval(()=>{const o={...this.callTime[t]},s=YT(o);this.setCallTime({callId:t,...s})},1e3);this.setTimeInterval(t,a)}async setActiveRoom(t){const n=this.currentActiveRoomId;t!==n&&(this.currentActiveRoomId=t,await this.roomReconfigure(n),await this.roomReconfigure(t))}getNewRoomId(){const t=Object.keys(this.activeRooms);return t.length===0?1:parseInt(t.sort()[t.length-1])+1}async setupCall(t){var _,g;const n=t.session;if(this.getActiveCalls[n.id]!==void 0)return;const o=this.getNewRoomId(),s={started:new Date,incomingInProgress:!1,roomId:o};n.direction==="incoming"?(this.context.logger.log("New incoming call from",(g=(_=n._remote_identity)==null?void 0:_._uri)==null?void 0:g._user),s.incomingInProgress=!0,this.context.subscribe(Xt.CALL_CONFIRMED,T=>{n.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:o}),this.startCallTimer(n.id))}),this.context.subscribe(Xt.CALL_FAILED,T=>{n.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:o}),this.deleteRoomIfEmpty(o))})):n.direction==="outgoing"&&(n.once("confirmed",()=>{this.startCallTimer(n.id)}),this.startCallTimer(n.id));const r=n,d=this.hasAutoAnswerHeaders(t),h=r.direction==="incoming"&&!this.hasActiveCalls&&(d||this.autoAnswer);r.roomId=o,r.localMuted=!1,r.autoAnswer=h,h?this.addCall(r,!1):this.addCall(r),this.addCallStatus(n.id),this.addRoom(s),h&&this.answerCall(r._id)}removeCall(t){const n={...this.activeCalls};delete n[t],this.activeCalls={...n};const a={...this.extendedCalls};delete a[t],this.extendedCalls={...a},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(t){var o;const n=this.extendedCalls[t._id];this.stopVUMeter("origin"),(o=n.connection)==null||o.getSenders().forEach(s=>{s.track.stop()});const a=n.roomId;this.removeCall(t._id),this.roomReconfigure(a)}async newRTCSessionCallback(t){const n=t.session;if(this.isDND){n.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(this.context.triggerListener({listenerType:Xt.NEW_CALL,session:n,event:t}),n.on("ended",a=>{var s,r,d;this.stopVUMeter(n.id),this.context.logger.log("Session ended for",(r=(s=n._remote_identity)==null?void 0:s._uri)==null?void 0:r._user),this.context.triggerListener({listenerType:Xt.CALL_ENDED,session:n,event:a});const o=this.getActiveCalls[n.id];o&&this.activeCallListRemove(o),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null)}),n.on("progress",a=>{var o,s;this.context.logger.log("Session in progress for",(s=(o=n._remote_identity)==null?void 0:o._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:Xt.CALL_PROGRESS,session:n,event:a})}),n.on("failed",a=>{var s,r,d;this.stopVUMeter(n.id),this.context.logger.log("Session failed for",(r=(s=n._remote_identity)==null?void 0:s._uri)==null?void 0:r._user),this.context.triggerListener({listenerType:Xt.CALL_FAILED,session:n,event:a}),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const o=this.getActiveCalls[n.id];o&&this.activeCallListRemove(o),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null)}),n.on("confirmed",a=>{var o,s;this.context.logger.log("Session confirmed for",(s=(o=n._remote_identity)==null?void 0:o._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:Xt.CALL_CONFIRMED,session:n,event:a}),this.updateCall(n),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(t),n.direction==="outgoing"){const a=this.getActiveCalls[n.id].roomId;this.setActiveRoom(a)}}setMuteWhenJoin(t){this.muteWhenJoinEnabled=t,this.context.emit("changeMuteWhenJoin",t)}setMicrophoneSensitivity(t){if(t<0||t>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=t,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(t){this.speakerVolumeValue=t,Object.values(this.extendedCalls).forEach(n=>{n.audioTag&&(n.audioTag.volume=t,this.updateCall(n))})}setAutoAnswer(t){this.isAutoAnswer=t}setSelectedInputDevice(t){localStorage.setItem(ba.SELECTED_INPUT_DEVICE,t),this.selectedMediaDevices.input=t,this.context.emit("changeActiveInputMediaDevice",t)}setSelectedOutputDevice(t){localStorage.setItem(ba.SELECTED_OUTPUT_DEVICE,t),this.selectedMediaDevices.output=t,this.context.emit("changeActiveOutputMediaDevice",t)}setCallMetrics(t){const n={...t};delete n.callId,this.callMetrics={...this.callMetrics,[t.callId]:n},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(t){const n={...this.callMetrics};delete n[t],this.callMetrics={...n},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(t){const n=new Hv(this.metricConfig),a=n.createProbe(t.connection,{cid:t._id}),o=[];let s;a.onreport=r=>{Object.entries(r.audio).forEach(([_,g])=>{g.direction==="inbound"&&!o.includes(_)&&(o.push(_),s=_)});const d=r.audio[s];if(!d)return;const h=Fv(d,jv);h.callId=t._id,this.setCallMetrics(h)},this.context.subscribe(Xt.CALL_ENDED,r=>{r._id===t._id&&n.stopAllProbes()}),n.startAllProbes()}setupVUMeter(t,n){this.VUMeter.start(t,n)}stopVUMeter(t){this.VUMeter.stop(t)}async setupStream(){const t=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach(n=>n.stop()),this.initialStreamValue=null),this.initialStreamValue=t}async triggerAddStream(t,n){this.setIsMuted(this.muteWhenJoin||this.isMuted),this.initialStreamValue||await this.setupStream();const a=vh(this.initialStreamValue,this.microphoneInputLevel*2),o=this.isMuted||this.muteWhenJoin;a.getTracks().forEach(r=>r.enabled=!o),this.setActiveStream(a),await n.connection.getSenders()[0].replaceTrack(a.getTracks()[0]);const s=new MediaStream([t.track]);PT(s,n,this.selectedOutputDevice,this.speakerVolume),this.setupVUMeter(s,n._id),this.getCallQuality(n),this.updateCall(n)}initCall(t,n,a=!1){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`);const o=this.context.call(`sip:${t}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=o.id,n&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:o.id,roomId:this.currentActiveRoomId}),a)){const s=Object.values(this.extendedCalls).filter(r=>r.roomId===this.currentActiveRoomId&&r._id!==o.id);for(const r of s)this.holdCall(r._id,!0)}o.connection.addEventListener("track",s=>{this.triggerAddStream(s,o)})}async processRoomChange({callId:t,roomId:n}){const a=this.extendedCalls[t].roomId;this.extendedCalls[t].roomId=n;const o=this.extendedCalls[t];return this.updateCall(o),await this.setActiveRoom(n),Promise.all([this.roomReconfigure(a),this.roomReconfigure(n)]).then(()=>{this.deleteRoomIfEmpty(a),this.deleteRoomIfEmpty(n)})}}class Gv{constructor(t){this.context=t}get sipOptions(){return{...this.context.options.sipOptions}}initCall(t,n){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${t}@${this.context.sipDomain}`,n,this.sipOptions)}stop(t={}){this.context.terminateJanusSessions(t)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(t){this.context.changeMediaConstraints(t)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class Wv{constructor(t){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=t,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this.context))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(t){const n=this.extendedMessages[t];this.updateMSRPSession(n)}updateMSRPSession(t){this.activeMessages[t._id]=Th(t),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(t){this.activeMessages={...this.activeMessages,[t._id]:Th(t)},this.extendedMessages[t._id]=t,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(t,n){const a=this.msrpHistory[n.id]||[];a.push(t),this.msrpHistory={...this.msrpHistory,[n.id]:[...a]},this.context.emit("newMSRPMessage",{message:t,session:n})}messageTerminate(t){const n=this.extendedMessages[t];n._status!==8&&n.terminate()}addMessageSession(t){if(!t._id||this.getActiveMessages[t._id]!==void 0)return;const a=t;this.addMMSRPSession(a)}triggerMSRPListener({listenerType:t,session:n,event:a}){const o=this.context.listenersList[t];!o||!o.length||o.forEach(s=>{s(n,a)})}removeMMSRPSession(t){const n={...this.activeMessages};delete n[t],this.activeMessages={...n};const a={...this.extendedMessages};delete a[t],this.extendedMessages={...a},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(t){this.removeMMSRPSession(t._id)}newMSRPSessionCallback(t){const n=t.session;n.on("ended",a=>{this.triggerMSRPListener({listenerType:Xt.CALL_ENDED,session:n,event:a});const o=this.getActiveMessages[n.id];this.activeMessageListRemove(o)}),n.on("failed",a=>{this.triggerMSRPListener({listenerType:Xt.CALL_FAILED,session:n,event:a});const o=this.getActiveMessages[n.id];this.activeMessageListRemove(o)}),n.on("confirmed",a=>{this.triggerMSRPListener({listenerType:Xt.CALL_CONFIRMED,session:n,event:a}),this.updateMSRPSession(n)}),n.on("newMessage",a=>{this.addMSRPMessage(a,n)}),this.addMessageSession(n)}setIsMSRPInitializing(t){this.isMSRPInitializingValue=t,this.context.emit("isMSRPInitializingChanged",t)}initMSRP(t,n,a){if(t.length===0)return console.error("Target must be a valid string");const o=this.context.startMSRP(t,a);o.on("active",()=>{this.addMessageSession(o),o.sendMSRP(n),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(t,n){const a=this.extendedMessages[t];if(!a)throw new Error(`MSRP session with id ${t} doesn't exist!`);a.sendMSRP(n)}}const Ou={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class kh{constructor(t){this.opensips=null,this.session=null,this.name=null,this.name=t}setOpensips(t){this.opensips=t}setSession(t){this.session=t}kill(){this.opensips.kill(this.name)}}class Mh extends kh{constructor(t,n){super(t),this._candidates=[],this._subscribeSent=!1,this._configureSent=!1,this._lastTrickleReceived=!1,this.type=n}connect(t={}){this.opaqueId=this.session.generateOpaqueId();const n=xe.cloneArray(t.extraHeaders),a={from_tag:this.session._from_tag};t.fromUserName&&(a.from_uri=new ln("sip",t.fromUserName,this.session._ua.configuration.uri.host),n.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),t.fromDisplayName&&(a.from_display_name=t.fromDisplayName),n.push(`Contact: ${this.session._contact}`),n.push("Content-Type: application/json"),this.session._sessionTimers.enabled&&n.push(`Session-Expires: ${this.session._sessionTimers.defaultExpires}${this.session._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new Tt.InitialOutgoingInviteRequest(this.session.target,this.session._ua,a,n),this._createRTCConnection(),this._sendInitialRequest()}getStream(){return this.stream}getConnection(){return this._connection}_createRTCConnection(){this._connection=new RTCPeerConnection({iceServers:[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}]});let t;this._connection.onicecandidate=n=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||n.candidate&&(this._candidates.push(n.candidate),clearTimeout(t),t=setTimeout(()=>{this._lastTrickleReceived=!0,this._subscribeSent&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})},500))}}addTracks(t){t.forEach(n=>{this._connection.addTrack(n)})}async _sendInitialRequest(){const t=new Kr(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});if(await this.generateStream(),!this.stream||!this.stream.getTracks().length)return;this.addTracks(this.stream.getTracks());const n={audio:!1,video:!0};this.jsep_offer=await this._connection.createOffer(n),await this._connection.setLocalDescription(this.jsep_offer);const a={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},o=JSON.stringify(a);this._request.body=o,t.send()}_receiveInviteResponse(t){if(this._publisherSubscribeSent||!t.body)return;const n=JSON.parse(t.body);this.handleId=n.data.id;const a={janus:"message",body:{request:"join",room:this.session.room_id,ptype:"publisher",display:this.session.display_name+" (Screen Share)",opaque_id:this.opaqueId},handle_id:this.handleId},o=[this.session.getPTypeHeader(xt.PUBLISHER)];this.session.sendRequest(L.SUBSCRIBE,{extraHeaders:o,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async s=>{var r,d,h,_;if(s.status_code===200){if(this._subscribeSent=!0,s.body)try{const g=JSON.parse(s.body)||{};((d=(r=g.plugindata)==null?void 0:r.data)==null?void 0:d.videoroom)==="joined"&&this.session.myFeedList.push(g.plugindata.data.id),(_=(h=g.plugindata)==null?void 0:h.data)!=null&&_.publishers&&this.session.receivePublishers(g)}catch(g){console.error(g)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}}}}),this._publisherSubscribeSent=!0}async _sendConfigureMessage(t){const n=this._candidates.map(r=>({janus:"trickle",candidate:r,handle_id:this.handleId,session_id:this.session.session_id})),o={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.session.getRecordFileName(),...t},jsep:this.jsep_offer,handle_id:this.handleId,session_id:this.session.session_id},trickles:[...n]},s=["Content-Type: application/json",this.session.getPTypeHeader(xt.ICE)];this.session.sendRequest(L.INFO,{extraHeaders:s,body:JSON.stringify(o),eventHandlers:{onSuccessResponse:async r=>{this._configureSent=!0;const h=r.data.split(`\r
159
- `),_=h[h.length-1],g=JSON.parse(_);await this._connection.setRemoteDescription(g.jsep),this._candidates=[]}}})}_sendDetach(){const t={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},n=[this.session.getPTypeHeader(xt.DETACH)];this.session.sendRequest(L.INFO,{extraHeaders:n,body:JSON.stringify(t)}),this.session._ua.emit("pluginDetach",this.name)}async stopMedia(){this._connection&&(this._connection.close(),this._connection=null),this.stream&&(this.stream=null)}async stop(){await this.session.stopProcessPlugins(this.type);const t=this._connection.getSenders();t.forEach(n=>{const a=n.track;a&&a.stop()}),t.forEach(n=>{this._connection.removeTrack(n)}),await this.stopMedia(),this._sendDetach()}async generateStream(){throw new Error("generateStream method is not implemented")}}class Lh extends kh{constructor(t,n,a={}){super(t),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=a.immediate||!1,this.type=n}start(t){return t}stop(){throw new Error("stop method is not implemented")}async process(t){if(this.immediate){const n=await this.start(t);return this.running=!0,n}return t}async connect(){this.running=!0,await this.session.resyncPlugins(this.type)}terminate(){this.stop()}async kill(){this.stop(),this.running=!1,await this.session.resyncPlugins(this.type)}}class Kv extends IT{constructor(t,n){if(!t.modules.length)throw new Error("options.modules should include at least 1 module");const a={...t.configuration,sockets:t.socketInterfaces.map(o=>new KT.WebSocketInterface(o))};super(a),this.initialized=!1,this.connected=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.activeConnection=!1,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],t.pnExtraHeaders&&Object.keys(t.pnExtraHeaders).length&&this.registrator().setExtraContactUriParams(t.pnExtraHeaders),this.options=t,this.modules=t.modules,n&&xT(n)&&(this.logger=n)}on(t,n){return super.on(t,n)}off(t,n){return super.off(t,n)}emit(t,n){return super.emit(t,n)}get sipDomain(){return this.options.sipDomain}use(t){if(this.newStreamPlugins.find(n=>n.name===t.name)||this.processStreamPlugins.find(n=>n.name===t.name))throw new Error(`Plugin with name ${t.name} already exists`);if(t instanceof Mh)t.setOpensips(this),this.newStreamPlugins.push(t);else if(t instanceof Lh)t.setOpensips(this),this.processStreamPlugins.push(t);else throw new Error("Wrong plugin instance")}getPlugin(t){return this.newStreamPlugins.find(n=>n.name===t)||this.processStreamPlugins.find(n=>n.name===t)}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(Ou.AUDIO)&&(this.audio=new Bv(this)),this.modules.includes(Ou.MSRP)&&(this.msrp=new Wv(this)),this.modules.includes(Ou.VIDEO)&&(this.video=new Gv(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.setConnected(!0),this.isReconnecting=!1,this.activeConnection=!0}),this.on(this.disconnectedEventName,()=>{this.isReconnecting||(this.isReconnecting=!0,this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.stop(),this.setInitialized(!1),this.setConnected(!1),this.activeConnection&&setTimeout(this.start.bind(this),5e3))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}disconnect(){this.activeConnection=!1,this.stop()}subscribe(t,n){const o=!this.listenersList[t]||!this.listenersList[t].length?[n]:[...this.listenersList[t],n];this.listenersList={...this.listenersList,[t]:o}}removeIListener(t){const n={...this.listenersList};delete n[t],this.listenersList={...n}}triggerListener({listenerType:t,session:n,event:a}){const o=this.listenersList[t];!o||!o.length||o.forEach(s=>{s(n,a)})}setInitialized(t){this.initialized=t,this.emit("ready",t)}setConnected(t){this.connected=t,this.emit("connection",t)}}return Wt.BaseNewStreamPlugin=Mh,Wt.BaseProcessStreamPlugin=Lh,Wt.default=Kv,Object.defineProperties(Wt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),Wt}({});
159
+ `),_=h[h.length-1],g=JSON.parse(_);await this._connection.setRemoteDescription(g.jsep),this._candidates=[]}}})}_sendDetach(){const t={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},n=[this.session.getPTypeHeader(xt.DETACH)];this.session.sendRequest(L.INFO,{extraHeaders:n,body:JSON.stringify(t)}),this.session._ua.emit("pluginDetach",this.name)}async stopMedia(){this._connection&&(this._connection.close(),this._connection=null),this.stream&&(this.stream=null)}async stop(){await this.session.stopProcessPlugins(this.type);const t=this._connection.getSenders();t.forEach(n=>{const a=n.track;a&&a.stop()}),t.forEach(n=>{this._connection.removeTrack(n)}),await this.stopMedia(),this._sendDetach()}async generateStream(){throw new Error("generateStream method is not implemented")}}class Lh extends kh{constructor(t,n,a={}){super(t),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=a.immediate||!1,this.type=n}start(t){return t}stop(){throw new Error("stop method is not implemented")}async process(t){if(this.immediate){const n=await this.start(t);return this.running=!0,n}return t}async connect(){this.running=!0,await this.session.resyncPlugins(this.type)}terminate(){this.stop()}async kill(){this.stop(),this.running=!1,await this.session.resyncPlugins(this.type)}}class Kv extends IT{constructor(t,n){if(!t.modules.length)throw new Error("options.modules should include at least 1 module");const a={...t.configuration,sockets:t.socketInterfaces.map(o=>new KT.WebSocketInterface(o))};super(a),this.initialized=!1,this.connected=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.activeConnection=!1,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],t.pnExtraHeaders&&Object.keys(t.pnExtraHeaders).length&&this.registrator().setExtraContactUriParams(t.pnExtraHeaders),this.options=t,this.modules=t.modules,n&&xT(n)&&(this.logger=n)}on(t,n){return super.on(t,n)}off(t,n){return super.off(t,n)}emit(t,n){return super.emit(t,n)}get sipDomain(){return this.options.sipDomain}use(t){if(this.newStreamPlugins.find(n=>n.name===t.name)||this.processStreamPlugins.find(n=>n.name===t.name))throw new Error(`Plugin with name ${t.name} already exists`);if(t instanceof Mh)t.setOpensips(this),this.newStreamPlugins.push(t);else if(t instanceof Lh)t.setOpensips(this),this.processStreamPlugins.push(t);else throw new Error("Wrong plugin instance")}getPlugin(t){return this.newStreamPlugins.find(n=>n.name===t)||this.processStreamPlugins.find(n=>n.name===t)}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(Ou.AUDIO)&&(this.audio=new Bv(this)),this.modules.includes(Ou.MSRP)&&(this.msrp=new Wv(this)),this.modules.includes(Ou.VIDEO)&&(this.video=new Gv(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.setConnected(!0),this.setReconnecting(!1),this.activeConnection=!0}),this.on(this.disconnectedEventName,()=>{this.isReconnecting||(this.setReconnecting(!0),this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.stop(),this.setInitialized(!1),this.setConnected(!1),this.activeConnection&&setTimeout(this.start.bind(this),5e3))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}disconnect(){this.activeConnection=!1,this.stop()}subscribe(t,n){const o=!this.listenersList[t]||!this.listenersList[t].length?[n]:[...this.listenersList[t],n];this.listenersList={...this.listenersList,[t]:o}}removeIListener(t){const n={...this.listenersList};delete n[t],this.listenersList={...n}}triggerListener({listenerType:t,session:n,event:a}){const o=this.listenersList[t];!o||!o.length||o.forEach(s=>{s(n,a)})}setInitialized(t){this.initialized=t,this.emit("ready",t)}setConnected(t){this.connected=t,this.emit("connection",t)}setReconnecting(t){this.isReconnecting=t,this.emit("reconnecting",t)}}return Wt.BaseNewStreamPlugin=Mh,Wt.BaseProcessStreamPlugin=Lh,Wt.default=Kv,Object.defineProperties(Wt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),Wt}({});
@@ -156,4 +156,4 @@ a=path:${t.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 Kr(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:s=>{this.onTransportError(),console.log(s)},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s),s.status_code===200&&(s.parseSDP(!0),this._status=Ce.STATUS_CONFIRMED,this.target_addr=s.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=Ce.STATUS_INVITE_SENT}terminate(t={}){const n=t.cause||L.causes.BYE,a=xe.cloneArray(t.extraHeaders),o=t.body;let s,r=t.status_code,d=t.reason_phrase;if(this._status===Ce.STATUS_TERMINATED)throw new Ns.InvalidStateError(this._status);switch(this.status="terminated",this._status){case Ce.STATUS_NULL:case Ce.STATUS_INVITE_SENT:case Ce.STATUS_1XX_RECEIVED:if(r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);r&&(d=d||L.REASON_PHRASE[r]||"",s=`SIP ;cause=${r} ;text="${d}"`),this._status===Ce.STATUS_NULL||this._status===Ce.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=s):this._status===Ce.STATUS_1XX_RECEIVED&&this._request.cancel(s),this._status=Ce.STATUS_CANCELED,this._failed("local",null,L.causes.CANCELED);break;case Ce.STATUS_WAITING_FOR_ANSWER:case Ce.STATUS_ANSWERED:if(r=r||480,r<300||r>=700)throw new TypeError(`Invalid status_code: ${r}`);this._request.reply(r,d,a,o),this._failed("local",null,L.causes.REJECTED);break;case Ce.STATUS_WAITING_FOR_ACK:case Ce.STATUS_CONFIRMED:if(d=t.reason_phrase||L.REASON_PHRASE[r]||"",r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);if(r&&a.push(`Reason: SIP ;cause=${r}; text="${d}"`),this._status===Ce.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==jt.C.STATUS_TERMINATED){const h=this._dialog;this.receiveRequest=({method:_})=>{_===L.ACK&&(this.sendRequest(L.BYE,{extraHeaders:a,body:o}),h.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===jt.C.STATUS_TERMINATED&&(this.sendRequest(L.BYE,{extraHeaders:a,body:o}),h.terminate())}),this._ended("local",null,n),this._dialog=h,this._ua.newDialog(h)}else this.sendRequest(L.BYE,{extraHeaders:a,body:o}),this._ended("local",null,n)}}sendRequest(t,n){return this._dialog.sendRequest(t,n)}authenticate(t){this.status="auth";let n=new qn("");n.method="AUTH",n.addHeader("To-Path",`msrp://${this._ua._configuration.realm}:2856;ws`),n.addHeader("From-Path",`msrp://${this.credentials.username}.${this.credentials.realm}:2856/${this.auth_id};ws`),t&&n.addHeader("Authorization",t.toString());let a=n.toString(),o=[];for(var s=0;s<a.length;s++)o.push(a.charCodeAt(s).toString(16));this._connection.send(n.toString())}onmessage(t){const n=new qn(t.data);if(this.status==="auth"&&n.code===401){const a=this.parseAuth(n.getHeader("WWW-Authenticate")),o=new Dm(this.credentials);o.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},a,xe.createRandomToken(12)),this.authenticate(o)}this.status==="auth"&&n.code===200&&this._direction==="outgoing"?(this.my_addr.push(n.getHeader("To-Path")),this.my_addr.push(n.getHeader("Use-Path")),this.status="active",this.inviteParty(n)):this.status==="auth"&&n.code===200&&this._direction==="incoming"?(this.my_addr.push(n.getHeader("To-Path")),this.my_addr.push(n.getHeader("Use-Path")),this.status="active",this.acceptParty(n),this.emit("confirmed")):n.method==="SEND"&&(this._sendOk(n),this._sendReport(n),n.direction="incoming",this.emit("newMessage",n),this._msgHistory.push(n),this.emit("msgHistoryUpdate",this._msgHistory)),n.code===480&&this._close()}onclose(){console.log("close")}onopen(){const t=new RTCPeerConnection({iceServers:[]});t.createDataChannel(""),t.createOffer().then(t.setLocalDescription.bind(t)),t.onicecandidate=n=>{if(!n||!n.candidate||!n.candidate.candidate)return;const a=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,o=n.candidate.candidate.match(a);this.my_ip=o&&o[1],t.onicecandidate=()=>{},this.authenticate(null)}}onerror(t){console.log(t)}_receiveInviteResponse(t){if(console.log("resp0000000000000",t),this._dialog&&t.status_code>=200&&t.status_code<=299)if(console.log("200000000000000"),this._dialog.id.call_id===t.call_id&&this._dialog.id.local_tag===t.from_tag&&this._dialog.id.remote_tag===t.to_tag){this.sendRequest(L.ACK);return}else{const n=new ca(this,t,"UAC");if(n.error!==void 0){console.log(n.error);return}this.sendRequest(L.ACK),this.sendRequest(L.BYE);return}if(this._is_canceled){t.status_code>=100&&t.status_code<200?this._request.cancel(this._cancel_reason):t.status_code>=200&&t.status_code<299&&this._acceptAndTerminate(t);return}if(!(this._status!==Ce.STATUS_INVITE_SENT&&this._status!==Ce.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(t.status_code):this._status=Ce.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(t.status_code):{if(!t.to_tag){console.log("1xx response received without to tag");break}if(t.hasHeader("contact")&&!this._createDialog(t,"UAC",!0))break;if(this._status=Ce.STATUS_1XX_RECEIVED,!t.body){this._progress("remote",t);break}const n={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",n);const a=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>this._progress("remote",t)).catch(o=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',o),this.emit("peerconnection:setremotedescriptionfailed",o)});break}case/^2[0-9]{2}$/.test(t.status_code):{if(console.log("maybe here???"),this._status=Ce.STATUS_CONFIRMED,!t.body){this._acceptAndTerminate(t,400,L.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",t,L.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(t,"UAC"))break;const n={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",n),new RTCSessionDescription({type:"answer",sdp:n.sdp}),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(a=>this._connection.setLocalDescription(a)).catch(a=>{this._acceptAndTerminate(t,500,a.toString()),console.log("failed 4"),this._failed("local",t,L.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(t),this._accepted("remote",t),this.sendRequest(L.ACK),this._confirmed("local",null)});break}default:{const n=xe.sipErrorCause(t.status_code);console.log("failed 5"),this._failed("remote",t,n)}}}sendMSRP(t){const n=new qn("");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",xe.createRandomToken(10)),n.addHeader("Byte-Range","1-25/25"),n.addHeader("Content-Type","text/plain"),n.addHeader("Success-Report","yes"),n.addHeader("Failure-Report","yes"),n.body=t;let a=n.toString();console.log(a);let o=[];for(var s=0;s<a.length;s++)o.push(a.charCodeAt(s).toString(16));console.log(o),this._connection.send(n.toString()),n.direction="outgoing",this.emit("newMessage",n),this._msgHistory.push(n),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(t){let n=t.ident,a=t.getHeader("Message-ID"),o=new qn("");o.method="200 OK",o.addHeader("To-Path",`${this.my_addr[1]}`),o.addHeader("From-Path",`${this.my_addr[0]}`),o.addHeader("Message-ID",a),o.ident=n;let s=o.toString();console.log(s);let r=[];for(var d=0;d<s.length;d++)r.push(s.charCodeAt(d).toString(16));console.log(r),this._connection.send(o.toString())}_sendReport(t){let n=t.ident,a=t.getHeader("Message-ID"),o=new qn("");o.method="REPORT",o.addHeader("To-Path",`${t.getHeader("From-Path")}`),o.addHeader("From-Path",`${this.my_addr[0]}`),o.addHeader("Message-ID",a),o.addHeader("Byte-Range","1-25/25"),o.addHeader("Status","000 200 OK"),o.ident=n;let s=o.toString();console.log(s);let r=[];for(var d=0;d<s.length;d++)r.push(s.charCodeAt(d).toString(16));console.log(r),this._connection.send(o.toString())}parseAuth(t){const n={},a=t.replace("Digest","").split(",");for(const o of a){const s=o.trim().split("=");n[s[0]]=s[1].match('^"(.+)"$')[1]}return n}init_incoming(t,n){let a;const o=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;if(t.body&&o!=="application/sdp"){t.reply(415);return}if(this._status=Ce.STATUS_INVITE_RECEIVED,this._from_tag=t.from_tag,this._id=t.call_id+this._from_tag,this._request=t,this._contact=this._ua.contact.toString(),t.hasHeader("expires")&&(a=t.getHeader("expires")*1e3),t.to_tag=xe.newTag(),!this._createDialog(t,"UAS",!0)){t.reply(500,"Missing Contact header field");return}t.body?this._late_sdp=!1:this._late_sdp=!0,this._status=Ce.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{t.reply(408),console.log("failed 6"),this._failed("local",null,L.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),a&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Ce.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),console.log("failed 7"),this._failed("system",null,L.causes.EXPIRES))},a)),this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from,n&&n(this),t.parseSDP(!0),this.target_addr=t.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",t),this._status!==Ce.STATUS_TERMINATED&&(t.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(t,n,a){this.emit("_failed",{originator:t,message:n||null,cause:a}),this._close(),this.emit("failed",{originator:t,message:n||null,cause:a})}_close(){if(console.log("CLOSE SESSION"),this._status!==Ce.STATUS_TERMINATED){if(this._status=Ce.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(t){console.log("close() | error closing the RTCPeerConnection: %o",t)}for(const t in this._timers)Object.prototype.hasOwnProperty.call(this._timers,t)&&clearTimeout(this._timers[t]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const t in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,t)&&(this._earlyDialogs[t].terminate(),delete this._earlyDialogs[t]);for(const t in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,t)&&delete this._referSubscribers[t];this._ua.destroyMSRPSession(this)}}_createDialog(t,n,a){const o=n==="UAS"?t.to_tag:t.from_tag,s=n==="UAS"?t.from_tag:t.to_tag,r=t.call_id+o+s;let d=this._earlyDialogs[r];if(a)return d?!0:(d=new ca(this,t,n,ca.C.STATUS_EARLY),d.error?(console.log("failed 8"),this._failed("remote",t,L.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[r]=d,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,d)return d.update(t,n),this._dialog=d,delete this._earlyDialogs[r],!0;const h=new ca(this,t,n);return h.error?(console.log("failed 9"),this._failed("remote",t,L.causes.INTERNAL_ERROR),!1):(this._dialog=h,!0)}}_newMSRPSession(t,n){this._ua.newMSRPSession(this,{originator:t,session:this,request:n})}_progress(t,n){this.emit("progress",{originator:t,response:n||null})}isEnded(){switch(this._status){case Ce.STATUS_CANCELED:case Ce.STATUS_TERMINATED:return!0;default:return!1}}_accepted(t,n){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:t,response:n||null})}_confirmed(t,n){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:t,ack:n||null})}_ended(t,n,a){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:t,message:n||null,cause:a})}_handleSessionTimersInIncomingResponse(t){if(!this._sessionTimers.enabled)return;let n;t.session_expires&&t.session_expires>=L.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,n=t.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,n="uac"),this._sessionTimers.refresher=n==="uac",this._runSessionTimer()}receiveRequest(t){if(console.log("receiveRequest()"),t.method===L.CANCEL)(this._status===Ce.STATUS_WAITING_FOR_ANSWER||this._status===Ce.STATUS_ANSWERED)&&(this._status=Ce.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",t,L.causes.CANCELED));else switch(t.method){case L.ACK:if(this._status!==Ce.STATUS_WAITING_FOR_ACK)return;if(this._status=Ce.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!t.body){this.terminate({cause:L.causes.MISSING_SDP,status_code:400});break}const n={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",n);const a=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>{this._is_confirmed||this._confirmed("remote",t)}).catch(o=>{this.terminate({cause:L.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',o),this.emit("peerconnection:setremotedescriptionfailed",o)})}else this._is_confirmed||this._confirmed("remote",t);break;case L.BYE:this._status===Ce.STATUS_CONFIRMED||this._status===Ce.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,L.causes.BYE)):this._status===Ce.STATUS_INVITE_RECEIVED||this._status===Ce.STATUS_WAITING_FOR_ANSWER?(t.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",t,L.causes.BYE)):t.reply(403,"Wrong Status");break;case L.INVITE:this._status===Ce.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case L.INFO:this._status===Ce.STATUS_1XX_RECEIVED||this._status===Ce.STATUS_WAITING_FOR_ANSWER||this._status===Ce.STATUS_ANSWERED||this._status===Ce.STATUS_WAITING_FOR_ACK||this._status===Ce.STATUS_CONFIRMED?(t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new nu(this).init_incoming(t):t.reply(415):t.reply(403,"Wrong Status");break;case L.UPDATE:this._status===Ce.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case L.REFER:this._status===Ce.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case L.NOTIFY:this._status===Ce.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:L.causes.CONNECTION_ERROR,cause:L.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:L.causes.REQUEST_TIMEOUT,cause:L.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:L.causes.DIALOG_ERROR,cause:L.causes.DIALOG_ERROR})}}var vT=Jt();const yu=Me(vT),ya=new ra("Parser"),ET=(c,t)=>{let n,a,o=c.indexOf(`\r
157
157
  `);if(o===-1){ya.warn("parseMessage() | no CRLF found, not a SIP message");return}const s=c.substring(0,o);let r=yu.parse(s,"Request_Response");if(r===-1){ya.warn(`parseMessage() | error parsing first line of SIP message: "${s}"`);return}else r.status_code?(n=new $n.IncomingResponse,n.status_code=r.status_code,n.reason_phrase=r.reason_phrase):(n=new $n.IncomingRequest(t),n.method=r.method,n.ruri=r.uri);n.data=c;let d=o+2;for(;;){if(o=ST(c,d),o===-2){a=d+2;break}else if(o===-1){ya.warn("parseMessage() | malformed message");return}if(r=yT(n,c,d,o),r!==!0){ya.warn("parseMessage() |",r.error);return}d=o+2}if(n.hasHeader("content-length")){const h=n.getHeader("content-length");n.body=c.substr(a,h)}else n.body=c.substring(a);return n};function ST(c,t){let n=t,a=0,o=0;if(c.substring(n,n+2).match(/(^\r\n)/))return-2;for(;a===0;){if(o=c.indexOf(`\r
158
158
  `,n),o===-1)return o;!c.substring(o+2,o+4).match(/(^\r\n)/)&&c.charAt(o+2).match(/(^\s+)/)?n=o+2:a=o}return a}function yT(c,t,n,a){let o;const s=t.indexOf(":",n),r=t.substring(n,s).trim(),d=t.substring(s+1,a).trim();switch(r.toLowerCase()){case"via":case"v":c.addHeader("via",d),c.getHeaders("via").length===1?(o=c.parseHeader("Via"),o&&(c.via=o,c.via_branch=o.branch)):o=0;break;case"from":case"f":c.setHeader("from",d),o=c.parseHeader("from"),o&&(c.from=o,c.from_tag=o.getParam("tag"));break;case"to":case"t":c.setHeader("to",d),o=c.parseHeader("to"),o&&(c.to=o,c.to_tag=o.getParam("tag"));break;case"record-route":if(o=yu.parse(d,"Record_Route"),o===-1)o=void 0;else for(const h of o)c.addHeader("record-route",d.substring(h.possition,h.offset)),c.headers["Record-Route"][c.getHeaders("record-route").length-1].parsed=h.parsed;break;case"call-id":case"i":c.setHeader("call-id",d),o=c.parseHeader("call-id"),o&&(c.call_id=d);break;case"contact":case"m":if(o=yu.parse(d,"Contact"),o===-1)o=void 0;else for(const h of o)c.addHeader("contact",d.substring(h.possition,h.offset)),c.headers.Contact[c.getHeaders("contact").length-1].parsed=h.parsed;break;case"content-length":case"l":c.setHeader("content-length",d),o=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",d),o=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",d),o=c.parseHeader("cseq"),o&&(c.cseq=o.value),c instanceof $n.IncomingResponse&&(c.method=o.method);break;case"max-forwards":c.setHeader("max-forwards",d),o=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",d),o=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",d),o=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",d),o=c.parseHeader("session-expires"),o&&(c.session_expires=o.expires,c.session_expires_refresher=o.refresher);break;case"refer-to":case"r":c.setHeader("refer-to",d),o=c.parseHeader("refer-to"),o&&(c.refer_to=o);break;case"replaces":c.setHeader("replaces",d),o=c.parseHeader("replaces"),o&&(c.replaces=o);break;case"event":case"o":c.setHeader("event",d),o=c.parseHeader("event"),o&&(c.event=o);break;default:c.addHeader(r,d),o=0}return o===void 0?{error:`error parsing header "${r}"`}:!0}const AT={parseMessage:ET},ni=new ra("Registrator"),Aa=10;class CT{constructor(t,n){this._reg_id=1,this._ua=t,this._transport=n,this._registrar=t.configuration.registrar_server,this._expires=t.configuration.register_expires,this._call_id=vs.createRandomToken(22),this._cseq=0,this._to_uri=t.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const a=this._contact.indexOf(">");if(a!==-1){const o=this._contact.slice(0,a)+this._contact.slice(a+1,this._contact.length);this._contact=o}this._extra_contact="",this._extraContactParams="",this._extra_contact+=";+sip.ice",this._extraHeaders=[],this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._extra_contact+=`;reg-id=${this._reg_id}`,this._extra_contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(t){Array.isArray(t)||(t=[]),this._extraHeaders=t.slice()}setExtraContactParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const a=t[n];this._extraContactParams+=`;${n}`,a&&(this._extraContactParams+=`=${a}`)}}setExtraContactUriParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const a=t[n];this._extraContactParams+=`;${n}`,a&&(this._extraContactParams+=`=${a}`)}}register(){if(this._registering){ni.debug("Register request in progress...");return}const t=this._extraHeaders.slice();t.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),t.push(`Expires: ${this._expires}`);const n=new Tt.OutgoingRequest(L.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t),a=new Kr(this._ua,n,{onRequestTimeout:()=>{this._registrationFailure(null,L.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,L.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:o=>{if(o.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(o.status_code):break;case/^2[0-9]{2}$/.test(o.status_code):{if(this._registering=!1,!o.hasHeader("Contact")){ni.debug("no Contact header in response to REGISTER, response ignored");break}const s=o.headers.Contact.reduce((_,g)=>_.concat(g.parsed),[]);let r=s.find(_=>this._sipInstance===_.getParam("+sip.instance")&&this._reg_id===parseInt(_.getParam("reg-id")));if(r||(r=s.find(_=>_.uri.user===this._ua.contact.uri.user)),!r){ni.debug("no Contact header pointing to us, response ignored");break}let d=r.getParam("expires");!d&&o.hasHeader("expires")&&(d=o.getHeader("expires")),d||(d=this._expires),d=Number(d),d<Aa&&(d=Aa);const h=d>64?d*1e3/2+Math.floor((d/2-32)*1e3*Math.random()):d*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},h),r.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=r.getParam("temp-gruu").replace(/"/g,"")),r.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=r.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:o}));break}case/^423$/.test(o.status_code):{o.hasHeader("min-expires")?(this._expires=Number(o.getHeader("min-expires")),this._expires<Aa&&(this._expires=Aa),this.register()):(ni.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(o,L.causes.SIP_FAILURE_CODE));break}default:{const s=vs.sipErrorCause(o.status_code);this._registrationFailure(o,s)}}}});this._registering=!0,a.send()}unregister(t={}){if(!this._registered){ni.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const n=this._extraHeaders.slice();t.all?n.push(`Contact: *${this._extraContactParams}`):n.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),n.push("Expires: 0");const a=new Tt.OutgoingRequest(L.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n);new Kr(this._ua,a,{onRequestTimeout:()=>{this._unregistered(null,L.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,L.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:s=>{switch(!0){case/^1[0-9]{2}$/.test(s.status_code):break;case/^2[0-9]{2}$/.test(s.status_code):this._unregistered(s);break;default:{const r=vs.sipErrorCause(s.status_code);this._unregistered(s,r)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(t,n){this._registering=!1,this._ua.registrationFailed({response:t||null,cause:n}),this._registered&&(this._registered=!1,this._ua.unregistered({response:t||null,cause:n}))}_unregistered(t,n){this._registering=!1,this._registered=!1,this._ua.unregistered({response:t||null,cause:n||null})}}const et=console,ks={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},RT=fT;class IT extends RT{constructor(t){super(t),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this.newStreamPlugins=[],this.processStreamPlugins=[],this._registrator=new CT(this)}call(t,n){return super.call(t,n)}joinVideoCall(t,n,a){et.debug("call()");const o=new Sa(this);return o.configureMedia({audio:!0,video:!0}),o.connect(t,n,a),o}startScreenShare(){et.debug("startScreenShare()");for(const t in this._janus_sessions)this._janus_sessions[t].connectScreenShare()}changeMediaConstraints(t){for(const n in this._janus_sessions)this._janus_sessions[n].changeMediaConstraints(t)}startBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].connectBlur()}stopBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].stopBlur()}_loadConfig(t){try{si.load(this._configuration,t)}catch(s){throw s}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=vs.newUUID());let n;typeof window<"u"&&typeof window.document<"u"?n=window==null?void 0:window.navigator.userAgent:typeof self<"u"&&self.navigator&&(n=self.navigator.userAgent),n+=" "+De.USER_AGENT,this._configuration.user_agent=t.overrideUserAgent&&typeof t.overrideUserAgent=="function"?t.overrideUserAgent(n):n,this._configuration.jssip_id=vs.createRandomToken(5);const a=this._configuration.uri.clone();a.user=null,this._configuration.hostport_params=a.toString().replace(/^sip:/i,"");try{this._transport=new Lg(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=bT.bind(this),this._transport.onconnect=wT.bind(this),this._transport.ondisconnect=OT.bind(this),this._transport.ondata=DT.bind(this)}catch(s){throw et.warn(s),new Ns.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const s=this._configuration.uri.clone();s.user=null,s.clearParams(),s.clearHeaders(),this._configuration.registrar_server=s}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new ln("sip",vs.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(s={}){const r=s.anonymous||null,d=s.outbound||null;let h="<";return r?h+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":h+=this.pub_gruu||this.uri.toString(),d&&(r?!this.temp_gruu:!this.pub_gruu)&&(h+=";ob"),h+=">",h}};const o=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const s in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,s)&&(o.indexOf(s)!==-1?Object.defineProperty(this._configuration,s,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,s,{writable:!1,configurable:!1}));et.debug("configuration parameters after validation:");for(const s in this._configuration)if(Object.prototype.hasOwnProperty.call(si.settings,s))switch(s){case"uri":case"registrar_server":et.debug(`- ${s}: ${this._configuration[s]}`);break;case"password":case"ha1":case"authorization_jwt":et.debug(`- ${s}: NOT SHOWN`);break;default:et.debug(`- ${s}: ${JSON.stringify(this._configuration[s])}`)}}newMSRPSession(t,n){t.on("msgHistoryUpdate",a=>{console.log(a)}),this._msrp_sessions[t.id]=t,this.emit("newMSRPSession",n)}newJanusSession(t,n){this._janus_sessions[t.id]=t,this.newStreamPlugins.forEach(a=>{a.setSession(t)}),this.processStreamPlugins.forEach(a=>{a.setSession(t)}),this.emit("newJanusSession",n)}kill(){}destroyMSRPSession(t){delete this._msrp_sessions[t.id]}destroyJanusSession(t){delete this._janus_sessions[t.id]}receiveRequest(t){var s,r,d,h;const n=t.method;if(t.ruri.user!==this._configuration.uri.user&&t.ruri.user!==this._contact.uri.user){et.debug("Request-URI does not point to us"),t.method!==De.ACK&&t.reply_sl(404);return}if(t.ruri.scheme===De.SIPS){t.reply_sl(416);return}if(jt.checkTransaction(this,t))return;if(n===De.INVITE?new jt.InviteServerTransaction(this,this._transport,t):n!==De.ACK&&n!==De.CANCEL&&new jt.NonInviteServerTransaction(this,this._transport,t),n===De.OPTIONS){if(this.listeners("newOptions").length===0){t.reply(200);return}new yf.Options(this).init_incoming(t)}else if(n===De.MESSAGE){if(this.listeners("newMessage").length===0){t.reply(405);return}new yf.Message(this).init_incoming(t)}else if(n===De.INVITE&&!t.to_tag&&this.listeners("newRTCSession").length===0){t.reply(405);return}let a,o;if(t.to_tag)if(a=this._findDialog(t.call_id,t.from_tag,t.to_tag),a)a.receiveRequest(t);else if(n===De.NOTIFY)if(o=this._findSession(t),o)o.receiveRequest(t);else{if(t.body)try{const _=JSON.parse(t.body)||{};(r=(s=_.plugindata)==null?void 0:s.data)!=null&&r.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(_),(h=(d=_.plugindata)==null?void 0:d.data)!=null&&h.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(_.plugindata.data.unpublished)}catch(_){console.error(_)}t.reply(200)}else n!==De.ACK&&t.reply(481);else switch(n){case De.INVITE:if(window.RTCPeerConnection)if(t.hasHeader("replaces")){const _=t.replaces;a=this._findDialog(_.call_id,_.from_tag,_.to_tag),a?(o=a.owner,o.isEnded()?t.reply(603):o.receiveRequest(t)):t.reply(481)}else t.body.search(/MSRP/ig)>-1?(o=new Su(this),o.init_incoming(t)):t.body.search(/JANUS/ig)>-1||(o=new Sg(this),o.init_incoming(t));else et.warn("INVITE received but WebRTC is not supported"),t.reply(488);break;case De.BYE:t.reply(481);break;case De.CANCEL:o=this._findSession(t),o?o.receiveRequest(t):et.debug("received CANCEL request for a non existent session");break;case De.ACK:break;case De.NOTIFY:this.emit("sipEvent",{event:t.event,request:t}),t.reply(200);break;default:t.reply(405);break}}startMSRP(t,n){et.debug("startMSRP()",n);const a=new Su(this);return a.connect(t),a}startJanus(t,n){et.debug("startJanus()",n);const a=new Su(this);return a.connect(t),a}terminateMSRPSessions(t){et.debug("terminateSessions()");for(const n in this._msrp_sessions)this._msrp_sessions[n].isEnded()||this._msrp_sessions[n].terminate(t)}terminateJanusSessions(t){et.debug("terminateSessions()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||this._janus_sessions[n].terminate(t)}enableJanusAudio(t){et.debug("enableJanusAudio()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||(t?this._janus_sessions[n].startAudio():this._janus_sessions[n].stopAudio())}enableJanusVideo(t){et.debug("enableJanusVideo()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||(t?this._janus_sessions[n].startVideo():this._janus_sessions[n].stopVideo())}stop(){if(et.debug("stop()"),this._dynConfiguration={},this._status===ks.STATUS_USER_CLOSED){et.debug("UA already closed");return}this._registrator.close();const t=Object.keys(this._sessions).length;for(const a in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,a)){et.debug(`closing session ${a}`);try{this._sessions[a].terminate()}catch(o){console.error(o)}}for(const a in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,a)){et.debug(`closing session ${a}`);try{this._msrp_sessions[a].terminate()}catch(o){console.error(o)}}for(const a in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,a)){et.debug(`closing session ${a}`);try{this._janus_sessions[a].terminate()}catch(o){console.error(o)}}for(const a in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,a))try{this._applicants[a].close()}catch(o){console.error(o)}this._status=ks.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&t===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function bT(c){this.emit("connecting",c)}function wT(c){this._status!==ks.STATUS_USER_CLOSED&&(this._status=ks.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function OT(c){const t=["nict","ict","nist","ist"];for(const n of t)for(const a in this._transactions[n])Object.prototype.hasOwnProperty.call(this._transactions[n],a)&&this._transactions[n][a].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==ks.STATUS_USER_CLOSED&&(this._status=ks.STATUS_NOT_READY,this._error=ks.NETWORK_ERROR)}function DT(c){const t=c.transport;let n=c.message;if(n=AT.parseMessage(n,this),!!n&&!(this._status===ks.STATUS_USER_CLOSED&&n instanceof $n.IncomingRequest)&&Qg(n,this,t)){if(n instanceof $n.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof $n.IncomingResponse){let a;switch(n.method){case De.INVITE:a=this._transactions.ict[n.via_branch],a&&a.receiveResponse(n);break;case De.ACK:break;default:a=this._transactions.nict[n.via_branch],a&&a.receiveResponse(n);break}}}}const NT=["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"],UT=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function gh(c){const t={};return NT.forEach(n=>{c[n]!==void 0&&(t[n]=c[n])}),t.localHold=c._localHold,t}function Th(c){const t={};return UT.forEach(n=>{c[n]!==void 0&&(t[n]=c[n])}),t}function vh(c,t){const n=new AudioContext,a=n.createMediaStreamSource(c),o=n.createMediaStreamDestination(),s=n.createGain();return a.connect(s),s.connect(o),s.gain.value=t,o.stream}function PT(c,t,n,a){const o=document.createElement("audio");o.id=t._id,o.className="audioTag",o.srcObject=c,Eh()||(o.setSinkId(n),o.volume=a),o.play(),t.audioTag=o}function xT(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}function Eh(){return/Mobi|Android|iPhone/i.test(navigator.userAgent)}const kT=at,MT=Jt(),Ot=new kT("WebSocketInterface");var LT=class{constructor(t){Ot.debug('new() [url:"%s"]',t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;const n=MT.parse(t,"absoluteURI");if(n===-1)throw Ot.warn(`invalid WebSocket URI: ${t}`),new TypeError(`Invalid argument: ${t}`);if(n.scheme!=="wss"&&n.scheme!=="ws")throw Ot.warn(`invalid WebSocket URI scheme: ${n.scheme}`),new TypeError(`Invalid argument: ${t}`);this._sip_uri=`sip:${n.host}${n.port?`:${n.port}`:""};transport=ws`,this._via_transport=n.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(t){this._via_transport=t.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Ot.debug("connect()"),this.isConnected()){Ot.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Ot.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Ot.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(t){this._onError(t)}}disconnect(){Ot.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(t){return Ot.debug("send()"),this.isConnected()?(this._ws.send(t),!0):(Ot.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(){Ot.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:t,code:n,reason:a}){Ot.debug(`WebSocket ${this._url} closed`),t===!1&&Ot.debug("WebSocket abrupt disconnection"),this.ondisconnect(!t,n,a)}_onMessage({data:t}){Ot.debug("received WebSocket message"),this.ondata(t)}_onError(t){Ot.warn(`WebSocket ${this._url} error: `,t)}};const Au=vl,$T=De,HT=Ts,FT=mt(),jT=_h,qT=ps(),VT=Vo(),BT=Jt(),GT=LT;Un("JsSIP")("version %s",Au.version);var WT={C:$T,Exceptions:HT,Utils:FT,UA:jT,URI:qT,NameAddrHeader:VT,WebSocketInterface:GT,Grammar:BT,debug:Un,get name(){return Au.title},get version(){return Au.version}};const KT=Me(WT);function Cu(c){return c<10?`0${c}`:`${c}`}function YT(c){let t=c.hours||0,n=c.minutes||0,a=c.seconds||0;a++,a===60&&(a=0,n++,n===60&&(n=0,t++));const o=`${Cu(t)}:${Cu(n)}:${Cu(a)}`;return{seconds:a,minutes:n,hours:t,formatted:o}}var yt={};yt.forEach=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)if(o in c){const s=Promise.resolve(c[o]).then(r=>t.call(n||globalThis,r,o,c));a.push(s)}await Promise.all(a)},yt.forEachSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)a in c&&await t.call(n||globalThis,await c[a],a,c)},yt.map=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)o in c&&(a[o]=Promise.resolve(c[o]).then(s=>t.call(n||globalThis,s,o,c)));return Promise.all(a)},yt.mapSeries=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)o in c&&(a[o]=await t.call(n||globalThis,await c[o],o,c));return a},yt.find=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a();let s=1;for(let r=0;r<c.length;r++){const d=h=>{h?a(c[r]):s===c.length&&a(),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}}),yt.findSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(await t.call(n||globalThis,await c[a],a,c))return c[a]},yt.findIndex=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a(-1);let s=1;for(let r=0;r<c.length;r++){const d=h=>{h?a(r):s===c.length&&a(-1),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}}),yt.findIndexSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(await t.call(n||globalThis,await c[a],a,c))return a},yt.some=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a(!1);let s=1;for(let r=0;r<c.length;r++){if(!(r in c)){s++;continue}const d=h=>{h?a(!0):s===c.length&&a(!1),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}}),yt.someSeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(a in c&&await t.call(n||globalThis,await c[a],a,c))return!0;return!1},yt.every=(c,t,n)=>new Promise((a,o)=>{if(c.length===0)return a(!0);let s=1;for(let r=0;r<c.length;r++){if(!(r in c)){s++;continue}const d=h=>{h?s===c.length&&a(!0):a(!1),s++};Promise.resolve(c[r]).then(h=>t.call(n||globalThis,h,r,c)).then(d).catch(o)}}),yt.everySeries=async(c,t,n)=>{for(let a=0;a<c.length;a++)if(a in c&&!await t.call(n||globalThis,await c[a],a,c))return!1;return!0},yt.filter=(c,t,n)=>new Promise(async(a,o)=>{const s=[];for(let d=0;d<c.length;d++)d in c&&(s[d]=Promise.resolve(c[d]).then(h=>t.call(n||globalThis,h,d,c)).catch(o));const r=[];for(let d=0;d<s.length;d++)await s[d]&&r.push(await c[d]);a(r)}),yt.filterSeries=async(c,t,n)=>{const a=[];for(let o=0;o<c.length;o++)o in c&&await t.call(n||globalThis,await c[o],o,c)&&a.push(await c[o]);return a},yt.reduce=async(c,t,n)=>{if(c.length===0&&n===void 0)throw TypeError("Reduce of empty array with no initial value");let a,o;for(n!==void 0?(o=n,a=0):(o=c[0],a=1),a;a<c.length;a++)a in c&&(o=await t(await o,await c[a],a,c));return o};var Sh={};(function(c){const t=yt;Object.keys(t).forEach(n=>{const a=n.charAt(0).toUpperCase()+n.slice(1);c[`async${a}`]=async function(...o){return t[n](this,...o)}})})(Sh);var JT=Object.assign(yt,{instanceMethods:Sh});const an=new AudioContext,Qt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var zT={exports:{}};(function(c){var t=function(n){var a=Object.prototype,o=a.hasOwnProperty,s=Object.defineProperty||function(ee,Y,G){ee[Y]=G.value},r,d=typeof Symbol=="function"?Symbol:{},h=d.iterator||"@@iterator",_=d.asyncIterator||"@@asyncIterator",g=d.toStringTag||"@@toStringTag";function T(ee,Y,G){return Object.defineProperty(ee,Y,{value:G,enumerable:!0,configurable:!0,writable:!0}),ee[Y]}try{T({},"")}catch{T=function(Y,G,re){return Y[G]=re}}function E(ee,Y,G,re){var ge=Y&&Y.prototype instanceof oe?Y:oe,be=Object.create(ge.prototype),ke=new P(re||[]);return s(be,"_invoke",{value:J(ee,G,ke)}),be}n.wrap=E;function y(ee,Y,G){try{return{type:"normal",arg:ee.call(Y,G)}}catch(re){return{type:"throw",arg:re}}}var A="suspendedStart",C="suspendedYield",I="executing",H="completed",$={};function oe(){}function N(){}function j(){}var Se={};T(Se,h,function(){return this});var ve=Object.getPrototypeOf,k=ve&&ve(ve(se([])));k&&k!==a&&o.call(k,h)&&(Se=k);var D=j.prototype=oe.prototype=Object.create(Se);N.prototype=j,s(D,"constructor",{value:j,configurable:!0}),s(j,"constructor",{value:N,configurable:!0}),N.displayName=T(j,g,"GeneratorFunction");function B(ee){["next","throw","return"].forEach(function(Y){T(ee,Y,function(G){return this._invoke(Y,G)})})}n.isGeneratorFunction=function(ee){var Y=typeof ee=="function"&&ee.constructor;return Y?Y===N||(Y.displayName||Y.name)==="GeneratorFunction":!1},n.mark=function(ee){return Object.setPrototypeOf?Object.setPrototypeOf(ee,j):(ee.__proto__=j,T(ee,g,"GeneratorFunction")),ee.prototype=Object.create(D),ee},n.awrap=function(ee){return{__await:ee}};function V(ee,Y){function G(be,ke,Re,le){var ye=y(ee[be],ee,ke);if(ye.type==="throw")le(ye.arg);else{var lt=ye.arg,ot=lt.value;return ot&&typeof ot=="object"&&o.call(ot,"__await")?Y.resolve(ot.__await).then(function(Ee){G("next",Ee,Re,le)},function(Ee){G("throw",Ee,Re,le)}):Y.resolve(ot).then(function(Ee){lt.value=Ee,Re(lt)},function(Ee){return G("throw",Ee,Re,le)})}}var re;function ge(be,ke){function Re(){return new Y(function(le,ye){G(be,ke,le,ye)})}return re=re?re.then(Re,Re):Re()}s(this,"_invoke",{value:ge})}B(V.prototype),T(V.prototype,_,function(){return this}),n.AsyncIterator=V,n.async=function(ee,Y,G,re,ge){ge===void 0&&(ge=Promise);var be=new V(E(ee,Y,G,re),ge);return n.isGeneratorFunction(Y)?be:be.next().then(function(ke){return ke.done?ke.value:be.next()})};function J(ee,Y,G){var re=A;return function(be,ke){if(re===I)throw new Error("Generator is already running");if(re===H){if(be==="throw")throw ke;return it()}for(G.method=be,G.arg=ke;;){var Re=G.delegate;if(Re){var le=F(Re,G);if(le){if(le===$)continue;return le}}if(G.method==="next")G.sent=G._sent=G.arg;else if(G.method==="throw"){if(re===A)throw re=H,G.arg;G.dispatchException(G.arg)}else G.method==="return"&&G.abrupt("return",G.arg);re=I;var ye=y(ee,Y,G);if(ye.type==="normal"){if(re=G.done?H:C,ye.arg===$)continue;return{value:ye.arg,done:G.done}}else ye.type==="throw"&&(re=H,G.method="throw",G.arg=ye.arg)}}}function F(ee,Y){var G=Y.method,re=ee.iterator[G];if(re===r)return Y.delegate=null,G==="throw"&&ee.iterator.return&&(Y.method="return",Y.arg=r,F(ee,Y),Y.method==="throw")||G!=="return"&&(Y.method="throw",Y.arg=new TypeError("The iterator does not provide a '"+G+"' method")),$;var ge=y(re,ee.iterator,Y.arg);if(ge.type==="throw")return Y.method="throw",Y.arg=ge.arg,Y.delegate=null,$;var be=ge.arg;if(!be)return Y.method="throw",Y.arg=new TypeError("iterator result is not an object"),Y.delegate=null,$;if(be.done)Y[ee.resultName]=be.value,Y.next=ee.nextLoc,Y.method!=="return"&&(Y.method="next",Y.arg=r);else return be;return Y.delegate=null,$}B(D),T(D,g,"Generator"),T(D,h,function(){return this}),T(D,"toString",function(){return"[object Generator]"});function Z(ee){var Y={tryLoc:ee[0]};1 in ee&&(Y.catchLoc=ee[1]),2 in ee&&(Y.finallyLoc=ee[2],Y.afterLoc=ee[3]),this.tryEntries.push(Y)}function U(ee){var Y=ee.completion||{};Y.type="normal",delete Y.arg,ee.completion=Y}function P(ee){this.tryEntries=[{tryLoc:"root"}],ee.forEach(Z,this),this.reset(!0)}n.keys=function(ee){var Y=Object(ee),G=[];for(var re in Y)G.push(re);return G.reverse(),function ge(){for(;G.length;){var be=G.pop();if(be in Y)return ge.value=be,ge.done=!1,ge}return ge.done=!0,ge}};function se(ee){if(ee){var Y=ee[h];if(Y)return Y.call(ee);if(typeof ee.next=="function")return ee;if(!isNaN(ee.length)){var G=-1,re=function ge(){for(;++G<ee.length;)if(o.call(ee,G))return ge.value=ee[G],ge.done=!1,ge;return ge.value=r,ge.done=!0,ge};return re.next=re}}return{next:it}}n.values=se;function it(){return{value:r,done:!0}}return P.prototype={constructor:P,reset:function(ee){if(this.prev=0,this.next=0,this.sent=this._sent=r,this.done=!1,this.delegate=null,this.method="next",this.arg=r,this.tryEntries.forEach(U),!ee)for(var Y in this)Y.charAt(0)==="t"&&o.call(this,Y)&&!isNaN(+Y.slice(1))&&(this[Y]=r)},stop:function(){this.done=!0;var ee=this.tryEntries[0],Y=ee.completion;if(Y.type==="throw")throw Y.arg;return this.rval},dispatchException:function(ee){if(this.done)throw ee;var Y=this;function G(le,ye){return be.type="throw",be.arg=ee,Y.next=le,ye&&(Y.method="next",Y.arg=r),!!ye}for(var re=this.tryEntries.length-1;re>=0;--re){var ge=this.tryEntries[re],be=ge.completion;if(ge.tryLoc==="root")return G("end");if(ge.tryLoc<=this.prev){var ke=o.call(ge,"catchLoc"),Re=o.call(ge,"finallyLoc");if(ke&&Re){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0);if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else if(ke){if(this.prev<ge.catchLoc)return G(ge.catchLoc,!0)}else if(Re){if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(ee,Y){for(var G=this.tryEntries.length-1;G>=0;--G){var re=this.tryEntries[G];if(re.tryLoc<=this.prev&&o.call(re,"finallyLoc")&&this.prev<re.finallyLoc){var ge=re;break}}ge&&(ee==="break"||ee==="continue")&&ge.tryLoc<=Y&&Y<=ge.finallyLoc&&(ge=null);var be=ge?ge.completion:{};return be.type=ee,be.arg=Y,ge?(this.method="next",this.next=ge.finallyLoc,$):this.complete(be)},complete:function(ee,Y){if(ee.type==="throw")throw ee.arg;return ee.type==="break"||ee.type==="continue"?this.next=ee.arg:ee.type==="return"?(this.rval=this.arg=ee.arg,this.method="return",this.next="end"):ee.type==="normal"&&Y&&(this.next=Y),$},finish:function(ee){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var G=this.tryEntries[Y];if(G.finallyLoc===ee)return this.complete(G.completion,G.afterLoc),U(G),$}},catch:function(ee){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var G=this.tryEntries[Y];if(G.tryLoc===ee){var re=G.completion;if(re.type==="throw"){var ge=re.arg;U(G)}return ge}}throw new Error("illegal catch attempt")},delegateYield:function(ee,Y,G){return this.delegate={iterator:se(ee),resultName:Y,nextLoc:G},this.method==="next"&&(this.arg=r),$}},n}(c.exports);try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}})(zT);var yh={exports:{}};(function(c){(function(t,n){c.exports?c.exports=n():t.log=n()})(Mt,function(){var t=function(){},n="undefined",a=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),o=["trace","debug","info","warn","error"];function s(C,I){var H=C[I];if(typeof H.bind=="function")return H.bind(C);try{return Function.prototype.bind.call(H,C)}catch{return function(){return Function.prototype.apply.apply(H,[C,arguments])}}}function r(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function d(C){return C==="debug"&&(C="log"),typeof console===n?!1:C==="trace"&&a?r:console[C]!==void 0?s(console,C):console.log!==void 0?s(console,"log"):t}function h(C,I){for(var H=0;H<o.length;H++){var $=o[H];this[$]=H<C?t:this.methodFactory($,C,I)}this.log=this.debug}function _(C,I,H){return function(){typeof console!==n&&(h.call(this,I,H),this[C].apply(this,arguments))}}function g(C,I,H){return d(C)||_.apply(this,arguments)}function T(C,I,H){var $=this,oe;I=I??"WARN";var N="loglevel";typeof C=="string"?N+=":"+C:typeof C=="symbol"&&(N=void 0);function j(D){var B=(o[D]||"silent").toUpperCase();if(!(typeof window===n||!N)){try{window.localStorage[N]=B;return}catch{}try{window.document.cookie=encodeURIComponent(N)+"="+B+";"}catch{}}}function Se(){var D;if(!(typeof window===n||!N)){try{D=window.localStorage[N]}catch{}if(typeof D===n)try{var B=window.document.cookie,V=B.indexOf(encodeURIComponent(N)+"=");V!==-1&&(D=/^([^;]+)/.exec(B.slice(V))[1])}catch{}return $.levels[D]===void 0&&(D=void 0),D}}function ve(){if(!(typeof window===n||!N)){try{window.localStorage.removeItem(N);return}catch{}try{window.document.cookie=encodeURIComponent(N)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}$.name=C,$.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},$.methodFactory=H||g,$.getLevel=function(){return oe},$.setLevel=function(D,B){if(typeof D=="string"&&$.levels[D.toUpperCase()]!==void 0&&(D=$.levels[D.toUpperCase()]),typeof D=="number"&&D>=0&&D<=$.levels.SILENT){if(oe=D,B!==!1&&j(D),h.call($,D,C),typeof console===n&&D<$.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+D},$.setDefaultLevel=function(D){I=D,Se()||$.setLevel(D,!1)},$.resetLevel=function(){$.setLevel(I,!1),ve()},$.enableAll=function(D){$.setLevel($.levels.TRACE,D)},$.disableAll=function(D){$.setLevel($.levels.SILENT,D)};var k=Se();k==null&&(k=I),$.setLevel(k,!1)}var E=new T,y={};E.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var H=y[I];return H||(H=y[I]=new T(I,E.getLevel(),E.methodFactory)),H};var A=typeof window!==n?window.log:void 0;return E.noConflict=function(){return typeof window!==n&&window.log===E&&(window.log=A),E},E.getLoggers=function(){return y},E.default=E,E})})(yh);var It=yh.exports;const Es=()=>`${new Date().toISOString()} | metrics`,Ss=(c,t,n)=>`${c} | ${t} | ${n}`;It.setDefaultLevel(It.levels.TRACE);const XT=c=>{It.info(Ss(Es(),"log ",`set log level to ${c?"verbose":"info"}`)),It.setLevel(c?It.levels.TRACE:It.levels.INFO)},QT=c=>{const t=[...Object.keys(It.levels)];t.includes(c)?(It.info(Ss(Es(),"log ",`update log level to ${c.toLowerCase()}`)),It.setLevel(c)):It.warn(Ss(Es(),"log ","Incorrect log level please choose one of "),t)},Pe=(c,t,n)=>{n?It.debug(Ss(Es(),c,t),n):It.debug(Ss(Es(),c,t))},Ru=(c,t)=>{It.info(Ss(Es(),c,t))},on=(c,t)=>{It.info(Ss(Es(),c,t))},Ca=(c,t)=>{It.warn(Ss(Es(),c,t))},Vn=(c,t)=>{It.error(Ss(Es(),c,t))};function ZT(c){return Math.floor(Math.random()*c).toString()}function Ah(c,t){let n=t;return c.forEach(a=>{n=n.replace(a,"")}),n}function ev(c,t){let n="";for(let a=0;a<t;a+=1)n+=c[ZT(c.length)];return n}function tv({length:c=20,useLetters:t=!0,useNumbers:n=!0,includeSymbols:a=[],excludeSymbols:o=[]}={}){let s="abcdefghijklmnopqrstuvwxyz",r="0123456789",d=[],h=[],_=[];return t&&(o.length&&(s=Ah(o,s)),h=s.split("")),n&&(o.length&&(r=Ah(o,r)),_=r.split("")),d=[...h,..._,...a],ev(d,c)}var sv=tv;const ri=Me(sv),nv=()=>"WebRTCMetrics",rv=()=>"5.0.3",$e={INBOUND:"inbound",OUTBOUND:"outbound"},ys={IDLE:"idle",RUNNING:"running",MUTED:"muted"},ii={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},iv=()=>({...{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:[]}}),Ch={level_in:0,codec_id_in:"",codec_in:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,mos_in:0,mos_emodel_in:0,ssrc:"",direction:$e.INBOUND},Rh={level_out:0,codec_id_out:"",codec_out:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,timestamp_out:null,mos_out:0,mos_emodel_out:0,ssrc:"",direction:$e.OUTBOUND},Ih={codec_id_in:"",size_in:{width:null,height:null,framerate:null},codec_in:{mime_type:null,clock_rate:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,decoder_in:null,delta_ms_decode_frame_in:0,total_frames_decoded_in:0,total_time_decoded_in:0,delta_nack_sent_in:0,delta_pli_sent_in:0,total_nack_sent_in:0,total_pli_sent_in:0,ssrc:"",direction:$e.INBOUND},bh={codec_id_out:"",size_out:{width:null,height:null,framerate:null},codec_out:{mime_type:null,clock_rate:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,encoder_out:null,delta_ms_encode_frame_out:0,total_time_encoded_out:0,total_frames_encoded_out:0,delta_nack_received_out:0,delta_pli_received_out:0,total_nack_received_out:0,total_pli_received_out:0,limitation_out:{reason:null,durations:null,resolutionChanges:0},timestamp_out:null,ssrc:"",direction:$e.OUTBOUND},lv=c=>{const t={pname:"",call_id:"",user_id:"",timestamp:null,count:0,audio:{},video:{},network:{infrastructure:3,local_candidate_id:"",local_candidate_type:"",local_candidate_protocol:"",local_candidate_relay_protocol:"",remote_candidate_id:"",remote_candidate_type:"",remote_candidate_protocol:""},data:{total_KBytes_in:0,total_KBytes_out:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,delta_kbs_bandwidth_in:0,delta_kbs_bandwidth_out:0,delta_rtt_connectivity_ms:null,total_rtt_connectivity_ms:0,total_rtt_connectivity_measure:0},experimental:{time_to_measure_ms:0}};if(c){const n={...c,audio:{},video:{},data:{...c.data},network:{...c.network},experimental:{...c.experimental}};return Object.keys(c.audio).forEach(a=>{n.audio[a]={...c.audio[a]}}),Object.keys(c.video).forEach(a=>{n.video[a]={...c.video[a]}}),n}return{...t,audio:{},video:{},data:{...t.data},network:{...t.network},experimental:{...t.experimental}}},av={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${ri()}`,cid:`c-${ri()}`,uid:`u-${ri()}`,record:!1,ticket:!0},Zt={CANDIDATE_PAIR:"candidate-pair",CODEC:"codec",INBOUND_RTP:"inbound-rtp",LOCAL_CANDIDATE:"local-candidate",MEDIA_SOURCE:"media-source",OUTBOUND_RTP:"outbound-rtp",REMOTE_CANDIDATE:"remote-candidate",REMOTE_INBOUND_RTP:"remote-inbound-rtp",TRACK:"track"},q={AUDIO_LEVEL:"audioLevel",AVAILABLE_OUTGOING_BITRATE:"availableOutgoingBitrate",AVAILABLE_INCOMING_BITRATE:"availableIncomingBitrate",BYTES_RECEIVED:"bytesReceived",BYTES_SENT:"bytesSent",CANDIDATE_TYPE:"candidateType",CHANNELS:"channels",CLOCK_RATE:"clockRate",CODEC_ID:"codecId",CURRENT_ROUND_TRIP_TIME:"currentRoundTripTime",ROUND_TRIP_TIME:"roundTripTime",FRACTION_LOST:"fractionLost",FRAME_HEIGHT:"frameHeight",FRAME_WIDTH:"frameWidth",QUALITY_LIMITATION_REASON:"qualityLimitationReason",QUALITY_LIMITATION_DURATIONS:"qualityLimitationDurations",QUALITY_LIMITATION_RESOLUTION_CHANGES:"qualityLimitationResolutionChanges",ID:"id",JITTER:"jitter",KIND:"kind",MEDIA_TYPE:"mediaType",MIME_TYPE:"mimeType",LOCAL_CANDIDATE_ID:"localCandidateId",NETWORK_TYPE:"networkType",RELAY_PROTOCOL:"relayProtocol",NOMINATED:"nominated",PACKETS_LOST:"packetsLost",PACKETS_RECEIVED:"packetsReceived",PACKETS_SENT:"packetsSent",PROTOCOL:"protocol",PORT:"port",REMOTE_CANDIDATE_ID:"remoteCandidateId",REMOTE_SOURCE:"remoteSource",RESPONSES_RECEIVED:"responsesReceived",SDP_FMTP_LINE:"sdpFmtpLine",SSRC:"ssrc",SELECTED:"selected",STATE:"state",TIMESTAMP:"timestamp",TOTAL_ROUND_TRIP_TIME:"totalRoundTripTime",TOTAL_ROUND_TRIP_TIME_MEASUREMENTS:"roundTripTimeMeasurements",TYPE:"type",DECODER_IMPLEMENTATION:"decoderImplementation",ENCODER_IMPLEMENTATION:"encoderImplementation",FRAMES_DECODED:"framesDecoded",FRAMES_ENCODED:"framesEncoded",FRAMES_PER_SECOND:"framesPerSecond",TOTAL_DECODE_TIME:"totalDecodeTime",TOTAL_ENCODE_TIME:"totalEncodeTime",PLI:"pliCount",NACK:"nackCount"},x={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},li={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},Iu={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ne={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},bu="config ",ov=(c,t={},n)=>{const a={...n,...t};return t.pname||Ca(bu,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${n.pname}'`),t.cid||Ca(bu,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${n.cid}'`),t.uid||Ca(bu,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${n.uid}'`),a.pc=c,a},uv=(c={})=>{const t={...av,...c};return t.name=nv(),t.version=rv(),t},ai=(c,t,n,a=!1,o)=>{let s=c.map(r=>{if(!n)return r[t];if(!o)return r[t][n];const d=r[t][o];return d?d[n]:null});return s=s.filter(r=>a?Number.isFinite(r)&&r>0:Number.isFinite(r)),s.length===0?[]:s},Ms=c=>c.reduce((t,n)=>t+n,0)/c.length,cv=()=>`probe-${ri()}`,fv=()=>`coltr-${ri()}`,wh=c=>new Promise(t=>setTimeout(t,c)),wu=(c,t,n)=>{t?c.call(t,n):c(n)},We=(c,t,n,a)=>{const o=ai(c,t,n,!0,a);if(o.length===0)return null;const s=o.reduce((_,g)=>_+g,0)/o.length;return s===0?null:o.map(_=>Math.abs(s-_)).reduce((_,g)=>_+g,0)/o.length*100/s},Xe=(c,t,n,a=!1,o)=>{const s=ai(c,t,n,a,o);return s.length===0?null:s.reduce((r,d)=>r+d,0)/s.length},un=(c,t,n)=>ai(c,t,n).reduce((o,s)=>o+s,0),Ke=(c,t,n,a)=>{const o=ai(c,t,n,!0,a);return o.length===0?null:Math.min(...o)},Ye=(c,t,n,a)=>{const o=ai(c,t,n,!1,a);return o.length===0?null:Math.max(...o)},At=(c,t,n,a)=>{const o=c.slice().pop();if(!o)return null;if(!n)return o[t];if(!a)return o[t][n];const s=o[t][a];return s?s[n]:null},hv=c=>c.slice().pop(),ht=(c,t,n)=>{if(!t)return null;const a={};let o=t[x.AUDIO][c];o||(o=n===$e.INBOUND?{...Ch}:{...Rh}),a[x.AUDIO]=o;let s=t[x.VIDEO][c];return s||(s=n===$e.INBOUND?{...Ih}:{...bh}),a[x.VIDEO]=s,a},oi="exporter ",dv="2.0",Oh=(c,t,n)=>{if(!c||c.length===0)return 0;const a=c[c.length-1];if(!a)return 0;const o=a[t][n];if(o){const s=o.total_rtt_ms_out,r=o.total_rtt_measure_out;return!r||!s?Xe(c,t,"delta_rtt_ms_out",!1,n):Number(s/r)}return null},_v=(c,t)=>{if(!c||c.length===0)return 0;const n=c[c.length-1];if(!n)return 0;const a=n[t].total_rtt_connectivity_ms,o=n[t].total_rtt_connectivity_measure;return!o||!a?Xe(c,t,"delta_rtt_connectivity_ms"):Number(a/o)},pv=c=>At(c,"network","local_candidate_type")!=="relay"?`direct/${At(c,"network","local_candidate_protocol")}`:`turn/${At(c,"network","local_candidate_relay_protocol")}`,mv=c=>{const t=At(c,"network","remote_candidate_type"),n=At(c,"network","remote_candidate_protocol");return t!=="relay"?`direct/${n}`:`turn/${n}`};class gv{constructor(t){this._start=null,this._end=null,this._cfg=t,this._referenceReport=null,this._reports=[],this._events=[]}start(){Ru(oi,"start() - start exporter...");const t=new Date;return this._start=t.toJSON(),t}stop(){Ru(oi,"stop() - stop exporter...");const t=new Date;return this._end=t.toJSON(),t}saveReferenceReport(t){this._referenceReport=t}getReferenceReport(){return this._referenceReport}addReport(t){this._cfg.ticket&&(Pe(oi,`addReport() - add report to exporter at ${t.timestamp}`),this._reports.push(t))}addCustomEvent(t){this._events.push(t)}reset(){Ru(oi,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Pe(oi,"ticket() - generate ticket");const t=At(this._reports,"audio","total_packets_lost_in"),n=At(this._reports,"audio","total_packets_in"),a=At(this._reports,"video","total_packets_lost_in"),o=At(this._reports,"video","total_packets_in"),s={},r=hv(this._reports);return r&&(Object.keys(r[x.AUDIO]).forEach(d=>{const h=r[x.AUDIO][d];if(s[h.ssrc]={type:x.AUDIO,direction:h.direction},h.direction===$e.INBOUND){const _={avg:Xe(this._reports,x.AUDIO,"delta_jitter_ms_in",!1,d),min:Ke(this._reports,x.AUDIO,"delta_jitter_ms_in",d),max:Ye(this._reports,x.AUDIO,"delta_jitter_ms_in",d),volatility:We(this._reports,x.AUDIO,"delta_jitter_ms_in",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.AUDIO,"delta_kbs_in",!1,d),min:Ke(this._reports,x.AUDIO,"delta_kbs_in",d),max:Ye(this._reports,x.AUDIO,"delta_kbs_in",d),volatility:We(this._reports,x.AUDIO,"delta_kbs_in",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.AUDIO,"delta_KBytes_in",!1,d),min:Ke(this._reports,x.AUDIO,"delta_KBytes_in",d),max:Ye(this._reports,x.AUDIO,"delta_KBytes_in",d),volatility:We(this._reports,x.AUDIO,"delta_KBytes_in",d),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={emodel:{avg:Xe(this._reports,x.AUDIO,"mos_emodel_in",!1,d),min:Ke(this._reports,x.AUDIO,"mos_emodel_in",d),max:Ye(this._reports,x.AUDIO,"mos_emodel_in",d),volatility:We(this._reports,x.AUDIO,"mos_emodel_in",d)},effective:{avg:Xe(this._reports,x.AUDIO,"mos_in",!1,d),min:Ke(this._reports,x.AUDIO,"mos_in",d),max:Ye(this._reports,x.AUDIO,"mos_in",d),volatility:We(this._reports,x.AUDIO,"mos_in",d)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},y=At(this._reports,x.AUDIO,"total_packets_lost_in",d),A=At(this._reports,x.AUDIO,"total_packets_in",d),C={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[d].jitter=_,s[d].mos=E,s[d].traffic=T,s[d].bitrate=g,s[d].loss=C}else{const _={avg:Xe(this._reports,x.AUDIO,"delta_jitter_ms_out",!1,d),min:Ke(this._reports,x.AUDIO,"delta_jitter_ms_out",d),max:Ye(this._reports,x.AUDIO,"delta_jitter_ms_out",d),volatility:We(this._reports,x.AUDIO,"delta_jitter_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.AUDIO,"delta_kbs_out",!1,d),min:Ke(this._reports,x.AUDIO,"delta_kbs_out",d),max:Ye(this._reports,x.AUDIO,"delta_kbs_out",d),volatility:We(this._reports,x.AUDIO,"delta_kbs_out",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.AUDIO,"delta_KBytes_out",!1,d),min:Ke(this._reports,x.AUDIO,"delta_KBytes_out",d),max:Ye(this._reports,x.AUDIO,"delta_KBytes_out",d),volatility:We(this._reports,x.AUDIO,"delta_KBytes_out",d),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},E={avg:Oh(this._reports,x.AUDIO,d),min:Ke(this._reports,x.AUDIO,"delta_rtt_ms_out",d),max:Ye(this._reports,x.AUDIO,"delta_rtt_ms_out",d),volatility:We(this._reports,x.AUDIO,"delta_rtt_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=At(this._reports,x.AUDIO,"total_packets_lost_out",d),A=At(this._reports,x.AUDIO,"total_packets_out",d),C={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},I={emodel:{avg:Xe(this._reports,x.AUDIO,"mos_emodel_out",!1,d),min:Ke(this._reports,x.AUDIO,"mos_emodel_out",d),max:Ye(this._reports,x.AUDIO,"mos_emodel_out",d),volatility:We(this._reports,x.AUDIO,"mos_emodel_out",d)},effective:{avg:Xe(this._reports,x.AUDIO,"mos_out",!1,d),min:Ke(this._reports,x.AUDIO,"mos_out",d),max:Ye(this._reports,x.AUDIO,"mos_out",d),volatility:We(this._reports,x.AUDIO,"mos_out",d)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};s[d].jitter=_,s[d].rtt=E,s[d].traffic=T,s[d].bitrate=g,s[d].loss=C,s[d].mos=I}}),Object.keys(r[x.VIDEO]).forEach(d=>{const h=r[x.VIDEO][d];if(s[d]={type:x.VIDEO,direction:h.direction},h.direction===$e.INBOUND){const _={avg:Xe(this._reports,x.VIDEO,"delta_jitter_ms_in",!1,d),min:Ke(this._reports,x.VIDEO,"delta_jitter_ms_in",d),max:Ye(this._reports,x.VIDEO,"delta_jitter_ms_in",d),volatility:We(this._reports,x.VIDEO,"delta_jitter_ms_in",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.VIDEO,"delta_kbs_in",!1,d),min:Ke(this._reports,x.VIDEO,"delta_kbs_in",d),max:Ye(this._reports,x.VIDEO,"delta_kbs_in",d),volatility:We(this._reports,x.VIDEO,"delta_kbs_in",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.VIDEO,"delta_KBytes_in",!1,d),min:Ke(this._reports,x.VIDEO,"delta_KBytes_in",d),max:Ye(this._reports,x.VIDEO,"delta_KBytes_in",d),volatility:We(this._reports,x.VIDEO,"delta_KBytes_in",d),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E=At(this._reports,x.VIDEO,"total_packets_lost_in",d),y=At(this._reports,x.VIDEO,"total_packets_in",d),A={lost:E,avg:Math.round((E/(E+y)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[d].jitter=_,s[d].traffic=T,s[d].bitrate=g,s[d].loss=A}else{const _={avg:Xe(this._reports,x.VIDEO,"delta_jitter_ms_out",!1,d),min:Ke(this._reports,x.VIDEO,"delta_jitter_ms_out",d),max:Ye(this._reports,x.VIDEO,"delta_jitter_ms_out",d),volatility:We(this._reports,x.VIDEO,"delta_jitter_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Xe(this._reports,x.VIDEO,"delta_kbs_out",!1,d),min:Ke(this._reports,x.VIDEO,"delta_kbs_out",d),max:Ye(this._reports,x.VIDEO,"delta_kbs_out",d),volatility:We(this._reports,x.VIDEO,"delta_kbs_out",d),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,x.VIDEO,"delta_KBytes_out",!1,d),min:Ke(this._reports,x.VIDEO,"delta_KBytes_out",d),max:Ye(this._reports,x.VIDEO,"delta_KBytes_out",d),volatility:We(this._reports,x.VIDEO,"delta_KBytes_out",d),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={avg:Oh(this._reports,x.VIDEO,d),min:Ke(this._reports,x.VIDEO,"delta_rtt_ms_out",d),max:Ye(this._reports,x.VIDEO,"delta_rtt_ms_out",d),volatility:We(this._reports,x.VIDEO,"delta_rtt_ms_out",d),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=At(this._reports,x.VIDEO,"total_packets_lost_out",d),A=At(this._reports,x.VIDEO,"total_packets_out",d),C={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[d].jitter=_,s[d].rtt=E,s[d].traffic=T,s[d].bitrate=g,s[d].loss=C}})),{version:dv,configuration:{frequency:this._cfg.refreshEvery},started:this._start,ended:this._end,ua:{agent:navigator.userAgent,pname:this._cfg.pname,user_id:this._cfg.uid},call:{call_id:this._cfg.cid,events:this._events},details:{count:this._reports.length,reports:this._cfg.record?this._reports:[],reference:this._referenceReport||null},ssrc:s,data:{rtt:{avg:_v(this._reports,"data"),min:Ke(this._reports,"data","delta_rtt_connectivity_ms"),max:Ye(this._reports,"data","delta_rtt_connectivity_ms"),volatility:We(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((t/(t+n)*100||0)*100)/100}},video:{in:{avg:Math.round((a/(a+o)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:Xe(this._reports,"data","delta_kbs_in"),min:Ke(this._reports,"data","delta_kbs_in"),max:Ye(this._reports,"data","delta_kbs_in"),volatility:We(this._reports,"data","delta_kbs_in")},out:{avg:Xe(this._reports,"data","delta_kbs_out"),min:Ke(this._reports,"data","delta_kbs_out"),max:Ye(this._reports,"data","delta_kbs_out"),volatility:We(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:Xe(this._reports,"data","delta_KBytes_in"),min:Ke(this._reports,"data","delta_KBytes_in"),max:Ye(this._reports,"data","delta_KBytes_in"),volatility:We(this._reports,"data","delta_KBytes_in")},out:{avg:Xe(this._reports,"data","delta_KBytes_out"),min:Ke(this._reports,"data","delta_KBytes_out"),max:Ye(this._reports,"data","delta_KBytes_out"),volatility:We(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:pv(this._reports),remoteConnection:mv(this._reports)}}}}updateConfig(t){this._cfg=t}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const t=this._reports.slice();return t.pop(),t.pop()||null}getReportsNumber(){return this._reports.length}}const Ls="extractor ",Dh=(c,t,n,a)=>{let o=!1;const s=a[t].total_rtt_ms_out,r=a[t].total_rtt_measure_out,d=n?n[t].total_rtt_ms_out:0,h=n?n[t].total_rtt_measure_out:0,_={rtt:null,totalRTT:s,totalRTTMeasurements:r};if(c[q.TIMESTAMP]===a[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,q.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(o=!0,Number(c[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-h===r))return _;const g=1e3*Number(c[q.ROUND_TRIP_TIME]);let T=s+g,E=r+1;return o&&(T=1e3*Number(c[q.TOTAL_ROUND_TRIP_TIME])-d,E=Number(c[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-h),{rtt:g,totalRTT:T,totalRTTMeasurements:E}},Tv=(c,t,n,a)=>{if(!Object.prototype.hasOwnProperty.call(c,q.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:a[t].total_rtt_connectivity_ms,totalRTTMeasurements:a[t].total_rtt_connectivity_measure};const o=1e3*Number(c[q.CURRENT_ROUND_TRIP_TIME]);let s=a[t].total_rtt_connectivity_ms+o,r=a[t].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,q.TOTAL_ROUND_TRIP_TIME)&&(s=1e3*Number(c[q.TOTAL_ROUND_TRIP_TIME])-(n?n[t].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,q.RESPONSES_RECEIVED)&&(r=Number(c[q.RESPONSES_RECEIVED])-(n?n[t].total_rtt_connectivity_measure:0)),{rtt:o,totalRTT:s,totalRTTMeasurements:r}},Ra=(c,t,n)=>c[q.TIMESTAMP]===n[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,q.JITTER)?null:1e3*(Number(c[q.JITTER])||0),vv=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,q.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,q.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:t[x.VIDEO].delta_ms_decode_frame_in,frames_decoded:t[x.VIDEO].total_frames_decoded_in,total_decode_time:t[x.VIDEO].total_time_decoded_in};const n=c[q.FRAMES_DECODED],a=c[q.TOTAL_DECODE_TIME],o=a-t[x.VIDEO].total_time_decoded_in,s=n-t[x.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:s>0?o*1e3/s:0,frames_decoded:n,total_decode_time:a}},Ev=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,q.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,q.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:t[x.VIDEO].delta_ms_encode_frame_out,frames_encoded:t[x.VIDEO].total_frames_encoded_out,total_encode_time:t[x.VIDEO].total_time_encoded_out};const n=c[q.FRAMES_ENCODED],a=c[q.TOTAL_ENCODE_TIME],o=a-t[x.VIDEO].total_time_encoded_out,s=n-t[x.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:s>0&&o?o*1e3/s:0,frames_encoded:n,total_encode_time:a}},Nh=(c,t,n,a)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,q.BYTES_SENT))return{packetsSent:n[t].total_packets_out,packetsLost:n[t].total_packets_lost_out,bytesSent:n[t].total_KBytes_out};const o=Number(c[q.PACKETS_SENT])||0-(a?a[t].total_packets_out:0),s=o-n[t].total_packets_out,r=Number(c[q.BYTES_SENT])/1024-(a?a[t].total_KBytes_out:0),d=r-n[t].total_KBytes_out,h=c[q.TIMESTAMP]||Date.now(),_=a?a.timestamp:null;let g=n.timestamp;!g&&_&&(g=_);const T=g?h-g:0,E=T>0?d*.008*1024/T*1e3:0;return{packetsSent:o,deltaPacketsSent:s,KBytesSent:r,deltaKBytesSent:d,kbsSent:E}},Uh=(c,t,n,a)=>{let o=n[t].total_packets_lost_out,s=0,r=0;return Object.prototype.hasOwnProperty.call(c,q.PACKETS_LOST)&&(o=Number(c[q.PACKETS_LOST])||0-(a?a[t].total_packets_lost_out:0),s=o-n[t].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,q.FRACTION_LOST)&&(r=Number(100*c[q.FRACTION_LOST])),{packetsLost:o,deltaPacketsLost:s,fractionLost:r}},Ph=(c,t,n,a)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,q.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,q.BYTES_RECEIVED))return{percent_packets_lost:n[t].percent_packets_lost_in,packetsReceived:n[t].total_packets_in,packetsLost:n[t].total_packets_lost_in,bytesReceived:n[t].total_KBytes_in};const o=Number(c[q.PACKETS_RECEIVED])||0-(a?a[t].total_packets_in:0),s=Number(c[q.PACKETS_LOST])||0-(a?a[t].total_packets_lost_in:0),r=s-n[t].total_packets_lost_in,d=o-n[t].total_packets_in,h=o!==n[t].total_packets_in?r*100/(r+d):0,_=Number(c[q.BYTES_RECEIVED])/1024-(a?a[t].total_KBytes_in:0),g=_-n[t].total_KBytes_in,T=c[q.TIMESTAMP]||Date.now(),E=a?a.timestamp:null;let y=n.timestamp;!y&&E&&(y=E);const A=y?T-y:0,C=A>0?g*.008*1024/A*1e3:0;return{percentPacketsLost:h,packetsReceived:o,deltaPacketsReceived:d,packetsLost:s,deltaPacketsLost:r,KBytesReceived:_,deltaKBytesReceived:g,kbsReceived:C}},Sv=c=>c[q.CANDIDATE_TYPE]!=="relay"?"":c[q.RELAY_PROTOCOL]||"",yv=c=>{if(!Object.prototype.hasOwnProperty.call(c,q.NETWORK_TYPE))return li.WIFI;switch(c[q.NETWORK_TYPE]){case Iu.ETHERNET:return li.ETHERNET;case Iu.CELLULAR_4G:return li.CELLULAR_4G;case Iu.WIFI:return li.WIFI;default:return li.CELLULAR}},xh=c=>!Object.prototype.hasOwnProperty.call(c,q.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,q.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[q.FRAME_WIDTH]||null,height:c[q.FRAME_HEIGHT]||null,framerate:c[q.FRAMES_PER_SECOND]},Av=c=>{const t=Object.prototype.hasOwnProperty.call(c,q.QUALITY_LIMITATION_REASON)?c[q.QUALITY_LIMITATION_REASON]:null,n=Object.prototype.hasOwnProperty.call(c,q.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[q.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,a=Object.prototype.hasOwnProperty.call(c,q.QUALITY_LIMITATION_DURATIONS)?c[q.QUALITY_LIMITATION_DURATIONS]:null;return a&&Object.keys(a).forEach(o=>{a[o]>1e3&&(a[o]=Number(a[o]/1e3))}),{reason:t,durations:a,resolutionChanges:n}},Cv=(c,t,n)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PLI)||!Object.prototype.hasOwnProperty.call(c,q.NACK))return{pliCount:t.total_pli_sent_in,nackCount:t.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const a=(c[q.PLI]||0)-(n?n[x.VIDEO].total_pli_sent_in:0),o=(c[q.NACK]||0)-(n?n[x.VIDEO].total_nack_sent_in:0);return{pliCount:a,nackCount:o,deltaPliCount:a-t[x.VIDEO].total_pli_sent_in,deltaNackCount:o-t[x.VIDEO].total_nack_sent_in}},Rv=(c,t,n)=>{if(!Object.prototype.hasOwnProperty.call(c,q.PLI)||!Object.prototype.hasOwnProperty.call(c,q.NACK))return{pliCount:t.total_pli_received_out,nackCount:t.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const a=(c[q.PLI]||0)-(n?n[x.VIDEO].total_pli_received_out:0),o=(c[q.NACK]||0)-(n?n[x.VIDEO].total_nack_received_out:0);return{pliCount:a,nackCount:o,deltaPliCount:a-t[x.VIDEO].total_pli_received_out,deltaNackCount:o-t[x.VIDEO].total_nack_received_out}},Iv=c=>({channels:c[q.CHANNELS]||null,clock_rate:c[q.CLOCK_RATE]||null,mime_type:c[q.MIME_TYPE]||null,sdp_fmtp_line:c[q.SDP_FMTP_LINE]||null}),bv=c=>({clock_rate:c[q.CLOCK_RATE]||null,mime_type:c[q.MIME_TYPE]||null}),wv=(c,t,n)=>{const a=(c[q.BYTES_RECEIVED]||0)/1024-(n?n.data.total_KBytes_in:0),o=(c[q.BYTES_SENT]||0)/1024-(n?n.data.total_KBytes_out:0),s=c[q.TIMESTAMP]||Date.now(),r=a-t.data.total_KBytes_in,d=o-t.data.total_KBytes_out,h=n?n.timestamp:null;let _=t.timestamp;!_&&h&&(_=h);const g=_?s-_:0,T=g>0?r*.008*1024/g*1e3:0,E=g>0?d*.008*1024/g*1e3:0;return{total_KBytes_received:a,total_KBytes_sent:o,delta_KBytes_received:r,delta_KBytes_sent:d,kbs_speed_received:T,kbs_speed_sent:E}},Ov=c=>{const t=c[q.AVAILABLE_INCOMING_BITRATE]/1024||0,n=c[q.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:t,kbs_outgoing_bandwidth:n}},Dv=(c,t,n,a)=>{if(!c)return[];switch(c[q.TYPE]){case Zt.CANDIDATE_PAIR:let o=!1;if(c[q.NOMINATED]&&c[q.STATE]===x.SUCCEEDED&&(o=!0,Pe(Ls,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c),q.SELECTED in c&&!c[q.SELECTED]&&(o=!1)),o){const r=c[q.LOCAL_CANDIDATE_ID],d=c[q.REMOTE_CANDIDATE_ID],h=wv(c,t,a),_=Ov(c),g=Tv(c,"data",a,t);return[{type:ne.NETWORK,value:{local_candidate_id:r}},{type:ne.NETWORK,value:{remote_candidate_id:d}},{type:ne.DATA,value:{total_KBytes_in:h.total_KBytes_received}},{type:ne.DATA,value:{total_KBytes_out:h.total_KBytes_sent}},{type:ne.DATA,value:{delta_KBytes_in:h.delta_KBytes_received}},{type:ne.DATA,value:{delta_KBytes_out:h.delta_KBytes_sent}},{type:ne.DATA,value:{delta_kbs_in:h.kbs_speed_received}},{type:ne.DATA,value:{delta_kbs_out:h.kbs_speed_sent}},{type:ne.DATA,value:{delta_kbs_bandwidth_in:_.kbs_incoming_bandwidth}},{type:ne.DATA,value:{delta_kbs_bandwidth_out:_.kbs_outgoing_bandwidth}},{type:ne.DATA,value:{delta_rtt_connectivity_ms:g.rtt}},{type:ne.DATA,value:{total_rtt_connectivity_ms:g.totalRTT}},{type:ne.DATA,value:{total_rtt_connectivity_measure:g.totalRTTMeasurements}}]}break;case Zt.LOCAL_CANDIDATE:if(c[q.ID]===t.network.local_candidate_id)return[{type:ne.NETWORK,value:{infrastructure:yv(c)}},{type:ne.NETWORK,value:{local_candidate_type:c[q.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{local_candidate_protocol:c[q.PROTOCOL]||""}},{type:ne.NETWORK,value:{local_candidate_relay_protocol:Sv(c)}}];break;case Zt.REMOTE_CANDIDATE:if(c[q.ID]===t.network.remote_candidate_id)return[{type:ne.NETWORK,value:{remote_candidate_type:c[q.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{remote_candidate_protocol:c[q.PROTOCOL]||""}}];break;case Zt.INBOUND_RTP:{Pe(Ls,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const r=c[q.SSRC],d=ht(r,t,$e.INBOUND);d&&(d.timestamp=t.timestamp);const h=ht(r,a,$e.INBOUND);if(h&&(h.timestamp=a.timestamp),c[q.MEDIA_TYPE]===x.AUDIO){const _=Ph(c,x.AUDIO,d,h),g=Ra(c,x.AUDIO,d),T=c[q.CODEC_ID]||"";return[{ssrc:r,type:ne.AUDIO,value:{codec_id_in:T}},{ssrc:r,type:ne.AUDIO,value:{total_packets_in:_.packetsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_in:_.deltaPacketsReceived}},{ssrc:r,type:ne.AUDIO,value:{total_packets_lost_in:_.packetsLost}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_lost_in:_.deltaPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{percent_packets_lost_in:_.percentPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{total_KBytes_in:_.KBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_KBytes_in:_.deltaKBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_kbs_in:_.kbsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_in:g}}]}if(c[q.MEDIA_TYPE]===x.VIDEO){const _=vv(c,d),g=Ph(c,x.VIDEO,d,h),T=Ra(c,x.VIDEO,d),E=c[q.DECODER_IMPLEMENTATION]||null,y=c[q.CODEC_ID]||null,A=xh(c),C=Cv(c,d,h);return[{ssrc:r,type:ne.VIDEO,value:{codec_id_in:y}},{ssrc:r,type:ne.VIDEO,value:{total_packets_in:g.packetsReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_in:g.deltaPacketsReceived}},{ssrc:r,type:ne.VIDEO,value:{total_packets_lost_in:g.packetsLost}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_lost_in:g.deltaPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{percent_packets_lost_in:g.percentPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{total_KBytes_in:g.KBytesReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_KBytes_in:g.deltaKBytesReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_kbs_in:g.kbsReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_jitter_ms_in:T}},{ssrc:r,type:ne.VIDEO,value:{decoder_in:E}},{ssrc:r,type:ne.VIDEO,value:{delta_ms_decode_frame_in:_.delta_ms_decode_frame}},{ssrc:r,type:ne.VIDEO,value:{total_frames_decoded_in:_.frames_decoded}},{ssrc:r,type:ne.VIDEO,value:{total_time_decoded_in:_.total_decode_time}},{ssrc:r,type:ne.VIDEO,value:{total_nack_sent_in:C.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_sent_in:C.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_sent_in:C.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_sent_in:C.deltaPliCount}},{ssrc:r,type:ne.VIDEO,value:{size_in:A}}]}break}case Zt.OUTBOUND_RTP:{Pe(Ls,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const r=c[q.SSRC],d=ht(r,t,$e.OUTBOUND);d&&(d.timestamp=t.timestamp);const h=ht(r,a,$e.OUTBOUND);if(h&&(h.timestamp=a.timestamp),c[q.MEDIA_TYPE]===x.AUDIO){const _=c[q.CODEC_ID]||null,g=Nh(c,x.AUDIO,d,h);return[{ssrc:r,type:ne.AUDIO,value:{codec_id_out:_}},{ssrc:r,type:ne.AUDIO,value:{total_packets_out:g.packetsSent}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_out:g.deltaPacketsSent}},{ssrc:r,type:ne.AUDIO,value:{total_KBytes_out:g.KBytesSent}},{ssrc:r,type:ne.AUDIO,value:{delta_KBytes_out:g.deltaKBytesSent}},{ssrc:r,type:ne.AUDIO,value:{delta_kbs_out:g.kbsSent}}]}if(c[q.MEDIA_TYPE]===x.VIDEO){const _=c[q.ENCODER_IMPLEMENTATION]||null,g=c[q.CODEC_ID]||null,T=Ev(c,d),E=xh(c),y=Av(c),A=Rv(c,d,h),C=Nh(c,x.VIDEO,d,h);return[{ssrc:r,type:ne.VIDEO,value:{codec_id_out:g}},{ssrc:r,type:ne.VIDEO,value:{total_packets_out:C.packetsSent}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_out:C.deltaPacketsSent}},{ssrc:r,type:ne.VIDEO,value:{total_KBytes_out:C.KBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_KBytes_out:C.deltaKBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_kbs_out:C.kbsSent}},{ssrc:r,type:ne.VIDEO,value:{encoder_out:_}},{ssrc:r,type:ne.VIDEO,value:{delta_ms_encode_frame_out:T.delta_ms_encode_frame}},{ssrc:r,type:ne.VIDEO,value:{total_frames_encoded_out:T.frames_encoded}},{ssrc:r,type:ne.VIDEO,value:{total_time_encoded_out:T.total_encode_time}},{ssrc:r,type:ne.VIDEO,value:{total_nack_received_out:A.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_received_out:A.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_received_out:A.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_received_out:A.deltaPliCount}},{ssrc:r,type:ne.VIDEO,value:{size_out:E}},{ssrc:r,type:ne.VIDEO,value:{limitation_out:y}}]}break}case Zt.MEDIA_SOURCE:{Pe(Ls,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);break}case Zt.TRACK:{Pe(Ls,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);break}case Zt.CODEC:const s=[];return Object.keys(t[x.AUDIO]).forEach(r=>{const d=t[x.AUDIO][r];if(d.codec_id_in===c[q.ID]||d.codec_id_out===c[q.ID]){Pe(Ls,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const h=Iv(c);c[q.ID]===d.codec_id_in?s.push({ssrc:d.ssrc,type:ne.AUDIO,value:{codec_in:h}}):s.push({ssrc:d.ssrc,type:ne.AUDIO,value:{codec_out:h}})}}),Object.keys(t[x.VIDEO]).forEach(r=>{const d=t[x.VIDEO][r];if(d.codec_id_in===c[q.ID]||d.codec_id_out===c[q.ID]){Pe(Ls,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const h=bv(c);c[q.ID]===d.codec_id_in?s.push({ssrc:d.ssrc,type:ne.VIDEO,value:{codec_in:h}}):s.push({ssrc:d.ssrc,type:ne.VIDEO,value:{codec_out:h}})}}),s;case Zt.REMOTE_INBOUND_RTP:{Pe(Ls,`analyze() - got stats ${c[q.TYPE]} for ${n}`,c);const r=c[q.SSRC],d=ht(r,t,$e.OUTBOUND),h=ht(r,a,$e.OUTBOUND);if(c[q.KIND]===x.AUDIO){const _=Dh(c,x.AUDIO,h,d),g=Ra(c,x.AUDIO,d),T=Uh(c,x.AUDIO,d,h);return[{ssrc:r,type:ne.AUDIO,value:{delta_rtt_ms_out:_.rtt}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_ms_out:_.totalRTT}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_measure_out:_.totalRTTMeasurements}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_out:g}},{ssrc:r,type:ne.AUDIO,value:{timestamp_out:c[q.TIMESTAMP]}},{ssrc:r,type:ne.AUDIO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{percent_packets_lost_out:T.fractionLost}}]}if(c[q.KIND]===x.VIDEO){const _=Dh(c,x.VIDEO,h,d),g=Ra(c,x.VIDEO,d),T=Uh(c,x.VIDEO,d,h);return[{ssrc:r,type:ne.VIDEO,value:{delta_rtt_ms_out:_.rtt}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_ms_out:_.totalRTT}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_measure_out:_.totalRTTMeasurements}},{ssrc:r,type:ne.VIDEO,value:{delta_jitter_ms_out:g}},{ssrc:r,type:ne.VIDEO,value:{timestamp_out:c[q.TIMESTAMP]}},{ssrc:r,type:ne.VIDEO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{percent_packets_lost_out:T.fractionLost}}]}break}}return[]},Ia=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),Nv=(c,t=x.AUDIO,n,a,o)=>{const s=ht(o,c,$e.INBOUND),r=ht(o,n,$e.INBOUND),d=ht(o,a,$e.INBOUND),h=[],_=[],g=s[t].percent_packets_lost_in,T=s[t].delta_jitter_ms_in,E=r&&r[t].delta_jitter_ms_in||null,y=d&&d[t].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,C=n&&n.data.delta_rtt_connectivity_ms||null,I=a&&a.data.delta_rtt_connectivity_ms||null;A&&h.push(A),C&&h.push(C),I&&h.push(I),T&&_.push(T),n&&E&&_.push(E),a&&y&&_.push(y);const H=h.length>0?Ms(h):100,$=_.length>0?Ms(_):10,oe=93.2-g,N=.18*oe*oe-27.9*oe+1126.62,j=(H+$)/2,Se=j-177.3<0?0:1,ve=.024*j+.11*(j-177.3)*Se,k=N-ve;return Ia(k)},Uv=(c,t=x.AUDIO,n,a,o)=>{const s=ht(o,c,$e.OUTBOUND),r=ht(o,n,$e.OUTBOUND),d=ht(o,a,$e.OUTBOUND),h=[],_=[],g=s[t].percent_packets_lost_out,T=s[t].delta_rtt_ms_out,E=r&&r[t].delta_rtt_ms_out||null,y=d&&d[t].delta_rtt_ms_out||null,A=s[t].delta_jitter_ms_out,C=r&&r[t].delta_jitter_ms_out||null,I=d&&d[t].delta_jitter_ms_out||null,H=c.data.delta_rtt_connectivity_ms,$=n&&n.data.delta_rtt_connectivity_ms||null,oe=a&&a.data.delta_rtt_connectivity_ms||null;T?h.push(T):H&&h.push(H),E?h.push(E):$&&h.push($),y?h.push(y):oe&&h.push(oe),A&&_.push(A),n&&C&&_.push(C),a&&I&&_.push(I);const N=h.length>0?Ms(h):100,j=_.length>0?Ms(_):10,Se=93.2-g,ve=.18*Se*Se-27.9*Se+1126.62,k=(N+j)/2,D=k-177.3<0?0:1,B=.024*k+.11*(k-177.3)*D,V=ve-B;return Ia(V)},Pv=(c,t=x.AUDIO,n,a,o)=>{const s=ht(o,c,$e.INBOUND),r=ht(o,n,$e.INBOUND),d=ht(o,a,$e.INBOUND),h=[],_=[],g=s[t].percent_packets_lost_in/100,T=s[t].delta_jitter_ms_in,E=r&&r[t].delta_jitter_ms_in||null,y=d&&d[t].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,C=n&&n.data.delta_rtt_connectivity_ms||null,I=a&&a.data.delta_rtt_connectivity_ms||null;A&&h.push(A),C&&h.push(C),I&&h.push(I),T&&_.push(T),r&&E&&_.push(E),d&&y&&_.push(y);const H=h.length>0?Ms(h):100,$=_.length>0?Ms(_):10,oe=0,N=19.8,j=29.7,Se=30,ve=(H+$)/2+Se,k=ve-177.3<0?0:1,D=.024*ve+.11*(ve-177.3)*k,V=93.2-(oe+N*Math.log(1+j*g)+D);return Ia(V)},xv=(c,t=x.AUDIO,n,a,o)=>{const s=ht(o,c,$e.OUTBOUND),r=ht(o,n,$e.OUTBOUND),d=ht(o,a,$e.OUTBOUND),h=[],_=[],g=s[t].percent_packets_lost_out/100,T=s[t].delta_rtt_ms_out,E=r&&r[t].delta_rtt_ms_out||null,y=d&&d[t].delta_rtt_ms_out||null,A=s[t].delta_jitter_ms_out,C=r&&r[t].delta_jitter_ms_out||null,I=d&&d[t].delta_jitter_ms_out||null,H=c.data.delta_rtt_connectivity_ms,$=n&&n.data.delta_rtt_connectivity_ms||null,oe=a&&a.data.delta_rtt_connectivity_ms||null;T?h.push(T):H&&h.push(H),E?h.push(E):$&&h.push($),y?h.push(y):oe&&h.push(oe),A&&_.push(A),r&&C&&_.push(C),d&&I&&_.push(I);const N=h.length>0?Ms(h):100,j=_.length>0?Ms(_):10,Se=0,ve=19.8,k=29.7,D=30,B=(N+j)/2+D,V=B-177.3<0?0:1,J=.024*B+.11*(B-177.3)*V,Z=93.2-(Se+ve*Math.log(1+k*g)+J);return Ia(Z)};class kv{constructor(t,n){this._callbacks={onreport:null,onticket:null},this._id=fv(),this._moduleName=this._id,this._probeId=n,this._config=t,this._exporter=new gv(t),this._state=ys.IDLE,this.registerToPCEvents(),on(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(t,n,a,o){const s=(h,_)=>h===x.AUDIO?_===Zt.INBOUND_RTP?{...Ch}:{...Rh}:_===Zt.INBOUND_RTP?{...Ih}:{...bh},r=lv(n);r.pname=this._config.pname,r.call_id=this._config.cid,r.user_id=this._config.uid,r.count=n?n.count+1:1;let d=null;return t.forEach(h=>{!d&&h.timestamp&&(d=h.timestamp),Dv(h,r,r.pname,o).forEach(g=>{if(g.value&&g.type)if(g.ssrc){let T=r[g.type][g.ssrc];T||(T=s(g.type,h.type),T.ssrc=g.ssrc,r[g.type][g.ssrc]=T),Object.keys(g.value).forEach(E=>{T[E]=g.value[E]})}else Object.keys(g.value).forEach(T=>{r[g.type][T]=g.value[T]})})}),r.timestamp=d,Object.keys(r[x.AUDIO]).forEach(h=>{const _=r[x.AUDIO][h];_.direction===$e.INBOUND?(_.mos_emodel_in=Nv(r,x.AUDIO,n,a,_.ssrc),_.mos_in=Pv(r,x.AUDIO,n,a,_.ssrc)):(_.mos_emodel_out=Uv(r,x.AUDIO,n,a,_.ssrc),_.mos_out=xv(r,x.AUDIO,n,a,_.ssrc))}),r}async takeReferenceStats(){return new Promise((t,n)=>{const a=Date.now();setTimeout(async()=>{try{const o=Date.now()-a,s=Date.now(),r=await this._config.pc.getStats(),d=this.analyze(r,null,null,null),h=Date.now();d.experimental.time_to_measure_ms=h-s,d.experimental.time_to_wait_ms=o,this._exporter.saveReferenceReport(d),Pe(this._moduleName,`got reference report for probe ${this._probeId}`),t()}catch(o){n(o)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==ys.RUNNING||!this._config.pc)return Pe(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const t=Date.now(),n=await this._config.pc.getStats(),a=this.analyze(n,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),o=Date.now();return a.experimental.time_to_measure_ms=o-t,this._exporter.addReport(a),Pe(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(a),a}catch(t){return Vn(this._moduleName,`got error ${t}`),null}}async start(){Pe(this._moduleName,"starting"),this.state=ys.RUNNING,this._startedTime=this._exporter.start(),Pe(this._moduleName,"started")}async mute(){this.state=ys.MUTED,Pe(this._moduleName,"muted")}async unmute(){this.state=ys.RUNNING,Pe(this._moduleName,"unmuted")}async stop(t){if(Pe(this._moduleName,`stopping${t?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=ys.IDLE,this._config.ticket){const{ticket:n}=this._exporter;this.fireOnTicket(n)}this._exporter.reset(),Pe(this._moduleName,"stopped")}registerCallback(t,n,a){t in this._callbacks?(this._callbacks[t]={callback:n,context:a},Pe(this._moduleName,`registered callback '${t}'`)):Vn(this._moduleName,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],Pe(this._moduleName,`unregistered callback '${t}'`)):Vn(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReport(t){this._callbacks.onreport&&wu(this._callbacks.onreport.callback,this._callbacks.onreport.context,t)}fireOnTicket(t){this._callbacks.onticket&&wu(this._callbacks.onticket.callback,this._callbacks.onticket.context,t)}updateConfig(t){this._config=t,this._exporter.updateConfig(t)}get state(){return this._state}set state(t){this._state=t,Pe(this._moduleName,`state changed to ${t}`)}addCustomEvent(t,n,a,o){this._exporter.addCustomEvent({at:typeof t=="object"?t.toJSON():t,category:n,name:a,description:o})}async registerToPCEvents(){const{pc:t}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const n=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${n.length} devices found`,"Media Devices state")}catch{Vn(this._moduleName,"can't get devices")}},t){t.oniceconnectionstatechange=()=>{const a=t.iceConnectionState;a===ii.CONNECTED||a===ii.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===ii.DISCONNECTED||a===ii.FAILED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===ii.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},t.onicegatheringstatechange=()=>{const a=t.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",a,"ICE gathering state")},t.ontrack=a=>{this.addCustomEvent(new Date().toJSON(),"call",`${a.track.kind}track`,"MediaStreamTrack received")},t.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const n=t.getReceivers();if(n&&n.length>0){const a=n[0],{transport:o}=a;if(o){const{iceTransport:s}=o;s&&(s.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class Mv{constructor(t){this._id=t.pname&&t.pname.substr(0,12).padEnd(12," ")||cv(),this._moduleName=this._id,on(this._moduleName,"probe created"),this._config=t,this._collector=new kv(this._config,this._id)}set onreport(t){t?this._collector.registerCallback("onreport",t):this._collector.unregisterCallback("onreport")}set onticket(t){t?this._collector.registerCallback("onticket",t):this._collector.unregisterCallback("onticket")}get id(){return this._id}get pname(){return this._config.pname}get cid(){return this._config.cid}get uid(){return this._config.uid}get state(){return this._collector.state}set state(t){this._collector.state=t}addCustomEvent(t,n,a,o=new Date().toJSON()){this._collector.addCustomEvent(o,n,t,a)}get isRunning(){return this._collector.state===ys.RUNNING}get isIdle(){return this._collector.state===ys.IDLE}updateUserId(t){this._config.uid=t,this._collector.updateConfig(this._config)}updateCallId(t){this._config.cid=t,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){Ca(this._moduleName,"probe is already running");return}this._collector.start()}stop(t=!1){this.isRunning&&this._collector.stop(t)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const bt="engine ";class Lv{constructor(t){this._config=t,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},on(bt,`configured for probing every ${this._config.refreshEvery}ms`),on(bt,`configured for starting after ${this._config.startAfter}ms`),on(bt,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Pe(bt,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(t=>t.isRunning)}get isIdle(){return this._probes.every(t=>t.isIdle)}addNewProbe(t,n){if(!t)throw new Error("undefined peer connection");const a=ov(t,n,this._config),o=new Mv(a);return this._probes.push(o),Pe(bt,`${this._probes.length} probes registered`),o}removeExistingProbe(t){if(!t)throw new Error("undefined probe");t.state===ys.RUNNING&&t.stop(),this._probes=this._probes.filter(n=>t.id!==n.id)}async start(){const t=()=>{this._probes.forEach(s=>s.start())},n=async()=>Promise.all(this._probes.map(s=>s.takeReferenceStats())),a=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,o=async()=>{const s=iv(),r=this._probes.filter(d=>d.isRunning);for(const d of r){const h=await d.collectStats();h&&s.probes.push(h),Pe(bt,`got probe ${d.id}`),await wh(0)}return s.delta_time_to_measure_probes_ms=un(s.probes,"experimental","time_to_measure_ms"),s.delta_KBytes_in=un(s.probes,"data","delta_KBytes_in"),s.delta_KBytes_out=un(s.probes,"data","delta_KBytes_out"),s.delta_kbs_in=un(s.probes,"data","delta_kbs_in"),s.delta_kbs_out=un(s.probes,"data","delta_kbs_out"),s.total_time_decoded_in=un(s.probes,"video","total_time_decoded_in"),s.total_time_encoded_out=un(s.probes,"video","total_time_encoded_out"),s};for(Pe(bt,"starting to collect"),t(),Pe(bt,"generating reference reports..."),await n(),Pe(bt,"reference reports generated"),this._startedTime=Date.now();a();)if(Pe(bt,`wait ${this._config.refreshEvery}ms before collecting`),await wh(this._config.refreshEvery),a()){Pe(bt,"collecting...");const s=Date.now(),r=await o(),d=Date.now();r.delta_time_consumed_to_measure_ms=d-s,this.fireOnReports(r),Pe(bt,"collected")}Pe(bt,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(t){const n=a=>{this._probes.forEach(o=>{o.stop(a)})};on(bt,"stop collecting"),n(t)}registerCallback(t,n,a){t in this._callbacks?(this._callbacks[t]={callback:n,context:a},Pe(bt,`registered callback '${t}'`)):Vn(bt,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],Pe(this._moduleName,`unregistered callback '${t}'`)):Vn(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReports(t){this._callbacks.onresult&&t.probes.length>0&&wu(this._callbacks.onresult.callback,this._callbacks.onresult.context,t)}}const $v="interface ";class Hv{constructor(t){this._config=uv(t),on($v,`welcome to ${this._config.name} version ${this._config.version}`),XT(this._config.verbose||!1),this._engine=new Lv(this._config)}setupLogLevel(t){QT(t)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(t,n){return this._engine.addNewProbe(t,n)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(t){this._engine.removeExistingProbe(t)}set onresult(t){t?this._engine.registerCallback("onresult",t):this._engine.unregisterCallback("onresult")}}function Fv(c,t){return Object.keys(c).filter(n=>t.includes(n)).reduce((n,a)=>{const o=a;return{...n,[o]:c[o]}},{})}const jv=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"];class qv{constructor(t){this.intervals={},this.emitInterval=t.emitInterval||200,this.onChangeFunction=t.onChangeFunction}start(t,n){t&&t.getTracks().length&&requestAnimationFrame(()=>this.beginCalculation(t,n))}stop(t){this.clearVolumeInterval(t)}clearVolumeInterval(t){clearInterval(this.intervals[t]),delete this.intervals[t]}clearAllIntervals(){Object.keys(this.intervals).forEach(t=>{clearInterval(this.intervals[t])}),this.intervals={}}beginCalculation(t,n){this.clearVolumeInterval(n);const a=an.createAnalyser(),o=an.createMediaStreamSource(t),s=an.createScriptProcessor(2048,1,1);a.smoothingTimeConstant=.8,a.fftSize=1024,o.connect(a),a.connect(s),s.connect(an.destination),this.intervals[n]=setInterval(()=>{const r=new Uint8Array(a.frequencyBinCount);a.getByteFrequencyData(r);let d=0;const h=r.length;for(let g=0;g<h;g++)d+=r[g];const _=d/h;this.onChangeFunction(n,_)},this.emitInterval)}}const ba={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},Vv=0;class Bv{constructor(t){this.isAutoAnswer=!1,this.muteWhenJoinEnabled=!1,this.isDNDEnabled=!1,this.muted=!1,this.microphoneInputLevelValue=1,this.speakerVolumeValue=1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.availableMediaDevices=[],this.selectedMediaDevices={input:"default",output:"default"},this.callStatus={},this.callTime={},this.callMetrics={},this.timeIntervals={},this.metricConfig={refreshEvery:1e3},this.activeStreamValue=null,this.initialStreamValue=null,this.context=t,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new qv({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices()}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(t){this.currentActiveRoomIdValue=t,this.context.emit("currentActiveRoomChanged",t)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(t){this.isCallAddingInProgress=t,this.context.emit("callAddingInProgressChanged",t)}get muteWhenJoin(){return this.muteWhenJoinEnabled}get isDND(){return this.isDNDEnabled}get speakerVolume(){return this.speakerVolumeValue}get microphoneInputLevel(){return this.microphoneInputLevelValue}get getActiveCalls(){return this.activeCalls}get hasActiveCalls(){return Object.values(this.extendedCalls).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audiooutput")}get getUserMediaConstraints(){return Eh()?{video:!1,audio:!0}:{audio:{deviceId:{exact:this.selectedMediaDevices.input}},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(t){this.availableMediaDevices=t,this.context.emit("changeAvailableDeviceList",t)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const t=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(t)}async initializeMediaDevices(){const t=localStorage.getItem(ba.SELECTED_INPUT_DEVICE)||"default",n=localStorage.getItem(ba.SELECTED_OUTPUT_DEVICE)||"default";try{const a=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),o=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(o),await this.setMicrophone(t),await this.setSpeaker(n),navigator.mediaDevices.addEventListener("devicechange",async()=>{const s=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(s)}),a.getTracks().forEach(s=>s.stop())}catch(a){console.error(a)}}setCallTime(t){const n={...t};delete n.callId,this.callTime={...this.callTime,[t.callId]:n},this.context.emit("changeCallTime",this.callTime)}removeCallTime(t){const n={...this.callTime};delete n[t],this.callTime={...n},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(t,n){this.timeIntervals={...this.timeIntervals,[t]:n}}removeTimeInterval(t){const n={...this.timeIntervals};n[t]&&(clearInterval(n[t]),delete n[t],this.timeIntervals={...n})}stopCallTimer(t){this.removeTimeInterval(t),this.removeCallTime(t)}emitVolumeChange(t,n){this.context.emit("changeCallVolume",{callId:t,volume:n})}setMetricsConfig(t){this.metricConfig={...this.metricConfig,...t}}sendDTMF(t,n){if(!/^[A-D0-9]+$/g.test(n))throw new Error("Not allowed character in DTMF input");this.extendedCalls[t].sendDTMF(n)}setIsMuted(t){this.muted=t,this.context.emit("changeIsMuted",t)}processMute(t){const n=this.currentActiveRoomId;this.setIsMuted(t),this.initialStreamValue.getTracks().forEach(a=>a.enabled=!t),this.roomReconfigure(n)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:t,toHold:n,automatic:a}){const o=this.extendedCalls[t];o._automaticHold=a??!1,await new Promise(d=>{const h=()=>{o.putOnHoldTimestamp=n?Date.now():void 0,d()};n?o.hold({},h):o.unhold({},h)}),this.updateCall(o);const r=Object.values(this.extendedCalls).filter(d=>d.roomId===this.currentActiveRoomId&&(n?t!==d._id:!0));r.length>1&&await this.doConference(r)}holdCall(t,n=!1){return this.processHold({callId:t,automatic:n,toHold:!0})}unholdCall(t){return this.processHold({callId:t,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(t=>t.direction==="outgoing"&&t.status===Vv).forEach(t=>this.terminateCall(t._id))}answerCall(t){const n=this.extendedCalls[t];this.cancelAllOutgoingUnanswered(),n.answer(this.sipOptions),this.updateCall(n),this.setActiveRoom(n.roomId),n.connection.addEventListener("track",a=>{this.triggerAddStream(a,n)})}async moveCall(t,n){this.updateCallStatus({callId:t,isMoving:!0}),await this.processRoomChange({callId:t,roomId:n}),this.updateCallStatus({callId:t,isMoving:!1})}updateCall(t){this.activeCalls[t._id]=gh(t),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(t){const a={...this.activeRooms[t.roomId],...t};this.activeRooms={...this.activeRooms,[t.roomId]:{...a}},this.context.emit("updateRoom",{room:a,roomList:this.activeRooms})}hasAutoAnswerHeaders(t){const n=/answer-after=0/,o=t.request.getHeader("Call-Info");return o&&n.test(o)}addCall(t,n=!0){this.activeCalls={...this.activeCalls,[t._id]:gh(t)},this.extendedCalls[t._id]=t,n&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(t){this.callStatus={...this.callStatus,[t]:{isMoving:!1,isTransferring:!1,isMerging:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(t){const a={...{...this.callStatus[t.callId]}};t.isMoving!==void 0&&(a.isMoving=t.isMoving),t.isTransferring!==void 0&&(a.isTransferring=t.isTransferring),t.isMerging!==void 0&&(a.isMerging=t.isMerging),this.callStatus={...this.callStatus,[t.callId]:{...a}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(t){const n={...this.callStatus};delete n[t],this.callStatus={...n},this.context.emit("changeCallStatus",this.callStatus)}addRoom(t){this.activeRooms={...this.activeRooms,[t.roomId]:t},this.context.emit("addRoom",{room:t,roomList:this.activeRooms})}getActiveStream(){const t=vh(this.initialStreamValue,this.microphoneInputLevel*2);return t.getTracks().forEach(n=>n.enabled=!this.isMuted),this.setActiveStream(t),t}async setMicrophone(t){if(!this.getInputDeviceList.find(({deviceId:a})=>a===t)||(this.setSelectedInputDevice(t),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const n=Object.values(this.extendedCalls).filter(a=>a.roomId===this.currentActiveRoomId);n.length===1?Object.values(n).forEach(async a=>{const o=this.getActiveStream();a.connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.updateCall(a)}):await this.doConference(n)}setActiveStream(t){this.activeStream&&this.stopVUMeter("origin"),this.setupVUMeter(t,"origin"),this.activeStreamValue=t,this.context.emit("changeActiveStream",t)}async setSpeaker(t){if(!this.getOutputDeviceList.find(({deviceId:o})=>o===t))return;this.setSelectedOutputDevice(t);const n=Object.values(this.extendedCalls);if(n.length===0)return;const a=n.filter(o=>o.roomId===this.currentActiveRoomId);a.length===1?n.forEach(o=>{var s;(s=o.audioTag)==null||s.setSinkId(t),this.updateCall(o)}):await this.doConference(a)}removeRoom(t){const n={...this.activeRooms},a={...n[t]};delete n[t],this.activeRooms={...n},this.context.emit("removeRoom",{room:a,roomList:this.activeRooms})}deleteRoomIfEmpty(t){t!==void 0&&Object.values(this.extendedCalls).filter(n=>n.roomId===t).length===0&&(this.removeRoom(t),this.currentActiveRoomId===t&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(t){this.muted?t.mute({audio:!0}):t.unmute({audio:!0})}async roomReconfigure(t){var a;if(t===void 0)return;const n=Object.values(this.extendedCalls).filter(o=>o.roomId===t);if(this.currentActiveRoomId===t?n.forEach(o=>{o.audioTag&&(this.muteReconfigure(o),o.audioTag.muted=!1,this.updateCall(o))}):n.forEach(o=>{o.audioTag&&(o.audioTag.muted=!0,this.updateCall(o))}),n.length===0)this.deleteRoomIfEmpty(t);else if(n.length===1&&this.currentActiveRoomId!==t)n[0].isOnHold().local||await this.holdCall(n[0].id,!0);else if(n.length===1&&this.currentActiveRoomId===t){if(n[0].isOnHold().local&&n[0]._automaticHold&&await this.unholdCall(n[0].id),n[0].connection&&((a=n[0].connection)!=null&&a.getSenders()[0])){const o=this.getActiveStream();await n[0].connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.muteReconfigure(n[0])}}else n.length>1&&await this.doConference(n)}async doConference(t){const n=[];t.forEach(a=>{a!=null&&a.connection.getReceivers().forEach(o=>{n.push(o.track)})}),await JT.forEach(t,async a=>{var r;if(a==null)return;const o=new MediaStream,s=an.createMediaStreamDestination();if(a.connection.getReceivers().forEach(d=>{n.forEach(h=>{o.addTrack(d.track),d.track.id!==h.id&&an.createMediaStreamSource(new MediaStream([h])).connect(s)})}),t[0].roomId===this.currentActiveRoomId){const d=this.getActiveStream();an.createMediaStreamSource(d).connect(s)}(r=a.connection)!=null&&r.getSenders()[0]&&(await a.connection.getSenders()[0].replaceTrack(s.stream.getTracks()[0]),this.muteReconfigure(a))})}processCallerMute(t,n){const a=this.extendedCalls[t];a&&a.connection.getReceivers().length&&(a.localMuted=n,a.connection.getReceivers().forEach(o=>{o.track.enabled=!n}),this.updateCall(a))}muteCaller(t){this.processCallerMute(t,!0)}unmuteCaller(t){this.processCallerMute(t,!1)}terminateCall(t){const n=this.extendedCalls[t];n._status!==8&&n.terminate()}transferCall(t,n){if(n.toString().length===0)return new Error("Target must be passed");const a=this.extendedCalls[t];if(!a._is_confirmed&&!a._is_canceled){const o=`sip:${n}@${this.context.sipDomain}`;a.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${o}`]});return}this.updateCallStatus({callId:t,isTransferring:!0}),a.refer(`sip:${n}@${this.context.sipDomain}`),this.updateCall(a)}mergeCall(t){const n=Object.values(this.extendedCalls).filter(s=>s.roomId===t);if(n.length!==2)return;const a=n[0],o=n[1];!a||!o||(this.updateCallStatus({callId:a._id,isMerging:!0}),this.updateCallStatus({callId:o._id,isMerging:!0}),a.refer(o.remote_identity.uri.toString(),{replaces:o}),this.updateCall(a))}mergeCallByIds(t,n){const a=Object.values(this.extendedCalls).find(s=>s._id===t),o=Object.values(this.extendedCalls).find(s=>s._id===n);if(!a||!o)throw new Error("Call ID is not provided");this.updateCallStatus({callId:t,isMerging:!0}),this.updateCallStatus({callId:n,isMerging:!0}),a.refer(o.remote_identity.uri.toString(),{replaces:o}),this.updateCall(a)}setDND(t){this.isDNDEnabled=t,this.context.emit("changeIsDND",t)}startCallTimer(t){this.removeTimeInterval(t);const n={callId:t,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(n);const a=setInterval(()=>{const o={...this.callTime[t]},s=YT(o);this.setCallTime({callId:t,...s})},1e3);this.setTimeInterval(t,a)}async setActiveRoom(t){const n=this.currentActiveRoomId;t!==n&&(this.currentActiveRoomId=t,await this.roomReconfigure(n),await this.roomReconfigure(t))}getNewRoomId(){const t=Object.keys(this.activeRooms);return t.length===0?1:parseInt(t.sort()[t.length-1])+1}async setupCall(t){var _,g;const n=t.session;if(this.getActiveCalls[n.id]!==void 0)return;const o=this.getNewRoomId(),s={started:new Date,incomingInProgress:!1,roomId:o};n.direction==="incoming"?(this.context.logger.log("New incoming call from",(g=(_=n._remote_identity)==null?void 0:_._uri)==null?void 0:g._user),s.incomingInProgress=!0,this.context.subscribe(Qt.CALL_CONFIRMED,T=>{n.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:o}),this.startCallTimer(n.id))}),this.context.subscribe(Qt.CALL_FAILED,T=>{n.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:o}),this.deleteRoomIfEmpty(o))})):n.direction==="outgoing"&&(n.once("confirmed",()=>{this.startCallTimer(n.id)}),this.startCallTimer(n.id));const r=n,d=this.hasAutoAnswerHeaders(t),h=r.direction==="incoming"&&!this.hasActiveCalls&&(d||this.autoAnswer);r.roomId=o,r.localMuted=!1,r.autoAnswer=h,h?this.addCall(r,!1):this.addCall(r),this.addCallStatus(n.id),this.addRoom(s),h&&this.answerCall(r._id)}removeCall(t){const n={...this.activeCalls};delete n[t],this.activeCalls={...n};const a={...this.extendedCalls};delete a[t],this.extendedCalls={...a},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(t){var o;const n=this.extendedCalls[t._id];this.stopVUMeter("origin"),(o=n.connection)==null||o.getSenders().forEach(s=>{s.track.stop()});const a=n.roomId;this.removeCall(t._id),this.roomReconfigure(a)}async newRTCSessionCallback(t){const n=t.session;if(this.isDND){n.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(this.context.triggerListener({listenerType:Qt.NEW_CALL,session:n,event:t}),n.on("ended",a=>{var s,r,d;this.stopVUMeter(n.id),this.context.logger.log("Session ended for",(r=(s=n._remote_identity)==null?void 0:s._uri)==null?void 0:r._user),this.context.triggerListener({listenerType:Qt.CALL_ENDED,session:n,event:a});const o=this.getActiveCalls[n.id];o&&this.activeCallListRemove(o),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null)}),n.on("progress",a=>{var o,s;this.context.logger.log("Session in progress for",(s=(o=n._remote_identity)==null?void 0:o._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:Qt.CALL_PROGRESS,session:n,event:a})}),n.on("failed",a=>{var s,r,d;this.stopVUMeter(n.id),this.context.logger.log("Session failed for",(r=(s=n._remote_identity)==null?void 0:s._uri)==null?void 0:r._user),this.context.triggerListener({listenerType:Qt.CALL_FAILED,session:n,event:a}),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const o=this.getActiveCalls[n.id];o&&this.activeCallListRemove(o),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null)}),n.on("confirmed",a=>{var o,s;this.context.logger.log("Session confirmed for",(s=(o=n._remote_identity)==null?void 0:o._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:Qt.CALL_CONFIRMED,session:n,event:a}),this.updateCall(n),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(t),n.direction==="outgoing"){const a=this.getActiveCalls[n.id].roomId;this.setActiveRoom(a)}}setMuteWhenJoin(t){this.muteWhenJoinEnabled=t,this.context.emit("changeMuteWhenJoin",t)}setMicrophoneSensitivity(t){if(t<0||t>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=t,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(t){this.speakerVolumeValue=t,Object.values(this.extendedCalls).forEach(n=>{n.audioTag&&(n.audioTag.volume=t,this.updateCall(n))})}setAutoAnswer(t){this.isAutoAnswer=t}setSelectedInputDevice(t){localStorage.setItem(ba.SELECTED_INPUT_DEVICE,t),this.selectedMediaDevices.input=t,this.context.emit("changeActiveInputMediaDevice",t)}setSelectedOutputDevice(t){localStorage.setItem(ba.SELECTED_OUTPUT_DEVICE,t),this.selectedMediaDevices.output=t,this.context.emit("changeActiveOutputMediaDevice",t)}setCallMetrics(t){const n={...t};delete n.callId,this.callMetrics={...this.callMetrics,[t.callId]:n},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(t){const n={...this.callMetrics};delete n[t],this.callMetrics={...n},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(t){const n=new Hv(this.metricConfig),a=n.createProbe(t.connection,{cid:t._id}),o=[];let s;a.onreport=r=>{Object.entries(r.audio).forEach(([_,g])=>{g.direction==="inbound"&&!o.includes(_)&&(o.push(_),s=_)});const d=r.audio[s];if(!d)return;const h=Fv(d,jv);h.callId=t._id,this.setCallMetrics(h)},this.context.subscribe(Qt.CALL_ENDED,r=>{r._id===t._id&&n.stopAllProbes()}),n.startAllProbes()}setupVUMeter(t,n){this.VUMeter.start(t,n)}stopVUMeter(t){this.VUMeter.stop(t)}async setupStream(){const t=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach(n=>n.stop()),this.initialStreamValue=null),this.initialStreamValue=t}async triggerAddStream(t,n){this.setIsMuted(this.muteWhenJoin||this.isMuted),this.initialStreamValue||await this.setupStream();const a=vh(this.initialStreamValue,this.microphoneInputLevel*2),o=this.isMuted||this.muteWhenJoin;a.getTracks().forEach(r=>r.enabled=!o),this.setActiveStream(a),await n.connection.getSenders()[0].replaceTrack(a.getTracks()[0]);const s=new MediaStream([t.track]);PT(s,n,this.selectedOutputDevice,this.speakerVolume),this.setupVUMeter(s,n._id),this.getCallQuality(n),this.updateCall(n)}initCall(t,n,a=!1){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`);const o=this.context.call(`sip:${t}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=o.id,n&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:o.id,roomId:this.currentActiveRoomId}),a)){const s=Object.values(this.extendedCalls).filter(r=>r.roomId===this.currentActiveRoomId&&r._id!==o.id);for(const r of s)this.holdCall(r._id,!0)}o.connection.addEventListener("track",s=>{this.triggerAddStream(s,o)})}async processRoomChange({callId:t,roomId:n}){const a=this.extendedCalls[t].roomId;this.extendedCalls[t].roomId=n;const o=this.extendedCalls[t];return this.updateCall(o),await this.setActiveRoom(n),Promise.all([this.roomReconfigure(a),this.roomReconfigure(n)]).then(()=>{this.deleteRoomIfEmpty(a),this.deleteRoomIfEmpty(n)})}}class Gv{constructor(t){this.context=t}get sipOptions(){return{...this.context.options.sipOptions}}initCall(t,n){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${t}@${this.context.sipDomain}`,n,this.sipOptions)}stop(t={}){this.context.terminateJanusSessions(t)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(t){this.context.changeMediaConstraints(t)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class Wv{constructor(t){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=t,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this.context))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(t){const n=this.extendedMessages[t];this.updateMSRPSession(n)}updateMSRPSession(t){this.activeMessages[t._id]=Th(t),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(t){this.activeMessages={...this.activeMessages,[t._id]:Th(t)},this.extendedMessages[t._id]=t,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(t,n){const a=this.msrpHistory[n.id]||[];a.push(t),this.msrpHistory={...this.msrpHistory,[n.id]:[...a]},this.context.emit("newMSRPMessage",{message:t,session:n})}messageTerminate(t){const n=this.extendedMessages[t];n._status!==8&&n.terminate()}addMessageSession(t){if(!t._id||this.getActiveMessages[t._id]!==void 0)return;const a=t;this.addMMSRPSession(a)}triggerMSRPListener({listenerType:t,session:n,event:a}){const o=this.context.listenersList[t];!o||!o.length||o.forEach(s=>{s(n,a)})}removeMMSRPSession(t){const n={...this.activeMessages};delete n[t],this.activeMessages={...n};const a={...this.extendedMessages};delete a[t],this.extendedMessages={...a},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(t){this.removeMMSRPSession(t._id)}newMSRPSessionCallback(t){const n=t.session;n.on("ended",a=>{this.triggerMSRPListener({listenerType:Qt.CALL_ENDED,session:n,event:a});const o=this.getActiveMessages[n.id];this.activeMessageListRemove(o)}),n.on("failed",a=>{this.triggerMSRPListener({listenerType:Qt.CALL_FAILED,session:n,event:a});const o=this.getActiveMessages[n.id];this.activeMessageListRemove(o)}),n.on("confirmed",a=>{this.triggerMSRPListener({listenerType:Qt.CALL_CONFIRMED,session:n,event:a}),this.updateMSRPSession(n)}),n.on("newMessage",a=>{this.addMSRPMessage(a,n)}),this.addMessageSession(n)}setIsMSRPInitializing(t){this.isMSRPInitializingValue=t,this.context.emit("isMSRPInitializingChanged",t)}initMSRP(t,n,a){if(t.length===0)return console.error("Target must be a valid string");const o=this.context.startMSRP(t,a);o.on("active",()=>{this.addMessageSession(o),o.sendMSRP(n),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(t,n){const a=this.extendedMessages[t];if(!a)throw new Error(`MSRP session with id ${t} doesn't exist!`);a.sendMSRP(n)}}const Ou={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class kh{constructor(t){this.opensips=null,this.session=null,this.name=null,this.name=t}setOpensips(t){this.opensips=t}setSession(t){this.session=t}kill(){this.opensips.kill(this.name)}}class Mh extends kh{constructor(t,n){super(t),this._candidates=[],this._subscribeSent=!1,this._configureSent=!1,this._lastTrickleReceived=!1,this.type=n}connect(t={}){this.opaqueId=this.session.generateOpaqueId();const n=xe.cloneArray(t.extraHeaders),a={from_tag:this.session._from_tag};t.fromUserName&&(a.from_uri=new ln("sip",t.fromUserName,this.session._ua.configuration.uri.host),n.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),t.fromDisplayName&&(a.from_display_name=t.fromDisplayName),n.push(`Contact: ${this.session._contact}`),n.push("Content-Type: application/json"),this.session._sessionTimers.enabled&&n.push(`Session-Expires: ${this.session._sessionTimers.defaultExpires}${this.session._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new Tt.InitialOutgoingInviteRequest(this.session.target,this.session._ua,a,n),this._createRTCConnection(),this._sendInitialRequest()}getStream(){return this.stream}getConnection(){return this._connection}_createRTCConnection(){this._connection=new RTCPeerConnection({iceServers:[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}]});let t;this._connection.onicecandidate=n=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||n.candidate&&(this._candidates.push(n.candidate),clearTimeout(t),t=setTimeout(()=>{this._lastTrickleReceived=!0,this._subscribeSent&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})},500))}}addTracks(t){t.forEach(n=>{this._connection.addTrack(n)})}async _sendInitialRequest(){const t=new Kr(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});if(await this.generateStream(),!this.stream||!this.stream.getTracks().length)return;this.addTracks(this.stream.getTracks());const n={audio:!1,video:!0};this.jsep_offer=await this._connection.createOffer(n),await this._connection.setLocalDescription(this.jsep_offer);const a={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},o=JSON.stringify(a);this._request.body=o,t.send()}_receiveInviteResponse(t){if(this._publisherSubscribeSent||!t.body)return;const n=JSON.parse(t.body);this.handleId=n.data.id;const a={janus:"message",body:{request:"join",room:this.session.room_id,ptype:"publisher",display:this.session.display_name+" (Screen Share)",opaque_id:this.opaqueId},handle_id:this.handleId},o=[this.session.getPTypeHeader(kt.PUBLISHER)];this.session.sendRequest(L.SUBSCRIBE,{extraHeaders:o,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async s=>{var r,d,h,_;if(s.status_code===200){if(this._subscribeSent=!0,s.body)try{const g=JSON.parse(s.body)||{};((d=(r=g.plugindata)==null?void 0:r.data)==null?void 0:d.videoroom)==="joined"&&this.session.myFeedList.push(g.plugindata.data.id),(_=(h=g.plugindata)==null?void 0:h.data)!=null&&_.publishers&&this.session.receivePublishers(g)}catch(g){console.error(g)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}}}}),this._publisherSubscribeSent=!0}async _sendConfigureMessage(t){const n=this._candidates.map(r=>({janus:"trickle",candidate:r,handle_id:this.handleId,session_id:this.session.session_id})),o={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.session.getRecordFileName(),...t},jsep:this.jsep_offer,handle_id:this.handleId,session_id:this.session.session_id},trickles:[...n]},s=["Content-Type: application/json",this.session.getPTypeHeader(kt.ICE)];this.session.sendRequest(L.INFO,{extraHeaders:s,body:JSON.stringify(o),eventHandlers:{onSuccessResponse:async r=>{this._configureSent=!0;const h=r.data.split(`\r
159
- `),_=h[h.length-1],g=JSON.parse(_);await this._connection.setRemoteDescription(g.jsep),this._candidates=[]}}})}_sendDetach(){const t={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},n=[this.session.getPTypeHeader(kt.DETACH)];this.session.sendRequest(L.INFO,{extraHeaders:n,body:JSON.stringify(t)}),this.session._ua.emit("pluginDetach",this.name)}async stopMedia(){this._connection&&(this._connection.close(),this._connection=null),this.stream&&(this.stream=null)}async stop(){await this.session.stopProcessPlugins(this.type);const t=this._connection.getSenders();t.forEach(n=>{const a=n.track;a&&a.stop()}),t.forEach(n=>{this._connection.removeTrack(n)}),await this.stopMedia(),this._sendDetach()}async generateStream(){throw new Error("generateStream method is not implemented")}}class Lh extends kh{constructor(t,n,a={}){super(t),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=a.immediate||!1,this.type=n}start(t){return t}stop(){throw new Error("stop method is not implemented")}async process(t){if(this.immediate){const n=await this.start(t);return this.running=!0,n}return t}async connect(){this.running=!0,await this.session.resyncPlugins(this.type)}terminate(){this.stop()}async kill(){this.stop(),this.running=!1,await this.session.resyncPlugins(this.type)}}class Kv extends IT{constructor(t,n){if(!t.modules.length)throw new Error("options.modules should include at least 1 module");const a={...t.configuration,sockets:t.socketInterfaces.map(o=>new KT.WebSocketInterface(o))};super(a),this.initialized=!1,this.connected=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.activeConnection=!1,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],t.pnExtraHeaders&&Object.keys(t.pnExtraHeaders).length&&this.registrator().setExtraContactUriParams(t.pnExtraHeaders),this.options=t,this.modules=t.modules,n&&xT(n)&&(this.logger=n)}on(t,n){return super.on(t,n)}off(t,n){return super.off(t,n)}emit(t,n){return super.emit(t,n)}get sipDomain(){return this.options.sipDomain}use(t){if(this.newStreamPlugins.find(n=>n.name===t.name)||this.processStreamPlugins.find(n=>n.name===t.name))throw new Error(`Plugin with name ${t.name} already exists`);if(t instanceof Mh)t.setOpensips(this),this.newStreamPlugins.push(t);else if(t instanceof Lh)t.setOpensips(this),this.processStreamPlugins.push(t);else throw new Error("Wrong plugin instance")}getPlugin(t){return this.newStreamPlugins.find(n=>n.name===t)||this.processStreamPlugins.find(n=>n.name===t)}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(Ou.AUDIO)&&(this.audio=new Bv(this)),this.modules.includes(Ou.MSRP)&&(this.msrp=new Wv(this)),this.modules.includes(Ou.VIDEO)&&(this.video=new Gv(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.setConnected(!0),this.isReconnecting=!1,this.activeConnection=!0}),this.on(this.disconnectedEventName,()=>{this.isReconnecting||(this.isReconnecting=!0,this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.stop(),this.setInitialized(!1),this.setConnected(!1),this.activeConnection&&setTimeout(this.start.bind(this),5e3))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}disconnect(){this.activeConnection=!1,this.stop()}subscribe(t,n){const o=!this.listenersList[t]||!this.listenersList[t].length?[n]:[...this.listenersList[t],n];this.listenersList={...this.listenersList,[t]:o}}removeIListener(t){const n={...this.listenersList};delete n[t],this.listenersList={...n}}triggerListener({listenerType:t,session:n,event:a}){const o=this.listenersList[t];!o||!o.length||o.forEach(s=>{s(n,a)})}setInitialized(t){this.initialized=t,this.emit("ready",t)}setConnected(t){this.connected=t,this.emit("connection",t)}}Nt.BaseNewStreamPlugin=Mh,Nt.BaseProcessStreamPlugin=Lh,Nt.default=Kv,Object.defineProperties(Nt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
159
+ `),_=h[h.length-1],g=JSON.parse(_);await this._connection.setRemoteDescription(g.jsep),this._candidates=[]}}})}_sendDetach(){const t={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},n=[this.session.getPTypeHeader(kt.DETACH)];this.session.sendRequest(L.INFO,{extraHeaders:n,body:JSON.stringify(t)}),this.session._ua.emit("pluginDetach",this.name)}async stopMedia(){this._connection&&(this._connection.close(),this._connection=null),this.stream&&(this.stream=null)}async stop(){await this.session.stopProcessPlugins(this.type);const t=this._connection.getSenders();t.forEach(n=>{const a=n.track;a&&a.stop()}),t.forEach(n=>{this._connection.removeTrack(n)}),await this.stopMedia(),this._sendDetach()}async generateStream(){throw new Error("generateStream method is not implemented")}}class Lh extends kh{constructor(t,n,a={}){super(t),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=a.immediate||!1,this.type=n}start(t){return t}stop(){throw new Error("stop method is not implemented")}async process(t){if(this.immediate){const n=await this.start(t);return this.running=!0,n}return t}async connect(){this.running=!0,await this.session.resyncPlugins(this.type)}terminate(){this.stop()}async kill(){this.stop(),this.running=!1,await this.session.resyncPlugins(this.type)}}class Kv extends IT{constructor(t,n){if(!t.modules.length)throw new Error("options.modules should include at least 1 module");const a={...t.configuration,sockets:t.socketInterfaces.map(o=>new KT.WebSocketInterface(o))};super(a),this.initialized=!1,this.connected=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.activeConnection=!1,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],t.pnExtraHeaders&&Object.keys(t.pnExtraHeaders).length&&this.registrator().setExtraContactUriParams(t.pnExtraHeaders),this.options=t,this.modules=t.modules,n&&xT(n)&&(this.logger=n)}on(t,n){return super.on(t,n)}off(t,n){return super.off(t,n)}emit(t,n){return super.emit(t,n)}get sipDomain(){return this.options.sipDomain}use(t){if(this.newStreamPlugins.find(n=>n.name===t.name)||this.processStreamPlugins.find(n=>n.name===t.name))throw new Error(`Plugin with name ${t.name} already exists`);if(t instanceof Mh)t.setOpensips(this),this.newStreamPlugins.push(t);else if(t instanceof Lh)t.setOpensips(this),this.processStreamPlugins.push(t);else throw new Error("Wrong plugin instance")}getPlugin(t){return this.newStreamPlugins.find(n=>n.name===t)||this.processStreamPlugins.find(n=>n.name===t)}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(Ou.AUDIO)&&(this.audio=new Bv(this)),this.modules.includes(Ou.MSRP)&&(this.msrp=new Wv(this)),this.modules.includes(Ou.VIDEO)&&(this.video=new Gv(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.setConnected(!0),this.setReconnecting(!1),this.activeConnection=!0}),this.on(this.disconnectedEventName,()=>{this.isReconnecting||(this.setReconnecting(!0),this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.stop(),this.setInitialized(!1),this.setConnected(!1),this.activeConnection&&setTimeout(this.start.bind(this),5e3))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}disconnect(){this.activeConnection=!1,this.stop()}subscribe(t,n){const o=!this.listenersList[t]||!this.listenersList[t].length?[n]:[...this.listenersList[t],n];this.listenersList={...this.listenersList,[t]:o}}removeIListener(t){const n={...this.listenersList};delete n[t],this.listenersList={...n}}triggerListener({listenerType:t,session:n,event:a}){const o=this.listenersList[t];!o||!o.length||o.forEach(s=>{s(n,a)})}setInitialized(t){this.initialized=t,this.emit("ready",t)}setConnected(t){this.connected=t,this.emit("connection",t)}setReconnecting(t){this.isReconnecting=t,this.emit("reconnecting",t)}}Nt.BaseNewStreamPlugin=Mh,Nt.BaseProcessStreamPlugin=Lh,Nt.default=Kv,Object.defineProperties(Nt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voicenter-team/opensips-js",
3
- "version": "1.0.131",
3
+ "version": "1.0.132",
4
4
  "description": "The JS package for opensips",
5
5
  "default": "src/index.ts",
6
6
  "jsdelivr": "dist/opensips-js.iife.js",
@@ -18,6 +18,7 @@ export type ChangeVolumeEventType = {
18
18
 
19
19
  export type readyListener = (value: boolean) => void
20
20
  export type connectionListener = (value: boolean) => void
21
+ export type reconnectionListener = (value: boolean) => void
21
22
  export type changeActiveCallsListener = (event: { [key: string]: ICall }) => void
22
23
  export type changeActiveMessagesListener = (event: { [key: string]: IMessage }) => void
23
24
  export type TestEventListener = (event: { test: string }) => void
@@ -58,6 +59,7 @@ export type changeVideoStateListener = (state: boolean) => void
58
59
  export interface OpenSIPSEventMap extends UAEventMap {
59
60
  ready: readyListener
60
61
  connection: connectionListener
62
+ reconnecting: reconnectionListener
61
63
  // JSSIP
62
64
  changeActiveCalls: changeActiveCallsListener
63
65
  changeActiveMessages: changeActiveMessagesListener