@cloudflare/realtimekit 2.0.2-staging.8 → 2.0.2

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 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}}}var Kf={},jd={},ID={get exports(){return jd},set exports(s){jd=s}},zf=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(zf).forEach(function(s){var t=zf[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=jd,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],S=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(S))return r(w,u,S)}}),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}})})}}(Kf);var Ch=jd,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""}})},oo=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){Ch[n].forEach(function(o){o.name in s&&s[o.name]!=null?i.push(oo(n,o,s)):o.push in s&&s[o.push]!=null&&s[o.push].forEach(function(c){i.push(oo(n,o,c))})})}),s.media.forEach(function(n){i.push(oo("m",Ch.m[0],n)),r.forEach(function(o){Ch[o].forEach(function(c){c.name in n&&n[c.name]!=null?i.push(oo(o,c,n)):c.push in n&&n[c.push]!=null&&n[c.push].forEach(function(d){i.push(oo(o,c,d))})})})}),i.join(`\r
16
16
  `)+`\r
17
17
  `},bi=Kf,VD=ND,Gd=VD,wi=bi.parse;bi.parseParams,bi.parseFmtpConfig,bi.parsePayloads,bi.parseRemoteCandidates,bi.parseImageAttributes,bi.parseSimulcastStreamList;class Wd extends _h{constructor(e,r){super(e);p(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new Wd(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 x;const S=wi(h),y=S.media[S.media.length-1],w=y.rtp.filter(B=>m.some(j=>j.name===B.codec)),_=y.fmtp.filter(B=>w.some(j=>j.payload===B.payload)),C=(x=y.rtcpFb)==null?void 0:x.filter(B=>w.some(j=>j.payload===B.payload)),V=w.map(B=>B.payload);return S.media[S.media.length-1].rtp=w,S.media[S.media.length-1].fmtp=_,S.media[S.media.length-1].rtcpFb=C,S.media[S.media.length-1].payloads=V.join(" "),Gd(S)},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,S=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=${S}`)}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)}}class Rh extends _h{static createFactory(t){return()=>new Rh(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(S=>S.mimeType.includes(u.name));if(u.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(u.parameters)}`);const S=((m=h.sdpFmtpLine)==null?void 0:m.split(";"))||[];S.push(...u.parameters);const y=[...new Set(S).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}}}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 qd{constructor(e,r){var i;super(e);g(this,xs);g(this,Yo);g(this,wl);g(this,Pl);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,zo,void 0);g(this,Ji,void 0);g(this,Ls,void 0);g(this,bl,void 0);this.id=r.id,this.localId=r.localId,f(this,zo,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,f(this,Ls,!1),this.producerId=r.producerId,this.track=r.track,f(this,Ji,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,N(this,wl,tv).call(this),f(this,bl,e)}get closed(){return a(this,Ls)}get kind(){return this.track.kind}get paused(){return a(this,Ji)}close(e,r){a(this,Ls)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,xs,di)),f(this,Ls,!0),r&&(N(this,Pl,sv).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(a(this,Ls))throw new kt("closed");return a(this,zo).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",a(this,xs,di)),a(this,Ls)){this.logger.error("consumer::pause() | Consumer closed",a(this,xs,di));return}f(this,Ji,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,xs,di)),a(this,Ls)){this.logger.error("Consumer::resume() | Consumer closed",a(this,xs,di));return}f(this,Ji,!1),this.track.enabled=!0,this.safeEmit("resume")}}zo=new WeakMap,Ji=new WeakMap,Ls=new WeakMap,bl=new WeakMap,xs=new WeakSet,di=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},Yo=new WeakSet,tp=function(){this.logger.debug('Consumer::track "ended" event',a(this,xs,di)),this.safeEmit("trackended")},wl=new WeakSet,tv=function(){this.track.addEventListener("ended",N(this,Yo,tp).bind(this))},Pl=new WeakSet,sv=function(){try{this.track.removeEventListener("ended",N(this,Yo,tp)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...a(this,xs,di),error:e})}};class UD extends qd{constructor(e,r){var i,n;super(e);g(this,Ft);p(this,"id");p(this,"localId");g(this,ys,void 0);p(this,"kind");p(this,"appData");p(this,"rtpSender");g(this,pa,void 0);g(this,ma,void 0);g(this,Ki,void 0);g(this,is,!1);g(this,ot,void 0);g(this,ti,void 0);g(this,ga,void 0);g(this,_l,void 0);this.id=r.id,this.localId=r.localId,f(this,ot,r.track),this.kind=(i=r.track)==null?void 0:i.kind,f(this,ti,r.disableTrackOnPause?!((n=r.track)!=null&&n.enabled):!1),f(this,ga,void 0),f(this,pa,r.stopTracks),f(this,ma,r.disableTrackOnPause),f(this,Ki,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),f(this,ys,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),f(this,_l,e)}get closed(){return a(this,is)}get track(){return a(this,ot)}get paused(){return a(this,ti)}get maxSpatialLayer(){return a(this,ga)}async close(e){if(a(this,is))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,Ft,_s)),f(this,is,!0),this._destroyTrack(),e===co){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await a(this,ys).stopSending(this.localId),{answer:n}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(n)}async getStats(){if(a(this,is))throw new kt("closed");return a(this,ys).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",a(this,Ft,_s)),a(this,is)&&this.logger.error("Producer::pause() | Producer closed",a(this,Ft,_s)),f(this,ti,!0),a(this,ot)&&a(this,ma)&&(a(this,ot).enabled=!1),a(this,Ki)&&a(this,ys).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,Ft,_s)),a(this,is)){this.logger.error("Producer::resume() | Producer closed",a(this,Ft,_s));return}f(this,ti,!1),a(this,ot)&&a(this,ma)&&(a(this,ot).enabled=!0),a(this,Ki)&&a(this,ys).replaceTrack(this.localId,a(this,ot)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,a(this,Ft,_s)),a(this,is)){if(e&&a(this,pa))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...a(this,Ft,_s),error:r})}throw new kt("closed")}else if(e&&e.readyState==="ended")throw new kt("track ended");if(e===a(this,ot)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,a(this,Ft,_s));return}(!a(this,Ki)||!a(this,ti))&&await a(this,ys).replaceTrack(this.localId,e),this._destroyTrack(),f(this,ot,e),this._handleTrack()}async setMaxSpatialLayer(e){if(a(this,is))throw new kt("closed");if(this.kind!=="video")throw new ao("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await a(this,ys).setMaxSpatialLayer(this.localId,e),f(this,ga,e)}async setRtpEncodingParameters(e){if(a(this,is))throw new kt("closed");if(typeof e!="object")throw new TypeError("invalid params");await a(this,ys).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,Ft,_s)),this.safeEmit("trackended",this.track.id)}_handleTrack(){a(this,ot)&&a(this,ot).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(a(this,ot))try{a(this,ot).removeEventListener("ended",this._onTrackEnded),a(this,pa)&&a(this,ot).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...a(this,Ft,_s),error:r})}}}ys=new WeakMap,pa=new WeakMap,ma=new WeakMap,Ki=new WeakMap,is=new WeakMap,ot=new WeakMap,ti=new WeakMap,ga=new WeakMap,_l=new WeakMap,Ft=new WeakSet,_s=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};const co="transport closed",Sa=class extends qd{constructor(e,{id:r,direction:i,handlerFactory:n,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:h}){var w,_,C;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,"connected",!1);p(this,"transportConnectionPromise");p(this,"consumerTrackEvents");p(this,"unknownTracksMap");p(this,"appData");g(this,fa,void 0);f(this,fa,e);const m=e.getValue("logger");m.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const S=LD(l,{});delete S.iceServers,delete S.iceTransportPolicy,delete S.bundlePolicy,delete S.rtcpMuxPolicy,delete S.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new Ph(m,!0),this.handler=n(),this.handler.enableHighBitrate=(w=h==null?void 0:h.enableHighBitrate)!=null?w:!1,this.handler.enableStereo=(_=h==null?void 0:h.enableStereo)!=null?_:!1,this.handler.enableDtx=(C=h==null?void 0:h.enableDtx)!=null?C:!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(V=>{const x=setTimeout(()=>{m.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),V(!1)},y);this.once("connected",()=>{clearTimeout(x),V(!0)}),this.once("disconnect",()=>{clearTimeout(x),V(!1)}),this.once("close",()=>{clearTimeout(x),V(!1)})}),this.handler.on("@connectionstatechange",V=>{V!==this.connectionState&&(this.logger.debug(`connection state changed to ${V}`),this.connectionState=V,V==="connected"&&(this.connected=!0,this.emit("connected")),V==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(V==="failed"||V==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",V))}),this.handler.on("@icecandidate",({candidate:V})=>{this.closed||this.safeEmit("icecandidate",V)})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId!==e&&(this.serverId=e,this.emit("serveridchange",e))}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(co).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(co)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new kt("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 kt("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new ao("not a sending Transport");if(r.readyState==="ended")throw new kt("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 Lr("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:S,rtpSender:y}=await this.awaitQueue.push(async()=>{const{offerSdp:w,callback:_,sender:C,mid:V}=await this.handler.send({track:n,encodings:o,codecOptions:c,screenShare:h==null?void 0:h.screenShare}),{answer:x,producerId:B}=await r({offer:w,kind:n.kind,paused:l?!n.enabled||Object.hasOwn(n,"fakeTracks"):!1,appData:{...h||{},mid:V},codecOptions:c,producingTransportId:this.serverId}),j=await _(x);return{producerId:B,localId:j,rtpSender:C}},"Transport.produce");return this.createProducerObject({id:m,localId:S,track:n,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:h,handler:this.handler,rtpSender:y})}async createProducerObject(e){const r=new UD(a(this,fa),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 kt("closed");if(this.direction!=="recv")throw new ao("not a receiving transport");if(!await this.transportConnectionPromise)throw new Lr("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=wi(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=wi(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:Gd(n)}}static parseHeaderExtensionMappings(e){const r=wi(e.sdp),i={};return r.media.forEach(n=>{i[n.mid]=n.ext}),i}static setHeaderExtensionMappings(e,r){const i=wi(e.sdp);return i.media=i.media.map(o=>{const c={...o};return c.ext=r[o.mid],c}),{...e,sdp:Gd(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),n=Sa.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=Sa.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=Sa.setCodecAndFmtpMappings(c,i,n),c=Sa.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=wi(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=Gd(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))}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,S=`${c}:${h}`,y={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(w,_)=>{const C=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${S} producingPeerId: ${n}`),this.consumerTrackEvents.delete(S),y.isTimedout=!0,_(y)},5e3),V=(B,j)=>{try{if(B.readyState==="ended")clearTimeout(C),_(y);else{const F=B;F.enabled=!0,this.handler.midTransceiverMap.set(j.mid,j);const Z=new xD(a(this,fa),{id:r,localId:j.mid,transceiver:j,track:F,paused:d,producerId:i,producingPeerId:n,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:n},rtpReceiver:j.receiver,mimeType:m});this.consumers.set(r,Z),Z.once("close",()=>{this.consumers.delete(Z.id),this.handler.midTransceiverMap.delete(j.mid)}),this.logger.info("consumer created for ",{consumer:{id:r,kind:h,appData:{screenShare:l},peerId:n,producerId:i}}),this.emit("newconsumer",Z),clearTimeout(C),w(Z)}}catch(F){this.logger.warn("error while creating consumer:",F),clearTimeout(C),_(y)}},x=this.unknownTracksMap.get(S);x?(this.logger.info(`track event already received [trackId: ${x.track.id}] [mid: ${x.transceiver.mid}]`),this.unknownTracksMap.delete(S),V(x.track,x.transceiver)):(this.logger.info(`Registering onTrack handler for key ${S} [producingPeerId: ${n}]`),this.consumerTrackEvents.set(S,V))})}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)}};let Ih=Sa;fa=new WeakMap;function $D(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=hp.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 BD{constructor(t,{handlerName:e,handlerFactory:r}={}){p(this,"handlerFactory");g(this,fr,void 0);g(this,zi,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),f(this,fr,t),f(this,zi,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,zi).debug(`Device::constructor() | handler given: ${e}`);else if(e=$D(a(this,zi)),e)a(this,zi).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=kh.createFactory(a(this,fr));break;case"Safari12":this.handlerFactory=Rh.createFactory(a(this,fr));break;case"Firefox60":this.handlerFactory=Wd.createFactory(a(this,fr),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=Wd.createFactory(a(this,fr),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=La();return new Ih(a(this,fr),{id:e,...t,handlerFactory:this.handlerFactory})}}fr=new WeakMap,zi=new WeakMap;const FD=2e3;class HD extends gt.EventEmitter{constructor(e,r){super();g(this,Ea);g(this,ec);g(this,kl);g(this,tc);g(this,Cl);g(this,Rl);g(this,Il);g(this,Al);g(this,Ml);g(this,sc);g(this,si);p(this,"context");g(this,va,void 0);g(this,tt,void 0);g(this,st,void 0);g(this,Qo,void 0);g(this,Xo,void 0);g(this,Yi,void 0);g(this,Ta,void 0);g(this,Zo,void 0);g(this,ya,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});g(this,Qi,void 0);g(this,Us,"all");this.context=e,f(this,Yi,r),f(this,va,new BD(e)),f(this,Ta,new RD(r)),f(this,Zo,hs),a(this,Ea,au).mediaState={send:{state:Ds.NEW},recv:{state:Ds.NEW}},Tn(this.context,"forceRelay")&&f(this,Us,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,Us)}`),N(this,ec,sp).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,Yi)}get socketHandler(){return a(this,Ta)}get sendTransport(){return a(this,tt)}get recvTransport(){return a(this,st)}get events(){return a(this,Zo)}set sendTransportConnectedCallback(e){f(this,Qo,e)}set recvTransportConnectedCallback(e){f(this,Xo,e)}async setupTransports(e){await N(this,kl,rv).call(this,e);let r,i;e.send&&(r=N(this,tc,rp).call(this,a(this,tt)).then(n=>{try{a(this,Qo).call(this,n)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=N(this,tc,rp).call(this,a(this,st)).then(n=>{try{a(this,Xo).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,tt);this.logger.info("Closing send transport",{transport:{id:n,serverId:o,type:c}}),a(this,tt).close(),a(this,tt).removeAllListeners(),f(this,tt,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,st);this.logger.info("Closing recv transport",{transport:{id:n,serverId:o,type:c}}),(r=a(this,st))==null||r.close(),(i=a(this,st))==null||i.removeAllListeners(),f(this,st,void 0)}N(this,ec,sp).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}va=new WeakMap,tt=new WeakMap,st=new WeakMap,Qo=new WeakMap,Xo=new WeakMap,Yi=new WeakMap,Ta=new WeakMap,Zo=new WeakMap,ya=new WeakMap,Qi=new WeakMap,Us=new WeakMap,Ea=new WeakSet,au=function(){return this.context.getValue("connectionHandler")},ec=new WeakSet,sp=function(){f(this,Qi,{send:void 0,recv:void 0})},kl=new WeakSet,rv=async function(e){var o,c,d,l,u,h,m,S;Tn(this.context,"forceRelay")&&f(this,Us,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,Us)}`);const n=await Pt().getICEServers().catch(y=>(this.logger.warn(`failed to get iceservers from server: ${y.message}`),[]));e.send&&N(this,Rl,nv).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,Us)}),e.recv&&N(this,Il,av).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(S=this.context.getValue("modules").e2ee)==null?void 0:S.enabled},iceTransportPolicy:a(this,Us)})},tc=new WeakSet,rp=async function(e){const{id:r,serverId:i,direction:n}=e;N(this,Al,ov).call(this,e);try{return await Jf(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 Lr("Cannot reconnect closed transport");await N(this,Cl,iv).call(this,e)}catch(l){if(l instanceof Lr){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}},Cl=new WeakSet,iv=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!a(this,Yi).isConnected)throw new Lr("Socket is not connected");if(e.connectionState==="closed")throw new Lr("Transport is closed");try{await e.connect(n=>N(this,Ml,cv).call(this,i,n)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(n){throw a(this,ya).transportFailureCount[i]+=1,n.message==="ice connection failed"?new Lr(n.message):n}},Rl=new WeakSet,nv=function(e){var r,i;if(a(this,tt)&&a(this,tt).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=a(this,tt))==null?void 0:r.id,serverId:(i=a(this,tt))==null?void 0:i.serverId,type:"send"}});return}f(this,tt,a(this,va).createTransport({...e,direction:"send"})),N(this,si,Va).call(this,{state:Ds.NEW,direction:"send",sfuSessionId:a(this,tt).serverId}),this.context.getValue("callstats").configureSendTransport(a(this,tt))},Il=new WeakSet,av=function(e){var r,i;if(a(this,st)&&a(this,st).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=a(this,st))==null?void 0:r.id,serverId:(i=a(this,st))==null?void 0:i.serverId,type:"recv"}});return}f(this,st,a(this,va).createTransport({...e,direction:"recv"})),N(this,si,Va).call(this,{state:Ds.NEW,direction:"recv",sfuSessionId:a(this,st).serverId}),this.context.getValue("callstats").configureRecvTransport(a(this,st))},Al=new WeakSet,ov=function(e){const{direction:r,id:i}=e;e.on("serveridchange",n=>{N(this,si,Va).call(this,{state:e.connectionState,direction:r,sfuSessionId:n})}),e.on("connectionstatechange",async n=>{N(this,si,Va).call(this,{state:n,direction:r,sfuSessionId:e.serverId}),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,Qi)[r];c!==void 0&&(clearTimeout(c),a(this,Qi)[r]=void 0)};switch(n){case"connected":o(),a(this,ya).lastConnectionTime=performance.now();break;case"disconnected":a(this,Qi)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await N(this,sc,ip).call(this,e.direction)},FD);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 N(this,sc,ip).call(this,e.direction);break}}),e.on("icecandidate",async n=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:n})})},Ml=new WeakSet,cv=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?Ks.SUBSCRIBER:Ks.PUBLISHER},producers:[]};return a(this,Ta).connectTransport(c)}catch(n){throw this.logger.error(`Error in ${e} transport connection:`,{error:n}),n}},sc=new WeakSet,ip=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),a(this,Yi).isConnected&&a(this,ya).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),f(this,Us,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:a(this,tt)}),this.context.getValue("peerSessionStore").emit(k.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,st)}),this.context.getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}const r=e==="send"?a(this,tt):a(this,st);N(this,si,Va).call(this,{state:Ds.CONNECTED,direction:e,sfuSessionId:r.serverId})},si=new WeakSet,Va=function(e){const{state:r,direction:i,sfuSessionId:n}=e;a(this,Ea,au).mediaState[i]={state:r,sfuSessionId:n},this.context.getValue("peerSessionStore").emit(k.TRANSPORT_STATE_UPDATE,{transport:i,...a(this,Ea,au).mediaState[i]})};class qD{constructor(t,e,r,i,n){g(this,Ol,void 0);g(this,ns,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=n,f(this,Ol,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:Ks.SUBSCRIBER}};return a(this,ns).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,Ok.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:Ks.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=nR.fromBinary(c).description;return{sdp:d.sdp,type:d.type}};await this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(t,e),"SocketConsumerStrategy.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)})}}Ol=new WeakMap,ns=new WeakMap;class Ah{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return wi(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:Ks.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}}}function jD(s){try{const t=JSON.parse(s.message);if(typeof t!="object"||t===null)return{};const{errorCode:e,errorDescription:r}=t;return{...typeof e=="string"&&{errorCode:e},...typeof r=="string"&&{errorDescription:r}}}catch(t){return{}}}class GD extends HD{constructor(e,r){super(e,r);g(this,ic);g(this,Nl);g(this,Vl);g(this,Ll);g(this,xl);g(this,ri,void 0);g(this,ii,void 0);g(this,ba,void 0);g(this,rc,void 0);g(this,$s,void 0);g(this,Dl,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});g(this,Sr,[]);g(this,wa,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{f(this,rc,new Ah(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{a(this,ba).clear(),f(this,$s,new qD(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,ri)}get consumers(){return a(this,ii)}get producerIdToConsumerIdMap(){return a(this,ba)}get logger(){return this.context.getValue("logger")}reset(){f(this,ri,new Map),f(this,ii,new Map),f(this,ba,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,N(this,Nl,dv).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_PRODUCER,o),N(this,Vl,lv).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,Dl).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,ri).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,ri).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(co)}))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){a(this,wa)||clearTimeout(a(this,wa)),f(this,Sr,a(this,Sr).concat(e)),await N(this,ic,np).call(this)}closeConsumer(e){return this.closeConsumers([e])}async closeConsumers(e){if(!a(this,$s))return;const r=e.map(i=>this.consumers.get(i)).filter(i=>i!==void 0);r.length!==0&&await a(this,$s).close(r)}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,ii).keys()))}async switchConsumersToLayer(e,r){a(this,$s).switchConsumersToLayer(e,r)}}ri=new WeakMap,ii=new WeakMap,ba=new WeakMap,rc=new WeakMap,$s=new WeakMap,Dl=new WeakMap,Sr=new WeakMap,wa=new WeakMap,ic=new WeakSet,np=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=a(this,Sr).splice(0,a(this,Sr).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,N(this,Ll,uv).bind(this),a(this,$s).negotiate.bind(a(this,$s)));if(o.forEach(N(this,xl,hv).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,Sr,a(this,Sr).concat(d)),f(this,wa,setTimeout(N(this,ic,np).bind(this),e))}}catch(i){const n=i instanceof Error?i:new Error(String(i));this.logger.error("failed to consume on transport",{error:n});const{errorCode:o,errorDescription:c}=jD(n);if(o==="internal_error"&&c==="Backend error"||o==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:o,message:c}});try{this.stopTransports({recv:!0})}catch(d){}await this.setupTransports({recv:!0})}}},Nl=new WeakSet,dv=function(e){return a(this,rc).create(e)},Vl=new WeakSet,lv=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!==co){const d={producerId:e.id,description:{sdp:o.sdp,type:o.type,target:Ks.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,ri).set(e.id,e)},Ll=new WeakSet,uv=async function(e){try{return await this.recvTransport.canConsume(),await a(this,$s).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},xl=new WeakSet,hv=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,ii).delete(e.id),this.context.getValue("peerSessionStore").emit(k.CONSUMER_CLOSED,{id:e.id})}),a(this,ii).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 Hl=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,Ul);g(this,$l);g(this,nc,void 0);g(this,ac,void 0);g(this,oc,void 0);g(this,Pa,void 0);g(this,_a,void 0);g(this,ka,void 0);g(this,cc,void 0);g(this,dc,void 0);g(this,Ca,void 0);g(this,Rt,void 0);g(this,Es,void 0);g(this,bs,!1);g(this,Xi,0);g(this,Zi,0);g(this,vr,[]);g(this,lc,void 0);f(this,Pa,t),f(this,Rt,t),f(this,nc,e),f(this,ac,r),f(this,oc,i),f(this,_a,n),f(this,ka,o),f(this,cc,c),f(this,dc,d),f(this,Ca,l),f(this,lc,u),f(this,Es,t/2)}get voiceDetected(){return a(this,bs)}processAudioChunk(t){var o,c;const e=N(o=Hl,Bl,gv).call(o,t),r=N(c=Hl,Fl,fv).call(c,t);return N(this,Ul,pv).call(this,e),e/a(this,Es)>a(this,Ca)&&e>a(this,Rt)&&r>a(this,nc)?(f(this,Xi,a(this,Xi)+1),f(this,Zi,a(this,oc)),a(this,Xi)>=a(this,ac)&&f(this,bs,!0)):(f(this,Xi,0),a(this,Zi)>0?f(this,Zi,a(this,Zi)-1):a(this,bs)&&f(this,bs,!1),a(this,bs)||N(this,$l,mv).call(this,e)),{energy:e,isVoice:a(this,bs)}}reset(){f(this,bs,!1),f(this,Xi,0),f(this,Zi,0),f(this,Rt,a(this,Pa)),f(this,Es,a(this,Pa)/2),f(this,vr,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,Rt),backgroundNoiseEnergy:a(this,Es),energyRatioThreshold:a(this,Ca)}}};let lo=Hl;nc=new WeakMap,ac=new WeakMap,oc=new WeakMap,Pa=new WeakMap,_a=new WeakMap,ka=new WeakMap,cc=new WeakMap,dc=new WeakMap,Ca=new WeakMap,Rt=new WeakMap,Es=new WeakMap,bs=new WeakMap,Xi=new WeakMap,Zi=new WeakMap,vr=new WeakMap,lc=new WeakMap,Ul=new WeakSet,pv=function(t){a(this,bs)?f(this,Rt,a(this,ka)*a(this,Rt)+(1-a(this,ka))*t):f(this,Rt,a(this,_a)*a(this,Rt)+(1-a(this,_a))*a(this,Es)),f(this,Rt,Math.max(a(this,cc),Math.min(a(this,dc),a(this,Rt))))},$l=new WeakSet,mv=function(t){if(t<a(this,Rt)*1.2)if(a(this,vr).push(t),a(this,vr).length>a(this,lc)&&a(this,vr).shift(),a(this,vr).length>=10){const e=[...a(this,vr)].sort((i,n)=>i-n),r=Math.floor(e.length/2);f(this,Es,e[r])}else f(this,Es,.95*a(this,Es)+.05*t)},Bl=new WeakSet,gv=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Fl=new WeakSet,fv=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(lo,Bl),g(lo,Fl);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 WD{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 JD=60,KD=400,gc=class{constructor(t,e){g(this,ql);g(this,jl);g(this,Tr,void 0);g(this,yr,void 0);g(this,Er,void 0);g(this,pc,void 0);g(this,Ra,void 0);g(this,Ia,void 0);g(this,ni,void 0);g(this,en,void 0);g(this,Aa,void 0);g(this,tn,void 0);g(this,br,void 0);g(this,Bs,void 0);this.reportRequest=e,f(this,tn,t),f(this,Ia,new lo);const{isReactNative:r}=navigator;f(this,br,r?new Yf(a(this,tn)):new Qf(a(this,tn))),f(this,Bs,r?WD:Nf)}get logger(){return a(this,tn).getValue("logger")}set producerId(t){f(this,Er,t)}set audioTrack(t){f(this,pc,t),a(this,br)instanceof Qf&&(a(this,br).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${a(this,Er)}`),a(this,Tr)&&a(this,Bs).clearInterval(a(this,Tr)),f(this,Tr,a(this,Bs).setInterval(async()=>{var i;if(!a(this,pc)||!a(this,Er))return;const{energy:t}=N(this,ql,Sv).call(this),e=N(i=gc,mc,ap).call(i,t);let r=.9;a(this,Aa)!==e&&a(this,Aa)?r=.9:e?r=.3:r=.5,f(this,Ra,(a(this,Ra)||0)*(1-r)+t*r)},JD)),a(this,yr)&&a(this,Bs).clearInterval(a(this,yr)),f(this,yr,a(this,Bs).setInterval(N(this,jl,vv).bind(this),KD))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${a(this,Er)}`),a(this,Tr)&&(a(this,Bs).clearInterval(a(this,Tr)),f(this,Tr,void 0)),a(this,yr)&&(a(this,Bs).clearInterval(a(this,yr)),f(this,yr,void 0))}catch(t){}a(this,Ia).reset(),a(this,br)instanceof Yf&&a(this,br).stop()}};let uo=gc;Tr=new WeakMap,yr=new WeakMap,Er=new WeakMap,pc=new WeakMap,Ra=new WeakMap,Ia=new WeakMap,ni=new WeakMap,en=new WeakMap,Aa=new WeakMap,tn=new WeakMap,br=new WeakMap,Bs=new WeakMap,ql=new WeakSet,Sv=function(){var o;const{samples:t}=a(this,br),{energy:e,isVoice:r}=a(this,Ia).processAudioChunk(t),i=N(o=gc,Gl,Tv).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,ni)||i<a(this,ni))&&f(this,ni,i),(!a(this,en)||i>a(this,en))&&f(this,en,i),{energy:(i-a(this,ni))/(a(this,en)-a(this,ni))*10||0,isVoice:r})},mc=new WeakSet,ap=function(t){return t<5},jl=new WeakSet,vv=function(t=a(this,Ra)){var r;if(!a(this,Er)||!t)return;const e={producerId:a(this,Er),energy:Math.round(t),silent:N(r=gc,mc,ap).call(r,t)};f(this,Aa,e.silent),this.reportRequest(e)},Gl=new WeakSet,Tv=function(t){const e=Math.log10(t);return Math.round(e)},g(uo,mc),g(uo,Gl);var zD=Object.defineProperty,YD=Object.getOwnPropertyDescriptor,de=(s,t,e,r)=>{for(var i=r>1?void 0:r?YD(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};class ae{constructor(t,e){g(this,wr);g(this,Jl);g(this,Kl);g(this,zl);g(this,Tc);g(this,Yl);g(this,Ql);g(this,wt);g(this,an);g(this,Xl);g(this,Zl);g(this,eu);p(this,"context");p(this,"authToken");p(this,"e2ee");g(this,fc,void 0);g(this,Sc,void 0);g(this,ht,void 0);g(this,H,void 0);g(this,Wl,void 0);g(this,bt,void 0);g(this,sn,void 0);g(this,rn,void 0);g(this,nn,void 0);g(this,vc,void 0);g(this,Ht,null);g(this,Fs,void 0);g(this,pt,void 0);g(this,It,void 0);var i,n;this.context=t;const{socket:r}=e;this.mediaJoined=!1,f(this,ht,r),f(this,sn,!1),f(this,H,new GD(t,r)),f(this,bt,a(this,H).events),f(this,Fs,new Set),f(this,pt,new Map),f(this,rn,!1),f(this,nn,new Ph(t.getValue("logger"))),f(this,It,new uo(this.context,a(this,H).socketHandler.audioActivity.bind(a(this,H).socketHandler))),this.e2ee=(n=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,vc,Ou(async()=>{if(!a(this,wr,pn).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(a(this,Sc),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,wr,pn).mediaJoined}set mediaJoined(t){a(this,wr,pn).mediaJoined=t}reset({resetTransportQueue:t}){this.logger.info(`Resetting media node client: closing all transports, producers, consumers, and queues(resetTransportQueue: ${t}).`),a(this,H).closeAllProducers(),a(this,H).closeAllConsumers(),a(this,pt).clear(),a(this,Fs).clear(),f(this,Ht,null),t&&a(this,nn).stop(),a(this,H).stopAllTransports(),a(this,H).reset(),t&&f(this,nn,new Ph)}async joinRoom(t,e,r=!1,i={}){a(this,wr,pn).mediaJoinAttempted=!0,f(this,sn,!0);try{return await a(this,nn).push(()=>N(this,Jl,yv).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,Ht)?a(this,Ht):(f(this,Ht,(async()=>{try{await N(this,Tc,op).call(this,t,e,r,i)}catch(n){throw f(this,Ht,null),n}})()),a(this,Ht))}getConsumers(){return a(this,H).consumers}getProducers(){return a(this,H).producers}async leaveRoom(){a(this,H).stopAllTransports(),f(this,rn,!1),a(this,wr,pn).mediaJoinAttempted=!1;const t={closeRoom:!1};a(this,ht).sendMessagePromise(a(this,bt).leaveRoom,rC.toBinary(t)).then(r=>{var i;(i=GC.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,H).createConsumers(t)}async closeConsumers(t){if(!t.length)return;const e=t.reduce((r,i)=>{const n=a(this,H).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,H).closeConsumers(e)}async _shareWebcam(t){var u,h,m,S;const e=Ae.WEBCAM,r=N(this,wt,Wt).call(this,e);if(r){const y=await r;if(a(this,H).producers.has(y)){const w=a(this,H).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=N(this,eu,Cv).call(this,t),n=Tn(this.context,"disableSimulcast"),o=(h=(u=this.context)==null?void 0:u.getValue("overrides"))==null?void 0:h.simulcastConfig;n||o&&o.disable||!((S=(m=this.context)==null?void 0:m.getValue("theme"))!=null&&S.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),i.encodings=OO(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,H).createProducer(i,d);return N(this,an,Wc).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(Ae.SCREENSHARE_VIDEO),a(this,pt).delete(Ae.SCREENSHARE_AUDIO)},o=a(this,H).createProducer(i,n);N(this,an,Wc).call(this,Ae.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,H).createProducer(d,l),N(this,an,Wc).call(this,Ae.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 kt("track undefined");const e=N(this,wt,Wt).call(this,Ae.MIC);if(e){const o=await e;if(a(this,H).producers.has(o)){const c=a(this,H).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),a(this,It)&&(a(this,It).audioTrack=t,a(this,It).producerId=o,a(this,It).start());return}await a(this,H).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=N(this,Zl,kv).call(this,t),i=()=>{a(this,pt).delete(Ae.MIC)},n=a(this,H).createProducer(r,i);N(this,an,Wc).call(this,Ae.MIC,n.then(o=>o.id)),await n.then(o=>{a(this,It)&&(a(this,It).audioTrack=o.track,a(this,It).producerId=o.id,a(this,It).start())})}catch(e){throw new R(e)}}async pauseMic(){var i;const t=await N(this,wt,Wt).call(this,Ae.MIC),e=a(this,H).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,It))==null||i.stop();const r={producerId:e.id,pause:!0};a(this,ht).sendMessage(a(this,bt).toggleProducer,kd.toBinary(r))}async pauseWebcam(){const t=await N(this,wt,Wt).call(this,Ae.WEBCAM),e=a(this,H).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,bt).toggleProducer,kd.toBinary(r))}async resumeMic(){const t=await N(this,wt,Wt).call(this,Ae.MIC),e=a(this,H).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,bt).toggleProducer,kd.toBinary(r))}async resumeWebcam(t=Ae.WEBCAM){const e=await N(this,wt,Wt).call(this,t),r=a(this,H).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,bt).toggleProducer,kd.toBinary(i))}async disableWebcam(){const t=Ae.WEBCAM,e=await N(this,wt,Wt).call(this,t);N(this,Xl,_v).call(this,t),e&&await a(this,H).closeProducer(e)}async disableMic(){var e;const t=await N(this,wt,Wt).call(this,Ae.MIC);t&&await a(this,H).closeProducer(t),(e=a(this,It))==null||e.stop(),a(this,pt).delete(Ae.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await N(this,wt,Wt).call(this,Ae.SCREENSHARE_VIDEO),e=await N(this,wt,Wt).call(this,Ae.SCREENSHARE_AUDIO);t&&await a(this,H).closeProducer(t),e&&await a(this,H).closeProducer(e),a(this,Fs).clear(),a(this,pt).delete(Ae.SCREENSHARE_VIDEO),a(this,pt).delete(Ae.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await N(this,wt,Wt).call(this,Ae.WEBCAM);await a(this,H).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await N(this,wt,Wt).call(this,Ae.SCREENSHARE_VIDEO);await a(this,H).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,H).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};a(this,H).socketHandler.kickPeer(e)}kickAll(){a(this,H).socketHandler.kickAll()}async muteAll(t){if(!await a(this,H).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,H).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await a(this,H).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await a(this,H).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,bt).globalPinPeer,SC.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&a(this,H).producers.get(t.producerId)&&a(this,Fs).add(t.consumerPeerId),a(this,Fs).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));a(this,H).switchConsumersToLayer(r,e)}async handleSocketEvents(){a(this,ht).on(a(this,bt).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:r}=ER.fromBinary(t);if(e===this.peerId)return;r!=null&&r.mimeType||(r.mimeType=r.kind===zs.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===zs.AUDIO?"audio":"video",producingPeerId:e}})}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),a(this,ht).on(a(this,bt).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:i,pause:n,producerId:o,screenShare:c}}=qg.fromBinary(t);if(c)return;const d=i===zs.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${o}, kind:${d}, paused:${n} payload: ${JSON.stringify(qg.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,bt).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=Wu.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,Fs).delete(e),a(this,H).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,bt).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=PR.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,H).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,H).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),a(this,H).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,bt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,sn)&&!a(this,rn)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(k.ROOM_NODE_DISCONNECTED),a(this,vc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=a(this,H).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,H).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,Sc=new WeakMap,ht=new WeakMap,H=new WeakMap,Wl=new WeakMap,bt=new WeakMap,sn=new WeakMap,rn=new WeakMap,nn=new WeakMap,vc=new WeakMap,Ht=new WeakMap,Fs=new WeakMap,pt=new WeakMap,It=new WeakMap,wr=new WeakSet,pn=function(){return this.context.getValue("connectionHandler")},Jl=new WeakSet,yv=async function(t,e,r,i){var o;f(this,Sc,t);let n=!1;if(r){const{recv:c,send:d}=(o=a(this,wr,pn).mediaState)!=null?o:{};(d==null?void 0:d.state)===Ds.CONNECTED&&(c==null?void 0:c.state)===Ds.CONNECTED?(this.logger.info("MediaNodeClient.joinRoom: transports healthy — partial reset (producers only)"),await a(this,H).closeAllProducersLocally(),a(this,pt).clear(),a(this,Fs).clear(),f(this,Ht,null),n=!0):(this.logger.info("MediaNodeClient.joinRoom: transports unhealthy — full reset"),this.reset({resetTransportQueue:!1}))}try{a(this,Ht)?await a(this,Ht):await N(this,Tc,op).call(this,t,e,r,i,n),N(this,zl,bv).call(this,e);const{joined:c,error:d}=await N(this,Kl,Ev).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,Ht,null)}},Kl=new WeakSet,Ev=async function(){try{this.mediaJoined=!0;const{roomState:t}=await a(this,H).socketHandler.notifySelfJoinComplete();return f(this,fc,t.roomUuid),f(this,rn,!0),f(this,sn,!1),{joined:!0}}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,{joined:!1,error:t}}},zl=new WeakSet,bv=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,op=async function(t,e,r,i,n=!1){try{const o=N(this,Yl,wv).call(this);await N(this,Ql,Pv).call(this,t,e,r,o),n?this.logger.info("MediaNodeClient: reusing existing transports on rejoin"):await a(this,H).setupTransports({send:!0,recv:!0})}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},Yl=new WeakSet,wv=function(){const t=CD("video/VP8");return f(this,Wl,t),t},Ql=new WeakSet,Pv=async function(t,e,r,i){await Jf(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,H).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})},wt=new WeakSet,Wt=function(t){return a(this,pt).get(t)},an=new WeakSet,Wc=function(t,e){return a(this,pt).set(t,e)},Xl=new WeakSet,_v=function(t){return a(this,pt).delete(t)},Zl=new WeakSet,kv=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},eu=new WeakSet,Cv=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 QD(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 XD=Object.defineProperty,ZD=Object.getOwnPropertyDescriptor,Pi=(s,t,e,r)=>{for(var i=r>1?void 0:r?ZD(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&&XD(t,e,i),i};const Zf=(HS=class{constructor(s,t,e,r){g(this,At);p(this,"self");p(this,"authToken");g(this,Ma,void 0);p(this,"viewType");g(this,ws,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,Ma,i),f(this,ws,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=Pt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await Ke.__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:b_(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,At,os).shareMic(s),this.self.audioEnabled||a(this,At,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,At,os).shareWebcam(t),this.self.videoEnabled||a(this,At,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,At,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,At,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,Ma).updateURL(t),a(this,ee).getValue("telemetry").resetPeerId(t),Pt().setHeader("tracing-id",t),Rr.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,ws).on(U.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,ws).on(Od.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,ee).getValue("peerSessionStore").emit(k.UPDATE_PERMISSIONS,t.patch)})}),a(this,ws).on(U.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,ws).on(U.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,ws).on(U.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,ws).joinRoom(this.self);this.logger.info("Joined socket room."),a(this,ws).socket.flush();const e=lh(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 R("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 Lr&&t.message==="ice connection failed"?new R("A firewall or network restriction may be blocking the connection.","0014"):new R("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===Ws.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}Xf(a(this,ee),{socket:a(this,Ma),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:h}=(o=await((n=a(this,At,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===Ws.Webinar)&&a(this,At,os)&&(a(this,At,os).mediaJoined&&s!=="disconnected"&&await a(this,At,os).leaveRoom(),!(s==="stageLeft"&&t===Ws.Livestream)&&(a(this,At,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()}},Ma=new WeakMap,ws=new WeakMap,ee=new WeakMap,At=new WeakSet,os=function(){return a(this,ee).getValue("roomNodeClient")},HS);let xr=Zf;Pi([E.trace("SelfController.resetSelf")],xr.prototype,"resetSelf",1),Pi([E.trace("SelfController.setupEvents")],xr.prototype,"setupEvents",1),Pi([E.trace("SelfController.joinRoom")],xr.prototype,"joinRoom",1),Pi([E.trace("SelfController.leaveRoom")],xr.prototype,"leaveRoom",1),Pi([E.trace("SelfController.joinMediaRoom")],xr.prototype,"joinMediaRoom",1),Pi([E.trace("SelfController.leaveMediaRoom")],xr.prototype,"leaveMediaRoom",1),Pi([E.trace("SelfController.init")],xr,"init",1);class e1{constructor(t){g(this,yc,void 0);f(this,yc,t)}on(t,e){let r;t===U.roomPeerCount?r=Wg.fromBinary.bind(Wg):r=of.fromBinary.bind(of),a(this,yc).on(t,({payload:i})=>{if(t===U.roomPeerCount&&!i)return;const n=r(i);e(n)})}}yc=new WeakMap;class t1{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 U.transcript:{r=Ju.fromBinary.bind(Ju),i=Ju.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 s1=Object.defineProperty,r1=Object.getOwnPropertyDescriptor,Mh=(s,t,e,r)=>{for(var i=r>1?void 0:r?r1(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&&s1(t,e,i),i};class Jd{constructor(t,e){g(this,Pr,void 0);g(this,Oa,void 0);f(this,Pr,e),f(this,Oa,t)}get logger(){return a(this,Oa).getValue("logger")}get telemetry(){return a(this,Oa).getValue("telemetry")}getPolls(){return a(this,Pr).sendMessagePromise(Xs.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Pr).sendMessage(Xs.createPoll,ZA.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Pr).sendMessage(Xs.votePoll,tM.toBinary(r))}on(t,e){let r,i;switch(t){case Xs.updatePoll:case Xs.createPoll:case Xs.votePoll:{r=nh.fromBinary.bind(nh),i=nh.create();break}}a(this,Pr).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,Pr).removeListeners(t)}}Pr=new WeakMap,Oa=new WeakMap,Mh([E.trace("PollSocketHandler.getPolls")],Jd.prototype,"getPolls",1),Mh([E.trace("PollSocketHandler.createPoll")],Jd.prototype,"createPoll",1),Mh([E.trace("PollSocketHandler.votePoll")],Jd.prototype,"votePoll",1);var i1=Object.defineProperty,n1=Object.getOwnPropertyDescriptor,a1=(s,t,e,r)=>{for(var i=r>1?void 0:r?n1(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 eS{constructor(t,e){p(this,"socket");g(this,qt,void 0);f(this,qt,t),this.socket=e,this.handleSocketEvents(),a(this,qt).setValue("roomSocketHandler",this)}get telemetry(){return a(this,qt).getValue("telemetry")}get logger(){return a(this,qt).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(U.joinRoom,ZR.toBinary(e));try{const{peer:n}=bn.fromBinary((await r).payload);a(this,qt).getValue("connectionHandler").socketJoined=!0,a(this,qt).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,qt).getValue("peerSessionStore").emit(k.ROOM_STATE,d),a(this,qt).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 xI.fromBinary((await this.socket.sendMessagePromise(U.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(U.getRoomPeersInfo,qR.toBinary(n));i=Yu.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(U.getRoomPeersInfo);t=Yu.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(U.getRoomPeersInfo);t=Yu.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(U.getPeerInfo,zg.toBinary({peerId:t}));e=bn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=Kg.create();try{const e=await this.socket.sendMessagePromise(U.getRoomInfo);t=Kg.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=tf.create();try{const e=await this.socket.sendMessagePromise(U.getRoomStageState);t=tf.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(U.broadcastMessage,Qa.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(U.broadcastToEntity,Qa.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(U.broadcastToEntity,Qa.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(U.leaveRoom,tI.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(U.kick,Zg.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(U.kickAll,Ug.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(U.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.acceptWaitingRoomRequests,qI.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.denyWaitingRoomRequests,GI.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Od.updateUserPreset,y0.toBinary(r))}handleSocketEvents(){this.socket.on(U.broadcastMessage,({payload:t})=>{try{const e=Qa.fromBinary(t);a(this,qt).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(U.broadcastToEntity,({payload:t})=>{try{const e=Qa.fromBinary(t);a(this,qt).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 U.joinRoom:case U.leaveRoom:case U.kick:case U.kickAll:{r=bn.fromBinary.bind(bn),i=bn.create();break}case U.getWaitingRoomRequests:{r=(n,o)=>n?ef.fromBinary(n,o):{requests:[]},i=ef.create();break}case U.recordingPaused:case U.recordingStarted:case U.recordingStopped:{r=uf.fromBinary.bind(uf);break}case Od.updateUserPreset:{r=rf.fromBinary.bind(rf);break}case hs.peerJoinedBroadcast:case Mr.peerJoinedBroadcast:{r=Fg.fromBinary.bind(Fg);break}case hs.selfJoinComplete:case Mr.selfJoinComplete:{r=Gu.fromBinary.bind(Gu);break}case hs.globalPeerPinBroadcast:case Mr.globalPeerPinBroadcast:{r=jg.fromBinary.bind(jg);break}case hs.selectedPeer:case Mr.selectedPeer:{r=ju.fromBinary.bind(ju);break}case hs.selectedPeerDiff:case Mr.selectedPeerDiff:{r=Bg.fromBinary.bind(Bg);break}case hs.leaveRoom:case Mr.leaveRoom:{r=Wu.fromBinary.bind(Wu);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(Od.getUserPresets,p0.toBinary(e)),i=S0.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}}}qt=new WeakMap,a1([E.trace("RoomSocketHandler.joinRoom")],eS.prototype,"joinRoom",1);class o1{constructor(t){g(this,Mt,void 0);f(this,Mt,t)}async getStageRequests(){const{payload:t}=await a(this,Mt).sendMessagePromise(U.getStageRequests);return t?ih.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,Mt).sendMessage(U.requestStageAccess)}cancelRequestAccess(){a(this,Mt).sendMessage(U.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,Mt).sendMessage(U.grantStageAccess,qA.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,Mt).sendMessage(U.denyStageAccess,GA.toBinary(e))}joinStage(){return a(this,Mt).sendMessagePromise(U.joinStage,void 0,void 0,U.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,Mt).sendMessagePromise(U.leaveStage,df.toBinary(e),void 0,U.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,Mt).sendMessagePromise(U.leaveStage,df.toBinary(e))}on(t,e){let r;switch(t){case U.grantStageAccess:case U.denyStageAccess:{r=void 0;break}case U.getStagePeers:{r=cf.fromBinary.bind(cf);break}case U.getStageRequests:case U.requestStageAccess:case U.cancelStageRequest:{r=ih.fromBinary.bind(ih);break}case U.peerStageStatusUpdate:{r=Gg.fromBinary.bind(Gg);break}}a(this,Mt).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,Mt).sendMessagePromise(U.getPeerInfo,zg.toBinary({peerId:t}));return bn.fromBinary(e.payload)}}Mt=new WeakMap;class c1{constructor(t,e){g(this,ai,void 0);g(this,Da,void 0);f(this,ai,e),f(this,Da,t)}get logger(){return a(this,Da).getValue("logger")}get peerId(){return a(this,Da).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,ai).sendMessage(Qs.storeInsertKeys,wA.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,ai).sendMessage(Qs.storeGetKeys,_A.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,ai).sendMessage(Qs.storeDeleteKeys,CA.toBinary(n),i)}on(t,e){const r=af.fromBinary.bind(af);a(this,ai).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}ai=new WeakMap,Da=new WeakMap;var d1=Object.defineProperty,l1=(s,t,e)=>t in s?d1(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,u1=(s,t,e)=>(l1(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),Kd={},h1={get exports(){return Kd},set exports(s){Kd=s}},Rn=typeof Reflect=="object"?Reflect:null,tS=Rn&&typeof Rn.apply=="function"?Rn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},zd;Rn&&typeof Rn.ownKeys=="function"?zd=Rn.ownKeys:Object.getOwnPropertySymbols?zd=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:zd=function(s){return Object.getOwnPropertyNames(s)};function p1(s){console&&console.warn&&console.warn(s)}var sS=Number.isNaN||function(s){return s!==s};function ue(){ue.init.call(this)}h1.exports=ue,Kd.once=S1,ue.EventEmitter=ue,ue.prototype._events=void 0,ue.prototype._eventsCount=0,ue.prototype._maxListeners=void 0;var rS=10;function Yd(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 rS},set:function(s){if(typeof s!="number"||s<0||sS(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");rS=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||sS(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 iS(s){return s._maxListeners===void 0?ue.defaultMaxListeners:s._maxListeners}ue.prototype.getMaxListeners=function(){return iS(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")tS(c,this,t);else for(var d=c.length,l=dS(c,d),e=0;e<d;++e)tS(l[e],this,t);return!0};function nS(s,t,e,r){var i,n,o;if(Yd(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=iS(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,p1(c)}return s}ue.prototype.addListener=function(s,t){return nS(this,s,t,!1)},ue.prototype.on=ue.prototype.addListener,ue.prototype.prependListener=function(s,t){return nS(this,s,t,!0)};function m1(){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 aS(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=m1.bind(r);return i.listener=e,r.wrapFn=i,i}ue.prototype.once=function(s,t){return Yd(t),this.on(s,aS(this,s,t)),this},ue.prototype.prependOnceListener=function(s,t){return Yd(t),this.prependListener(s,aS(this,s,t)),this},ue.prototype.removeListener=function(s,t){var e,r,i,n,o;if(Yd(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():g1(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 oS(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?f1(i):dS(i,i.length)}ue.prototype.listeners=function(s){return oS(this,s,!0)},ue.prototype.rawListeners=function(s){return oS(this,s,!1)},ue.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):cS.call(s,t)},ue.prototype.listenerCount=cS;function cS(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?zd(this._events):[]};function dS(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function g1(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function f1(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))}lS(s,t,n,{once:!0}),t!=="error"&&v1(s,i,{once:!0})})}function v1(s,t,e){typeof s.on=="function"&&lS(s,"error",t,e)}function lS(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 T1 extends v{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 uS=new T1;class hS{static encode(t){return uS.toBinary(t)}static decode(t){return uS.fromBinary(new Uint8Array(t))}}function y1(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Ur;class E1{constructor(t={}){u1(this,"opts"),le(this,Ur,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ie(this,Ur,0)}async wait(){ie(this,Ur,M(this,Ur)+1);const t=y1(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**M(this,Ur)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return M(this,Ur)}reset(){ie(this,Ur,0)}}Ur=new WeakMap;const $r={debug:0,info:1,warn:2,error:3};var _i,ki;class b1{constructor(t){le(this,_i,void 0),le(this,ki,void 0),ie(this,_i,console),ie(this,ki,t)}debug(...t){$r[M(this,ki)]>$r.debug||M(this,_i).debug("[Sockrates]:",...t)}info(...t){$r[M(this,ki)]>$r.info||M(this,_i).info("[Sockrates]:",...t)}warn(...t){$r[M(this,ki)]>$r.warn||M(this,_i).warn("[Sockrates]:",...t)}error(...t){$r[M(this,ki)]>$r.error||M(this,_i).error("[Sockrates]:",...t)}}_i=new WeakMap,ki=new WeakMap;var pS=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(pS||{});const mS="2",gS="3";var Oe,In,he,Ce,Br,ze,ir,Fr,ms,An,Mn,nr,Dh,fS,ho,Qd,Nh,SS,Xd,Vh,Zd,Lh,xh,vS,po,el,On,mo,tl,Uh,Dn,go,$h,TS,fo,sl,So,rl;class w1{constructor(t,e){var y,w,_,C,V,x,B,j,F,Z,be,Ge;le(this,Dh),le(this,ho),le(this,Nh),le(this,Xd),le(this,Zd),le(this,xh),le(this,po),le(this,On),le(this,tl),le(this,Dn),le(this,$h),le(this,fo),le(this,So),le(this,Oe,void 0),le(this,In,void 0),le(this,he,void 0),le(this,Ce,void 0),le(this,Br,void 0),le(this,ze,void 0),le(this,ir,void 0),le(this,Fr,void 0),le(this,ms,void 0),le(this,An,void 0),le(this,Mn,void 0),le(this,nr,void 0);var r,i,n,o,c,d,l,u,h,m,S;ie(this,In,t),ie(this,Br,[]),ie(this,ze,new Kd),ie(this,ir,!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),(_=(n=M(this,he)).pingTimeout)!=null||(n.pingTimeout=3e4),(C=(o=M(this,he)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(V=(c=M(this,he)).debug)!=null||(c.debug=!0),(x=(d=M(this,he)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(B=(l=M(this,he)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(j=(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),(be=(S=M(this,he)).clientInitiatedPingInterval)!=null||(S.clientInitiatedPingInterval=3e4),ie(this,Fr,{code:void 0,reason:void 0}),ie(this,Ce,(Ge=M(this,he).logger)!=null?Ge:new b1(M(this,he).debug?"debug":"info")),ie(this,nr,new E1)}get readyState(){var t;return(t=M(this,Oe))==null?void 0:t.readyState}get url(){return M(this,In)}updateURL(t){ie(this,In,t),ne(this,xh,vS).call(this)}get config(){return M(this,he)}get sendQueue(){return M(this,Br)}flush(){if(!M(this,he).queueOnDisconnect)return!1;const t=[];return M(this,Br).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ie(this,Br,t),M(this,Br)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){M(this,Ce).debug("Websocket was already connecting or connected.");return}if(M(this,ir)!==!1)return new Promise((e,r)=>{ne(this,Dn,go).call(this),ne(this,So,rl).call(this);try{ie(this,Oe,new WebSocket(ne(this,Dh,fS).call(this,M(this,In)))),M(this,Oe).binaryType="arraybuffer",M(this,Ce).debug("Connecting");const i=setTimeout(()=>{M(this,Ce).debug("Connection timeout. Closing socket"),ie(this,ir,!0),ne(this,So,rl).call(this),M(this,Oe).close(3001,"Connection Timeout"),M(this,he).autoReconnect&&!M(this,ms)&&(M(this,ze).emit("reconnecting"),ne(this,po,el).call(this)),r(new Error("Connection timed out!"))},M(this,he).connectionTimeout);M(this,Oe).onopen=()=>{M(this,Ce).debug(`Ready State: ${pS[M(this,Oe).readyState]}`),i&&clearTimeout(i),ne(this,tl,Uh).call(this),ne(this,$h,TS).call(this),ie(this,Fr,{code:void 0,reason:void 0}),M(this,ze).emit("connected"),M(this,he).flushOnReconnect&&this.flush(),e()},M(this,Oe).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),M(this,Ce).debug("Socket closed. Close event:",{event:n}),M(this,Ce).debug(`Connection closed code: ${o}`),M(this,Ce).debug(`Connection closed reason: ${c}`),M(this,ms)||ne(this,Zd,Lh).call(this,o,c)}catch(o){ne(this,ho,Qd).call(this,o)}},M(this,Oe).onerror=n=>{ne(this,ho,Qd).call(this,n)},M(this,Oe).onmessage=n=>ne(this,Nh,SS).call(this,n)}catch(i){ne(this,ho,Qd).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,Oe)||M(this,Oe).readyState!==1))return M(this,Ce).debug("Queuing message since socket is not connected!",n),M(this,Br).push(n),!1;const o=hS.encode(n);return ne(this,On,mo).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return ne(this,On,mo).call(this,t)}receive(t,e){return M(this,ze).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,ze).on(t,e);return}this.receive(t,e)}removeAllListeners(){M(this,ze).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){M(this,ze).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){M(this,ze).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ie(this,ir,!1),ne(this,Dn,go).call(this),ne(this,fo,sl).call(this),this.removeAllListeners(),ie(this,Fr,{code:1e3,reason:"Sockrates disconnect method called"}),M(this,Oe).close(1e3,"Sockrates disconnect method called.")}}Oe=new WeakMap,In=new WeakMap,he=new WeakMap,Ce=new WeakMap,Br=new WeakMap,ze=new WeakMap,ir=new WeakMap,Fr=new WeakMap,ms=new WeakMap,An=new WeakMap,Mn=new WeakMap,nr=new WeakMap,Dh=new WeakSet,fS=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)://.")},ho=new WeakSet,Qd=function(s,t){M(this,Ce).error("Error:",{error:s}),M(this,ze).emit("errored",{error:s}),t==null||t(s)},Nh=new WeakSet,SS=function(s){if(ne(this,tl,Uh).call(this),s.data===mS){M(this,Ce).debug("Received ping from server"),ne(this,On,mo).call(this,gS);return}if(s.data===gS){M(this,Ce).debug("Received pong from server");return}const t=hS.decode(s.data),{id:e,payload:r}=t;M(this,Ce).debug("Received message",{event:t.event,messageID:e}),M(this,ze).emit(t.event.toString(),{id:e,payload:r})},Xd=new WeakSet,Vh=function(){return M(this,Oe).readyState===1},Zd=new WeakSet,Lh=function(s,t){ie(this,Fr,{reason:t,code:s}),M(this,ze).emit("disconnected",{code:s,reason:t})},xh=new WeakSet,vS=function(){const{reason:s,code:t}=M(this,Fr);t&&t!==1e3&&M(this,ir)&&M(this,he).autoReconnect&&!M(this,ms)&&(M(this,Ce).debug(`Triggering reconnection due to ${s}.`),M(this,ze).emit("reconnecting"),ne(this,po,el).call(this))},po=new WeakSet,el=async function(s=!0){if(s&&M(this,ms)){M(this,Ce).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(M(this,ms)||M(this,nr).reset(),M(this,he).maxReconnectionAttempts!==null&&M(this,nr).getAttempts()>=M(this,he).maxReconnectionAttempts){M(this,ze).emit("failed"),ie(this,ms,!1);return}ie(this,ms,!0),ne(this,So,rl).call(this),ne(this,Dn,go).call(this);try{if(await M(this,nr).wait(),M(this,ir)===!1)return;if(M(this,Ce).debug(`Reconnection attempt ${M(this,nr).getAttempts()}`),M(this,ze).emit("reconnectAttempt",{attempt:M(this,nr).getAttempts()}),await this.connect(),!ne(this,Xd,Vh).call(this))throw Error("Reconnect Failed");ie(this,ms,!1),ie(this,Fr,{code:void 0,reason:void 0}),M(this,ze).emit("reconnected")}catch(t){M(this,Ce).debug("Failed to reconnect."),M(this,ze).emit("reconnectFailure",{attempt:M(this,nr).getAttempts()}),ne(this,po,el).call(this,!1)}},On=new WeakSet,mo=function(s){try{return M(this,Oe).send(s),!0}catch(t){return M(this,Ce).error(t.message),!1}},tl=new WeakSet,Uh=function(){this.config.disconnectOnPingTimeout&&(M(this,Ce).debug("Resetting ping timeout"),ne(this,Dn,go).call(this),ie(this,An,setTimeout(()=>{var s;M(this,Ce).debug("Disconnecting the socket due to ping timeout"),ie(this,ir,!0);const t=3002,e="Ping timeout";(s=M(this,Oe))==null||s.close(t,e),ne(this,Zd,Lh).call(this,t,e)},M(this,he).pingTimeout)))},Dn=new WeakSet,go=function(){M(this,An)&&(clearTimeout(M(this,An)),ie(this,An,void 0))},$h=new WeakSet,TS=function(){ne(this,fo,sl).call(this),M(this,he).clientInitiatedPings&&ie(this,Mn,setInterval(()=>{ne(this,Xd,Vh).call(this)&&(M(this,Ce).debug("Sending client-initiated ping"),ne(this,On,mo).call(this,mS))},M(this,he).clientInitiatedPingInterval))},fo=new WeakSet,sl=function(){M(this,Mn)&&(clearInterval(M(this,Mn)),ie(this,Mn,void 0))},So=new WeakSet,rl=function(){ne(this,fo,sl).call(this),M(this,Oe)&&(M(this,Oe).onopen=void 0,M(this,Oe).onerror=void 0,M(this,Oe).onmessage=void 0,M(this,Oe).onclose=void 0)};var P1=Object.defineProperty,_1=Object.getOwnPropertyDescriptor,il=(s,t,e,r)=>{for(var i=r>1?void 0:r?_1(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&&P1(t,e,i),i};const yS=65535,k1=3e3,ES=(qS=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,Ie);g(this,wc);g(this,Pc);g(this,oi,void 0);g(this,Re,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");g(this,as,void 0);g(this,rt,void 0);if(!t||!e||!r)throw new R("peerId, meetingId, or authToken can not be empty","0404");f(this,as,void 0),f(this,rt,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,oi,N(this,wc,cp).call(this,t));const n=i.includes("PING");f(this,Re,new w1(a(this,oi),{autoReconnect:!0,disconnectOnPingTimeout:n,queueOnDisconnect:!1,flushOnReconnect:!1,logger:this.logger,clientInitiatedPings:!n,maxReconnectionAttempts:50,clientInitiatedPingInterval:15e3})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Ie,He).socketJoinAttempted}set joinAttempted(s){a(this,Ie,He).socketJoinAttempted=s}get telemetry(){return a(this,rt).getValue("telemetry")}get logger(){return a(this,rt).getValue("logger")}get peerId(){return a(this,rt).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,oi,N(this,wc,cp).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Re).updateURL(a(this,oi))}static getSocketEdgeDomain(s){return yn({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,oi)}async connect(){a(this,Ie,He).socketJoinAttempted=!0,await a(this,Re).connect(),a(this,Ie,He).socketJoinAttempted=!0,a(this,Ie,He).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){a(this,Ie,He).socketJoinAttempted=!1,a(this,Re).disconnect(),a(this,Ie,He).socketJoinAttempted=!0,a(this,Ie,He).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Re).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,rt).getValue("telemetry").injectContext(r),a(this,Re).send(s,e!=null?e:N(this,Pc,dp).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,Re).removeListener(n,y),a(this,Re).removeListener(yS,w),a(this,Re).removeListener(Mr.errorResponse,w),a(this,Re).removeListener(hs.errorResponse,w)},l=r!=null?r:N(this,Pc,dp).call(this),u={};a(this,rt).getValue("telemetry").injectContext(u);const m=({id:y,payload:w})=>{if(l===y){let _;try{const C=VC.fromBinary(w);_=new Error(C.errorMessage)}catch(C){_=new Error("failed to parse error message",{cause:C});try{const V=LR.fromBinary(w);_=new Error(V.message)}catch(V){_=new Error("failed to parse error message",{cause:V})}}c(_),d(S,m)}},S=({id:y,payload:w})=>{l===y&&(o({id:y,payload:w}),d(S,m))};a(this,Re).on(n,S),a(this,Re).on(yS,m),a(this,Re).on(Mr.errorResponse,m),a(this,Re).on(hs.errorResponse,m),setTimeout(()=>{d(S,m),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Re).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){a(this,Re).on(s,t)}onStateEvent(s,t){a(this,Re).on(s,t)}removeListener(s,t){a(this,Re).removeListener(s,t)}removeListeners(s){a(this,Re).removeListeners(s)}flush(){return a(this,Re).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,Ie,He).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,Ie,He).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Ds.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Ds.CONNECTED?a(this,rt).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ie,He).joinAttempted}):f(this,as,setTimeout(()=>{a(this,rt).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ie,He).joinAttempted}),f(this,as,void 0)},k1)),a(this,Ie,He).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge"),a(this,Ie,He).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,Ie,He).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,Ie,He).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Ie,He).mediaJoinAttempted}}),a(this,as)&&(clearTimeout(a(this,as)),f(this,as,void 0)),a(this,rt).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Ie,He).mediaJoinAttempted}),a(this,Ie,He).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge"),a(this,rt).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_FAILED),a(this,Ie,He).updateSocketConnectionState("failed")})}},oi=new WeakMap,Re=new WeakMap,Ie=new WeakSet,He=function(){return a(this,rt).getValue("connectionHandler")},as=new WeakMap,rt=new WeakMap,wc=new WeakSet,cp=function(s){const t=a(this,rt).getValue("socketBaseURI")||a(this,rt).getValue("baseURI");let e=ES.getSocketEdgeDomain(t);typeof Tn(a(this,rt),"socket_server_base")=="string"&&(e=Tn(a(this,rt),"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=>Cd[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,dp=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},qS);let vo=ES;il([E.trace("SocketService.connect")],vo.prototype,"connect",1),il([E.trace("SocketService.disconnect")],vo.prototype,"disconnect",1),il([E.trace("SocketService.sendMessagePromise")],vo.prototype,"sendMessagePromise",1),il([E.trace("SocketService.sendMessagePromiseWithTimeout")],vo.prototype,"sendMessagePromiseWithTimeout",1);class C1{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=dI.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=VI.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=Xg.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return Qg.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return _I.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(U.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(U.createConnectedRooms,pI.toBinary({payloads:t}));return Qg.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(U.deleteConnectedRooms,wI.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(U.movePeers,MI.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 R1=Object.defineProperty,I1=Object.getOwnPropertyDescriptor,A1=(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 bS extends Dt{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);g(this,jt,void 0);f(this,jt,e)}get isActive(){return this.meetings.length!==0}validateAlterAction(){const e=a(this,jt).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,jt).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,jt).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,jt).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,jt).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,jt).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,jt).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,jt).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,jt).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})}}jt=new WeakMap,A1([Nt({maxInvocations:60,period:60})],bS.prototype,"getConnectedMeetings",1);var M1=Object.defineProperty,O1=Object.getOwnPropertyDescriptor,Bh=(s,t,e,r)=>{for(var i=r>1?void 0:r?O1(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&&M1(t,e,i),i};const wS=(jS=class{constructor(s){p(this,"connectedMeetings");g(this,ve,void 0);f(this,ve,s),this.connectedMeetings=new bS(s)}get telemetry(){return a(this,ve).getValue("telemetry")}get logger(){return a(this,ve).getValue("logger")}static init(s){const t=new wS(s);return s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings()),t.setupEvents(),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,ve).getValue("connectedMeetingsSocketHandler").socketService.on(U.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,ve).getValue("connectedMeetingsSocketHandler").socketService.on(U.transferPeer,this.handleTransferPeer.bind(this)),a(this,ve).getValue("connectedMeetingsSocketHandler").socketService.on(U.movedPeer,this.handleMovedPeer.bind(this)),a(this,ve).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,ve).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=a(this,ve).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,ve).getValue("self").videoEnabled,audio:a(this,ve).getValue("self").audioEnabled};try{a(this,ve).getValue("self").cleanupEvents(),await a(this,ve).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,ve).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 _S.init({...a(this,ve).getValue("options"),cachedUserDetails:null,defaults:{...a(this,ve).getValue("options").defaults,...e,mediaHandler:a(this,ve).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,ve).getValue("self");r.self.setName(a(this,ve).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,ve).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,ve).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,ve).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,ve).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})}},ve=new WeakMap,jS);let nl=wS;Bh([E.trace("ConnectedMeetingsController.getConnectedMeetings")],nl.prototype,"getConnectedMeetings",1),Bh([E.trace("ConnectedMeetingsController.setupEvents")],nl.prototype,"setupEvents",1),Bh([E.trace("ConnectedMeetingsController.switchMeeting")],nl.prototype,"switchMeeting",1);var D1=Object.defineProperty,N1=Object.getOwnPropertyDescriptor,Fh=(s,t,e,r)=>{for(var i=r>1?void 0:r?N1(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&&D1(t,e,i),i};const To=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 x,B,j;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(QD(s),Te.isSupported()===!1)throw new R("Browser not supported","0010",c,!0);const d=AM(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 hO(s);s.setValue("connectionHandler",l);let u="",h="",m=null;c.info("CF SFU is being used.");try{m=await d.getUserDetails(),u=((x=m.meeting)==null?void 0:x.title)||"",h=((B=m.socket)==null?void 0:B.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 Dd?F.status===401?new R("Unauthorized. The auth token may be invalid or expired. (401)","0004"):F.status===403?new R("Access denied. Insufficient permissions to join the meeting. (403)","0004"):F.status===404?(c.error("[ERROR:0004] participant-details returned 404."),new R("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 R(`The server encountered an error. Try again. (${F.status})`,"0001"):F.isHttpError?new R(`Request rejected by the server. (${F.status})`,"0001"):F.isTimeout?new R("Connection timed out. Check the network and try again.","0001"):new R("Unable to connect to the server. Check the internet connection.","0001"):new R((F==null?void 0:F.message)||"Failed to initialize.","0001")}const S=To.createSocketService(s),y=S.connect();try{await y}catch(F){c.error("[Controller]: Failed to connect to socket server:",{error:F})}const w=Th.init(m.preset,!s.getValue("modules").theme);s.setValue("theme",w);const _=Eh.init(s,w.viewType,m.preset.permissions),C=To.setupControllers(S,s,m,u,w,_);eO(w)&&((j=To.createRoomNodeClient(s,S).initializeConnection(m.participant.name,i,!1,_))==null||j.catch(Z=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:Z})}));const{controllers:V}=await C;return q_(),new To(e,V,s)}static async setupControllers(s,t,e,r,i,n){var Le,L,I;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:(Le=h.enableHighBitrate)!=null?Le:!1,enableStereo:(L=h.enableStereo)!=null?L:!1}},...d}),t.setValue("maxPreferredStreams",Te.isMobile()?i.maxVideoStreams.mobile:i.maxVideoStreams.desktop);let m,S,y,w,_,C,V,x,B;const j=new t1(t,s),F=new C1(s);t.setValue("connectedMeetingsSocketHandler",F);const Z=new Jd(t,s),be=new Zs(t,s),Ge=new o1(s),Ps=new eS(t,s),un=new c1(t,s),A=new e1(s),T=await xr.init(t,Ps,c,n,i);t.setValue("selfController",T);const P=await yf.init(t,T.self,Ps,j,r);o.participant&&(x=new rr(t,T.self,Ps)),(I=o.e2ee)!=null&&I.enabled&&o.e2ee.manager.init(l,t.getValue("peerSessionStore")),o.chat&&(S=await Za.init(t,be,T.self,x.participants)),o.internals&&(_=await mh.init(t)),o.livestream&&i.viewType===Ws.Livestream&&(V=new Hf(t,T.self,A)),o.poll&&(m=await ff.init(t,T.self,Z)),o.recording&&(C=new Cf(t,T.self,Ps)),o.stage&&(y=new Ef(t,Ge,Ps,T.self,x.participants));const $=new lD(t,un);if(o.plugin){if(!x)throw new R("The plugin module cannot be initialized without the `participant` module","0102");const Fe=d.plugins||[];w=await _f.init(t,Fe,T.self,$)}if(o.connectedMeetings&&(B=await nl.init(t)),o.pip){const Fe=await xu._init(t,T.self);t.setValue("pip",Fe)}return{theme:i,permissions:n,controllers:{storesManager:$,pollController:m,selfController:T,metaController:P,chatController:S,stageController:y,pluginController:w,recordingController:C,internalsController:_,livestreamController:V,participantController:x,connectedMeetingsController:B}}}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 vo(s,{peerId:t,meetingId:e,authToken:r,capabilities:o})}};let al=To;Fh([E.trace("Controller.init")],al,"init",1),Fh([E.trace("Controller.createRoomNodeClient")],al,"createRoomNodeClient",1),Fh([E.trace("Controller.createSocketService")],al,"createSocketService",1);class V1{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 PS=new V1;function L1(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=gi.baseURI.prod;t&&(n=t);const o=`https://${yn({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new R("Invalid auth token","0004")}}class x1{constructor(){g(this,tu);g(this,ci,new Audio);g(this,on,new MediaStream);g(this,cn,new Map);g(this,_c,void 0);a(this,ci).srcObject=a(this,on),a(this,ci).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,cn).has(e.id)||(a(this,on).addTrack(e),a(this,cn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,ci).setSinkId(t)}removeTrack(t){const e=a(this,cn).get(t);e&&(a(this,on).removeTrack(e),a(this,cn).delete(t))}async play(){return a(this,ci).srcObject=a(this,on),a(this,ci).play().catch(t=>{N(this,tu,Rv).call(this,t)})}onError(t){f(this,_c,t)}}ci=new WeakMap,on=new WeakMap,cn=new WeakMap,_c=new WeakMap,tu=new WeakSet,Rv=function(t){var e;(e=a(this,_c))==null||e.call(this,t)};class U1 extends x1{constructor(){super();g(this,dn,void 0);f(this,dn,new Map)}addParticipantTrack(e,r){a(this,dn).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,dn).get(e);r&&this.removeTrack(r),a(this,dn).delete(e)}}dn=new WeakMap;var $1=Object.defineProperty,B1=Object.getOwnPropertyDescriptor,ol=(s,t,e,r)=>{for(var i=r>1?void 0:r?B1(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};let Hr=(GS=class{constructor(t,e){g(this,qe,void 0);g(this,ln,void 0);f(this,ln,t),f(this,qe,e)}get peerId(){return a(this,ln).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:La(),n=Rr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new Gf(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var m,S,y,w,_,C,V,x,B;Te.init();const e=(S=(m=t==null?void 0:t.cachedUserDetails)==null?void 0:m.peerId)!=null?S:La(),{authToken:r,baseURI:i}=t,{meetingId:n,...o}=L1(r,i);if((y=o.baseURI)!=null&&y.includes("dyte.io"))throw new R("Dyte Base URIs are no longer supported. Use RealtimeKit Base URIs.","0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=Hr.setupContext(e,t,n,o),d=c.getValue("telemetry"),l=c.getValue("logger");Ov(l),PS.init(l),d.init(c,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(_=(w=t.modules)==null?void 0:w.tracing)!=null?_:!0,(V=(C=t==null?void 0:t.modules)==null?void 0:C.devTools)==null?void 0:V.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(x=t.authToken)==null?void 0:x.slice(0,10)}...
18
- ${(B=t.authToken)==null?void 0:B.slice(-10)}`}});const u=await al.init(c),h=new Hr(c,u);return c.setValue("meeting",h),h}static setupContext(t,e,r,i){var d,l;const n=Rr.createContext(t,e),o={...y_,...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",E_({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Is(e.cachedUserDetails)),n.setValue("sdkVersion","2.0.2-staging.8"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new U1),n}async join(){const{selfController:t}=a(this,qe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){var r;PS.cleanup(),a(this,ln).getValue("peerSessionStore").reset(),(r=a(this,qe).pluginController)==null||r.cleanup();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,ln).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,qe).internalsController)==null?void 0:t.internals}},qe=new WeakMap,ln=new WeakMap,GS);ol([dt("0002"),tr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Hr.prototype,"join",1),ol([dt("0003")],Hr.prototype,"leave",1),ol([dt("0001"),tr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Hr,"init",1),Hr=ol([dt("0000")],Hr);const _S=Hr;return _S}();
18
+ ${(B=t.authToken)==null?void 0:B.slice(-10)}`}});const u=await al.init(c),h=new Hr(c,u);return c.setValue("meeting",h),h}static setupContext(t,e,r,i){var d,l;const n=Rr.createContext(t,e),o={...y_,...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",E_({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Is(e.cachedUserDetails)),n.setValue("sdkVersion","2.0.2"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new U1),n}async join(){const{selfController:t}=a(this,qe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){var r;PS.cleanup(),a(this,ln).getValue("peerSessionStore").reset(),(r=a(this,qe).pluginController)==null||r.cleanup();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,ln).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,qe).internalsController)==null?void 0:t.internals}},qe=new WeakMap,ln=new WeakMap,GS);ol([dt("0002"),tr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Hr.prototype,"join",1),ol([dt("0003")],Hr.prototype,"leave",1),ol([dt("0001"),tr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Hr,"init",1),Hr=ol([dt("0000")],Hr);const _S=Hr;return _S}();
@@ -1,5 +1,5 @@
1
1
  Name: @cloudflare/realtimekit
2
- Version: 2.0.2-staging.7
2
+ Version: 2.0.2-staging.8
3
3
  License: Apache-2.0
4
4
  Private: false
5
5
  Description: A real-time video and audio SDK for building custom, collaborative communication experiences.