@cloudflare/realtimekit 2.0.0-staging.1 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.js +1 -1
- package/dist/dependencies.txt +1 -1
- package/dist/index.cjs.js +1 -1
- package/dist/index.es.js +1 -1
- package/dist/index.rn.js +1 -1
- package/package.json +3 -2
package/dist/browser.js
CHANGED
|
@@ -15,4 +15,4 @@ ${this.message}`;try{let d=n&&!!i;r&&r.endsWith("00")&&i&&(d=!0),d&&i.error("Cli
|
|
|
15
15
|
`}this.midTransceiverMap.set(n.mid,n);const c=async d=>(this.logger.debug(`[SDP] send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),await this.pc.setRemoteDescription(d),n.mid);return this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(o,void 0,2)}]`),{offerSdp:o,callback:c,sender:n.sender,mid:n.mid}}addCustomEventListeners(){this.pc.addEventListener("datachannel",t=>{const{channel:e}=t;e.onmessage=r=>{this.safeEmit("datachannel",t.channel,String.fromCharCode(...new Uint8Array(r.data)))}})}}var Wf={},Hd={},ID={get exports(){return Hd},set exports(s){Hd=s}},Jf=ID.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(s){return s.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(s){return s.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(s){var t="candidate:%s %d %s %d %s %d typ %s";return t+=s.raddr!=null?" raddr %s rport %d":"%v%v",t+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(t+=" generation %d"),t+=s["network-id"]!=null?" network-id %d":"%v",t+=s["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(s){var t="ssrc:%d";return s.attribute!=null&&(t+=" %s",s.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(s){return s.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(s){return s.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(s){return"imageattr:%s %s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(s){return"simulcast:%s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var t="mediaclk:";return t+=s.id!=null?"id=%s %s":"%v%s",t+=s.mediaClockValue!=null?"=%s":"",t+=s.rateNumerator!=null?" rate=%s":"",t+=s.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Jf).forEach(function(s){var t=Jf[s];t.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})}),function(s){var t=function(c){return String(Number(c))===c?Number(c):c},e=function(c,d,l,u){if(u&&!l)d[u]=t(c[1]);else for(var h=0;h<l.length;h+=1)c[h+1]!=null&&(d[l[h]]=t(c[h+1]))},r=function(c,d,l){var u=c.name&&c.names;c.push&&!d[c.push]?d[c.push]=[]:u&&!d[c.name]&&(d[c.name]={});var h=c.push?{}:u?d[c.name]:d;e(l.match(c.reg),h,c.names,c.name),c.push&&d[c.push].push(h)},i=Hd,n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);s.parse=function(c){var d={},l=[],u=d;return c.split(/(\r\n|\r|\n)/).filter(n).forEach(function(h){var m=h[0],v=h.slice(2);m==="m"&&(l.push({rtp:[],fmtp:[]}),u=l[l.length-1]);for(var y=0;y<(i[m]||[]).length;y+=1){var w=i[m][y];if(w.reg.test(v))return r(w,u,v)}}),d.media=l,d};var o=function(c,d){var l=d.split(/=(.+)/,2);return l.length===2?c[l[0]]=t(l[1]):l.length===1&&d.length>1&&(c[l[0]]=void 0),c};s.parseParams=function(c){return c.split(/;\s?/).reduce(o,{})},s.parseFmtpConfig=s.parseParams,s.parsePayloads=function(c){return c.toString().split(" ").map(Number)},s.parseRemoteCandidates=function(c){for(var d=[],l=c.split(" ").map(t),u=0;u<l.length;u+=3)d.push({component:l[u],ip:l[u+1],port:l[u+2]});return d},s.parseImageAttributes=function(c){return c.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(o,{})})},s.parseSimulcastStreamList=function(c){return c.split(";").map(function(d){return d.split(",").map(function(l){var u,h=!1;return l[0]!=="~"?u=t(l):(u=t(l.substring(1,l.length)),h=!0),{scid:u,paused:h}})})}}(Wf);var kh=Hd,AD=/%[sdv%]/g,MD=function(s){var t=1,e=arguments,r=e.length;return s.replace(AD,function(i){if(t>=r)return i;var n=e[t];switch(t+=1,i){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}})},co=function(s,t,e){var r=t.format instanceof Function?t.format(t.push?e:e[t.name]):t.format,i=[s+"="+r];if(t.names)for(var n=0;n<t.names.length;n+=1){var o=t.names[n];t.name?i.push(e[t.name][o]):i.push(e[t.names[n]])}else i.push(e[t.name]);return MD.apply(null,i)},OD=["v","o","s","i","u","e","p","c","b","t","r","z","a"],DD=["i","c","b","a"],ND=function(s,t){t=t||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(n){n.payloads==null&&(n.payloads="")});var e=t.outerOrder||OD,r=t.innerOrder||DD,i=[];return e.forEach(function(n){kh[n].forEach(function(o){o.name in s&&s[o.name]!=null?i.push(co(n,o,s)):o.push in s&&s[o.push]!=null&&s[o.push].forEach(function(c){i.push(co(n,o,c))})})}),s.media.forEach(function(n){i.push(co("m",kh.m[0],n)),r.forEach(function(o){kh[o].forEach(function(c){c.name in n&&n[c.name]!=null?i.push(co(o,c,n)):c.push in n&&n[c.push]!=null&&n[c.push].forEach(function(d){i.push(co(o,c,d))})})})}),i.join(`\r
|
|
16
16
|
`)+`\r
|
|
17
17
|
`},Ti=Wf,VD=ND,qd=VD,yi=Ti.parse;Ti.parseParams,Ti.parseFmtpConfig,Ti.parsePayloads,Ti.parseRemoteCandidates,Ti.parseImageAttributes,Ti.parseSimulcastStreamList;class jd extends Ph{constructor(e,r){super(e);p(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new jd(e,r)}get name(){return"Firefox60"}async send({track:e,encodings:r,codecOptions:i,screenShare:n}){this._assertSendDirection();const o=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(e,{direction:"sendonly",streams:[n?this._sendScreenShareStream:this._sendWebStream],...o});if(!this.supportsSendEncodings&&r){r.reverse();const h=c.sender.getParameters();h.encodings=r,await c.sender.setParameters(h)}const d=(h,m)=>{var U;const v=yi(h),y=v.media[v.media.length-1],w=y.rtp.filter(L=>m.some(H=>H.name===L.codec)),C=y.fmtp.filter(L=>w.some(H=>H.payload===L.payload)),P=(U=y.rtcpFb)==null?void 0:U.filter(L=>w.some(H=>H.payload===L.payload)),N=w.map(L=>L.payload);return v.media[v.media.length-1].rtp=w,v.media[v.media.length-1].fmtp=C,v.media[v.media.length-1].rtcpFb=P,v.media[v.media.length-1].payloads=N.join(" "),qd(v)},l=await this.pc.createOffer();if(l.sdp=d(l.sdp,i),this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),await this.pc.setLocalDescription(l),e==="audio"||e.kind==="audio"){const{enableDtx:h,enableStereo:m}=this,v=this.enableHighBitrate?m?128e3:64e3:m?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${m?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${v}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:l,callback:async h=>(this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),await this.pc.setRemoteDescription(h),c.mid),sender:c.sender,mid:c.mid}}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters(),o=n.encodings.length-1-r;n.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),await i.sender.setParameters(n)}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:r}=e;r.onmessage=async i=>{const n=await i.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(n)))}})}}class Ch extends Ph{static createFactory(t){return()=>new Ch(t)}get name(){return"Safari12"}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection(),this.logger.debug("Safari12::creating new transceiver");const n=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e}),o=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`Safari12::senders available params: ${JSON.stringify(o)}`);const c=[];r&&r.length>0&&r.forEach(u=>{var m;const h=o.codecs.find(v=>v.mimeType.includes(u.name));if(u.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(u.parameters)}`);const v=((m=h.sdpFmtpLine)==null?void 0:m.split(";"))||[];v.push(...u.parameters);const y=[...new Set(v).values()];h.sdpFmtpLine=y.join(";")}c.push(h)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(c)}`),n.setCodecPreferences(c);const d=await this.pc.createOffer();if(await this.pc.setLocalDescription(d),t==="audio"||t.kind==="audio"){const{enableStereo:u,enableDtx:h}=this,m=this.enableHighBitrate?u?128e3:64e3:u?64e3:32e3;d.sdp=d.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${u?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${m}`)}return this.midTransceiverMap.set(n.mid,n),{offerSdp:d,callback:async u=>(this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),await this.pc.setRemoteDescription(u),n.mid),sender:n.sender,mid:n.mid}}addCustomEventListeners(){this.pc.ondatachannel=t=>{const{channel:e}=t;e.onmessage=async r=>{const i=String.fromCharCode(...new Uint8Array(r.data));this.safeEmit("datachannel",t.channel,i)}}}}function LD(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}class xD extends Fd{constructor(e,r){var i;super(e);g(this,Vs);g(this,zo);g(this,El);g(this,bl);p(this,"rtpReceiver");p(this,"id");p(this,"localId");p(this,"producerId");p(this,"producingTransportId");p(this,"mimeType");p(this,"track");p(this,"peerId");p(this,"appData");p(this,"transceiver");g(this,Ko,void 0);g(this,Wi,void 0);g(this,Ns,void 0);g(this,yl,void 0);this.id=r.id,this.localId=r.localId,f(this,Ko,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,f(this,Ns,!1),this.producerId=r.producerId,this.track=r.track,f(this,Wi,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,$(this,El,eS).call(this),f(this,yl,e)}get closed(){return a(this,Ns)}get kind(){return this.track.kind}get paused(){return a(this,Wi)}close(e,r){a(this,Ns)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,Vs,ai)),f(this,Ns,!0),r&&($(this,bl,tS).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(a(this,Ns))throw new _t("closed");return a(this,Ko).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",a(this,Vs,ai)),a(this,Ns)){this.logger.error("consumer::pause() | Consumer closed",a(this,Vs,ai));return}f(this,Wi,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,Vs,ai)),a(this,Ns)){this.logger.error("Consumer::resume() | Consumer closed",a(this,Vs,ai));return}f(this,Wi,!1),this.track.enabled=!0,this.safeEmit("resume")}}Ko=new WeakMap,Wi=new WeakMap,Ns=new WeakMap,yl=new WeakMap,Vs=new WeakSet,ai=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},zo=new WeakSet,Xh=function(){this.logger.debug('Consumer::track "ended" event',a(this,Vs,ai)),this.safeEmit("trackended")},El=new WeakSet,eS=function(){this.track.addEventListener("ended",$(this,zo,Xh).bind(this))},bl=new WeakSet,tS=function(){try{this.track.removeEventListener("ended",$(this,zo,Xh)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...a(this,Vs,ai),error:e})}};class UD extends Fd{constructor(e,r){var i,n;super(e);g(this,Bt);p(this,"id");p(this,"localId");g(this,Ts,void 0);p(this,"kind");p(this,"appData");p(this,"rtpSender");g(this,fa,void 0);g(this,va,void 0);g(this,Ji,void 0);g(this,is,!1);g(this,it,void 0);g(this,Xr,void 0);g(this,Sa,void 0);g(this,wl,void 0);this.id=r.id,this.localId=r.localId,f(this,it,r.track),this.kind=(i=r.track)==null?void 0:i.kind,f(this,Xr,r.disableTrackOnPause?!((n=r.track)!=null&&n.enabled):!1),f(this,Sa,void 0),f(this,fa,r.stopTracks),f(this,va,r.disableTrackOnPause),f(this,Ji,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),f(this,Ts,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),f(this,wl,e)}get closed(){return a(this,is)}get track(){return a(this,it)}get paused(){return a(this,Xr)}get maxSpatialLayer(){return a(this,Sa)}async close(e){if(a(this,is))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,Bt,Ps)),f(this,is,!0),this._destroyTrack(),e===lo){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await a(this,Ts).stopSending(this.localId),{answer:n}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(n)}async getStats(){if(a(this,is))throw new _t("closed");return a(this,Ts).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",a(this,Bt,Ps)),a(this,is)&&this.logger.error("Producer::pause() | Producer closed",a(this,Bt,Ps)),f(this,Xr,!0),a(this,it)&&a(this,va)&&(a(this,it).enabled=!1),a(this,Ji)&&a(this,Ts).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,Bt,Ps)),a(this,is)){this.logger.error("Producer::resume() | Producer closed",a(this,Bt,Ps));return}f(this,Xr,!1),a(this,it)&&a(this,va)&&(a(this,it).enabled=!0),a(this,Ji)&&a(this,Ts).replaceTrack(this.localId,a(this,it)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,a(this,Bt,Ps)),a(this,is)){if(e&&a(this,fa))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...a(this,Bt,Ps),error:r})}throw new _t("closed")}else if(e&&e.readyState==="ended")throw new _t("track ended");if(e===a(this,it)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,a(this,Bt,Ps));return}(!a(this,Ji)||!a(this,Xr))&&await a(this,Ts).replaceTrack(this.localId,e),this._destroyTrack(),f(this,it,e),this._handleTrack()}async setMaxSpatialLayer(e){if(a(this,is))throw new _t("closed");if(this.kind!=="video")throw new oo("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await a(this,Ts).setMaxSpatialLayer(this.localId,e),f(this,Sa,e)}async setRtpEncodingParameters(e){if(a(this,is))throw new _t("closed");if(typeof e!="object")throw new TypeError("invalid params");await a(this,Ts).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,Bt,Ps)),this.safeEmit("trackended",this.track.id)}_handleTrack(){a(this,it)&&a(this,it).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(a(this,it))try{a(this,it).removeEventListener("ended",this._onTrackEnded),a(this,fa)&&a(this,it).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...a(this,Bt,Ps),error:r})}}}Ts=new WeakMap,fa=new WeakMap,va=new WeakMap,Ji=new WeakMap,is=new WeakMap,it=new WeakMap,Xr=new WeakMap,Sa=new WeakMap,wl=new WeakMap,Bt=new WeakSet,Ps=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function Kf(s){return typeof s=="object"&&!Array.isArray(s)&&s!==null}function Rh(s){return Math.random().toString(36).substring(2,2+s)}const Gd=1;function zf(s){const t=s;return delete t.payload._bolt,t}function $D(s){return s.payload&&Kf(s.payload)}function BD(s){var t,e;return $D(s)&&(e=(t=s.payload._bolt)==null?void 0:t.id)!=null?e:""}const Ta=class extends at.EventEmitter{constructor(e,r,i,n){super();p(this,"channel");p(this,"queue");p(this,"serverProtocolVersion");g(this,Zr,new Map);g(this,Pl,void 0);g(this,Ki,void 0);p(this,"respond",(e,r,i=!1)=>{let n;i?n=Ta.createErrorResponse(e,r):n=Ta.createResponse(e,r),this.channel.send(JSON.stringify(n))});p(this,"notify",e=>{const r=Ta.createNotification(e);this.channel.send(JSON.stringify(r))});p(this,"request",async e=>{const r=Ta.createRequest(e),i=new Promise((n,o)=>{const{id:d}=r.payload._bolt,l={id:d,method:r.type,resolve:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),n(u))},timer:setTimeout(()=>{this.queue.delete(d)&&o(new Error(`request timeout for message id: ${d}`))},2e4),cancel:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),o(u))}};this.queue.set(d,l)});return this.channel.send(JSON.stringify(r)),i});p(this,"send",e=>{const r=JSON.stringify(e),i=16384;if(r.length>i){const n=i-200,o=Math.ceil(r.length/n),c=[];for(let l=0;l<o;l+=1){const u=l*n,h=(l+1)*n;c.push(r.slice(u,h))}const d=fn();for(let l=0;l<o;l+=1){const u=c[l],m=JSON.stringify({id:d,count:o,chunkIndex:l,chunk:u});a(this,Ki).debug(`Sending message chunk over dc: ${m}`),this.channel.send(m)}}else a(this,Ki).debug(`Sending message over dc: ${r}`),this.channel.send(r)});p(this,"processMessage",e=>{var i;a(this,Zr).has(e.id)||a(this,Zr).set(e.id,[]);const r=a(this,Zr).get(e.id);if(r[e.chunkIndex]=e,(r==null?void 0:r.length)===e.count&&!r.some(n=>n===void 0)){const n=a(this,Zr).get(e.id),o=n==null?void 0:n.reduce((d,l)=>d+l.chunk,"");a(this,Zr).delete(e.id);const c=JSON.parse(o);if(!c.payload||!Kf(c.payload))throw new Error("corrupted incoming message over dc",{cause:{code:"CORRUPT_DC_MESSAGE",values:c}});if(this.processBoltHandshake(c))return;if(this.serverProtocolVersion=(i=c.payload._bolt)==null?void 0:i.version,!this.processResponseMsg(c))return c}});p(this,"processResponseMsg",e=>{const{id:r}=e.payload._bolt,i=this.queue.get(r);return i?(a(this,Ki).debug(`resolving pending request with id: ${r}, complete response: ${JSON.stringify(e)}`),e.type==="error"?i.cancel(zf(e)):i.resolve(zf(e)),!0):!1});p(this,"processBoltHandshake",e=>{var r,i;return e.type==="_bolt"||e.type==="handshake"?(this.respond((i=(r=e.payload._bolt)==null?void 0:r.id)!=null?i:Rh(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1});this.label=i,this.transportId=n,f(this,Pl,e),f(this,Ki,e.getValue("logger")),this.channel=r,this.queue=new Map}};let Ei=Ta;Zr=new WeakMap,Pl=new WeakMap,Ki=new WeakMap,p(Ei,"createRequest",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,_bolt:{id:Rh(8),type:"REQUEST",version:Gd}}}}),p(Ei,"createResponse",(e,r)=>{var i;if((i=r.payload)!=null&&i._bolt)throw new Error("rpc fields are internal values");return{type:r.type,payload:{...r.payload,_bolt:{id:e,type:"RESPONSE",version:Gd}}}}),p(Ei,"createNotification",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,bolt:{id:Rh(8),type:"NOTIFY",version:Gd}}}}),p(Ei,"createErrorResponse",(e,r)=>({type:"error",payload:{error:r.message,_bolt:{id:e,type:"RESPONSE",version:Gd}}}));const lo="transport closed",ya=class extends Fd{constructor(e,{id:r,direction:i,handlerFactory:n,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:h}){var w,C,P;super(e);p(this,"awaitQueue");p(this,"observer");p(this,"id");p(this,"serverId");p(this,"direction");p(this,"maxSctpMessageSize");p(this,"handler");p(this,"connectionState","new");p(this,"producers");p(this,"consumers");p(this,"datachannels");p(this,"connected",!1);p(this,"eventsDCReadyPromise");p(this,"eventsDCReadyPromiseResolver");p(this,"eventsDCFailureTimer");p(this,"transportConnectionPromise");p(this,"consumerTrackEvents");p(this,"unknownTracksMap");p(this,"appData");g(this,zi,void 0);f(this,zi,e);const m=e.getValue("logger");m.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const v=LD(l,{});delete v.iceServers,delete v.iceTransportPolicy,delete v.bundlePolicy,delete v.rtcpMuxPolicy,delete v.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new wh(m,!0),this.handler=n(),this.handler.enableHighBitrate=(w=h==null?void 0:h.enableHighBitrate)!=null?w:!1,this.handler.enableStereo=(C=h==null?void 0:h.enableStereo)!=null?C:!1,this.handler.enableDtx=(P=h==null?void 0:h.enableDtx)!=null?P:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=u||{};const y=3e4;this.transportConnectionPromise=new Promise(N=>{const U=setTimeout(()=>{m.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),N(!1)},y);this.once("connected",()=>{clearTimeout(U),N(!0)}),this.once("disconnect",()=>{clearTimeout(U),N(!1)}),this.once("close",()=>{clearTimeout(U),N(!1)})}),this.eventsDCReadyPromise=new Promise(N=>{this.eventsDCReadyPromiseResolver=N}),this.handler.on("@connectionstatechange",N=>{N!==this.connectionState&&(this.logger.debug(`connection state changed to ${N}`),this.connectionState=N,N==="connected"&&(this.connected=!0,this.emit("connected")),N==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(N==="failed"||N==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",N))}),this.handler.on("@icecandidate",({candidate:N})=>{this.closed||this.safeEmit("icecandidate",N)}),this.handler.on("dc_open",N=>{let U=this.datachannels.get(N.label);U||(U||(U=new Ei(a(this,zi),N,N.label,this.serverId),this.datachannels.set(N.label,U)),this.eventsDCFailureTimer=setTimeout(()=>{N.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",N.label))},5e3))}),this.handler.on("datachannel",(N,U)=>{N.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const L=this.datachannels.get(N.label);if(!L){this.logger.error("unregistered datachannel for message",{rtcChannel:{label:N.label,message:U}});return}try{const H=JSON.parse(U);this.logger.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:H.id,count:H.count,chunkIndex:H.chunkIndex,chunk:H.chunk,transprtId:this.serverId}});const F=L.processMessage(H);if(!F)return;this.logger.debug(`datachannel message with id:${H.id} on transport:${this.serverId}complete - ${JSON.stringify(F)}`),this.emit(`datachannel:${N.label}`,L.label,F)}catch(H){this.logger.error("error parsing message",{error:H})}})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId=e}getDatachannel(e){return this.datachannels.get(e)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(this.logger.debug("Transport close called"),this.connectionState="closed",this.awaitQueue.stop(),this.awaitQueue=void 0,this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(lo).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(lo)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new _t("closed");return this.handler.getTransportStats()}async connect(e){try{if(await this.awaitQueue.push(async()=>{const{offerSdp:r,callback:i}=await this.handler.connect(),{transportId:n,answer:o}=await e(r);this.setServerId(n),await i(o)}),!await this.transportConnectionPromise)throw new Error("ice connection failed")}catch(r){throw this.logger.error("transport failed to connect:",{error:r}),r}}async restartIce(){if(this.logger.debug("restartIce()"),this.closed)throw new _t("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new oo("not a sending Transport");if(r.readyState==="ended")throw new _t("track ended");if(i&&typeof i!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!await this.transportConnectionPromise)throw new Dr("transport not connected");return!0}async produce(e,r){if(!await this.canProduce(e))throw new Error("Cannot produce");const{track:n,encodings:o,codecOptions:c,stopTracks:d=!0,disableTrackOnPause:l=!0,zeroRtpOnPause:u=!1,appData:h={}}=e;this.logger.debug(`produce() [track:${n.id}]`);const{producerId:m,localId:v,rtpSender:y}=await this.awaitQueue.push(async()=>{const{offerSdp:w,callback:C,sender:P,mid:N}=await this.handler.send({track:n,encodings:o,codecOptions:c,screenShare:h==null?void 0:h.screenShare}),{answer:U,producerId:L}=await r({offer:w,kind:n.kind,paused:l?!n.enabled||Object.hasOwn(n,"fakeTracks"):!1,appData:{...h||{},mid:N},codecOptions:c,producingTransportId:this.serverId}),H=await C(U);return{producerId:L,localId:H,rtpSender:P}},"Transport.produce");return this.createProducerObject({id:m,localId:v,track:n,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:h,handler:this.handler,rtpSender:y})}async createProducerObject(e){const r=new UD(a(this,zi),e);return this.producers.set(r.id,r),r.once("close",()=>{this.producers.delete(r.id)}),this.emit("newproducer",r),r}async closeProducer(e){await this.awaitQueue.push(e.close.bind(e),"Transport.closeProducer")}async canConsume(){if(this.closed)throw new _t("closed");if(this.direction!=="recv")throw new oo("not a receiving transport");if(!await this.transportConnectionPromise)throw new Dr("transport not connected");return!0}async consume(e,r,i){return this.awaitQueue.push(async()=>{const n={},{consumerStates:o,sessionDescription:c,failedProducers:d}=await r(e);o.forEach((u,h)=>{n[h]=this.createConsumerObjectAndWaitForTrack({...u,producerId:h})}),c&&(this.logger.info("Session description found, sending negotiation request"),await i(c));const l=[];return await Promise.all(Object.entries(n).map(([u,h])=>h.then(m=>l.push(m)).catch(()=>{this.logger.error(`Failed to create consumer object, producer: ${u}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:l,failedProducers:d}},"Transport.consume",{producersLength:e.length})}static parseCodecAndFmtpMappings(e,r){const i=yi(e.sdp),n={};return i.media.forEach(o=>{r.includes(o.mid.toString())&&(n[o.mid.toString()]={rtp:o.rtp,fmtp:o.fmtp,payloads:o.payloads,rtcpFb:o.rtcpFb})}),n}static setCodecAndFmtpMappings(e,r,i){const n=yi(e.sdp);return n.media=n.media.map(c=>{if(r.includes(c.mid.toString())){const d={...c};return d.rtp=i[c.mid.toString()].rtp,d.fmtp=i[c.mid.toString()].fmtp,d.payloads=i[c.mid.toString()].payloads,d.rtcpFb=i[c.mid.toString()].rtcpFb,d}return c}),{...e,sdp:qd(n)}}static parseHeaderExtensionMappings(e){const r=yi(e.sdp),i={};return r.media.forEach(n=>{i[n.mid]=n.ext}),i}static setHeaderExtensionMappings(e,r){const i=yi(e.sdp);return i.media=i.media.map(o=>{const c={...o};return c.ext=r[o.mid],c}),{...e,sdp:qd(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),n=ya.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=ya.parseHeaderExtensionMappings(this.handler.pc.remoteDescription);this.logger.info("Stopping transceivers",{consumerIds:e.map(({id:l})=>l)}),e.forEach(l=>l.close(void 0,!0));let c=await this.handler.pc.createOffer();this.logger.info("[SDP] Created offer for closing consumers",{sdp:c.sdp}),c=ya.setCodecAndFmtpMappings(c,i,n),c=ya.setHeaderExtensionMappings(c,o),this.logger.info("[SDP] Updated codec and fmtp mappings in close consumer offer",{sdp:c.sdp}),await this.setLocalDescription(c),this.logger.info("Successfully set local description in close consumers");const d=await r(e,c);this.logger.info("[SDP] Received answer in close consumers",{sdp:d.sdp}),await this.setRemoteDescription(d),this.logger.info("[SDP] Remote description was set successfully in close consumers",{sdp:d.sdp})}catch(i){this.logger.error("Failed to close consumers",{error:i})}}async setRemoteOffer(e){try{this.logger.info("[SDP] Received offer from SFU",{sdp:e.sdp}),await this.setRemoteDescription(e);const r=await this.handler.pc.createAnswer();this.logger.info("[SDP] Created answer corresponding to received offer",{sdp:r.sdp});const i=yi(r.sdp);return i.media=i.media.map(n=>{if(n.type==="audio"){const o={...n},c=o.fmtp.find(l=>l.payload===111);return c&&(c.config+=";stereo=1;sprop-stereo=1"),o.rtcpFb||(o.rtcpFb=[]),o.rtcpFb.some(l=>l.type==="nack")||o.rtcpFb.push({payload:parseInt(o.payloads,10),type:"nack"}),o}return n}),r.sdp=qd(i),this.logger.info("[SDP] Setting munged SDP",{sdp:r.sdp}),await this.setLocalDescription(r),this.logger.info("[SDP] Successfully set local description",{sdp:r.sdp}),r}catch(r){throw this.logger.error("Set remote offer failed",{error:r}),r}}_ontrack(e){const{track:r,transceiver:i}=e;this.logger.info(`track event received [trackId: ${r.id}] [mid: ${i.mid}]`);const n=`${i.mid}:${r.kind}`;r.addEventListener("ended",()=>{this.logger.info(`rtc consumer track ended [trackId: ${r.id}]`),this.unknownTracksMap.delete(n)});const o=this.consumerTrackEvents.get(n);o?(o(r,i),this.consumerTrackEvents.delete(n)):(this.logger.warn(`track event handler not found ${n}`),this.unknownTracksMap.set(n,e))}sendErrorOverDC(e,r,i){const n=this.getDatachannel(e);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});n.respond(r,i,!0)}sendResponseOverDC(e,r,i){const n=this.getDatachannel(e);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});n.respond(r,i)}async createConsumerObjectAndWaitForTrack(e){const{consumerId:r,producerId:i,producingPeerId:n,producingTransportId:o,streamId:c,paused:d,screenShare:l,appData:u,kind:h,mimeType:m}=e,v=`${c}:${h}`,y={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(w,C)=>{const P=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${v} producingPeerId: ${n}`),this.consumerTrackEvents.delete(v),y.isTimedout=!0,C(y)},5e3),N=(L,H)=>{try{if(L.readyState==="ended")clearTimeout(P),C(y);else{const F=L;F.enabled=!0,this.handler.midTransceiverMap.set(H.mid,H);const Z=new xD(a(this,zi),{id:r,localId:H.mid,transceiver:H,track:F,paused:d,producerId:i,producingPeerId:n,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:n},rtpReceiver:H.receiver,mimeType:m});this.consumers.set(r,Z),Z.once("close",()=>{this.consumers.delete(Z.id),this.handler.midTransceiverMap.delete(H.mid)}),this.logger.info("consumer created for ",{consumer:{id:r,kind:h,appData:{screenShare:l},peerId:n,producerId:i}}),this.emit("newconsumer",Z),clearTimeout(P),w(Z)}}catch(F){this.logger.warn("error while creating consumer:",F),clearTimeout(P),C(y)}},U=this.unknownTracksMap.get(v);U?(this.logger.info(`track event already received [trackId: ${U.track.id}] [mid: ${U.transceiver.mid}]`),this.unknownTracksMap.delete(v),N(U.track,U.transceiver)):(this.logger.info(`Registering onTrack handler for key ${v} [producingPeerId: ${n}]`),this.consumerTrackEvents.set(v,N))})}async setRemoteDescription(e){await this.handler.pc.setRemoteDescription(e)}async setLocalDescription(e){this.logger.debug(`[SDP] ${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),await this.handler.pc.setLocalDescription(e)}async sendDataChannelMessage(e,r){const i=this.getDatachannel(e);if(!i)throw PD("DC_NOT_READY",`${e} datachannel not ready`);const n=(await i.request(r)).payload;return this.logger.info(`sendDataChannelMessage::response ${JSON.stringify(n)}`),n}};let Ih=ya;zi=new WeakMap;function FD(s){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){s.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return s.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=lp.getParser(t),r=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=55",chromium:">=55"}))return;if(e.satisfies({firefox:">=110"}))return"Firefox110";if(e.satisfies({firefox:">=60"}))return"Firefox60";if(e.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||e.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(e.satisfies({safari:">=11"})||e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return;if(r.name&&r.name.toLowerCase()==="blink"){const i=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return i?Number(i[1])>=74?"Chrome74":void 0:"Chrome74"}if(r.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;s.warn("Device::this._detectDevice() | browser not supported");return}s.warn("Device::this._detectDevice() | unknown device")}class HD{constructor(t,{handlerName:e,handlerFactory:r}={}){p(this,"handlerFactory");g(this,pr,void 0);g(this,Yi,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),f(this,pr,t),f(this,Yi,i),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)a(this,Yi).debug(`Device::constructor() | handler given: ${e}`);else if(e=FD(a(this,Yi)),e)a(this,Yi).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=_h.createFactory(a(this,pr));break;case"Safari12":this.handlerFactory=Ch.createFactory(a(this,pr));break;case"Firefox60":this.handlerFactory=jd.createFactory(a(this,pr),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=jd.createFactory(a(this,pr),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=fn();return new Ih(a(this,pr),{id:e,...t,handlerFactory:this.handlerFactory})}}pr=new WeakMap,Yi=new WeakMap;const qD=2e3;class jD extends at.EventEmitter{constructor(e,r){super();g(this,Pa);g(this,Zo);g(this,_l);g(this,ec);g(this,kl);g(this,Cl);g(this,Rl);g(this,Il);g(this,Al);g(this,tc);g(this,sc);p(this,"context");g(this,Ea,void 0);g(this,lt,void 0);g(this,ut,void 0);g(this,Yo,void 0);g(this,Qo,void 0);g(this,Qi,void 0);g(this,ba,void 0);g(this,Xo,void 0);g(this,wa,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});g(this,Xi,void 0);g(this,Ls,"all");this.context=e,f(this,Qi,r),f(this,Ea,new HD(e)),f(this,ba,new RD(r)),f(this,Xo,hs),a(this,Pa,nu).mediaState={send:{state:Nr.NEW},recv:{state:Nr.NEW}},bn(this.context,"forceRelay")&&f(this,Ls,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,Ls)}`),$(this,Zo,Zh).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,Qi)}get socketHandler(){return a(this,ba)}get sendTransport(){return a(this,lt)}get recvTransport(){return a(this,ut)}get events(){return a(this,Xo)}set sendTransportConnectedCallback(e){f(this,Yo,e)}set recvTransportConnectedCallback(e){f(this,Qo,e)}async setupTransports(e){await $(this,_l,sS).call(this,e);let r,i;e.send&&(r=$(this,ec,ep).call(this,a(this,lt)).then(n=>{try{a(this,Yo).call(this,n)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=$(this,ec,ep).call(this,a(this,ut)).then(n=>{try{a(this,Qo).call(this,n)}catch(o){this.logger.error("Failed to run recv transport callback")}})),await Promise.all([r,i])}stopTransports(e){var r,i;if(e.send&&this.sendTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,lt);this.logger.info("Closing send transport",{transport:{id:n,serverId:o,type:c}}),a(this,lt).close(),a(this,lt).removeAllListeners(),f(this,lt,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,ut);this.logger.info("Closing recv transport",{transport:{id:n,serverId:o,type:c}}),(r=a(this,ut))==null||r.close(),(i=a(this,ut))==null||i.removeAllListeners(),f(this,ut,void 0)}$(this,Zo,Zh).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}Ea=new WeakMap,lt=new WeakMap,ut=new WeakMap,Yo=new WeakMap,Qo=new WeakMap,Qi=new WeakMap,ba=new WeakMap,Xo=new WeakMap,wa=new WeakMap,Xi=new WeakMap,Ls=new WeakMap,Pa=new WeakSet,nu=function(){return this.context.getValue("connectionHandler")},Zo=new WeakSet,Zh=function(){f(this,Xi,{send:void 0,recv:void 0})},_l=new WeakSet,sS=async function(e){var o,c,d,l,u,h,m,v;bn(this.context,"forceRelay")&&f(this,Ls,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,Ls)}`);const n=await wt().getICEServers().catch(y=>(this.logger.warn(`failed to get iceservers from server: ${y.message}`),[]));e.send&&$(this,Cl,iS).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(o=this.context.getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(l=(d=(c=this.context.getValue("defaults").mediaConfiguration)==null?void 0:c.audio)==null?void 0:d.enableHighBitrate)!=null?l:!1,enableStereo:(m=(h=(u=this.context.getValue("defaults").mediaConfiguration)==null?void 0:u.audio)==null?void 0:h.enableStereo)!=null?m:!1,enableDtx:!1},iceTransportPolicy:a(this,Ls)}),e.recv&&$(this,Rl,nS).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(v=this.context.getValue("modules").e2ee)==null?void 0:v.enabled},iceTransportPolicy:a(this,Ls)})},ec=new WeakSet,ep=async function(e){const{id:r,serverId:i,direction:n}=e;$(this,Il,aS).call(this,e);try{return await Gf(async(c,d)=>{c>0&&this.logger.debug(`Retrying transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:n}});try{if(e.closed)throw new Dr("Cannot reconnect closed transport");await $(this,kl,rS).call(this,e)}catch(l){if(l instanceof Dr){d(l);return}throw this.logger.error("Failed to connect transport, retrying",{transport:e,error:l}),l}},{delayTime:100,strategy:"exponential",maxRetryCount:15}),e}catch(o){throw this.logger.error(`Failed to connect send transport after retry: ${e.id}`,{error:o,transport:{id:r,serverId:i,type:n}}),e.close(),e.removeAllListeners(),o}},kl=new WeakSet,rS=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!a(this,Qi).isConnected)throw new Dr("Socket is not connected");if(e.connectionState==="closed")throw new Dr("Transport is closed");try{await e.connect(n=>$(this,Al,oS).call(this,i,n)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(n){throw a(this,wa).transportFailureCount[i]+=1,n.message==="ice connection failed"?new Dr(n.message):n}},Cl=new WeakSet,iS=function(e){var r,i;if(a(this,lt)&&a(this,lt).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=a(this,lt))==null?void 0:r.id,serverId:(i=a(this,lt))==null?void 0:i.serverId,type:"send"}});return}f(this,lt,a(this,Ea).createTransport({...e,direction:"send"})),this.context.getValue("callstats").configureSendTransport(a(this,lt))},Rl=new WeakSet,nS=function(e){var r,i;if(a(this,ut)&&a(this,ut).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=a(this,ut))==null?void 0:r.id,serverId:(i=a(this,ut))==null?void 0:i.serverId,type:"recv"}});return}f(this,ut,a(this,Ea).createTransport({...e,direction:"recv"})),this.context.getValue("callstats").configureRecvTransport(a(this,ut))},Il=new WeakSet,aS=function(e){const{direction:r,id:i}=e;e.on("connectionstatechange",async n=>{$(this,sc,sp).call(this,{state:n,direction:r}),this.logger.info(`Transport connection state changed for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:n}});const o=()=>{const c=a(this,Xi)[r];c!==void 0&&(clearTimeout(c),a(this,Xi)[r]=void 0)};switch(n){case"connected":o(),a(this,wa).lastConnectionTime=performance.now();break;case"disconnected":a(this,Xi)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await $(this,tc,tp).call(this,e.direction)},qD);break;case"failed":if(e.closed)return;o(),this.logger.warn(`${r} transport is in failed state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await $(this,tc,tp).call(this,e.direction);break}}),e.on("icecandidate",async n=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:n})}),e.on("datachannel:events",async(n,o)=>{var c,d;this.logger.debug("Got data channel message on event:",{rtcChannel:{label:n,message:o}});try{switch(o.type){case"handshake":{const l={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,BD(o),l);break}case"hub-disconnect":{this.logger.debug(`media hub disconnected, full_reconnect: ${(c=o.payload)==null?void 0:c.full_reconnect}`),((d=o.payload)==null?void 0:d.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":break;default:break}}catch(l){this.logger.error(`Unable to handle the incoming datachannel message on channel ${n}`)}}),e.on("dc_error",()=>{e.direction==="recv"&&(this.logger.warn("Events datachannel did not open in 5s"),this.handleErrors("reconnectRecvTransport"))})},Al=new WeakSet,oS=async function(e,r){const i=e==="recv";try{const{sdp:n,type:o}=r,c={consuming:i,description:{sdp:n,type:o,target:i?Ws.SUBSCRIBER:Ws.PUBLISHER},producers:[]};return a(this,ba).connectTransport(c)}catch(n){throw this.logger.error(`Error in ${e} transport connection:`,{error:n}),n}},tc=new WeakSet,tp=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),a(this,Qi).isConnected&&a(this,wa).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),f(this,Ls,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:a(this,lt)}),this.context.getValue("peerSessionStore").emit(k.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,ut)}),this.context.getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}$(this,sc,sp).call(this,{state:Nr.CONNECTED,direction:e})},sc=new WeakSet,sp=function(e){const{state:r,direction:i}=e;a(this,Pa,nu).mediaState[i]={state:r},this.context.getValue("peerSessionStore").emit(k.TRANSPORT_STATE_UPDATE,{transport:i,...a(this,Pa,nu).mediaState[i]})};class GD{constructor(t,e,r,i,n){g(this,Ml,void 0);g(this,ns,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=n,f(this,Ml,t),f(this,ns,t.getValue("logger"))}async create(t){if(!t||t&&t.length===0)throw new Error("List of producers is required");const e=new Map,r=[];t.forEach(d=>{const{producingPeerId:l,producerId:u,producingTransportId:h}=d,m={simulcast:{preferredRid:"f",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}};e.set(u,l),r.push({producingPeerId:l,producerId:u,producingTransportId:h,...m})});const i=await this.socketHandler.consume({requests:r,consumingTransportId:this.recvTransport.serverId}),n=new Map;t.forEach(d=>n.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const u=n.get(d);if(!u)return;if(l.errorCode){a(this,ns).warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),c.push({...u,errorCode:l.errorCode});return}let h={};try{h=JSON.parse(l.producerState.appData)}catch(m){}o.set(d,{consumerId:l.consumerId,producingTransportId:u.producingTransportId,producingPeerId:u.producingPeerId,kind:u.kind,paused:u.pause,streamId:l.producerTrack.streamId,trackId:l.producerTrack.trackId,screenShare:u.screenShare,mimeType:u.mimeType,appData:h})}),{consumerStates:o,sessionDescription:i.sessionDescription,failedProducers:c}}async negotiate(t){try{a(this,ns).info("Negotiating socket consumer",{transport:this.recvTransport}),a(this,ns).debug(`[SDP] setting remote offer: ${JSON.stringify(t)} on recvTransport`,{transport:this.recvTransport});const e=await this.recvTransport.setRemoteOffer(t),r={transportId:this.recvTransport.serverId,description:{sdp:e.sdp,type:e.type,target:Ws.SUBSCRIBER}};return a(this,ns).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,Mk.toBinary(r)),a(this,ns).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){a(this,ns).error("Failed to renegotiate",{error:e});return}}async close(t){if(!t.length)return{};const e=async(r,i)=>{const n=r.map(l=>l.localId);a(this,ns).info(`Closing consumers: ${JSON.stringify(n)}`);const o={description:{sdp:i.sdp,type:i.type,target:Ws.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=iR.fromBinary(c).description;return{sdp:d.sdp,type:d.type}};return await this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(t,e),"ConsumerStrategy.close",{consumersLength:t.length}),{}}async switchConsumersToLayer(t,e){const r={requests:[],consumingTransportId:this.recvTransport.serverId},i=t.filter(n=>n&&n.id);i.forEach(({id:n,producingTransportId:o,localId:c})=>{r.requests.push({producerId:n,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),await this.socketHandler.updateConsumersSimulcastConfig(r),a(this,ns).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:n})=>n)})}}Ml=new WeakMap,ns=new WeakMap;class Ah{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return yi(t).media.filter(n=>e==="video"?n.type==="video":n.type==="audio").at(-1).msid}async create({offer:t,kind:e,paused:r,appData:i,codecOptions:n,producingTransportId:o}){var h,m;const c=Ah.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:Ws.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(h=i.screenShare)!=null?h:!1,mimeType:`${e}/${(m=n[0])==null?void 0:m.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}class WD extends jD{constructor(e,r){super(e,r);g(this,ic);g(this,Dl);g(this,Nl);g(this,Vl);g(this,Ll);g(this,ei,void 0);g(this,ti,void 0);g(this,_a,void 0);g(this,rc,void 0);g(this,xs,void 0);g(this,Ol,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});g(this,mr,[]);g(this,ka,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{f(this,rc,new Ah(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{a(this,_a).clear(),f(this,xs,new GD(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,ei)}get consumers(){return a(this,ti)}get producerIdToConsumerIdMap(){return a(this,_a)}get logger(){return this.context.getValue("logger")}reset(){f(this,ei,new Map),f(this,ti,new Map),f(this,_a,new Map)}async createProducer(e,r){var i,n;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const o=await this.sendTransport.produce(e,$(this,Dl,cS).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_PRODUCER,o),$(this,Nl,dS).call(this,o,r),o}catch(o){throw this.logger.error(`Failed to create ${((n=e==null?void 0:e.track)==null?void 0:n.kind)||"unknown"} producer`,{error:o}),a(this,Ol).producerCreationFailureCount+=1,o}}async closeProducer(e,r){var n;const i=this.producers.get(e);if(!i){this.logger.warn(`Producer with ID ${e} was not found`);return}r!=null&&r.stopTrack&&i.track.stop();try{await this.sendTransport.closeProducer(i),(n=this.context.getValue("modules").e2ee)!=null&&n.enabled&&this.context.getValue("peerSessionStore").emit(k.E2EE_INACTIVE_PRODUCER,i)}catch(o){this.logger.error("Failed to close producer on server",{error:o,producer:i})}}closeAllProducers(){return Promise.all(Array.from(a(this,ei).entries()).map(([,e])=>e.close()))}async closeAllProducersLocally(){var r;const e=(r=this.sendTransport)==null?void 0:r.handler;await Promise.all(Array.from(a(this,ei).values()).map(async i=>{try{if(e){const n=e.midTransceiverMap.get(i.localId);n&&(await n.sender.replaceTrack(null),n.direction="inactive")}}catch(n){this.logger.warn("closeAllProducersLocally: failed to deactivate transceiver",{producer:{id:i.id,kind:i.kind,appData:i.appData},error:n})}await i.close(lo)}))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){a(this,ka)||clearTimeout(a(this,ka)),f(this,mr,a(this,mr).concat(e)),await $(this,ic,rp).call(this)}closeConsumer(e){return this.closeConsumers([e])}async closeConsumers(e){if(!a(this,xs))return;const r=e.map(n=>this.consumers.get(n)).filter(n=>n!==void 0);if(r.length===0)return;const{failedConsumers:i}=await a(this,xs).close(r);i!=null&&i.length&&this.logger.warn("Failed to close some consumers",{consumerIds:i})}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,ti).keys()))}async switchConsumersToLayer(e,r){a(this,xs).switchConsumersToLayer(e,r)}}ei=new WeakMap,ti=new WeakMap,_a=new WeakMap,rc=new WeakMap,xs=new WeakMap,Ol=new WeakMap,mr=new WeakMap,ka=new WeakMap,ic=new WeakSet,rp=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=a(this,mr).splice(0,a(this,mr).length);try{const i=new Set(Array.from(this.consumers.values()).map(({producerId:d})=>d)),n=r.filter(({producerId:d})=>!this.producers.get(d)&&!i.has(d));if(n.length===0)return;const{consumers:o,failedProducers:c}=await this.recvTransport.consume(n,$(this,Vl,lS).bind(this),a(this,xs).negotiate.bind(a(this,xs)));if(o.forEach($(this,Ll,uS).bind(this)),c!=null&&c.length){this.logger.error("Failed to create consumers for producers",{producers:c});const d=c.filter(({errorCode:l,producerId:u})=>l==="not_found_track_error"?(this.logger.error(`Track not found for producer: ${u}. This will not be retried.`),!1):l==="backend_error"?(this.logger.error("Unrecoverable error: backend error"),!1):!0);f(this,mr,a(this,mr).concat(d)),f(this,ka,setTimeout($(this,ic,rp).bind(this),e))}}catch(i){if(this.logger.error("failed to consume on transport",{error:i}),i.errorCode==="internal_error"&&i.errorDescription==="Backend error"||i.errorCode==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:i.errorCode,message:i.errorDescription}});try{this.stopTransports({recv:!0})}catch(n){}await this.setupTransports({recv:!0})}}},Dl=new WeakSet,cS=function(e){return a(this,rc).create(e)},Nl=new WeakSet,dS=function(e,r){e.on("close",async(i,n)=>{const{offer:o,reason:c}=i;if(this.logger.info("producer::closing",{debuggingHint:c,producer:{...e,status:"closing"}}),c!==lo){const d={producerId:e.id,description:{sdp:o.sdp,type:o.type,target:Ws.PUBLISHER}};try{const l=await this.socketHandler.closeProducer(d),u={sdp:l==null?void 0:l.sdp,type:l==null?void 0:l.type};this.logger.info("producer::closed",{producer:{...e,status:"closed"}}),n({answer:u})}catch(l){this.logger.error("producer close error",l)}}this.producers.delete(e.id),r()}),e.on("trackended",()=>{this.logger.info("producer::trackended",{producer:{...e,status:"UNKNOWN"}})}),a(this,ei).set(e.id,e)},Vl=new WeakSet,lS=async function(e){try{return await this.recvTransport.canConsume(),await a(this,xs).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},Ll=new WeakSet,uS=function(e){e.on("close",async r=>{this.logger.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),a(this,ti).delete(e.id),this.context.getValue("peerSessionStore").emit(k.CONSUMER_CLOSED,{id:e.id})}),a(this,ti).set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),this.context.getValue("peerSessionStore").emit(k.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId})};const Fl=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:n=.95,voiceAdaptationRate:o=.99,minEnergyThreshold:c=.005,maxEnergyThreshold:d=.2,energyRatioThreshold:l=1.5,noiseHistorySize:u=50}={}){g(this,xl);g(this,Ul);g(this,nc,void 0);g(this,ac,void 0);g(this,oc,void 0);g(this,Ca,void 0);g(this,Ra,void 0);g(this,Ia,void 0);g(this,cc,void 0);g(this,dc,void 0);g(this,Aa,void 0);g(this,Ct,void 0);g(this,ys,void 0);g(this,Es,!1);g(this,Zi,0);g(this,en,0);g(this,gr,[]);g(this,lc,void 0);f(this,Ca,t),f(this,Ct,t),f(this,nc,e),f(this,ac,r),f(this,oc,i),f(this,Ra,n),f(this,Ia,o),f(this,cc,c),f(this,dc,d),f(this,Aa,l),f(this,lc,u),f(this,ys,t/2)}get voiceDetected(){return a(this,Es)}processAudioChunk(t){var o,c;const e=$(o=Fl,$l,mS).call(o,t),r=$(c=Fl,Bl,gS).call(c,t);return $(this,xl,hS).call(this,e),e/a(this,ys)>a(this,Aa)&&e>a(this,Ct)&&r>a(this,nc)?(f(this,Zi,a(this,Zi)+1),f(this,en,a(this,oc)),a(this,Zi)>=a(this,ac)&&f(this,Es,!0)):(f(this,Zi,0),a(this,en)>0?f(this,en,a(this,en)-1):a(this,Es)&&f(this,Es,!1),a(this,Es)||$(this,Ul,pS).call(this,e)),{energy:e,isVoice:a(this,Es)}}reset(){f(this,Es,!1),f(this,Zi,0),f(this,en,0),f(this,Ct,a(this,Ca)),f(this,ys,a(this,Ca)/2),f(this,gr,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,Ct),backgroundNoiseEnergy:a(this,ys),energyRatioThreshold:a(this,Aa)}}};let uo=Fl;nc=new WeakMap,ac=new WeakMap,oc=new WeakMap,Ca=new WeakMap,Ra=new WeakMap,Ia=new WeakMap,cc=new WeakMap,dc=new WeakMap,Aa=new WeakMap,Ct=new WeakMap,ys=new WeakMap,Es=new WeakMap,Zi=new WeakMap,en=new WeakMap,gr=new WeakMap,lc=new WeakMap,xl=new WeakSet,hS=function(t){a(this,Es)?f(this,Ct,a(this,Ia)*a(this,Ct)+(1-a(this,Ia))*t):f(this,Ct,a(this,Ra)*a(this,Ct)+(1-a(this,Ra))*a(this,ys)),f(this,Ct,Math.max(a(this,cc),Math.min(a(this,dc),a(this,Ct))))},Ul=new WeakSet,pS=function(t){if(t<a(this,Ct)*1.2)if(a(this,gr).push(t),a(this,gr).length>a(this,lc)&&a(this,gr).shift(),a(this,gr).length>=10){const e=[...a(this,gr)].sort((i,n)=>i-n),r=Math.floor(e.length/2);f(this,ys,e[r])}else f(this,ys,.95*a(this,ys)+.05*t)},$l=new WeakSet,mS=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Bl=new WeakSet,gS=function(t){let e=0;for(let r=1;r<t.length;r+=1)(t[r]>=0&&t[r-1]<0||t[r]<0&&t[r-1]>=0)&&(e+=1);return e},g(uo,$l),g(uo,Bl);class Yf{constructor(t){p(this,"RNAudioSampleHandler");g(this,uc,void 0);f(this,uc,t);const{RNAudioSampleHandlerImpl:e}=navigator;e==null||e.init().then(r=>{this.RNAudioSampleHandler=r}).catch(r=>{this.logger.error("ReactNativeAudioSampler: Failed to initialize audio sampler",r)})}get logger(){return a(this,uc).getValue("logger")}get samples(){var e;const t=new Float32Array(1024);return(e=this.RNAudioSampleHandler)==null||e.getFloatTimeDomainData(t),t}stop(){var t;(t=this.RNAudioSampleHandler)==null||t.destructor()}}uc=new WeakMap;class Qf{constructor(t){p(this,"audioContext");p(this,"analyser");g(this,hc,void 0);f(this,hc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return a(this,hc).getValue("logger")}get samples(){if(this.audioContext.state==="suspended")try{this.audioContext.resume()}catch(e){this.logger.error("AudioContextSampler: Failed to resume audio context",e)}const t=new Float32Array(this.analyser.frequencyBinCount);return this.analyser.getFloatTimeDomainData(t),t}set audioTrack(t){const e=new MediaStream;e.addTrack(t),this.audioContext.createMediaStreamSource(e).connect(this.analyser)}}hc=new WeakMap;class JD{static setInterval(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setInterval(t,e,...r):global.setInterval(t,e,...r)}static clearInterval(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearInterval(t):global.clearInterval(t)}static setTimeout(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setTimeout(t,e,...r):global.setTimeout(t,e,...r)}static clearTimeout(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearTimeout(t):global.clearTimeout(t)}}const KD=60,zD=400,gc=class{constructor(t,e){g(this,Hl);g(this,ql);g(this,fr,void 0);g(this,vr,void 0);g(this,Sr,void 0);g(this,pc,void 0);g(this,Ma,void 0);g(this,Oa,void 0);g(this,si,void 0);g(this,tn,void 0);g(this,Da,void 0);g(this,sn,void 0);g(this,Tr,void 0);g(this,Us,void 0);this.reportRequest=e,f(this,sn,t),f(this,Oa,new uo);const{isReactNative:r}=navigator;f(this,Tr,r?new Yf(a(this,sn)):new Qf(a(this,sn))),f(this,Us,r?JD:Of)}get logger(){return a(this,sn).getValue("logger")}set producerId(t){f(this,Sr,t)}set audioTrack(t){f(this,pc,t),a(this,Tr)instanceof Qf&&(a(this,Tr).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${a(this,Sr)}`),a(this,fr)&&a(this,Us).clearInterval(a(this,fr)),f(this,fr,a(this,Us).setInterval(async()=>{var i;if(!a(this,pc)||!a(this,Sr))return;const{energy:t}=$(this,Hl,fS).call(this),e=$(i=gc,mc,ip).call(i,t);let r=.9;a(this,Da)!==e&&a(this,Da)?r=.9:e?r=.3:r=.5,f(this,Ma,(a(this,Ma)||0)*(1-r)+t*r)},KD)),a(this,vr)&&a(this,Us).clearInterval(a(this,vr)),f(this,vr,a(this,Us).setInterval($(this,ql,vS).bind(this),zD))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${a(this,Sr)}`),a(this,fr)&&(a(this,Us).clearInterval(a(this,fr)),f(this,fr,void 0)),a(this,vr)&&(a(this,Us).clearInterval(a(this,vr)),f(this,vr,void 0))}catch(t){}a(this,Oa).reset(),a(this,Tr)instanceof Yf&&a(this,Tr).stop()}};let ho=gc;fr=new WeakMap,vr=new WeakMap,Sr=new WeakMap,pc=new WeakMap,Ma=new WeakMap,Oa=new WeakMap,si=new WeakMap,tn=new WeakMap,Da=new WeakMap,sn=new WeakMap,Tr=new WeakMap,Us=new WeakMap,Hl=new WeakSet,fS=function(){var o;const{samples:t}=a(this,Tr),{energy:e,isVoice:r}=a(this,Oa).processAudioChunk(t),i=$(o=gc,jl,SS).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,si)||i<a(this,si))&&f(this,si,i),(!a(this,tn)||i>a(this,tn))&&f(this,tn,i),{energy:(i-a(this,si))/(a(this,tn)-a(this,si))*10||0,isVoice:r})},mc=new WeakSet,ip=function(t){return t<5},ql=new WeakSet,vS=function(t=a(this,Ma)){var r;if(!a(this,Sr)||!t)return;const e={producerId:a(this,Sr),energy:Math.round(t),silent:$(r=gc,mc,ip).call(r,t)};f(this,Da,e.silent),this.reportRequest(e)},jl=new WeakSet,SS=function(t){const e=Math.log10(t);return Math.round(e)},g(ho,mc),g(ho,jl);var YD=Object.defineProperty,QD=Object.getOwnPropertyDescriptor,de=(s,t,e,r)=>{for(var i=r>1?void 0:r?QD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&YD(t,e,i),i};class ae{constructor(t,e){g(this,yr);g(this,Wl);g(this,Jl);g(this,Kl);g(this,Tc);g(this,zl);g(this,Yl);g(this,bt);g(this,on);g(this,Ql);g(this,Xl);g(this,Zl);p(this,"context");p(this,"authToken");p(this,"e2ee");g(this,fc,void 0);g(this,vc,void 0);g(this,ht,void 0);g(this,q,void 0);g(this,Gl,void 0);g(this,Et,void 0);g(this,rn,void 0);g(this,nn,void 0);g(this,an,void 0);g(this,Sc,void 0);g(this,Ft,null);g(this,$s,void 0);g(this,pt,void 0);g(this,Rt,void 0);var i,n;this.context=t;const{socket:r}=e;this.mediaJoined=!1,f(this,ht,r),f(this,rn,!1),f(this,q,new WD(t,r)),f(this,Et,a(this,q).events),f(this,$s,new Set),f(this,pt,new Map),f(this,nn,!1),f(this,an,new wh(t.getValue("logger"))),f(this,Rt,new ho(this.context,a(this,q).socketHandler.audioActivity.bind(a(this,q).socketHandler))),this.e2ee=(n=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,Sc,Mu(async()=>{if(!a(this,yr,gn).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(a(this,vc),a(this,fc),!0);o&&(this.context.getValue("peerSessionStore").emit(k.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(k.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return a(this,yr,gn).mediaJoined}set mediaJoined(t){a(this,yr,gn).mediaJoined=t}reset({resetTransportQueue:t}){this.logger.info(`Resetting media node client: closing all transports, producers, consumers, and queues(resetTransportQueue: ${t}).`),a(this,q).closeAllProducers(),a(this,q).closeAllConsumers(),a(this,pt).clear(),a(this,$s).clear(),f(this,Ft,null),t&&a(this,an).stop(),a(this,q).stopAllTransports(),a(this,q).reset(),t&&f(this,an,new wh)}async joinRoom(t,e,r=!1,i={}){a(this,yr,gn).mediaJoinAttempted=!0,f(this,rn,!0);try{return await a(this,an).push(()=>$(this,Wl,TS).call(this,t,e,r,i),"joinRoom")}catch(n){return this.logger.error("Error in room joining process",{error:n}),this.context.getValue("peerSessionStore").emit(k.ROOM_NODE_FAILED),{roomJoined:!1,error:n}}}async initializeConnection(t,e,r=!1,i={}){return a(this,Ft)?a(this,Ft):(f(this,Ft,(async()=>{try{await $(this,Tc,np).call(this,t,e,r,i)}catch(n){throw f(this,Ft,null),n}})()),a(this,Ft))}getConsumers(){return a(this,q).consumers}getProducers(){return a(this,q).producers}async leaveRoom(){a(this,q).stopAllTransports(),f(this,nn,!1),a(this,yr,gn).mediaJoinAttempted=!1;const t={closeRoom:!1};a(this,ht).sendMessagePromise(a(this,Et).leaveRoom,sC.toBinary(t)).then(r=>{var i;(i=jC.fromBinary(r.payload))!=null&&i.closed&&this.logger.warn("Weird state on peer closed and should not happen")}).catch(r=>{this.logger.error("error on sending leave room request",{error:r})}),this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct().catch(r=>{this.logger.error("leaveRoom::telemetry_destruct_failed",{error:r})})}async activatePeers(t){return this.createConsumers(t)}async createConsumers(t){return t.length===0?Promise.resolve():a(this,q).createConsumers(t)}async closeConsumers(t){if(!t.length)return;const e=t.reduce((r,i)=>{const n=a(this,q).producerIdToConsumerIdMap.get(i.producerId);return n?(r.push(n),r):(this.logger.warn(`consumer not found in close consumers: ${i.producerId}`),r)},[]);await a(this,q).closeConsumers(e)}async _shareWebcam(t){var u,h,m,v;const e=Ie.WEBCAM,r=$(this,bt,Wt).call(this,e);if(r){const y=await r;if(a(this,q).producers.has(y)){const w=a(this,q).producers.get(y);if(!w.closed)return await w.replaceTrack({track:t}),await this.resumeWebcam(e),t;await this.disableWebcam()}return this._shareWebcam(t)}const i=$(this,Zl,kS).call(this,t),n=bn(this.context,"disableSimulcast"),o=(h=(u=this.context)==null?void 0:u.getValue("overrides"))==null?void 0:h.simulcastConfig;n||o&&o.disable||!((v=(m=this.context)==null?void 0:m.getValue("theme"))!=null&&v.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),i.encodings=MO(this.context,t),this.logger.info(`Simulcast encodings: ${JSON.stringify(i.encodings)}`));const d=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,pt).delete(e)},l=a(this,q).createProducer(i,d);return $(this,on,Gc).call(this,e,l.then(y=>y.id)),l.then(y=>y.track)}async shareWebcam(t){return t===void 0?null:(this.logger.debug("Calling _shareWebcam with VP8 codec"),this._shareWebcam(t))}async shareScreen(t){const{video:e,audio:r}=t;if(e===void 0)return;const i={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1},n=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,pt).delete(Ie.SCREENSHARE_VIDEO),a(this,pt).delete(Ie.SCREENSHARE_AUDIO)},o=a(this,q).createProducer(i,n);$(this,on,Gc).call(this,Ie.SCREENSHARE_VIDEO,o.then(d=>d.id));let c;if(r){const d={track:r,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},l=()=>{};c=a(this,q).createProducer(d,l),$(this,on,Gc).call(this,Ie.SCREENSHARE_AUDIO,c.then(u=>u.id))}await Promise.all([o,c||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()}async shareMic(t){try{if(t===void 0)throw new _t("track undefined");const e=$(this,bt,Wt).call(this,Ie.MIC);if(e){const o=await e;if(a(this,q).producers.has(o)){const c=a(this,q).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),a(this,Rt)&&(a(this,Rt).audioTrack=t,a(this,Rt).producerId=o,a(this,Rt).start());return}await a(this,q).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=$(this,Xl,_S).call(this,t),i=()=>{a(this,pt).delete(Ie.MIC)},n=a(this,q).createProducer(r,i);$(this,on,Gc).call(this,Ie.MIC,n.then(o=>o.id)),await n.then(o=>{a(this,Rt)&&(a(this,Rt).audioTrack=o.track,a(this,Rt).producerId=o.id,a(this,Rt).start())})}catch(e){throw new I(e)}}async pauseMic(){var i;const t=await $(this,bt,Wt).call(this,Ie.MIC),e=a(this,q).producers.get(t);if(!e){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(e.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}e.pause(),(i=a(this,Rt))==null||i.stop();const r={producerId:e.id,pause:!0};a(this,ht).sendMessage(a(this,Et).toggleProducer,_d.toBinary(r))}async pauseWebcam(){const t=await $(this,bt,Wt).call(this,Ie.WEBCAM),e=a(this,q).producers.get(t);if(!e){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}e.pause();const r={producerId:e.id,pause:!0};a(this,ht).sendMessage(a(this,Et).toggleProducer,_d.toBinary(r))}async resumeMic(){const t=await $(this,bt,Wt).call(this,Ie.MIC),e=a(this,q).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,ht).sendMessage(a(this,Et).toggleProducer,_d.toBinary(r))}async resumeWebcam(t=Ie.WEBCAM){const e=await $(this,bt,Wt).call(this,t),r=a(this,q).producers.get(e);if(!r){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!r.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}r.resume(),r.appData.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};a(this,ht).sendMessage(a(this,Et).toggleProducer,_d.toBinary(i))}async disableWebcam(){const t=Ie.WEBCAM,e=await $(this,bt,Wt).call(this,t);$(this,Ql,PS).call(this,t),e&&await a(this,q).closeProducer(e)}async disableMic(){var e;const t=await $(this,bt,Wt).call(this,Ie.MIC);t&&await a(this,q).closeProducer(t),(e=a(this,Rt))==null||e.stop(),a(this,pt).delete(Ie.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await $(this,bt,Wt).call(this,Ie.SCREENSHARE_VIDEO),e=await $(this,bt,Wt).call(this,Ie.SCREENSHARE_AUDIO);t&&await a(this,q).closeProducer(t),e&&await a(this,q).closeProducer(e),a(this,$s).clear(),a(this,pt).delete(Ie.SCREENSHARE_VIDEO),a(this,pt).delete(Ie.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await $(this,bt,Wt).call(this,Ie.WEBCAM);await a(this,q).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await $(this,bt,Wt).call(this,Ie.SCREENSHARE_VIDEO);await a(this,q).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:e})}}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await a(this,q).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};a(this,q).socketHandler.kickPeer(e)}kickAll(){a(this,q).socketHandler.kickAll()}async muteAll(t){if(!await a(this,q).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,q).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await a(this,q).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await a(this,q).socketHandler.hostControlForPeer(t,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(t){const e={participantId:t!=null?t:""};try{await a(this,ht).sendMessagePromise(a(this,Et).globalPinPeer,fC.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&a(this,q).producers.get(t.producerId)&&a(this,$s).add(t.consumerPeerId),a(this,$s).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));a(this,q).switchConsumersToLayer(r,e)}async handleSocketEvents(){a(this,ht).on(a(this,Et).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:r}=yR.fromBinary(t);if(e===this.peerId)return;r!=null&&r.mimeType||(r.mimeType=r.kind===Js.AUDIO?"audio/opus":"video/VP8"),this.logger.info(`producer created broadcast: ${e}, producer state: ${r}`),this.context.getValue("peerSessionStore").emit(k.NEW_PRODUCER,{peerId:e,producer:{...r,kind:r.kind===Js.AUDIO?"audio":"video",producingPeerId:e}})}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),a(this,ht).on(a(this,Et).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:i,pause:n,producerId:o,screenShare:c}}=Hg.fromBinary(t);if(c)return;const d=i===Js.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${o}, kind:${d}, paused:${n} payload: ${JSON.stringify(Hg.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&n&&this.context.getValue("peerSessionStore").emit(d==="audio"?k.MUTE_SELF:k.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(k.PRODUCER_TOGGLE,{peerId:e,producerId:o,paused:n,kind:d}),Array.from(this.getConsumers().values()).filter(u=>u.producerId===o).forEach(u=>{u.kind==="video"&&n||u.paused!==n&&(this.logger.debug(`consumer state mismatched for ${u.id}. updating consumer pause state ${u.paused} to ${n}`),n?(u.pause(),this.context.getValue("peerSessionStore").emit(k.CONSUMER_PAUSED,{id:u.id})):(u.resume(),this.context.getValue("peerSessionStore").emit(k.CONSUMER_RESUMED,{id:u.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,ht).on(a(this,Et).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=ju.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,$s).delete(e),a(this,q).consumers.forEach(r=>{r.peerId===e&&r.close()}),this.context.getValue("peerSessionStore").emit(k.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),a(this,ht).on(a(this,Et).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=wR.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(k.PRODUCER_CLOSED,{peerId:e,producerId:r});const i=a(this,q).producerIdToConsumerIdMap.get(r);if(!i){this.logger.warn(`no consumer found for producer:${r}`);return}this.logger.info(`closing consumer ${i}, producer id: ${r}`),a(this,q).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),a(this,q).producerIdToConsumerIdMap.delete(r),this.context.getValue("peerSessionStore").emit(k.CONSUMER_CLOSED,{id:i})}).catch(n=>{this.logger.error("error closing consumer",{error:n})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,ht).on(a(this,Et).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,rn)&&!a(this,nn)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(k.ROOM_NODE_DISCONNECTED),a(this,Sc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=a(this,q).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(k.CONSUMER_SCORE_UPDATE,{id:r,kind:i.kind,peerId:i.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,r)=>{const i=Array.from(a(this,q).producers.values()).find(n=>n.id===r);i&&this.context.getValue("peerSessionStore").emit(k.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}}fc=new WeakMap,vc=new WeakMap,ht=new WeakMap,q=new WeakMap,Gl=new WeakMap,Et=new WeakMap,rn=new WeakMap,nn=new WeakMap,an=new WeakMap,Sc=new WeakMap,Ft=new WeakMap,$s=new WeakMap,pt=new WeakMap,Rt=new WeakMap,yr=new WeakSet,gn=function(){return this.context.getValue("connectionHandler")},Wl=new WeakSet,TS=async function(t,e,r,i){var o;f(this,vc,t);let n=!1;if(r){const{recv:c,send:d}=(o=a(this,yr,gn).mediaState)!=null?o:{};(d==null?void 0:d.state)===Nr.CONNECTED&&(c==null?void 0:c.state)===Nr.CONNECTED?(this.logger.info("MediaNodeClient.joinRoom: transports healthy — partial reset (producers only)"),await a(this,q).closeAllProducersLocally(),a(this,pt).clear(),a(this,$s).clear(),f(this,Ft,null),n=!0):(this.logger.info("MediaNodeClient.joinRoom: transports unhealthy — full reset"),this.reset({resetTransportQueue:!1}))}try{a(this,Ft)?await a(this,Ft):await $(this,Tc,np).call(this,t,e,r,i,n),$(this,Kl,ES).call(this,e);const{joined:c,error:d}=await $(this,Jl,yS).call(this);return{roomJoined:c,error:d}}catch(c){return this.logger.error("Failed to complete room join",{error:c}),{roomJoined:!1,error:c}}finally{f(this,Ft,null)}},Jl=new WeakSet,yS=async function(){try{this.mediaJoined=!0;const{roomState:t}=await a(this,q).socketHandler.notifySelfJoinComplete();return f(this,fc,t.roomUuid),f(this,nn,!0),f(this,rn,!1),{joined:!0}}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,{joined:!1,error:t}}},Kl=new WeakSet,ES=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...Te.getDeviceInfo(),userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency},sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};this.context.getValue("callstats").roomJoined(r)}catch(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},Tc=new WeakSet,np=async function(t,e,r,i,n=!1){try{const o=$(this,zl,bS).call(this);await $(this,Yl,wS).call(this,t,e,r,o),n?this.logger.info("MediaNodeClient: reusing existing transports on rejoin"):await a(this,q).setupTransports({send:!0,recv:!0})}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},zl=new WeakSet,bS=function(){const t=CD("video/VP8");return f(this,Gl,t),t},Yl=new WeakSet,wS=async function(t,e,r,i){await Gf(async(n,o)=>{if(!a(this,ht).isConnected){o(new Error("Socket is not connected"));return}n>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${n}`});try{await a(this,q).socketHandler.joinRoom(e,t,i,r)}catch(c){throw this.logger.error("Failed to send joinRoom message after retries",{error:c}),c}},{delayTime:1e3,strategy:"exponential",maxRetryCount:15})},bt=new WeakSet,Wt=function(t){return a(this,pt).get(t)},on=new WeakSet,Gc=function(t,e){return a(this,pt).set(t,e)},Ql=new WeakSet,PS=function(t){return a(this,pt).delete(t)},Xl=new WeakSet,_S=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},Zl=new WeakSet,kS=function(t){return{track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},de([E.trace("MediaNodeClient.reset")],ae.prototype,"reset",1),de([E.trace("MediaNodeClient.joinRoom")],ae.prototype,"joinRoom",1),de([E.trace("MediaNodeClient.leaveRoom")],ae.prototype,"leaveRoom",1),de([E.trace("MediaNodeClient.activatePeers")],ae.prototype,"activatePeers",1),de([E.trace("MediaNodeClient.createConsumers")],ae.prototype,"createConsumers",1),de([E.trace("MediaNodeClient.closeConsumers")],ae.prototype,"closeConsumers",1),de([E.trace("MediaNodeClient._shareWebcam")],ae.prototype,"_shareWebcam",1),de([E.trace("MediaNodeClient.shareWebcam")],ae.prototype,"shareWebcam",1),de([E.trace("MediaNodeClient.shareScreen")],ae.prototype,"shareScreen",1),de([E.trace("MediaNodeClient.shareMic")],ae.prototype,"shareMic",1),de([E.trace("MediaNodeClient.pauseMic")],ae.prototype,"pauseMic",1),de([E.trace("MediaNodeClient.pauseWebcam")],ae.prototype,"pauseWebcam",1),de([E.trace("MediaNodeClient.resumeMic")],ae.prototype,"resumeMic",1),de([E.trace("MediaNodeClient.resumeWebcam")],ae.prototype,"resumeWebcam",1),de([E.trace("MediaNodeClient.disableWebcam")],ae.prototype,"disableWebcam",1),de([E.trace("MediaNodeClient.disableMic")],ae.prototype,"disableMic",1),de([E.trace("MediaNodeClient.disableScreenShare")],ae.prototype,"disableScreenShare",1),de([E.trace("MediaNodeClient.muteSelf")],ae.prototype,"muteSelf",1),de([E.trace("MediaNodeClient.resetVideoProducers")],ae.prototype,"resetVideoProducers",1),de([E.trace("MediaNodeClient.changeDisplayName")],ae.prototype,"changeDisplayName",1),de([E.trace("MediaNodeClient.kickPeer")],ae.prototype,"kick",1),de([E.trace("MediaNodeClient.kickAllPeers")],ae.prototype,"kickAll",1),de([E.trace("MediaNodeClient.muteAll")],ae.prototype,"muteAll",1),de([E.trace("MediaNodeClient.muteAllVideo")],ae.prototype,"muteAllVideo",1),de([E.trace("MediaNodeClient.disableAudio")],ae.prototype,"disableAudio",1),de([E.trace("MediaNodeClient.disableVideo")],ae.prototype,"disableVideo",1),de([E.trace("MediaNodeClient.pinPeer")],ae.prototype,"pinPeer",1),de([E.trace("MediaNodeClient.validateScreenShare")],ae.prototype,"validateScreenShare",1);function Xf(s,t){const e=s.getValue("roomNodeClient");if(e){if(e)return e;throw new Error("Room node client already set up.")}const r=new ae(s,t);return s.setValue("roomNodeClient",r),r}function XD(s){const t=s.getValue("roomNodeClient");try{t==null||t.leaveRoom()}catch(e){s.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}s.setValue("roomNodeClient",void 0)}var ZD=Object.defineProperty,e1=Object.getOwnPropertyDescriptor,bi=(s,t,e,r)=>{for(var i=r>1?void 0:r?e1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ZD(t,e,i),i};const Zf=(Hv=class{constructor(s,t,e,r){g(this,It);p(this,"self");p(this,"authToken");g(this,Na,void 0);p(this,"viewType");g(this,bs,void 0);g(this,ee,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,ee,s),this.viewType=r,this.authToken=n,f(this,Na,i),f(this,bs,e),this.setupEvents()}get peerId(){return a(this,ee).getValue("peerId")}get telemetry(){return a(this,ee).getValue("telemetry")}get logger(){return a(this,ee).getValue("logger")}get mediaJoined(){return a(this,ee).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=wt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await Je.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");return navigator.product!=="ReactNative"?setTimeout(async()=>{const h=await d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(h)}),s.getValue("callstats").devices("AUDIO",h==null?void 0:h.filter(m=>m.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",h==null?void 0:h.filter(m=>m.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",h==null?void 0:h.filter(m=>m.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:Te.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:l,apiHostnames:E_(s),skipConnectivityChecks:!0,authToken:s.getValue("authToken")}),l.info("Callstats:: initialized")}catch(m){l.error("Callstats:: initialization failed",{error:m})}},0):l.info("Callstats:: Skipped initialization due to navigator product being ReactNative."),new Zf(s,d,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:n,screenShareTracks:o}=this.self;if(e.canProduceAudio===G.Allowed&&r)if((s==null?void 0:s.readyState)==="live")try{await a(this,It,os).shareMic(s),this.self.audioEnabled||a(this,It,os).pauseMic()}catch(d){this.self.disableAudio()}else this.logger.warn("shareMediaTracks: audio track is dead, disabling audio"),this.self.disableAudio();if(e.canProduceVideo===G.Allowed&&i)if((t==null?void 0:t.readyState)==="live")try{await a(this,It,os).shareWebcam(t),this.self.videoEnabled||a(this,It,os).pauseWebcam()}catch(d){this.self.disableVideo()}else this.logger.warn("shareMediaTracks: video track is dead, disabling video"),this.self.disableVideo();if(e.canProduceScreenshare===G.Allowed&&n){const d=o.video,l=o.audio;if((d==null?void 0:d.readyState)==="live")try{await((c=a(this,It,os))==null?void 0:c.shareScreen({video:d,audio:(l==null?void 0:l.readyState)==="live"?l:void 0}))}catch(u){this.self.disableScreenShare()}else this.logger.warn("shareMediaTracks: screenshare video track is dead, disabling screenshare"),this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){a(this,ee).getValue("callstats").callEnded(),s?(this.logger.info("Resetting Self post reconnect. Peer has earlier tried joining the meeting. State cleanup will be done during room rejoin."),await this.joinRoom(s)):(this.logger.info("Resetting Self post reconnect. User never joined the room so doing full reset."),a(this,It,os).reset({resetTransportQueue:!0}))}setupEvents(){a(this,ee).getValue("peerSessionStore").on(k.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,ee).getValue("peerSessionStore").on(k.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,ee).getValue("peerSessionStore").on(k.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,ee).getValue("peerSessionStore").on(k.ROOM_NODE_FAILED,()=>{this.logger.error("Room node failed. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,ee).getValue("peerSessionStore").on(k.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,ee).getValue("peerSessionStore").on(k.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;const{peerId:t}=this;a(this,Na).updateURL(t),a(this,ee).getValue("telemetry").resetPeerId(t),wt().setHeader("tracing-id",t),_r.remapContext(t,a(this,ee)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,ee).getValue("peerSessionStore").on(k.SOCKET_SERVICE_FAILED,()=>{this.logger.error("Socket reconnection failed after exhausting all attempts. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,bs).on(x.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,bs).on(Md.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,ee).getValue("peerSessionStore").emit(k.UPDATE_PERMISSIONS,t.patch)})}),a(this,bs).on(x.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,bs).on(x.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,bs).on(x.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,ee).getValue("peerSessionStore").onAsync(k.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,ee).getValue("peerSessionStore").on(k.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var n;const i=(n=e==null?void 0:e.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),a(this,ee).getValue("peerSessionStore").on(k.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,ee).getValue("callstats").audioOff())}),a(this,ee).getValue("peerSessionStore").on(k.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,ee).getValue("callstats").videoOff())}),a(this,ee).getValue("peerSessionStore").onAsync(k.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,ee).getValue("peerSessionStore").on(k.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{this.logger.info("Joining socket room.");const{peer:t}=await a(this,bs).joinRoom(this.self);this.logger.info("Joined socket room."),a(this,bs).socket.flush();const e=dh(t.stageType);if(a(this,ee).setValue("stageStatus",e,!1),t.waitlisted){this.logger.info("Peer was waitlisted. Skipped joining media room."),this.waitlistedHandler();return}}catch(t){throw this.logger.error("SelfController.joinRoom: socket join failed",{error:t}),new I("Check the network and try again.","0002")}try{this.logger.info("Joining media room."),await this.joinMediaRoom(s),this.logger.info("Joined media room."),a(this,ee).notify("stageStatus")}catch(t){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:t}),t instanceof Dr&&t.message==="ice connection failed"?new I("A firewall or network restriction may be blocking the connection.","0014"):new I("Check the network and try again.","0014")}}async leaveRoom(s="left"){var t;if(this.logger.info(`Leaving room with state: ${s}`),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),a(this,ee).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,ee).setValue("roomNodeClient",void 0),a(this,ee).notify("stageStatus"),(t=a(this,ee).getValue("roomSocketHandler"))==null||t.cleanup(),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var n,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,ee).getAllValues();try{if(e===js.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}Xf(a(this,ee),{socket:a(this,Na),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:h}=(o=await((n=a(this,It,os))==null?void 0:n.joinRoom(this.self.name,r,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)throw h!=null?h:new Error("Could not connect to media server");this.logger.info(i==="ON_STAGE"?"Peer is on stage. Sharing media tracks":"Peer is not on stage. Not sharing media tracks"),i==="ON_STAGE"&&await this.shareMediaTracks(),this.logger.info(i==="ON_STAGE"?"Peer is on stage. Shared media tracks":"Peer is not on stage. Did not share media tracks"),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("SelfController.mediaRoomJoin",{error:c}),c}}async leaveMediaRoom(s){const t=a(this,ee).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===js.Webinar)&&a(this,It,os)&&(a(this,It,os).mediaJoined&&s!=="disconnected"&&await a(this,It,os).leaveRoom(),!(s==="stageLeft"&&t===js.Livestream)&&(a(this,It,os).mediaJoined=!1))}async cleanupSelf(){await this.self.disableAudio(),await this.self.disableVideo(),await this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()}},Na=new WeakMap,bs=new WeakMap,ee=new WeakMap,It=new WeakSet,os=function(){return a(this,ee).getValue("roomNodeClient")},Hv);let Vr=Zf;bi([E.trace("SelfController.resetSelf")],Vr.prototype,"resetSelf",1),bi([E.trace("SelfController.setupEvents")],Vr.prototype,"setupEvents",1),bi([E.trace("SelfController.joinRoom")],Vr.prototype,"joinRoom",1),bi([E.trace("SelfController.leaveRoom")],Vr.prototype,"leaveRoom",1),bi([E.trace("SelfController.joinMediaRoom")],Vr.prototype,"joinMediaRoom",1),bi([E.trace("SelfController.leaveMediaRoom")],Vr.prototype,"leaveMediaRoom",1),bi([E.trace("SelfController.init")],Vr,"init",1);class t1{constructor(t){g(this,yc,void 0);f(this,yc,t)}on(t,e){let r;t===x.roomPeerCount?r=Gg.fromBinary.bind(Gg):r=af.fromBinary.bind(af),a(this,yc).on(t,({payload:i})=>{if(t===x.roomPeerCount&&!i)return;const n=r(i);e(n)})}}yc=new WeakMap;class s1{constructor(t,e){g(this,Ec,void 0);g(this,bc,void 0);f(this,Ec,e),f(this,bc,t)}get logger(){return a(this,bc).getValue("logger")}on(t,e){let r,i;switch(t){case x.transcript:{r=Gu.fromBinary.bind(Gu),i=Gu.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Ec).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}Ec=new WeakMap,bc=new WeakMap;var r1=Object.defineProperty,i1=Object.getOwnPropertyDescriptor,Mh=(s,t,e,r)=>{for(var i=r>1?void 0:r?i1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&r1(t,e,i),i};class Wd{constructor(t,e){g(this,Er,void 0);g(this,Va,void 0);f(this,Er,e),f(this,Va,t)}get logger(){return a(this,Va).getValue("logger")}get telemetry(){return a(this,Va).getValue("telemetry")}getPolls(){return a(this,Er).sendMessagePromise(Ys.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Er).sendMessage(Ys.createPoll,XA.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Er).sendMessage(Ys.votePoll,eM.toBinary(r))}on(t,e){let r,i;switch(t){case Ys.updatePoll:case Ys.createPoll:case Ys.votePoll:{r=rh.fromBinary.bind(rh),i=rh.create();break}}a(this,Er).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){a(this,Er).removeListeners(t)}}Er=new WeakMap,Va=new WeakMap,Mh([E.trace("PollSocketHandler.getPolls")],Wd.prototype,"getPolls",1),Mh([E.trace("PollSocketHandler.createPoll")],Wd.prototype,"createPoll",1),Mh([E.trace("PollSocketHandler.votePoll")],Wd.prototype,"votePoll",1);var n1=Object.defineProperty,a1=Object.getOwnPropertyDescriptor,o1=(s,t,e,r)=>{for(var i=r>1?void 0:r?a1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&n1(t,e,i),i};class ev{constructor(t,e){p(this,"socket");g(this,Ht,void 0);f(this,Ht,t),this.socket=e,this.handleSocketEvents(),a(this,Ht).setValue("roomSocketHandler",this)}get telemetry(){return a(this,Ht).getValue("telemetry")}get logger(){return a(this,Ht).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}async joinRoom(t){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(x.joinRoom,XR.toBinary(e));try{const{peer:n}=_n.fromBinary((await r).payload);a(this,Ht).getValue("connectionHandler").socketJoined=!0,a(this,Ht).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_ROOM_JOINED,{peer:n});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return a(this,Ht).getValue("peerSessionStore").emit(k.ROOM_STATE,d),a(this,Ht).getValue("peerSessionStore").emit(k.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),n}}async getAllAddedParticipants(){try{return LI.fromBinary((await this.socket.sendMessagePromise(x.getAllAddedParticipants)).payload).participants.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}async getRoomPeers(t,e,r){let i;try{const n={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise(x.getRoomPeersInfo,HR.toBinary(n));i=Ku.fromBinary(o.payload)}catch(n){this.logger.error("getRoomPeers::binary_decode_error",{error:n})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise(x.getRoomPeersInfo);t=Ku.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getStagePeers(){let t;try{const e=await this.socket.sendMessagePromise(x.getRoomPeersInfo);t=Ku.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getPeerInfo(t){let e;try{const r=await this.socket.sendMessagePromise(x.getPeerInfo,Kg.toBinary({peerId:t}));e=_n.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=Jg.create();try{const e=await this.socket.sendMessagePromise(x.getRoomInfo);t=Jg.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=ef.create();try{const e=await this.socket.sendMessagePromise(x.getRoomStageState);t=ef.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t}async broadcastMessage(t,e){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(x.broadcastMessage,Xa.toBinary(r))}async broadcastToMeetings(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(x.broadcastToEntity,Xa.toBinary(i))}async broadcastToPeers(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(x.broadcastToEntity,Xa.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(x.leaveRoom,eI.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(x.kick,Xg.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(x.kickAll,xg.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(x.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(x.acceptWaitingRoomRequests,HI.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(x.denyWaitingRoomRequests,jI.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Md.updateUserPreset,T0.toBinary(r))}handleSocketEvents(){this.socket.on(x.broadcastMessage,({payload:t})=>{try{const e=Xa.fromBinary(t);a(this,Ht).getValue("peerSessionStore").emit(k.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on(x.broadcastToEntity,({payload:t})=>{try{const e=Xa.fromBinary(t);a(this,Ht).getValue("peerSessionStore").emit(k.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case x.joinRoom:case x.leaveRoom:case x.kick:case x.kickAll:{r=_n.fromBinary.bind(_n),i=_n.create();break}case x.getWaitingRoomRequests:{r=(n,o)=>n?Zg.fromBinary(n,o):{requests:[]},i=Zg.create();break}case x.recordingPaused:case x.recordingStarted:case x.recordingStopped:{r=lf.fromBinary.bind(lf);break}case Md.updateUserPreset:{r=sf.fromBinary.bind(sf);break}case hs.peerJoinedBroadcast:case Rr.peerJoinedBroadcast:{r=Bg.fromBinary.bind(Bg);break}case hs.selfJoinComplete:case Rr.selfJoinComplete:{r=qu.fromBinary.bind(qu);break}case hs.globalPeerPinBroadcast:case Rr.globalPeerPinBroadcast:{r=qg.fromBinary.bind(qg);break}case hs.selectedPeer:case Rr.selectedPeer:{r=Hu.fromBinary.bind(Hu);break}case hs.selectedPeerDiff:case Rr.selectedPeerDiff:{r=$g.fromBinary.bind($g);break}case hs.leaveRoom:case Rr.leaveRoom:{r=ju.fromBinary.bind(ju);break}}this.socket.on(t,({payload:n})=>{let o=i;if(!r)return e(void 0);try{o=r(n)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}async getUserPermissions(t){const e={userIds:[t]};try{const r=await this.socket.sendMessagePromise(Md.getUserPresets,h0.toBinary(e)),i=f0.fromBinary(r.payload).peerPresets[0],n=new TextDecoder().decode(i.preset),o=JSON.parse(n).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}}}Ht=new WeakMap,o1([E.trace("RoomSocketHandler.joinRoom")],ev.prototype,"joinRoom",1);class c1{constructor(t){g(this,At,void 0);f(this,At,t)}async getStageRequests(){const{payload:t}=await a(this,At).sendMessagePromise(x.getStageRequests);return t?sh.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,At).sendMessage(x.requestStageAccess)}cancelRequestAccess(){a(this,At).sendMessage(x.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,At).sendMessage(x.grantStageAccess,HA.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,At).sendMessage(x.denyStageAccess,jA.toBinary(e))}joinStage(){return a(this,At).sendMessagePromise(x.joinStage,void 0,void 0,x.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,At).sendMessagePromise(x.leaveStage,cf.toBinary(e),void 0,x.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,At).sendMessagePromise(x.leaveStage,cf.toBinary(e))}on(t,e){let r;switch(t){case x.grantStageAccess:case x.denyStageAccess:{r=void 0;break}case x.getStagePeers:{r=of.fromBinary.bind(of);break}case x.getStageRequests:case x.requestStageAccess:case x.cancelStageRequest:{r=sh.fromBinary.bind(sh);break}case x.peerStageStatusUpdate:{r=jg.fromBinary.bind(jg);break}}a(this,At).on(t,({payload:i,id:n})=>{if(!i||!r)return e(void 0,n);const o=r(i);return e(o,n)})}async getPeerInfo(t){const e=await a(this,At).sendMessagePromise(x.getPeerInfo,Kg.toBinary({peerId:t}));return _n.fromBinary(e.payload)}}At=new WeakMap;class d1{constructor(t,e){g(this,ri,void 0);g(this,La,void 0);f(this,ri,e),f(this,La,t)}get logger(){return a(this,La).getValue("logger")}get peerId(){return a(this,La).getValue("peerId")}storeInsertKeys(t,e,r,i){const n={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,ri).sendMessage(zs.storeInsertKeys,bA.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,ri).sendMessage(zs.storeGetKeys,PA.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,ri).sendMessage(zs.storeDeleteKeys,kA.toBinary(n),i)}on(t,e){const r=nf.fromBinary.bind(nf);a(this,ri).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}ri=new WeakMap,La=new WeakMap;var l1=Object.defineProperty,u1=(s,t,e)=>t in s?l1(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,h1=(s,t,e)=>(u1(s,typeof t!="symbol"?t+"":t,e),e),Oh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},M=(s,t,e)=>(Oh(s,t,"read from private field"),e?e.call(s):t.get(s)),le=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},ie=(s,t,e,r)=>(Oh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),ne=(s,t,e)=>(Oh(s,t,"access private method"),e),Jd={},p1={get exports(){return Jd},set exports(s){Jd=s}},Mn=typeof Reflect=="object"?Reflect:null,tv=Mn&&typeof Mn.apply=="function"?Mn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},Kd;Mn&&typeof Mn.ownKeys=="function"?Kd=Mn.ownKeys:Object.getOwnPropertySymbols?Kd=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:Kd=function(s){return Object.getOwnPropertyNames(s)};function m1(s){console&&console.warn&&console.warn(s)}var sv=Number.isNaN||function(s){return s!==s};function ue(){ue.init.call(this)}p1.exports=ue,Jd.once=S1,ue.EventEmitter=ue,ue.prototype._events=void 0,ue.prototype._eventsCount=0,ue.prototype._maxListeners=void 0;var rv=10;function zd(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ue,"defaultMaxListeners",{enumerable:!0,get:function(){return rv},set:function(s){if(typeof s!="number"||s<0||sv(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");rv=s}}),ue.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},ue.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||sv(s))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+s+".");return this._maxListeners=s,this};function iv(s){return s._maxListeners===void 0?ue.defaultMaxListeners:s._maxListeners}ue.prototype.getMaxListeners=function(){return iv(this)},ue.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var n;if(t.length>0&&(n=t[0]),n instanceof Error)throw n;var o=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw o.context=n,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")tv(c,this,t);else for(var d=c.length,l=dv(c,d),e=0;e<d;++e)tv(l[e],this,t);return!0};function nv(s,t,e,r){var i,n,o;if(zd(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=iv(s),i>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=s,c.type=t,c.count=o.length,m1(c)}return s}ue.prototype.addListener=function(s,t){return nv(this,s,t,!1)},ue.prototype.on=ue.prototype.addListener,ue.prototype.prependListener=function(s,t){return nv(this,s,t,!0)};function g1(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function av(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=g1.bind(r);return i.listener=e,r.wrapFn=i,i}ue.prototype.once=function(s,t){return zd(t),this.on(s,av(this,s,t)),this},ue.prototype.prependOnceListener=function(s,t){return zd(t),this.prependListener(s,av(this,s,t)),this},ue.prototype.removeListener=function(s,t){var e,r,i,n,o;if(zd(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,n=e.length-1;n>=0;n--)if(e[n]===t||e[n].listener===t){o=e[n].listener,i=n;break}if(i<0)return this;i===0?e.shift():f1(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this},ue.prototype.off=ue.prototype.removeListener,ue.prototype.removeAllListeners=function(s){var t,e,r;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[s]),this;if(arguments.length===0){var i=Object.keys(e),n;for(r=0;r<i.length;++r)n=i[r],n!=="removeListener"&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=e[s],typeof t=="function")this.removeListener(s,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(s,t[r]);return this};function ov(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?v1(i):dv(i,i.length)}ue.prototype.listeners=function(s){return ov(this,s,!0)},ue.prototype.rawListeners=function(s){return ov(this,s,!1)},ue.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):cv.call(s,t)},ue.prototype.listenerCount=cv;function cv(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}ue.prototype.eventNames=function(){return this._eventsCount>0?Kd(this._events):[]};function dv(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function f1(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function v1(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function S1(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,n),r(o)}function n(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}lv(s,t,n,{once:!0}),t!=="error"&&T1(s,i,{once:!0})})}function T1(s,t,e){typeof s.on=="function"&&lv(s,"error",t,e)}function lv(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(n){r.once&&s.removeEventListener(t,i),e(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class y1 extends S{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const uv=new y1;class hv{static encode(t){return uv.toBinary(t)}static decode(t){return uv.fromBinary(new Uint8Array(t))}}function E1(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Lr;class b1{constructor(t={}){h1(this,"opts"),le(this,Lr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ie(this,Lr,0)}async wait(){ie(this,Lr,M(this,Lr)+1);const t=E1(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**M(this,Lr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return M(this,Lr)}reset(){ie(this,Lr,0)}}Lr=new WeakMap;const xr={debug:0,info:1,warn:2,error:3};var wi,Pi;class w1{constructor(t){le(this,wi,void 0),le(this,Pi,void 0),ie(this,wi,console),ie(this,Pi,t)}debug(...t){xr[M(this,Pi)]>xr.debug||M(this,wi).debug("[Sockrates]:",...t)}info(...t){xr[M(this,Pi)]>xr.info||M(this,wi).info("[Sockrates]:",...t)}warn(...t){xr[M(this,Pi)]>xr.warn||M(this,wi).warn("[Sockrates]:",...t)}error(...t){xr[M(this,Pi)]>xr.error||M(this,wi).error("[Sockrates]:",...t)}}wi=new WeakMap,Pi=new WeakMap;var pv=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(pv||{});const mv="2",gv="3";var Me,On,he,ke,Ur,Ke,sr,$r,ms,Dn,Nn,rr,Dh,fv,po,Yd,Nh,vv,Qd,Vh,Xd,Lh,xh,Sv,mo,Zd,Vn,go,el,Uh,Ln,fo,$h,Tv,vo,tl,So,sl;class P1{constructor(t,e){var y,w,C,P,N,U,L,H,F,Z,je,jt;le(this,Dh),le(this,po),le(this,Nh),le(this,Qd),le(this,Xd),le(this,xh),le(this,mo),le(this,Vn),le(this,el),le(this,Ln),le(this,$h),le(this,vo),le(this,So),le(this,Me,void 0),le(this,On,void 0),le(this,he,void 0),le(this,ke,void 0),le(this,Ur,void 0),le(this,Ke,void 0),le(this,sr,void 0),le(this,$r,void 0),le(this,ms,void 0),le(this,Dn,void 0),le(this,Nn,void 0),le(this,rr,void 0);var r,i,n,o,c,d,l,u,h,m,v;ie(this,On,t),ie(this,Ur,[]),ie(this,Ke,new Jd),ie(this,sr,!0),ie(this,ms,!1),ie(this,he,e!=null?e:{}),(y=(r=M(this,he)).autoReconnect)!=null||(r.autoReconnect=!0),(w=(i=M(this,he)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(C=(n=M(this,he)).pingTimeout)!=null||(n.pingTimeout=3e4),(P=(o=M(this,he)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(N=(c=M(this,he)).debug)!=null||(c.debug=!0),(U=(d=M(this,he)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(L=(l=M(this,he)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(H=(u=M(this,he)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(F=(h=M(this,he)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),(Z=(m=M(this,he)).clientInitiatedPings)!=null||(m.clientInitiatedPings=!1),(je=(v=M(this,he)).clientInitiatedPingInterval)!=null||(v.clientInitiatedPingInterval=3e4),ie(this,$r,{code:void 0,reason:void 0}),ie(this,ke,(jt=M(this,he).logger)!=null?jt:new w1(M(this,he).debug?"debug":"info")),ie(this,rr,new b1)}get readyState(){var t;return(t=M(this,Me))==null?void 0:t.readyState}get url(){return M(this,On)}updateURL(t){ie(this,On,t),ne(this,xh,Sv).call(this)}get config(){return M(this,he)}get sendQueue(){return M(this,Ur)}flush(){if(!M(this,he).queueOnDisconnect)return!1;const t=[];return M(this,Ur).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ie(this,Ur,t),M(this,Ur)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){M(this,ke).debug("Websocket was already connecting or connected.");return}if(M(this,sr)!==!1)return new Promise((e,r)=>{ne(this,Ln,fo).call(this),ne(this,So,sl).call(this);try{ie(this,Me,new WebSocket(ne(this,Dh,fv).call(this,M(this,On)))),M(this,Me).binaryType="arraybuffer",M(this,ke).debug("Connecting");const i=setTimeout(()=>{M(this,ke).debug("Connection timeout. Closing socket"),ie(this,sr,!0),ne(this,So,sl).call(this),M(this,Me).close(3001,"Connection Timeout"),M(this,he).autoReconnect&&!M(this,ms)&&(M(this,Ke).emit("reconnecting"),ne(this,mo,Zd).call(this)),r(new Error("Connection timed out!"))},M(this,he).connectionTimeout);M(this,Me).onopen=()=>{M(this,ke).debug(`Ready State: ${pv[M(this,Me).readyState]}`),i&&clearTimeout(i),ne(this,el,Uh).call(this),ne(this,$h,Tv).call(this),ie(this,$r,{code:void 0,reason:void 0}),M(this,Ke).emit("connected"),M(this,he).flushOnReconnect&&this.flush(),e()},M(this,Me).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),M(this,ke).debug("Socket closed. Close event:",{event:n}),M(this,ke).debug(`Connection closed code: ${o}`),M(this,ke).debug(`Connection closed reason: ${c}`),M(this,ms)||ne(this,Xd,Lh).call(this,o,c)}catch(o){ne(this,po,Yd).call(this,o)}},M(this,Me).onerror=n=>{ne(this,po,Yd).call(this,n)},M(this,Me).onmessage=n=>ne(this,Nh,vv).call(this,n)}catch(i){ne(this,po,Yd).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(M(this,he).queueOnDisconnect&&(!M(this,Me)||M(this,Me).readyState!==1))return M(this,ke).debug("Queuing message since socket is not connected!",n),M(this,Ur).push(n),!1;const o=hv.encode(n);return ne(this,Vn,go).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return ne(this,Vn,go).call(this,t)}receive(t,e){return M(this,Ke).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){M(this,Ke).on(t,e);return}this.receive(t,e)}removeAllListeners(){M(this,Ke).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){M(this,Ke).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){M(this,Ke).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ie(this,sr,!1),ne(this,Ln,fo).call(this),ne(this,vo,tl).call(this),this.removeAllListeners(),ie(this,$r,{code:1e3,reason:"Sockrates disconnect method called"}),M(this,Me).close(1e3,"Sockrates disconnect method called.")}}Me=new WeakMap,On=new WeakMap,he=new WeakMap,ke=new WeakMap,Ur=new WeakMap,Ke=new WeakMap,sr=new WeakMap,$r=new WeakMap,ms=new WeakMap,Dn=new WeakMap,Nn=new WeakMap,rr=new WeakMap,Dh=new WeakSet,fv=function(s){if(s.startsWith("ws://")||s.startsWith("wss://"))return s;if(s.startsWith("https://"))return`wss://${s.substring(8)}`;if(s.startsWith("http://"))return`ws://${s.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},po=new WeakSet,Yd=function(s,t){M(this,ke).error("Error:",{error:s}),M(this,Ke).emit("errored",{error:s}),t==null||t(s)},Nh=new WeakSet,vv=function(s){if(ne(this,el,Uh).call(this),s.data===mv){M(this,ke).debug("Received ping from server"),ne(this,Vn,go).call(this,gv);return}if(s.data===gv){M(this,ke).debug("Received pong from server");return}const t=hv.decode(s.data),{id:e,payload:r}=t;M(this,ke).debug("Received message",{event:t.event,messageID:e}),M(this,Ke).emit(t.event.toString(),{id:e,payload:r})},Qd=new WeakSet,Vh=function(){return M(this,Me).readyState===1},Xd=new WeakSet,Lh=function(s,t){ie(this,$r,{reason:t,code:s}),M(this,Ke).emit("disconnected",{code:s,reason:t})},xh=new WeakSet,Sv=function(){const{reason:s,code:t}=M(this,$r);t&&t!==1e3&&M(this,sr)&&M(this,he).autoReconnect&&!M(this,ms)&&(M(this,ke).debug(`Triggering reconnection due to ${s}.`),M(this,Ke).emit("reconnecting"),ne(this,mo,Zd).call(this))},mo=new WeakSet,Zd=async function(s=!0){if(s&&M(this,ms)){M(this,ke).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(M(this,ms)||M(this,rr).reset(),M(this,he).maxReconnectionAttempts!==null&&M(this,rr).getAttempts()>=M(this,he).maxReconnectionAttempts){M(this,Ke).emit("failed"),ie(this,ms,!1);return}ie(this,ms,!0),ne(this,So,sl).call(this),ne(this,Ln,fo).call(this);try{if(await M(this,rr).wait(),M(this,sr)===!1)return;if(M(this,ke).debug(`Reconnection attempt ${M(this,rr).getAttempts()}`),M(this,Ke).emit("reconnectAttempt",{attempt:M(this,rr).getAttempts()}),await this.connect(),!ne(this,Qd,Vh).call(this))throw Error("Reconnect Failed");ie(this,ms,!1),ie(this,$r,{code:void 0,reason:void 0}),M(this,Ke).emit("reconnected")}catch(t){M(this,ke).debug("Failed to reconnect."),M(this,Ke).emit("reconnectFailure",{attempt:M(this,rr).getAttempts()}),ne(this,mo,Zd).call(this,!1)}},Vn=new WeakSet,go=function(s){try{return M(this,Me).send(s),!0}catch(t){return M(this,ke).error(t.message),!1}},el=new WeakSet,Uh=function(){this.config.disconnectOnPingTimeout&&(M(this,ke).debug("Resetting ping timeout"),ne(this,Ln,fo).call(this),ie(this,Dn,setTimeout(()=>{var s;M(this,ke).debug("Disconnecting the socket due to ping timeout"),ie(this,sr,!0);const t=3002,e="Ping timeout";(s=M(this,Me))==null||s.close(t,e),ne(this,Xd,Lh).call(this,t,e)},M(this,he).pingTimeout)))},Ln=new WeakSet,fo=function(){M(this,Dn)&&(clearTimeout(M(this,Dn)),ie(this,Dn,void 0))},$h=new WeakSet,Tv=function(){ne(this,vo,tl).call(this),M(this,he).clientInitiatedPings&&ie(this,Nn,setInterval(()=>{ne(this,Qd,Vh).call(this)&&(M(this,ke).debug("Sending client-initiated ping"),ne(this,Vn,go).call(this,mv))},M(this,he).clientInitiatedPingInterval))},vo=new WeakSet,tl=function(){M(this,Nn)&&(clearInterval(M(this,Nn)),ie(this,Nn,void 0))},So=new WeakSet,sl=function(){ne(this,vo,tl).call(this),M(this,Me)&&(M(this,Me).onopen=void 0,M(this,Me).onerror=void 0,M(this,Me).onmessage=void 0,M(this,Me).onclose=void 0)};var _1=Object.defineProperty,k1=Object.getOwnPropertyDescriptor,rl=(s,t,e,r)=>{for(var i=r>1?void 0:r?k1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&_1(t,e,i),i};const yv=65535,C1=3e3,Ev=(qv=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,Re);g(this,wc);g(this,Pc);g(this,ii,void 0);g(this,Ce,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");g(this,as,void 0);g(this,et,void 0);if(!t||!e||!r)throw new I("peerId, meetingId, or authToken can not be empty","0404");f(this,as,void 0),f(this,et,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,ii,$(this,wc,ap).call(this,t));const n=i.includes("PING");f(this,Ce,new P1(a(this,ii),{autoReconnect:!0,disconnectOnPingTimeout:n,queueOnDisconnect:!1,flushOnReconnect:!1,logger:this.logger,clientInitiatedPings:!n,maxReconnectionAttempts:50,clientInitiatedPingInterval:15e3})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Re,Fe).socketJoinAttempted}set joinAttempted(s){a(this,Re,Fe).socketJoinAttempted=s}get telemetry(){return a(this,et).getValue("telemetry")}get logger(){return a(this,et).getValue("logger")}get peerId(){return a(this,et).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,ii,$(this,wc,ap).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Ce).updateURL(a(this,ii))}static getSocketEdgeDomain(s){return wn({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,ii)}async connect(){a(this,Re,Fe).socketJoinAttempted=!0,await a(this,Ce).connect(),a(this,Re,Fe).socketJoinAttempted=!0,a(this,Re,Fe).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){a(this,Re,Fe).socketJoinAttempted=!1,a(this,Ce).disconnect(),a(this,Re,Fe).socketJoinAttempted=!0,a(this,Re,Fe).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Ce).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,et).getValue("telemetry").injectContext(r),a(this,Ce).send(s,e!=null?e:$(this,Pc,op).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:i,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:i}){const n=i!=null?i:s;return new Promise((o,c)=>{const d=(y,w)=>{a(this,Ce).removeListener(n,y),a(this,Ce).removeListener(yv,w),a(this,Ce).removeListener(Rr.errorResponse,w),a(this,Ce).removeListener(hs.errorResponse,w)},l=r!=null?r:$(this,Pc,op).call(this),u={};a(this,et).getValue("telemetry").injectContext(u);const m=({id:y,payload:w})=>{if(l===y){let C;try{const P=NC.fromBinary(w);C=new Error(P.errorMessage)}catch(P){C=new Error("failed to parse error message",{cause:P});try{const N=VR.fromBinary(w);C=new Error(N.message)}catch(N){C=new Error("failed to parse error message",{cause:N})}}c(C),d(v,m)}},v=({id:y,payload:w})=>{l===y&&(o({id:y,payload:w}),d(v,m))};a(this,Ce).on(n,v),a(this,Ce).on(yv,m),a(this,Ce).on(Rr.errorResponse,m),a(this,Ce).on(hs.errorResponse,m),setTimeout(()=>{d(v,m),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Ce).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){a(this,Ce).on(s,t)}onStateEvent(s,t){a(this,Ce).on(s,t)}removeListener(s,t){a(this,Ce).removeListener(s,t)}removeListeners(s){a(this,Ce).removeListeners(s)}flush(){return a(this,Ce).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),a(this,as)&&(clearTimeout(a(this,as)),f(this,as,void 0)),a(this,Re,Fe).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}});const{recv:e,send:r}=(i=a(this,Re,Fe).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Nr.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Nr.CONNECTED?a(this,et).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Re,Fe).joinAttempted}):f(this,as,setTimeout(()=>{a(this,et).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Re,Fe).joinAttempted}),f(this,as,void 0)},C1)),a(this,Re,Fe).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge"),a(this,Re,Fe).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,Re,Fe).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,Re,Fe).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Re,Fe).mediaJoinAttempted}}),a(this,as)&&(clearTimeout(a(this,as)),f(this,as,void 0)),a(this,et).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Re,Fe).mediaJoinAttempted}),a(this,Re,Fe).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge"),a(this,et).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_FAILED),a(this,Re,Fe).updateSocketConnectionState("failed")})}},ii=new WeakMap,Ce=new WeakMap,Re=new WeakSet,Fe=function(){return a(this,et).getValue("connectionHandler")},as=new WeakMap,et=new WeakMap,wc=new WeakSet,ap=function(s){const t=a(this,et).getValue("socketBaseURI")||a(this,et).getValue("baseURI");let e=Ev.getSocketEdgeDomain(t);typeof bn(a(this,et),"socket_server_base")=="string"&&(e=bn(a(this,et),"socket_server_base"));const r=`wss://${e}`,i=new URL(`${r}/ws`),n=this.peerId,o={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...n!==s&&{oldPeerID:n},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(c=>kd[c]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(o).forEach(([c,d])=>{i.searchParams.append(c,d.toString())}),i.href},Pc=new WeakSet,op=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},qv);let To=Ev;rl([E.trace("SocketService.connect")],To.prototype,"connect",1),rl([E.trace("SocketService.disconnect")],To.prototype,"disconnect",1),rl([E.trace("SocketService.sendMessagePromise")],To.prototype,"sendMessagePromise",1),rl([E.trace("SocketService.sendMessagePromiseWithTimeout")],To.prototype,"sendMessagePromiseWithTimeout",1);class R1{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=cI.fromBinary(t),r=e.meetings.map(o=>{var c;return{id:o.id,title:o.title,participants:(c=o.participants)!=null?c:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(n=e.parentMeeting.participants)!=null?n:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=NI.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=Qg.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return Yg.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return PI.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(x.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(x.createConnectedRooms,hI.toBinary({payloads:t}));return Yg.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}async updateConnectedRooms(t){}async disableConnectedRooms(t){const e=t.map(i=>({id:i})),r=await this.socketService.sendMessagePromise(x.deleteConnectedRooms,bI.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(x.movePeers,AI.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}}}var I1=Object.defineProperty,A1=Object.getOwnPropertyDescriptor,M1=(s,t,e,r)=>{for(var i=r>1?void 0:r?A1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&I1(t,e,i),i};class bv extends Ot{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);g(this,qt,void 0);f(this,qt,e)}get isActive(){return this.meetings.length!==0}validateAlterAction(){const e=a(this,qt).getValue("self").permissions.connectedMeetings;if(!(e!=null&&e.canAlterConnectedMeetings))throw new Error("You are not allowed to perform this action. Please enable canAlterConnectedMeetings permission in your preset.")}validateMoveAction(e,r){var d;if(!(r!=null&&r.length))throw new Error("You're trying to move participants with an empty list.");const i=a(this,qt).getValue("self").permissions.connectedMeetings;if(!i)throw new Error("You are not allowed to perform this action. Please enable connected meetings permissions in your preset.");if(i.canAlterConnectedMeetings)return;const n=a(this,qt).getValue("userId");if(!(r.length===1&&r[0]===n))throw new Error("You are not allowed to move other participants. Please enable canAlterConnectedMeetings permission in your preset.");if(e===((d=this.parentMeeting)==null?void 0:d.id)){if(!i.canSwitchToParentMeeting)throw new Error("You are not allowed to move to the parent meeting. Please enable canSwitchToParentMeeting permission in your preset.");return}if(!i.canSwitchConnectedMeetings)throw new Error("You are not allowed to move to a connected meeting. Please enable canSwitchConnectedMeetings permission in your preset.")}async getConnectedMeetings(){this.logger.info("Getting connected meetings dump");const e=await a(this,qt).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateAlterAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await a(this,qt).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateAlterAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await a(this,qt).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)}async deleteMeetings(e){this.validateAlterAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),await Promise.all(r);const i=await a(this,qt).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateMoveAction(r,i),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,qt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return n.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),n}async moveParticipantsWithCustomPreset(e,r,i){this.validateMoveAction(r,i.map(o=>o.id)),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,qt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return n.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),n}moveSuccessHandler(e,r,i){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>n.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>n.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>n.get(d)));return{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}qt=new WeakMap,M1([Dt({maxInvocations:60,period:60})],bv.prototype,"getConnectedMeetings",1);var O1=Object.defineProperty,D1=Object.getOwnPropertyDescriptor,Bh=(s,t,e,r)=>{for(var i=r>1?void 0:r?D1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&O1(t,e,i),i};const wv=(jv=class{constructor(s){p(this,"connectedMeetings");g(this,Se,void 0);f(this,Se,s),this.connectedMeetings=new bv(s)}get telemetry(){return a(this,Se).getValue("telemetry")}get logger(){return a(this,Se).getValue("logger")}static init(s){const t=new wv(s);return s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings()),t.setupEvents(),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(x.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(x.transferPeer,this.handleTransferPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(x.movedPeer,this.handleMovedPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(x.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(x.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,n,o,c;this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:a(this,Se).getValue("self").videoEnabled,audio:a(this,Se).getValue("self").audioEnabled};try{a(this,Se).getValue("self").cleanupEvents(),await a(this,Se).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,Se).getValue("meeting"))==null?void 0:i.meta)==null?void 0:n.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await _v.init({...a(this,Se).getValue("options"),cachedUserDetails:null,defaults:{...a(this,Se).getValue("options").defaults,...e,mediaHandler:a(this,Se).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=a(this,Se).getValue("self");r.self.setName(a(this,Se).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return a(this,Se).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s),e=new Map;this.connectedMeetings.meetings.forEach(r=>{e.set(r.id,r)}),t.forEach(r=>{e.has(r.id)?e.get(r.id).title=r.title:e.set(r.id,{...r,participants:[]})}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Se=new WeakMap,jv);let il=wv;Bh([E.trace("ConnectedMeetingsController.getConnectedMeetings")],il.prototype,"getConnectedMeetings",1),Bh([E.trace("ConnectedMeetingsController.setupEvents")],il.prototype,"setupEvents",1),Bh([E.trace("ConnectedMeetingsController.switchMeeting")],il.prototype,"switchMeeting",1);var N1=Object.defineProperty,V1=Object.getOwnPropertyDescriptor,Fh=(s,t,e,r)=>{for(var i=r>1?void 0:r?V1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&N1(t,e,i),i};const yo=class{constructor(s,t,e){p(this,"apiBase");p(this,"selfController");p(this,"pollController");p(this,"chatController");p(this,"metaController");p(this,"storesManager");p(this,"stageController");p(this,"pluginController");p(this,"internalsController");p(this,"recordingController");p(this,"livestreamController");p(this,"participantController");p(this,"connectedMeetingsController");p(this,"telemetry");p(this,"logger");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController,this.connectedMeetingsController=t.connectedMeetingsController,this.telemetry=e.getValue("telemetry"),this.logger=e.getValue("logger")}static async init(s){var U,L,H;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(XD(s),Te.isSupported()===!1)throw new I("Browser not supported","0010",c,!0);const d=IM(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(n),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new uO(s);s.setValue("connectionHandler",l);let u="",h="",m=null;c.info("CF SFU is being used.");try{m=await d.getUserDetails(),u=((U=m.meeting)==null?void 0:U.title)||"",h=((L=m.socket)==null?void 0:L.baseUri)||s.getValue("baseURI"),s.setValue("presetName",m.preset.name),s.setValue("socketBaseURI",h),c.info(`Socket Base URI ${h} is being used`)}catch(F){throw c.error("Failed to get user details",{error:F}),F instanceof nh?F.status===401?new I("Unauthorized. The auth token may be invalid or expired. (401)","0004"):F.status===403?new I("Access denied. Insufficient permissions to join the meeting. (403)","0004"):F.status===404?new I("The auth token is not associated with an active participant in this meeting. The meeting may have ended, or the participant may no longer exist. (404)","0004"):F.status>=500?new I(`The server encountered an error. Try again. (${F.status})`,"0001"):F.isHttpError?new I(`Request rejected by the server. (${F.status})`,"0001"):F.isTimeout?new I("Connection timed out. Check the network and try again.","0001"):new I("Unable to connect to the server. Check the internet connection.","0001"):new I((F==null?void 0:F.message)||"Failed to initialize.","0001")}const v=yo.createSocketService(s),y=v.connect();try{await y}catch(F){c.error("[Controller]: Failed to connect to socket server:",{error:F})}const w=Sh.init(m.preset,!s.getValue("modules").theme);s.setValue("theme",w);const C=yh.init(s,w.viewType,m.preset.permissions),P=yo.setupControllers(v,s,m,u,w,C);ZM(w)&&((H=yo.createRoomNodeClient(s,v).initializeConnection(m.participant.name,i,!1,C))==null||H.catch(Z=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:Z})}));const{controllers:N}=await P;return H_(),new yo(e,N,s)}static async setupControllers(s,t,e,r,i,n){var Ve,V,R;const o=t.getValue("modules"),{participant:c}=e,d=t.getValue("defaults"),l=t.getValue("logger"),{viewType:u,mediaConstraints:{audio:h}}=i;t.setValue("viewType",u),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(Ve=h.enableHighBitrate)!=null?Ve:!1,enableStereo:(V=h.enableStereo)!=null?V:!1}},...d}),t.setValue("maxPreferredStreams",Te.isMobile()?i.maxVideoStreams.mobile:i.maxVideoStreams.desktop);let m,v,y,w,C,P,N,U,L;const H=new s1(t,s),F=new R1(s);t.setValue("connectedMeetingsSocketHandler",F);const Z=new Wd(t,s),je=new Qs(t,s),jt=new c1(s),ws=new ev(t,s),hn=new d1(t,s),A=new t1(s),T=await Vr.init(t,ws,c,n,i);t.setValue("selfController",T);const _=await Tf.init(t,T.self,ws,H,r);o.participant&&(U=new tr(t,T.self,ws)),(R=o.e2ee)!=null&&R.enabled&&o.e2ee.manager.init(l,t.getValue("peerSessionStore")),o.chat&&(v=await eo.init(t,je,T.self,U.participants)),o.internals&&(C=await ph.init(t)),o.livestream&&i.viewType===js.Livestream&&(N=new Bf(t,T.self,A)),o.poll&&(m=await gf.init(t,T.self,Z)),o.recording&&(P=new _f(t,T.self,ws)),o.stage&&(y=new yf(t,jt,ws,T.self,U.participants));const B=new dD(t,hn);if(o.plugin){if(!U)throw new I("The plugin module cannot be initialized without the `participant` module","0102");const Be=d.plugins||[],pn=await B.create(ig,!0);w=await Pf.init(t,Be,pn,T.self,B)}if(o.connectedMeetings&&(L=await il.init(t)),o.pip){const Be=await Vu._init(t,T.self);t.setValue("pip",Be)}return{theme:i,permissions:n,controllers:{storesManager:B,pollController:m,selfController:T,metaController:_,chatController:v,stageController:y,pluginController:w,recordingController:P,internalsController:C,livestreamController:N,participantController:U,connectedMeetingsController:L}}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return Xf(s,{socket:t,peerId:e})}static createSocketService(s){var d;const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),o=((d=s.getValue("socketBaseURI"))!=null?d:"").includes("realtime.cloudflare.com")?[]:["PING"];return s.getValue("logger").info(`Socket service capabilities: ${JSON.stringify(o)}`),new To(s,{peerId:t,meetingId:e,authToken:r,capabilities:o})}};let nl=yo;Fh([E.trace("Controller.init")],nl,"init",1),Fh([E.trace("Controller.createRoomNodeClient")],nl,"createRoomNodeClient",1),Fh([E.trace("Controller.createSocketService")],nl,"createSocketService",1);class L1{constructor(){p(this,"battery");p(this,"logger");p(this,"init",async t=>{this.logger=t;try{"getBattery"in navigator&&(this.battery=await navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){t.error("Error getting battery",e)}});p(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});p(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});p(this,"cleanup",()=>{var t,e;"getBattery"in navigator&&((t=this.battery)==null||t.removeEventListener("chargingchange",this.updateChargeInfo),(e=this.battery)==null||e.removeEventListener("levelchange",this.updateLevelInfo))})}}const Pv=new L1;function x1(s,t){s.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c — not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.realtime.cloudflare.com/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:e,orgId:r,participantId:i}=JSON.parse(atob(s.split(".")[1]));if(!e)throw Error(`Received V1 auth token ${s}`);let n=hi.baseURI.prod;t&&(n=t);const o=`https://${wn({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new I("Invalid auth token","0004")}}class U1{constructor(){g(this,eu);g(this,ni,new Audio);g(this,cn,new MediaStream);g(this,dn,new Map);g(this,_c,void 0);a(this,ni).srcObject=a(this,cn),a(this,ni).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,dn).has(e.id)||(a(this,cn).addTrack(e),a(this,dn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,ni).setSinkId(t)}removeTrack(t){const e=a(this,dn).get(t);e&&(a(this,cn).removeTrack(e),a(this,dn).delete(t))}async play(){return a(this,ni).srcObject=a(this,cn),a(this,ni).play().catch(t=>{$(this,eu,CS).call(this,t)})}onError(t){f(this,_c,t)}}ni=new WeakMap,cn=new WeakMap,dn=new WeakMap,_c=new WeakMap,eu=new WeakSet,CS=function(t){var e;(e=a(this,_c))==null||e.call(this,t)};class $1 extends U1{constructor(){super();g(this,ln,void 0);f(this,ln,new Map)}addParticipantTrack(e,r){a(this,ln).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,ln).get(e);r&&this.removeTrack(r),a(this,ln).delete(e)}}ln=new WeakMap;var B1=Object.defineProperty,F1=Object.getOwnPropertyDescriptor,al=(s,t,e,r)=>{for(var i=r>1?void 0:r?F1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&B1(t,e,i),i};let Br=(Gv=class{constructor(t,e){g(this,qe,void 0);g(this,un,void 0);f(this,un,t),f(this,qe,e)}get peerId(){return a(this,un).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:fn(),n=_r.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new qf(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var m,v,y,w,C,P,N,U,L;Te.init();const e=(v=(m=t==null?void 0:t.cachedUserDetails)==null?void 0:m.peerId)!=null?v:fn(),{authToken:r,baseURI:i}=t,{meetingId:n,...o}=x1(r,i);if((y=o.baseURI)!=null&&y.includes("dyte.io"))throw new I("Dyte Base URIs are no longer supported. Use RealtimeKit Base URIs.","0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=Br.setupContext(e,t,n,o),d=c.getValue("telemetry"),l=c.getValue("logger");MS(l),Pv.init(l),d.init(c,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(C=(w=t.modules)==null?void 0:w.tracing)!=null?C:!0,(N=(P=t==null?void 0:t.modules)==null?void 0:P.devTools)==null?void 0:N.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(U=t.authToken)==null?void 0:U.slice(0,10)}...
|
|
18
|
-
${(L=t.authToken)==null?void 0:L.slice(-10)}`}});const u=await nl.init(c),h=new Br(c,u);return c.setValue("meeting",h),h}static setupContext(t,e,r,i){var d,l;const n=_r.createContext(t,e),o={...T_,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return n.setValue("options",e),n.setValue("peerId",t),n.setValue("modules",o),n.setValue("sdkName","web-core"),n.setValue("meetingId",r),n.setValue("apiBase",i.apiBase),n.setValue("baseURI",i.baseURI),n.setValue("userId",i.participantId),n.setValue("organizationId",i.orgId),n.setValue("authToken",e.authToken),n.setValue("overrides",(d=e.overrides)!=null?d:{}),n.setValue("env",y_({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Rs(e.cachedUserDetails)),n.setValue("sdkVersion","2.0.0
|
|
18
|
+
${(L=t.authToken)==null?void 0:L.slice(-10)}`}});const u=await nl.init(c),h=new Br(c,u);return c.setValue("meeting",h),h}static setupContext(t,e,r,i){var d,l;const n=_r.createContext(t,e),o={...T_,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return n.setValue("options",e),n.setValue("peerId",t),n.setValue("modules",o),n.setValue("sdkName","web-core"),n.setValue("meetingId",r),n.setValue("apiBase",i.apiBase),n.setValue("baseURI",i.baseURI),n.setValue("userId",i.participantId),n.setValue("organizationId",i.orgId),n.setValue("authToken",e.authToken),n.setValue("overrides",(d=e.overrides)!=null?d:{}),n.setValue("env",y_({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Rs(e.cachedUserDetails)),n.setValue("sdkVersion","2.0.0"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new $1),n}async join(){const{selfController:t}=a(this,qe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){Pv.cleanup(),a(this,un).getValue("peerSessionStore").reset();const{selfController:e}=a(this,qe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,qe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,qe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,qe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,qe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,qe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,qe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,qe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,qe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,qe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,qe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,qe).stageController)==null?void 0:t.stage}get stores(){return a(this,qe).storesManager}get audio(){return a(this,un).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,qe).internalsController)==null?void 0:t.internals}},qe=new WeakMap,un=new WeakMap,Gv);al([ot("0002"),Zs.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Br.prototype,"join",1),al([ot("0003")],Br.prototype,"leave",1),al([ot("0001"),Zs.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Br,"init",1),Br=al([ot("0000")],Br);const _v=Br;return _v}();
|
package/dist/dependencies.txt
CHANGED