@voicenter-team/opensips-js 1.0.81 → 1.0.82

Sign up to get free protection for your applications and to get access to all the features.
@@ -131,7 +131,7 @@ ${n}
131
131
  `,o+=`Call-ID: ${Fe.call_id}\r
132
132
  `,o+=`CSeq: ${Fe.cseq} ${Fe.method}\r
133
133
  `,o+=`\r
134
- `,Kf.send(o)}var Xa={};const Nn=pt(),Js=De,Qa=Xt(),Yf=us(),Za=Ga,eu=_s;Xa.settings={authorization_user:null,password:null,realm:null,ha1:null,authorization_jwt:null,display_name:null,uri:null,contact_uri:null,instance_id:null,use_preloaded_route:!1,session_timers:!0,session_timers_refresh_method:Js.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:Js.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:Js.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:`${Nn.createRandomToken(12)}.invalid`};const no={mandatory:{sockets(c){const n=[];if(Za.isSocket(c))n.push({socket:c});else if(Array.isArray(c)&&c.length)for(const r of c)Object.prototype.hasOwnProperty.call(r,"socket")&&Za.isSocket(r.socket)?n.push(r):Za.isSocket(r)&&n.push({socket:r});else return;return n},uri(c){/^sip:/i.test(c)||(c=`${Js.SIP}:${c}`);const n=Yf.parse(c);if(n)return n.user?n:void 0}},optional:{authorization_user(c){if(Qa.parse(`"${c}"`,"quoted_string")!==-1)return c},authorization_jwt(c){if(typeof c=="string")return c},user_agent(c){if(typeof c=="string")return c},connection_recovery_max_interval(c){if(Nn.isDecimal(c)){const n=Number(c);if(n>0)return n}},connection_recovery_min_interval(c){if(Nn.isDecimal(c)){const n=Number(c);if(n>0)return n}},contact_uri(c){if(typeof c=="string"){const n=Qa.parse(c,"SIP_URI");if(n!==-1)return n}},display_name(c){return c},instance_id(c){if(/^uuid:/i.test(c)&&(c=c.substr(5)),Qa.parse(c,"uuid")!==-1)return c},no_answer_timeout(c){if(Nn.isDecimal(c)){const n=Number(c);if(n>0)return n}},session_timers(c){if(typeof c=="boolean")return c},session_timers_refresh_method(c){if(typeof c=="string"&&(c=c.toUpperCase(),c===Js.INVITE||c===Js.UPDATE))return c},session_timers_force_refresher(c){if(typeof c=="boolean")return c},password(c){return String(c)},realm(c){return String(c)},ha1(c){return String(c)},register(c){if(typeof c=="boolean")return c},register_expires(c){if(Nn.isDecimal(c)){const n=Number(c);if(n>0)return n}},registrar_server(c){/^sip:/i.test(c)||(c=`${Js.SIP}:${c}`);const n=Yf.parse(c);if(n)return n.user?void 0:n},use_preloaded_route(c){if(typeof c=="boolean")return c},extra_headers(c){const n=[];if(Array.isArray(c)&&c.length)for(const r of c)typeof r=="string"&&n.push(r);else return;return n}}};Xa.load=(c,n)=>{for(const r in no.mandatory)if(n.hasOwnProperty(r)){const o=n[r],a=no.mandatory[r](o);if(a!==void 0)c[r]=a;else throw new eu.ConfigurationError(r,o)}else throw new eu.ConfigurationError(r);for(const r in no.optional)if(n.hasOwnProperty(r)){const o=n[r];if(Nn.isEmpty(o))continue;const a=no.optional[r](o);if(a!==void 0)c[r]=a;else throw new eu.ConfigurationError(r,o)}};const xg=ut.EventEmitter,Mg=lt,gt=De,kg=Cm,zf=Ff,Jf=ag,Xf=hg,tu=On,Lg=Tg,ro=pt(),$g=_s,Hg=us(),Fg=Bf,su=Pt,Vg=Ig,nu=Xa,je=new Mg("UA"),Tt={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2};var Qf=class extends xg{static get C(){return Tt}constructor(n){if(je.debug("new() [configuration:%o]",n),super(),this._cache={credentials:{}},this._configuration=Object.assign({},nu.settings),this._dynConfiguration={},this._dialogs={},this._applicants={},this._sessions={},this._transport=null,this._contact=null,this._status=Tt.STATUS_INIT,this._error=null,this._transactions={nist:{},nict:{},ist:{},ict:{}},this._data={},this._closeTimer=null,n===void 0)throw new TypeError("Not enough arguments");try{this._loadConfig(n)}catch(r){throw this._status=Tt.STATUS_NOT_READY,this._error=Tt.CONFIGURATION_ERROR,r}this._registrator=new kg(this)}get C(){return Tt}get status(){return this._status}get contact(){return this._contact}get configuration(){return this._configuration}get transport(){return this._transport}start(){je.debug("start()"),this._status===Tt.STATUS_INIT?this._transport.connect():this._status===Tt.STATUS_USER_CLOSED?(je.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=Tt.STATUS_INIT,this._transport.connect()):this._status===Tt.STATUS_READY?je.debug("UA is in READY status, not restarted"):je.debug("ERROR: connection is down, Auto-Recovery system is trying to reconnect"),this._dynConfiguration.register=this._configuration.register}register(){je.debug("register()"),this._dynConfiguration.register=!0,this._registrator.register()}unregister(n){je.debug("unregister()"),this._dynConfiguration.register=!1,this._registrator.unregister(n)}registrator(){return this._registrator}isRegistered(){return this._registrator.registered}isConnected(){return this._transport.isConnected()}call(n,r){je.debug("call()");const o=new zf(this);return o.connect(n,r),o}sendMessage(n,r,o){je.debug("sendMessage()");const a=new Jf(this);return a.send(n,r,o),a}sendOptions(n,r,o){je.debug("sendOptions()");const a=new Xf(this);return a.send(n,r,o),a}terminateSessions(n){je.debug("terminateSessions()");for(const r in this._sessions)this._sessions[r].isEnded()||this._sessions[r].terminate(n)}stop(){if(je.debug("stop()"),this._dynConfiguration={},this._status===Tt.STATUS_USER_CLOSED){je.debug("UA already closed");return}this._registrator.close();const n=Object.keys(this._sessions).length;for(const o in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,o)){je.debug(`closing session ${o}`);try{this._sessions[o].terminate()}catch{}}for(const o in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,o))try{this._applicants[o].close()}catch{}this._status=Tt.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&n===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}normalizeTarget(n){return ro.normalizeTarget(n,this._configuration.hostport_params)}get(n){switch(n){case"authorization_user":return this._configuration.authorization_user;case"realm":return this._configuration.realm;case"ha1":return this._configuration.ha1;case"authorization_jwt":return this._configuration.authorization_jwt;default:je.warn('get() | cannot get "%s" parameter in runtime',n);return}}set(n,r){switch(n){case"authorization_user":{this._configuration.authorization_user=String(r);break}case"password":{this._configuration.password=String(r);break}case"realm":{this._configuration.realm=String(r);break}case"ha1":{this._configuration.ha1=String(r),this._configuration.password=null;break}case"authorization_jwt":{this._configuration.authorization_jwt=String(r);break}case"display_name":{this._configuration.display_name=r;break}default:return je.warn('set() | cannot set "%s" parameter in runtime',n),!1}return!0}newTransaction(n){this._transactions[n.type][n.id]=n,this.emit("newTransaction",{transaction:n})}destroyTransaction(n){delete this._transactions[n.type][n.id],this.emit("transactionDestroyed",{transaction:n})}newDialog(n){this._dialogs[n.id]=n}destroyDialog(n){delete this._dialogs[n.id]}newMessage(n,r){this._applicants[n]=n,this.emit("newMessage",r)}newOptions(n,r){this._applicants[n]=n,this.emit("newOptions",r)}destroyMessage(n){delete this._applicants[n]}newRTCSession(n,r){this._sessions[n.id]=n,this.emit("newRTCSession",r)}destroyRTCSession(n){delete this._sessions[n.id]}registered(n){this.emit("registered",n)}unregistered(n){this.emit("unregistered",n)}registrationFailed(n){this.emit("registrationFailed",n)}receiveRequest(n){const r=n.method;if(n.ruri.user!==this._configuration.uri.user&&n.ruri.user!==this._contact.uri.user){je.debug("Request-URI does not point to us"),n.method!==gt.ACK&&n.reply_sl(404);return}if(n.ruri.scheme===gt.SIPS){n.reply_sl(416);return}if(tu.checkTransaction(this,n))return;if(r===gt.INVITE?new tu.InviteServerTransaction(this,this._transport,n):r!==gt.ACK&&r!==gt.CANCEL&&new tu.NonInviteServerTransaction(this,this._transport,n),r===gt.OPTIONS){if(this.listeners("newOptions").length===0){n.reply(200);return}new Xf(this).init_incoming(n)}else if(r===gt.MESSAGE){if(this.listeners("newMessage").length===0){n.reply(405);return}new Jf(this).init_incoming(n)}else if(r===gt.INVITE&&!n.to_tag&&this.listeners("newRTCSession").length===0){n.reply(405);return}let o,a;if(n.to_tag)o=this._findDialog(n.call_id,n.from_tag,n.to_tag),o?o.receiveRequest(n):r===gt.NOTIFY?(a=this._findSession(n),a?a.receiveRequest(n):(je.debug("received NOTIFY request for a non existent subscription"),n.reply(481,"Subscription does not exist"))):r!==gt.ACK&&n.reply(481);else switch(r){case gt.INVITE:if(window.RTCPeerConnection)if(n.hasHeader("replaces")){const t=n.replaces;o=this._findDialog(t.call_id,t.from_tag,t.to_tag),o?(a=o.owner,a.isEnded()?n.reply(603):a.receiveRequest(n)):n.reply(481)}else a=new zf(this),a.init_incoming(n);else je.warn("INVITE received but WebRTC is not supported"),n.reply(488);break;case gt.BYE:n.reply(481);break;case gt.CANCEL:a=this._findSession(n),a?a.receiveRequest(n):je.debug("received CANCEL request for a non existent session");break;case gt.ACK:break;case gt.NOTIFY:this.emit("sipEvent",{event:n.event,request:n}),n.reply(200);break;default:n.reply(405);break}}_findSession({call_id:n,from_tag:r,to_tag:o}){const a=n+r,t=this._sessions[a],s=n+o,p=this._sessions[s];return t||p||null}_findDialog(n,r,o){let a=n+r+o,t=this._dialogs[a];return t||(a=n+o+r,t=this._dialogs[a],t||null)}_loadConfig(n){try{nu.load(this._configuration,n)}catch(a){throw a}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=ro.newUUID()),this._configuration.jssip_id=ro.createRandomToken(5);const r=this._configuration.uri.clone();r.user=null,this._configuration.hostport_params=r.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=jg.bind(this),this._transport.onconnect=qg.bind(this),this._transport.ondisconnect=Bg.bind(this),this._transport.ondata=Gg.bind(this)}catch(a){throw je.warn(a),new $g.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const a=this._configuration.uri.clone();a.user=null,a.clearParams(),a.clearHeaders(),this._configuration.registrar_server=a}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new Hg("sip",ro.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(a={}){const t=a.anonymous||null,s=a.outbound||null;let p="<";return t?p+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":p+=this.pub_gruu||this.uri.toString(),s&&(t?!this.temp_gruu:!this.pub_gruu)&&(p+=";ob"),p+=">",p}};const o=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const a in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,a)&&(o.indexOf(a)!==-1?Object.defineProperty(this._configuration,a,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,a,{writable:!1,configurable:!1}));je.debug("configuration parameters after validation:");for(const a in this._configuration)if(Object.prototype.hasOwnProperty.call(nu.settings,a))switch(a){case"uri":case"registrar_server":je.debug(`- ${a}: ${this._configuration[a]}`);break;case"password":case"ha1":case"authorization_jwt":je.debug(`- ${a}: NOT SHOWN`);break;default:je.debug(`- ${a}: ${JSON.stringify(this._configuration[a])}`)}}};function jg(c){this.emit("connecting",c)}function qg(c){this._status!==Tt.STATUS_USER_CLOSED&&(this._status=Tt.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function Bg(c){const n=["nict","ict","nist","ist"];for(const r of n)for(const o in this._transactions[r])Object.prototype.hasOwnProperty.call(this._transactions[r],o)&&this._transactions[r][o].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==Tt.STATUS_USER_CLOSED&&(this._status=Tt.STATUS_NOT_READY,this._error=Tt.NETWORK_ERROR)}function Gg(c){const n=c.transport;let r=c.message;if(r=Fg.parseMessage(r,this),!!r&&!(this._status===Tt.STATUS_USER_CLOSED&&r instanceof su.IncomingRequest)&&Vg(r,this,n)){if(r instanceof su.IncomingRequest)r.transport=n,this.receiveRequest(r);else if(r instanceof su.IncomingResponse){let o;switch(r.method){case gt.INVITE:o=this._transactions.ict[r.via_branch],o&&o.receiveResponse(r);break;case gt.ACK:break;default:o=this._transactions.nict[r.via_branch],o&&o.receiveResponse(r);break}}}}const Wg=it(Qf);var Me=pt();const ru=it(Me),iu=new of("Dialog"),Is={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};class io{static get C(){return Is}constructor(n,r,o,a=Is.STATUS_CONFIRMED){if(this._owner=n,this._ua=n._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,r instanceof Pt.IncomingResponse&&(a=r.status_code<200?Is.STATUS_EARLY:Is.STATUS_CONFIRMED),o==="UAS"){this._id={call_id:r.call_id,local_tag:r.to_tag,remote_tag:r.from_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=a,this._remote_seqnum=r.cseq,this._local_uri=r.parseHeader("to").uri,this._remote_uri=r.parseHeader("from").uri;let t=r.getHeaders("to")[0].split(";")[0];t=t.match(/<([^>]*)>/)[1],this._remote_target=t,this._route_set=r.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum}else if(o==="UAC"){this._id={call_id:r.call_id,local_tag:r.from_tag,remote_tag:r.to_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=a,this._local_seqnum=r.cseq,this._local_uri=r.parseHeader("from").uri,this._remote_uri=r.parseHeader("to").uri;let t=r.getHeaders("to")[0].split(";")[0];t=t.match(/<([^>]*)>/)[1],this._remote_target=t,this._route_set=r.getHeaders("record-route").reverse(),this._ack_seqnum=null}this._ua.newDialog(this),iu.debug(`new ${o} dialog created with status ${this._state===Is.STATUS_EARLY?"EARLY":"CONFIRMED"}`)}get id(){return this._id}get local_seqnum(){return this._local_seqnum}set local_seqnum(n){this._local_seqnum=n}get owner(){return this._owner}get uac_pending_reply(){return this._uac_pending_reply}set uac_pending_reply(n){this._uac_pending_reply=n}get uas_pending_reply(){return this._uas_pending_reply}isTerminated(){return this._status===Is.STATUS_TERMINATED}update(n,r){this._state=Is.STATUS_CONFIRMED,iu.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),r==="UAC"&&(this._route_set=n.getHeaders("record-route").reverse())}terminate(){iu.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=Is.STATUS_TERMINATED}sendRequest(n,r={}){const o=ru.cloneArray(r.extraHeaders),a=ru.cloneObject(r.eventHandlers),t=r.body||null,s=this._createRequest(n,o,t);return a.onAuthenticated=()=>{this._local_seqnum+=1},new Dm(this,s,a).send(),s}receiveRequest(n){this._checkInDialogRequest(n)&&(n.method===q.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:n.method===q.INVITE&&(this._ack_seqnum=n.cseq),this._owner.receiveRequest(n))}_createRequest(n,r,o){r=ru.cloneArray(r),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));const a=n===q.CANCEL||n===q.ACK?this._local_seqnum:this._local_seqnum+=1;return new Pt.OutgoingRequest(n,this._remote_target,this._ua,{cseq:a,call_id:this._id.call_id,from_uri:this._local_uri,from_tag:this._id.local_tag,to_uri:this._remote_uri,to_tag:this._id.remote_tag,route_set:this._route_set},r,o)}_checkInDialogRequest(n){if(!this._remote_seqnum)this._remote_seqnum=n.cseq;else if(n.cseq<this._remote_seqnum)if(n.method===q.ACK){if(this._ack_seqnum===null||n.cseq!==this._ack_seqnum)return!1}else return n.reply(500),!1;else n.cseq>this._remote_seqnum&&(this._remote_seqnum=n.cseq);if(n.method===q.INVITE||n.method===q.UPDATE&&n.body){if(this._uac_pending_reply===!0)n.reply(491);else if(this._uas_pending_reply===!0){const r=(Math.random()*10|0)+1;return n.reply(500,null,[`Retry-After:${r}`]),!1}else{this._uas_pending_reply=!0;const r=()=>{(n.server_transaction.state===Lt.C.STATUS_ACCEPTED||n.server_transaction.state===Lt.C.STATUS_COMPLETED||n.server_transaction.state===Lt.C.STATUS_TERMINATED)&&(n.server_transaction.removeListener("stateChanged",r),this._uas_pending_reply=!1)};n.server_transaction.on("stateChanged",r)}n.hasHeader("contact")&&n.server_transaction.on("stateChanged",()=>{n.server_transaction.state===Lt.C.STATUS_ACCEPTED&&(this._remote_target=n.parseHeader("contact").uri)})}else n.method===q.NOTIFY&&n.hasHeader("contact")&&n.server_transaction.on("stateChanged",()=>{n.server_transaction.state===Lt.C.STATUS_COMPLETED&&(this._remote_target=n.parseHeader("contact").uri)});return!0}}var Kg=us();const Gr=it(Kg);function Yg(c){const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let r="";for(let o=0;o<c;o++){const a=Math.floor(Math.random()*n.length);r+=n.substring(a,a+1)}return r}const Q=new of("JanusSession"),te={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},lo=["audio","video"];class oo extends ut.EventEmitter{static get C(){return te}constructor(n){Q.debug("new"),super(),console.log("constructor call"),this._id=null,this._ua=n,this._status=te.STATUS_NULL,this._dialog=null,this._earlyDialogs={},this._contact=null,this._from_tag=null,this._to_tag=null,this.lastTransaction=0,this._connection=null,this._connectionPromiseQueue=Promise.resolve(),this._request=null,this._is_canceled=!1,this._cancel_reason="",this._is_confirmed=!1,this._late_sdp=!1,this._rtcOfferConstraints=null,this._rtcAnswerConstraints=null,this._localMediaStream=null,this._localMediaStreamLocallyGenerated=!1,this._rtcReady=!0,this._iceReady=!1,this._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},this._direction=null,this._local_identity=null,this._remote_identity=null,this._start_time=null,this._end_time=null,this._audioMuted=!1,this._videoMuted=!1,this._localHold=!1,this._remoteHold=!1,this._sessionTimers={enabled:this._ua.configuration.session_timers,refreshMethod:this._ua.configuration.session_timers_refresh_method,defaultExpires:q.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._data={}}get C(){return te}get causes(){return q.causes}get id(){return this._id}get connection(){return this._connection}get contact(){return this._contact}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}get start_time(){return this._start_time}get end_time(){return this._end_time}get data(){return this._data}set data(n){this._data=n}get status(){return this._status}isInProgress(){switch(this._status){case te.STATUS_NULL:case te.STATUS_INVITE_SENT:case te.STATUS_1XX_RECEIVED:case te.STATUS_INVITE_RECEIVED:case te.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case te.STATUS_ANSWERED:case te.STATUS_WAITING_FOR_ACK:case te.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case te.STATUS_CANCELED:case te.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}connect(n,r={},o){Q.debug("connect()");const a=n,t=Me.cloneObject(r.eventHandlers),s=Me.cloneArray(r.extraHeaders),p=Me.cloneObject(r.mediaConstraints,{audio:!0,video:!0}),_=r.mediaStream||null,d=Me.cloneObject(r.pcConfig,{iceServers:[]}),g=r.rtcConstraints||null,T=r.rtcOfferConstraints||null;if(this._rtcOfferConstraints=T,this._rtcAnswerConstraints=r.rtcAnswerConstraints||null,this._data=r.data||this._data,n===void 0)throw new TypeError("Not enough arguments");if(this._status!==te.STATUS_NULL)throw new Ks.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new Ks.NotSupportedError("WebRTC not supported");if(console.log("target",n),n=this._ua.normalizeTarget(n),console.log("normalizeTarget target",n),!n)throw new TypeError(`Invalid target: ${a}`);this._sessionTimers.enabled&&Me.isDecimal(r.sessionTimersExpires)&&(r.sessionTimersExpires>=q.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=r.sessionTimersExpires:this._sessionTimers.defaultExpires=q.SESSION_EXPIRES);for(const A in t)Object.prototype.hasOwnProperty.call(t,A)&&this.on(A,t[A]);this._from_tag=Me.newTag();const E=r.anonymous||!1,y={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:E,outbound:!0}),E?(y.from_display_name="Anonymous",y.from_uri=new Gr("sip","anonymous","anonymous.invalid"),s.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),s.push("Privacy: id")):r.fromUserName&&(y.from_uri=new Gr("sip",r.fromUserName,this._ua.configuration.uri.host),s.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),r.fromDisplayName&&(y.from_display_name=r.fromDisplayName),s.push(`Contact: ${this._contact}`),s.push("Content-Type: application/json"),this._sessionTimers.enabled&&s.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new Pt.InitialOutgoingInviteRequest(n,this._ua,y,s),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(d,g),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,console.log("this._remote_identity",this._remote_identity),o&&o(this),this._newJanusSession("local",this._request),this._sendInitialRequest(p,T,_)}init_incoming(n,r){Q.debug("init_incoming()");let o;const a=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0;if(n.body&&a!=="application/sdp"){n.reply(415);return}if(this._status=te.STATUS_INVITE_RECEIVED,this._from_tag=n.from_tag,this._id=n.call_id+this._from_tag,this._request=n,this._contact=this._ua.contact.toString(),n.hasHeader("expires")&&(o=n.getHeader("expires")*1e3),n.to_tag=Me.newTag(),!this._createDialog(n,"UAS",!0)){n.reply(500,"Missing Contact header field");return}n.body?this._late_sdp=!1:this._late_sdp=!0,this._status=te.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{n.reply(408),this._failed("local",null,q.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),o&&(this._timers.expiresTimer=setTimeout(()=>{this._status===te.STATUS_WAITING_FOR_ANSWER&&(n.reply(487),this._failed("system",null,q.causes.EXPIRES))},o)),this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from,r&&r(this),this._newJanusSession("remote",n),this._status!==te.STATUS_TERMINATED&&(n.reply(180,null,[`Contact: ${this._contact}`]),this._progress("local",null))}answer(n={}){Q.debug("answer()");const r=this._request,o=Me.cloneArray(n.extraHeaders),a=Me.cloneObject(n.mediaConstraints),t=n.mediaStream||null,s=Me.cloneObject(n.pcConfig,{iceServers:[]}),p=n.rtcConstraints||null,_=n.rtcAnswerConstraints||null,d=Me.cloneObject(n.rtcOfferConstraints);let g,T=!1,E=!1,y=!1,A=!1;if(this._rtcAnswerConstraints=_,this._rtcOfferConstraints=n.rtcOfferConstraints||null,this._data=n.data||this._data,this._direction!=="incoming")throw new Ks.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==te.STATUS_WAITING_FOR_ANSWER)throw new Ks.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Me.isDecimal(n.sessionTimersExpires)&&(n.sessionTimersExpires>=q.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=n.sessionTimersExpires:this._sessionTimers.defaultExpires=q.SESSION_EXPIRES),this._status=te.STATUS_ANSWERED,!this._createDialog(r,"UAS")){r.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),o.unshift(`Contact: ${this._contact}`);const R=r.parseSDP();Array.isArray(R.media)||(R.media=[R.media]);for(const I of R.media)I.type==="audio"&&(T=!0,(!I.direction||I.direction==="sendrecv")&&(y=!0)),I.type==="video"&&(E=!0,(!I.direction||I.direction==="sendrecv")&&(A=!0));if(t&&a.audio===!1){g=t.getAudioTracks();for(const I of g)t.removeTrack(I)}if(t&&a.video===!1){g=t.getVideoTracks();for(const I of g)t.removeTrack(I)}!t&&a.audio===void 0&&(a.audio=y),!t&&a.video===void 0&&(a.video=A),!t&&!T&&!d.offerToReceiveAudio&&(a.audio=!1),!t&&!E&&!d.offerToReceiveVideo&&(a.video=!1),this._createRTCConnection(s,p),Promise.resolve().then(()=>{if(t)return t;if(a.audio||a.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(a).catch(I=>{throw this._status===te.STATUS_TERMINATED?new Error("terminated"):(r.reply(480),this._failed("local",null,q.causes.USER_DENIED_MEDIA_ACCESS),Q.warn('emit "getusermediafailed" [error:%o]',I),this.emit("getusermediafailed",I),new Error("getUserMedia() failed"))})}).then(I=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=I,I&&I.getTracks().forEach($=>{this._connection.addTrack($,I)})}).then(()=>{if(this._late_sdp)return;const I={originator:"remote",type:"offer",sdp:r.body};Q.debug('emit "sdp"'),this.emit("sdp",I);const $=new RTCSessionDescription({type:"offer",sdp:I.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription($)).catch(L=>{throw r.reply(488),this._failed("system",null,q.causes.WEBRTC_ERROR),Q.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',L),this.emit("peerconnection:setremotedescriptionfailed",L),new Error("peerconnection.setRemoteDescription() failed")}),this._connectionPromiseQueue}).then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._connecting(r),this._late_sdp?this._createLocalDescription("offer",this._rtcOfferConstraints).catch(()=>{throw r.reply(500),new Error("_createLocalDescription() failed")}):this._createLocalDescription("answer",_).catch(()=>{throw r.reply(500),new Error("_createLocalDescription() failed")})}).then(I=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(r,o),r.reply(200,null,o,I,()=>{this._status=te.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(r,I),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,q.causes.CONNECTION_ERROR)})}).catch(I=>{this._status!==te.STATUS_TERMINATED&&Q.warn(I)})}terminate(n={}){Q.debug("terminate()");const r=n.cause||q.causes.BYE,o=Me.cloneArray(n.extraHeaders),a=n.body;let t,s=n.status_code,p=n.reason_phrase;if(this._status===te.STATUS_TERMINATED)throw new Ks.InvalidStateError(this._status);switch(this._status){case te.STATUS_NULL:case te.STATUS_INVITE_SENT:case te.STATUS_1XX_RECEIVED:if(Q.debug("canceling session"),s&&(s<200||s>=700))throw new TypeError(`Invalid status_code: ${s}`);s&&(p=p||q.REASON_PHRASE[s]||"",t=`SIP ;cause=${s} ;text="${p}"`),this._status===te.STATUS_NULL||this._status===te.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=t):this._status===te.STATUS_1XX_RECEIVED&&this._request.cancel(t),this._status=te.STATUS_CANCELED,this._failed("local",null,q.causes.CANCELED);break;case te.STATUS_WAITING_FOR_ANSWER:case te.STATUS_ANSWERED:if(Q.debug("rejecting session"),s=s||480,s<300||s>=700)throw new TypeError(`Invalid status_code: ${s}`);this._request.reply(s,p,o,a),this._failed("local",null,q.causes.REJECTED);break;case te.STATUS_WAITING_FOR_ACK:case te.STATUS_CONFIRMED:if(Q.debug("terminating session"),p=n.reason_phrase||q.REASON_PHRASE[s]||"",s&&(s<200||s>=700))throw new TypeError(`Invalid status_code: ${s}`);if(s&&o.push(`Reason: SIP ;cause=${s}; text="${p}"`),this._status===te.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Lt.C.STATUS_TERMINATED){const _=this._dialog;this.receiveRequest=({method:d})=>{d===q.ACK&&(this.sendRequest(q.BYE,{extraHeaders:o,body:a}),_.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Lt.C.STATUS_TERMINATED&&(this.sendRequest(q.BYE,{extraHeaders:o,body:a}),_.terminate())}),this._ended("local",null,r),this._dialog=_,console.log("SET DIALOG terminate"),this._ua.newDialog(_)}else this.sendRequest(q.BYE,{extraHeaders:o,body:a}),this._ended("local",null,r)}}sendInfo(n,r,o={}){if(Q.debug("sendInfo()"),this._status!==te.STATUS_CONFIRMED&&this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_1XX_RECEIVED)throw new Ks.InvalidStateError(this._status);new Va(this).send(n,r,o)}mute(n={audio:!0,video:!1}){Q.debug("mute()");let r=!1,o=!1;this._audioMuted===!1&&n.audio&&(r=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&n.video&&(o=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(r===!0||o===!0)&&this._onmute({audio:r,video:o})}unmute(n={audio:!0,video:!0}){Q.debug("unmute()");let r=!1,o=!1;this._audioMuted===!0&&n.audio&&(r=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&n.video&&(o=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(r===!0||o===!0)&&this._onunmute({audio:r,video:o})}hold(n={},r){if(Q.debug("hold()"),this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");const o={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:q.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return n.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:o,extraHeaders:n.extraHeaders}):this._sendReinvite({eventHandlers:o,extraHeaders:n.extraHeaders}),!0}unhold(n={},r){if(Q.debug("unhold()"),this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");const o={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:q.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return n.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:o,extraHeaders:n.extraHeaders}):this._sendReinvite({eventHandlers:o,extraHeaders:n.extraHeaders}),!0}renegotiate(n={},r){Q.debug("renegotiate()");const o=n.rtcOfferConstraints||null;if(this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;const a={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:q.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),n.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,rtcOfferConstraints:o,extraHeaders:n.extraHeaders}):this._sendReinvite({eventHandlers:a,rtcOfferConstraints:o,extraHeaders:n.extraHeaders}),!0}refer(n,r){Q.debug("refer()");const o=n;if(this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;if(n=this._ua.normalizeTarget(n),!n)throw new TypeError(`Invalid target: ${o}`);const a=new zm(this);a.sendRefer(n,r);const t=a.id;return this._referSubscribers[t]=a,a.on("requestFailed",()=>{delete this._referSubscribers[t]}),a.on("accepted",()=>{delete this._referSubscribers[t]}),a.on("failed",()=>{delete this._referSubscribers[t]}),a}sendRequest(n,r){return Q.debug("sendRequest()"),this._dialog.sendRequest(n,r)}receiveRequest(n){if(Q.debug("receiveRequest()"),n.method===q.CANCEL)(this._status===te.STATUS_WAITING_FOR_ANSWER||this._status===te.STATUS_ANSWERED)&&(this._status=te.STATUS_CANCELED,this._request.reply(487),this._failed("remote",n,q.causes.CANCELED));else switch(n.method){case q.ACK:if(this._status!==te.STATUS_WAITING_FOR_ACK)return;if(this._status=te.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!n.body){this.terminate({cause:q.causes.MISSING_SDP,status_code:400});break}const r={originator:"remote",type:"answer",sdp:n.body};Q.debug('emit "sdp"'),this.emit("sdp",r);const o=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>{this._is_confirmed||this._confirmed("remote",n)}).catch(a=>{this.terminate({cause:q.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),Q.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})}else this._is_confirmed||this._confirmed("remote",n);break;case q.BYE:this._status===te.STATUS_CONFIRMED||this._status===te.STATUS_WAITING_FOR_ACK?(n.reply(200),this._ended("remote",n,q.causes.BYE)):this._status===te.STATUS_INVITE_RECEIVED||this._status===te.STATUS_WAITING_FOR_ANSWER?(n.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",n,q.causes.BYE)):n.reply(403,"Wrong Status");break;case q.INVITE:this._status===te.STATUS_CONFIRMED?n.hasHeader("replaces")?this._receiveReplaces(n):this._receiveReinvite(n):n.reply(403,"Wrong Status");break;case q.INFO:if(this._status===te.STATUS_1XX_RECEIVED||this._status===te.STATUS_WAITING_FOR_ANSWER||this._status===te.STATUS_ANSWERED||this._status===te.STATUS_WAITING_FOR_ACK||this._status===te.STATUS_CONFIRMED){const r=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0;r&&r.match(/^application\/dtmf-relay/i)?new $m(this).init_incoming(n):r!==void 0?new Va(this).init_incoming(n):n.reply(415)}else n.reply(403,"Wrong Status");break;case q.UPDATE:this._status===te.STATUS_CONFIRMED?this._receiveUpdate(n):n.reply(403,"Wrong Status");break;case q.REFER:this._status===te.STATUS_CONFIRMED?this._receiveRefer(n):n.reply(403,"Wrong Status");break;case q.NOTIFY:this._status===te.STATUS_CONFIRMED?this._receiveNotify(n):n.reply(403,"Wrong Status");break;default:n.reply(501)}}onTransportError(){Q.warn("onTransportError()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:q.causes.CONNECTION_ERROR,cause:q.causes.CONNECTION_ERROR})}onRequestTimeout(){Q.warn("onRequestTimeout()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:q.causes.REQUEST_TIMEOUT,cause:q.causes.REQUEST_TIMEOUT})}onDialogError(){Q.warn("onDialogError()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:q.causes.DIALOG_ERROR,cause:q.causes.DIALOG_ERROR})}newDTMF(n){Q.debug("newDTMF()"),this.emit("newDTMF",n)}newInfo(n){Q.debug("newInfo()"),this.emit("newInfo",n)}_isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(Q.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(Q.debug("_isReadyToReOffer() | session not established yet"),!1):(Q.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}_close(){if(Q.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(Q.debug("close() | closing local MediaStream"),Me.closeMediaStream(this._localMediaStream)),this._status!==te.STATUS_TERMINATED){if(this._status=te.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(n){Q.warn("close() | error closing the RTCPeerConnection: %o",n)}for(const n in this._timers)Object.prototype.hasOwnProperty.call(this._timers,n)&&clearTimeout(this._timers[n]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const n in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,n)&&(this._earlyDialogs[n].terminate(),delete this._earlyDialogs[n]);for(const n in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,n)&&delete this._referSubscribers[n];this._ua.destroyRTCSession(this)}}_setInvite2xxTimer(n,r){let o=Pr.T1;function a(){this._status===te.STATUS_WAITING_FOR_ACK&&(n.reply(200,null,[`Contact: ${this._contact}`],r),o<Pr.T2&&(o=o*2,o>Pr.T2&&(o=Pr.T2)),this._timers.invite2xxTimer=setTimeout(a.bind(this),o))}this._timers.invite2xxTimer=setTimeout(a.bind(this),o)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===te.STATUS_WAITING_FOR_ACK&&(Q.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(q.BYE),this._ended("remote",null,q.causes.NO_ACK))},Pr.TIMER_H)}_createRTCConnection(n,r){this._connection=new RTCPeerConnection(n,r),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:q.causes.RTP_TIMEOUT,status_code:408,reason_phrase:q.causes.RTP_TIMEOUT})}),Q.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(n,r){if(Q.debug("createLocalDescription()"),n!=="offer"&&n!=="answer")throw new Error(`createLocalDescription() | invalid type "${n}"`);const o=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>n==="offer"?o.createOffer(r).catch(a=>(Q.warn('emit "peerconnection:createofferfailed" [error:%o]',a),this.emit("peerconnection:createofferfailed",a),Promise.reject(a))):o.createAnswer(r).catch(a=>(Q.warn('emit "peerconnection:createanswerfailed" [error:%o]',a),this.emit("peerconnection:createanswerfailed",a),Promise.reject(a)))).then(a=>o.setLocalDescription(a).catch(t=>(this._rtcReady=!0,Q.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',t),this.emit("peerconnection:setlocaldescriptionfailed",t),Promise.reject(t)))).then(()=>{const a=r&&r.iceRestart;if(o.iceGatheringState==="complete"&&!a||o.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const t={originator:"local",type:n,sdp:o.localDescription.sdp};return Q.debug('emit "sdp"'),this.emit("sdp",t),Promise.resolve(t.sdp)}return new Promise(t=>{let s=!1,p,_;this._iceReady=!1;const d=()=>{o.removeEventListener("icecandidate",p),o.removeEventListener("icegatheringstatechange",_),s=!0,this._rtcReady=!0,this._iceReady=!0;const g={originator:"local",type:n,sdp:o.localDescription.sdp};Q.debug('emit "sdp"'),this.emit("sdp",g),t(g.sdp)};o.addEventListener("icecandidate",p=g=>{const T=g.candidate;T?this.emit("icecandidate",{candidate:T,ready:d}):s||d()}),o.addEventListener("icegatheringstatechange",_=()=>{o.iceGatheringState==="complete"&&!s&&d()})})})}_createDialog(n,r,o){console.log("_createDialog",n);const a=r==="UAS"?n.to_tag:n.from_tag,t=r==="UAS"?n.from_tag:n.to_tag,s=n.call_id+a+t;console.log("remote_tag",t);let p=this._earlyDialogs[s];if(o)return p?!0:(p=new io(this,n,r,io.C.STATUS_EARLY),console.log("SET DIALOG early"),p.error?(console.log("early_dialog error",p.error),Q.debug(p.error),this._failed("remote",n,q.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[s]=p,!0));{if(this._from_tag=n.from_tag,this._to_tag=n.to_tag,p)return p.update(n,r),console.log("SET DIALOG 1"),this._dialog=p,delete this._earlyDialogs[s],!0;const _=new io(this,n,r);return _.error?(console.log("dialog.error",_.error),Q.debug(_.error),this._failed("remote",n,q.causes.INTERNAL_ERROR),!1):(console.log("AAA SET DIALOG 2"),this._dialog=_,!0)}}_receiveReinvite(n){Q.debug("receiveReinvite()");const r=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0,o={request:n,callback:void 0,reject:t.bind(this)};let a=!1;function t(p={}){a=!0;const _=p.status_code||403,d=p.reason_phrase||"",g=Me.cloneArray(p.extraHeaders);if(this._status!==te.STATUS_CONFIRMED)return!1;if(_<300||_>=700)throw new TypeError(`Invalid status_code: ${_}`);n.reply(_,d,g)}if(this.emit("reinvite",o),a)return;if(this._late_sdp=!1,!n.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",this._rtcOfferConstraints)).then(p=>{s.call(this,p)}).catch(()=>{n.reply(500)});return}if(r!=="application/sdp"){Q.debug("invalid Content-Type"),n.reply(415);return}this._processInDialogSdpOffer(n).then(p=>{this._status!==te.STATUS_TERMINATED&&s.call(this,p)}).catch(p=>{Q.warn(p)});function s(p){const _=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(n,_),this._late_sdp&&(p=this._mangleOffer(p)),n.reply(200,null,_,p,()=>{this._status=te.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(n,p),this._setACKTimer()}),typeof o.callback=="function"&&o.callback()}}_receiveUpdate(n){Q.debug("receiveUpdate()");const r=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0,o={request:n,callback:void 0,reject:t.bind(this)};let a=!1;function t(p={}){a=!0;const _=p.status_code||403,d=p.reason_phrase||"",g=Me.cloneArray(p.extraHeaders);if(this._status!==te.STATUS_CONFIRMED)return!1;if(_<300||_>=700)throw new TypeError(`Invalid status_code: ${_}`);n.reply(_,d,g)}if(this.emit("update",o),a)return;if(!n.body){s.call(this,null);return}if(r!=="application/sdp"){Q.debug("invalid Content-Type"),n.reply(415);return}this._processInDialogSdpOffer(n).then(p=>{this._status!==te.STATUS_TERMINATED&&s.call(this,p)}).catch(p=>{Q.warn(p)});function s(p){const _=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(n,_),n.reply(200,null,_,p),typeof o.callback=="function"&&o.callback()}}_processInDialogSdpOffer(n){Q.debug("_processInDialogSdpOffer()");const r=n.parseSDP();let o=!1;for(const s of r.media){if(lo.indexOf(s.type)===-1)continue;const p=s.direction||r.direction||"sendrecv";if(p==="sendonly"||p==="inactive")o=!0;else{o=!1;break}}const a={originator:"remote",type:"offer",sdp:n.body};Q.debug('emit "sdp"'),this.emit("sdp",a);const t=new RTCSessionDescription({type:"offer",sdp:a.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._connection.setRemoteDescription(t).catch(s=>{throw n.reply(488),Q.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',s),this.emit("peerconnection:setremotedescriptionfailed",s),s})}).then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._remoteHold===!0&&o===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&o===!0&&(this._remoteHold=!0,this._onhold("remote"))}).then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._createLocalDescription("answer",this._rtcAnswerConstraints).catch(s=>{throw n.reply(500),Q.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',s),s})}).catch(s=>{Q.warn("_processInDialogSdpOffer() failed [error: %o]",s)}),this._connectionPromiseQueue}_receiveRefer(n){if(Q.debug("receiveRefer()"),!n.refer_to){Q.debug("no Refer-To header field present in REFER"),n.reply(400);return}if(n.refer_to.uri.scheme!==q.SIP){Q.debug("Refer-To header field points to a non-SIP URI scheme"),n.reply(416);return}n.reply(202);const r=new Gm(this,n.cseq);Q.debug('emit "refer"'),this.emit("refer",{request:n,accept:(t,s)=>{o.call(this,t,s)},reject:()=>{a.call(this)}});function o(t,s={}){if(t=typeof t=="function"?t:null,this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;const p=new oo(this._ua);if(p.on("progress",({response:_})=>{r.notify(_.status_code,_.reason_phrase)}),p.on("accepted",({response:_})=>{r.notify(_.status_code,_.reason_phrase)}),p.on("_failed",({message:_,cause:d})=>{_?r.notify(_.status_code,_.reason_phrase):r.notify(487,d)}),n.refer_to.uri.hasHeader("replaces")){const _=decodeURIComponent(n.refer_to.uri.getHeader("replaces"));s.extraHeaders=Me.cloneArray(s.extraHeaders),s.extraHeaders.push(`Replaces: ${_}`)}p.connect(n.refer_to.uri.toAor(),s,t)}function a(){r.notify(603)}}_receiveNotify(n){switch(Q.debug("receiveNotify()"),n.event||n.reply(400),n.event.event){case"refer":{let r,o;if(n.event.params&&n.event.params.id)r=n.event.params.id,o=this._referSubscribers[r];else if(Object.keys(this._referSubscribers).length===1)o=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{n.reply(400,"Missing event id parameter");return}if(!o){n.reply(481,"Subscription does not exist");return}o.receiveNotify(n),n.reply(200);break}default:n.reply(489)}}_receiveReplaces(n){Q.debug("receiveReplaces()");function r(a){if(this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;const t=new oo(this._ua);t.on("confirmed",()=>{this.terminate()}),t.init_incoming(n,a)}function o(){Q.debug("Replaced INVITE rejected by the user"),n.reply(486)}this.emit("replaces",{request:n,accept:a=>{r.call(this,a)},reject:()=>{o.call(this)}})}_getNextTransactionId(){return(this.lastTransaction+1).toString()}_sendInitialRequest(n,r,o){this.ackSent=!1;const a=new yf(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:t=>{this._request=t},onReceiveResponse:t=>{this._receiveInviteResponse(t)}});Promise.resolve().then(()=>{if(o)return o;if(n.audio||n.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(n).catch(t=>{throw this._status===te.STATUS_TERMINATED?new Error("terminated"):(this._failed("local",null,q.causes.USER_DENIED_MEDIA_ACCESS),Q.warn('emit "getusermediafailed" [error:%o]',t),this.emit("getusermediafailed",t),t)})}).then(t=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._localMediaStream=t,t&&t.getTracks().forEach(s=>{this._connection.addTrack(s,t)}),this._connecting(this._request),this._createLocalDescription("offer",r).catch(s=>{throw this._failed("local",null,q.causes.WEBRTC_ERROR),s})}).then(t=>{if(this._is_canceled||this._status===te.STATUS_TERMINATED)throw new Error("terminated");const p=JSON.stringify({janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:"videoroomtest-uzkIUidc1969"});this._request.body=p,this._status=te.STATUS_INVITE_SENT,Q.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),a.send()}).catch(t=>{this._status!==te.STATUS_TERMINATED&&Q.warn(t)})}_receiveInviteResponse(n){if(Q.debug("receiveInviteResponse()"),console.log("_receiveInviteResponse response",n),console.log("dialog",this._dialog),this._dialog&&n.status_code>=200&&n.status_code<=299&&!this.ackSent)if(console.log("IF 1 dialog"),this._dialog.id.call_id===n.call_id&&this._dialog.id.local_tag===n.from_tag&&this._dialog.id.remote_tag===n.to_tag){console.log("IF 1 SEND ACK"),this.ackSent=!0,this.sendRequest(q.ACK);return}else{const r=new io(this,n,"UAC");if(r.error!==void 0){Q.debug(r.error);return}this.sendRequest(q.ACK),this.sendRequest(q.BYE);return}if(this.ackSent){const r=JSON.parse(n.body);this.session_id=r.session_id,this.handle_id=r.data.id;const a={janus:"message",body:{request:"join",room:"abcd",ptype:"publisher",display:"User1",clientID:"dufgjb023gh4vr872v238ugf2y82g4",opaque_id:`videoroomtest-${Yg(12)}`},handle_id:this.handle_id},t=["PTYPE: Publisher"];console.log("JOIN MESSAGE",a),this.sendRequest(q.SUBSCRIBE,{extraHeaders:t,body:JSON.stringify(a)})}if(this._is_canceled){console.log("IF 2 canceled"),n.status_code>=100&&n.status_code<200?this._request.cancel(this._cancel_reason):n.status_code>=200&&n.status_code<299&&(console.log("IF 2 _acceptAndTerminate"),this._acceptAndTerminate(n));return}if(console.log("IF 2 this._status",this._status),this._status!==te.STATUS_INVITE_SENT&&this._status!==te.STATUS_1XX_RECEIVED){console.log("IF 3 not invite sent");return}switch(!0){case/^100$/.test(n.status_code):console.log("IF 4 SWITCH 1"),this._status=te.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(n.status_code):{if(console.log("IF 5 SWITCH 2"),!n.to_tag){console.log("IF 5 break"),Q.debug("1xx response received without to tag");break}if(n.hasHeader("contact")&&(console.log("IF 5 contact"),!this._createDialog(n,"UAC",!0))){console.log("IF 5 _createDialog break");break}if(this._status=te.STATUS_1XX_RECEIVED,!n.body){console.log("IF 5 !response.body"),this._progress("remote",n);break}const r={originator:"remote",type:"answer",sdp:n.body};Q.debug('emit "sdp"'),this.emit("sdp",r);const o=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>this._progress("remote",n)).catch(a=>{Q.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)});break}case/^2[0-9]{2}$/.test(n.status_code):{if(console.log("IF 6 SWITCH 3"),this._status=te.STATUS_CONFIRMED,!n.body){console.log("IF 6 !response.body"),this._acceptAndTerminate(n,400,q.causes.MISSING_SDP),this._failed("remote",n,q.causes.BAD_MEDIA_DESCRIPTION);break}if(console.log("AAA _createDialog"),!this._createDialog(n,"UAC"))break;break}default:{console.log("IF 7 SWITCH 4");const r=Me.sipErrorCause(n.status_code);this._failed("remote",n,r)}}}_sendReinvite(n={}){Q.debug("sendReinvite()");const r=Me.cloneArray(n.extraHeaders),o=Me.cloneObject(n.eventHandlers),a=n.rtcOfferConstraints||this._rtcOfferConstraints||null;let t=!1;r.push(`Contact: ${this._contact}`),r.push("Content-Type: application/sdp"),this._sessionTimers.running&&r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",a)).then(_=>{_=this._mangleOffer(_);const d={originator:"local",type:"offer",sdp:_};Q.debug('emit "sdp"'),this.emit("sdp",d),this.sendRequest(q.INVITE,{extraHeaders:r,body:_,eventHandlers:{onSuccessResponse:g=>{s.call(this,g),t=!0},onErrorResponse:g=>{p.call(this,g)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{p()});function s(_){if(this._status===te.STATUS_TERMINATED||(this.sendRequest(q.ACK),t))return;if(this._handleSessionTimersInIncomingResponse(_),_.body){if(!_.hasHeader("Content-Type")||_.getHeader("Content-Type").toLowerCase()!=="application/sdp"){p.call(this);return}}else{p.call(this);return}const d={originator:"remote",type:"answer",sdp:_.body};Q.debug('emit "sdp"'),this.emit("sdp",d);const g=new RTCSessionDescription({type:"answer",sdp:d.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(g)).then(()=>{o.succeeded&&o.succeeded(_)}).catch(T=>{p.call(this),Q.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',T),this.emit("peerconnection:setremotedescriptionfailed",T)})}function p(_){o.failed&&o.failed(_)}}_sendUpdate(n={}){Q.debug("sendUpdate()");const r=Me.cloneArray(n.extraHeaders),o=Me.cloneObject(n.eventHandlers),a=n.rtcOfferConstraints||this._rtcOfferConstraints||null,t=n.sdpOffer||!1;let s=!1;r.push(`Contact: ${this._contact}`),this._sessionTimers.running&&r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),t?(r.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",a)).then(d=>{d=this._mangleOffer(d);const g={originator:"local",type:"offer",sdp:d};Q.debug('emit "sdp"'),this.emit("sdp",g),this.sendRequest(q.UPDATE,{extraHeaders:r,body:d,eventHandlers:{onSuccessResponse:T=>{p.call(this,T),s=!0},onErrorResponse:T=>{_.call(this,T)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{_.call(this)})):this.sendRequest(q.UPDATE,{extraHeaders:r,eventHandlers:{onSuccessResponse:d=>{p.call(this,d)},onErrorResponse:d=>{_.call(this,d)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function p(d){if(this._status!==te.STATUS_TERMINATED&&!s)if(this._handleSessionTimersInIncomingResponse(d),t){if(d.body){if(!d.hasHeader("Content-Type")||d.getHeader("Content-Type").toLowerCase()!=="application/sdp"){_.call(this);return}}else{_.call(this);return}const g={originator:"remote",type:"answer",sdp:d.body};Q.debug('emit "sdp"'),this.emit("sdp",g);const T=new RTCSessionDescription({type:"answer",sdp:g.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(T)).then(()=>{o.succeeded&&o.succeeded(d)}).catch(E=>{_.call(this),Q.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',E),this.emit("peerconnection:setremotedescriptionfailed",E)})}else o.succeeded&&o.succeeded(d)}function _(d){o.failed&&o.failed(d)}}_acceptAndTerminate(n,r,o){Q.debug("acceptAndTerminate()");const a=[];r&&(o=o||q.REASON_PHRASE[r]||"",a.push(`Reason: SIP ;cause=${r}; text="${o}"`)),(this._dialog||this._createDialog(n,"UAC"))&&(this.sendRequest(q.ACK),this.sendRequest(q.BYE,{extraHeaders:a})),this._status=te.STATUS_TERMINATED}_mangleOffer(n){if(!this._localHold&&!this._remoteHold)return n;if(n=wt.parse(n),this._localHold&&!this._remoteHold){Q.debug("mangleOffer() | me on hold, mangling offer");for(const r of n.media)lo.indexOf(r.type)!==-1&&(r.direction?r.direction==="sendrecv"?r.direction="sendonly":r.direction==="recvonly"&&(r.direction="inactive"):r.direction="sendonly")}else if(this._localHold&&this._remoteHold){Q.debug("mangleOffer() | both on hold, mangling offer");for(const r of n.media)lo.indexOf(r.type)!==-1&&(r.direction="inactive")}else if(this._remoteHold){Q.debug("mangleOffer() | remote on hold, mangling offer");for(const r of n.media)lo.indexOf(r.type)!==-1&&(r.direction?r.direction==="sendrecv"?r.direction="recvonly":r.direction==="recvonly"&&(r.direction="inactive"):r.direction="recvonly")}return wt.write(n)}_setLocalMediaStatus(){let n=!0,r=!0;(this._localHold||this._remoteHold)&&(n=!1,r=!1),this._audioMuted&&(n=!1),this._videoMuted&&(r=!1),this._toggleMuteAudio(!n),this._toggleMuteVideo(!r)}_handleSessionTimersInIncomingRequest(n,r){if(!this._sessionTimers.enabled)return;let o;n.session_expires&&n.session_expires>=q.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=n.session_expires,o=n.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,o="uas"),r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${o}`),this._sessionTimers.refresher=o==="uas",this._runSessionTimer()}_handleSessionTimersInIncomingResponse(n){if(!this._sessionTimers.enabled)return;let r;n.session_expires&&n.session_expires>=q.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=n.session_expires,r=n.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,r="uac"),this._sessionTimers.refresher=r==="uac",this._runSessionTimer()}_runSessionTimer(){const n=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(()=>{this._status!==te.STATUS_TERMINATED&&this._isReadyToReOffer()&&(Q.debug("runSessionTimer() | sending session refresh request"),this._sessionTimers.refreshMethod===q.UPDATE?this._sendUpdate():this._sendReinvite())},n*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==te.STATUS_TERMINATED&&(Q.warn("runSessionTimer() | timer expired, terminating the session"),this.terminate({cause:q.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},n*1100)}_toggleMuteAudio(n){const r=this._connection.getSenders().filter(o=>o.track&&o.track.kind==="audio");for(const o of r)o.track.enabled=!n}_toggleMuteVideo(n){const r=this._connection.getSenders().filter(o=>o.track&&o.track.kind==="video");for(const o of r)o.track.enabled=!n}_newJanusSession(n,r){Q.debug("newRTCSession()"),this._ua.newJanusSession(this,{originator:n,session:this,request:r})}_connecting(n){Q.debug("session connecting"),Q.debug('emit "connecting"'),this.emit("connecting",{request:n})}_progress(n,r){Q.debug("session progress"),Q.debug('emit "progress"'),this.emit("progress",{originator:n,response:r||null})}_accepted(n,r){Q.debug("session accepted"),this._start_time=new Date,Q.debug('emit "accepted"'),this.emit("accepted",{originator:n,response:r||null})}_confirmed(n,r){Q.debug("session confirmed"),this._is_confirmed=!0,Q.debug('emit "confirmed"'),this.emit("confirmed",{originator:n,ack:r||null})}_ended(n,r,o){Q.debug("session ended"),this._end_time=new Date,this._close(),Q.debug('emit "ended"'),this.emit("ended",{originator:n,message:r||null,cause:o})}_failed(n,r,o){Q.debug("session failed"),Q.debug('emit "_failed"'),this.emit("_failed",{originator:n,message:r||null,cause:o}),this._close(),Q.debug('emit "failed"'),this.emit("failed",{originator:n,message:r||null,cause:o})}_onhold(n){Q.debug("session onhold"),this._setLocalMediaStatus(),Q.debug('emit "hold"'),this.emit("hold",{originator:n})}_onunhold(n){Q.debug("session onunhold"),this._setLocalMediaStatus(),Q.debug('emit "unhold"'),this.emit("unhold",{originator:n})}_onmute({audio:n,video:r}){Q.debug("session onmute"),this._setLocalMediaStatus(),Q.debug('emit "muted"'),this.emit("muted",{audio:n,video:r})}_onunmute({audio:n,video:r}){Q.debug("session onunmute"),this._setLocalMediaStatus(),Q.debug('emit "unmuted"'),this.emit("unmuted",{audio:n,video:r})}}class Un{constructor(n){if(this.headers={},n.length>0){let r=!1;const o=n.split(`\r
134
+ `,Kf.send(o)}var Xa={};const Nn=pt(),Js=De,Qa=Xt(),Yf=us(),Za=Ga,eu=_s;Xa.settings={authorization_user:null,password:null,realm:null,ha1:null,authorization_jwt:null,display_name:null,uri:null,contact_uri:null,instance_id:null,use_preloaded_route:!1,session_timers:!0,session_timers_refresh_method:Js.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:Js.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:Js.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:`${Nn.createRandomToken(12)}.invalid`};const no={mandatory:{sockets(c){const n=[];if(Za.isSocket(c))n.push({socket:c});else if(Array.isArray(c)&&c.length)for(const r of c)Object.prototype.hasOwnProperty.call(r,"socket")&&Za.isSocket(r.socket)?n.push(r):Za.isSocket(r)&&n.push({socket:r});else return;return n},uri(c){/^sip:/i.test(c)||(c=`${Js.SIP}:${c}`);const n=Yf.parse(c);if(n)return n.user?n:void 0}},optional:{authorization_user(c){if(Qa.parse(`"${c}"`,"quoted_string")!==-1)return c},authorization_jwt(c){if(typeof c=="string")return c},user_agent(c){if(typeof c=="string")return c},connection_recovery_max_interval(c){if(Nn.isDecimal(c)){const n=Number(c);if(n>0)return n}},connection_recovery_min_interval(c){if(Nn.isDecimal(c)){const n=Number(c);if(n>0)return n}},contact_uri(c){if(typeof c=="string"){const n=Qa.parse(c,"SIP_URI");if(n!==-1)return n}},display_name(c){return c},instance_id(c){if(/^uuid:/i.test(c)&&(c=c.substr(5)),Qa.parse(c,"uuid")!==-1)return c},no_answer_timeout(c){if(Nn.isDecimal(c)){const n=Number(c);if(n>0)return n}},session_timers(c){if(typeof c=="boolean")return c},session_timers_refresh_method(c){if(typeof c=="string"&&(c=c.toUpperCase(),c===Js.INVITE||c===Js.UPDATE))return c},session_timers_force_refresher(c){if(typeof c=="boolean")return c},password(c){return String(c)},realm(c){return String(c)},ha1(c){return String(c)},register(c){if(typeof c=="boolean")return c},register_expires(c){if(Nn.isDecimal(c)){const n=Number(c);if(n>0)return n}},registrar_server(c){/^sip:/i.test(c)||(c=`${Js.SIP}:${c}`);const n=Yf.parse(c);if(n)return n.user?void 0:n},use_preloaded_route(c){if(typeof c=="boolean")return c},extra_headers(c){const n=[];if(Array.isArray(c)&&c.length)for(const r of c)typeof r=="string"&&n.push(r);else return;return n}}};Xa.load=(c,n)=>{for(const r in no.mandatory)if(n.hasOwnProperty(r)){const o=n[r],a=no.mandatory[r](o);if(a!==void 0)c[r]=a;else throw new eu.ConfigurationError(r,o)}else throw new eu.ConfigurationError(r);for(const r in no.optional)if(n.hasOwnProperty(r)){const o=n[r];if(Nn.isEmpty(o))continue;const a=no.optional[r](o);if(a!==void 0)c[r]=a;else throw new eu.ConfigurationError(r,o)}};const xg=ut.EventEmitter,Mg=lt,gt=De,kg=Cm,zf=Ff,Jf=ag,Xf=hg,tu=On,Lg=Tg,ro=pt(),$g=_s,Hg=us(),Fg=Bf,su=Pt,Vg=Ig,nu=Xa,je=new Mg("UA"),Tt={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2};var Qf=class extends xg{static get C(){return Tt}constructor(n){if(je.debug("new() [configuration:%o]",n),super(),this._cache={credentials:{}},this._configuration=Object.assign({},nu.settings),this._dynConfiguration={},this._dialogs={},this._applicants={},this._sessions={},this._transport=null,this._contact=null,this._status=Tt.STATUS_INIT,this._error=null,this._transactions={nist:{},nict:{},ist:{},ict:{}},this._data={},this._closeTimer=null,n===void 0)throw new TypeError("Not enough arguments");try{this._loadConfig(n)}catch(r){throw this._status=Tt.STATUS_NOT_READY,this._error=Tt.CONFIGURATION_ERROR,r}this._registrator=new kg(this)}get C(){return Tt}get status(){return this._status}get contact(){return this._contact}get configuration(){return this._configuration}get transport(){return this._transport}start(){je.debug("start()"),this._status===Tt.STATUS_INIT?this._transport.connect():this._status===Tt.STATUS_USER_CLOSED?(je.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=Tt.STATUS_INIT,this._transport.connect()):this._status===Tt.STATUS_READY?je.debug("UA is in READY status, not restarted"):je.debug("ERROR: connection is down, Auto-Recovery system is trying to reconnect"),this._dynConfiguration.register=this._configuration.register}register(){je.debug("register()"),this._dynConfiguration.register=!0,this._registrator.register()}unregister(n){je.debug("unregister()"),this._dynConfiguration.register=!1,this._registrator.unregister(n)}registrator(){return this._registrator}isRegistered(){return this._registrator.registered}isConnected(){return this._transport.isConnected()}call(n,r){je.debug("call()");const o=new zf(this);return o.connect(n,r),o}sendMessage(n,r,o){je.debug("sendMessage()");const a=new Jf(this);return a.send(n,r,o),a}sendOptions(n,r,o){je.debug("sendOptions()");const a=new Xf(this);return a.send(n,r,o),a}terminateSessions(n){je.debug("terminateSessions()");for(const r in this._sessions)this._sessions[r].isEnded()||this._sessions[r].terminate(n)}stop(){if(je.debug("stop()"),this._dynConfiguration={},this._status===Tt.STATUS_USER_CLOSED){je.debug("UA already closed");return}this._registrator.close();const n=Object.keys(this._sessions).length;for(const o in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,o)){je.debug(`closing session ${o}`);try{this._sessions[o].terminate()}catch{}}for(const o in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,o))try{this._applicants[o].close()}catch{}this._status=Tt.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&n===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}normalizeTarget(n){return ro.normalizeTarget(n,this._configuration.hostport_params)}get(n){switch(n){case"authorization_user":return this._configuration.authorization_user;case"realm":return this._configuration.realm;case"ha1":return this._configuration.ha1;case"authorization_jwt":return this._configuration.authorization_jwt;default:je.warn('get() | cannot get "%s" parameter in runtime',n);return}}set(n,r){switch(n){case"authorization_user":{this._configuration.authorization_user=String(r);break}case"password":{this._configuration.password=String(r);break}case"realm":{this._configuration.realm=String(r);break}case"ha1":{this._configuration.ha1=String(r),this._configuration.password=null;break}case"authorization_jwt":{this._configuration.authorization_jwt=String(r);break}case"display_name":{this._configuration.display_name=r;break}default:return je.warn('set() | cannot set "%s" parameter in runtime',n),!1}return!0}newTransaction(n){this._transactions[n.type][n.id]=n,this.emit("newTransaction",{transaction:n})}destroyTransaction(n){delete this._transactions[n.type][n.id],this.emit("transactionDestroyed",{transaction:n})}newDialog(n){this._dialogs[n.id]=n}destroyDialog(n){delete this._dialogs[n.id]}newMessage(n,r){this._applicants[n]=n,this.emit("newMessage",r)}newOptions(n,r){this._applicants[n]=n,this.emit("newOptions",r)}destroyMessage(n){delete this._applicants[n]}newRTCSession(n,r){this._sessions[n.id]=n,this.emit("newRTCSession",r)}destroyRTCSession(n){delete this._sessions[n.id]}registered(n){this.emit("registered",n)}unregistered(n){this.emit("unregistered",n)}registrationFailed(n){this.emit("registrationFailed",n)}receiveRequest(n){const r=n.method;if(n.ruri.user!==this._configuration.uri.user&&n.ruri.user!==this._contact.uri.user){je.debug("Request-URI does not point to us"),n.method!==gt.ACK&&n.reply_sl(404);return}if(n.ruri.scheme===gt.SIPS){n.reply_sl(416);return}if(tu.checkTransaction(this,n))return;if(r===gt.INVITE?new tu.InviteServerTransaction(this,this._transport,n):r!==gt.ACK&&r!==gt.CANCEL&&new tu.NonInviteServerTransaction(this,this._transport,n),r===gt.OPTIONS){if(this.listeners("newOptions").length===0){n.reply(200);return}new Xf(this).init_incoming(n)}else if(r===gt.MESSAGE){if(this.listeners("newMessage").length===0){n.reply(405);return}new Jf(this).init_incoming(n)}else if(r===gt.INVITE&&!n.to_tag&&this.listeners("newRTCSession").length===0){n.reply(405);return}let o,a;if(n.to_tag)o=this._findDialog(n.call_id,n.from_tag,n.to_tag),o?o.receiveRequest(n):r===gt.NOTIFY?(a=this._findSession(n),a?a.receiveRequest(n):(je.debug("received NOTIFY request for a non existent subscription"),n.reply(481,"Subscription does not exist"))):r!==gt.ACK&&n.reply(481);else switch(r){case gt.INVITE:if(window.RTCPeerConnection)if(n.hasHeader("replaces")){const t=n.replaces;o=this._findDialog(t.call_id,t.from_tag,t.to_tag),o?(a=o.owner,a.isEnded()?n.reply(603):a.receiveRequest(n)):n.reply(481)}else a=new zf(this),a.init_incoming(n);else je.warn("INVITE received but WebRTC is not supported"),n.reply(488);break;case gt.BYE:n.reply(481);break;case gt.CANCEL:a=this._findSession(n),a?a.receiveRequest(n):je.debug("received CANCEL request for a non existent session");break;case gt.ACK:break;case gt.NOTIFY:this.emit("sipEvent",{event:n.event,request:n}),n.reply(200);break;default:n.reply(405);break}}_findSession({call_id:n,from_tag:r,to_tag:o}){const a=n+r,t=this._sessions[a],s=n+o,p=this._sessions[s];return t||p||null}_findDialog(n,r,o){let a=n+r+o,t=this._dialogs[a];return t||(a=n+o+r,t=this._dialogs[a],t||null)}_loadConfig(n){try{nu.load(this._configuration,n)}catch(a){throw a}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=ro.newUUID()),this._configuration.jssip_id=ro.createRandomToken(5);const r=this._configuration.uri.clone();r.user=null,this._configuration.hostport_params=r.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=jg.bind(this),this._transport.onconnect=qg.bind(this),this._transport.ondisconnect=Bg.bind(this),this._transport.ondata=Gg.bind(this)}catch(a){throw je.warn(a),new $g.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const a=this._configuration.uri.clone();a.user=null,a.clearParams(),a.clearHeaders(),this._configuration.registrar_server=a}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new Hg("sip",ro.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(a={}){const t=a.anonymous||null,s=a.outbound||null;let p="<";return t?p+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":p+=this.pub_gruu||this.uri.toString(),s&&(t?!this.temp_gruu:!this.pub_gruu)&&(p+=";ob"),p+=">",p}};const o=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const a in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,a)&&(o.indexOf(a)!==-1?Object.defineProperty(this._configuration,a,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,a,{writable:!1,configurable:!1}));je.debug("configuration parameters after validation:");for(const a in this._configuration)if(Object.prototype.hasOwnProperty.call(nu.settings,a))switch(a){case"uri":case"registrar_server":je.debug(`- ${a}: ${this._configuration[a]}`);break;case"password":case"ha1":case"authorization_jwt":je.debug(`- ${a}: NOT SHOWN`);break;default:je.debug(`- ${a}: ${JSON.stringify(this._configuration[a])}`)}}};function jg(c){this.emit("connecting",c)}function qg(c){this._status!==Tt.STATUS_USER_CLOSED&&(this._status=Tt.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function Bg(c){const n=["nict","ict","nist","ist"];for(const r of n)for(const o in this._transactions[r])Object.prototype.hasOwnProperty.call(this._transactions[r],o)&&this._transactions[r][o].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==Tt.STATUS_USER_CLOSED&&(this._status=Tt.STATUS_NOT_READY,this._error=Tt.NETWORK_ERROR)}function Gg(c){const n=c.transport;let r=c.message;if(r=Fg.parseMessage(r,this),!!r&&!(this._status===Tt.STATUS_USER_CLOSED&&r instanceof su.IncomingRequest)&&Vg(r,this,n)){if(r instanceof su.IncomingRequest)r.transport=n,this.receiveRequest(r);else if(r instanceof su.IncomingResponse){let o;switch(r.method){case gt.INVITE:o=this._transactions.ict[r.via_branch],o&&o.receiveResponse(r);break;case gt.ACK:break;default:o=this._transactions.nict[r.via_branch],o&&o.receiveResponse(r);break}}}}const Wg=it(Qf);var Me=pt();const ru=it(Me),iu=new of("Dialog"),Is={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};class io{static get C(){return Is}constructor(n,r,o,a=Is.STATUS_CONFIRMED){if(this._owner=n,this._ua=n._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,r instanceof Pt.IncomingResponse&&(a=r.status_code<200?Is.STATUS_EARLY:Is.STATUS_CONFIRMED),o==="UAS"){this._id={call_id:r.call_id,local_tag:r.to_tag,remote_tag:r.from_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=a,this._remote_seqnum=r.cseq,this._local_uri=r.parseHeader("to").uri,this._remote_uri=r.parseHeader("from").uri;let t=r.getHeaders("to")[0].split(";")[0];t=t.match(/<([^>]*)>/)[1],this._remote_target=t,this._route_set=r.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum}else if(o==="UAC"){this._id={call_id:r.call_id,local_tag:r.from_tag,remote_tag:r.to_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=a,this._local_seqnum=r.cseq,this._local_uri=r.parseHeader("from").uri,this._remote_uri=r.parseHeader("to").uri;let t=r.getHeaders("to")[0].split(";")[0];t=t.match(/<([^>]*)>/)[1],this._remote_target=t,this._route_set=r.getHeaders("record-route").reverse(),this._ack_seqnum=null}this._ua.newDialog(this),iu.debug(`new ${o} dialog created with status ${this._state===Is.STATUS_EARLY?"EARLY":"CONFIRMED"}`)}get id(){return this._id}get local_seqnum(){return this._local_seqnum}set local_seqnum(n){this._local_seqnum=n}get owner(){return this._owner}get uac_pending_reply(){return this._uac_pending_reply}set uac_pending_reply(n){this._uac_pending_reply=n}get uas_pending_reply(){return this._uas_pending_reply}isTerminated(){return this._status===Is.STATUS_TERMINATED}update(n,r){this._state=Is.STATUS_CONFIRMED,iu.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),r==="UAC"&&(this._route_set=n.getHeaders("record-route").reverse())}terminate(){iu.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=Is.STATUS_TERMINATED}sendRequest(n,r={}){const o=ru.cloneArray(r.extraHeaders),a=ru.cloneObject(r.eventHandlers),t=r.body||null,s=this._createRequest(n,o,t);return a.onAuthenticated=()=>{this._local_seqnum+=1},new Dm(this,s,a).send(),s}receiveRequest(n){this._checkInDialogRequest(n)&&(n.method===q.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:n.method===q.INVITE&&(this._ack_seqnum=n.cseq),this._owner.receiveRequest(n))}_createRequest(n,r,o){r=ru.cloneArray(r),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));const a=n===q.CANCEL||n===q.ACK?this._local_seqnum:this._local_seqnum+=1;return new Pt.OutgoingRequest(n,this._remote_target,this._ua,{cseq:a,call_id:this._id.call_id,from_uri:this._local_uri,from_tag:this._id.local_tag,to_uri:this._remote_uri,to_tag:this._id.remote_tag,route_set:this._route_set},r,o)}_checkInDialogRequest(n){if(!this._remote_seqnum)this._remote_seqnum=n.cseq;else if(n.cseq<this._remote_seqnum)if(n.method===q.ACK){if(this._ack_seqnum===null||n.cseq!==this._ack_seqnum)return!1}else return n.reply(500),!1;else n.cseq>this._remote_seqnum&&(this._remote_seqnum=n.cseq);if(n.method===q.INVITE||n.method===q.UPDATE&&n.body){if(this._uac_pending_reply===!0)n.reply(491);else if(this._uas_pending_reply===!0){const r=(Math.random()*10|0)+1;return n.reply(500,null,[`Retry-After:${r}`]),!1}else{this._uas_pending_reply=!0;const r=()=>{(n.server_transaction.state===Lt.C.STATUS_ACCEPTED||n.server_transaction.state===Lt.C.STATUS_COMPLETED||n.server_transaction.state===Lt.C.STATUS_TERMINATED)&&(n.server_transaction.removeListener("stateChanged",r),this._uas_pending_reply=!1)};n.server_transaction.on("stateChanged",r)}n.hasHeader("contact")&&n.server_transaction.on("stateChanged",()=>{n.server_transaction.state===Lt.C.STATUS_ACCEPTED&&(this._remote_target=n.parseHeader("contact").uri)})}else n.method===q.NOTIFY&&n.hasHeader("contact")&&n.server_transaction.on("stateChanged",()=>{n.server_transaction.state===Lt.C.STATUS_COMPLETED&&(this._remote_target=n.parseHeader("contact").uri)});return!0}}var Kg=us();const Gr=it(Kg);function Yg(c){const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let r="";for(let o=0;o<c;o++){const a=Math.floor(Math.random()*n.length);r+=n.substring(a,a+1)}return r}const Q=new of("JanusSession"),te={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},lo=["audio","video"];class oo extends ut.EventEmitter{static get C(){return te}constructor(n){Q.debug("new"),super(),console.log("constructor call"),this._id=null,this._ua=n,this._status=te.STATUS_NULL,this._dialog=null,this._earlyDialogs={},this._contact=null,this._from_tag=null,this._to_tag=null,this.lastTransaction=0,this._connection=null,this._connectionPromiseQueue=Promise.resolve(),this._request=null,this._is_canceled=!1,this._cancel_reason="",this._is_confirmed=!1,this._late_sdp=!1,this._rtcOfferConstraints=null,this._rtcAnswerConstraints=null,this._localMediaStream=null,this._localMediaStreamLocallyGenerated=!1,this._rtcReady=!0,this._iceReady=!1,this._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},this._direction=null,this._local_identity=null,this._remote_identity=null,this._start_time=null,this._end_time=null,this._audioMuted=!1,this._videoMuted=!1,this._localHold=!1,this._remoteHold=!1,this._sessionTimers={enabled:this._ua.configuration.session_timers,refreshMethod:this._ua.configuration.session_timers_refresh_method,defaultExpires:q.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._data={}}get C(){return te}get causes(){return q.causes}get id(){return this._id}get connection(){return this._connection}get contact(){return this._contact}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}get start_time(){return this._start_time}get end_time(){return this._end_time}get data(){return this._data}set data(n){this._data=n}get status(){return this._status}isInProgress(){switch(this._status){case te.STATUS_NULL:case te.STATUS_INVITE_SENT:case te.STATUS_1XX_RECEIVED:case te.STATUS_INVITE_RECEIVED:case te.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case te.STATUS_ANSWERED:case te.STATUS_WAITING_FOR_ACK:case te.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case te.STATUS_CANCELED:case te.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}connect(n,r={},o){Q.debug("connect()");const a=n,t=Me.cloneObject(r.eventHandlers),s=Me.cloneArray(r.extraHeaders),p=Me.cloneObject(r.mediaConstraints,{audio:!0,video:!0}),_=r.mediaStream||null,d=Me.cloneObject(r.pcConfig,{iceServers:[]}),g=r.rtcConstraints||null,T=r.rtcOfferConstraints||null;if(this._rtcOfferConstraints=T,this._rtcAnswerConstraints=r.rtcAnswerConstraints||null,this._data=r.data||this._data,n===void 0)throw new TypeError("Not enough arguments");if(this._status!==te.STATUS_NULL)throw new Ks.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new Ks.NotSupportedError("WebRTC not supported");if(console.log("target",n),n=this._ua.normalizeTarget(n),console.log("normalizeTarget target",n),!n)throw new TypeError(`Invalid target: ${a}`);this._sessionTimers.enabled&&Me.isDecimal(r.sessionTimersExpires)&&(r.sessionTimersExpires>=q.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=r.sessionTimersExpires:this._sessionTimers.defaultExpires=q.SESSION_EXPIRES);for(const A in t)Object.prototype.hasOwnProperty.call(t,A)&&this.on(A,t[A]);this._from_tag=Me.newTag();const E=r.anonymous||!1,y={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:E,outbound:!0}),E?(y.from_display_name="Anonymous",y.from_uri=new Gr("sip","anonymous","anonymous.invalid"),s.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),s.push("Privacy: id")):r.fromUserName&&(y.from_uri=new Gr("sip",r.fromUserName,this._ua.configuration.uri.host),s.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),r.fromDisplayName&&(y.from_display_name=r.fromDisplayName),s.push(`Contact: ${this._contact}`),s.push("Content-Type: application/json"),this._sessionTimers.enabled&&s.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new Pt.InitialOutgoingInviteRequest(n,this._ua,y,s),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(d,g),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,console.log("this._remote_identity",this._remote_identity),o&&o(this),this._newJanusSession("local",this._request),this._sendInitialRequest(p,T,_)}init_incoming(n,r){Q.debug("init_incoming()");let o;const a=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0;if(n.body&&a!=="application/sdp"){n.reply(415);return}if(this._status=te.STATUS_INVITE_RECEIVED,this._from_tag=n.from_tag,this._id=n.call_id+this._from_tag,this._request=n,this._contact=this._ua.contact.toString(),n.hasHeader("expires")&&(o=n.getHeader("expires")*1e3),n.to_tag=Me.newTag(),!this._createDialog(n,"UAS",!0)){n.reply(500,"Missing Contact header field");return}n.body?this._late_sdp=!1:this._late_sdp=!0,this._status=te.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{n.reply(408),this._failed("local",null,q.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),o&&(this._timers.expiresTimer=setTimeout(()=>{this._status===te.STATUS_WAITING_FOR_ANSWER&&(n.reply(487),this._failed("system",null,q.causes.EXPIRES))},o)),this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from,r&&r(this),this._newJanusSession("remote",n),this._status!==te.STATUS_TERMINATED&&(n.reply(180,null,[`Contact: ${this._contact}`]),this._progress("local",null))}answer(n={}){Q.debug("answer()");const r=this._request,o=Me.cloneArray(n.extraHeaders),a=Me.cloneObject(n.mediaConstraints),t=n.mediaStream||null,s=Me.cloneObject(n.pcConfig,{iceServers:[]}),p=n.rtcConstraints||null,_=n.rtcAnswerConstraints||null,d=Me.cloneObject(n.rtcOfferConstraints);let g,T=!1,E=!1,y=!1,A=!1;if(this._rtcAnswerConstraints=_,this._rtcOfferConstraints=n.rtcOfferConstraints||null,this._data=n.data||this._data,this._direction!=="incoming")throw new Ks.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==te.STATUS_WAITING_FOR_ANSWER)throw new Ks.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Me.isDecimal(n.sessionTimersExpires)&&(n.sessionTimersExpires>=q.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=n.sessionTimersExpires:this._sessionTimers.defaultExpires=q.SESSION_EXPIRES),this._status=te.STATUS_ANSWERED,!this._createDialog(r,"UAS")){r.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),o.unshift(`Contact: ${this._contact}`);const R=r.parseSDP();Array.isArray(R.media)||(R.media=[R.media]);for(const I of R.media)I.type==="audio"&&(T=!0,(!I.direction||I.direction==="sendrecv")&&(y=!0)),I.type==="video"&&(E=!0,(!I.direction||I.direction==="sendrecv")&&(A=!0));if(t&&a.audio===!1){g=t.getAudioTracks();for(const I of g)t.removeTrack(I)}if(t&&a.video===!1){g=t.getVideoTracks();for(const I of g)t.removeTrack(I)}!t&&a.audio===void 0&&(a.audio=y),!t&&a.video===void 0&&(a.video=A),!t&&!T&&!d.offerToReceiveAudio&&(a.audio=!1),!t&&!E&&!d.offerToReceiveVideo&&(a.video=!1),this._createRTCConnection(s,p),Promise.resolve().then(()=>{if(t)return t;if(a.audio||a.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(a).catch(I=>{throw this._status===te.STATUS_TERMINATED?new Error("terminated"):(r.reply(480),this._failed("local",null,q.causes.USER_DENIED_MEDIA_ACCESS),Q.warn('emit "getusermediafailed" [error:%o]',I),this.emit("getusermediafailed",I),new Error("getUserMedia() failed"))})}).then(I=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=I,I&&I.getTracks().forEach($=>{this._connection.addTrack($,I)})}).then(()=>{if(this._late_sdp)return;const I={originator:"remote",type:"offer",sdp:r.body};Q.debug('emit "sdp"'),this.emit("sdp",I);const $=new RTCSessionDescription({type:"offer",sdp:I.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription($)).catch(L=>{throw r.reply(488),this._failed("system",null,q.causes.WEBRTC_ERROR),Q.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',L),this.emit("peerconnection:setremotedescriptionfailed",L),new Error("peerconnection.setRemoteDescription() failed")}),this._connectionPromiseQueue}).then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._connecting(r),this._late_sdp?this._createLocalDescription("offer",this._rtcOfferConstraints).catch(()=>{throw r.reply(500),new Error("_createLocalDescription() failed")}):this._createLocalDescription("answer",_).catch(()=>{throw r.reply(500),new Error("_createLocalDescription() failed")})}).then(I=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(r,o),r.reply(200,null,o,I,()=>{this._status=te.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(r,I),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,q.causes.CONNECTION_ERROR)})}).catch(I=>{this._status!==te.STATUS_TERMINATED&&Q.warn(I)})}terminate(n={}){Q.debug("terminate()");const r=n.cause||q.causes.BYE,o=Me.cloneArray(n.extraHeaders),a=n.body;let t,s=n.status_code,p=n.reason_phrase;if(this._status===te.STATUS_TERMINATED)throw new Ks.InvalidStateError(this._status);switch(this._status){case te.STATUS_NULL:case te.STATUS_INVITE_SENT:case te.STATUS_1XX_RECEIVED:if(Q.debug("canceling session"),s&&(s<200||s>=700))throw new TypeError(`Invalid status_code: ${s}`);s&&(p=p||q.REASON_PHRASE[s]||"",t=`SIP ;cause=${s} ;text="${p}"`),this._status===te.STATUS_NULL||this._status===te.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=t):this._status===te.STATUS_1XX_RECEIVED&&this._request.cancel(t),this._status=te.STATUS_CANCELED,this._failed("local",null,q.causes.CANCELED);break;case te.STATUS_WAITING_FOR_ANSWER:case te.STATUS_ANSWERED:if(Q.debug("rejecting session"),s=s||480,s<300||s>=700)throw new TypeError(`Invalid status_code: ${s}`);this._request.reply(s,p,o,a),this._failed("local",null,q.causes.REJECTED);break;case te.STATUS_WAITING_FOR_ACK:case te.STATUS_CONFIRMED:if(Q.debug("terminating session"),p=n.reason_phrase||q.REASON_PHRASE[s]||"",s&&(s<200||s>=700))throw new TypeError(`Invalid status_code: ${s}`);if(s&&o.push(`Reason: SIP ;cause=${s}; text="${p}"`),this._status===te.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Lt.C.STATUS_TERMINATED){const _=this._dialog;this.receiveRequest=({method:d})=>{d===q.ACK&&(this.sendRequest(q.BYE,{extraHeaders:o,body:a}),_.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Lt.C.STATUS_TERMINATED&&(this.sendRequest(q.BYE,{extraHeaders:o,body:a}),_.terminate())}),this._ended("local",null,r),this._dialog=_,console.log("SET DIALOG terminate"),this._ua.newDialog(_)}else this.sendRequest(q.BYE,{extraHeaders:o,body:a}),this._ended("local",null,r)}}sendInfo(n,r,o={}){if(Q.debug("sendInfo()"),this._status!==te.STATUS_CONFIRMED&&this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_1XX_RECEIVED)throw new Ks.InvalidStateError(this._status);new Va(this).send(n,r,o)}mute(n={audio:!0,video:!1}){Q.debug("mute()");let r=!1,o=!1;this._audioMuted===!1&&n.audio&&(r=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&n.video&&(o=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(r===!0||o===!0)&&this._onmute({audio:r,video:o})}unmute(n={audio:!0,video:!0}){Q.debug("unmute()");let r=!1,o=!1;this._audioMuted===!0&&n.audio&&(r=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&n.video&&(o=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(r===!0||o===!0)&&this._onunmute({audio:r,video:o})}hold(n={},r){if(Q.debug("hold()"),this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");const o={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:q.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return n.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:o,extraHeaders:n.extraHeaders}):this._sendReinvite({eventHandlers:o,extraHeaders:n.extraHeaders}),!0}unhold(n={},r){if(Q.debug("unhold()"),this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");const o={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:q.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return n.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:o,extraHeaders:n.extraHeaders}):this._sendReinvite({eventHandlers:o,extraHeaders:n.extraHeaders}),!0}renegotiate(n={},r){Q.debug("renegotiate()");const o=n.rtcOfferConstraints||null;if(this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;const a={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:q.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),n.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,rtcOfferConstraints:o,extraHeaders:n.extraHeaders}):this._sendReinvite({eventHandlers:a,rtcOfferConstraints:o,extraHeaders:n.extraHeaders}),!0}refer(n,r){Q.debug("refer()");const o=n;if(this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;if(n=this._ua.normalizeTarget(n),!n)throw new TypeError(`Invalid target: ${o}`);const a=new zm(this);a.sendRefer(n,r);const t=a.id;return this._referSubscribers[t]=a,a.on("requestFailed",()=>{delete this._referSubscribers[t]}),a.on("accepted",()=>{delete this._referSubscribers[t]}),a.on("failed",()=>{delete this._referSubscribers[t]}),a}sendRequest(n,r){return Q.debug("sendRequest()"),this._dialog.sendRequest(n,r)}receiveRequest(n){if(Q.debug("receiveRequest()"),n.method===q.CANCEL)(this._status===te.STATUS_WAITING_FOR_ANSWER||this._status===te.STATUS_ANSWERED)&&(this._status=te.STATUS_CANCELED,this._request.reply(487),this._failed("remote",n,q.causes.CANCELED));else switch(n.method){case q.ACK:if(this._status!==te.STATUS_WAITING_FOR_ACK)return;if(this._status=te.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!n.body){this.terminate({cause:q.causes.MISSING_SDP,status_code:400});break}const r={originator:"remote",type:"answer",sdp:n.body};Q.debug('emit "sdp"'),this.emit("sdp",r);const o=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>{this._is_confirmed||this._confirmed("remote",n)}).catch(a=>{this.terminate({cause:q.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),Q.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})}else this._is_confirmed||this._confirmed("remote",n);break;case q.BYE:this._status===te.STATUS_CONFIRMED||this._status===te.STATUS_WAITING_FOR_ACK?(n.reply(200),this._ended("remote",n,q.causes.BYE)):this._status===te.STATUS_INVITE_RECEIVED||this._status===te.STATUS_WAITING_FOR_ANSWER?(n.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",n,q.causes.BYE)):n.reply(403,"Wrong Status");break;case q.INVITE:this._status===te.STATUS_CONFIRMED?n.hasHeader("replaces")?this._receiveReplaces(n):this._receiveReinvite(n):n.reply(403,"Wrong Status");break;case q.INFO:if(this._status===te.STATUS_1XX_RECEIVED||this._status===te.STATUS_WAITING_FOR_ANSWER||this._status===te.STATUS_ANSWERED||this._status===te.STATUS_WAITING_FOR_ACK||this._status===te.STATUS_CONFIRMED){const r=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0;r&&r.match(/^application\/dtmf-relay/i)?new $m(this).init_incoming(n):r!==void 0?new Va(this).init_incoming(n):n.reply(415)}else n.reply(403,"Wrong Status");break;case q.UPDATE:this._status===te.STATUS_CONFIRMED?this._receiveUpdate(n):n.reply(403,"Wrong Status");break;case q.REFER:this._status===te.STATUS_CONFIRMED?this._receiveRefer(n):n.reply(403,"Wrong Status");break;case q.NOTIFY:this._status===te.STATUS_CONFIRMED?this._receiveNotify(n):n.reply(403,"Wrong Status");break;default:n.reply(501)}}onTransportError(){Q.warn("onTransportError()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:q.causes.CONNECTION_ERROR,cause:q.causes.CONNECTION_ERROR})}onRequestTimeout(){Q.warn("onRequestTimeout()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:q.causes.REQUEST_TIMEOUT,cause:q.causes.REQUEST_TIMEOUT})}onDialogError(){Q.warn("onDialogError()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:q.causes.DIALOG_ERROR,cause:q.causes.DIALOG_ERROR})}newDTMF(n){Q.debug("newDTMF()"),this.emit("newDTMF",n)}newInfo(n){Q.debug("newInfo()"),this.emit("newInfo",n)}_isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(Q.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(Q.debug("_isReadyToReOffer() | session not established yet"),!1):(Q.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}_close(){if(Q.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(Q.debug("close() | closing local MediaStream"),Me.closeMediaStream(this._localMediaStream)),this._status!==te.STATUS_TERMINATED){if(this._status=te.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(n){Q.warn("close() | error closing the RTCPeerConnection: %o",n)}for(const n in this._timers)Object.prototype.hasOwnProperty.call(this._timers,n)&&clearTimeout(this._timers[n]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const n in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,n)&&(this._earlyDialogs[n].terminate(),delete this._earlyDialogs[n]);for(const n in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,n)&&delete this._referSubscribers[n];this._ua.destroyRTCSession(this)}}_setInvite2xxTimer(n,r){let o=Pr.T1;function a(){this._status===te.STATUS_WAITING_FOR_ACK&&(n.reply(200,null,[`Contact: ${this._contact}`],r),o<Pr.T2&&(o=o*2,o>Pr.T2&&(o=Pr.T2)),this._timers.invite2xxTimer=setTimeout(a.bind(this),o))}this._timers.invite2xxTimer=setTimeout(a.bind(this),o)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===te.STATUS_WAITING_FOR_ACK&&(Q.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(q.BYE),this._ended("remote",null,q.causes.NO_ACK))},Pr.TIMER_H)}_createRTCConnection(n,r){this._connection=new RTCPeerConnection(n,r),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:q.causes.RTP_TIMEOUT,status_code:408,reason_phrase:q.causes.RTP_TIMEOUT})}),Q.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(n,r){if(Q.debug("createLocalDescription()"),n!=="offer"&&n!=="answer")throw new Error(`createLocalDescription() | invalid type "${n}"`);const o=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>n==="offer"?o.createOffer(r).catch(a=>(Q.warn('emit "peerconnection:createofferfailed" [error:%o]',a),this.emit("peerconnection:createofferfailed",a),Promise.reject(a))):o.createAnswer(r).catch(a=>(Q.warn('emit "peerconnection:createanswerfailed" [error:%o]',a),this.emit("peerconnection:createanswerfailed",a),Promise.reject(a)))).then(a=>o.setLocalDescription(a).catch(t=>(this._rtcReady=!0,Q.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',t),this.emit("peerconnection:setlocaldescriptionfailed",t),Promise.reject(t)))).then(()=>{const a=r&&r.iceRestart;if(o.iceGatheringState==="complete"&&!a||o.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const t={originator:"local",type:n,sdp:o.localDescription.sdp};return Q.debug('emit "sdp"'),this.emit("sdp",t),Promise.resolve(t.sdp)}return new Promise(t=>{let s=!1,p,_;this._iceReady=!1;const d=()=>{o.removeEventListener("icecandidate",p),o.removeEventListener("icegatheringstatechange",_),s=!0,this._rtcReady=!0,this._iceReady=!0;const g={originator:"local",type:n,sdp:o.localDescription.sdp};Q.debug('emit "sdp"'),this.emit("sdp",g),t(g.sdp)};o.addEventListener("icecandidate",p=g=>{const T=g.candidate;T?this.emit("icecandidate",{candidate:T,ready:d}):s||d()}),o.addEventListener("icegatheringstatechange",_=()=>{o.iceGatheringState==="complete"&&!s&&d()})})})}_createDialog(n,r,o){console.log("_createDialog",n);const a=r==="UAS"?n.to_tag:n.from_tag,t=r==="UAS"?n.from_tag:n.to_tag,s=n.call_id+a+t;console.log("remote_tag",t);let p=this._earlyDialogs[s];if(o)return p?!0:(p=new io(this,n,r,io.C.STATUS_EARLY),console.log("SET DIALOG early"),p.error?(console.log("early_dialog error",p.error),Q.debug(p.error),this._failed("remote",n,q.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[s]=p,!0));{if(this._from_tag=n.from_tag,this._to_tag=n.to_tag,p)return p.update(n,r),console.log("SET DIALOG 1"),this._dialog=p,delete this._earlyDialogs[s],!0;const _=new io(this,n,r);return _.error?(console.log("dialog.error",_.error),Q.debug(_.error),this._failed("remote",n,q.causes.INTERNAL_ERROR),!1):(console.log("AAA SET DIALOG 2"),this._dialog=_,!0)}}_receiveReinvite(n){Q.debug("receiveReinvite()");const r=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0,o={request:n,callback:void 0,reject:t.bind(this)};let a=!1;function t(p={}){a=!0;const _=p.status_code||403,d=p.reason_phrase||"",g=Me.cloneArray(p.extraHeaders);if(this._status!==te.STATUS_CONFIRMED)return!1;if(_<300||_>=700)throw new TypeError(`Invalid status_code: ${_}`);n.reply(_,d,g)}if(this.emit("reinvite",o),a)return;if(this._late_sdp=!1,!n.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",this._rtcOfferConstraints)).then(p=>{s.call(this,p)}).catch(()=>{n.reply(500)});return}if(r!=="application/sdp"){Q.debug("invalid Content-Type"),n.reply(415);return}this._processInDialogSdpOffer(n).then(p=>{this._status!==te.STATUS_TERMINATED&&s.call(this,p)}).catch(p=>{Q.warn(p)});function s(p){const _=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(n,_),this._late_sdp&&(p=this._mangleOffer(p)),n.reply(200,null,_,p,()=>{this._status=te.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(n,p),this._setACKTimer()}),typeof o.callback=="function"&&o.callback()}}_receiveUpdate(n){Q.debug("receiveUpdate()");const r=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0,o={request:n,callback:void 0,reject:t.bind(this)};let a=!1;function t(p={}){a=!0;const _=p.status_code||403,d=p.reason_phrase||"",g=Me.cloneArray(p.extraHeaders);if(this._status!==te.STATUS_CONFIRMED)return!1;if(_<300||_>=700)throw new TypeError(`Invalid status_code: ${_}`);n.reply(_,d,g)}if(this.emit("update",o),a)return;if(!n.body){s.call(this,null);return}if(r!=="application/sdp"){Q.debug("invalid Content-Type"),n.reply(415);return}this._processInDialogSdpOffer(n).then(p=>{this._status!==te.STATUS_TERMINATED&&s.call(this,p)}).catch(p=>{Q.warn(p)});function s(p){const _=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(n,_),n.reply(200,null,_,p),typeof o.callback=="function"&&o.callback()}}_processInDialogSdpOffer(n){Q.debug("_processInDialogSdpOffer()");const r=n.parseSDP();let o=!1;for(const s of r.media){if(lo.indexOf(s.type)===-1)continue;const p=s.direction||r.direction||"sendrecv";if(p==="sendonly"||p==="inactive")o=!0;else{o=!1;break}}const a={originator:"remote",type:"offer",sdp:n.body};Q.debug('emit "sdp"'),this.emit("sdp",a);const t=new RTCSessionDescription({type:"offer",sdp:a.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._connection.setRemoteDescription(t).catch(s=>{throw n.reply(488),Q.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',s),this.emit("peerconnection:setremotedescriptionfailed",s),s})}).then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._remoteHold===!0&&o===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&o===!0&&(this._remoteHold=!0,this._onhold("remote"))}).then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._createLocalDescription("answer",this._rtcAnswerConstraints).catch(s=>{throw n.reply(500),Q.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',s),s})}).catch(s=>{Q.warn("_processInDialogSdpOffer() failed [error: %o]",s)}),this._connectionPromiseQueue}_receiveRefer(n){if(Q.debug("receiveRefer()"),!n.refer_to){Q.debug("no Refer-To header field present in REFER"),n.reply(400);return}if(n.refer_to.uri.scheme!==q.SIP){Q.debug("Refer-To header field points to a non-SIP URI scheme"),n.reply(416);return}n.reply(202);const r=new Gm(this,n.cseq);Q.debug('emit "refer"'),this.emit("refer",{request:n,accept:(t,s)=>{o.call(this,t,s)},reject:()=>{a.call(this)}});function o(t,s={}){if(t=typeof t=="function"?t:null,this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;const p=new oo(this._ua);if(p.on("progress",({response:_})=>{r.notify(_.status_code,_.reason_phrase)}),p.on("accepted",({response:_})=>{r.notify(_.status_code,_.reason_phrase)}),p.on("_failed",({message:_,cause:d})=>{_?r.notify(_.status_code,_.reason_phrase):r.notify(487,d)}),n.refer_to.uri.hasHeader("replaces")){const _=decodeURIComponent(n.refer_to.uri.getHeader("replaces"));s.extraHeaders=Me.cloneArray(s.extraHeaders),s.extraHeaders.push(`Replaces: ${_}`)}p.connect(n.refer_to.uri.toAor(),s,t)}function a(){r.notify(603)}}_receiveNotify(n){switch(Q.debug("receiveNotify()"),n.event||n.reply(400),n.event.event){case"refer":{let r,o;if(n.event.params&&n.event.params.id)r=n.event.params.id,o=this._referSubscribers[r];else if(Object.keys(this._referSubscribers).length===1)o=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{n.reply(400,"Missing event id parameter");return}if(!o){n.reply(481,"Subscription does not exist");return}o.receiveNotify(n),n.reply(200);break}default:n.reply(489)}}_receiveReplaces(n){Q.debug("receiveReplaces()");function r(a){if(this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;const t=new oo(this._ua);t.on("confirmed",()=>{this.terminate()}),t.init_incoming(n,a)}function o(){Q.debug("Replaced INVITE rejected by the user"),n.reply(486)}this.emit("replaces",{request:n,accept:a=>{r.call(this,a)},reject:()=>{o.call(this)}})}_getNextTransactionId(){return(this.lastTransaction+1).toString()}_sendInitialRequest(n,r,o){this.ackSent=!1,this.publisherSubscribeSent=!1;const a=new yf(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:t=>{this._request=t},onReceiveResponse:t=>{this._receiveInviteResponse(t)}});Promise.resolve().then(()=>{if(o)return o;if(n.audio||n.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(n).catch(t=>{throw this._status===te.STATUS_TERMINATED?new Error("terminated"):(this._failed("local",null,q.causes.USER_DENIED_MEDIA_ACCESS),Q.warn('emit "getusermediafailed" [error:%o]',t),this.emit("getusermediafailed",t),t)})}).then(t=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._localMediaStream=t,t&&t.getTracks().forEach(s=>{this._connection.addTrack(s,t)}),this._connecting(this._request),this._createLocalDescription("offer",r).catch(s=>{throw this._failed("local",null,q.causes.WEBRTC_ERROR),s})}).then(t=>{if(this._is_canceled||this._status===te.STATUS_TERMINATED)throw new Error("terminated");const p=JSON.stringify({janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:"videoroomtest-uzkIUidc1969"});this._request.body=p,this._status=te.STATUS_INVITE_SENT,Q.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),a.send()}).catch(t=>{this._status!==te.STATUS_TERMINATED&&Q.warn(t)})}_receiveInviteResponse(n){if(Q.debug("receiveInviteResponse()"),console.log("_receiveInviteResponse response",n),console.log("dialog",this._dialog),this._dialog&&n.status_code>=200&&n.status_code<=299&&!this.ackSent)if(console.log("IF 1 dialog"),this._dialog.id.call_id===n.call_id&&this._dialog.id.local_tag===n.from_tag&&this._dialog.id.remote_tag===n.to_tag){console.log("IF 1 SEND ACK"),this.ackSent=!0,this.sendRequest(q.ACK);return}else{const r=new io(this,n,"UAC");if(r.error!==void 0){Q.debug(r.error);return}this.sendRequest(q.ACK),this.sendRequest(q.BYE);return}if(this.ackSent&&!this.publisherSubscribeSent){const r=JSON.parse(n.body);this.session_id=r.session_id,this.handle_id=r.data.id;const a={janus:"message",body:{request:"join",room:"abcd",ptype:"publisher",display:"User1",clientID:"dufgjb023gh4vr872v238ugf2y82g4",opaque_id:`videoroomtest-${Yg(12)}`},handle_id:this.handle_id},t=["PTYPE: Publisher"];this.sendRequest(q.SUBSCRIBE,{extraHeaders:t,body:JSON.stringify(a)}),this.publisherSubscribeSent=!0}if(this._is_canceled){console.log("IF 2 canceled"),n.status_code>=100&&n.status_code<200?this._request.cancel(this._cancel_reason):n.status_code>=200&&n.status_code<299&&(console.log("IF 2 _acceptAndTerminate"),this._acceptAndTerminate(n));return}if(console.log("IF 2 this._status",this._status),this._status!==te.STATUS_INVITE_SENT&&this._status!==te.STATUS_1XX_RECEIVED){console.log("IF 3 not invite sent");return}switch(!0){case/^100$/.test(n.status_code):console.log("IF 4 SWITCH 1"),this._status=te.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(n.status_code):{if(console.log("IF 5 SWITCH 2"),!n.to_tag){console.log("IF 5 break"),Q.debug("1xx response received without to tag");break}if(n.hasHeader("contact")&&(console.log("IF 5 contact"),!this._createDialog(n,"UAC",!0))){console.log("IF 5 _createDialog break");break}if(this._status=te.STATUS_1XX_RECEIVED,!n.body){console.log("IF 5 !response.body"),this._progress("remote",n);break}const r={originator:"remote",type:"answer",sdp:n.body};Q.debug('emit "sdp"'),this.emit("sdp",r);const o=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>this._progress("remote",n)).catch(a=>{Q.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)});break}case/^2[0-9]{2}$/.test(n.status_code):{if(console.log("IF 6 SWITCH 3"),this._status=te.STATUS_CONFIRMED,!n.body){console.log("IF 6 !response.body"),this._acceptAndTerminate(n,400,q.causes.MISSING_SDP),this._failed("remote",n,q.causes.BAD_MEDIA_DESCRIPTION);break}if(console.log("AAA _createDialog"),!this._createDialog(n,"UAC"))break;break}default:{console.log("IF 7 SWITCH 4");const r=Me.sipErrorCause(n.status_code);this._failed("remote",n,r)}}}_sendReinvite(n={}){Q.debug("sendReinvite()");const r=Me.cloneArray(n.extraHeaders),o=Me.cloneObject(n.eventHandlers),a=n.rtcOfferConstraints||this._rtcOfferConstraints||null;let t=!1;r.push(`Contact: ${this._contact}`),r.push("Content-Type: application/sdp"),this._sessionTimers.running&&r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",a)).then(_=>{_=this._mangleOffer(_);const d={originator:"local",type:"offer",sdp:_};Q.debug('emit "sdp"'),this.emit("sdp",d),this.sendRequest(q.INVITE,{extraHeaders:r,body:_,eventHandlers:{onSuccessResponse:g=>{s.call(this,g),t=!0},onErrorResponse:g=>{p.call(this,g)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{p()});function s(_){if(this._status===te.STATUS_TERMINATED||(this.sendRequest(q.ACK),t))return;if(this._handleSessionTimersInIncomingResponse(_),_.body){if(!_.hasHeader("Content-Type")||_.getHeader("Content-Type").toLowerCase()!=="application/sdp"){p.call(this);return}}else{p.call(this);return}const d={originator:"remote",type:"answer",sdp:_.body};Q.debug('emit "sdp"'),this.emit("sdp",d);const g=new RTCSessionDescription({type:"answer",sdp:d.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(g)).then(()=>{o.succeeded&&o.succeeded(_)}).catch(T=>{p.call(this),Q.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',T),this.emit("peerconnection:setremotedescriptionfailed",T)})}function p(_){o.failed&&o.failed(_)}}_sendUpdate(n={}){Q.debug("sendUpdate()");const r=Me.cloneArray(n.extraHeaders),o=Me.cloneObject(n.eventHandlers),a=n.rtcOfferConstraints||this._rtcOfferConstraints||null,t=n.sdpOffer||!1;let s=!1;r.push(`Contact: ${this._contact}`),this._sessionTimers.running&&r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),t?(r.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",a)).then(d=>{d=this._mangleOffer(d);const g={originator:"local",type:"offer",sdp:d};Q.debug('emit "sdp"'),this.emit("sdp",g),this.sendRequest(q.UPDATE,{extraHeaders:r,body:d,eventHandlers:{onSuccessResponse:T=>{p.call(this,T),s=!0},onErrorResponse:T=>{_.call(this,T)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{_.call(this)})):this.sendRequest(q.UPDATE,{extraHeaders:r,eventHandlers:{onSuccessResponse:d=>{p.call(this,d)},onErrorResponse:d=>{_.call(this,d)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function p(d){if(this._status!==te.STATUS_TERMINATED&&!s)if(this._handleSessionTimersInIncomingResponse(d),t){if(d.body){if(!d.hasHeader("Content-Type")||d.getHeader("Content-Type").toLowerCase()!=="application/sdp"){_.call(this);return}}else{_.call(this);return}const g={originator:"remote",type:"answer",sdp:d.body};Q.debug('emit "sdp"'),this.emit("sdp",g);const T=new RTCSessionDescription({type:"answer",sdp:g.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(T)).then(()=>{o.succeeded&&o.succeeded(d)}).catch(E=>{_.call(this),Q.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',E),this.emit("peerconnection:setremotedescriptionfailed",E)})}else o.succeeded&&o.succeeded(d)}function _(d){o.failed&&o.failed(d)}}_acceptAndTerminate(n,r,o){Q.debug("acceptAndTerminate()");const a=[];r&&(o=o||q.REASON_PHRASE[r]||"",a.push(`Reason: SIP ;cause=${r}; text="${o}"`)),(this._dialog||this._createDialog(n,"UAC"))&&(this.sendRequest(q.ACK),this.sendRequest(q.BYE,{extraHeaders:a})),this._status=te.STATUS_TERMINATED}_mangleOffer(n){if(!this._localHold&&!this._remoteHold)return n;if(n=wt.parse(n),this._localHold&&!this._remoteHold){Q.debug("mangleOffer() | me on hold, mangling offer");for(const r of n.media)lo.indexOf(r.type)!==-1&&(r.direction?r.direction==="sendrecv"?r.direction="sendonly":r.direction==="recvonly"&&(r.direction="inactive"):r.direction="sendonly")}else if(this._localHold&&this._remoteHold){Q.debug("mangleOffer() | both on hold, mangling offer");for(const r of n.media)lo.indexOf(r.type)!==-1&&(r.direction="inactive")}else if(this._remoteHold){Q.debug("mangleOffer() | remote on hold, mangling offer");for(const r of n.media)lo.indexOf(r.type)!==-1&&(r.direction?r.direction==="sendrecv"?r.direction="recvonly":r.direction==="recvonly"&&(r.direction="inactive"):r.direction="recvonly")}return wt.write(n)}_setLocalMediaStatus(){let n=!0,r=!0;(this._localHold||this._remoteHold)&&(n=!1,r=!1),this._audioMuted&&(n=!1),this._videoMuted&&(r=!1),this._toggleMuteAudio(!n),this._toggleMuteVideo(!r)}_handleSessionTimersInIncomingRequest(n,r){if(!this._sessionTimers.enabled)return;let o;n.session_expires&&n.session_expires>=q.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=n.session_expires,o=n.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,o="uas"),r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${o}`),this._sessionTimers.refresher=o==="uas",this._runSessionTimer()}_handleSessionTimersInIncomingResponse(n){if(!this._sessionTimers.enabled)return;let r;n.session_expires&&n.session_expires>=q.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=n.session_expires,r=n.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,r="uac"),this._sessionTimers.refresher=r==="uac",this._runSessionTimer()}_runSessionTimer(){const n=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(()=>{this._status!==te.STATUS_TERMINATED&&this._isReadyToReOffer()&&(Q.debug("runSessionTimer() | sending session refresh request"),this._sessionTimers.refreshMethod===q.UPDATE?this._sendUpdate():this._sendReinvite())},n*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==te.STATUS_TERMINATED&&(Q.warn("runSessionTimer() | timer expired, terminating the session"),this.terminate({cause:q.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},n*1100)}_toggleMuteAudio(n){const r=this._connection.getSenders().filter(o=>o.track&&o.track.kind==="audio");for(const o of r)o.track.enabled=!n}_toggleMuteVideo(n){const r=this._connection.getSenders().filter(o=>o.track&&o.track.kind==="video");for(const o of r)o.track.enabled=!n}_newJanusSession(n,r){Q.debug("newRTCSession()"),this._ua.newJanusSession(this,{originator:n,session:this,request:r})}_connecting(n){Q.debug("session connecting"),Q.debug('emit "connecting"'),this.emit("connecting",{request:n})}_progress(n,r){Q.debug("session progress"),Q.debug('emit "progress"'),this.emit("progress",{originator:n,response:r||null})}_accepted(n,r){Q.debug("session accepted"),this._start_time=new Date,Q.debug('emit "accepted"'),this.emit("accepted",{originator:n,response:r||null})}_confirmed(n,r){Q.debug("session confirmed"),this._is_confirmed=!0,Q.debug('emit "confirmed"'),this.emit("confirmed",{originator:n,ack:r||null})}_ended(n,r,o){Q.debug("session ended"),this._end_time=new Date,this._close(),Q.debug('emit "ended"'),this.emit("ended",{originator:n,message:r||null,cause:o})}_failed(n,r,o){Q.debug("session failed"),Q.debug('emit "_failed"'),this.emit("_failed",{originator:n,message:r||null,cause:o}),this._close(),Q.debug('emit "failed"'),this.emit("failed",{originator:n,message:r||null,cause:o})}_onhold(n){Q.debug("session onhold"),this._setLocalMediaStatus(),Q.debug('emit "hold"'),this.emit("hold",{originator:n})}_onunhold(n){Q.debug("session onunhold"),this._setLocalMediaStatus(),Q.debug('emit "unhold"'),this.emit("unhold",{originator:n})}_onmute({audio:n,video:r}){Q.debug("session onmute"),this._setLocalMediaStatus(),Q.debug('emit "muted"'),this.emit("muted",{audio:n,video:r})}_onunmute({audio:n,video:r}){Q.debug("session onunmute"),this._setLocalMediaStatus(),Q.debug('emit "unmuted"'),this.emit("unmuted",{audio:n,video:r})}}class Un{constructor(n){if(this.headers={},n.length>0){let r=!1;const o=n.split(`\r
135
135
  `),a=o.shift().split(/\s/);this.protocol=a[0],this.ident=a[1],this.code=a.length>3?parseInt(a[2]):0,this.method=a.length>3?a[3]:a[2],this.body="";for(const t of o){if(t==`-------${this.ident}$`)break;if(t===""){r=!0;continue}if(t&&r)this.body+=`${t}\r
136
136
  `;else{const s=t.split(": ");this.addHeader(s[0],s[1].trim())}}}else this.ident=Me.createRandomToken(12),this.protocol="MSRP"}addHeader(n,r){this.headers[n]=r}getHeader(n){return this.headers[n]}toString(){let n=`${this.protocol} ${this.ident} ${this.code} ${this.method}`.replaceAll(/null\s|undefined\s/ig,"")+`\r
137
137
  `;for(const r in this.headers)n+=`${r}: ${this.headers[r]}\r
@@ -152,4 +152,4 @@ t=0 0
152
152
  m=message 2856 TCP/TLS/MSRP *
153
153
  a=accept-types:text/plain text/html
154
154
  a=path:${n.getHeader("Use-Path")} msrp://${this._ua._configuration.authorization_user}.${this._ua._configuration.realm}:2856/${this.auth_id};ws
155
- `),this._newMSRPSession("local",this._request),this._id=this._request.call_id+this._from_tag,console.log("dialog be",this._dialog),new yf(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:t=>{this.onTransportError(),console.log(t)},onAuthenticated:t=>{this._request=t},onReceiveResponse:t=>{this._receiveInviteResponse(t),console.log("dialog af",this._dialog),t.status_code===200&&(t.parseSDP(!0),this._status=Ce.STATUS_CONFIRMED,this.target_addr=t.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=Ce.STATUS_INVITE_SENT}terminate(n={}){console.log("terminate",this);const r=n.cause||q.causes.BYE,o=Me.cloneArray(n.extraHeaders),a=n.body;let t,s=n.status_code,p=n.reason_phrase;if(this._status===Ce.STATUS_TERMINATED)throw new Ks.InvalidStateError(this._status);switch(this.status="terminated",this._status){case Ce.STATUS_NULL:case Ce.STATUS_INVITE_SENT:case Ce.STATUS_1XX_RECEIVED:if(s&&(s<200||s>=700))throw new TypeError(`Invalid status_code: ${s}`);s&&(p=p||q.REASON_PHRASE[s]||"",t=`SIP ;cause=${s} ;text="${p}"`),this._status===Ce.STATUS_NULL||this._status===Ce.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=t):this._status===Ce.STATUS_1XX_RECEIVED&&this._request.cancel(t),this._status=Ce.STATUS_CANCELED,console.log("failed 1"),this._failed("local",null,q.causes.CANCELED);break;case Ce.STATUS_WAITING_FOR_ANSWER:case Ce.STATUS_ANSWERED:if(s=s||480,console.log("REPLY 480"),s<300||s>=700)throw new TypeError(`Invalid status_code: ${s}`);this._request.reply(s,p,o,a),console.log("failed 2"),this._failed("local",null,q.causes.REJECTED);break;case Ce.STATUS_WAITING_FOR_ACK:case Ce.STATUS_CONFIRMED:if(p=n.reason_phrase||q.REASON_PHRASE[s]||"",s&&(s<200||s>=700))throw new TypeError(`Invalid status_code: ${s}`);if(s&&o.push(`Reason: SIP ;cause=${s}; text="${p}"`),this._status===Ce.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Lt.C.STATUS_TERMINATED){const _=this._dialog;this.receiveRequest=({method:d})=>{d===q.ACK&&(this.sendRequest(q.BYE,{extraHeaders:o,body:a}),_.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Lt.C.STATUS_TERMINATED&&(this.sendRequest(q.BYE,{extraHeaders:o,body:a}),_.terminate())}),this._ended("local",null,r),this._dialog=_,this._ua.newDialog(_)}else console.log("here it is"),this.sendRequest(q.BYE,{extraHeaders:o,body:a}),this._ended("local",null,r)}}sendRequest(n,r){return this._dialog.sendRequest(n,r)}authenticate(n){this.status="auth";let r=new Un("");r.method="AUTH",r.addHeader("To-Path",`msrp://${this._ua._configuration.realm}:2856;ws`),r.addHeader("From-Path",`msrp://${this.credentials.username}.${this.credentials.realm}:2856/${this.auth_id};ws`),n&&r.addHeader("Authorization",n.toString());let o=r.toString();console.log(o);let a=[];for(var t=0;t<o.length;t++)a.push(o.charCodeAt(t).toString(16));console.log(a),this._connection.send(r.toString())}onmessage(n){console.log("onmessage",n);const r=new Un(n.data);if(this.status==="auth"&&r.code===401){const o=this.parseAuth(r.getHeader("WWW-Authenticate")),a=new fm(this.credentials);a.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},o,Me.createRandomToken(12)),this.authenticate(a)}this.status==="auth"&&r.code===200&&this._direction==="outgoing"?(this.my_addr.push(r.getHeader("To-Path")),this.my_addr.push(r.getHeader("Use-Path")),this.status="active",this.inviteParty(r)):this.status==="auth"&&r.code===200&&this._direction==="incoming"?(this.my_addr.push(r.getHeader("To-Path")),this.my_addr.push(r.getHeader("Use-Path")),this.status="active",this.acceptParty(r),this.emit("confirmed")):r.method==="SEND"&&(this._sendOk(r),this._sendReport(r),r.direction="incoming",this.emit("newMessage",r),this._msgHistory.push(r),this.emit("msgHistoryUpdate",this._msgHistory),console.log("======================================================================")),r.code===480&&this._close()}onclose(){console.log("close")}onopen(){const n=new RTCPeerConnection({iceServers:[]});n.createDataChannel(""),n.createOffer().then(n.setLocalDescription.bind(n)),n.onicecandidate=r=>{if(!r||!r.candidate||!r.candidate.candidate)return;const o=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,a=r.candidate.candidate.match(o);this.my_ip=a&&a[1],n.onicecandidate=()=>{},this.authenticate(null)}}onerror(n){console.log(n)}_receiveInviteResponse(n){if(console.log("resp0000000000000",n),this._dialog&&n.status_code>=200&&n.status_code<=299)if(console.log("200000000000000"),this._dialog.id.call_id===n.call_id&&this._dialog.id.local_tag===n.from_tag&&this._dialog.id.remote_tag===n.to_tag){this.sendRequest(q.ACK);return}else{const r=new Xl(this,n,"UAC");if(r.error!==void 0){console.log(r.error);return}this.sendRequest(q.ACK),this.sendRequest(q.BYE);return}if(this._is_canceled){n.status_code>=100&&n.status_code<200?this._request.cancel(this._cancel_reason):n.status_code>=200&&n.status_code<299&&this._acceptAndTerminate(n);return}if(!(this._status!==Ce.STATUS_INVITE_SENT&&this._status!==Ce.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(n.status_code):this._status=Ce.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(n.status_code):{if(!n.to_tag){console.log("1xx response received without to tag");break}if(n.hasHeader("contact")&&!this._createDialog(n,"UAC",!0))break;if(this._status=Ce.STATUS_1XX_RECEIVED,!n.body){this._progress("remote",n);break}const r={originator:"remote",type:"answer",sdp:n.body};console.log('emit "sdp"'),this.emit("sdp",r);const o=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>this._progress("remote",n)).catch(a=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)});break}case/^2[0-9]{2}$/.test(n.status_code):{if(console.log("maybe here???"),this._status=Ce.STATUS_CONFIRMED,!n.body){this._acceptAndTerminate(n,400,q.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",n,q.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(n,"UAC"))break;const r={originator:"remote",type:"answer",sdp:n.body};console.log('emit "sdp"'),this.emit("sdp",r),new RTCSessionDescription({type:"answer",sdp:r.sdp}),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(o=>this._connection.setLocalDescription(o)).catch(o=>{this._acceptAndTerminate(n,500,o.toString()),console.log("failed 4"),this._failed("local",n,q.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(n),this._accepted("remote",n),this.sendRequest(q.ACK),this._confirmed("local",null)});break}default:{const r=Me.sipErrorCause(n.status_code);console.log("failed 5"),this._failed("remote",n,r)}}}sendMSRP(n){const r=new Un("");r.method="SEND",r.addHeader("To-Path",`${this.my_addr[1]} ${this.target_addr[1]} ${this.target_addr[0]}`),r.addHeader("From-Path",`${this.my_addr[0]}`),r.addHeader("Message-ID",Me.createRandomToken(10)),r.addHeader("Byte-Range","1-25/25"),r.addHeader("Content-Type","text/plain"),r.addHeader("Success-Report","yes"),r.addHeader("Failure-Report","yes"),r.body=n;let o=r.toString();console.log(o);let a=[];for(var t=0;t<o.length;t++)a.push(o.charCodeAt(t).toString(16));console.log(a),this._connection.send(r.toString()),r.direction="outgoing",this.emit("newMessage",r),this._msgHistory.push(r),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(n){let r=n.ident,o=n.getHeader("Message-ID"),a=new Un("");a.method="200 OK",a.addHeader("To-Path",`${this.my_addr[1]}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",o),a.ident=r;let t=a.toString();console.log(t);let s=[];for(var p=0;p<t.length;p++)s.push(t.charCodeAt(p).toString(16));console.log(s),this._connection.send(a.toString())}_sendReport(n){let r=n.ident,o=n.getHeader("Message-ID"),a=new Un("");a.method="REPORT",a.addHeader("To-Path",`${n.getHeader("From-Path")}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",o),a.addHeader("Byte-Range","1-25/25"),a.addHeader("Status","000 200 OK"),a.ident=r;let t=a.toString();console.log(t);let s=[];for(var p=0;p<t.length;p++)s.push(t.charCodeAt(p).toString(16));console.log(s),this._connection.send(a.toString())}parseAuth(n){const r={},o=n.replace("Digest","").split(",");for(const a of o){const t=a.trim().split("=");r[t[0]]=t[1].match('^"(.+)"$')[1]}return r}init_incoming(n,r){let o;const a=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0;if(n.body&&a!=="application/sdp"){n.reply(415);return}if(this._status=Ce.STATUS_INVITE_RECEIVED,this._from_tag=n.from_tag,this._id=n.call_id+this._from_tag,this._request=n,this._contact=this._ua.contact.toString(),n.hasHeader("expires")&&(o=n.getHeader("expires")*1e3),n.to_tag=Me.newTag(),!this._createDialog(n,"UAS",!0)){n.reply(500,"Missing Contact header field");return}n.body?this._late_sdp=!1:this._late_sdp=!0,this._status=Ce.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{n.reply(408),console.log("failed 6"),this._failed("local",null,q.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),o&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Ce.STATUS_WAITING_FOR_ANSWER&&(n.reply(487),console.log("failed 7"),this._failed("system",null,q.causes.EXPIRES))},o)),this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from,r&&r(this),n.parseSDP(!0),this.target_addr=n.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",n),this._status!==Ce.STATUS_TERMINATED&&(n.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(n,r,o){this.emit("_failed",{originator:n,message:r||null,cause:o}),this._close(),this.emit("failed",{originator:n,message:r||null,cause:o})}_close(){if(console.log("CLOSE SESSION"),this._status!==Ce.STATUS_TERMINATED){if(this._status=Ce.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(n){console.log("close() | error closing the RTCPeerConnection: %o",n)}for(const n in this._timers)Object.prototype.hasOwnProperty.call(this._timers,n)&&clearTimeout(this._timers[n]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const n in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,n)&&(this._earlyDialogs[n].terminate(),delete this._earlyDialogs[n]);for(const n in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,n)&&delete this._referSubscribers[n];this._ua.destroyMSRPSession(this)}}_createDialog(n,r,o){const a=r==="UAS"?n.to_tag:n.from_tag,t=r==="UAS"?n.from_tag:n.to_tag,s=n.call_id+a+t;let p=this._earlyDialogs[s];if(o)return p?!0:(p=new Xl(this,n,r,Xl.C.STATUS_EARLY),p.error?(console.log("failed 8"),this._failed("remote",n,q.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[s]=p,!0));{if(this._from_tag=n.from_tag,this._to_tag=n.to_tag,p)return p.update(n,r),this._dialog=p,delete this._earlyDialogs[s],!0;const _=new Xl(this,n,r);return _.error?(console.log("failed 9"),this._failed("remote",n,q.causes.INTERNAL_ERROR),!1):(this._dialog=_,!0)}}_newMSRPSession(n,r){this._ua.newMSRPSession(this,{originator:n,session:this,request:r})}_progress(n,r){this.emit("progress",{originator:n,response:r||null})}isEnded(){switch(this._status){case Ce.STATUS_CANCELED:case Ce.STATUS_TERMINATED:return!0;default:return!1}}_accepted(n,r){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:n,response:r||null})}_confirmed(n,r){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:n,ack:r||null})}_ended(n,r,o){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:n,message:r||null,cause:o})}_handleSessionTimersInIncomingResponse(n){if(!this._sessionTimers.enabled)return;let r;n.session_expires&&n.session_expires>=q.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=n.session_expires,r=n.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,r="uac"),this._sessionTimers.refresher=r==="uac",this._runSessionTimer()}receiveRequest(n){if(console.log("receiveRequest()"),n.method===q.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",n,q.causes.CANCELED));else switch(n.method){case q.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(!n.body){this.terminate({cause:q.causes.MISSING_SDP,status_code:400});break}const r={originator:"remote",type:"answer",sdp:n.body};console.log('emit "sdp"'),this.emit("sdp",r);const o=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>{this._is_confirmed||this._confirmed("remote",n)}).catch(a=>{this.terminate({cause:q.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})}else this._is_confirmed||this._confirmed("remote",n);break;case q.BYE:this._status===Ce.STATUS_CONFIRMED||this._status===Ce.STATUS_WAITING_FOR_ACK?(n.reply(200),this._ended("remote",n,q.causes.BYE)):this._status===Ce.STATUS_INVITE_RECEIVED||this._status===Ce.STATUS_WAITING_FOR_ANSWER?(n.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",n,q.causes.BYE)):n.reply(403,"Wrong Status");break;case q.INVITE:this._status===Ce.STATUS_CONFIRMED?n.hasHeader("replaces")?this._receiveReplaces(n):this._receiveReinvite(n):n.reply(403,"Wrong Status");break;case q.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?(n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new Va(this).init_incoming(n):n.reply(415):n.reply(403,"Wrong Status");break;case q.UPDATE:this._status===Ce.STATUS_CONFIRMED?this._receiveUpdate(n):n.reply(403,"Wrong Status");break;case q.REFER:this._status===Ce.STATUS_CONFIRMED?this._receiveRefer(n):n.reply(403,"Wrong Status");break;case q.NOTIFY:this._status===Ce.STATUS_CONFIRMED?this._receiveNotify(n):n.reply(403,"Wrong Status");break;default:n.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:q.causes.CONNECTION_ERROR,cause:q.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:q.causes.REQUEST_TIMEOUT,cause:q.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:q.causes.DIALOG_ERROR,cause:q.causes.DIALOG_ERROR})}}const Nt=console,Zf={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},zg=Wg;class Jg extends zg{constructor(n){super(n),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[]}call(n,r){return super.call(n,r)}joinVideoCall(n,r){Nt.debug("call()");const o=new oo(this);return o.connect(n,r),o}newMSRPSession(n,r){n.on("msgHistoryUpdate",o=>{console.log(o)}),this._msrp_sessions[n.id]=n,this.emit("newMSRPSession",r)}newJanusSession(n,r){this._janus_sessions[n.id]=n,this.emit("newJanusSession",r)}destroyMSRPSession(n){delete this._msrp_sessions[n.id]}destroyJanusSession(n){delete this._janus_sessions[n.id]}receiveRequest(n){const r=n.method;if(console.log("-----------"),n.ruri.user!==this._configuration.uri.user&&n.ruri.user!==this._contact.uri.user){Nt.debug("Request-URI does not point to us"),n.method!==De.ACK&&n.reply_sl(404);return}if(n.ruri.scheme===De.SIPS){n.reply_sl(416);return}if(Lt.checkTransaction(this,n))return;if(r===De.INVITE?new Lt.InviteServerTransaction(this,this._transport,n):r!==De.ACK&&r!==De.CANCEL&&new Lt.NonInviteServerTransaction(this,this._transport,n),r===De.OPTIONS){if(this.listeners("newOptions").length===0){n.reply(200);return}new lf.Options(this).init_incoming(n)}else if(r===De.MESSAGE){if(this.listeners("newMessage").length===0){n.reply(405);return}new lf.Message(this).init_incoming(n)}else if(r===De.INVITE&&!n.to_tag&&this.listeners("newRTCSession").length===0){n.reply(405);return}let o,a;if(n.to_tag)o=this._findDialog(n.call_id,n.from_tag,n.to_tag),o?o.receiveRequest(n):r===De.NOTIFY?(a=this._findSession(n),a?a.receiveRequest(n):(Nt.debug("received NOTIFY request for a non existent subscription"),n.reply(481,"Subscription does not exist"))):r!==De.ACK&&n.reply(481);else switch(r){case De.INVITE:if(window.RTCPeerConnection)if(n.hasHeader("replaces")){const t=n.replaces;o=this._findDialog(t.call_id,t.from_tag,t.to_tag),o?(a=o.owner,a.isEnded()?n.reply(603):a.receiveRequest(n)):n.reply(481)}else n.body.search(/MSRP/ig)>-1?(a=new lu(this),a.init_incoming(n)):n.body.search(/JANUS/ig)>-1||(a=new sg(this),a.init_incoming(n));else Nt.warn("INVITE received but WebRTC is not supported"),n.reply(488);break;case De.BYE:n.reply(481);break;case De.CANCEL:a=this._findSession(n),a?a.receiveRequest(n):Nt.debug("received CANCEL request for a non existent session");break;case De.ACK:break;case De.NOTIFY:this.emit("sipEvent",{event:n.event,request:n}),n.reply(200);break;default:n.reply(405);break}}startMSRP(n,r){Nt.debug("startMSRP()",r);const o=new lu(this);return o.connect(n),o}startJanus(n,r){Nt.debug("startJanus()",r);const o=new lu(this);return o.connect(n),o}terminateMSRPSessions(n){Nt.debug("terminateSessions()");for(const r in this._msrp_sessions)this._msrp_sessions[r].isEnded()||this._msrp_sessions[r].terminate(n)}terminateJanusSessions(n){Nt.debug("terminateSessions()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||this._janus_sessions[r].terminate(n)}stop(){if(Nt.debug("stop()"),this._dynConfiguration={},this._status===Zf.STATUS_USER_CLOSED){Nt.debug("UA already closed");return}this._registrator.close();const n=Object.keys(this._sessions).length;for(const o in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,o)){Nt.debug(`closing session ${o}`);try{this._sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,o)){Nt.debug(`closing session ${o}`);try{this._msrp_sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,o)){Nt.debug(`closing session ${o}`);try{this._janus_sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,o))try{this._applicants[o].close()}catch(a){console.error(a)}this._status=Zf.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&n===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}const Xg=["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"],Qg=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function e_(c){const n={};return Xg.forEach(r=>{c[r]!==void 0&&(n[r]=c[r])}),n.localHold=c._localHold,n}function t_(c){const n={};return Qg.forEach(r=>{c[r]!==void 0&&(n[r]=c[r])}),n}function s_(c,n){const r=new AudioContext,o=r.createMediaStreamSource(c),a=r.createMediaStreamDestination(),t=r.createGain();return o.connect(t),t.connect(a),t.gain.value=n,a.stream}function Zg(c,n,r,o){const a=document.createElement("audio");a.id=n._id,a.className="audioTag",a.srcObject=c,a.setSinkId(r),a.volume=o,a.play(),n.audioTag=a}function eT(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}const tT=lt,sT=Xt(),It=new tT("WebSocketInterface");var nT=class{constructor(n){It.debug('new() [url:"%s"]',n),this._url=n,this._sip_uri=null,this._via_transport=null,this._ws=null;const r=sT.parse(n,"absoluteURI");if(r===-1)throw It.warn(`invalid WebSocket URI: ${n}`),new TypeError(`Invalid argument: ${n}`);if(r.scheme!=="wss"&&r.scheme!=="ws")throw It.warn(`invalid WebSocket URI scheme: ${r.scheme}`),new TypeError(`Invalid argument: ${n}`);this._sip_uri=`sip:${r.host}${r.port?`:${r.port}`:""};transport=ws`,this._via_transport=r.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(n){this._via_transport=n.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(It.debug("connect()"),this.isConnected()){It.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){It.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),It.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(n){this._onError(n)}}disconnect(){It.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(n){return It.debug("send()"),this.isConnected()?(this._ws.send(n),!0):(It.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(){It.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:n,code:r,reason:o}){It.debug(`WebSocket ${this._url} closed`),n===!1&&It.debug("WebSocket abrupt disconnection"),this.ondisconnect(!n,r,o)}_onMessage({data:n}){It.debug("received WebSocket message"),this.ondata(n)}_onError(n){It.warn(`WebSocket ${this._url} error: `,n)}};const ou=ol,rT=De,iT=_s,lT=pt(),oT=Qf,aT=us(),uT=ba(),cT=Xt(),fT=nT;An("JsSIP")("version %s",ou.version);var _T={C:rT,Exceptions:iT,Utils:lT,UA:oT,URI:aT,NameAddrHeader:uT,WebSocketInterface:fT,Grammar:cT,debug:An,get name(){return ou.title},get version(){return ou.version}};const hT=it(_T);function au(c){return c<10?`0${c}`:`${c}`}function dT(c){let n=c.hours||0,r=c.minutes||0,o=c.seconds||0;o++,o===60&&(o=0,r++,r===60&&(r=0,n++));const a=`${au(n)}:${au(r)}:${au(o)}`;return{seconds:o,minutes:r,hours:n,formatted:a}}var vt={};vt.forEach=async(c,n,r)=>{const o=[];for(let a=0;a<c.length;a++)if(a in c){const t=Promise.resolve(c[a]).then(s=>n.call(r||globalThis,s,a,c));o.push(t)}await Promise.all(o)},vt.forEachSeries=async(c,n,r)=>{for(let o=0;o<c.length;o++)o in c&&await n.call(r||globalThis,await c[o],o,c)},vt.map=async(c,n,r)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&(o[a]=Promise.resolve(c[a]).then(t=>n.call(r||globalThis,t,a,c)));return Promise.all(o)},vt.mapSeries=async(c,n,r)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&(o[a]=await n.call(r||globalThis,await c[a],a,c));return o},vt.find=(c,n,r)=>new Promise((o,a)=>{if(c.length===0)return o();let t=1;for(let s=0;s<c.length;s++){const p=_=>{_?o(c[s]):t===c.length&&o(),t++};Promise.resolve(c[s]).then(_=>n.call(r||globalThis,_,s,c)).then(p).catch(a)}}),vt.findSeries=async(c,n,r)=>{for(let o=0;o<c.length;o++)if(await n.call(r||globalThis,await c[o],o,c))return c[o]},vt.findIndex=(c,n,r)=>new Promise((o,a)=>{if(c.length===0)return o(-1);let t=1;for(let s=0;s<c.length;s++){const p=_=>{_?o(s):t===c.length&&o(-1),t++};Promise.resolve(c[s]).then(_=>n.call(r||globalThis,_,s,c)).then(p).catch(a)}}),vt.findIndexSeries=async(c,n,r)=>{for(let o=0;o<c.length;o++)if(await n.call(r||globalThis,await c[o],o,c))return o},vt.some=(c,n,r)=>new Promise((o,a)=>{if(c.length===0)return o(!1);let t=1;for(let s=0;s<c.length;s++){if(!(s in c)){t++;continue}const p=_=>{_?o(!0):t===c.length&&o(!1),t++};Promise.resolve(c[s]).then(_=>n.call(r||globalThis,_,s,c)).then(p).catch(a)}}),vt.someSeries=async(c,n,r)=>{for(let o=0;o<c.length;o++)if(o in c&&await n.call(r||globalThis,await c[o],o,c))return!0;return!1},vt.every=(c,n,r)=>new Promise((o,a)=>{if(c.length===0)return o(!0);let t=1;for(let s=0;s<c.length;s++){if(!(s in c)){t++;continue}const p=_=>{_?t===c.length&&o(!0):o(!1),t++};Promise.resolve(c[s]).then(_=>n.call(r||globalThis,_,s,c)).then(p).catch(a)}}),vt.everySeries=async(c,n,r)=>{for(let o=0;o<c.length;o++)if(o in c&&!await n.call(r||globalThis,await c[o],o,c))return!1;return!0},vt.filter=(c,n,r)=>new Promise(async(o,a)=>{const t=[];for(let p=0;p<c.length;p++)p in c&&(t[p]=Promise.resolve(c[p]).then(_=>n.call(r||globalThis,_,p,c)).catch(a));const s=[];for(let p=0;p<t.length;p++)await t[p]&&s.push(await c[p]);o(s)}),vt.filterSeries=async(c,n,r)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&await n.call(r||globalThis,await c[a],a,c)&&o.push(await c[a]);return o},vt.reduce=async(c,n,r)=>{if(c.length===0&&r===void 0)throw TypeError("Reduce of empty array with no initial value");let o,a;for(r!==void 0?(a=r,o=0):(a=c[0],o=1),o;o<c.length;o++)o in c&&(a=await n(await a,await c[o],o,c));return a};var n_={};(function(c){const n=vt;Object.keys(n).forEach(r=>{const o=r.charAt(0).toUpperCase()+r.slice(1);c[`async${o}`]=async function(...a){return n[r](this,...a)}})})(n_);var r_=Object.assign(vt,{instanceMethods:n_});const Xs=new AudioContext,es={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var pT={exports:{}};(function(c){var n=function(r){var o=Object.prototype,a=o.hasOwnProperty,t=Object.defineProperty||function(ee,Y,G){ee[Y]=G.value},s,p=typeof Symbol=="function"?Symbol:{},_=p.iterator||"@@iterator",d=p.asyncIterator||"@@asyncIterator",g=p.toStringTag||"@@toStringTag";function T(ee,Y,G){return Object.defineProperty(ee,Y,{value:G,enumerable:!0,configurable:!0,writable:!0}),ee[Y]}try{T({},"")}catch{T=function(Y,G,re){return Y[G]=re}}function E(ee,Y,G,re){var ge=Y&&Y.prototype instanceof ae?Y:ae,be=Object.create(ge.prototype),xe=new P(re||[]);return t(be,"_invoke",{value:z(ee,G,xe)}),be}r.wrap=E;function y(ee,Y,G){try{return{type:"normal",arg:ee.call(Y,G)}}catch(re){return{type:"throw",arg:re}}}var A="suspendedStart",R="suspendedYield",I="executing",$="completed",L={};function ae(){}function N(){}function F(){}var Se={};T(Se,_,function(){return this});var ve=Object.getPrototypeOf,M=ve&&ve(ve(se([])));M&&M!==o&&a.call(M,_)&&(Se=M);var D=F.prototype=ae.prototype=Object.create(Se);N.prototype=F,t(D,"constructor",{value:F,configurable:!0}),t(F,"constructor",{value:N,configurable:!0}),N.displayName=T(F,g,"GeneratorFunction");function B(ee){["next","throw","return"].forEach(function(Y){T(ee,Y,function(G){return this._invoke(Y,G)})})}r.isGeneratorFunction=function(ee){var Y=typeof ee=="function"&&ee.constructor;return Y?Y===N||(Y.displayName||Y.name)==="GeneratorFunction":!1},r.mark=function(ee){return Object.setPrototypeOf?Object.setPrototypeOf(ee,F):(ee.__proto__=F,T(ee,g,"GeneratorFunction")),ee.prototype=Object.create(D),ee},r.awrap=function(ee){return{__await:ee}};function j(ee,Y){function G(be,xe,Re,le){var ye=y(ee[be],ee,xe);if(ye.type==="throw")le(ye.arg);else{var rt=ye.arg,ot=rt.value;return ot&&typeof ot=="object"&&a.call(ot,"__await")?Y.resolve(ot.__await).then(function(Ee){G("next",Ee,Re,le)},function(Ee){G("throw",Ee,Re,le)}):Y.resolve(ot).then(function(Ee){rt.value=Ee,Re(rt)},function(Ee){return G("throw",Ee,Re,le)})}}var re;function ge(be,xe){function Re(){return new Y(function(le,ye){G(be,xe,le,ye)})}return re=re?re.then(Re,Re):Re()}t(this,"_invoke",{value:ge})}B(j.prototype),T(j.prototype,d,function(){return this}),r.AsyncIterator=j,r.async=function(ee,Y,G,re,ge){ge===void 0&&(ge=Promise);var be=new j(E(ee,Y,G,re),ge);return r.isGeneratorFunction(Y)?be:be.next().then(function(xe){return xe.done?xe.value:be.next()})};function z(ee,Y,G){var re=A;return function(be,xe){if(re===I)throw new Error("Generator is already running");if(re===$){if(be==="throw")throw xe;return nt()}for(G.method=be,G.arg=xe;;){var Re=G.delegate;if(Re){var le=H(Re,G);if(le){if(le===L)continue;return le}}if(G.method==="next")G.sent=G._sent=G.arg;else if(G.method==="throw"){if(re===A)throw re=$,G.arg;G.dispatchException(G.arg)}else G.method==="return"&&G.abrupt("return",G.arg);re=I;var ye=y(ee,Y,G);if(ye.type==="normal"){if(re=G.done?$:R,ye.arg===L)continue;return{value:ye.arg,done:G.done}}else ye.type==="throw"&&(re=$,G.method="throw",G.arg=ye.arg)}}}function H(ee,Y){var G=Y.method,re=ee.iterator[G];if(re===s)return Y.delegate=null,G==="throw"&&ee.iterator.return&&(Y.method="return",Y.arg=s,H(ee,Y),Y.method==="throw")||G!=="return"&&(Y.method="throw",Y.arg=new TypeError("The iterator does not provide a '"+G+"' method")),L;var ge=y(re,ee.iterator,Y.arg);if(ge.type==="throw")return Y.method="throw",Y.arg=ge.arg,Y.delegate=null,L;var be=ge.arg;if(!be)return Y.method="throw",Y.arg=new TypeError("iterator result is not an object"),Y.delegate=null,L;if(be.done)Y[ee.resultName]=be.value,Y.next=ee.nextLoc,Y.method!=="return"&&(Y.method="next",Y.arg=s);else return be;return Y.delegate=null,L}B(D),T(D,g,"Generator"),T(D,_,function(){return this}),T(D,"toString",function(){return"[object Generator]"});function Z(ee){var Y={tryLoc:ee[0]};1 in ee&&(Y.catchLoc=ee[1]),2 in ee&&(Y.finallyLoc=ee[2],Y.afterLoc=ee[3]),this.tryEntries.push(Y)}function U(ee){var Y=ee.completion||{};Y.type="normal",delete Y.arg,ee.completion=Y}function P(ee){this.tryEntries=[{tryLoc:"root"}],ee.forEach(Z,this),this.reset(!0)}r.keys=function(ee){var Y=Object(ee),G=[];for(var re in Y)G.push(re);return G.reverse(),function ge(){for(;G.length;){var be=G.pop();if(be in Y)return ge.value=be,ge.done=!1,ge}return ge.done=!0,ge}};function se(ee){if(ee){var Y=ee[_];if(Y)return Y.call(ee);if(typeof ee.next=="function")return ee;if(!isNaN(ee.length)){var G=-1,re=function ge(){for(;++G<ee.length;)if(a.call(ee,G))return ge.value=ee[G],ge.done=!1,ge;return ge.value=s,ge.done=!0,ge};return re.next=re}}return{next:nt}}r.values=se;function nt(){return{value:s,done:!0}}return P.prototype={constructor:P,reset:function(ee){if(this.prev=0,this.next=0,this.sent=this._sent=s,this.done=!1,this.delegate=null,this.method="next",this.arg=s,this.tryEntries.forEach(U),!ee)for(var Y in this)Y.charAt(0)==="t"&&a.call(this,Y)&&!isNaN(+Y.slice(1))&&(this[Y]=s)},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=s),!!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=a.call(ge,"catchLoc"),Re=a.call(ge,"finallyLoc");if(xe&&Re){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(Re){if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(ee,Y){for(var G=this.tryEntries.length-1;G>=0;--G){var re=this.tryEntries[G];if(re.tryLoc<=this.prev&&a.call(re,"finallyLoc")&&this.prev<re.finallyLoc){var ge=re;break}}ge&&(ee==="break"||ee==="continue")&&ge.tryLoc<=Y&&Y<=ge.finallyLoc&&(ge=null);var be=ge?ge.completion:{};return be.type=ee,be.arg=Y,ge?(this.method="next",this.next=ge.finallyLoc,L):this.complete(be)},complete:function(ee,Y){if(ee.type==="throw")throw ee.arg;return ee.type==="break"||ee.type==="continue"?this.next=ee.arg:ee.type==="return"?(this.rval=this.arg=ee.arg,this.method="return",this.next="end"):ee.type==="normal"&&Y&&(this.next=Y),L},finish:function(ee){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var G=this.tryEntries[Y];if(G.finallyLoc===ee)return this.complete(G.completion,G.afterLoc),U(G),L}},catch:function(ee){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var G=this.tryEntries[Y];if(G.tryLoc===ee){var re=G.completion;if(re.type==="throw"){var ge=re.arg;U(G)}return ge}}throw new Error("illegal catch attempt")},delegateYield:function(ee,Y,G){return this.delegate={iterator:se(ee),resultName:Y,nextLoc:G},this.method==="next"&&(this.arg=s),L}},r}(c.exports);try{regeneratorRuntime=n}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}})(pT);var i_={exports:{}};(function(c){(function(n,r){c.exports?c.exports=r():n.log=r()})(E_,function(){var n=function(){},r="undefined",o=typeof window!==r&&typeof window.navigator!==r&&/Trident\/|MSIE /.test(window.navigator.userAgent),a=["trace","debug","info","warn","error"];function t(R,I){var $=R[I];if(typeof $.bind=="function")return $.bind(R);try{return Function.prototype.bind.call($,R)}catch{return function(){return Function.prototype.apply.apply($,[R,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function p(R){return R==="debug"&&(R="log"),typeof console===r?!1:R==="trace"&&o?s:console[R]!==void 0?t(console,R):console.log!==void 0?t(console,"log"):n}function _(R,I){for(var $=0;$<a.length;$++){var L=a[$];this[L]=$<R?n:this.methodFactory(L,R,I)}this.log=this.debug}function d(R,I,$){return function(){typeof console!==r&&(_.call(this,I,$),this[R].apply(this,arguments))}}function g(R,I,$){return p(R)||d.apply(this,arguments)}function T(R,I,$){var L=this,ae;I=I??"WARN";var N="loglevel";typeof R=="string"?N+=":"+R:typeof R=="symbol"&&(N=void 0);function F(D){var B=(a[D]||"silent").toUpperCase();if(!(typeof window===r||!N)){try{window.localStorage[N]=B;return}catch{}try{window.document.cookie=encodeURIComponent(N)+"="+B+";"}catch{}}}function Se(){var D;if(!(typeof window===r||!N)){try{D=window.localStorage[N]}catch{}if(typeof D===r)try{var B=window.document.cookie,j=B.indexOf(encodeURIComponent(N)+"=");j!==-1&&(D=/^([^;]+)/.exec(B.slice(j))[1])}catch{}return L.levels[D]===void 0&&(D=void 0),D}}function ve(){if(!(typeof window===r||!N)){try{window.localStorage.removeItem(N);return}catch{}try{window.document.cookie=encodeURIComponent(N)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}L.name=R,L.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},L.methodFactory=$||g,L.getLevel=function(){return ae},L.setLevel=function(D,B){if(typeof D=="string"&&L.levels[D.toUpperCase()]!==void 0&&(D=L.levels[D.toUpperCase()]),typeof D=="number"&&D>=0&&D<=L.levels.SILENT){if(ae=D,B!==!1&&F(D),_.call(L,D,R),typeof console===r&&D<L.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+D},L.setDefaultLevel=function(D){I=D,Se()||L.setLevel(D,!1)},L.resetLevel=function(){L.setLevel(I,!1),ve()},L.enableAll=function(D){L.setLevel(L.levels.TRACE,D)},L.disableAll=function(D){L.setLevel(L.levels.SILENT,D)};var M=Se();M==null&&(M=I),L.setLevel(M,!1)}var E=new T,y={};E.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var $=y[I];return $||($=y[I]=new T(I,E.getLevel(),E.methodFactory)),$};var A=typeof window!==r?window.log:void 0;return E.noConflict=function(){return typeof window!==r&&window.log===E&&(window.log=A),E},E.getLoggers=function(){return y},E.default=E,E})})(i_);var At=i_.exports;const hs=()=>`${new Date().toISOString()} | metrics`,ds=(c,n,r)=>`${c} | ${n} | ${r}`;At.setDefaultLevel(At.levels.TRACE);const mT=c=>{At.info(ds(hs(),"log ",`set log level to ${c?"verbose":"info"}`)),At.setLevel(c?At.levels.TRACE:At.levels.INFO)},gT=c=>{const n=[...Object.keys(At.levels)];n.includes(c)?(At.info(ds(hs(),"log ",`update log level to ${c.toLowerCase()}`)),At.setLevel(c)):At.warn(ds(hs(),"log ","Incorrect log level please choose one of "),n)},Pe=(c,n,r)=>{r?At.debug(ds(hs(),c,n),r):At.debug(ds(hs(),c,n))},uu=(c,n)=>{At.info(ds(hs(),c,n))},Qs=(c,n)=>{At.info(ds(hs(),c,n))},ao=(c,n)=>{At.warn(ds(hs(),c,n))},Pn=(c,n)=>{At.error(ds(hs(),c,n))};function TT(c){return Math.floor(Math.random()*c).toString()}function l_(c,n){let r=n;return c.forEach(o=>{r=r.replace(o,"")}),r}function vT(c,n){let r="";for(let o=0;o<n;o+=1)r+=c[TT(c.length)];return r}function ET({length:c=20,useLetters:n=!0,useNumbers:r=!0,includeSymbols:o=[],excludeSymbols:a=[]}={}){let t="abcdefghijklmnopqrstuvwxyz",s="0123456789",p=[],_=[],d=[];return n&&(a.length&&(t=l_(a,t)),_=t.split("")),r&&(a.length&&(s=l_(a,s)),d=s.split("")),p=[..._,...d,...o],vT(p,c)}var ST=ET;const Wr=it(ST),yT=()=>"WebRTCMetrics",AT=()=>"5.0.3",Le={INBOUND:"inbound",OUTBOUND:"outbound"},ps={IDLE:"idle",RUNNING:"running",MUTED:"muted"},Kr={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},CT=()=>({...{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:[]}}),o_={level_in:0,codec_id_in:"",codec_in:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,mos_in:0,mos_emodel_in:0,ssrc:"",direction:Le.INBOUND},a_={level_out:0,codec_id_out:"",codec_out:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,timestamp_out:null,mos_out:0,mos_emodel_out:0,ssrc:"",direction:Le.OUTBOUND},u_={codec_id_in:"",size_in:{width:null,height:null,framerate:null},codec_in:{mime_type:null,clock_rate:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,decoder_in:null,delta_ms_decode_frame_in:0,total_frames_decoded_in:0,total_time_decoded_in:0,delta_nack_sent_in:0,delta_pli_sent_in:0,total_nack_sent_in:0,total_pli_sent_in:0,ssrc:"",direction:Le.INBOUND},c_={codec_id_out:"",size_out:{width:null,height:null,framerate:null},codec_out:{mime_type:null,clock_rate:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,encoder_out:null,delta_ms_encode_frame_out:0,total_time_encoded_out:0,total_frames_encoded_out:0,delta_nack_received_out:0,delta_pli_received_out:0,total_nack_received_out:0,total_pli_received_out:0,limitation_out:{reason:null,durations:null,resolutionChanges:0},timestamp_out:null,ssrc:"",direction:Le.OUTBOUND},RT=c=>{const n={pname:"",call_id:"",user_id:"",timestamp:null,count:0,audio:{},video:{},network:{infrastructure:3,local_candidate_id:"",local_candidate_type:"",local_candidate_protocol:"",local_candidate_relay_protocol:"",remote_candidate_id:"",remote_candidate_type:"",remote_candidate_protocol:""},data:{total_KBytes_in:0,total_KBytes_out:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,delta_kbs_bandwidth_in:0,delta_kbs_bandwidth_out:0,delta_rtt_connectivity_ms:null,total_rtt_connectivity_ms:0,total_rtt_connectivity_measure:0},experimental:{time_to_measure_ms:0}};if(c){const r={...c,audio:{},video:{},data:{...c.data},network:{...c.network},experimental:{...c.experimental}};return Object.keys(c.audio).forEach(o=>{r.audio[o]={...c.audio[o]}}),Object.keys(c.video).forEach(o=>{r.video[o]={...c.video[o]}}),r}return{...n,audio:{},video:{},data:{...n.data},network:{...n.network},experimental:{...n.experimental}}},IT={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${Wr()}`,cid:`c-${Wr()}`,uid:`u-${Wr()}`,record:!1,ticket:!0},Wt={CANDIDATE_PAIR:"candidate-pair",CODEC:"codec",INBOUND_RTP:"inbound-rtp",LOCAL_CANDIDATE:"local-candidate",MEDIA_SOURCE:"media-source",OUTBOUND_RTP:"outbound-rtp",REMOTE_CANDIDATE:"remote-candidate",REMOTE_INBOUND_RTP:"remote-inbound-rtp",TRACK:"track"},V={AUDIO_LEVEL:"audioLevel",AVAILABLE_OUTGOING_BITRATE:"availableOutgoingBitrate",AVAILABLE_INCOMING_BITRATE:"availableIncomingBitrate",BYTES_RECEIVED:"bytesReceived",BYTES_SENT:"bytesSent",CANDIDATE_TYPE:"candidateType",CHANNELS:"channels",CLOCK_RATE:"clockRate",CODEC_ID:"codecId",CURRENT_ROUND_TRIP_TIME:"currentRoundTripTime",ROUND_TRIP_TIME:"roundTripTime",FRACTION_LOST:"fractionLost",FRAME_HEIGHT:"frameHeight",FRAME_WIDTH:"frameWidth",QUALITY_LIMITATION_REASON:"qualityLimitationReason",QUALITY_LIMITATION_DURATIONS:"qualityLimitationDurations",QUALITY_LIMITATION_RESOLUTION_CHANGES:"qualityLimitationResolutionChanges",ID:"id",JITTER:"jitter",KIND:"kind",MEDIA_TYPE:"mediaType",MIME_TYPE:"mimeType",LOCAL_CANDIDATE_ID:"localCandidateId",NETWORK_TYPE:"networkType",RELAY_PROTOCOL:"relayProtocol",NOMINATED:"nominated",PACKETS_LOST:"packetsLost",PACKETS_RECEIVED:"packetsReceived",PACKETS_SENT:"packetsSent",PROTOCOL:"protocol",PORT:"port",REMOTE_CANDIDATE_ID:"remoteCandidateId",REMOTE_SOURCE:"remoteSource",RESPONSES_RECEIVED:"responsesReceived",SDP_FMTP_LINE:"sdpFmtpLine",SSRC:"ssrc",SELECTED:"selected",STATE:"state",TIMESTAMP:"timestamp",TOTAL_ROUND_TRIP_TIME:"totalRoundTripTime",TOTAL_ROUND_TRIP_TIME_MEASUREMENTS:"roundTripTimeMeasurements",TYPE:"type",DECODER_IMPLEMENTATION:"decoderImplementation",ENCODER_IMPLEMENTATION:"encoderImplementation",FRAMES_DECODED:"framesDecoded",FRAMES_ENCODED:"framesEncoded",FRAMES_PER_SECOND:"framesPerSecond",TOTAL_DECODE_TIME:"totalDecodeTime",TOTAL_ENCODE_TIME:"totalEncodeTime",PLI:"pliCount",NACK:"nackCount"},x={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},Yr={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},cu={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ne={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},fu="config ",bT=(c,n={},r)=>{const o={...r,...n};return n.pname||ao(fu,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${r.pname}'`),n.cid||ao(fu,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${r.cid}'`),n.uid||ao(fu,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${r.uid}'`),o.pc=c,o},wT=(c={})=>{const n={...IT,...c};return n.name=yT(),n.version=AT(),n},zr=(c,n,r,o=!1,a)=>{let t=c.map(s=>{if(!r)return s[n];if(!a)return s[n][r];const p=s[n][a];return p?p[r]:null});return t=t.filter(s=>o?Number.isFinite(s)&&s>0:Number.isFinite(s)),t.length===0?[]:t},bs=c=>c.reduce((n,r)=>n+r,0)/c.length,OT=()=>`probe-${Wr()}`,DT=()=>`coltr-${Wr()}`,f_=c=>new Promise(n=>setTimeout(n,c)),_u=(c,n,r)=>{n?c.call(n,r):c(r)},Ge=(c,n,r,o)=>{const a=zr(c,n,r,!0,o);if(a.length===0)return null;const t=a.reduce((d,g)=>d+g,0)/a.length;return t===0?null:a.map(d=>Math.abs(t-d)).reduce((d,g)=>d+g,0)/a.length*100/t},Je=(c,n,r,o=!1,a)=>{const t=zr(c,n,r,o,a);return t.length===0?null:t.reduce((s,p)=>s+p,0)/t.length},Zs=(c,n,r)=>zr(c,n,r).reduce((a,t)=>a+t,0),We=(c,n,r,o)=>{const a=zr(c,n,r,!0,o);return a.length===0?null:Math.min(...a)},Ke=(c,n,r,o)=>{const a=zr(c,n,r,!1,o);return a.length===0?null:Math.max(...a)},Et=(c,n,r,o)=>{const a=c.slice().pop();if(!a)return null;if(!r)return a[n];if(!o)return a[n][r];const t=a[n][o];return t?t[r]:null},NT=c=>c.slice().pop(),ft=(c,n,r)=>{if(!n)return null;const o={};let a=n[x.AUDIO][c];a||(a=r===Le.INBOUND?{...o_}:{...a_}),o[x.AUDIO]=a;let t=n[x.VIDEO][c];return t||(t=r===Le.INBOUND?{...u_}:{...c_}),o[x.VIDEO]=t,o},Jr="exporter ",UT="2.0",__=(c,n,r)=>{if(!c||c.length===0)return 0;const o=c[c.length-1];if(!o)return 0;const a=o[n][r];if(a){const t=a.total_rtt_ms_out,s=a.total_rtt_measure_out;return!s||!t?Je(c,n,"delta_rtt_ms_out",!1,r):Number(t/s)}return null},PT=(c,n)=>{if(!c||c.length===0)return 0;const r=c[c.length-1];if(!r)return 0;const o=r[n].total_rtt_connectivity_ms,a=r[n].total_rtt_connectivity_measure;return!a||!o?Je(c,n,"delta_rtt_connectivity_ms"):Number(o/a)},xT=c=>Et(c,"network","local_candidate_type")!=="relay"?`direct/${Et(c,"network","local_candidate_protocol")}`:`turn/${Et(c,"network","local_candidate_relay_protocol")}`,MT=c=>{const n=Et(c,"network","remote_candidate_type"),r=Et(c,"network","remote_candidate_protocol");return n!=="relay"?`direct/${r}`:`turn/${r}`};class kT{constructor(n){this._start=null,this._end=null,this._cfg=n,this._referenceReport=null,this._reports=[],this._events=[]}start(){uu(Jr,"start() - start exporter...");const n=new Date;return this._start=n.toJSON(),n}stop(){uu(Jr,"stop() - stop exporter...");const n=new Date;return this._end=n.toJSON(),n}saveReferenceReport(n){this._referenceReport=n}getReferenceReport(){return this._referenceReport}addReport(n){this._cfg.ticket&&(Pe(Jr,`addReport() - add report to exporter at ${n.timestamp}`),this._reports.push(n))}addCustomEvent(n){this._events.push(n)}reset(){uu(Jr,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Pe(Jr,"ticket() - generate ticket");const n=Et(this._reports,"audio","total_packets_lost_in"),r=Et(this._reports,"audio","total_packets_in"),o=Et(this._reports,"video","total_packets_lost_in"),a=Et(this._reports,"video","total_packets_in"),t={},s=NT(this._reports);return s&&(Object.keys(s[x.AUDIO]).forEach(p=>{const _=s[x.AUDIO][p];if(t[_.ssrc]={type:x.AUDIO,direction:_.direction},_.direction===Le.INBOUND){const d={avg:Je(this._reports,x.AUDIO,"delta_jitter_ms_in",!1,p),min:We(this._reports,x.AUDIO,"delta_jitter_ms_in",p),max:Ke(this._reports,x.AUDIO,"delta_jitter_ms_in",p),volatility:Ge(this._reports,x.AUDIO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Je(this._reports,x.AUDIO,"delta_kbs_in",!1,p),min:We(this._reports,x.AUDIO,"delta_kbs_in",p),max:Ke(this._reports,x.AUDIO,"delta_kbs_in",p),volatility:Ge(this._reports,x.AUDIO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Je(this._reports,x.AUDIO,"delta_KBytes_in",!1,p),min:We(this._reports,x.AUDIO,"delta_KBytes_in",p),max:Ke(this._reports,x.AUDIO,"delta_KBytes_in",p),volatility:Ge(this._reports,x.AUDIO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={emodel:{avg:Je(this._reports,x.AUDIO,"mos_emodel_in",!1,p),min:We(this._reports,x.AUDIO,"mos_emodel_in",p),max:Ke(this._reports,x.AUDIO,"mos_emodel_in",p),volatility:Ge(this._reports,x.AUDIO,"mos_emodel_in",p)},effective:{avg:Je(this._reports,x.AUDIO,"mos_in",!1,p),min:We(this._reports,x.AUDIO,"mos_in",p),max:Ke(this._reports,x.AUDIO,"mos_in",p),volatility:Ge(this._reports,x.AUDIO,"mos_in",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},y=Et(this._reports,x.AUDIO,"total_packets_lost_in",p),A=Et(this._reports,x.AUDIO,"total_packets_in",p),R={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].mos=E,t[p].traffic=T,t[p].bitrate=g,t[p].loss=R}else{const d={avg:Je(this._reports,x.AUDIO,"delta_jitter_ms_out",!1,p),min:We(this._reports,x.AUDIO,"delta_jitter_ms_out",p),max:Ke(this._reports,x.AUDIO,"delta_jitter_ms_out",p),volatility:Ge(this._reports,x.AUDIO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Je(this._reports,x.AUDIO,"delta_kbs_out",!1,p),min:We(this._reports,x.AUDIO,"delta_kbs_out",p),max:Ke(this._reports,x.AUDIO,"delta_kbs_out",p),volatility:Ge(this._reports,x.AUDIO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Je(this._reports,x.AUDIO,"delta_KBytes_out",!1,p),min:We(this._reports,x.AUDIO,"delta_KBytes_out",p),max:Ke(this._reports,x.AUDIO,"delta_KBytes_out",p),volatility:Ge(this._reports,x.AUDIO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},E={avg:__(this._reports,x.AUDIO,p),min:We(this._reports,x.AUDIO,"delta_rtt_ms_out",p),max:Ke(this._reports,x.AUDIO,"delta_rtt_ms_out",p),volatility:Ge(this._reports,x.AUDIO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=Et(this._reports,x.AUDIO,"total_packets_lost_out",p),A=Et(this._reports,x.AUDIO,"total_packets_out",p),R={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},I={emodel:{avg:Je(this._reports,x.AUDIO,"mos_emodel_out",!1,p),min:We(this._reports,x.AUDIO,"mos_emodel_out",p),max:Ke(this._reports,x.AUDIO,"mos_emodel_out",p),volatility:Ge(this._reports,x.AUDIO,"mos_emodel_out",p)},effective:{avg:Je(this._reports,x.AUDIO,"mos_out",!1,p),min:We(this._reports,x.AUDIO,"mos_out",p),max:Ke(this._reports,x.AUDIO,"mos_out",p),volatility:Ge(this._reports,x.AUDIO,"mos_out",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};t[p].jitter=d,t[p].rtt=E,t[p].traffic=T,t[p].bitrate=g,t[p].loss=R,t[p].mos=I}}),Object.keys(s[x.VIDEO]).forEach(p=>{const _=s[x.VIDEO][p];if(t[p]={type:x.VIDEO,direction:_.direction},_.direction===Le.INBOUND){const d={avg:Je(this._reports,x.VIDEO,"delta_jitter_ms_in",!1,p),min:We(this._reports,x.VIDEO,"delta_jitter_ms_in",p),max:Ke(this._reports,x.VIDEO,"delta_jitter_ms_in",p),volatility:Ge(this._reports,x.VIDEO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Je(this._reports,x.VIDEO,"delta_kbs_in",!1,p),min:We(this._reports,x.VIDEO,"delta_kbs_in",p),max:Ke(this._reports,x.VIDEO,"delta_kbs_in",p),volatility:Ge(this._reports,x.VIDEO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Je(this._reports,x.VIDEO,"delta_KBytes_in",!1,p),min:We(this._reports,x.VIDEO,"delta_KBytes_in",p),max:Ke(this._reports,x.VIDEO,"delta_KBytes_in",p),volatility:Ge(this._reports,x.VIDEO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E=Et(this._reports,x.VIDEO,"total_packets_lost_in",p),y=Et(this._reports,x.VIDEO,"total_packets_in",p),A={lost:E,avg:Math.round((E/(E+y)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].traffic=T,t[p].bitrate=g,t[p].loss=A}else{const d={avg:Je(this._reports,x.VIDEO,"delta_jitter_ms_out",!1,p),min:We(this._reports,x.VIDEO,"delta_jitter_ms_out",p),max:Ke(this._reports,x.VIDEO,"delta_jitter_ms_out",p),volatility:Ge(this._reports,x.VIDEO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Je(this._reports,x.VIDEO,"delta_kbs_out",!1,p),min:We(this._reports,x.VIDEO,"delta_kbs_out",p),max:Ke(this._reports,x.VIDEO,"delta_kbs_out",p),volatility:Ge(this._reports,x.VIDEO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Je(this._reports,x.VIDEO,"delta_KBytes_out",!1,p),min:We(this._reports,x.VIDEO,"delta_KBytes_out",p),max:Ke(this._reports,x.VIDEO,"delta_KBytes_out",p),volatility:Ge(this._reports,x.VIDEO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={avg:__(this._reports,x.VIDEO,p),min:We(this._reports,x.VIDEO,"delta_rtt_ms_out",p),max:Ke(this._reports,x.VIDEO,"delta_rtt_ms_out",p),volatility:Ge(this._reports,x.VIDEO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=Et(this._reports,x.VIDEO,"total_packets_lost_out",p),A=Et(this._reports,x.VIDEO,"total_packets_out",p),R={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].rtt=E,t[p].traffic=T,t[p].bitrate=g,t[p].loss=R}})),{version:UT,configuration:{frequency:this._cfg.refreshEvery},started:this._start,ended:this._end,ua:{agent:navigator.userAgent,pname:this._cfg.pname,user_id:this._cfg.uid},call:{call_id:this._cfg.cid,events:this._events},details:{count:this._reports.length,reports:this._cfg.record?this._reports:[],reference:this._referenceReport||null},ssrc:t,data:{rtt:{avg:PT(this._reports,"data"),min:We(this._reports,"data","delta_rtt_connectivity_ms"),max:Ke(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Ge(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((n/(n+r)*100||0)*100)/100}},video:{in:{avg:Math.round((o/(o+a)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:Je(this._reports,"data","delta_kbs_in"),min:We(this._reports,"data","delta_kbs_in"),max:Ke(this._reports,"data","delta_kbs_in"),volatility:Ge(this._reports,"data","delta_kbs_in")},out:{avg:Je(this._reports,"data","delta_kbs_out"),min:We(this._reports,"data","delta_kbs_out"),max:Ke(this._reports,"data","delta_kbs_out"),volatility:Ge(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:Je(this._reports,"data","delta_KBytes_in"),min:We(this._reports,"data","delta_KBytes_in"),max:Ke(this._reports,"data","delta_KBytes_in"),volatility:Ge(this._reports,"data","delta_KBytes_in")},out:{avg:Je(this._reports,"data","delta_KBytes_out"),min:We(this._reports,"data","delta_KBytes_out"),max:Ke(this._reports,"data","delta_KBytes_out"),volatility:Ge(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:xT(this._reports),remoteConnection:MT(this._reports)}}}}updateConfig(n){this._cfg=n}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const n=this._reports.slice();return n.pop(),n.pop()||null}getReportsNumber(){return this._reports.length}}const ws="extractor ",h_=(c,n,r,o)=>{let a=!1;const t=o[n].total_rtt_ms_out,s=o[n].total_rtt_measure_out,p=r?r[n].total_rtt_ms_out:0,_=r?r[n].total_rtt_measure_out:0,d={rtt:null,totalRTT:t,totalRTTMeasurements:s};if(c[V.TIMESTAMP]===o[n].timestamp_out||!Object.prototype.hasOwnProperty.call(c,V.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(a=!0,Number(c[V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-_===s))return d;const g=1e3*Number(c[V.ROUND_TRIP_TIME]);let T=t+g,E=s+1;return a&&(T=1e3*Number(c[V.TOTAL_ROUND_TRIP_TIME])-p,E=Number(c[V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-_),{rtt:g,totalRTT:T,totalRTTMeasurements:E}},LT=(c,n,r,o)=>{if(!Object.prototype.hasOwnProperty.call(c,V.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:o[n].total_rtt_connectivity_ms,totalRTTMeasurements:o[n].total_rtt_connectivity_measure};const a=1e3*Number(c[V.CURRENT_ROUND_TRIP_TIME]);let t=o[n].total_rtt_connectivity_ms+a,s=o[n].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,V.TOTAL_ROUND_TRIP_TIME)&&(t=1e3*Number(c[V.TOTAL_ROUND_TRIP_TIME])-(r?r[n].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,V.RESPONSES_RECEIVED)&&(s=Number(c[V.RESPONSES_RECEIVED])-(r?r[n].total_rtt_connectivity_measure:0)),{rtt:a,totalRTT:t,totalRTTMeasurements:s}},uo=(c,n,r)=>c[V.TIMESTAMP]===r[n].timestamp_out||!Object.prototype.hasOwnProperty.call(c,V.JITTER)?null:1e3*(Number(c[V.JITTER])||0),$T=(c,n)=>{if(!Object.prototype.hasOwnProperty.call(c,V.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,V.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:n[x.VIDEO].delta_ms_decode_frame_in,frames_decoded:n[x.VIDEO].total_frames_decoded_in,total_decode_time:n[x.VIDEO].total_time_decoded_in};const r=c[V.FRAMES_DECODED],o=c[V.TOTAL_DECODE_TIME],a=o-n[x.VIDEO].total_time_decoded_in,t=r-n[x.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:t>0?a*1e3/t:0,frames_decoded:r,total_decode_time:o}},HT=(c,n)=>{if(!Object.prototype.hasOwnProperty.call(c,V.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,V.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:n[x.VIDEO].delta_ms_encode_frame_out,frames_encoded:n[x.VIDEO].total_frames_encoded_out,total_encode_time:n[x.VIDEO].total_time_encoded_out};const r=c[V.FRAMES_ENCODED],o=c[V.TOTAL_ENCODE_TIME],a=o-n[x.VIDEO].total_time_encoded_out,t=r-n[x.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:t>0&&a?a*1e3/t:0,frames_encoded:r,total_encode_time:o}},d_=(c,n,r,o)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,V.BYTES_SENT))return{packetsSent:r[n].total_packets_out,packetsLost:r[n].total_packets_lost_out,bytesSent:r[n].total_KBytes_out};const a=Number(c[V.PACKETS_SENT])||0-(o?o[n].total_packets_out:0),t=a-r[n].total_packets_out,s=Number(c[V.BYTES_SENT])/1024-(o?o[n].total_KBytes_out:0),p=s-r[n].total_KBytes_out,_=c[V.TIMESTAMP]||Date.now(),d=o?o.timestamp:null;let g=r.timestamp;!g&&d&&(g=d);const T=g?_-g:0,E=T>0?p*.008*1024/T*1e3:0;return{packetsSent:a,deltaPacketsSent:t,KBytesSent:s,deltaKBytesSent:p,kbsSent:E}},p_=(c,n,r,o)=>{let a=r[n].total_packets_lost_out,t=0,s=0;return Object.prototype.hasOwnProperty.call(c,V.PACKETS_LOST)&&(a=Number(c[V.PACKETS_LOST])||0-(o?o[n].total_packets_lost_out:0),t=a-r[n].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,V.FRACTION_LOST)&&(s=Number(100*c[V.FRACTION_LOST])),{packetsLost:a,deltaPacketsLost:t,fractionLost:s}},m_=(c,n,r,o)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,V.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,V.BYTES_RECEIVED))return{percent_packets_lost:r[n].percent_packets_lost_in,packetsReceived:r[n].total_packets_in,packetsLost:r[n].total_packets_lost_in,bytesReceived:r[n].total_KBytes_in};const a=Number(c[V.PACKETS_RECEIVED])||0-(o?o[n].total_packets_in:0),t=Number(c[V.PACKETS_LOST])||0-(o?o[n].total_packets_lost_in:0),s=t-r[n].total_packets_lost_in,p=a-r[n].total_packets_in,_=a!==r[n].total_packets_in?s*100/(s+p):0,d=Number(c[V.BYTES_RECEIVED])/1024-(o?o[n].total_KBytes_in:0),g=d-r[n].total_KBytes_in,T=c[V.TIMESTAMP]||Date.now(),E=o?o.timestamp:null;let y=r.timestamp;!y&&E&&(y=E);const A=y?T-y:0,R=A>0?g*.008*1024/A*1e3:0;return{percentPacketsLost:_,packetsReceived:a,deltaPacketsReceived:p,packetsLost:t,deltaPacketsLost:s,KBytesReceived:d,deltaKBytesReceived:g,kbsReceived:R}},FT=c=>c[V.CANDIDATE_TYPE]!=="relay"?"":c[V.RELAY_PROTOCOL]||"",VT=c=>{if(!Object.prototype.hasOwnProperty.call(c,V.NETWORK_TYPE))return Yr.WIFI;switch(c[V.NETWORK_TYPE]){case cu.ETHERNET:return Yr.ETHERNET;case cu.CELLULAR_4G:return Yr.CELLULAR_4G;case cu.WIFI:return Yr.WIFI;default:return Yr.CELLULAR}},g_=c=>!Object.prototype.hasOwnProperty.call(c,V.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,V.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[V.FRAME_WIDTH]||null,height:c[V.FRAME_HEIGHT]||null,framerate:c[V.FRAMES_PER_SECOND]},jT=c=>{const n=Object.prototype.hasOwnProperty.call(c,V.QUALITY_LIMITATION_REASON)?c[V.QUALITY_LIMITATION_REASON]:null,r=Object.prototype.hasOwnProperty.call(c,V.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[V.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,o=Object.prototype.hasOwnProperty.call(c,V.QUALITY_LIMITATION_DURATIONS)?c[V.QUALITY_LIMITATION_DURATIONS]:null;return o&&Object.keys(o).forEach(a=>{o[a]>1e3&&(o[a]=Number(o[a]/1e3))}),{reason:n,durations:o,resolutionChanges:r}},qT=(c,n,r)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PLI)||!Object.prototype.hasOwnProperty.call(c,V.NACK))return{pliCount:n.total_pli_sent_in,nackCount:n.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const o=(c[V.PLI]||0)-(r?r[x.VIDEO].total_pli_sent_in:0),a=(c[V.NACK]||0)-(r?r[x.VIDEO].total_nack_sent_in:0);return{pliCount:o,nackCount:a,deltaPliCount:o-n[x.VIDEO].total_pli_sent_in,deltaNackCount:a-n[x.VIDEO].total_nack_sent_in}},BT=(c,n,r)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PLI)||!Object.prototype.hasOwnProperty.call(c,V.NACK))return{pliCount:n.total_pli_received_out,nackCount:n.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const o=(c[V.PLI]||0)-(r?r[x.VIDEO].total_pli_received_out:0),a=(c[V.NACK]||0)-(r?r[x.VIDEO].total_nack_received_out:0);return{pliCount:o,nackCount:a,deltaPliCount:o-n[x.VIDEO].total_pli_received_out,deltaNackCount:a-n[x.VIDEO].total_nack_received_out}},GT=c=>({channels:c[V.CHANNELS]||null,clock_rate:c[V.CLOCK_RATE]||null,mime_type:c[V.MIME_TYPE]||null,sdp_fmtp_line:c[V.SDP_FMTP_LINE]||null}),WT=c=>({clock_rate:c[V.CLOCK_RATE]||null,mime_type:c[V.MIME_TYPE]||null}),KT=(c,n,r)=>{const o=(c[V.BYTES_RECEIVED]||0)/1024-(r?r.data.total_KBytes_in:0),a=(c[V.BYTES_SENT]||0)/1024-(r?r.data.total_KBytes_out:0),t=c[V.TIMESTAMP]||Date.now(),s=o-n.data.total_KBytes_in,p=a-n.data.total_KBytes_out,_=r?r.timestamp:null;let d=n.timestamp;!d&&_&&(d=_);const g=d?t-d:0,T=g>0?s*.008*1024/g*1e3:0,E=g>0?p*.008*1024/g*1e3:0;return{total_KBytes_received:o,total_KBytes_sent:a,delta_KBytes_received:s,delta_KBytes_sent:p,kbs_speed_received:T,kbs_speed_sent:E}},YT=c=>{const n=c[V.AVAILABLE_INCOMING_BITRATE]/1024||0,r=c[V.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:n,kbs_outgoing_bandwidth:r}},zT=(c,n,r,o)=>{if(!c)return[];switch(c[V.TYPE]){case Wt.CANDIDATE_PAIR:let a=!1;if(c[V.NOMINATED]&&c[V.STATE]===x.SUCCEEDED&&(a=!0,Pe(ws,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c),V.SELECTED in c&&!c[V.SELECTED]&&(a=!1)),a){const s=c[V.LOCAL_CANDIDATE_ID],p=c[V.REMOTE_CANDIDATE_ID],_=KT(c,n,o),d=YT(c),g=LT(c,"data",o,n);return[{type:ne.NETWORK,value:{local_candidate_id:s}},{type:ne.NETWORK,value:{remote_candidate_id:p}},{type:ne.DATA,value:{total_KBytes_in:_.total_KBytes_received}},{type:ne.DATA,value:{total_KBytes_out:_.total_KBytes_sent}},{type:ne.DATA,value:{delta_KBytes_in:_.delta_KBytes_received}},{type:ne.DATA,value:{delta_KBytes_out:_.delta_KBytes_sent}},{type:ne.DATA,value:{delta_kbs_in:_.kbs_speed_received}},{type:ne.DATA,value:{delta_kbs_out:_.kbs_speed_sent}},{type:ne.DATA,value:{delta_kbs_bandwidth_in:d.kbs_incoming_bandwidth}},{type:ne.DATA,value:{delta_kbs_bandwidth_out:d.kbs_outgoing_bandwidth}},{type:ne.DATA,value:{delta_rtt_connectivity_ms:g.rtt}},{type:ne.DATA,value:{total_rtt_connectivity_ms:g.totalRTT}},{type:ne.DATA,value:{total_rtt_connectivity_measure:g.totalRTTMeasurements}}]}break;case Wt.LOCAL_CANDIDATE:if(c[V.ID]===n.network.local_candidate_id)return[{type:ne.NETWORK,value:{infrastructure:VT(c)}},{type:ne.NETWORK,value:{local_candidate_type:c[V.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{local_candidate_protocol:c[V.PROTOCOL]||""}},{type:ne.NETWORK,value:{local_candidate_relay_protocol:FT(c)}}];break;case Wt.REMOTE_CANDIDATE:if(c[V.ID]===n.network.remote_candidate_id)return[{type:ne.NETWORK,value:{remote_candidate_type:c[V.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{remote_candidate_protocol:c[V.PROTOCOL]||""}}];break;case Wt.INBOUND_RTP:{Pe(ws,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const s=c[V.SSRC],p=ft(s,n,Le.INBOUND);p&&(p.timestamp=n.timestamp);const _=ft(s,o,Le.INBOUND);if(_&&(_.timestamp=o.timestamp),c[V.MEDIA_TYPE]===x.AUDIO){const d=m_(c,x.AUDIO,p,_),g=uo(c,x.AUDIO,p),T=c[V.CODEC_ID]||"";return[{ssrc:s,type:ne.AUDIO,value:{codec_id_in:T}},{ssrc:s,type:ne.AUDIO,value:{total_packets_in:d.packetsReceived}},{ssrc:s,type:ne.AUDIO,value:{delta_packets_in:d.deltaPacketsReceived}},{ssrc:s,type:ne.AUDIO,value:{total_packets_lost_in:d.packetsLost}},{ssrc:s,type:ne.AUDIO,value:{delta_packets_lost_in:d.deltaPacketsLost}},{ssrc:s,type:ne.AUDIO,value:{percent_packets_lost_in:d.percentPacketsLost}},{ssrc:s,type:ne.AUDIO,value:{total_KBytes_in:d.KBytesReceived}},{ssrc:s,type:ne.AUDIO,value:{delta_KBytes_in:d.deltaKBytesReceived}},{ssrc:s,type:ne.AUDIO,value:{delta_kbs_in:d.kbsReceived}},{ssrc:s,type:ne.AUDIO,value:{delta_jitter_ms_in:g}}]}if(c[V.MEDIA_TYPE]===x.VIDEO){const d=$T(c,p),g=m_(c,x.VIDEO,p,_),T=uo(c,x.VIDEO,p),E=c[V.DECODER_IMPLEMENTATION]||null,y=c[V.CODEC_ID]||null,A=g_(c),R=qT(c,p,_);return[{ssrc:s,type:ne.VIDEO,value:{codec_id_in:y}},{ssrc:s,type:ne.VIDEO,value:{total_packets_in:g.packetsReceived}},{ssrc:s,type:ne.VIDEO,value:{delta_packets_in:g.deltaPacketsReceived}},{ssrc:s,type:ne.VIDEO,value:{total_packets_lost_in:g.packetsLost}},{ssrc:s,type:ne.VIDEO,value:{delta_packets_lost_in:g.deltaPacketsLost}},{ssrc:s,type:ne.VIDEO,value:{percent_packets_lost_in:g.percentPacketsLost}},{ssrc:s,type:ne.VIDEO,value:{total_KBytes_in:g.KBytesReceived}},{ssrc:s,type:ne.VIDEO,value:{delta_KBytes_in:g.deltaKBytesReceived}},{ssrc:s,type:ne.VIDEO,value:{delta_kbs_in:g.kbsReceived}},{ssrc:s,type:ne.VIDEO,value:{delta_jitter_ms_in:T}},{ssrc:s,type:ne.VIDEO,value:{decoder_in:E}},{ssrc:s,type:ne.VIDEO,value:{delta_ms_decode_frame_in:d.delta_ms_decode_frame}},{ssrc:s,type:ne.VIDEO,value:{total_frames_decoded_in:d.frames_decoded}},{ssrc:s,type:ne.VIDEO,value:{total_time_decoded_in:d.total_decode_time}},{ssrc:s,type:ne.VIDEO,value:{total_nack_sent_in:R.nackCount}},{ssrc:s,type:ne.VIDEO,value:{delta_nack_sent_in:R.deltaNackCount}},{ssrc:s,type:ne.VIDEO,value:{total_pli_sent_in:R.pliCount}},{ssrc:s,type:ne.VIDEO,value:{delta_pli_sent_in:R.deltaPliCount}},{ssrc:s,type:ne.VIDEO,value:{size_in:A}}]}break}case Wt.OUTBOUND_RTP:{Pe(ws,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const s=c[V.SSRC],p=ft(s,n,Le.OUTBOUND);p&&(p.timestamp=n.timestamp);const _=ft(s,o,Le.OUTBOUND);if(_&&(_.timestamp=o.timestamp),c[V.MEDIA_TYPE]===x.AUDIO){const d=c[V.CODEC_ID]||null,g=d_(c,x.AUDIO,p,_);return[{ssrc:s,type:ne.AUDIO,value:{codec_id_out:d}},{ssrc:s,type:ne.AUDIO,value:{total_packets_out:g.packetsSent}},{ssrc:s,type:ne.AUDIO,value:{delta_packets_out:g.deltaPacketsSent}},{ssrc:s,type:ne.AUDIO,value:{total_KBytes_out:g.KBytesSent}},{ssrc:s,type:ne.AUDIO,value:{delta_KBytes_out:g.deltaKBytesSent}},{ssrc:s,type:ne.AUDIO,value:{delta_kbs_out:g.kbsSent}}]}if(c[V.MEDIA_TYPE]===x.VIDEO){const d=c[V.ENCODER_IMPLEMENTATION]||null,g=c[V.CODEC_ID]||null,T=HT(c,p),E=g_(c),y=jT(c),A=BT(c,p,_),R=d_(c,x.VIDEO,p,_);return[{ssrc:s,type:ne.VIDEO,value:{codec_id_out:g}},{ssrc:s,type:ne.VIDEO,value:{total_packets_out:R.packetsSent}},{ssrc:s,type:ne.VIDEO,value:{delta_packets_out:R.deltaPacketsSent}},{ssrc:s,type:ne.VIDEO,value:{total_KBytes_out:R.KBytesSent}},{ssrc:s,type:ne.VIDEO,value:{delta_KBytes_out:R.deltaKBytesSent}},{ssrc:s,type:ne.VIDEO,value:{delta_kbs_out:R.kbsSent}},{ssrc:s,type:ne.VIDEO,value:{encoder_out:d}},{ssrc:s,type:ne.VIDEO,value:{delta_ms_encode_frame_out:T.delta_ms_encode_frame}},{ssrc:s,type:ne.VIDEO,value:{total_frames_encoded_out:T.frames_encoded}},{ssrc:s,type:ne.VIDEO,value:{total_time_encoded_out:T.total_encode_time}},{ssrc:s,type:ne.VIDEO,value:{total_nack_received_out:A.nackCount}},{ssrc:s,type:ne.VIDEO,value:{delta_nack_received_out:A.deltaNackCount}},{ssrc:s,type:ne.VIDEO,value:{total_pli_received_out:A.pliCount}},{ssrc:s,type:ne.VIDEO,value:{delta_pli_received_out:A.deltaPliCount}},{ssrc:s,type:ne.VIDEO,value:{size_out:E}},{ssrc:s,type:ne.VIDEO,value:{limitation_out:y}}]}break}case Wt.MEDIA_SOURCE:{Pe(ws,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);break}case Wt.TRACK:{Pe(ws,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);break}case Wt.CODEC:const t=[];return Object.keys(n[x.AUDIO]).forEach(s=>{const p=n[x.AUDIO][s];if(p.codec_id_in===c[V.ID]||p.codec_id_out===c[V.ID]){Pe(ws,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const _=GT(c);c[V.ID]===p.codec_id_in?t.push({ssrc:p.ssrc,type:ne.AUDIO,value:{codec_in:_}}):t.push({ssrc:p.ssrc,type:ne.AUDIO,value:{codec_out:_}})}}),Object.keys(n[x.VIDEO]).forEach(s=>{const p=n[x.VIDEO][s];if(p.codec_id_in===c[V.ID]||p.codec_id_out===c[V.ID]){Pe(ws,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const _=WT(c);c[V.ID]===p.codec_id_in?t.push({ssrc:p.ssrc,type:ne.VIDEO,value:{codec_in:_}}):t.push({ssrc:p.ssrc,type:ne.VIDEO,value:{codec_out:_}})}}),t;case Wt.REMOTE_INBOUND_RTP:{Pe(ws,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const s=c[V.SSRC],p=ft(s,n,Le.OUTBOUND),_=ft(s,o,Le.OUTBOUND);if(c[V.KIND]===x.AUDIO){const d=h_(c,x.AUDIO,_,p),g=uo(c,x.AUDIO,p),T=p_(c,x.AUDIO,p,_);return[{ssrc:s,type:ne.AUDIO,value:{delta_rtt_ms_out:d.rtt}},{ssrc:s,type:ne.AUDIO,value:{total_rtt_ms_out:d.totalRTT}},{ssrc:s,type:ne.AUDIO,value:{total_rtt_measure_out:d.totalRTTMeasurements}},{ssrc:s,type:ne.AUDIO,value:{delta_jitter_ms_out:g}},{ssrc:s,type:ne.AUDIO,value:{timestamp_out:c[V.TIMESTAMP]}},{ssrc:s,type:ne.AUDIO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:s,type:ne.AUDIO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:s,type:ne.AUDIO,value:{percent_packets_lost_out:T.fractionLost}}]}if(c[V.KIND]===x.VIDEO){const d=h_(c,x.VIDEO,_,p),g=uo(c,x.VIDEO,p),T=p_(c,x.VIDEO,p,_);return[{ssrc:s,type:ne.VIDEO,value:{delta_rtt_ms_out:d.rtt}},{ssrc:s,type:ne.VIDEO,value:{total_rtt_ms_out:d.totalRTT}},{ssrc:s,type:ne.VIDEO,value:{total_rtt_measure_out:d.totalRTTMeasurements}},{ssrc:s,type:ne.VIDEO,value:{delta_jitter_ms_out:g}},{ssrc:s,type:ne.VIDEO,value:{timestamp_out:c[V.TIMESTAMP]}},{ssrc:s,type:ne.VIDEO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:s,type:ne.VIDEO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:s,type:ne.VIDEO,value:{percent_packets_lost_out:T.fractionLost}}]}break}}return[]},co=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),JT=(c,n=x.AUDIO,r,o,a)=>{const t=ft(a,c,Le.INBOUND),s=ft(a,r,Le.INBOUND),p=ft(a,o,Le.INBOUND),_=[],d=[],g=t[n].percent_packets_lost_in,T=t[n].delta_jitter_ms_in,E=s&&s[n].delta_jitter_ms_in||null,y=p&&p[n].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,R=r&&r.data.delta_rtt_connectivity_ms||null,I=o&&o.data.delta_rtt_connectivity_ms||null;A&&_.push(A),R&&_.push(R),I&&_.push(I),T&&d.push(T),r&&E&&d.push(E),o&&y&&d.push(y);const $=_.length>0?bs(_):100,L=d.length>0?bs(d):10,ae=93.2-g,N=.18*ae*ae-27.9*ae+1126.62,F=($+L)/2,Se=F-177.3<0?0:1,ve=.024*F+.11*(F-177.3)*Se,M=N-ve;return co(M)},XT=(c,n=x.AUDIO,r,o,a)=>{const t=ft(a,c,Le.OUTBOUND),s=ft(a,r,Le.OUTBOUND),p=ft(a,o,Le.OUTBOUND),_=[],d=[],g=t[n].percent_packets_lost_out,T=t[n].delta_rtt_ms_out,E=s&&s[n].delta_rtt_ms_out||null,y=p&&p[n].delta_rtt_ms_out||null,A=t[n].delta_jitter_ms_out,R=s&&s[n].delta_jitter_ms_out||null,I=p&&p[n].delta_jitter_ms_out||null,$=c.data.delta_rtt_connectivity_ms,L=r&&r.data.delta_rtt_connectivity_ms||null,ae=o&&o.data.delta_rtt_connectivity_ms||null;T?_.push(T):$&&_.push($),E?_.push(E):L&&_.push(L),y?_.push(y):ae&&_.push(ae),A&&d.push(A),r&&R&&d.push(R),o&&I&&d.push(I);const N=_.length>0?bs(_):100,F=d.length>0?bs(d):10,Se=93.2-g,ve=.18*Se*Se-27.9*Se+1126.62,M=(N+F)/2,D=M-177.3<0?0:1,B=.024*M+.11*(M-177.3)*D,j=ve-B;return co(j)},QT=(c,n=x.AUDIO,r,o,a)=>{const t=ft(a,c,Le.INBOUND),s=ft(a,r,Le.INBOUND),p=ft(a,o,Le.INBOUND),_=[],d=[],g=t[n].percent_packets_lost_in/100,T=t[n].delta_jitter_ms_in,E=s&&s[n].delta_jitter_ms_in||null,y=p&&p[n].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,R=r&&r.data.delta_rtt_connectivity_ms||null,I=o&&o.data.delta_rtt_connectivity_ms||null;A&&_.push(A),R&&_.push(R),I&&_.push(I),T&&d.push(T),s&&E&&d.push(E),p&&y&&d.push(y);const $=_.length>0?bs(_):100,L=d.length>0?bs(d):10,ae=0,N=19.8,F=29.7,Se=30,ve=($+L)/2+Se,M=ve-177.3<0?0:1,D=.024*ve+.11*(ve-177.3)*M,j=93.2-(ae+N*Math.log(1+F*g)+D);return co(j)},ZT=(c,n=x.AUDIO,r,o,a)=>{const t=ft(a,c,Le.OUTBOUND),s=ft(a,r,Le.OUTBOUND),p=ft(a,o,Le.OUTBOUND),_=[],d=[],g=t[n].percent_packets_lost_out/100,T=t[n].delta_rtt_ms_out,E=s&&s[n].delta_rtt_ms_out||null,y=p&&p[n].delta_rtt_ms_out||null,A=t[n].delta_jitter_ms_out,R=s&&s[n].delta_jitter_ms_out||null,I=p&&p[n].delta_jitter_ms_out||null,$=c.data.delta_rtt_connectivity_ms,L=r&&r.data.delta_rtt_connectivity_ms||null,ae=o&&o.data.delta_rtt_connectivity_ms||null;T?_.push(T):$&&_.push($),E?_.push(E):L&&_.push(L),y?_.push(y):ae&&_.push(ae),A&&d.push(A),s&&R&&d.push(R),p&&I&&d.push(I);const N=_.length>0?bs(_):100,F=d.length>0?bs(d):10,Se=0,ve=19.8,M=29.7,D=30,B=(N+F)/2+D,j=B-177.3<0?0:1,z=.024*B+.11*(B-177.3)*j,Z=93.2-(Se+ve*Math.log(1+M*g)+z);return co(Z)};class ev{constructor(n,r){this._callbacks={onreport:null,onticket:null},this._id=DT(),this._moduleName=this._id,this._probeId=r,this._config=n,this._exporter=new kT(n),this._state=ps.IDLE,this.registerToPCEvents(),Qs(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(n,r,o,a){const t=(_,d)=>_===x.AUDIO?d===Wt.INBOUND_RTP?{...o_}:{...a_}:d===Wt.INBOUND_RTP?{...u_}:{...c_},s=RT(r);s.pname=this._config.pname,s.call_id=this._config.cid,s.user_id=this._config.uid,s.count=r?r.count+1:1;let p=null;return n.forEach(_=>{!p&&_.timestamp&&(p=_.timestamp),zT(_,s,s.pname,a).forEach(g=>{if(g.value&&g.type)if(g.ssrc){let T=s[g.type][g.ssrc];T||(T=t(g.type,_.type),T.ssrc=g.ssrc,s[g.type][g.ssrc]=T),Object.keys(g.value).forEach(E=>{T[E]=g.value[E]})}else Object.keys(g.value).forEach(T=>{s[g.type][T]=g.value[T]})})}),s.timestamp=p,Object.keys(s[x.AUDIO]).forEach(_=>{const d=s[x.AUDIO][_];d.direction===Le.INBOUND?(d.mos_emodel_in=JT(s,x.AUDIO,r,o,d.ssrc),d.mos_in=QT(s,x.AUDIO,r,o,d.ssrc)):(d.mos_emodel_out=XT(s,x.AUDIO,r,o,d.ssrc),d.mos_out=ZT(s,x.AUDIO,r,o,d.ssrc))}),s}async takeReferenceStats(){return new Promise((n,r)=>{const o=Date.now();setTimeout(async()=>{try{const a=Date.now()-o,t=Date.now(),s=await this._config.pc.getStats(),p=this.analyze(s,null,null,null),_=Date.now();p.experimental.time_to_measure_ms=_-t,p.experimental.time_to_wait_ms=a,this._exporter.saveReferenceReport(p),Pe(this._moduleName,`got reference report for probe ${this._probeId}`),n()}catch(a){r(a)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==ps.RUNNING||!this._config.pc)return Pe(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const n=Date.now(),r=await this._config.pc.getStats(),o=this.analyze(r,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),a=Date.now();return o.experimental.time_to_measure_ms=a-n,this._exporter.addReport(o),Pe(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(o),o}catch(n){return Pn(this._moduleName,`got error ${n}`),null}}async start(){Pe(this._moduleName,"starting"),this.state=ps.RUNNING,this._startedTime=this._exporter.start(),Pe(this._moduleName,"started")}async mute(){this.state=ps.MUTED,Pe(this._moduleName,"muted")}async unmute(){this.state=ps.RUNNING,Pe(this._moduleName,"unmuted")}async stop(n){if(Pe(this._moduleName,`stopping${n?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=ps.IDLE,this._config.ticket){const{ticket:r}=this._exporter;this.fireOnTicket(r)}this._exporter.reset(),Pe(this._moduleName,"stopped")}registerCallback(n,r,o){n in this._callbacks?(this._callbacks[n]={callback:r,context:o},Pe(this._moduleName,`registered callback '${n}'`)):Pn(this._moduleName,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Pe(this._moduleName,`unregistered callback '${n}'`)):Pn(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReport(n){this._callbacks.onreport&&_u(this._callbacks.onreport.callback,this._callbacks.onreport.context,n)}fireOnTicket(n){this._callbacks.onticket&&_u(this._callbacks.onticket.callback,this._callbacks.onticket.context,n)}updateConfig(n){this._config=n,this._exporter.updateConfig(n)}get state(){return this._state}set state(n){this._state=n,Pe(this._moduleName,`state changed to ${n}`)}addCustomEvent(n,r,o,a){this._exporter.addCustomEvent({at:typeof n=="object"?n.toJSON():n,category:r,name:o,description:a})}async registerToPCEvents(){const{pc:n}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const r=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${r.length} devices found`,"Media Devices state")}catch{Pn(this._moduleName,"can't get devices")}},n){n.oniceconnectionstatechange=()=>{const o=n.iceConnectionState;o===Kr.CONNECTED||o===Kr.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===Kr.DISCONNECTED||o===Kr.FAILED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===Kr.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},n.onicegatheringstatechange=()=>{const o=n.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",o,"ICE gathering state")},n.ontrack=o=>{this.addCustomEvent(new Date().toJSON(),"call",`${o.track.kind}track`,"MediaStreamTrack received")},n.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const r=n.getReceivers();if(r&&r.length>0){const o=r[0],{transport:a}=o;if(a){const{iceTransport:t}=a;t&&(t.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class tv{constructor(n){this._id=n.pname&&n.pname.substr(0,12).padEnd(12," ")||OT(),this._moduleName=this._id,Qs(this._moduleName,"probe created"),this._config=n,this._collector=new ev(this._config,this._id)}set onreport(n){n?this._collector.registerCallback("onreport",n):this._collector.unregisterCallback("onreport")}set onticket(n){n?this._collector.registerCallback("onticket",n):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(n){this._collector.state=n}addCustomEvent(n,r,o,a=new Date().toJSON()){this._collector.addCustomEvent(a,r,n,o)}get isRunning(){return this._collector.state===ps.RUNNING}get isIdle(){return this._collector.state===ps.IDLE}updateUserId(n){this._config.uid=n,this._collector.updateConfig(this._config)}updateCallId(n){this._config.cid=n,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){ao(this._moduleName,"probe is already running");return}this._collector.start()}stop(n=!1){this.isRunning&&this._collector.stop(n)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const Ct="engine ";class sv{constructor(n){this._config=n,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},Qs(Ct,`configured for probing every ${this._config.refreshEvery}ms`),Qs(Ct,`configured for starting after ${this._config.startAfter}ms`),Qs(Ct,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Pe(Ct,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(n=>n.isRunning)}get isIdle(){return this._probes.every(n=>n.isIdle)}addNewProbe(n,r){if(!n)throw new Error("undefined peer connection");const o=bT(n,r,this._config),a=new tv(o);return this._probes.push(a),Pe(Ct,`${this._probes.length} probes registered`),a}removeExistingProbe(n){if(!n)throw new Error("undefined probe");n.state===ps.RUNNING&&n.stop(),this._probes=this._probes.filter(r=>n.id!==r.id)}async start(){const n=()=>{this._probes.forEach(t=>t.start())},r=async()=>Promise.all(this._probes.map(t=>t.takeReferenceStats())),o=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,a=async()=>{const t=CT(),s=this._probes.filter(p=>p.isRunning);for(const p of s){const _=await p.collectStats();_&&t.probes.push(_),Pe(Ct,`got probe ${p.id}`),await f_(0)}return t.delta_time_to_measure_probes_ms=Zs(t.probes,"experimental","time_to_measure_ms"),t.delta_KBytes_in=Zs(t.probes,"data","delta_KBytes_in"),t.delta_KBytes_out=Zs(t.probes,"data","delta_KBytes_out"),t.delta_kbs_in=Zs(t.probes,"data","delta_kbs_in"),t.delta_kbs_out=Zs(t.probes,"data","delta_kbs_out"),t.total_time_decoded_in=Zs(t.probes,"video","total_time_decoded_in"),t.total_time_encoded_out=Zs(t.probes,"video","total_time_encoded_out"),t};for(Pe(Ct,"starting to collect"),n(),Pe(Ct,"generating reference reports..."),await r(),Pe(Ct,"reference reports generated"),this._startedTime=Date.now();o();)if(Pe(Ct,`wait ${this._config.refreshEvery}ms before collecting`),await f_(this._config.refreshEvery),o()){Pe(Ct,"collecting...");const t=Date.now(),s=await a(),p=Date.now();s.delta_time_consumed_to_measure_ms=p-t,this.fireOnReports(s),Pe(Ct,"collected")}Pe(Ct,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(n){const r=o=>{this._probes.forEach(a=>{a.stop(o)})};Qs(Ct,"stop collecting"),r(n)}registerCallback(n,r,o){n in this._callbacks?(this._callbacks[n]={callback:r,context:o},Pe(Ct,`registered callback '${n}'`)):Pn(Ct,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Pe(this._moduleName,`unregistered callback '${n}'`)):Pn(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReports(n){this._callbacks.onresult&&n.probes.length>0&&_u(this._callbacks.onresult.callback,this._callbacks.onresult.context,n)}}const nv="interface ";class rv{constructor(n){this._config=wT(n),Qs(nv,`welcome to ${this._config.name} version ${this._config.version}`),mT(this._config.verbose||!1),this._engine=new sv(this._config)}setupLogLevel(n){gT(n)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(n,r){return this._engine.addNewProbe(n,r)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(n){this._engine.removeExistingProbe(n)}set onresult(n){n?this._engine.registerCallback("onresult",n):this._engine.unregisterCallback("onresult")}}function iv(c,n){return Object.keys(c).filter(r=>n.includes(r)).reduce((r,o)=>{const a=o;return{...r,[a]:c[a]}},{})}const lv=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"];class ov{constructor(n){this.intervals={},this.emitInterval=n.emitInterval||200,this.onChangeFunction=n.onChangeFunction}start(n,r){n&&n.getTracks().length&&requestAnimationFrame(()=>this.beginCalculation(n,r))}stop(n){this.clearVolumeInterval(n)}clearVolumeInterval(n){console.log("clearVolumeInterval",n),clearInterval(this.intervals[n]),delete this.intervals[n]}clearAllIntervals(){Object.keys(this.intervals).forEach(n=>{clearInterval(this.intervals[n])}),this.intervals={}}beginCalculation(n,r){this.clearVolumeInterval(r);const o=Xs.createAnalyser(),a=Xs.createMediaStreamSource(n),t=Xs.createScriptProcessor(2048,1,1);o.smoothingTimeConstant=.8,o.fftSize=1024,a.connect(o),o.connect(t),t.connect(Xs.destination),this.intervals[r]=setInterval(()=>{const s=new Uint8Array(o.frequencyBinCount);o.getByteFrequencyData(s);let p=0;const _=s.length;for(let g=0;g<_;g++)p+=s[g];const d=p/_;this.onChangeFunction(r,d)},this.emitInterval)}}const fo={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},av=0;class uv{constructor(n){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=n,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new ov({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices()}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(n){this.currentActiveRoomIdValue=n,this.context.emit("currentActiveRoomChanged",n)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(n){this.isCallAddingInProgress=n,this.context.emit("callAddingInProgressChanged",n)}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(n=>n.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audiooutput")}get getUserMediaConstraints(){return{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(n){this.availableMediaDevices=n,this.context.emit("changeAvailableDeviceList",n)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const n=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(n)}async initializeMediaDevices(){const n=localStorage.getItem(fo.SELECTED_INPUT_DEVICE)||"default",r=localStorage.getItem(fo.SELECTED_OUTPUT_DEVICE)||"default";(await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints)).getTracks().forEach(t=>t.stop());const a=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(a),await this.setMicrophone(n),await this.setSpeaker(r),navigator.mediaDevices.addEventListener("devicechange",async()=>{const t=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(t)})}setCallTime(n){const r={...n};delete r.callId,this.callTime={...this.callTime,[n.callId]:r},this.context.emit("changeCallTime",this.callTime)}removeCallTime(n){const r={...this.callTime};delete r[n],this.callTime={...r},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(n,r){this.timeIntervals={...this.timeIntervals,[n]:r}}removeTimeInterval(n){const r={...this.timeIntervals};r[n]&&(clearInterval(r[n]),delete r[n],this.timeIntervals={...r})}stopCallTimer(n){this.removeTimeInterval(n),this.removeCallTime(n)}emitVolumeChange(n,r){this.context.emit("changeCallVolume",{callId:n,volume:r})}setMetricsConfig(n){this.metricConfig={...this.metricConfig,...n}}sendDTMF(n,r){if(!/^[A-D0-9]+$/g.test(r))throw new Error("Not allowed character in DTMF input");this.extendedCalls[n].sendDTMF(r)}setIsMuted(n){this.muted=n,this.context.emit("changeIsMuted",n)}processMute(n){const r=this.currentActiveRoomId;this.setIsMuted(n),this.initialStreamValue.getTracks().forEach(o=>o.enabled=!n),this.roomReconfigure(r)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:n,toHold:r,automatic:o}){const a=this.extendedCalls[n];a._automaticHold=o??!1,await new Promise(p=>{const _=()=>{p()};r?a.hold({},_):a.unhold({},_)}),this.updateCall(a);const s=Object.values(this.extendedCalls).filter(p=>p.roomId===this.currentActiveRoomId&&(r?n!==p._id:!0));s.length>1&&await this.doConference(s)}holdCall(n,r=!1){return this.processHold({callId:n,automatic:r,toHold:!0})}unholdCall(n){return this.processHold({callId:n,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(n=>n.direction==="outgoing"&&n.status===av).forEach(n=>this.terminateCall(n._id))}answerCall(n){const r=this.extendedCalls[n];this.cancelAllOutgoingUnanswered(),r.answer(this.sipOptions),this.updateCall(r),this.setActiveRoom(r.roomId),r.connection.addEventListener("track",o=>{this.triggerAddStream(o,r)})}async moveCall(n,r){this.updateCallStatus({callId:n,isMoving:!0}),await this.processRoomChange({callId:n,roomId:r}),this.updateCallStatus({callId:n,isMoving:!1})}updateCall(n){this.activeCalls[n._id]=e_(n),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(n){const o={...this.activeRooms[n.roomId],...n};this.activeRooms={...this.activeRooms,[n.roomId]:{...o}},this.context.emit("updateRoom",{room:o,roomList:this.activeRooms})}hasAutoAnswerHeaders(n){const r=/answer-after=0/,a=n.request.getHeader("Call-Info");return a&&r.test(a)}addCall(n,r=!0){this.activeCalls={...this.activeCalls,[n._id]:e_(n)},this.extendedCalls[n._id]=n,r&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(n){this.callStatus={...this.callStatus,[n]:{isMoving:!1,isTransferring:!1,isMerging:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(n){const o={...{...this.callStatus[n.callId]}};n.isMoving!==void 0&&(o.isMoving=n.isMoving),n.isTransferring!==void 0&&(o.isTransferring=n.isTransferring),n.isMerging!==void 0&&(o.isMerging=n.isMerging),this.callStatus={...this.callStatus,[n.callId]:{...o}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(n){const r={...this.callStatus};delete r[n],this.callStatus={...r},this.context.emit("changeCallStatus",this.callStatus)}addRoom(n){this.activeRooms={...this.activeRooms,[n.roomId]:n},this.context.emit("addRoom",{room:n,roomList:this.activeRooms})}getActiveStream(){const n=s_(this.initialStreamValue,this.microphoneInputLevel*2);return n.getTracks().forEach(r=>r.enabled=!this.isMuted),this.setActiveStream(n),n}async setMicrophone(n){if(!this.getInputDeviceList.find(({deviceId:o})=>o===n)||(this.setSelectedInputDevice(n),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const r=Object.values(this.extendedCalls).filter(o=>o.roomId===this.currentActiveRoomId);r.length===1?Object.values(r).forEach(async o=>{const a=this.getActiveStream();o.connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.updateCall(o)}):await this.doConference(r)}setActiveStream(n){this.activeStream&&this.stopVUMeter("origin"),this.setupVUMeter(n,"origin"),this.activeStreamValue=n,this.context.emit("changeActiveStream",n)}async setSpeaker(n){if(!this.getOutputDeviceList.find(({deviceId:a})=>a===n))return;this.setSelectedOutputDevice(n);const r=Object.values(this.extendedCalls);if(r.length===0)return;const o=r.filter(a=>a.roomId===this.currentActiveRoomId);o.length===1?r.forEach(a=>{var t;(t=a.audioTag)==null||t.setSinkId(n),this.updateCall(a)}):await this.doConference(o)}removeRoom(n){const r={...this.activeRooms},o={...r[n]};delete r[n],this.activeRooms={...r},this.context.emit("removeRoom",{room:o,roomList:this.activeRooms})}deleteRoomIfEmpty(n){n!==void 0&&Object.values(this.extendedCalls).filter(r=>r.roomId===n).length===0&&(this.removeRoom(n),this.currentActiveRoomId===n&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(n){this.muted?n.mute({audio:!0}):n.unmute({audio:!0})}async roomReconfigure(n){if(n===void 0)return;const r=Object.values(this.extendedCalls).filter(o=>o.roomId===n);if(this.currentActiveRoomId===n?r.forEach(o=>{o.audioTag&&(this.muteReconfigure(o),o.audioTag.muted=!1,this.updateCall(o))}):r.forEach(o=>{o.audioTag&&(o.audioTag.muted=!0,this.updateCall(o))}),r.length===0)this.deleteRoomIfEmpty(n);else if(r.length===1&&this.currentActiveRoomId!==n)r[0].isOnHold().local||await this.holdCall(r[0].id,!0);else if(r.length===1&&this.currentActiveRoomId===n){if(r[0].isOnHold().local&&r[0]._automaticHold&&await this.unholdCall(r[0].id),r[0].connection&&r[0].connection.getSenders()[0]){const o=this.getActiveStream();await r[0].connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.muteReconfigure(r[0])}}else r.length>1&&await this.doConference(r)}async doConference(n){await r_.forEach(n,async o=>{o._localHold&&await this.unholdCall(o._id)});const r=[];n.forEach(o=>{o!=null&&o.connection.getReceivers().forEach(a=>{r.push(a.track)})}),await r_.forEach(n,async o=>{if(o==null)return;const a=new MediaStream,t=Xs.createMediaStreamDestination();if(o.connection.getReceivers().forEach(s=>{r.forEach(p=>{a.addTrack(s.track),s.track.id!==p.id&&Xs.createMediaStreamSource(new MediaStream([p])).connect(t)})}),n[0].roomId===this.currentActiveRoomId){const s=this.getActiveStream();Xs.createMediaStreamSource(s).connect(t)}o.connection.getSenders()[0]&&(await o.connection.getSenders()[0].replaceTrack(t.stream.getTracks()[0]),this.muteReconfigure(o))})}processCallerMute(n,r){const o=this.extendedCalls[n];o&&o.connection.getReceivers().length&&(o.localMuted=r,o.connection.getReceivers().forEach(a=>{a.track.enabled=!r}),this.updateCall(o))}muteCaller(n){this.processCallerMute(n,!0)}unmuteCaller(n){this.processCallerMute(n,!1)}terminateCall(n){const r=this.extendedCalls[n];r._status!==8&&r.terminate()}transferCall(n,r){if(r.toString().length===0)return new Error("Target must be passed");const o=this.extendedCalls[n];if(!o._is_confirmed&&!o._is_canceled){const a=`sip:${r}@${this.context.sipDomain}`;o.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${a}`]});return}this.updateCallStatus({callId:n,isTransferring:!0}),o.refer(`sip:${r}@${this.context.sipDomain}`),this.updateCall(o)}mergeCall(n){const r=Object.values(this.extendedCalls).filter(t=>t.roomId===n);if(r.length!==2)return;const o=r[0],a=r[1];!o||!a||(this.updateCallStatus({callId:o._id,isMerging:!0}),this.updateCallStatus({callId:a._id,isMerging:!0}),o.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(o))}setDND(n){this.isDNDEnabled=n,this.context.emit("changeIsDND",n)}startCallTimer(n){this.removeTimeInterval(n);const r={callId:n,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(r);const o=setInterval(()=>{const a={...this.callTime[n]},t=dT(a);this.setCallTime({callId:n,...t})},1e3);this.setTimeInterval(n,o)}async setActiveRoom(n){const r=this.currentActiveRoomId;n!==r&&(this.currentActiveRoomId=n,await this.roomReconfigure(r),await this.roomReconfigure(n))}getNewRoomId(){const n=Object.keys(this.activeRooms);return n.length===0?1:parseInt(n.sort()[n.length-1])+1}async setupCall(n){var d,g;const r=n.session;if(this.getActiveCalls[r.id]!==void 0)return;const a=this.getNewRoomId(),t={started:new Date,incomingInProgress:!1,roomId:a};r.direction==="incoming"?(this.context.logger.log("New incoming call from",(g=(d=r._remote_identity)==null?void 0:d._uri)==null?void 0:g._user),t.incomingInProgress=!0,this.context.subscribe(es.CALL_CONFIRMED,T=>{r.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.startCallTimer(r.id))}),this.context.subscribe(es.CALL_FAILED,T=>{r.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.deleteRoomIfEmpty(a))})):r.direction==="outgoing"&&(r.once("confirmed",()=>{this.startCallTimer(r.id)}),this.startCallTimer(r.id));const s=r,p=this.hasAutoAnswerHeaders(n),_=s.direction==="incoming"&&!this.hasActiveCalls&&(p||this.autoAnswer);s.roomId=a,s.localMuted=!1,s.autoAnswer=_,_?this.addCall(s,!1):this.addCall(s),this.addCallStatus(r.id),this.addRoom(t),_&&this.answerCall(s._id)}removeCall(n){const r={...this.activeCalls};delete r[n],this.activeCalls={...r};const o={...this.extendedCalls};delete o[n],this.extendedCalls={...o},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(n){const r=this.extendedCalls[n._id];this.stopVUMeter("origin"),r.connection.getSenders().forEach(a=>{a.track.stop()});const o=r.roomId;this.removeCall(n._id),this.roomReconfigure(o)}async newRTCSessionCallback(n){const r=n.session;if(this.isDND){r.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(r.on("ended",o=>{var t,s;this.stopVUMeter(r.id),this.context.logger.log("Session ended for",(s=(t=r._remote_identity)==null?void 0:t._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:es.CALL_ENDED,session:r,event:o});const a=this.getActiveCalls[r.id];a&&this.activeCallListRemove(a),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),this.initialStreamValue.getTracks().forEach(p=>p.stop()),this.initialStreamValue=null)}),r.on("progress",o=>{var a,t;this.context.logger.log("Session in progress for",(t=(a=r._remote_identity)==null?void 0:a._uri)==null?void 0:t._user),this.context.triggerListener({listenerType:es.CALL_PROGRESS,session:r,event:o})}),r.on("failed",o=>{var t,s;this.stopVUMeter(r.id),this.context.logger.log("Session failed for",(s=(t=r._remote_identity)==null?void 0:t._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:es.CALL_FAILED,session:r,event:o}),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const a=this.getActiveCalls[r.id];a&&this.activeCallListRemove(a),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),this.initialStreamValue.getTracks().forEach(p=>p.stop()),this.initialStreamValue=null)}),r.on("confirmed",o=>{var a,t;this.context.logger.log("Session confirmed for",(t=(a=r._remote_identity)==null?void 0:a._uri)==null?void 0:t._user),this.context.triggerListener({listenerType:es.CALL_CONFIRMED,session:r,event:o}),this.updateCall(r),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(n),r.direction==="outgoing"){const o=this.getActiveCalls[r.id].roomId;this.setActiveRoom(o)}}setMuteWhenJoin(n){this.muteWhenJoinEnabled=n,this.context.emit("changeMuteWhenJoin",n)}setMicrophoneSensitivity(n){if(n<0||n>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=n,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(n){this.speakerVolumeValue=n,Object.values(this.extendedCalls).forEach(r=>{r.audioTag&&(r.audioTag.volume=n,this.updateCall(r))})}setAutoAnswer(n){this.isAutoAnswer=n}setSelectedInputDevice(n){localStorage.setItem(fo.SELECTED_INPUT_DEVICE,n),this.selectedMediaDevices.input=n,this.context.emit("changeActiveInputMediaDevice",n)}setSelectedOutputDevice(n){localStorage.setItem(fo.SELECTED_OUTPUT_DEVICE,n),this.selectedMediaDevices.output=n,this.context.emit("changeActiveOutputMediaDevice",n)}setCallMetrics(n){const r={...n};delete r.callId,this.callMetrics={...this.callMetrics,[n.callId]:r},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(n){const r={...this.callMetrics};delete r[n],this.callMetrics={...r},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(n){const r=new rv(this.metricConfig),o=r.createProbe(n.connection,{cid:n._id}),a=[];let t;o.onreport=s=>{Object.entries(s.audio).forEach(([d,g])=>{g.direction==="inbound"&&!a.includes(d)&&(a.push(d),t=d)});const p=s.audio[t],_=iv(p,lv);_.callId=n._id,this.setCallMetrics(r)},this.context.subscribe(es.CALL_ENDED,s=>{s._id===n._id&&r.stopAllProbes()}),r.startAllProbes()}setupVUMeter(n,r){this.VUMeter.start(n,r)}stopVUMeter(n){this.VUMeter.stop(n)}async setupStream(){const n=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach(r=>r.stop()),this.initialStreamValue=null),this.initialStreamValue=n}async triggerAddStream(n,r){this.setIsMuted(this.muteWhenJoin||this.isMuted),this.initialStreamValue||await this.setupStream();const o=s_(this.initialStreamValue,this.microphoneInputLevel*2),a=this.isMuted||this.muteWhenJoin;o.getTracks().forEach(s=>s.enabled=!a),this.setActiveStream(o),await r.connection.getSenders()[0].replaceTrack(o.getTracks()[0]);const t=new MediaStream([n.track]);Zg(t,r,this.selectedOutputDevice,this.speakerVolume),this.setupVUMeter(t,r._id),this.getCallQuality(r),this.updateCall(r)}initCall(n,r){if(this.checkInitialized(),n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`);const o=this.context.call(`sip:${n}@${this.context.sipDomain}`,this.sipOptions);this.callAddingInProgress=o.id,r&&this.currentActiveRoomId!==void 0&&this.processRoomChange({callId:o.id,roomId:this.currentActiveRoomId}),o.connection.addEventListener("track",a=>{this.triggerAddStream(a,o)})}async processRoomChange({callId:n,roomId:r}){const o=this.extendedCalls[n].roomId;this.extendedCalls[n].roomId=r;const a=this.extendedCalls[n];return this.updateCall(a),await this.setActiveRoom(r),Promise.all([this.roomReconfigure(o),this.roomReconfigure(r)]).then(()=>{this.deleteRoomIfEmpty(o),this.deleteRoomIfEmpty(r)})}}class cv{constructor(n){this.context=n}get sipOptions(){return{...this.context.options.sipOptions}}initCall(n){if(n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${n}@${this.context.sipDomain}`,this.sipOptions),console.log("video call")}}class fv{constructor(n){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=n,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this.context))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(n){const r=this.extendedMessages[n];this.updateMSRPSession(r)}updateMSRPSession(n){this.activeMessages[n._id]=t_(n),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(n){this.activeMessages={...this.activeMessages,[n._id]:t_(n)},this.extendedMessages[n._id]=n,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(n,r){const o=this.msrpHistory[r.id]||[];o.push(n),this.msrpHistory={...this.msrpHistory,[r.id]:[...o]},this.context.emit("newMSRPMessage",{message:n,session:r})}messageTerminate(n){const r=this.extendedMessages[n];r._status!==8&&r.terminate()}addMessageSession(n){if(!n._id||this.getActiveMessages[n._id]!==void 0)return;const o=n;this.addMMSRPSession(o)}triggerMSRPListener({listenerType:n,session:r,event:o}){const a=this.context.listenersList[n];!a||!a.length||a.forEach(t=>{t(r,o)})}removeMMSRPSession(n){const r={...this.activeMessages};delete r[n],this.activeMessages={...r};const o={...this.extendedMessages};delete o[n],this.extendedMessages={...o},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(n){this.removeMMSRPSession(n._id)}newMSRPSessionCallback(n){const r=n.session;r.on("ended",o=>{this.triggerMSRPListener({listenerType:es.CALL_ENDED,session:r,event:o});const a=this.getActiveMessages[r.id];this.activeMessageListRemove(a)}),r.on("failed",o=>{this.triggerMSRPListener({listenerType:es.CALL_FAILED,session:r,event:o});const a=this.getActiveMessages[r.id];this.activeMessageListRemove(a)}),r.on("confirmed",o=>{this.triggerMSRPListener({listenerType:es.CALL_CONFIRMED,session:r,event:o}),this.updateMSRPSession(r)}),r.on("newMessage",o=>{this.addMSRPMessage(o,r)}),this.addMessageSession(r)}setIsMSRPInitializing(n){this.isMSRPInitializingValue=n,this.context.emit("isMSRPInitializingChanged",n)}initMSRP(n,r,o){if(n.length===0)return console.error("Target must be a valid string");const a=this.context.startMSRP(n,o);a.on("active",()=>{this.addMessageSession(a),a.sendMSRP(r),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(n,r){const o=this.extendedMessages[n];if(!o)throw new Error(`MSRP session with id ${n} doesn't exist!`);o.sendMSRP(r)}}const hu={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class _v extends Jg{constructor(n,r){if(!n.modules.length)throw new Error("options.modules should include at least 1 module");const o={...n.configuration,sockets:n.socketInterfaces.map(a=>new hT.WebSocketInterface(a))};super(o),this.initialized=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],n.pnExtraHeaders&&Object.keys(n.pnExtraHeaders).length&&this.registrator().setExtraContactParams(n.pnExtraHeaders),this.options=n,this.modules=n.modules,r&&eT(r)&&(this.logger=r)}on(n,r){return super.on(n,r)}off(n,r){return super.off(n,r)}emit(n,r){return super.emit(n,r)}get sipDomain(){return this.options.sipDomain}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(hu.AUDIO)&&(this.audio=new uv(this)),this.modules.includes(hu.MSRP)&&(this.msrp=new fv(this)),this.modules.includes(hu.VIDEO)&&(this.video=new cv(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.isReconnecting=!1}),this.on(this.disconnectedEventName,()=>{this.isReconnecting||(this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.isReconnecting=!0,this.stop(),this.setInitialized(!1),setTimeout(this.start.bind(this),5e3))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}subscribe(n,r){const a=!this.listenersList[n]||!this.listenersList[n].length?[r]:[...this.listenersList[n],r];this.listenersList={...this.listenersList,[n]:a}}removeIListener(n){const r={...this.listenersList};delete r[n],this.listenersList={...r}}triggerListener({listenerType:n,session:r,event:o}){const a=this.listenersList[n];!a||!a.length||a.forEach(t=>{t(r,o)})}setInitialized(n){this.initialized=n,this.emit("ready",n)}}return _v}();
155
+ `),this._newMSRPSession("local",this._request),this._id=this._request.call_id+this._from_tag,console.log("dialog be",this._dialog),new yf(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:t=>{this.onTransportError(),console.log(t)},onAuthenticated:t=>{this._request=t},onReceiveResponse:t=>{this._receiveInviteResponse(t),console.log("dialog af",this._dialog),t.status_code===200&&(t.parseSDP(!0),this._status=Ce.STATUS_CONFIRMED,this.target_addr=t.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=Ce.STATUS_INVITE_SENT}terminate(n={}){console.log("terminate",this);const r=n.cause||q.causes.BYE,o=Me.cloneArray(n.extraHeaders),a=n.body;let t,s=n.status_code,p=n.reason_phrase;if(this._status===Ce.STATUS_TERMINATED)throw new Ks.InvalidStateError(this._status);switch(this.status="terminated",this._status){case Ce.STATUS_NULL:case Ce.STATUS_INVITE_SENT:case Ce.STATUS_1XX_RECEIVED:if(s&&(s<200||s>=700))throw new TypeError(`Invalid status_code: ${s}`);s&&(p=p||q.REASON_PHRASE[s]||"",t=`SIP ;cause=${s} ;text="${p}"`),this._status===Ce.STATUS_NULL||this._status===Ce.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=t):this._status===Ce.STATUS_1XX_RECEIVED&&this._request.cancel(t),this._status=Ce.STATUS_CANCELED,console.log("failed 1"),this._failed("local",null,q.causes.CANCELED);break;case Ce.STATUS_WAITING_FOR_ANSWER:case Ce.STATUS_ANSWERED:if(s=s||480,console.log("REPLY 480"),s<300||s>=700)throw new TypeError(`Invalid status_code: ${s}`);this._request.reply(s,p,o,a),console.log("failed 2"),this._failed("local",null,q.causes.REJECTED);break;case Ce.STATUS_WAITING_FOR_ACK:case Ce.STATUS_CONFIRMED:if(p=n.reason_phrase||q.REASON_PHRASE[s]||"",s&&(s<200||s>=700))throw new TypeError(`Invalid status_code: ${s}`);if(s&&o.push(`Reason: SIP ;cause=${s}; text="${p}"`),this._status===Ce.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Lt.C.STATUS_TERMINATED){const _=this._dialog;this.receiveRequest=({method:d})=>{d===q.ACK&&(this.sendRequest(q.BYE,{extraHeaders:o,body:a}),_.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Lt.C.STATUS_TERMINATED&&(this.sendRequest(q.BYE,{extraHeaders:o,body:a}),_.terminate())}),this._ended("local",null,r),this._dialog=_,this._ua.newDialog(_)}else console.log("here it is"),this.sendRequest(q.BYE,{extraHeaders:o,body:a}),this._ended("local",null,r)}}sendRequest(n,r){return this._dialog.sendRequest(n,r)}authenticate(n){this.status="auth";let r=new Un("");r.method="AUTH",r.addHeader("To-Path",`msrp://${this._ua._configuration.realm}:2856;ws`),r.addHeader("From-Path",`msrp://${this.credentials.username}.${this.credentials.realm}:2856/${this.auth_id};ws`),n&&r.addHeader("Authorization",n.toString());let o=r.toString();console.log(o);let a=[];for(var t=0;t<o.length;t++)a.push(o.charCodeAt(t).toString(16));console.log(a),this._connection.send(r.toString())}onmessage(n){console.log("onmessage",n);const r=new Un(n.data);if(this.status==="auth"&&r.code===401){const o=this.parseAuth(r.getHeader("WWW-Authenticate")),a=new fm(this.credentials);a.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},o,Me.createRandomToken(12)),this.authenticate(a)}this.status==="auth"&&r.code===200&&this._direction==="outgoing"?(this.my_addr.push(r.getHeader("To-Path")),this.my_addr.push(r.getHeader("Use-Path")),this.status="active",this.inviteParty(r)):this.status==="auth"&&r.code===200&&this._direction==="incoming"?(this.my_addr.push(r.getHeader("To-Path")),this.my_addr.push(r.getHeader("Use-Path")),this.status="active",this.acceptParty(r),this.emit("confirmed")):r.method==="SEND"&&(this._sendOk(r),this._sendReport(r),r.direction="incoming",this.emit("newMessage",r),this._msgHistory.push(r),this.emit("msgHistoryUpdate",this._msgHistory),console.log("======================================================================")),r.code===480&&this._close()}onclose(){console.log("close")}onopen(){const n=new RTCPeerConnection({iceServers:[]});n.createDataChannel(""),n.createOffer().then(n.setLocalDescription.bind(n)),n.onicecandidate=r=>{if(!r||!r.candidate||!r.candidate.candidate)return;const o=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,a=r.candidate.candidate.match(o);this.my_ip=a&&a[1],n.onicecandidate=()=>{},this.authenticate(null)}}onerror(n){console.log(n)}_receiveInviteResponse(n){if(console.log("resp0000000000000",n),this._dialog&&n.status_code>=200&&n.status_code<=299)if(console.log("200000000000000"),this._dialog.id.call_id===n.call_id&&this._dialog.id.local_tag===n.from_tag&&this._dialog.id.remote_tag===n.to_tag){this.sendRequest(q.ACK);return}else{const r=new Xl(this,n,"UAC");if(r.error!==void 0){console.log(r.error);return}this.sendRequest(q.ACK),this.sendRequest(q.BYE);return}if(this._is_canceled){n.status_code>=100&&n.status_code<200?this._request.cancel(this._cancel_reason):n.status_code>=200&&n.status_code<299&&this._acceptAndTerminate(n);return}if(!(this._status!==Ce.STATUS_INVITE_SENT&&this._status!==Ce.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(n.status_code):this._status=Ce.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(n.status_code):{if(!n.to_tag){console.log("1xx response received without to tag");break}if(n.hasHeader("contact")&&!this._createDialog(n,"UAC",!0))break;if(this._status=Ce.STATUS_1XX_RECEIVED,!n.body){this._progress("remote",n);break}const r={originator:"remote",type:"answer",sdp:n.body};console.log('emit "sdp"'),this.emit("sdp",r);const o=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>this._progress("remote",n)).catch(a=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)});break}case/^2[0-9]{2}$/.test(n.status_code):{if(console.log("maybe here???"),this._status=Ce.STATUS_CONFIRMED,!n.body){this._acceptAndTerminate(n,400,q.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",n,q.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(n,"UAC"))break;const r={originator:"remote",type:"answer",sdp:n.body};console.log('emit "sdp"'),this.emit("sdp",r),new RTCSessionDescription({type:"answer",sdp:r.sdp}),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(o=>this._connection.setLocalDescription(o)).catch(o=>{this._acceptAndTerminate(n,500,o.toString()),console.log("failed 4"),this._failed("local",n,q.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(n),this._accepted("remote",n),this.sendRequest(q.ACK),this._confirmed("local",null)});break}default:{const r=Me.sipErrorCause(n.status_code);console.log("failed 5"),this._failed("remote",n,r)}}}sendMSRP(n){const r=new Un("");r.method="SEND",r.addHeader("To-Path",`${this.my_addr[1]} ${this.target_addr[1]} ${this.target_addr[0]}`),r.addHeader("From-Path",`${this.my_addr[0]}`),r.addHeader("Message-ID",Me.createRandomToken(10)),r.addHeader("Byte-Range","1-25/25"),r.addHeader("Content-Type","text/plain"),r.addHeader("Success-Report","yes"),r.addHeader("Failure-Report","yes"),r.body=n;let o=r.toString();console.log(o);let a=[];for(var t=0;t<o.length;t++)a.push(o.charCodeAt(t).toString(16));console.log(a),this._connection.send(r.toString()),r.direction="outgoing",this.emit("newMessage",r),this._msgHistory.push(r),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(n){let r=n.ident,o=n.getHeader("Message-ID"),a=new Un("");a.method="200 OK",a.addHeader("To-Path",`${this.my_addr[1]}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",o),a.ident=r;let t=a.toString();console.log(t);let s=[];for(var p=0;p<t.length;p++)s.push(t.charCodeAt(p).toString(16));console.log(s),this._connection.send(a.toString())}_sendReport(n){let r=n.ident,o=n.getHeader("Message-ID"),a=new Un("");a.method="REPORT",a.addHeader("To-Path",`${n.getHeader("From-Path")}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",o),a.addHeader("Byte-Range","1-25/25"),a.addHeader("Status","000 200 OK"),a.ident=r;let t=a.toString();console.log(t);let s=[];for(var p=0;p<t.length;p++)s.push(t.charCodeAt(p).toString(16));console.log(s),this._connection.send(a.toString())}parseAuth(n){const r={},o=n.replace("Digest","").split(",");for(const a of o){const t=a.trim().split("=");r[t[0]]=t[1].match('^"(.+)"$')[1]}return r}init_incoming(n,r){let o;const a=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0;if(n.body&&a!=="application/sdp"){n.reply(415);return}if(this._status=Ce.STATUS_INVITE_RECEIVED,this._from_tag=n.from_tag,this._id=n.call_id+this._from_tag,this._request=n,this._contact=this._ua.contact.toString(),n.hasHeader("expires")&&(o=n.getHeader("expires")*1e3),n.to_tag=Me.newTag(),!this._createDialog(n,"UAS",!0)){n.reply(500,"Missing Contact header field");return}n.body?this._late_sdp=!1:this._late_sdp=!0,this._status=Ce.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{n.reply(408),console.log("failed 6"),this._failed("local",null,q.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),o&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Ce.STATUS_WAITING_FOR_ANSWER&&(n.reply(487),console.log("failed 7"),this._failed("system",null,q.causes.EXPIRES))},o)),this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from,r&&r(this),n.parseSDP(!0),this.target_addr=n.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",n),this._status!==Ce.STATUS_TERMINATED&&(n.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(n,r,o){this.emit("_failed",{originator:n,message:r||null,cause:o}),this._close(),this.emit("failed",{originator:n,message:r||null,cause:o})}_close(){if(console.log("CLOSE SESSION"),this._status!==Ce.STATUS_TERMINATED){if(this._status=Ce.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(n){console.log("close() | error closing the RTCPeerConnection: %o",n)}for(const n in this._timers)Object.prototype.hasOwnProperty.call(this._timers,n)&&clearTimeout(this._timers[n]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const n in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,n)&&(this._earlyDialogs[n].terminate(),delete this._earlyDialogs[n]);for(const n in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,n)&&delete this._referSubscribers[n];this._ua.destroyMSRPSession(this)}}_createDialog(n,r,o){const a=r==="UAS"?n.to_tag:n.from_tag,t=r==="UAS"?n.from_tag:n.to_tag,s=n.call_id+a+t;let p=this._earlyDialogs[s];if(o)return p?!0:(p=new Xl(this,n,r,Xl.C.STATUS_EARLY),p.error?(console.log("failed 8"),this._failed("remote",n,q.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[s]=p,!0));{if(this._from_tag=n.from_tag,this._to_tag=n.to_tag,p)return p.update(n,r),this._dialog=p,delete this._earlyDialogs[s],!0;const _=new Xl(this,n,r);return _.error?(console.log("failed 9"),this._failed("remote",n,q.causes.INTERNAL_ERROR),!1):(this._dialog=_,!0)}}_newMSRPSession(n,r){this._ua.newMSRPSession(this,{originator:n,session:this,request:r})}_progress(n,r){this.emit("progress",{originator:n,response:r||null})}isEnded(){switch(this._status){case Ce.STATUS_CANCELED:case Ce.STATUS_TERMINATED:return!0;default:return!1}}_accepted(n,r){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:n,response:r||null})}_confirmed(n,r){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:n,ack:r||null})}_ended(n,r,o){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:n,message:r||null,cause:o})}_handleSessionTimersInIncomingResponse(n){if(!this._sessionTimers.enabled)return;let r;n.session_expires&&n.session_expires>=q.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=n.session_expires,r=n.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,r="uac"),this._sessionTimers.refresher=r==="uac",this._runSessionTimer()}receiveRequest(n){if(console.log("receiveRequest()"),n.method===q.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",n,q.causes.CANCELED));else switch(n.method){case q.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(!n.body){this.terminate({cause:q.causes.MISSING_SDP,status_code:400});break}const r={originator:"remote",type:"answer",sdp:n.body};console.log('emit "sdp"'),this.emit("sdp",r);const o=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>{this._is_confirmed||this._confirmed("remote",n)}).catch(a=>{this.terminate({cause:q.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})}else this._is_confirmed||this._confirmed("remote",n);break;case q.BYE:this._status===Ce.STATUS_CONFIRMED||this._status===Ce.STATUS_WAITING_FOR_ACK?(n.reply(200),this._ended("remote",n,q.causes.BYE)):this._status===Ce.STATUS_INVITE_RECEIVED||this._status===Ce.STATUS_WAITING_FOR_ANSWER?(n.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",n,q.causes.BYE)):n.reply(403,"Wrong Status");break;case q.INVITE:this._status===Ce.STATUS_CONFIRMED?n.hasHeader("replaces")?this._receiveReplaces(n):this._receiveReinvite(n):n.reply(403,"Wrong Status");break;case q.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?(n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new Va(this).init_incoming(n):n.reply(415):n.reply(403,"Wrong Status");break;case q.UPDATE:this._status===Ce.STATUS_CONFIRMED?this._receiveUpdate(n):n.reply(403,"Wrong Status");break;case q.REFER:this._status===Ce.STATUS_CONFIRMED?this._receiveRefer(n):n.reply(403,"Wrong Status");break;case q.NOTIFY:this._status===Ce.STATUS_CONFIRMED?this._receiveNotify(n):n.reply(403,"Wrong Status");break;default:n.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:q.causes.CONNECTION_ERROR,cause:q.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:q.causes.REQUEST_TIMEOUT,cause:q.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:q.causes.DIALOG_ERROR,cause:q.causes.DIALOG_ERROR})}}const Nt=console,Zf={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},zg=Wg;class Jg extends zg{constructor(n){super(n),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[]}call(n,r){return super.call(n,r)}joinVideoCall(n,r){Nt.debug("call()");const o=new oo(this);return o.connect(n,r),o}newMSRPSession(n,r){n.on("msgHistoryUpdate",o=>{console.log(o)}),this._msrp_sessions[n.id]=n,this.emit("newMSRPSession",r)}newJanusSession(n,r){this._janus_sessions[n.id]=n,this.emit("newJanusSession",r)}destroyMSRPSession(n){delete this._msrp_sessions[n.id]}destroyJanusSession(n){delete this._janus_sessions[n.id]}receiveRequest(n){const r=n.method;if(console.log("-----------"),n.ruri.user!==this._configuration.uri.user&&n.ruri.user!==this._contact.uri.user){Nt.debug("Request-URI does not point to us"),n.method!==De.ACK&&n.reply_sl(404);return}if(n.ruri.scheme===De.SIPS){n.reply_sl(416);return}if(Lt.checkTransaction(this,n))return;if(r===De.INVITE?new Lt.InviteServerTransaction(this,this._transport,n):r!==De.ACK&&r!==De.CANCEL&&new Lt.NonInviteServerTransaction(this,this._transport,n),r===De.OPTIONS){if(this.listeners("newOptions").length===0){n.reply(200);return}new lf.Options(this).init_incoming(n)}else if(r===De.MESSAGE){if(this.listeners("newMessage").length===0){n.reply(405);return}new lf.Message(this).init_incoming(n)}else if(r===De.INVITE&&!n.to_tag&&this.listeners("newRTCSession").length===0){n.reply(405);return}let o,a;if(n.to_tag)o=this._findDialog(n.call_id,n.from_tag,n.to_tag),o?o.receiveRequest(n):r===De.NOTIFY?(a=this._findSession(n),a?a.receiveRequest(n):(Nt.debug("received NOTIFY request for a non existent subscription"),n.reply(481,"Subscription does not exist"))):r!==De.ACK&&n.reply(481);else switch(r){case De.INVITE:if(window.RTCPeerConnection)if(n.hasHeader("replaces")){const t=n.replaces;o=this._findDialog(t.call_id,t.from_tag,t.to_tag),o?(a=o.owner,a.isEnded()?n.reply(603):a.receiveRequest(n)):n.reply(481)}else n.body.search(/MSRP/ig)>-1?(a=new lu(this),a.init_incoming(n)):n.body.search(/JANUS/ig)>-1||(a=new sg(this),a.init_incoming(n));else Nt.warn("INVITE received but WebRTC is not supported"),n.reply(488);break;case De.BYE:n.reply(481);break;case De.CANCEL:a=this._findSession(n),a?a.receiveRequest(n):Nt.debug("received CANCEL request for a non existent session");break;case De.ACK:break;case De.NOTIFY:this.emit("sipEvent",{event:n.event,request:n}),n.reply(200);break;default:n.reply(405);break}}startMSRP(n,r){Nt.debug("startMSRP()",r);const o=new lu(this);return o.connect(n),o}startJanus(n,r){Nt.debug("startJanus()",r);const o=new lu(this);return o.connect(n),o}terminateMSRPSessions(n){Nt.debug("terminateSessions()");for(const r in this._msrp_sessions)this._msrp_sessions[r].isEnded()||this._msrp_sessions[r].terminate(n)}terminateJanusSessions(n){Nt.debug("terminateSessions()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||this._janus_sessions[r].terminate(n)}stop(){if(Nt.debug("stop()"),this._dynConfiguration={},this._status===Zf.STATUS_USER_CLOSED){Nt.debug("UA already closed");return}this._registrator.close();const n=Object.keys(this._sessions).length;for(const o in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,o)){Nt.debug(`closing session ${o}`);try{this._sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,o)){Nt.debug(`closing session ${o}`);try{this._msrp_sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,o)){Nt.debug(`closing session ${o}`);try{this._janus_sessions[o].terminate()}catch(a){console.error(a)}}for(const o in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,o))try{this._applicants[o].close()}catch(a){console.error(a)}this._status=Zf.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&n===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}const Xg=["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"],Qg=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function e_(c){const n={};return Xg.forEach(r=>{c[r]!==void 0&&(n[r]=c[r])}),n.localHold=c._localHold,n}function t_(c){const n={};return Qg.forEach(r=>{c[r]!==void 0&&(n[r]=c[r])}),n}function s_(c,n){const r=new AudioContext,o=r.createMediaStreamSource(c),a=r.createMediaStreamDestination(),t=r.createGain();return o.connect(t),t.connect(a),t.gain.value=n,a.stream}function Zg(c,n,r,o){const a=document.createElement("audio");a.id=n._id,a.className="audioTag",a.srcObject=c,a.setSinkId(r),a.volume=o,a.play(),n.audioTag=a}function eT(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}const tT=lt,sT=Xt(),It=new tT("WebSocketInterface");var nT=class{constructor(n){It.debug('new() [url:"%s"]',n),this._url=n,this._sip_uri=null,this._via_transport=null,this._ws=null;const r=sT.parse(n,"absoluteURI");if(r===-1)throw It.warn(`invalid WebSocket URI: ${n}`),new TypeError(`Invalid argument: ${n}`);if(r.scheme!=="wss"&&r.scheme!=="ws")throw It.warn(`invalid WebSocket URI scheme: ${r.scheme}`),new TypeError(`Invalid argument: ${n}`);this._sip_uri=`sip:${r.host}${r.port?`:${r.port}`:""};transport=ws`,this._via_transport=r.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(n){this._via_transport=n.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(It.debug("connect()"),this.isConnected()){It.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){It.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),It.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(n){this._onError(n)}}disconnect(){It.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(n){return It.debug("send()"),this.isConnected()?(this._ws.send(n),!0):(It.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(){It.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:n,code:r,reason:o}){It.debug(`WebSocket ${this._url} closed`),n===!1&&It.debug("WebSocket abrupt disconnection"),this.ondisconnect(!n,r,o)}_onMessage({data:n}){It.debug("received WebSocket message"),this.ondata(n)}_onError(n){It.warn(`WebSocket ${this._url} error: `,n)}};const ou=ol,rT=De,iT=_s,lT=pt(),oT=Qf,aT=us(),uT=ba(),cT=Xt(),fT=nT;An("JsSIP")("version %s",ou.version);var _T={C:rT,Exceptions:iT,Utils:lT,UA:oT,URI:aT,NameAddrHeader:uT,WebSocketInterface:fT,Grammar:cT,debug:An,get name(){return ou.title},get version(){return ou.version}};const hT=it(_T);function au(c){return c<10?`0${c}`:`${c}`}function dT(c){let n=c.hours||0,r=c.minutes||0,o=c.seconds||0;o++,o===60&&(o=0,r++,r===60&&(r=0,n++));const a=`${au(n)}:${au(r)}:${au(o)}`;return{seconds:o,minutes:r,hours:n,formatted:a}}var vt={};vt.forEach=async(c,n,r)=>{const o=[];for(let a=0;a<c.length;a++)if(a in c){const t=Promise.resolve(c[a]).then(s=>n.call(r||globalThis,s,a,c));o.push(t)}await Promise.all(o)},vt.forEachSeries=async(c,n,r)=>{for(let o=0;o<c.length;o++)o in c&&await n.call(r||globalThis,await c[o],o,c)},vt.map=async(c,n,r)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&(o[a]=Promise.resolve(c[a]).then(t=>n.call(r||globalThis,t,a,c)));return Promise.all(o)},vt.mapSeries=async(c,n,r)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&(o[a]=await n.call(r||globalThis,await c[a],a,c));return o},vt.find=(c,n,r)=>new Promise((o,a)=>{if(c.length===0)return o();let t=1;for(let s=0;s<c.length;s++){const p=_=>{_?o(c[s]):t===c.length&&o(),t++};Promise.resolve(c[s]).then(_=>n.call(r||globalThis,_,s,c)).then(p).catch(a)}}),vt.findSeries=async(c,n,r)=>{for(let o=0;o<c.length;o++)if(await n.call(r||globalThis,await c[o],o,c))return c[o]},vt.findIndex=(c,n,r)=>new Promise((o,a)=>{if(c.length===0)return o(-1);let t=1;for(let s=0;s<c.length;s++){const p=_=>{_?o(s):t===c.length&&o(-1),t++};Promise.resolve(c[s]).then(_=>n.call(r||globalThis,_,s,c)).then(p).catch(a)}}),vt.findIndexSeries=async(c,n,r)=>{for(let o=0;o<c.length;o++)if(await n.call(r||globalThis,await c[o],o,c))return o},vt.some=(c,n,r)=>new Promise((o,a)=>{if(c.length===0)return o(!1);let t=1;for(let s=0;s<c.length;s++){if(!(s in c)){t++;continue}const p=_=>{_?o(!0):t===c.length&&o(!1),t++};Promise.resolve(c[s]).then(_=>n.call(r||globalThis,_,s,c)).then(p).catch(a)}}),vt.someSeries=async(c,n,r)=>{for(let o=0;o<c.length;o++)if(o in c&&await n.call(r||globalThis,await c[o],o,c))return!0;return!1},vt.every=(c,n,r)=>new Promise((o,a)=>{if(c.length===0)return o(!0);let t=1;for(let s=0;s<c.length;s++){if(!(s in c)){t++;continue}const p=_=>{_?t===c.length&&o(!0):o(!1),t++};Promise.resolve(c[s]).then(_=>n.call(r||globalThis,_,s,c)).then(p).catch(a)}}),vt.everySeries=async(c,n,r)=>{for(let o=0;o<c.length;o++)if(o in c&&!await n.call(r||globalThis,await c[o],o,c))return!1;return!0},vt.filter=(c,n,r)=>new Promise(async(o,a)=>{const t=[];for(let p=0;p<c.length;p++)p in c&&(t[p]=Promise.resolve(c[p]).then(_=>n.call(r||globalThis,_,p,c)).catch(a));const s=[];for(let p=0;p<t.length;p++)await t[p]&&s.push(await c[p]);o(s)}),vt.filterSeries=async(c,n,r)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&await n.call(r||globalThis,await c[a],a,c)&&o.push(await c[a]);return o},vt.reduce=async(c,n,r)=>{if(c.length===0&&r===void 0)throw TypeError("Reduce of empty array with no initial value");let o,a;for(r!==void 0?(a=r,o=0):(a=c[0],o=1),o;o<c.length;o++)o in c&&(a=await n(await a,await c[o],o,c));return a};var n_={};(function(c){const n=vt;Object.keys(n).forEach(r=>{const o=r.charAt(0).toUpperCase()+r.slice(1);c[`async${o}`]=async function(...a){return n[r](this,...a)}})})(n_);var r_=Object.assign(vt,{instanceMethods:n_});const Xs=new AudioContext,es={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var pT={exports:{}};(function(c){var n=function(r){var o=Object.prototype,a=o.hasOwnProperty,t=Object.defineProperty||function(ee,Y,G){ee[Y]=G.value},s,p=typeof Symbol=="function"?Symbol:{},_=p.iterator||"@@iterator",d=p.asyncIterator||"@@asyncIterator",g=p.toStringTag||"@@toStringTag";function T(ee,Y,G){return Object.defineProperty(ee,Y,{value:G,enumerable:!0,configurable:!0,writable:!0}),ee[Y]}try{T({},"")}catch{T=function(Y,G,re){return Y[G]=re}}function E(ee,Y,G,re){var ge=Y&&Y.prototype instanceof ae?Y:ae,be=Object.create(ge.prototype),xe=new P(re||[]);return t(be,"_invoke",{value:z(ee,G,xe)}),be}r.wrap=E;function y(ee,Y,G){try{return{type:"normal",arg:ee.call(Y,G)}}catch(re){return{type:"throw",arg:re}}}var A="suspendedStart",R="suspendedYield",I="executing",$="completed",L={};function ae(){}function N(){}function F(){}var Se={};T(Se,_,function(){return this});var ve=Object.getPrototypeOf,M=ve&&ve(ve(se([])));M&&M!==o&&a.call(M,_)&&(Se=M);var D=F.prototype=ae.prototype=Object.create(Se);N.prototype=F,t(D,"constructor",{value:F,configurable:!0}),t(F,"constructor",{value:N,configurable:!0}),N.displayName=T(F,g,"GeneratorFunction");function B(ee){["next","throw","return"].forEach(function(Y){T(ee,Y,function(G){return this._invoke(Y,G)})})}r.isGeneratorFunction=function(ee){var Y=typeof ee=="function"&&ee.constructor;return Y?Y===N||(Y.displayName||Y.name)==="GeneratorFunction":!1},r.mark=function(ee){return Object.setPrototypeOf?Object.setPrototypeOf(ee,F):(ee.__proto__=F,T(ee,g,"GeneratorFunction")),ee.prototype=Object.create(D),ee},r.awrap=function(ee){return{__await:ee}};function j(ee,Y){function G(be,xe,Re,le){var ye=y(ee[be],ee,xe);if(ye.type==="throw")le(ye.arg);else{var rt=ye.arg,ot=rt.value;return ot&&typeof ot=="object"&&a.call(ot,"__await")?Y.resolve(ot.__await).then(function(Ee){G("next",Ee,Re,le)},function(Ee){G("throw",Ee,Re,le)}):Y.resolve(ot).then(function(Ee){rt.value=Ee,Re(rt)},function(Ee){return G("throw",Ee,Re,le)})}}var re;function ge(be,xe){function Re(){return new Y(function(le,ye){G(be,xe,le,ye)})}return re=re?re.then(Re,Re):Re()}t(this,"_invoke",{value:ge})}B(j.prototype),T(j.prototype,d,function(){return this}),r.AsyncIterator=j,r.async=function(ee,Y,G,re,ge){ge===void 0&&(ge=Promise);var be=new j(E(ee,Y,G,re),ge);return r.isGeneratorFunction(Y)?be:be.next().then(function(xe){return xe.done?xe.value:be.next()})};function z(ee,Y,G){var re=A;return function(be,xe){if(re===I)throw new Error("Generator is already running");if(re===$){if(be==="throw")throw xe;return nt()}for(G.method=be,G.arg=xe;;){var Re=G.delegate;if(Re){var le=H(Re,G);if(le){if(le===L)continue;return le}}if(G.method==="next")G.sent=G._sent=G.arg;else if(G.method==="throw"){if(re===A)throw re=$,G.arg;G.dispatchException(G.arg)}else G.method==="return"&&G.abrupt("return",G.arg);re=I;var ye=y(ee,Y,G);if(ye.type==="normal"){if(re=G.done?$:R,ye.arg===L)continue;return{value:ye.arg,done:G.done}}else ye.type==="throw"&&(re=$,G.method="throw",G.arg=ye.arg)}}}function H(ee,Y){var G=Y.method,re=ee.iterator[G];if(re===s)return Y.delegate=null,G==="throw"&&ee.iterator.return&&(Y.method="return",Y.arg=s,H(ee,Y),Y.method==="throw")||G!=="return"&&(Y.method="throw",Y.arg=new TypeError("The iterator does not provide a '"+G+"' method")),L;var ge=y(re,ee.iterator,Y.arg);if(ge.type==="throw")return Y.method="throw",Y.arg=ge.arg,Y.delegate=null,L;var be=ge.arg;if(!be)return Y.method="throw",Y.arg=new TypeError("iterator result is not an object"),Y.delegate=null,L;if(be.done)Y[ee.resultName]=be.value,Y.next=ee.nextLoc,Y.method!=="return"&&(Y.method="next",Y.arg=s);else return be;return Y.delegate=null,L}B(D),T(D,g,"Generator"),T(D,_,function(){return this}),T(D,"toString",function(){return"[object Generator]"});function Z(ee){var Y={tryLoc:ee[0]};1 in ee&&(Y.catchLoc=ee[1]),2 in ee&&(Y.finallyLoc=ee[2],Y.afterLoc=ee[3]),this.tryEntries.push(Y)}function U(ee){var Y=ee.completion||{};Y.type="normal",delete Y.arg,ee.completion=Y}function P(ee){this.tryEntries=[{tryLoc:"root"}],ee.forEach(Z,this),this.reset(!0)}r.keys=function(ee){var Y=Object(ee),G=[];for(var re in Y)G.push(re);return G.reverse(),function ge(){for(;G.length;){var be=G.pop();if(be in Y)return ge.value=be,ge.done=!1,ge}return ge.done=!0,ge}};function se(ee){if(ee){var Y=ee[_];if(Y)return Y.call(ee);if(typeof ee.next=="function")return ee;if(!isNaN(ee.length)){var G=-1,re=function ge(){for(;++G<ee.length;)if(a.call(ee,G))return ge.value=ee[G],ge.done=!1,ge;return ge.value=s,ge.done=!0,ge};return re.next=re}}return{next:nt}}r.values=se;function nt(){return{value:s,done:!0}}return P.prototype={constructor:P,reset:function(ee){if(this.prev=0,this.next=0,this.sent=this._sent=s,this.done=!1,this.delegate=null,this.method="next",this.arg=s,this.tryEntries.forEach(U),!ee)for(var Y in this)Y.charAt(0)==="t"&&a.call(this,Y)&&!isNaN(+Y.slice(1))&&(this[Y]=s)},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=s),!!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=a.call(ge,"catchLoc"),Re=a.call(ge,"finallyLoc");if(xe&&Re){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(Re){if(this.prev<ge.finallyLoc)return G(ge.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(ee,Y){for(var G=this.tryEntries.length-1;G>=0;--G){var re=this.tryEntries[G];if(re.tryLoc<=this.prev&&a.call(re,"finallyLoc")&&this.prev<re.finallyLoc){var ge=re;break}}ge&&(ee==="break"||ee==="continue")&&ge.tryLoc<=Y&&Y<=ge.finallyLoc&&(ge=null);var be=ge?ge.completion:{};return be.type=ee,be.arg=Y,ge?(this.method="next",this.next=ge.finallyLoc,L):this.complete(be)},complete:function(ee,Y){if(ee.type==="throw")throw ee.arg;return ee.type==="break"||ee.type==="continue"?this.next=ee.arg:ee.type==="return"?(this.rval=this.arg=ee.arg,this.method="return",this.next="end"):ee.type==="normal"&&Y&&(this.next=Y),L},finish:function(ee){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var G=this.tryEntries[Y];if(G.finallyLoc===ee)return this.complete(G.completion,G.afterLoc),U(G),L}},catch:function(ee){for(var Y=this.tryEntries.length-1;Y>=0;--Y){var G=this.tryEntries[Y];if(G.tryLoc===ee){var re=G.completion;if(re.type==="throw"){var ge=re.arg;U(G)}return ge}}throw new Error("illegal catch attempt")},delegateYield:function(ee,Y,G){return this.delegate={iterator:se(ee),resultName:Y,nextLoc:G},this.method==="next"&&(this.arg=s),L}},r}(c.exports);try{regeneratorRuntime=n}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}})(pT);var i_={exports:{}};(function(c){(function(n,r){c.exports?c.exports=r():n.log=r()})(E_,function(){var n=function(){},r="undefined",o=typeof window!==r&&typeof window.navigator!==r&&/Trident\/|MSIE /.test(window.navigator.userAgent),a=["trace","debug","info","warn","error"];function t(R,I){var $=R[I];if(typeof $.bind=="function")return $.bind(R);try{return Function.prototype.bind.call($,R)}catch{return function(){return Function.prototype.apply.apply($,[R,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function p(R){return R==="debug"&&(R="log"),typeof console===r?!1:R==="trace"&&o?s:console[R]!==void 0?t(console,R):console.log!==void 0?t(console,"log"):n}function _(R,I){for(var $=0;$<a.length;$++){var L=a[$];this[L]=$<R?n:this.methodFactory(L,R,I)}this.log=this.debug}function d(R,I,$){return function(){typeof console!==r&&(_.call(this,I,$),this[R].apply(this,arguments))}}function g(R,I,$){return p(R)||d.apply(this,arguments)}function T(R,I,$){var L=this,ae;I=I??"WARN";var N="loglevel";typeof R=="string"?N+=":"+R:typeof R=="symbol"&&(N=void 0);function F(D){var B=(a[D]||"silent").toUpperCase();if(!(typeof window===r||!N)){try{window.localStorage[N]=B;return}catch{}try{window.document.cookie=encodeURIComponent(N)+"="+B+";"}catch{}}}function Se(){var D;if(!(typeof window===r||!N)){try{D=window.localStorage[N]}catch{}if(typeof D===r)try{var B=window.document.cookie,j=B.indexOf(encodeURIComponent(N)+"=");j!==-1&&(D=/^([^;]+)/.exec(B.slice(j))[1])}catch{}return L.levels[D]===void 0&&(D=void 0),D}}function ve(){if(!(typeof window===r||!N)){try{window.localStorage.removeItem(N);return}catch{}try{window.document.cookie=encodeURIComponent(N)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}L.name=R,L.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},L.methodFactory=$||g,L.getLevel=function(){return ae},L.setLevel=function(D,B){if(typeof D=="string"&&L.levels[D.toUpperCase()]!==void 0&&(D=L.levels[D.toUpperCase()]),typeof D=="number"&&D>=0&&D<=L.levels.SILENT){if(ae=D,B!==!1&&F(D),_.call(L,D,R),typeof console===r&&D<L.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+D},L.setDefaultLevel=function(D){I=D,Se()||L.setLevel(D,!1)},L.resetLevel=function(){L.setLevel(I,!1),ve()},L.enableAll=function(D){L.setLevel(L.levels.TRACE,D)},L.disableAll=function(D){L.setLevel(L.levels.SILENT,D)};var M=Se();M==null&&(M=I),L.setLevel(M,!1)}var E=new T,y={};E.getLogger=function(I){if(typeof I!="symbol"&&typeof I!="string"||I==="")throw new TypeError("You must supply a name when creating a logger.");var $=y[I];return $||($=y[I]=new T(I,E.getLevel(),E.methodFactory)),$};var A=typeof window!==r?window.log:void 0;return E.noConflict=function(){return typeof window!==r&&window.log===E&&(window.log=A),E},E.getLoggers=function(){return y},E.default=E,E})})(i_);var At=i_.exports;const hs=()=>`${new Date().toISOString()} | metrics`,ds=(c,n,r)=>`${c} | ${n} | ${r}`;At.setDefaultLevel(At.levels.TRACE);const mT=c=>{At.info(ds(hs(),"log ",`set log level to ${c?"verbose":"info"}`)),At.setLevel(c?At.levels.TRACE:At.levels.INFO)},gT=c=>{const n=[...Object.keys(At.levels)];n.includes(c)?(At.info(ds(hs(),"log ",`update log level to ${c.toLowerCase()}`)),At.setLevel(c)):At.warn(ds(hs(),"log ","Incorrect log level please choose one of "),n)},Pe=(c,n,r)=>{r?At.debug(ds(hs(),c,n),r):At.debug(ds(hs(),c,n))},uu=(c,n)=>{At.info(ds(hs(),c,n))},Qs=(c,n)=>{At.info(ds(hs(),c,n))},ao=(c,n)=>{At.warn(ds(hs(),c,n))},Pn=(c,n)=>{At.error(ds(hs(),c,n))};function TT(c){return Math.floor(Math.random()*c).toString()}function l_(c,n){let r=n;return c.forEach(o=>{r=r.replace(o,"")}),r}function vT(c,n){let r="";for(let o=0;o<n;o+=1)r+=c[TT(c.length)];return r}function ET({length:c=20,useLetters:n=!0,useNumbers:r=!0,includeSymbols:o=[],excludeSymbols:a=[]}={}){let t="abcdefghijklmnopqrstuvwxyz",s="0123456789",p=[],_=[],d=[];return n&&(a.length&&(t=l_(a,t)),_=t.split("")),r&&(a.length&&(s=l_(a,s)),d=s.split("")),p=[..._,...d,...o],vT(p,c)}var ST=ET;const Wr=it(ST),yT=()=>"WebRTCMetrics",AT=()=>"5.0.3",Le={INBOUND:"inbound",OUTBOUND:"outbound"},ps={IDLE:"idle",RUNNING:"running",MUTED:"muted"},Kr={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},CT=()=>({...{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:[]}}),o_={level_in:0,codec_id_in:"",codec_in:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,mos_in:0,mos_emodel_in:0,ssrc:"",direction:Le.INBOUND},a_={level_out:0,codec_id_out:"",codec_out:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,timestamp_out:null,mos_out:0,mos_emodel_out:0,ssrc:"",direction:Le.OUTBOUND},u_={codec_id_in:"",size_in:{width:null,height:null,framerate:null},codec_in:{mime_type:null,clock_rate:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,decoder_in:null,delta_ms_decode_frame_in:0,total_frames_decoded_in:0,total_time_decoded_in:0,delta_nack_sent_in:0,delta_pli_sent_in:0,total_nack_sent_in:0,total_pli_sent_in:0,ssrc:"",direction:Le.INBOUND},c_={codec_id_out:"",size_out:{width:null,height:null,framerate:null},codec_out:{mime_type:null,clock_rate:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,encoder_out:null,delta_ms_encode_frame_out:0,total_time_encoded_out:0,total_frames_encoded_out:0,delta_nack_received_out:0,delta_pli_received_out:0,total_nack_received_out:0,total_pli_received_out:0,limitation_out:{reason:null,durations:null,resolutionChanges:0},timestamp_out:null,ssrc:"",direction:Le.OUTBOUND},RT=c=>{const n={pname:"",call_id:"",user_id:"",timestamp:null,count:0,audio:{},video:{},network:{infrastructure:3,local_candidate_id:"",local_candidate_type:"",local_candidate_protocol:"",local_candidate_relay_protocol:"",remote_candidate_id:"",remote_candidate_type:"",remote_candidate_protocol:""},data:{total_KBytes_in:0,total_KBytes_out:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,delta_kbs_bandwidth_in:0,delta_kbs_bandwidth_out:0,delta_rtt_connectivity_ms:null,total_rtt_connectivity_ms:0,total_rtt_connectivity_measure:0},experimental:{time_to_measure_ms:0}};if(c){const r={...c,audio:{},video:{},data:{...c.data},network:{...c.network},experimental:{...c.experimental}};return Object.keys(c.audio).forEach(o=>{r.audio[o]={...c.audio[o]}}),Object.keys(c.video).forEach(o=>{r.video[o]={...c.video[o]}}),r}return{...n,audio:{},video:{},data:{...n.data},network:{...n.network},experimental:{...n.experimental}}},IT={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${Wr()}`,cid:`c-${Wr()}`,uid:`u-${Wr()}`,record:!1,ticket:!0},Wt={CANDIDATE_PAIR:"candidate-pair",CODEC:"codec",INBOUND_RTP:"inbound-rtp",LOCAL_CANDIDATE:"local-candidate",MEDIA_SOURCE:"media-source",OUTBOUND_RTP:"outbound-rtp",REMOTE_CANDIDATE:"remote-candidate",REMOTE_INBOUND_RTP:"remote-inbound-rtp",TRACK:"track"},V={AUDIO_LEVEL:"audioLevel",AVAILABLE_OUTGOING_BITRATE:"availableOutgoingBitrate",AVAILABLE_INCOMING_BITRATE:"availableIncomingBitrate",BYTES_RECEIVED:"bytesReceived",BYTES_SENT:"bytesSent",CANDIDATE_TYPE:"candidateType",CHANNELS:"channels",CLOCK_RATE:"clockRate",CODEC_ID:"codecId",CURRENT_ROUND_TRIP_TIME:"currentRoundTripTime",ROUND_TRIP_TIME:"roundTripTime",FRACTION_LOST:"fractionLost",FRAME_HEIGHT:"frameHeight",FRAME_WIDTH:"frameWidth",QUALITY_LIMITATION_REASON:"qualityLimitationReason",QUALITY_LIMITATION_DURATIONS:"qualityLimitationDurations",QUALITY_LIMITATION_RESOLUTION_CHANGES:"qualityLimitationResolutionChanges",ID:"id",JITTER:"jitter",KIND:"kind",MEDIA_TYPE:"mediaType",MIME_TYPE:"mimeType",LOCAL_CANDIDATE_ID:"localCandidateId",NETWORK_TYPE:"networkType",RELAY_PROTOCOL:"relayProtocol",NOMINATED:"nominated",PACKETS_LOST:"packetsLost",PACKETS_RECEIVED:"packetsReceived",PACKETS_SENT:"packetsSent",PROTOCOL:"protocol",PORT:"port",REMOTE_CANDIDATE_ID:"remoteCandidateId",REMOTE_SOURCE:"remoteSource",RESPONSES_RECEIVED:"responsesReceived",SDP_FMTP_LINE:"sdpFmtpLine",SSRC:"ssrc",SELECTED:"selected",STATE:"state",TIMESTAMP:"timestamp",TOTAL_ROUND_TRIP_TIME:"totalRoundTripTime",TOTAL_ROUND_TRIP_TIME_MEASUREMENTS:"roundTripTimeMeasurements",TYPE:"type",DECODER_IMPLEMENTATION:"decoderImplementation",ENCODER_IMPLEMENTATION:"encoderImplementation",FRAMES_DECODED:"framesDecoded",FRAMES_ENCODED:"framesEncoded",FRAMES_PER_SECOND:"framesPerSecond",TOTAL_DECODE_TIME:"totalDecodeTime",TOTAL_ENCODE_TIME:"totalEncodeTime",PLI:"pliCount",NACK:"nackCount"},x={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},Yr={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},cu={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ne={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},fu="config ",bT=(c,n={},r)=>{const o={...r,...n};return n.pname||ao(fu,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${r.pname}'`),n.cid||ao(fu,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${r.cid}'`),n.uid||ao(fu,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${r.uid}'`),o.pc=c,o},wT=(c={})=>{const n={...IT,...c};return n.name=yT(),n.version=AT(),n},zr=(c,n,r,o=!1,a)=>{let t=c.map(s=>{if(!r)return s[n];if(!a)return s[n][r];const p=s[n][a];return p?p[r]:null});return t=t.filter(s=>o?Number.isFinite(s)&&s>0:Number.isFinite(s)),t.length===0?[]:t},bs=c=>c.reduce((n,r)=>n+r,0)/c.length,OT=()=>`probe-${Wr()}`,DT=()=>`coltr-${Wr()}`,f_=c=>new Promise(n=>setTimeout(n,c)),_u=(c,n,r)=>{n?c.call(n,r):c(r)},Ge=(c,n,r,o)=>{const a=zr(c,n,r,!0,o);if(a.length===0)return null;const t=a.reduce((d,g)=>d+g,0)/a.length;return t===0?null:a.map(d=>Math.abs(t-d)).reduce((d,g)=>d+g,0)/a.length*100/t},Je=(c,n,r,o=!1,a)=>{const t=zr(c,n,r,o,a);return t.length===0?null:t.reduce((s,p)=>s+p,0)/t.length},Zs=(c,n,r)=>zr(c,n,r).reduce((a,t)=>a+t,0),We=(c,n,r,o)=>{const a=zr(c,n,r,!0,o);return a.length===0?null:Math.min(...a)},Ke=(c,n,r,o)=>{const a=zr(c,n,r,!1,o);return a.length===0?null:Math.max(...a)},Et=(c,n,r,o)=>{const a=c.slice().pop();if(!a)return null;if(!r)return a[n];if(!o)return a[n][r];const t=a[n][o];return t?t[r]:null},NT=c=>c.slice().pop(),ft=(c,n,r)=>{if(!n)return null;const o={};let a=n[x.AUDIO][c];a||(a=r===Le.INBOUND?{...o_}:{...a_}),o[x.AUDIO]=a;let t=n[x.VIDEO][c];return t||(t=r===Le.INBOUND?{...u_}:{...c_}),o[x.VIDEO]=t,o},Jr="exporter ",UT="2.0",__=(c,n,r)=>{if(!c||c.length===0)return 0;const o=c[c.length-1];if(!o)return 0;const a=o[n][r];if(a){const t=a.total_rtt_ms_out,s=a.total_rtt_measure_out;return!s||!t?Je(c,n,"delta_rtt_ms_out",!1,r):Number(t/s)}return null},PT=(c,n)=>{if(!c||c.length===0)return 0;const r=c[c.length-1];if(!r)return 0;const o=r[n].total_rtt_connectivity_ms,a=r[n].total_rtt_connectivity_measure;return!a||!o?Je(c,n,"delta_rtt_connectivity_ms"):Number(o/a)},xT=c=>Et(c,"network","local_candidate_type")!=="relay"?`direct/${Et(c,"network","local_candidate_protocol")}`:`turn/${Et(c,"network","local_candidate_relay_protocol")}`,MT=c=>{const n=Et(c,"network","remote_candidate_type"),r=Et(c,"network","remote_candidate_protocol");return n!=="relay"?`direct/${r}`:`turn/${r}`};class kT{constructor(n){this._start=null,this._end=null,this._cfg=n,this._referenceReport=null,this._reports=[],this._events=[]}start(){uu(Jr,"start() - start exporter...");const n=new Date;return this._start=n.toJSON(),n}stop(){uu(Jr,"stop() - stop exporter...");const n=new Date;return this._end=n.toJSON(),n}saveReferenceReport(n){this._referenceReport=n}getReferenceReport(){return this._referenceReport}addReport(n){this._cfg.ticket&&(Pe(Jr,`addReport() - add report to exporter at ${n.timestamp}`),this._reports.push(n))}addCustomEvent(n){this._events.push(n)}reset(){uu(Jr,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Pe(Jr,"ticket() - generate ticket");const n=Et(this._reports,"audio","total_packets_lost_in"),r=Et(this._reports,"audio","total_packets_in"),o=Et(this._reports,"video","total_packets_lost_in"),a=Et(this._reports,"video","total_packets_in"),t={},s=NT(this._reports);return s&&(Object.keys(s[x.AUDIO]).forEach(p=>{const _=s[x.AUDIO][p];if(t[_.ssrc]={type:x.AUDIO,direction:_.direction},_.direction===Le.INBOUND){const d={avg:Je(this._reports,x.AUDIO,"delta_jitter_ms_in",!1,p),min:We(this._reports,x.AUDIO,"delta_jitter_ms_in",p),max:Ke(this._reports,x.AUDIO,"delta_jitter_ms_in",p),volatility:Ge(this._reports,x.AUDIO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Je(this._reports,x.AUDIO,"delta_kbs_in",!1,p),min:We(this._reports,x.AUDIO,"delta_kbs_in",p),max:Ke(this._reports,x.AUDIO,"delta_kbs_in",p),volatility:Ge(this._reports,x.AUDIO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Je(this._reports,x.AUDIO,"delta_KBytes_in",!1,p),min:We(this._reports,x.AUDIO,"delta_KBytes_in",p),max:Ke(this._reports,x.AUDIO,"delta_KBytes_in",p),volatility:Ge(this._reports,x.AUDIO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={emodel:{avg:Je(this._reports,x.AUDIO,"mos_emodel_in",!1,p),min:We(this._reports,x.AUDIO,"mos_emodel_in",p),max:Ke(this._reports,x.AUDIO,"mos_emodel_in",p),volatility:Ge(this._reports,x.AUDIO,"mos_emodel_in",p)},effective:{avg:Je(this._reports,x.AUDIO,"mos_in",!1,p),min:We(this._reports,x.AUDIO,"mos_in",p),max:Ke(this._reports,x.AUDIO,"mos_in",p),volatility:Ge(this._reports,x.AUDIO,"mos_in",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},y=Et(this._reports,x.AUDIO,"total_packets_lost_in",p),A=Et(this._reports,x.AUDIO,"total_packets_in",p),R={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].mos=E,t[p].traffic=T,t[p].bitrate=g,t[p].loss=R}else{const d={avg:Je(this._reports,x.AUDIO,"delta_jitter_ms_out",!1,p),min:We(this._reports,x.AUDIO,"delta_jitter_ms_out",p),max:Ke(this._reports,x.AUDIO,"delta_jitter_ms_out",p),volatility:Ge(this._reports,x.AUDIO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Je(this._reports,x.AUDIO,"delta_kbs_out",!1,p),min:We(this._reports,x.AUDIO,"delta_kbs_out",p),max:Ke(this._reports,x.AUDIO,"delta_kbs_out",p),volatility:Ge(this._reports,x.AUDIO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Je(this._reports,x.AUDIO,"delta_KBytes_out",!1,p),min:We(this._reports,x.AUDIO,"delta_KBytes_out",p),max:Ke(this._reports,x.AUDIO,"delta_KBytes_out",p),volatility:Ge(this._reports,x.AUDIO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},E={avg:__(this._reports,x.AUDIO,p),min:We(this._reports,x.AUDIO,"delta_rtt_ms_out",p),max:Ke(this._reports,x.AUDIO,"delta_rtt_ms_out",p),volatility:Ge(this._reports,x.AUDIO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=Et(this._reports,x.AUDIO,"total_packets_lost_out",p),A=Et(this._reports,x.AUDIO,"total_packets_out",p),R={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},I={emodel:{avg:Je(this._reports,x.AUDIO,"mos_emodel_out",!1,p),min:We(this._reports,x.AUDIO,"mos_emodel_out",p),max:Ke(this._reports,x.AUDIO,"mos_emodel_out",p),volatility:Ge(this._reports,x.AUDIO,"mos_emodel_out",p)},effective:{avg:Je(this._reports,x.AUDIO,"mos_out",!1,p),min:We(this._reports,x.AUDIO,"mos_out",p),max:Ke(this._reports,x.AUDIO,"mos_out",p),volatility:Ge(this._reports,x.AUDIO,"mos_out",p)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};t[p].jitter=d,t[p].rtt=E,t[p].traffic=T,t[p].bitrate=g,t[p].loss=R,t[p].mos=I}}),Object.keys(s[x.VIDEO]).forEach(p=>{const _=s[x.VIDEO][p];if(t[p]={type:x.VIDEO,direction:_.direction},_.direction===Le.INBOUND){const d={avg:Je(this._reports,x.VIDEO,"delta_jitter_ms_in",!1,p),min:We(this._reports,x.VIDEO,"delta_jitter_ms_in",p),max:Ke(this._reports,x.VIDEO,"delta_jitter_ms_in",p),volatility:Ge(this._reports,x.VIDEO,"delta_jitter_ms_in",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Je(this._reports,x.VIDEO,"delta_kbs_in",!1,p),min:We(this._reports,x.VIDEO,"delta_kbs_in",p),max:Ke(this._reports,x.VIDEO,"delta_kbs_in",p),volatility:Ge(this._reports,x.VIDEO,"delta_kbs_in",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Je(this._reports,x.VIDEO,"delta_KBytes_in",!1,p),min:We(this._reports,x.VIDEO,"delta_KBytes_in",p),max:Ke(this._reports,x.VIDEO,"delta_KBytes_in",p),volatility:Ge(this._reports,x.VIDEO,"delta_KBytes_in",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E=Et(this._reports,x.VIDEO,"total_packets_lost_in",p),y=Et(this._reports,x.VIDEO,"total_packets_in",p),A={lost:E,avg:Math.round((E/(E+y)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].traffic=T,t[p].bitrate=g,t[p].loss=A}else{const d={avg:Je(this._reports,x.VIDEO,"delta_jitter_ms_out",!1,p),min:We(this._reports,x.VIDEO,"delta_jitter_ms_out",p),max:Ke(this._reports,x.VIDEO,"delta_jitter_ms_out",p),volatility:Ge(this._reports,x.VIDEO,"delta_jitter_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Je(this._reports,x.VIDEO,"delta_kbs_out",!1,p),min:We(this._reports,x.VIDEO,"delta_kbs_out",p),max:Ke(this._reports,x.VIDEO,"delta_kbs_out",p),volatility:Ge(this._reports,x.VIDEO,"delta_kbs_out",p),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Je(this._reports,x.VIDEO,"delta_KBytes_out",!1,p),min:We(this._reports,x.VIDEO,"delta_KBytes_out",p),max:Ke(this._reports,x.VIDEO,"delta_KBytes_out",p),volatility:Ge(this._reports,x.VIDEO,"delta_KBytes_out",p),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},E={avg:__(this._reports,x.VIDEO,p),min:We(this._reports,x.VIDEO,"delta_rtt_ms_out",p),max:Ke(this._reports,x.VIDEO,"delta_rtt_ms_out",p),volatility:Ge(this._reports,x.VIDEO,"delta_rtt_ms_out",p),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=Et(this._reports,x.VIDEO,"total_packets_lost_out",p),A=Et(this._reports,x.VIDEO,"total_packets_out",p),R={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};t[p].jitter=d,t[p].rtt=E,t[p].traffic=T,t[p].bitrate=g,t[p].loss=R}})),{version:UT,configuration:{frequency:this._cfg.refreshEvery},started:this._start,ended:this._end,ua:{agent:navigator.userAgent,pname:this._cfg.pname,user_id:this._cfg.uid},call:{call_id:this._cfg.cid,events:this._events},details:{count:this._reports.length,reports:this._cfg.record?this._reports:[],reference:this._referenceReport||null},ssrc:t,data:{rtt:{avg:PT(this._reports,"data"),min:We(this._reports,"data","delta_rtt_connectivity_ms"),max:Ke(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Ge(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((n/(n+r)*100||0)*100)/100}},video:{in:{avg:Math.round((o/(o+a)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:Je(this._reports,"data","delta_kbs_in"),min:We(this._reports,"data","delta_kbs_in"),max:Ke(this._reports,"data","delta_kbs_in"),volatility:Ge(this._reports,"data","delta_kbs_in")},out:{avg:Je(this._reports,"data","delta_kbs_out"),min:We(this._reports,"data","delta_kbs_out"),max:Ke(this._reports,"data","delta_kbs_out"),volatility:Ge(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:Je(this._reports,"data","delta_KBytes_in"),min:We(this._reports,"data","delta_KBytes_in"),max:Ke(this._reports,"data","delta_KBytes_in"),volatility:Ge(this._reports,"data","delta_KBytes_in")},out:{avg:Je(this._reports,"data","delta_KBytes_out"),min:We(this._reports,"data","delta_KBytes_out"),max:Ke(this._reports,"data","delta_KBytes_out"),volatility:Ge(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:xT(this._reports),remoteConnection:MT(this._reports)}}}}updateConfig(n){this._cfg=n}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const n=this._reports.slice();return n.pop(),n.pop()||null}getReportsNumber(){return this._reports.length}}const ws="extractor ",h_=(c,n,r,o)=>{let a=!1;const t=o[n].total_rtt_ms_out,s=o[n].total_rtt_measure_out,p=r?r[n].total_rtt_ms_out:0,_=r?r[n].total_rtt_measure_out:0,d={rtt:null,totalRTT:t,totalRTTMeasurements:s};if(c[V.TIMESTAMP]===o[n].timestamp_out||!Object.prototype.hasOwnProperty.call(c,V.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(a=!0,Number(c[V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-_===s))return d;const g=1e3*Number(c[V.ROUND_TRIP_TIME]);let T=t+g,E=s+1;return a&&(T=1e3*Number(c[V.TOTAL_ROUND_TRIP_TIME])-p,E=Number(c[V.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-_),{rtt:g,totalRTT:T,totalRTTMeasurements:E}},LT=(c,n,r,o)=>{if(!Object.prototype.hasOwnProperty.call(c,V.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:o[n].total_rtt_connectivity_ms,totalRTTMeasurements:o[n].total_rtt_connectivity_measure};const a=1e3*Number(c[V.CURRENT_ROUND_TRIP_TIME]);let t=o[n].total_rtt_connectivity_ms+a,s=o[n].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,V.TOTAL_ROUND_TRIP_TIME)&&(t=1e3*Number(c[V.TOTAL_ROUND_TRIP_TIME])-(r?r[n].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,V.RESPONSES_RECEIVED)&&(s=Number(c[V.RESPONSES_RECEIVED])-(r?r[n].total_rtt_connectivity_measure:0)),{rtt:a,totalRTT:t,totalRTTMeasurements:s}},uo=(c,n,r)=>c[V.TIMESTAMP]===r[n].timestamp_out||!Object.prototype.hasOwnProperty.call(c,V.JITTER)?null:1e3*(Number(c[V.JITTER])||0),$T=(c,n)=>{if(!Object.prototype.hasOwnProperty.call(c,V.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,V.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:n[x.VIDEO].delta_ms_decode_frame_in,frames_decoded:n[x.VIDEO].total_frames_decoded_in,total_decode_time:n[x.VIDEO].total_time_decoded_in};const r=c[V.FRAMES_DECODED],o=c[V.TOTAL_DECODE_TIME],a=o-n[x.VIDEO].total_time_decoded_in,t=r-n[x.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:t>0?a*1e3/t:0,frames_decoded:r,total_decode_time:o}},HT=(c,n)=>{if(!Object.prototype.hasOwnProperty.call(c,V.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,V.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:n[x.VIDEO].delta_ms_encode_frame_out,frames_encoded:n[x.VIDEO].total_frames_encoded_out,total_encode_time:n[x.VIDEO].total_time_encoded_out};const r=c[V.FRAMES_ENCODED],o=c[V.TOTAL_ENCODE_TIME],a=o-n[x.VIDEO].total_time_encoded_out,t=r-n[x.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:t>0&&a?a*1e3/t:0,frames_encoded:r,total_encode_time:o}},d_=(c,n,r,o)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,V.BYTES_SENT))return{packetsSent:r[n].total_packets_out,packetsLost:r[n].total_packets_lost_out,bytesSent:r[n].total_KBytes_out};const a=Number(c[V.PACKETS_SENT])||0-(o?o[n].total_packets_out:0),t=a-r[n].total_packets_out,s=Number(c[V.BYTES_SENT])/1024-(o?o[n].total_KBytes_out:0),p=s-r[n].total_KBytes_out,_=c[V.TIMESTAMP]||Date.now(),d=o?o.timestamp:null;let g=r.timestamp;!g&&d&&(g=d);const T=g?_-g:0,E=T>0?p*.008*1024/T*1e3:0;return{packetsSent:a,deltaPacketsSent:t,KBytesSent:s,deltaKBytesSent:p,kbsSent:E}},p_=(c,n,r,o)=>{let a=r[n].total_packets_lost_out,t=0,s=0;return Object.prototype.hasOwnProperty.call(c,V.PACKETS_LOST)&&(a=Number(c[V.PACKETS_LOST])||0-(o?o[n].total_packets_lost_out:0),t=a-r[n].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,V.FRACTION_LOST)&&(s=Number(100*c[V.FRACTION_LOST])),{packetsLost:a,deltaPacketsLost:t,fractionLost:s}},m_=(c,n,r,o)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,V.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,V.BYTES_RECEIVED))return{percent_packets_lost:r[n].percent_packets_lost_in,packetsReceived:r[n].total_packets_in,packetsLost:r[n].total_packets_lost_in,bytesReceived:r[n].total_KBytes_in};const a=Number(c[V.PACKETS_RECEIVED])||0-(o?o[n].total_packets_in:0),t=Number(c[V.PACKETS_LOST])||0-(o?o[n].total_packets_lost_in:0),s=t-r[n].total_packets_lost_in,p=a-r[n].total_packets_in,_=a!==r[n].total_packets_in?s*100/(s+p):0,d=Number(c[V.BYTES_RECEIVED])/1024-(o?o[n].total_KBytes_in:0),g=d-r[n].total_KBytes_in,T=c[V.TIMESTAMP]||Date.now(),E=o?o.timestamp:null;let y=r.timestamp;!y&&E&&(y=E);const A=y?T-y:0,R=A>0?g*.008*1024/A*1e3:0;return{percentPacketsLost:_,packetsReceived:a,deltaPacketsReceived:p,packetsLost:t,deltaPacketsLost:s,KBytesReceived:d,deltaKBytesReceived:g,kbsReceived:R}},FT=c=>c[V.CANDIDATE_TYPE]!=="relay"?"":c[V.RELAY_PROTOCOL]||"",VT=c=>{if(!Object.prototype.hasOwnProperty.call(c,V.NETWORK_TYPE))return Yr.WIFI;switch(c[V.NETWORK_TYPE]){case cu.ETHERNET:return Yr.ETHERNET;case cu.CELLULAR_4G:return Yr.CELLULAR_4G;case cu.WIFI:return Yr.WIFI;default:return Yr.CELLULAR}},g_=c=>!Object.prototype.hasOwnProperty.call(c,V.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,V.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[V.FRAME_WIDTH]||null,height:c[V.FRAME_HEIGHT]||null,framerate:c[V.FRAMES_PER_SECOND]},jT=c=>{const n=Object.prototype.hasOwnProperty.call(c,V.QUALITY_LIMITATION_REASON)?c[V.QUALITY_LIMITATION_REASON]:null,r=Object.prototype.hasOwnProperty.call(c,V.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[V.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,o=Object.prototype.hasOwnProperty.call(c,V.QUALITY_LIMITATION_DURATIONS)?c[V.QUALITY_LIMITATION_DURATIONS]:null;return o&&Object.keys(o).forEach(a=>{o[a]>1e3&&(o[a]=Number(o[a]/1e3))}),{reason:n,durations:o,resolutionChanges:r}},qT=(c,n,r)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PLI)||!Object.prototype.hasOwnProperty.call(c,V.NACK))return{pliCount:n.total_pli_sent_in,nackCount:n.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const o=(c[V.PLI]||0)-(r?r[x.VIDEO].total_pli_sent_in:0),a=(c[V.NACK]||0)-(r?r[x.VIDEO].total_nack_sent_in:0);return{pliCount:o,nackCount:a,deltaPliCount:o-n[x.VIDEO].total_pli_sent_in,deltaNackCount:a-n[x.VIDEO].total_nack_sent_in}},BT=(c,n,r)=>{if(!Object.prototype.hasOwnProperty.call(c,V.PLI)||!Object.prototype.hasOwnProperty.call(c,V.NACK))return{pliCount:n.total_pli_received_out,nackCount:n.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const o=(c[V.PLI]||0)-(r?r[x.VIDEO].total_pli_received_out:0),a=(c[V.NACK]||0)-(r?r[x.VIDEO].total_nack_received_out:0);return{pliCount:o,nackCount:a,deltaPliCount:o-n[x.VIDEO].total_pli_received_out,deltaNackCount:a-n[x.VIDEO].total_nack_received_out}},GT=c=>({channels:c[V.CHANNELS]||null,clock_rate:c[V.CLOCK_RATE]||null,mime_type:c[V.MIME_TYPE]||null,sdp_fmtp_line:c[V.SDP_FMTP_LINE]||null}),WT=c=>({clock_rate:c[V.CLOCK_RATE]||null,mime_type:c[V.MIME_TYPE]||null}),KT=(c,n,r)=>{const o=(c[V.BYTES_RECEIVED]||0)/1024-(r?r.data.total_KBytes_in:0),a=(c[V.BYTES_SENT]||0)/1024-(r?r.data.total_KBytes_out:0),t=c[V.TIMESTAMP]||Date.now(),s=o-n.data.total_KBytes_in,p=a-n.data.total_KBytes_out,_=r?r.timestamp:null;let d=n.timestamp;!d&&_&&(d=_);const g=d?t-d:0,T=g>0?s*.008*1024/g*1e3:0,E=g>0?p*.008*1024/g*1e3:0;return{total_KBytes_received:o,total_KBytes_sent:a,delta_KBytes_received:s,delta_KBytes_sent:p,kbs_speed_received:T,kbs_speed_sent:E}},YT=c=>{const n=c[V.AVAILABLE_INCOMING_BITRATE]/1024||0,r=c[V.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:n,kbs_outgoing_bandwidth:r}},zT=(c,n,r,o)=>{if(!c)return[];switch(c[V.TYPE]){case Wt.CANDIDATE_PAIR:let a=!1;if(c[V.NOMINATED]&&c[V.STATE]===x.SUCCEEDED&&(a=!0,Pe(ws,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c),V.SELECTED in c&&!c[V.SELECTED]&&(a=!1)),a){const s=c[V.LOCAL_CANDIDATE_ID],p=c[V.REMOTE_CANDIDATE_ID],_=KT(c,n,o),d=YT(c),g=LT(c,"data",o,n);return[{type:ne.NETWORK,value:{local_candidate_id:s}},{type:ne.NETWORK,value:{remote_candidate_id:p}},{type:ne.DATA,value:{total_KBytes_in:_.total_KBytes_received}},{type:ne.DATA,value:{total_KBytes_out:_.total_KBytes_sent}},{type:ne.DATA,value:{delta_KBytes_in:_.delta_KBytes_received}},{type:ne.DATA,value:{delta_KBytes_out:_.delta_KBytes_sent}},{type:ne.DATA,value:{delta_kbs_in:_.kbs_speed_received}},{type:ne.DATA,value:{delta_kbs_out:_.kbs_speed_sent}},{type:ne.DATA,value:{delta_kbs_bandwidth_in:d.kbs_incoming_bandwidth}},{type:ne.DATA,value:{delta_kbs_bandwidth_out:d.kbs_outgoing_bandwidth}},{type:ne.DATA,value:{delta_rtt_connectivity_ms:g.rtt}},{type:ne.DATA,value:{total_rtt_connectivity_ms:g.totalRTT}},{type:ne.DATA,value:{total_rtt_connectivity_measure:g.totalRTTMeasurements}}]}break;case Wt.LOCAL_CANDIDATE:if(c[V.ID]===n.network.local_candidate_id)return[{type:ne.NETWORK,value:{infrastructure:VT(c)}},{type:ne.NETWORK,value:{local_candidate_type:c[V.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{local_candidate_protocol:c[V.PROTOCOL]||""}},{type:ne.NETWORK,value:{local_candidate_relay_protocol:FT(c)}}];break;case Wt.REMOTE_CANDIDATE:if(c[V.ID]===n.network.remote_candidate_id)return[{type:ne.NETWORK,value:{remote_candidate_type:c[V.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{remote_candidate_protocol:c[V.PROTOCOL]||""}}];break;case Wt.INBOUND_RTP:{Pe(ws,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const s=c[V.SSRC],p=ft(s,n,Le.INBOUND);p&&(p.timestamp=n.timestamp);const _=ft(s,o,Le.INBOUND);if(_&&(_.timestamp=o.timestamp),c[V.MEDIA_TYPE]===x.AUDIO){const d=m_(c,x.AUDIO,p,_),g=uo(c,x.AUDIO,p),T=c[V.CODEC_ID]||"";return[{ssrc:s,type:ne.AUDIO,value:{codec_id_in:T}},{ssrc:s,type:ne.AUDIO,value:{total_packets_in:d.packetsReceived}},{ssrc:s,type:ne.AUDIO,value:{delta_packets_in:d.deltaPacketsReceived}},{ssrc:s,type:ne.AUDIO,value:{total_packets_lost_in:d.packetsLost}},{ssrc:s,type:ne.AUDIO,value:{delta_packets_lost_in:d.deltaPacketsLost}},{ssrc:s,type:ne.AUDIO,value:{percent_packets_lost_in:d.percentPacketsLost}},{ssrc:s,type:ne.AUDIO,value:{total_KBytes_in:d.KBytesReceived}},{ssrc:s,type:ne.AUDIO,value:{delta_KBytes_in:d.deltaKBytesReceived}},{ssrc:s,type:ne.AUDIO,value:{delta_kbs_in:d.kbsReceived}},{ssrc:s,type:ne.AUDIO,value:{delta_jitter_ms_in:g}}]}if(c[V.MEDIA_TYPE]===x.VIDEO){const d=$T(c,p),g=m_(c,x.VIDEO,p,_),T=uo(c,x.VIDEO,p),E=c[V.DECODER_IMPLEMENTATION]||null,y=c[V.CODEC_ID]||null,A=g_(c),R=qT(c,p,_);return[{ssrc:s,type:ne.VIDEO,value:{codec_id_in:y}},{ssrc:s,type:ne.VIDEO,value:{total_packets_in:g.packetsReceived}},{ssrc:s,type:ne.VIDEO,value:{delta_packets_in:g.deltaPacketsReceived}},{ssrc:s,type:ne.VIDEO,value:{total_packets_lost_in:g.packetsLost}},{ssrc:s,type:ne.VIDEO,value:{delta_packets_lost_in:g.deltaPacketsLost}},{ssrc:s,type:ne.VIDEO,value:{percent_packets_lost_in:g.percentPacketsLost}},{ssrc:s,type:ne.VIDEO,value:{total_KBytes_in:g.KBytesReceived}},{ssrc:s,type:ne.VIDEO,value:{delta_KBytes_in:g.deltaKBytesReceived}},{ssrc:s,type:ne.VIDEO,value:{delta_kbs_in:g.kbsReceived}},{ssrc:s,type:ne.VIDEO,value:{delta_jitter_ms_in:T}},{ssrc:s,type:ne.VIDEO,value:{decoder_in:E}},{ssrc:s,type:ne.VIDEO,value:{delta_ms_decode_frame_in:d.delta_ms_decode_frame}},{ssrc:s,type:ne.VIDEO,value:{total_frames_decoded_in:d.frames_decoded}},{ssrc:s,type:ne.VIDEO,value:{total_time_decoded_in:d.total_decode_time}},{ssrc:s,type:ne.VIDEO,value:{total_nack_sent_in:R.nackCount}},{ssrc:s,type:ne.VIDEO,value:{delta_nack_sent_in:R.deltaNackCount}},{ssrc:s,type:ne.VIDEO,value:{total_pli_sent_in:R.pliCount}},{ssrc:s,type:ne.VIDEO,value:{delta_pli_sent_in:R.deltaPliCount}},{ssrc:s,type:ne.VIDEO,value:{size_in:A}}]}break}case Wt.OUTBOUND_RTP:{Pe(ws,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const s=c[V.SSRC],p=ft(s,n,Le.OUTBOUND);p&&(p.timestamp=n.timestamp);const _=ft(s,o,Le.OUTBOUND);if(_&&(_.timestamp=o.timestamp),c[V.MEDIA_TYPE]===x.AUDIO){const d=c[V.CODEC_ID]||null,g=d_(c,x.AUDIO,p,_);return[{ssrc:s,type:ne.AUDIO,value:{codec_id_out:d}},{ssrc:s,type:ne.AUDIO,value:{total_packets_out:g.packetsSent}},{ssrc:s,type:ne.AUDIO,value:{delta_packets_out:g.deltaPacketsSent}},{ssrc:s,type:ne.AUDIO,value:{total_KBytes_out:g.KBytesSent}},{ssrc:s,type:ne.AUDIO,value:{delta_KBytes_out:g.deltaKBytesSent}},{ssrc:s,type:ne.AUDIO,value:{delta_kbs_out:g.kbsSent}}]}if(c[V.MEDIA_TYPE]===x.VIDEO){const d=c[V.ENCODER_IMPLEMENTATION]||null,g=c[V.CODEC_ID]||null,T=HT(c,p),E=g_(c),y=jT(c),A=BT(c,p,_),R=d_(c,x.VIDEO,p,_);return[{ssrc:s,type:ne.VIDEO,value:{codec_id_out:g}},{ssrc:s,type:ne.VIDEO,value:{total_packets_out:R.packetsSent}},{ssrc:s,type:ne.VIDEO,value:{delta_packets_out:R.deltaPacketsSent}},{ssrc:s,type:ne.VIDEO,value:{total_KBytes_out:R.KBytesSent}},{ssrc:s,type:ne.VIDEO,value:{delta_KBytes_out:R.deltaKBytesSent}},{ssrc:s,type:ne.VIDEO,value:{delta_kbs_out:R.kbsSent}},{ssrc:s,type:ne.VIDEO,value:{encoder_out:d}},{ssrc:s,type:ne.VIDEO,value:{delta_ms_encode_frame_out:T.delta_ms_encode_frame}},{ssrc:s,type:ne.VIDEO,value:{total_frames_encoded_out:T.frames_encoded}},{ssrc:s,type:ne.VIDEO,value:{total_time_encoded_out:T.total_encode_time}},{ssrc:s,type:ne.VIDEO,value:{total_nack_received_out:A.nackCount}},{ssrc:s,type:ne.VIDEO,value:{delta_nack_received_out:A.deltaNackCount}},{ssrc:s,type:ne.VIDEO,value:{total_pli_received_out:A.pliCount}},{ssrc:s,type:ne.VIDEO,value:{delta_pli_received_out:A.deltaPliCount}},{ssrc:s,type:ne.VIDEO,value:{size_out:E}},{ssrc:s,type:ne.VIDEO,value:{limitation_out:y}}]}break}case Wt.MEDIA_SOURCE:{Pe(ws,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);break}case Wt.TRACK:{Pe(ws,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);break}case Wt.CODEC:const t=[];return Object.keys(n[x.AUDIO]).forEach(s=>{const p=n[x.AUDIO][s];if(p.codec_id_in===c[V.ID]||p.codec_id_out===c[V.ID]){Pe(ws,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const _=GT(c);c[V.ID]===p.codec_id_in?t.push({ssrc:p.ssrc,type:ne.AUDIO,value:{codec_in:_}}):t.push({ssrc:p.ssrc,type:ne.AUDIO,value:{codec_out:_}})}}),Object.keys(n[x.VIDEO]).forEach(s=>{const p=n[x.VIDEO][s];if(p.codec_id_in===c[V.ID]||p.codec_id_out===c[V.ID]){Pe(ws,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const _=WT(c);c[V.ID]===p.codec_id_in?t.push({ssrc:p.ssrc,type:ne.VIDEO,value:{codec_in:_}}):t.push({ssrc:p.ssrc,type:ne.VIDEO,value:{codec_out:_}})}}),t;case Wt.REMOTE_INBOUND_RTP:{Pe(ws,`analyze() - got stats ${c[V.TYPE]} for ${r}`,c);const s=c[V.SSRC],p=ft(s,n,Le.OUTBOUND),_=ft(s,o,Le.OUTBOUND);if(c[V.KIND]===x.AUDIO){const d=h_(c,x.AUDIO,_,p),g=uo(c,x.AUDIO,p),T=p_(c,x.AUDIO,p,_);return[{ssrc:s,type:ne.AUDIO,value:{delta_rtt_ms_out:d.rtt}},{ssrc:s,type:ne.AUDIO,value:{total_rtt_ms_out:d.totalRTT}},{ssrc:s,type:ne.AUDIO,value:{total_rtt_measure_out:d.totalRTTMeasurements}},{ssrc:s,type:ne.AUDIO,value:{delta_jitter_ms_out:g}},{ssrc:s,type:ne.AUDIO,value:{timestamp_out:c[V.TIMESTAMP]}},{ssrc:s,type:ne.AUDIO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:s,type:ne.AUDIO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:s,type:ne.AUDIO,value:{percent_packets_lost_out:T.fractionLost}}]}if(c[V.KIND]===x.VIDEO){const d=h_(c,x.VIDEO,_,p),g=uo(c,x.VIDEO,p),T=p_(c,x.VIDEO,p,_);return[{ssrc:s,type:ne.VIDEO,value:{delta_rtt_ms_out:d.rtt}},{ssrc:s,type:ne.VIDEO,value:{total_rtt_ms_out:d.totalRTT}},{ssrc:s,type:ne.VIDEO,value:{total_rtt_measure_out:d.totalRTTMeasurements}},{ssrc:s,type:ne.VIDEO,value:{delta_jitter_ms_out:g}},{ssrc:s,type:ne.VIDEO,value:{timestamp_out:c[V.TIMESTAMP]}},{ssrc:s,type:ne.VIDEO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:s,type:ne.VIDEO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:s,type:ne.VIDEO,value:{percent_packets_lost_out:T.fractionLost}}]}break}}return[]},co=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),JT=(c,n=x.AUDIO,r,o,a)=>{const t=ft(a,c,Le.INBOUND),s=ft(a,r,Le.INBOUND),p=ft(a,o,Le.INBOUND),_=[],d=[],g=t[n].percent_packets_lost_in,T=t[n].delta_jitter_ms_in,E=s&&s[n].delta_jitter_ms_in||null,y=p&&p[n].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,R=r&&r.data.delta_rtt_connectivity_ms||null,I=o&&o.data.delta_rtt_connectivity_ms||null;A&&_.push(A),R&&_.push(R),I&&_.push(I),T&&d.push(T),r&&E&&d.push(E),o&&y&&d.push(y);const $=_.length>0?bs(_):100,L=d.length>0?bs(d):10,ae=93.2-g,N=.18*ae*ae-27.9*ae+1126.62,F=($+L)/2,Se=F-177.3<0?0:1,ve=.024*F+.11*(F-177.3)*Se,M=N-ve;return co(M)},XT=(c,n=x.AUDIO,r,o,a)=>{const t=ft(a,c,Le.OUTBOUND),s=ft(a,r,Le.OUTBOUND),p=ft(a,o,Le.OUTBOUND),_=[],d=[],g=t[n].percent_packets_lost_out,T=t[n].delta_rtt_ms_out,E=s&&s[n].delta_rtt_ms_out||null,y=p&&p[n].delta_rtt_ms_out||null,A=t[n].delta_jitter_ms_out,R=s&&s[n].delta_jitter_ms_out||null,I=p&&p[n].delta_jitter_ms_out||null,$=c.data.delta_rtt_connectivity_ms,L=r&&r.data.delta_rtt_connectivity_ms||null,ae=o&&o.data.delta_rtt_connectivity_ms||null;T?_.push(T):$&&_.push($),E?_.push(E):L&&_.push(L),y?_.push(y):ae&&_.push(ae),A&&d.push(A),r&&R&&d.push(R),o&&I&&d.push(I);const N=_.length>0?bs(_):100,F=d.length>0?bs(d):10,Se=93.2-g,ve=.18*Se*Se-27.9*Se+1126.62,M=(N+F)/2,D=M-177.3<0?0:1,B=.024*M+.11*(M-177.3)*D,j=ve-B;return co(j)},QT=(c,n=x.AUDIO,r,o,a)=>{const t=ft(a,c,Le.INBOUND),s=ft(a,r,Le.INBOUND),p=ft(a,o,Le.INBOUND),_=[],d=[],g=t[n].percent_packets_lost_in/100,T=t[n].delta_jitter_ms_in,E=s&&s[n].delta_jitter_ms_in||null,y=p&&p[n].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,R=r&&r.data.delta_rtt_connectivity_ms||null,I=o&&o.data.delta_rtt_connectivity_ms||null;A&&_.push(A),R&&_.push(R),I&&_.push(I),T&&d.push(T),s&&E&&d.push(E),p&&y&&d.push(y);const $=_.length>0?bs(_):100,L=d.length>0?bs(d):10,ae=0,N=19.8,F=29.7,Se=30,ve=($+L)/2+Se,M=ve-177.3<0?0:1,D=.024*ve+.11*(ve-177.3)*M,j=93.2-(ae+N*Math.log(1+F*g)+D);return co(j)},ZT=(c,n=x.AUDIO,r,o,a)=>{const t=ft(a,c,Le.OUTBOUND),s=ft(a,r,Le.OUTBOUND),p=ft(a,o,Le.OUTBOUND),_=[],d=[],g=t[n].percent_packets_lost_out/100,T=t[n].delta_rtt_ms_out,E=s&&s[n].delta_rtt_ms_out||null,y=p&&p[n].delta_rtt_ms_out||null,A=t[n].delta_jitter_ms_out,R=s&&s[n].delta_jitter_ms_out||null,I=p&&p[n].delta_jitter_ms_out||null,$=c.data.delta_rtt_connectivity_ms,L=r&&r.data.delta_rtt_connectivity_ms||null,ae=o&&o.data.delta_rtt_connectivity_ms||null;T?_.push(T):$&&_.push($),E?_.push(E):L&&_.push(L),y?_.push(y):ae&&_.push(ae),A&&d.push(A),s&&R&&d.push(R),p&&I&&d.push(I);const N=_.length>0?bs(_):100,F=d.length>0?bs(d):10,Se=0,ve=19.8,M=29.7,D=30,B=(N+F)/2+D,j=B-177.3<0?0:1,z=.024*B+.11*(B-177.3)*j,Z=93.2-(Se+ve*Math.log(1+M*g)+z);return co(Z)};class ev{constructor(n,r){this._callbacks={onreport:null,onticket:null},this._id=DT(),this._moduleName=this._id,this._probeId=r,this._config=n,this._exporter=new kT(n),this._state=ps.IDLE,this.registerToPCEvents(),Qs(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(n,r,o,a){const t=(_,d)=>_===x.AUDIO?d===Wt.INBOUND_RTP?{...o_}:{...a_}:d===Wt.INBOUND_RTP?{...u_}:{...c_},s=RT(r);s.pname=this._config.pname,s.call_id=this._config.cid,s.user_id=this._config.uid,s.count=r?r.count+1:1;let p=null;return n.forEach(_=>{!p&&_.timestamp&&(p=_.timestamp),zT(_,s,s.pname,a).forEach(g=>{if(g.value&&g.type)if(g.ssrc){let T=s[g.type][g.ssrc];T||(T=t(g.type,_.type),T.ssrc=g.ssrc,s[g.type][g.ssrc]=T),Object.keys(g.value).forEach(E=>{T[E]=g.value[E]})}else Object.keys(g.value).forEach(T=>{s[g.type][T]=g.value[T]})})}),s.timestamp=p,Object.keys(s[x.AUDIO]).forEach(_=>{const d=s[x.AUDIO][_];d.direction===Le.INBOUND?(d.mos_emodel_in=JT(s,x.AUDIO,r,o,d.ssrc),d.mos_in=QT(s,x.AUDIO,r,o,d.ssrc)):(d.mos_emodel_out=XT(s,x.AUDIO,r,o,d.ssrc),d.mos_out=ZT(s,x.AUDIO,r,o,d.ssrc))}),s}async takeReferenceStats(){return new Promise((n,r)=>{const o=Date.now();setTimeout(async()=>{try{const a=Date.now()-o,t=Date.now(),s=await this._config.pc.getStats(),p=this.analyze(s,null,null,null),_=Date.now();p.experimental.time_to_measure_ms=_-t,p.experimental.time_to_wait_ms=a,this._exporter.saveReferenceReport(p),Pe(this._moduleName,`got reference report for probe ${this._probeId}`),n()}catch(a){r(a)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==ps.RUNNING||!this._config.pc)return Pe(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const n=Date.now(),r=await this._config.pc.getStats(),o=this.analyze(r,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),a=Date.now();return o.experimental.time_to_measure_ms=a-n,this._exporter.addReport(o),Pe(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(o),o}catch(n){return Pn(this._moduleName,`got error ${n}`),null}}async start(){Pe(this._moduleName,"starting"),this.state=ps.RUNNING,this._startedTime=this._exporter.start(),Pe(this._moduleName,"started")}async mute(){this.state=ps.MUTED,Pe(this._moduleName,"muted")}async unmute(){this.state=ps.RUNNING,Pe(this._moduleName,"unmuted")}async stop(n){if(Pe(this._moduleName,`stopping${n?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=ps.IDLE,this._config.ticket){const{ticket:r}=this._exporter;this.fireOnTicket(r)}this._exporter.reset(),Pe(this._moduleName,"stopped")}registerCallback(n,r,o){n in this._callbacks?(this._callbacks[n]={callback:r,context:o},Pe(this._moduleName,`registered callback '${n}'`)):Pn(this._moduleName,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Pe(this._moduleName,`unregistered callback '${n}'`)):Pn(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReport(n){this._callbacks.onreport&&_u(this._callbacks.onreport.callback,this._callbacks.onreport.context,n)}fireOnTicket(n){this._callbacks.onticket&&_u(this._callbacks.onticket.callback,this._callbacks.onticket.context,n)}updateConfig(n){this._config=n,this._exporter.updateConfig(n)}get state(){return this._state}set state(n){this._state=n,Pe(this._moduleName,`state changed to ${n}`)}addCustomEvent(n,r,o,a){this._exporter.addCustomEvent({at:typeof n=="object"?n.toJSON():n,category:r,name:o,description:a})}async registerToPCEvents(){const{pc:n}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const r=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${r.length} devices found`,"Media Devices state")}catch{Pn(this._moduleName,"can't get devices")}},n){n.oniceconnectionstatechange=()=>{const o=n.iceConnectionState;o===Kr.CONNECTED||o===Kr.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===Kr.DISCONNECTED||o===Kr.FAILED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===Kr.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},n.onicegatheringstatechange=()=>{const o=n.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",o,"ICE gathering state")},n.ontrack=o=>{this.addCustomEvent(new Date().toJSON(),"call",`${o.track.kind}track`,"MediaStreamTrack received")},n.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const r=n.getReceivers();if(r&&r.length>0){const o=r[0],{transport:a}=o;if(a){const{iceTransport:t}=a;t&&(t.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class tv{constructor(n){this._id=n.pname&&n.pname.substr(0,12).padEnd(12," ")||OT(),this._moduleName=this._id,Qs(this._moduleName,"probe created"),this._config=n,this._collector=new ev(this._config,this._id)}set onreport(n){n?this._collector.registerCallback("onreport",n):this._collector.unregisterCallback("onreport")}set onticket(n){n?this._collector.registerCallback("onticket",n):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(n){this._collector.state=n}addCustomEvent(n,r,o,a=new Date().toJSON()){this._collector.addCustomEvent(a,r,n,o)}get isRunning(){return this._collector.state===ps.RUNNING}get isIdle(){return this._collector.state===ps.IDLE}updateUserId(n){this._config.uid=n,this._collector.updateConfig(this._config)}updateCallId(n){this._config.cid=n,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){ao(this._moduleName,"probe is already running");return}this._collector.start()}stop(n=!1){this.isRunning&&this._collector.stop(n)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const Ct="engine ";class sv{constructor(n){this._config=n,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},Qs(Ct,`configured for probing every ${this._config.refreshEvery}ms`),Qs(Ct,`configured for starting after ${this._config.startAfter}ms`),Qs(Ct,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Pe(Ct,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(n=>n.isRunning)}get isIdle(){return this._probes.every(n=>n.isIdle)}addNewProbe(n,r){if(!n)throw new Error("undefined peer connection");const o=bT(n,r,this._config),a=new tv(o);return this._probes.push(a),Pe(Ct,`${this._probes.length} probes registered`),a}removeExistingProbe(n){if(!n)throw new Error("undefined probe");n.state===ps.RUNNING&&n.stop(),this._probes=this._probes.filter(r=>n.id!==r.id)}async start(){const n=()=>{this._probes.forEach(t=>t.start())},r=async()=>Promise.all(this._probes.map(t=>t.takeReferenceStats())),o=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,a=async()=>{const t=CT(),s=this._probes.filter(p=>p.isRunning);for(const p of s){const _=await p.collectStats();_&&t.probes.push(_),Pe(Ct,`got probe ${p.id}`),await f_(0)}return t.delta_time_to_measure_probes_ms=Zs(t.probes,"experimental","time_to_measure_ms"),t.delta_KBytes_in=Zs(t.probes,"data","delta_KBytes_in"),t.delta_KBytes_out=Zs(t.probes,"data","delta_KBytes_out"),t.delta_kbs_in=Zs(t.probes,"data","delta_kbs_in"),t.delta_kbs_out=Zs(t.probes,"data","delta_kbs_out"),t.total_time_decoded_in=Zs(t.probes,"video","total_time_decoded_in"),t.total_time_encoded_out=Zs(t.probes,"video","total_time_encoded_out"),t};for(Pe(Ct,"starting to collect"),n(),Pe(Ct,"generating reference reports..."),await r(),Pe(Ct,"reference reports generated"),this._startedTime=Date.now();o();)if(Pe(Ct,`wait ${this._config.refreshEvery}ms before collecting`),await f_(this._config.refreshEvery),o()){Pe(Ct,"collecting...");const t=Date.now(),s=await a(),p=Date.now();s.delta_time_consumed_to_measure_ms=p-t,this.fireOnReports(s),Pe(Ct,"collected")}Pe(Ct,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(n){const r=o=>{this._probes.forEach(a=>{a.stop(o)})};Qs(Ct,"stop collecting"),r(n)}registerCallback(n,r,o){n in this._callbacks?(this._callbacks[n]={callback:r,context:o},Pe(Ct,`registered callback '${n}'`)):Pn(Ct,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Pe(this._moduleName,`unregistered callback '${n}'`)):Pn(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReports(n){this._callbacks.onresult&&n.probes.length>0&&_u(this._callbacks.onresult.callback,this._callbacks.onresult.context,n)}}const nv="interface ";class rv{constructor(n){this._config=wT(n),Qs(nv,`welcome to ${this._config.name} version ${this._config.version}`),mT(this._config.verbose||!1),this._engine=new sv(this._config)}setupLogLevel(n){gT(n)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(n,r){return this._engine.addNewProbe(n,r)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(n){this._engine.removeExistingProbe(n)}set onresult(n){n?this._engine.registerCallback("onresult",n):this._engine.unregisterCallback("onresult")}}function iv(c,n){return Object.keys(c).filter(r=>n.includes(r)).reduce((r,o)=>{const a=o;return{...r,[a]:c[a]}},{})}const lv=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"];class ov{constructor(n){this.intervals={},this.emitInterval=n.emitInterval||200,this.onChangeFunction=n.onChangeFunction}start(n,r){n&&n.getTracks().length&&requestAnimationFrame(()=>this.beginCalculation(n,r))}stop(n){this.clearVolumeInterval(n)}clearVolumeInterval(n){console.log("clearVolumeInterval",n),clearInterval(this.intervals[n]),delete this.intervals[n]}clearAllIntervals(){Object.keys(this.intervals).forEach(n=>{clearInterval(this.intervals[n])}),this.intervals={}}beginCalculation(n,r){this.clearVolumeInterval(r);const o=Xs.createAnalyser(),a=Xs.createMediaStreamSource(n),t=Xs.createScriptProcessor(2048,1,1);o.smoothingTimeConstant=.8,o.fftSize=1024,a.connect(o),o.connect(t),t.connect(Xs.destination),this.intervals[r]=setInterval(()=>{const s=new Uint8Array(o.frequencyBinCount);o.getByteFrequencyData(s);let p=0;const _=s.length;for(let g=0;g<_;g++)p+=s[g];const d=p/_;this.onChangeFunction(r,d)},this.emitInterval)}}const fo={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},av=0;class uv{constructor(n){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=n,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new ov({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices()}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(n){this.currentActiveRoomIdValue=n,this.context.emit("currentActiveRoomChanged",n)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(n){this.isCallAddingInProgress=n,this.context.emit("callAddingInProgressChanged",n)}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(n=>n.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audiooutput")}get getUserMediaConstraints(){return/Mobi|Android|iPhone/i.test(navigator.userAgent)?{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(n){this.availableMediaDevices=n,this.context.emit("changeAvailableDeviceList",n)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const n=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(n)}async initializeMediaDevices(){const n=localStorage.getItem(fo.SELECTED_INPUT_DEVICE)||"default",r=localStorage.getItem(fo.SELECTED_OUTPUT_DEVICE)||"default";try{const o=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),a=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(a),await this.setMicrophone(n),await this.setSpeaker(r),navigator.mediaDevices.addEventListener("devicechange",async()=>{const t=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(t)}),o.getTracks().forEach(t=>t.stop())}catch(o){console.error(o)}}setCallTime(n){const r={...n};delete r.callId,this.callTime={...this.callTime,[n.callId]:r},this.context.emit("changeCallTime",this.callTime)}removeCallTime(n){const r={...this.callTime};delete r[n],this.callTime={...r},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(n,r){this.timeIntervals={...this.timeIntervals,[n]:r}}removeTimeInterval(n){const r={...this.timeIntervals};r[n]&&(clearInterval(r[n]),delete r[n],this.timeIntervals={...r})}stopCallTimer(n){this.removeTimeInterval(n),this.removeCallTime(n)}emitVolumeChange(n,r){this.context.emit("changeCallVolume",{callId:n,volume:r})}setMetricsConfig(n){this.metricConfig={...this.metricConfig,...n}}sendDTMF(n,r){if(!/^[A-D0-9]+$/g.test(r))throw new Error("Not allowed character in DTMF input");this.extendedCalls[n].sendDTMF(r)}setIsMuted(n){this.muted=n,this.context.emit("changeIsMuted",n)}processMute(n){const r=this.currentActiveRoomId;this.setIsMuted(n),this.initialStreamValue.getTracks().forEach(o=>o.enabled=!n),this.roomReconfigure(r)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:n,toHold:r,automatic:o}){const a=this.extendedCalls[n];a._automaticHold=o??!1,await new Promise(p=>{const _=()=>{p()};r?a.hold({},_):a.unhold({},_)}),this.updateCall(a);const s=Object.values(this.extendedCalls).filter(p=>p.roomId===this.currentActiveRoomId&&(r?n!==p._id:!0));s.length>1&&await this.doConference(s)}holdCall(n,r=!1){return this.processHold({callId:n,automatic:r,toHold:!0})}unholdCall(n){return this.processHold({callId:n,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(n=>n.direction==="outgoing"&&n.status===av).forEach(n=>this.terminateCall(n._id))}answerCall(n){const r=this.extendedCalls[n];this.cancelAllOutgoingUnanswered(),r.answer(this.sipOptions),this.updateCall(r),this.setActiveRoom(r.roomId),r.connection.addEventListener("track",o=>{this.triggerAddStream(o,r)})}async moveCall(n,r){this.updateCallStatus({callId:n,isMoving:!0}),await this.processRoomChange({callId:n,roomId:r}),this.updateCallStatus({callId:n,isMoving:!1})}updateCall(n){this.activeCalls[n._id]=e_(n),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(n){const o={...this.activeRooms[n.roomId],...n};this.activeRooms={...this.activeRooms,[n.roomId]:{...o}},this.context.emit("updateRoom",{room:o,roomList:this.activeRooms})}hasAutoAnswerHeaders(n){const r=/answer-after=0/,a=n.request.getHeader("Call-Info");return a&&r.test(a)}addCall(n,r=!0){this.activeCalls={...this.activeCalls,[n._id]:e_(n)},this.extendedCalls[n._id]=n,r&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(n){this.callStatus={...this.callStatus,[n]:{isMoving:!1,isTransferring:!1,isMerging:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(n){const o={...{...this.callStatus[n.callId]}};n.isMoving!==void 0&&(o.isMoving=n.isMoving),n.isTransferring!==void 0&&(o.isTransferring=n.isTransferring),n.isMerging!==void 0&&(o.isMerging=n.isMerging),this.callStatus={...this.callStatus,[n.callId]:{...o}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(n){const r={...this.callStatus};delete r[n],this.callStatus={...r},this.context.emit("changeCallStatus",this.callStatus)}addRoom(n){this.activeRooms={...this.activeRooms,[n.roomId]:n},this.context.emit("addRoom",{room:n,roomList:this.activeRooms})}getActiveStream(){const n=s_(this.initialStreamValue,this.microphoneInputLevel*2);return n.getTracks().forEach(r=>r.enabled=!this.isMuted),this.setActiveStream(n),n}async setMicrophone(n){if(!this.getInputDeviceList.find(({deviceId:o})=>o===n)||(this.setSelectedInputDevice(n),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const r=Object.values(this.extendedCalls).filter(o=>o.roomId===this.currentActiveRoomId);r.length===1?Object.values(r).forEach(async o=>{const a=this.getActiveStream();o.connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.updateCall(o)}):await this.doConference(r)}setActiveStream(n){this.activeStream&&this.stopVUMeter("origin"),this.setupVUMeter(n,"origin"),this.activeStreamValue=n,this.context.emit("changeActiveStream",n)}async setSpeaker(n){if(!this.getOutputDeviceList.find(({deviceId:a})=>a===n))return;this.setSelectedOutputDevice(n);const r=Object.values(this.extendedCalls);if(r.length===0)return;const o=r.filter(a=>a.roomId===this.currentActiveRoomId);o.length===1?r.forEach(a=>{var t;(t=a.audioTag)==null||t.setSinkId(n),this.updateCall(a)}):await this.doConference(o)}removeRoom(n){const r={...this.activeRooms},o={...r[n]};delete r[n],this.activeRooms={...r},this.context.emit("removeRoom",{room:o,roomList:this.activeRooms})}deleteRoomIfEmpty(n){n!==void 0&&Object.values(this.extendedCalls).filter(r=>r.roomId===n).length===0&&(this.removeRoom(n),this.currentActiveRoomId===n&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(n){this.muted?n.mute({audio:!0}):n.unmute({audio:!0})}async roomReconfigure(n){if(n===void 0)return;const r=Object.values(this.extendedCalls).filter(o=>o.roomId===n);if(this.currentActiveRoomId===n?r.forEach(o=>{o.audioTag&&(this.muteReconfigure(o),o.audioTag.muted=!1,this.updateCall(o))}):r.forEach(o=>{o.audioTag&&(o.audioTag.muted=!0,this.updateCall(o))}),r.length===0)this.deleteRoomIfEmpty(n);else if(r.length===1&&this.currentActiveRoomId!==n)r[0].isOnHold().local||await this.holdCall(r[0].id,!0);else if(r.length===1&&this.currentActiveRoomId===n){if(r[0].isOnHold().local&&r[0]._automaticHold&&await this.unholdCall(r[0].id),r[0].connection&&r[0].connection.getSenders()[0]){const o=this.getActiveStream();await r[0].connection.getSenders()[0].replaceTrack(o.getTracks()[0]),this.muteReconfigure(r[0])}}else r.length>1&&await this.doConference(r)}async doConference(n){await r_.forEach(n,async o=>{o._localHold&&await this.unholdCall(o._id)});const r=[];n.forEach(o=>{o!=null&&o.connection.getReceivers().forEach(a=>{r.push(a.track)})}),await r_.forEach(n,async o=>{if(o==null)return;const a=new MediaStream,t=Xs.createMediaStreamDestination();if(o.connection.getReceivers().forEach(s=>{r.forEach(p=>{a.addTrack(s.track),s.track.id!==p.id&&Xs.createMediaStreamSource(new MediaStream([p])).connect(t)})}),n[0].roomId===this.currentActiveRoomId){const s=this.getActiveStream();Xs.createMediaStreamSource(s).connect(t)}o.connection.getSenders()[0]&&(await o.connection.getSenders()[0].replaceTrack(t.stream.getTracks()[0]),this.muteReconfigure(o))})}processCallerMute(n,r){const o=this.extendedCalls[n];o&&o.connection.getReceivers().length&&(o.localMuted=r,o.connection.getReceivers().forEach(a=>{a.track.enabled=!r}),this.updateCall(o))}muteCaller(n){this.processCallerMute(n,!0)}unmuteCaller(n){this.processCallerMute(n,!1)}terminateCall(n){const r=this.extendedCalls[n];r._status!==8&&r.terminate()}transferCall(n,r){if(r.toString().length===0)return new Error("Target must be passed");const o=this.extendedCalls[n];if(!o._is_confirmed&&!o._is_canceled){const a=`sip:${r}@${this.context.sipDomain}`;o.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${a}`]});return}this.updateCallStatus({callId:n,isTransferring:!0}),o.refer(`sip:${r}@${this.context.sipDomain}`),this.updateCall(o)}mergeCall(n){const r=Object.values(this.extendedCalls).filter(t=>t.roomId===n);if(r.length!==2)return;const o=r[0],a=r[1];!o||!a||(this.updateCallStatus({callId:o._id,isMerging:!0}),this.updateCallStatus({callId:a._id,isMerging:!0}),o.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(o))}setDND(n){this.isDNDEnabled=n,this.context.emit("changeIsDND",n)}startCallTimer(n){this.removeTimeInterval(n);const r={callId:n,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(r);const o=setInterval(()=>{const a={...this.callTime[n]},t=dT(a);this.setCallTime({callId:n,...t})},1e3);this.setTimeInterval(n,o)}async setActiveRoom(n){const r=this.currentActiveRoomId;n!==r&&(this.currentActiveRoomId=n,await this.roomReconfigure(r),await this.roomReconfigure(n))}getNewRoomId(){const n=Object.keys(this.activeRooms);return n.length===0?1:parseInt(n.sort()[n.length-1])+1}async setupCall(n){var d,g;const r=n.session;if(this.getActiveCalls[r.id]!==void 0)return;const a=this.getNewRoomId(),t={started:new Date,incomingInProgress:!1,roomId:a};r.direction==="incoming"?(this.context.logger.log("New incoming call from",(g=(d=r._remote_identity)==null?void 0:d._uri)==null?void 0:g._user),t.incomingInProgress=!0,this.context.subscribe(es.CALL_CONFIRMED,T=>{r.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.startCallTimer(r.id))}),this.context.subscribe(es.CALL_FAILED,T=>{r.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.deleteRoomIfEmpty(a))})):r.direction==="outgoing"&&(r.once("confirmed",()=>{this.startCallTimer(r.id)}),this.startCallTimer(r.id));const s=r,p=this.hasAutoAnswerHeaders(n),_=s.direction==="incoming"&&!this.hasActiveCalls&&(p||this.autoAnswer);s.roomId=a,s.localMuted=!1,s.autoAnswer=_,_?this.addCall(s,!1):this.addCall(s),this.addCallStatus(r.id),this.addRoom(t),_&&this.answerCall(s._id)}removeCall(n){const r={...this.activeCalls};delete r[n],this.activeCalls={...r};const o={...this.extendedCalls};delete o[n],this.extendedCalls={...o},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(n){const r=this.extendedCalls[n._id];this.stopVUMeter("origin"),r.connection.getSenders().forEach(a=>{a.track.stop()});const o=r.roomId;this.removeCall(n._id),this.roomReconfigure(o)}async newRTCSessionCallback(n){const r=n.session;if(this.isDND){r.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(r.on("ended",o=>{var t,s;this.stopVUMeter(r.id),this.context.logger.log("Session ended for",(s=(t=r._remote_identity)==null?void 0:t._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:es.CALL_ENDED,session:r,event:o});const a=this.getActiveCalls[r.id];a&&this.activeCallListRemove(a),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),this.initialStreamValue.getTracks().forEach(p=>p.stop()),this.initialStreamValue=null)}),r.on("progress",o=>{var a,t;this.context.logger.log("Session in progress for",(t=(a=r._remote_identity)==null?void 0:a._uri)==null?void 0:t._user),this.context.triggerListener({listenerType:es.CALL_PROGRESS,session:r,event:o})}),r.on("failed",o=>{var t,s;this.stopVUMeter(r.id),this.context.logger.log("Session failed for",(s=(t=r._remote_identity)==null?void 0:t._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:es.CALL_FAILED,session:r,event:o}),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const a=this.getActiveCalls[r.id];a&&this.activeCallListRemove(a),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),this.initialStreamValue.getTracks().forEach(p=>p.stop()),this.initialStreamValue=null)}),r.on("confirmed",o=>{var a,t;this.context.logger.log("Session confirmed for",(t=(a=r._remote_identity)==null?void 0:a._uri)==null?void 0:t._user),this.context.triggerListener({listenerType:es.CALL_CONFIRMED,session:r,event:o}),this.updateCall(r),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(n),r.direction==="outgoing"){const o=this.getActiveCalls[r.id].roomId;this.setActiveRoom(o)}}setMuteWhenJoin(n){this.muteWhenJoinEnabled=n,this.context.emit("changeMuteWhenJoin",n)}setMicrophoneSensitivity(n){if(n<0||n>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=n,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(n){this.speakerVolumeValue=n,Object.values(this.extendedCalls).forEach(r=>{r.audioTag&&(r.audioTag.volume=n,this.updateCall(r))})}setAutoAnswer(n){this.isAutoAnswer=n}setSelectedInputDevice(n){localStorage.setItem(fo.SELECTED_INPUT_DEVICE,n),this.selectedMediaDevices.input=n,this.context.emit("changeActiveInputMediaDevice",n)}setSelectedOutputDevice(n){localStorage.setItem(fo.SELECTED_OUTPUT_DEVICE,n),this.selectedMediaDevices.output=n,this.context.emit("changeActiveOutputMediaDevice",n)}setCallMetrics(n){const r={...n};delete r.callId,this.callMetrics={...this.callMetrics,[n.callId]:r},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(n){const r={...this.callMetrics};delete r[n],this.callMetrics={...r},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(n){const r=new rv(this.metricConfig),o=r.createProbe(n.connection,{cid:n._id}),a=[];let t;o.onreport=s=>{Object.entries(s.audio).forEach(([d,g])=>{g.direction==="inbound"&&!a.includes(d)&&(a.push(d),t=d)});const p=s.audio[t],_=iv(p,lv);_.callId=n._id,this.setCallMetrics(r)},this.context.subscribe(es.CALL_ENDED,s=>{s._id===n._id&&r.stopAllProbes()}),r.startAllProbes()}setupVUMeter(n,r){this.VUMeter.start(n,r)}stopVUMeter(n){this.VUMeter.stop(n)}async setupStream(){const n=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach(r=>r.stop()),this.initialStreamValue=null),this.initialStreamValue=n}async triggerAddStream(n,r){this.setIsMuted(this.muteWhenJoin||this.isMuted),this.initialStreamValue||await this.setupStream();const o=s_(this.initialStreamValue,this.microphoneInputLevel*2),a=this.isMuted||this.muteWhenJoin;o.getTracks().forEach(s=>s.enabled=!a),this.setActiveStream(o),await r.connection.getSenders()[0].replaceTrack(o.getTracks()[0]);const t=new MediaStream([n.track]);Zg(t,r,this.selectedOutputDevice,this.speakerVolume),this.setupVUMeter(t,r._id),this.getCallQuality(r),this.updateCall(r)}initCall(n,r){if(this.checkInitialized(),n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`);const o=this.context.call(`sip:${n}@${this.context.sipDomain}`,this.sipOptions);this.callAddingInProgress=o.id,r&&this.currentActiveRoomId!==void 0&&this.processRoomChange({callId:o.id,roomId:this.currentActiveRoomId}),o.connection.addEventListener("track",a=>{this.triggerAddStream(a,o)})}async processRoomChange({callId:n,roomId:r}){const o=this.extendedCalls[n].roomId;this.extendedCalls[n].roomId=r;const a=this.extendedCalls[n];return this.updateCall(a),await this.setActiveRoom(r),Promise.all([this.roomReconfigure(o),this.roomReconfigure(r)]).then(()=>{this.deleteRoomIfEmpty(o),this.deleteRoomIfEmpty(r)})}}class cv{constructor(n){this.context=n}get sipOptions(){return{...this.context.options.sipOptions}}initCall(n){if(n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${n}@${this.context.sipDomain}`,this.sipOptions),console.log("video call")}}class fv{constructor(n){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=n,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this.context))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(n){const r=this.extendedMessages[n];this.updateMSRPSession(r)}updateMSRPSession(n){this.activeMessages[n._id]=t_(n),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(n){this.activeMessages={...this.activeMessages,[n._id]:t_(n)},this.extendedMessages[n._id]=n,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(n,r){const o=this.msrpHistory[r.id]||[];o.push(n),this.msrpHistory={...this.msrpHistory,[r.id]:[...o]},this.context.emit("newMSRPMessage",{message:n,session:r})}messageTerminate(n){const r=this.extendedMessages[n];r._status!==8&&r.terminate()}addMessageSession(n){if(!n._id||this.getActiveMessages[n._id]!==void 0)return;const o=n;this.addMMSRPSession(o)}triggerMSRPListener({listenerType:n,session:r,event:o}){const a=this.context.listenersList[n];!a||!a.length||a.forEach(t=>{t(r,o)})}removeMMSRPSession(n){const r={...this.activeMessages};delete r[n],this.activeMessages={...r};const o={...this.extendedMessages};delete o[n],this.extendedMessages={...o},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(n){this.removeMMSRPSession(n._id)}newMSRPSessionCallback(n){const r=n.session;r.on("ended",o=>{this.triggerMSRPListener({listenerType:es.CALL_ENDED,session:r,event:o});const a=this.getActiveMessages[r.id];this.activeMessageListRemove(a)}),r.on("failed",o=>{this.triggerMSRPListener({listenerType:es.CALL_FAILED,session:r,event:o});const a=this.getActiveMessages[r.id];this.activeMessageListRemove(a)}),r.on("confirmed",o=>{this.triggerMSRPListener({listenerType:es.CALL_CONFIRMED,session:r,event:o}),this.updateMSRPSession(r)}),r.on("newMessage",o=>{this.addMSRPMessage(o,r)}),this.addMessageSession(r)}setIsMSRPInitializing(n){this.isMSRPInitializingValue=n,this.context.emit("isMSRPInitializingChanged",n)}initMSRP(n,r,o){if(n.length===0)return console.error("Target must be a valid string");const a=this.context.startMSRP(n,o);a.on("active",()=>{this.addMessageSession(a),a.sendMSRP(r),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(n,r){const o=this.extendedMessages[n];if(!o)throw new Error(`MSRP session with id ${n} doesn't exist!`);o.sendMSRP(r)}}const hu={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class _v extends Jg{constructor(n,r){if(!n.modules.length)throw new Error("options.modules should include at least 1 module");const o={...n.configuration,sockets:n.socketInterfaces.map(a=>new hT.WebSocketInterface(a))};super(o),this.initialized=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],n.pnExtraHeaders&&Object.keys(n.pnExtraHeaders).length&&this.registrator().setExtraContactParams(n.pnExtraHeaders),this.options=n,this.modules=n.modules,r&&eT(r)&&(this.logger=r)}on(n,r){return super.on(n,r)}off(n,r){return super.off(n,r)}emit(n,r){return super.emit(n,r)}get sipDomain(){return this.options.sipDomain}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(hu.AUDIO)&&(this.audio=new uv(this)),this.modules.includes(hu.MSRP)&&(this.msrp=new fv(this)),this.modules.includes(hu.VIDEO)&&(this.video=new cv(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.isReconnecting=!1}),this.on(this.disconnectedEventName,()=>{this.isReconnecting||(this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.isReconnecting=!0,this.stop(),this.setInitialized(!1),setTimeout(this.start.bind(this),5e3))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}subscribe(n,r){const a=!this.listenersList[n]||!this.listenersList[n].length?[r]:[...this.listenersList[n],r];this.listenersList={...this.listenersList,[n]:a}}removeIListener(n){const r={...this.listenersList};delete r[n],this.listenersList={...r}}triggerListener({listenerType:n,session:r,event:o}){const a=this.listenersList[n];!a||!a.length||a.forEach(t=>{t(r,o)})}setInitialized(n){this.initialized=n,this.emit("ready",n)}}return _v}();