@cloudflare/realtimekit 2.0.1-staging.2 → 2.0.2-staging.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.js +1 -1
- package/dist/dependencies.txt +1 -1
- package/dist/index.cjs.js +1 -1
- package/dist/index.es.js +66 -99
- package/dist/index.es5.js +382 -306
- package/dist/index.rn.js +1 -1
- package/package.json +1 -1
package/dist/browser.js
CHANGED
|
@@ -15,4 +15,4 @@ ${this.message}`;try{let d=n&&!!i;r&&r.endsWith("00")&&i&&(d=!0),d&&i.error("Cli
|
|
|
15
15
|
`}this.midTransceiverMap.set(n.mid,n);const c=async d=>(this.logger.debug(`[SDP] send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),await this.pc.setRemoteDescription(d),n.mid);return this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(o,void 0,2)}]`),{offerSdp:o,callback:c,sender:n.sender,mid:n.mid}}addCustomEventListeners(){this.pc.addEventListener("datachannel",t=>{const{channel:e}=t;e.onmessage=r=>{this.safeEmit("datachannel",t.channel,String.fromCharCode(...new Uint8Array(r.data)))}})}}var ev={},Wd={},UD={get exports(){return Wd},set exports(s){Wd=s}},tv=UD.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(tv).forEach(function(s){var t=tv[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=Wd,n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);s.parse=function(c){var d={},l=[],u=d;return c.split(/(\r\n|\r|\n)/).filter(n).forEach(function(h){var m=h[0],v=h.slice(2);m==="m"&&(l.push({rtp:[],fmtp:[]}),u=l[l.length-1]);for(var y=0;y<(i[m]||[]).length;y+=1){var w=i[m][y];if(w.reg.test(v))return r(w,u,v)}}),d.media=l,d};var o=function(c,d){var l=d.split(/=(.+)/,2);return l.length===2?c[l[0]]=t(l[1]):l.length===1&&d.length>1&&(c[l[0]]=void 0),c};s.parseParams=function(c){return c.split(/;\s?/).reduce(o,{})},s.parseFmtpConfig=s.parseParams,s.parsePayloads=function(c){return c.toString().split(" ").map(Number)},s.parseRemoteCandidates=function(c){for(var d=[],l=c.split(" ").map(t),u=0;u<l.length;u+=3)d.push({component:l[u],ip:l[u+1],port:l[u+2]});return d},s.parseImageAttributes=function(c){return c.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(o,{})})},s.parseSimulcastStreamList=function(c){return c.split(";").map(function(d){return d.split(",").map(function(l){var u,h=!1;return l[0]!=="~"?u=t(l):(u=t(l.substring(1,l.length)),h=!0),{scid:u,paused:h}})})}}(ev);var Oh=Wd,$D=/%[sdv%]/g,BD=function(s){var t=1,e=arguments,r=e.length;return s.replace($D,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""}})},lo=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 BD.apply(null,i)},FD=["v","o","s","i","u","e","p","c","b","t","r","z","a"],HD=["i","c","b","a"],qD=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||FD,r=t.innerOrder||HD,i=[];return e.forEach(function(n){Oh[n].forEach(function(o){o.name in s&&s[o.name]!=null?i.push(lo(n,o,s)):o.push in s&&s[o.push]!=null&&s[o.push].forEach(function(c){i.push(lo(n,o,c))})})}),s.media.forEach(function(n){i.push(lo("m",Oh.m[0],n)),r.forEach(function(o){Oh[o].forEach(function(c){c.name in n&&n[c.name]!=null?i.push(lo(o,c,n)):c.push in n&&n[c.push]!=null&&n[c.push].forEach(function(d){i.push(lo(o,c,d))})})})}),i.join(`\r
|
|
16
16
|
`)+`\r
|
|
17
17
|
`},bi=ev,jD=qD,Jd=jD,wi=bi.parse;bi.parseParams,bi.parseFmtpConfig,bi.parsePayloads,bi.parseRemoteCandidates,bi.parseImageAttributes,bi.parseSimulcastStreamList;class Kd extends Ah{constructor(e,r){super(e);p(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new Kd(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 $;const v=wi(h),y=v.media[v.media.length-1],w=y.rtp.filter(x=>m.some(H=>H.name===x.codec)),R=y.fmtp.filter(x=>w.some(H=>H.payload===x.payload)),P=($=y.rtcpFb)==null?void 0:$.filter(x=>w.some(H=>H.payload===x.payload)),N=w.map(x=>x.payload);return v.media[v.media.length-1].rtp=w,v.media[v.media.length-1].fmtp=R,v.media[v.media.length-1].rtcpFb=P,v.media[v.media.length-1].payloads=N.join(" "),Jd(v)},l=await this.pc.createOffer();if(l.sdp=d(l.sdp,i),this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),await this.pc.setLocalDescription(l),e==="audio"||e.kind==="audio"){const{enableDtx:h,enableStereo:m}=this,v=this.enableHighBitrate?m?128e3:64e3:m?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${m?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${v}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:l,callback:async h=>(this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),await this.pc.setRemoteDescription(h),c.mid),sender:c.sender,mid:c.mid}}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters(),o=n.encodings.length-1-r;n.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),await i.sender.setParameters(n)}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:r}=e;r.onmessage=async i=>{const n=await i.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(n)))}})}}class Dh extends Ah{static createFactory(t){return()=>new Dh(t)}get name(){return"Safari12"}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection(),this.logger.debug("Safari12::creating new transceiver");const n=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e}),o=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`Safari12::senders available params: ${JSON.stringify(o)}`);const c=[];r&&r.length>0&&r.forEach(u=>{var m;const h=o.codecs.find(v=>v.mimeType.includes(u.name));if(u.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(u.parameters)}`);const v=((m=h.sdpFmtpLine)==null?void 0:m.split(";"))||[];v.push(...u.parameters);const y=[...new Set(v).values()];h.sdpFmtpLine=y.join(";")}c.push(h)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(c)}`),n.setCodecPreferences(c);const d=await this.pc.createOffer();if(await this.pc.setLocalDescription(d),t==="audio"||t.kind==="audio"){const{enableStereo:u,enableDtx:h}=this,m=this.enableHighBitrate?u?128e3:64e3:u?64e3:32e3;d.sdp=d.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${u?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${m}`)}return this.midTransceiverMap.set(n.mid,n),{offerSdp:d,callback:async u=>(this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),await this.pc.setRemoteDescription(u),n.mid),sender:n.sender,mid:n.mid}}addCustomEventListeners(){this.pc.ondatachannel=t=>{const{channel:e}=t;e.onmessage=async r=>{const i=String.fromCharCode(...new Uint8Array(r.data));this.safeEmit("datachannel",t.channel,i)}}}}function GD(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}class WD extends Gd{constructor(e,r){var i;super(e);g(this,Ls);g(this,Xo);g(this,kl);g(this,Cl);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,Qo,void 0);g(this,Ki,void 0);g(this,Vs,void 0);g(this,_l,void 0);this.id=r.id,this.localId=r.localId,f(this,Qo,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,f(this,Vs,!1),this.producerId=r.producerId,this.track=r.track,f(this,Ki,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,L(this,kl,dS).call(this),f(this,_l,e)}get closed(){return a(this,Vs)}get kind(){return this.track.kind}get paused(){return a(this,Ki)}close(e,r){a(this,Vs)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,Ls,di)),f(this,Vs,!0),r&&(L(this,Cl,lS).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(a(this,Vs))throw new _t("closed");return a(this,Qo).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",a(this,Ls,di)),a(this,Vs)){this.logger.error("consumer::pause() | Consumer closed",a(this,Ls,di));return}f(this,Ki,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,Ls,di)),a(this,Vs)){this.logger.error("Consumer::resume() | Consumer closed",a(this,Ls,di));return}f(this,Ki,!1),this.track.enabled=!0,this.safeEmit("resume")}}Qo=new WeakMap,Ki=new WeakMap,Vs=new WeakMap,_l=new WeakMap,Ls=new WeakSet,di=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},Xo=new WeakSet,op=function(){this.logger.debug('Consumer::track "ended" event',a(this,Ls,di)),this.safeEmit("trackended")},kl=new WeakSet,dS=function(){this.track.addEventListener("ended",L(this,Xo,op).bind(this))},Cl=new WeakSet,lS=function(){try{this.track.removeEventListener("ended",L(this,Xo,op)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...a(this,Ls,di),error:e})}};class JD extends Gd{constructor(e,r){var i,n;super(e);g(this,Bt);p(this,"id");p(this,"localId");g(this,ys,void 0);p(this,"kind");p(this,"appData");p(this,"rtpSender");g(this,va,void 0);g(this,Sa,void 0);g(this,zi,void 0);g(this,is,!1);g(this,it,void 0);g(this,ti,void 0);g(this,Ta,void 0);g(this,Rl,void 0);this.id=r.id,this.localId=r.localId,f(this,it,r.track),this.kind=(i=r.track)==null?void 0:i.kind,f(this,ti,r.disableTrackOnPause?!((n=r.track)!=null&&n.enabled):!1),f(this,Ta,void 0),f(this,va,r.stopTracks),f(this,Sa,r.disableTrackOnPause),f(this,zi,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,Rl,e)}get closed(){return a(this,is)}get track(){return a(this,it)}get paused(){return a(this,ti)}get maxSpatialLayer(){return a(this,Ta)}async close(e){if(a(this,is))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,Bt,_s)),f(this,is,!0),this._destroyTrack(),e===uo){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 _t("closed");return a(this,ys).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",a(this,Bt,_s)),a(this,is)&&this.logger.error("Producer::pause() | Producer closed",a(this,Bt,_s)),f(this,ti,!0),a(this,it)&&a(this,Sa)&&(a(this,it).enabled=!1),a(this,zi)&&a(this,ys).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,Bt,_s)),a(this,is)){this.logger.error("Producer::resume() | Producer closed",a(this,Bt,_s));return}f(this,ti,!1),a(this,it)&&a(this,Sa)&&(a(this,it).enabled=!0),a(this,zi)&&a(this,ys).replaceTrack(this.localId,a(this,it)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,a(this,Bt,_s)),a(this,is)){if(e&&a(this,va))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...a(this,Bt,_s),error:r})}throw new _t("closed")}else if(e&&e.readyState==="ended")throw new _t("track ended");if(e===a(this,it)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,a(this,Bt,_s));return}(!a(this,zi)||!a(this,ti))&&await a(this,ys).replaceTrack(this.localId,e),this._destroyTrack(),f(this,it,e),this._handleTrack()}async setMaxSpatialLayer(e){if(a(this,is))throw new _t("closed");if(this.kind!=="video")throw new co("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await a(this,ys).setMaxSpatialLayer(this.localId,e),f(this,Ta,e)}async setRtpEncodingParameters(e){if(a(this,is))throw new _t("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,Bt,_s)),this.safeEmit("trackended",this.track.id)}_handleTrack(){a(this,it)&&a(this,it).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(a(this,it))try{a(this,it).removeEventListener("ended",this._onTrackEnded),a(this,va)&&a(this,it).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...a(this,Bt,_s),error:r})}}}ys=new WeakMap,va=new WeakMap,Sa=new WeakMap,zi=new WeakMap,is=new WeakMap,it=new WeakMap,ti=new WeakMap,Ta=new WeakMap,Rl=new WeakMap,Bt=new WeakSet,_s=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function sv(s){return typeof s=="object"&&!Array.isArray(s)&&s!==null}function Nh(s){return Math.random().toString(36).substring(2,2+s)}const zd=1;function rv(s){const t=s;return delete t.payload._bolt,t}function KD(s){return s.payload&&sv(s.payload)}function zD(s){var t,e;return KD(s)&&(e=(t=s.payload._bolt)==null?void 0:t.id)!=null?e:""}const ya=class extends at.EventEmitter{constructor(e,r,i,n){super();p(this,"channel");p(this,"queue");p(this,"serverProtocolVersion");g(this,si,new Map);g(this,Il,void 0);g(this,Yi,void 0);p(this,"respond",(e,r,i=!1)=>{let n;i?n=ya.createErrorResponse(e,r):n=ya.createResponse(e,r),this.channel.send(JSON.stringify(n))});p(this,"notify",e=>{const r=ya.createNotification(e);this.channel.send(JSON.stringify(r))});p(this,"request",async e=>{const r=ya.createRequest(e),i=new Promise((n,o)=>{const{id:d}=r.payload._bolt,l={id:d,method:r.type,resolve:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),n(u))},timer:setTimeout(()=>{this.queue.delete(d)&&o(new Error(`request timeout for message id: ${d}`))},2e4),cancel:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),o(u))}};this.queue.set(d,l)});return this.channel.send(JSON.stringify(r)),i});p(this,"send",e=>{const r=JSON.stringify(e),i=16384;if(r.length>i){const n=i-200,o=Math.ceil(r.length/n),c=[];for(let l=0;l<o;l+=1){const u=l*n,h=(l+1)*n;c.push(r.slice(u,h))}const d=vn();for(let l=0;l<o;l+=1){const u=c[l],m=JSON.stringify({id:d,count:o,chunkIndex:l,chunk:u});a(this,Yi).debug(`Sending message chunk over dc: ${m}`),this.channel.send(m)}}else a(this,Yi).debug(`Sending message over dc: ${r}`),this.channel.send(r)});p(this,"processMessage",e=>{var i;a(this,si).has(e.id)||a(this,si).set(e.id,[]);const r=a(this,si).get(e.id);if(r[e.chunkIndex]=e,(r==null?void 0:r.length)===e.count&&!r.some(n=>n===void 0)){const n=a(this,si).get(e.id),o=n==null?void 0:n.reduce((d,l)=>d+l.chunk,"");a(this,si).delete(e.id);const c=JSON.parse(o);if(!c.payload||!sv(c.payload))throw new Error("corrupted incoming message over dc",{cause:{code:"CORRUPT_DC_MESSAGE",values:c}});if(this.processBoltHandshake(c))return;if(this.serverProtocolVersion=(i=c.payload._bolt)==null?void 0:i.version,!this.processResponseMsg(c))return c}});p(this,"processResponseMsg",e=>{const{id:r}=e.payload._bolt,i=this.queue.get(r);return i?(a(this,Yi).debug(`resolving pending request with id: ${r}, complete response: ${JSON.stringify(e)}`),e.type==="error"?i.cancel(rv(e)):i.resolve(rv(e)),!0):!1});p(this,"processBoltHandshake",e=>{var r,i;return e.type==="_bolt"||e.type==="handshake"?(this.respond((i=(r=e.payload._bolt)==null?void 0:r.id)!=null?i:Nh(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1});this.label=i,this.transportId=n,f(this,Il,e),f(this,Yi,e.getValue("logger")),this.channel=r,this.queue=new Map}};let Pi=ya;si=new WeakMap,Il=new WeakMap,Yi=new WeakMap,p(Pi,"createRequest",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,_bolt:{id:Nh(8),type:"REQUEST",version:zd}}}}),p(Pi,"createResponse",(e,r)=>{var i;if((i=r.payload)!=null&&i._bolt)throw new Error("rpc fields are internal values");return{type:r.type,payload:{...r.payload,_bolt:{id:e,type:"RESPONSE",version:zd}}}}),p(Pi,"createNotification",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,bolt:{id:Nh(8),type:"NOTIFY",version:zd}}}}),p(Pi,"createErrorResponse",(e,r)=>({type:"error",payload:{error:r.message,_bolt:{id:e,type:"RESPONSE",version:zd}}}));const uo="transport closed",Ea=class extends Gd{constructor(e,{id:r,direction:i,handlerFactory:n,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:h}){var w,R,P;super(e);p(this,"awaitQueue");p(this,"observer");p(this,"id");p(this,"serverId");p(this,"direction");p(this,"maxSctpMessageSize");p(this,"handler");p(this,"connectionState","new");p(this,"producers");p(this,"consumers");p(this,"datachannels");p(this,"connected",!1);p(this,"eventsDCReadyPromise");p(this,"eventsDCReadyPromiseResolver");p(this,"eventsDCFailureTimer");p(this,"transportConnectionPromise");p(this,"consumerTrackEvents");p(this,"unknownTracksMap");p(this,"appData");g(this,Qi,void 0);f(this,Qi,e);const m=e.getValue("logger");m.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const v=GD(l,{});delete v.iceServers,delete v.iceTransportPolicy,delete v.bundlePolicy,delete v.rtcpMuxPolicy,delete v.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new Ih(m,!0),this.handler=n(),this.handler.enableHighBitrate=(w=h==null?void 0:h.enableHighBitrate)!=null?w:!1,this.handler.enableStereo=(R=h==null?void 0:h.enableStereo)!=null?R:!1,this.handler.enableDtx=(P=h==null?void 0:h.enableDtx)!=null?P:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=u||{};const y=3e4;this.transportConnectionPromise=new Promise(N=>{const $=setTimeout(()=>{m.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),N(!1)},y);this.once("connected",()=>{clearTimeout($),N(!0)}),this.once("disconnect",()=>{clearTimeout($),N(!1)}),this.once("close",()=>{clearTimeout($),N(!1)})}),this.eventsDCReadyPromise=new Promise(N=>{this.eventsDCReadyPromiseResolver=N}),this.handler.on("@connectionstatechange",N=>{N!==this.connectionState&&(this.logger.debug(`connection state changed to ${N}`),this.connectionState=N,N==="connected"&&(this.connected=!0,this.emit("connected")),N==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(N==="failed"||N==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",N))}),this.handler.on("@icecandidate",({candidate:N})=>{this.closed||this.safeEmit("icecandidate",N)}),this.handler.on("dc_open",N=>{let $=this.datachannels.get(N.label);$||($||($=new Pi(a(this,Qi),N,N.label,this.serverId),this.datachannels.set(N.label,$)),this.eventsDCFailureTimer=setTimeout(()=>{N.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",N.label))},5e3))}),this.handler.on("datachannel",(N,$)=>{N.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const x=this.datachannels.get(N.label);if(!x){this.logger.error("unregistered datachannel for message",{rtcChannel:{label:N.label,message:$}});return}try{const H=JSON.parse($);this.logger.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:H.id,count:H.count,chunkIndex:H.chunkIndex,chunk:H.chunk,transprtId:this.serverId}});const F=x.processMessage(H);if(!F)return;this.logger.debug(`datachannel message with id:${H.id} on transport:${this.serverId}complete - ${JSON.stringify(F)}`),this.emit(`datachannel:${N.label}`,x.label,F)}catch(H){this.logger.error("error parsing message",{error:H})}})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId=e}getDatachannel(e){return this.datachannels.get(e)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(this.logger.debug("Transport close called"),this.connectionState="closed",this.awaitQueue.stop(),this.awaitQueue=void 0,this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(uo).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(uo)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new _t("closed");return this.handler.getTransportStats()}async connect(e){try{if(await this.awaitQueue.push(async()=>{const{offerSdp:r,callback:i}=await this.handler.connect(),{transportId:n,answer:o}=await e(r);this.setServerId(n),await i(o)}),!await this.transportConnectionPromise)throw new Error("ice connection failed")}catch(r){throw this.logger.error("transport failed to connect:",{error:r}),r}}async restartIce(){if(this.logger.debug("restartIce()"),this.closed)throw new _t("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new co("not a sending Transport");if(r.readyState==="ended")throw new _t("track ended");if(i&&typeof i!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!await this.transportConnectionPromise)throw new Vr("transport not connected");return!0}async produce(e,r){if(!await this.canProduce(e))throw new Error("Cannot produce");const{track:n,encodings:o,codecOptions:c,stopTracks:d=!0,disableTrackOnPause:l=!0,zeroRtpOnPause:u=!1,appData:h={}}=e;this.logger.debug(`produce() [track:${n.id}]`);const{producerId:m,localId:v,rtpSender:y}=await this.awaitQueue.push(async()=>{const{offerSdp:w,callback:R,sender:P,mid:N}=await this.handler.send({track:n,encodings:o,codecOptions:c,screenShare:h==null?void 0:h.screenShare}),{answer:$,producerId:x}=await r({offer:w,kind:n.kind,paused:l?!n.enabled||Object.hasOwn(n,"fakeTracks"):!1,appData:{...h||{},mid:N},codecOptions:c,producingTransportId:this.serverId}),H=await R($);return{producerId:x,localId:H,rtpSender:P}},"Transport.produce");return this.createProducerObject({id:m,localId:v,track:n,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:h,handler:this.handler,rtpSender:y})}async createProducerObject(e){const r=new JD(a(this,Qi),e);return this.producers.set(r.id,r),r.once("close",()=>{this.producers.delete(r.id)}),this.emit("newproducer",r),r}async closeProducer(e){await this.awaitQueue.push(e.close.bind(e),"Transport.closeProducer")}async canConsume(){if(this.closed)throw new _t("closed");if(this.direction!=="recv")throw new co("not a receiving transport");if(!await this.transportConnectionPromise)throw new Vr("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:Jd(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:Jd(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),n=Ea.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=Ea.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=Ea.setCodecAndFmtpMappings(c,i,n),c=Ea.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=Jd(i),this.logger.info("[SDP] Setting munged SDP",{sdp:r.sdp}),await this.setLocalDescription(r),this.logger.info("[SDP] Successfully set local description",{sdp:r.sdp}),r}catch(r){throw this.logger.error("Set remote offer failed",{error:r}),r}}_ontrack(e){const{track:r,transceiver:i}=e;this.logger.info(`track event received [trackId: ${r.id}] [mid: ${i.mid}]`);const n=`${i.mid}:${r.kind}`;r.addEventListener("ended",()=>{this.logger.info(`rtc consumer track ended [trackId: ${r.id}]`),this.unknownTracksMap.delete(n)});const o=this.consumerTrackEvents.get(n);o?(o(r,i),this.consumerTrackEvents.delete(n)):(this.logger.warn(`track event handler not found ${n}`),this.unknownTracksMap.set(n,e))}sendErrorOverDC(e,r,i){const n=this.getDatachannel(e);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});n.respond(r,i,!0)}sendResponseOverDC(e,r,i){const n=this.getDatachannel(e);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});n.respond(r,i)}async createConsumerObjectAndWaitForTrack(e){const{consumerId:r,producerId:i,producingPeerId:n,producingTransportId:o,streamId:c,paused:d,screenShare:l,appData:u,kind:h,mimeType:m}=e,v=`${c}:${h}`,y={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(w,R)=>{const P=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${v} producingPeerId: ${n}`),this.consumerTrackEvents.delete(v),y.isTimedout=!0,R(y)},5e3),N=(x,H)=>{try{if(x.readyState==="ended")clearTimeout(P),R(y);else{const F=x;F.enabled=!0,this.handler.midTransceiverMap.set(H.mid,H);const Z=new WD(a(this,Qi),{id:r,localId:H.mid,transceiver:H,track:F,paused:d,producerId:i,producingPeerId:n,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:n},rtpReceiver:H.receiver,mimeType:m});this.consumers.set(r,Z),Z.once("close",()=>{this.consumers.delete(Z.id),this.handler.midTransceiverMap.delete(H.mid)}),this.logger.info("consumer created for ",{consumer:{id:r,kind:h,appData:{screenShare:l},peerId:n,producerId:i}}),this.emit("newconsumer",Z),clearTimeout(P),w(Z)}}catch(F){this.logger.warn("error while creating consumer:",F),clearTimeout(P),R(y)}},$=this.unknownTracksMap.get(v);$?(this.logger.info(`track event already received [trackId: ${$.track.id}] [mid: ${$.transceiver.mid}]`),this.unknownTracksMap.delete(v),N($.track,$.transceiver)):(this.logger.info(`Registering onTrack handler for key ${v} [producingPeerId: ${n}]`),this.consumerTrackEvents.set(v,N))})}async setRemoteDescription(e){await this.handler.pc.setRemoteDescription(e)}async setLocalDescription(e){this.logger.debug(`[SDP] ${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),await this.handler.pc.setLocalDescription(e)}async sendDataChannelMessage(e,r){const i=this.getDatachannel(e);if(!i)throw DD("DC_NOT_READY",`${e} datachannel not ready`);const n=(await i.request(r)).payload;return this.logger.info(`sendDataChannelMessage::response ${JSON.stringify(n)}`),n}};let Vh=Ea;Qi=new WeakMap;function YD(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=Tp.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 QD{constructor(t,{handlerName:e,handlerFactory:r}={}){p(this,"handlerFactory");g(this,gr,void 0);g(this,Xi,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),f(this,gr,t),f(this,Xi,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,Xi).debug(`Device::constructor() | handler given: ${e}`);else if(e=YD(a(this,Xi)),e)a(this,Xi).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=Mh.createFactory(a(this,gr));break;case"Safari12":this.handlerFactory=Dh.createFactory(a(this,gr));break;case"Firefox60":this.handlerFactory=Kd.createFactory(a(this,gr),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=Kd.createFactory(a(this,gr),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=vn();return new Vh(a(this,gr),{id:e,...t,handlerFactory:this.handlerFactory})}}gr=new WeakMap,Xi=new WeakMap;const XD=2e3;class ZD extends at.EventEmitter{constructor(e,r){super();g(this,_a);g(this,sc);g(this,Al);g(this,rc);g(this,Ml);g(this,Ol);g(this,Dl);g(this,Nl);g(this,Vl);g(this,ic);g(this,nc);p(this,"context");g(this,ba,void 0);g(this,lt,void 0);g(this,ut,void 0);g(this,Zo,void 0);g(this,ec,void 0);g(this,Zi,void 0);g(this,wa,void 0);g(this,tc,void 0);g(this,Pa,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});g(this,en,void 0);g(this,xs,"all");this.context=e,f(this,Zi,r),f(this,ba,new QD(e)),f(this,wa,new xD(r)),f(this,tc,hs),a(this,_a,lu).mediaState={send:{state:Lr.NEW},recv:{state:Lr.NEW}},wn(this.context,"forceRelay")&&f(this,xs,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,xs)}`),L(this,sc,cp).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,Zi)}get socketHandler(){return a(this,wa)}get sendTransport(){return a(this,lt)}get recvTransport(){return a(this,ut)}get events(){return a(this,tc)}set sendTransportConnectedCallback(e){f(this,Zo,e)}set recvTransportConnectedCallback(e){f(this,ec,e)}async setupTransports(e){await L(this,Al,uS).call(this,e);let r,i;e.send&&(r=L(this,rc,dp).call(this,a(this,lt)).then(n=>{try{a(this,Zo).call(this,n)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=L(this,rc,dp).call(this,a(this,ut)).then(n=>{try{a(this,ec).call(this,n)}catch(o){this.logger.error("Failed to run recv transport callback")}})),await Promise.all([r,i])}stopTransports(e){var r,i;if(e.send&&this.sendTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,lt);this.logger.info("Closing send transport",{transport:{id:n,serverId:o,type:c}}),a(this,lt).close(),a(this,lt).removeAllListeners(),f(this,lt,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,ut);this.logger.info("Closing recv transport",{transport:{id:n,serverId:o,type:c}}),(r=a(this,ut))==null||r.close(),(i=a(this,ut))==null||i.removeAllListeners(),f(this,ut,void 0)}L(this,sc,cp).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}ba=new WeakMap,lt=new WeakMap,ut=new WeakMap,Zo=new WeakMap,ec=new WeakMap,Zi=new WeakMap,wa=new WeakMap,tc=new WeakMap,Pa=new WeakMap,en=new WeakMap,xs=new WeakMap,_a=new WeakSet,lu=function(){return this.context.getValue("connectionHandler")},sc=new WeakSet,cp=function(){f(this,en,{send:void 0,recv:void 0})},Al=new WeakSet,uS=async function(e){var o,c,d,l,u,h,m,v;wn(this.context,"forceRelay")&&f(this,xs,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,xs)}`);const n=await wt().getICEServers().catch(y=>(this.logger.warn(`failed to get iceservers from server: ${y.message}`),[]));e.send&&L(this,Ol,pS).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,xs)}),e.recv&&L(this,Dl,mS).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(v=this.context.getValue("modules").e2ee)==null?void 0:v.enabled},iceTransportPolicy:a(this,xs)})},rc=new WeakSet,dp=async function(e){const{id:r,serverId:i,direction:n}=e;L(this,Nl,gS).call(this,e);try{return await Zf(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 Vr("Cannot reconnect closed transport");await L(this,Ml,hS).call(this,e)}catch(l){if(l instanceof Vr){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}},Ml=new WeakSet,hS=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!a(this,Zi).isConnected)throw new Vr("Socket is not connected");if(e.connectionState==="closed")throw new Vr("Transport is closed");try{await e.connect(n=>L(this,Vl,fS).call(this,i,n)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(n){throw a(this,Pa).transportFailureCount[i]+=1,n.message==="ice connection failed"?new Vr(n.message):n}},Ol=new WeakSet,pS=function(e){var r,i;if(a(this,lt)&&a(this,lt).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=a(this,lt))==null?void 0:r.id,serverId:(i=a(this,lt))==null?void 0:i.serverId,type:"send"}});return}f(this,lt,a(this,ba).createTransport({...e,direction:"send"})),this.context.getValue("callstats").configureSendTransport(a(this,lt))},Dl=new WeakSet,mS=function(e){var r,i;if(a(this,ut)&&a(this,ut).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=a(this,ut))==null?void 0:r.id,serverId:(i=a(this,ut))==null?void 0:i.serverId,type:"recv"}});return}f(this,ut,a(this,ba).createTransport({...e,direction:"recv"})),this.context.getValue("callstats").configureRecvTransport(a(this,ut))},Nl=new WeakSet,gS=function(e){const{direction:r,id:i}=e;e.on("connectionstatechange",async n=>{L(this,nc,up).call(this,{state:n,direction:r}),this.logger.info(`Transport connection state changed for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:n}});const o=()=>{const c=a(this,en)[r];c!==void 0&&(clearTimeout(c),a(this,en)[r]=void 0)};switch(n){case"connected":o(),a(this,Pa).lastConnectionTime=performance.now();break;case"disconnected":a(this,en)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await L(this,ic,lp).call(this,e.direction)},XD);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 L(this,ic,lp).call(this,e.direction);break}}),e.on("icecandidate",async n=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:n})}),e.on("datachannel:events",async(n,o)=>{var c,d;this.logger.debug("Got data channel message on event:",{rtcChannel:{label:n,message:o}});try{switch(o.type){case"handshake":{const l={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,zD(o),l);break}case"hub-disconnect":{this.logger.debug(`media hub disconnected, full_reconnect: ${(c=o.payload)==null?void 0:c.full_reconnect}`),((d=o.payload)==null?void 0:d.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":break;default:break}}catch(l){this.logger.error(`Unable to handle the incoming datachannel message on channel ${n}`)}}),e.on("dc_error",()=>{e.direction==="recv"&&(this.logger.warn("Events datachannel did not open in 5s"),this.handleErrors("reconnectRecvTransport"))})},Vl=new WeakSet,fS=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?Js.SUBSCRIBER:Js.PUBLISHER},producers:[]};return a(this,wa).connectTransport(c)}catch(n){throw this.logger.error(`Error in ${e} transport connection:`,{error:n}),n}},ic=new WeakSet,lp=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),a(this,Zi).isConnected&&a(this,Pa).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),f(this,xs,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:a(this,lt)}),this.context.getValue("peerSessionStore").emit(k.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,ut)}),this.context.getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}L(this,nc,up).call(this,{state:Lr.CONNECTED,direction:e})},nc=new WeakSet,up=function(e){const{state:r,direction:i}=e;a(this,_a,lu).mediaState[i]={state:r},this.context.getValue("peerSessionStore").emit(k.TRANSPORT_STATE_UPDATE,{transport:i,...a(this,_a,lu).mediaState[i]})};class e1{constructor(t,e,r,i,n){g(this,Ll,void 0);g(this,ns,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=n,f(this,Ll,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:Js.SUBSCRIBER}};return a(this,ns).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,Bk.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:Js.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=pR.fromBinary(c).description;return{sdp:d.sdp,type:d.type}};return await this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(t,e),"ConsumerStrategy.close",{consumersLength:t.length}),{}}async switchConsumersToLayer(t,e){const r={requests:[],consumingTransportId:this.recvTransport.serverId},i=t.filter(n=>n&&n.id);i.forEach(({id:n,producingTransportId:o,localId:c})=>{r.requests.push({producerId:n,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),await this.socketHandler.updateConsumersSimulcastConfig(r),a(this,ns).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:n})=>n)})}}Ll=new WeakMap,ns=new WeakMap;class Lh{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=Lh.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:Js.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(h=i.screenShare)!=null?h:!1,mimeType:`${e}/${(m=n[0])==null?void 0:m.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}class t1 extends ZD{constructor(e,r){super(e,r);g(this,oc);g(this,Ul);g(this,$l);g(this,Bl);g(this,Fl);g(this,ri,void 0);g(this,ii,void 0);g(this,ka,void 0);g(this,ac,void 0);g(this,Us,void 0);g(this,xl,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});g(this,fr,[]);g(this,Ca,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{f(this,ac,new Lh(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{a(this,ka).clear(),f(this,Us,new e1(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,ka)}get logger(){return this.context.getValue("logger")}reset(){f(this,ri,new Map),f(this,ii,new Map),f(this,ka,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,L(this,Ul,vS).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_PRODUCER,o),L(this,$l,SS).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,xl).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(uo)}))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){a(this,Ca)||clearTimeout(a(this,Ca)),f(this,fr,a(this,fr).concat(e)),await L(this,oc,hp).call(this)}closeConsumer(e){return this.closeConsumers([e])}async closeConsumers(e){if(!a(this,Us))return;const r=e.map(n=>this.consumers.get(n)).filter(n=>n!==void 0);if(r.length===0)return;const{failedConsumers:i}=await a(this,Us).close(r);i!=null&&i.length&&this.logger.warn("Failed to close some consumers",{consumerIds:i})}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,ii).keys()))}async switchConsumersToLayer(e,r){a(this,Us).switchConsumersToLayer(e,r)}}ri=new WeakMap,ii=new WeakMap,ka=new WeakMap,ac=new WeakMap,Us=new WeakMap,xl=new WeakMap,fr=new WeakMap,Ca=new WeakMap,oc=new WeakSet,hp=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=a(this,fr).splice(0,a(this,fr).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,L(this,Bl,TS).bind(this),a(this,Us).negotiate.bind(a(this,Us)));if(o.forEach(L(this,Fl,yS).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,fr,a(this,fr).concat(d)),f(this,Ca,setTimeout(L(this,oc,hp).bind(this),e))}}catch(i){if(this.logger.error("failed to consume on transport",{error:i}),i.errorCode==="internal_error"&&i.errorDescription==="Backend error"||i.errorCode==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:i.errorCode,message:i.errorDescription}});try{this.stopTransports({recv:!0})}catch(n){}await this.setupTransports({recv:!0})}}},Ul=new WeakSet,vS=function(e){return a(this,ac).create(e)},$l=new WeakSet,SS=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!==uo){const d={producerId:e.id,description:{sdp:o.sdp,type:o.type,target:Js.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)},Bl=new WeakSet,TS=async function(e){try{return await this.recvTransport.canConsume(),await a(this,Us).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},Fl=new WeakSet,yS=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 Wl=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,Hl);g(this,ql);g(this,cc,void 0);g(this,dc,void 0);g(this,lc,void 0);g(this,Ra,void 0);g(this,Ia,void 0);g(this,Aa,void 0);g(this,uc,void 0);g(this,hc,void 0);g(this,Ma,void 0);g(this,Ct,void 0);g(this,Es,void 0);g(this,bs,!1);g(this,tn,0);g(this,sn,0);g(this,vr,[]);g(this,pc,void 0);f(this,Ra,t),f(this,Ct,t),f(this,cc,e),f(this,dc,r),f(this,lc,i),f(this,Ia,n),f(this,Aa,o),f(this,uc,c),f(this,hc,d),f(this,Ma,l),f(this,pc,u),f(this,Es,t/2)}get voiceDetected(){return a(this,bs)}processAudioChunk(t){var o,c;const e=L(o=Wl,jl,wS).call(o,t),r=L(c=Wl,Gl,PS).call(c,t);return L(this,Hl,ES).call(this,e),e/a(this,Es)>a(this,Ma)&&e>a(this,Ct)&&r>a(this,cc)?(f(this,tn,a(this,tn)+1),f(this,sn,a(this,lc)),a(this,tn)>=a(this,dc)&&f(this,bs,!0)):(f(this,tn,0),a(this,sn)>0?f(this,sn,a(this,sn)-1):a(this,bs)&&f(this,bs,!1),a(this,bs)||L(this,ql,bS).call(this,e)),{energy:e,isVoice:a(this,bs)}}reset(){f(this,bs,!1),f(this,tn,0),f(this,sn,0),f(this,Ct,a(this,Ra)),f(this,Es,a(this,Ra)/2),f(this,vr,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,Ct),backgroundNoiseEnergy:a(this,Es),energyRatioThreshold:a(this,Ma)}}};let ho=Wl;cc=new WeakMap,dc=new WeakMap,lc=new WeakMap,Ra=new WeakMap,Ia=new WeakMap,Aa=new WeakMap,uc=new WeakMap,hc=new WeakMap,Ma=new WeakMap,Ct=new WeakMap,Es=new WeakMap,bs=new WeakMap,tn=new WeakMap,sn=new WeakMap,vr=new WeakMap,pc=new WeakMap,Hl=new WeakSet,ES=function(t){a(this,bs)?f(this,Ct,a(this,Aa)*a(this,Ct)+(1-a(this,Aa))*t):f(this,Ct,a(this,Ia)*a(this,Ct)+(1-a(this,Ia))*a(this,Es)),f(this,Ct,Math.max(a(this,uc),Math.min(a(this,hc),a(this,Ct))))},ql=new WeakSet,bS=function(t){if(t<a(this,Ct)*1.2)if(a(this,vr).push(t),a(this,vr).length>a(this,pc)&&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)},jl=new WeakSet,wS=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Gl=new WeakSet,PS=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(ho,jl),g(ho,Gl);class iv{constructor(t){p(this,"RNAudioSampleHandler");g(this,mc,void 0);f(this,mc,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,mc).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()}}mc=new WeakMap;class nv{constructor(t){p(this,"audioContext");p(this,"analyser");g(this,gc,void 0);f(this,gc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return a(this,gc).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)}}gc=new WeakMap;class s1{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 r1=60,i1=400,Sc=class{constructor(t,e){g(this,Jl);g(this,Kl);g(this,Sr,void 0);g(this,Tr,void 0);g(this,yr,void 0);g(this,fc,void 0);g(this,Oa,void 0);g(this,Da,void 0);g(this,ni,void 0);g(this,rn,void 0);g(this,Na,void 0);g(this,nn,void 0);g(this,Er,void 0);g(this,$s,void 0);this.reportRequest=e,f(this,nn,t),f(this,Da,new ho);const{isReactNative:r}=navigator;f(this,Er,r?new iv(a(this,nn)):new nv(a(this,nn))),f(this,$s,r?s1:Bf)}get logger(){return a(this,nn).getValue("logger")}set producerId(t){f(this,yr,t)}set audioTrack(t){f(this,fc,t),a(this,Er)instanceof nv&&(a(this,Er).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${a(this,yr)}`),a(this,Sr)&&a(this,$s).clearInterval(a(this,Sr)),f(this,Sr,a(this,$s).setInterval(async()=>{var i;if(!a(this,fc)||!a(this,yr))return;const{energy:t}=L(this,Jl,_S).call(this),e=L(i=Sc,vc,pp).call(i,t);let r=.9;a(this,Na)!==e&&a(this,Na)?r=.9:e?r=.3:r=.5,f(this,Oa,(a(this,Oa)||0)*(1-r)+t*r)},r1)),a(this,Tr)&&a(this,$s).clearInterval(a(this,Tr)),f(this,Tr,a(this,$s).setInterval(L(this,Kl,kS).bind(this),i1))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${a(this,yr)}`),a(this,Sr)&&(a(this,$s).clearInterval(a(this,Sr)),f(this,Sr,void 0)),a(this,Tr)&&(a(this,$s).clearInterval(a(this,Tr)),f(this,Tr,void 0))}catch(t){}a(this,Da).reset(),a(this,Er)instanceof iv&&a(this,Er).stop()}};let po=Sc;Sr=new WeakMap,Tr=new WeakMap,yr=new WeakMap,fc=new WeakMap,Oa=new WeakMap,Da=new WeakMap,ni=new WeakMap,rn=new WeakMap,Na=new WeakMap,nn=new WeakMap,Er=new WeakMap,$s=new WeakMap,Jl=new WeakSet,_S=function(){var o;const{samples:t}=a(this,Er),{energy:e,isVoice:r}=a(this,Da).processAudioChunk(t),i=L(o=Sc,zl,CS).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,rn)||i>a(this,rn))&&f(this,rn,i),{energy:(i-a(this,ni))/(a(this,rn)-a(this,ni))*10||0,isVoice:r})},vc=new WeakSet,pp=function(t){return t<5},Kl=new WeakSet,kS=function(t=a(this,Oa)){var r;if(!a(this,yr)||!t)return;const e={producerId:a(this,yr),energy:Math.round(t),silent:L(r=Sc,vc,pp).call(r,t)};f(this,Na,e.silent),this.reportRequest(e)},zl=new WeakSet,CS=function(t){const e=Math.log10(t);return Math.round(e)},g(po,vc),g(po,zl);var n1=Object.defineProperty,a1=Object.getOwnPropertyDescriptor,de=(s,t,e,r)=>{for(var i=r>1?void 0:r?a1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&n1(t,e,i),i};class ae{constructor(t,e){g(this,br);g(this,Ql);g(this,Xl);g(this,Zl);g(this,bc);g(this,eu);g(this,tu);g(this,bt);g(this,dn);g(this,su);g(this,ru);g(this,iu);p(this,"context");p(this,"authToken");p(this,"e2ee");g(this,Tc,void 0);g(this,yc,void 0);g(this,ht,void 0);g(this,q,void 0);g(this,Yl,void 0);g(this,Et,void 0);g(this,an,void 0);g(this,on,void 0);g(this,cn,void 0);g(this,Ec,void 0);g(this,Ft,null);g(this,Bs,void 0);g(this,pt,void 0);g(this,Rt,void 0);var i,n;this.context=t;const{socket:r}=e;this.mediaJoined=!1,f(this,ht,r),f(this,an,!1),f(this,q,new t1(t,r)),f(this,Et,a(this,q).events),f(this,Bs,new Set),f(this,pt,new Map),f(this,on,!1),f(this,cn,new Ih(t.getValue("logger"))),f(this,Rt,new po(this.context,a(this,q).socketHandler.audioActivity.bind(a(this,q).socketHandler))),this.e2ee=(n=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,Ec,Lu(async()=>{if(!a(this,br,fn).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(a(this,yc),a(this,Tc),!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,br,fn).mediaJoined}set mediaJoined(t){a(this,br,fn).mediaJoined=t}reset({resetTransportQueue:t}){this.logger.info(`Resetting media node client: closing all transports, producers, consumers, and queues(resetTransportQueue: ${t}).`),a(this,q).closeAllProducers(),a(this,q).closeAllConsumers(),a(this,pt).clear(),a(this,Bs).clear(),f(this,Ft,null),t&&a(this,cn).stop(),a(this,q).stopAllTransports(),a(this,q).reset(),t&&f(this,cn,new Ih)}async joinRoom(t,e,r=!1,i={}){a(this,br,fn).mediaJoinAttempted=!0,f(this,an,!0);try{return await a(this,cn).push(()=>L(this,Ql,RS).call(this,t,e,r,i),"joinRoom")}catch(n){return this.logger.error("Error in room joining process",{error:n}),this.context.getValue("peerSessionStore").emit(k.ROOM_NODE_FAILED),{roomJoined:!1,error:n}}}async initializeConnection(t,e,r=!1,i={}){return a(this,Ft)?a(this,Ft):(f(this,Ft,(async()=>{try{await L(this,bc,mp).call(this,t,e,r,i)}catch(n){throw f(this,Ft,null),n}})()),a(this,Ft))}getConsumers(){return a(this,q).consumers}getProducers(){return a(this,q).producers}async leaveRoom(){a(this,q).stopAllTransports(),f(this,on,!1),a(this,br,fn).mediaJoinAttempted=!1;const t={closeRoom:!1};a(this,ht).sendMessagePromise(a(this,Et).leaveRoom,uC.toBinary(t)).then(r=>{var i;(i=ZC.fromBinary(r.payload))!=null&&i.closed&&this.logger.warn("Weird state on peer closed and should not happen")}).catch(r=>{this.logger.error("error on sending leave room request",{error:r})}),this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct().catch(r=>{this.logger.error("leaveRoom::telemetry_destruct_failed",{error:r})})}async activatePeers(t){return this.createConsumers(t)}async createConsumers(t){return t.length===0?Promise.resolve():a(this,q).createConsumers(t)}async closeConsumers(t){if(!t.length)return;const e=t.reduce((r,i)=>{const n=a(this,q).producerIdToConsumerIdMap.get(i.producerId);return n?(r.push(n),r):(this.logger.warn(`consumer not found in close consumers: ${i.producerId}`),r)},[]);await a(this,q).closeConsumers(e)}async _shareWebcam(t){var u,h,m,v;const e=Ie.WEBCAM,r=L(this,bt,Wt).call(this,e);if(r){const y=await r;if(a(this,q).producers.has(y)){const w=a(this,q).producers.get(y);if(!w.closed)return await w.replaceTrack({track:t}),await this.resumeWebcam(e),t;await this.disableWebcam()}return this._shareWebcam(t)}const i=L(this,iu,VS).call(this,t),n=wn(this.context,"disableSimulcast"),o=(h=(u=this.context)==null?void 0:u.getValue("overrides"))==null?void 0:h.simulcastConfig;n||o&&o.disable||!((v=(m=this.context)==null?void 0:m.getValue("theme"))!=null&&v.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),i.encodings=BO(this.context,t),this.logger.info(`Simulcast encodings: ${JSON.stringify(i.encodings)}`));const d=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,pt).delete(e)},l=a(this,q).createProducer(i,d);return L(this,dn,zc).call(this,e,l.then(y=>y.id)),l.then(y=>y.track)}async shareWebcam(t){return t===void 0?null:(this.logger.debug("Calling _shareWebcam with VP8 codec"),this._shareWebcam(t))}async shareScreen(t){const{video:e,audio:r}=t;if(e===void 0)return;const i={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1},n=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,pt).delete(Ie.SCREENSHARE_VIDEO),a(this,pt).delete(Ie.SCREENSHARE_AUDIO)},o=a(this,q).createProducer(i,n);L(this,dn,zc).call(this,Ie.SCREENSHARE_VIDEO,o.then(d=>d.id));let c;if(r){const d={track:r,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},l=()=>{};c=a(this,q).createProducer(d,l),L(this,dn,zc).call(this,Ie.SCREENSHARE_AUDIO,c.then(u=>u.id))}await Promise.all([o,c||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()}async shareMic(t){try{if(t===void 0)throw new _t("track undefined");const e=L(this,bt,Wt).call(this,Ie.MIC);if(e){const o=await e;if(a(this,q).producers.has(o)){const c=a(this,q).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),a(this,Rt)&&(a(this,Rt).audioTrack=t,a(this,Rt).producerId=o,a(this,Rt).start());return}await a(this,q).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=L(this,ru,NS).call(this,t),i=()=>{a(this,pt).delete(Ie.MIC)},n=a(this,q).createProducer(r,i);L(this,dn,zc).call(this,Ie.MIC,n.then(o=>o.id)),await n.then(o=>{a(this,Rt)&&(a(this,Rt).audioTrack=o.track,a(this,Rt).producerId=o.id,a(this,Rt).start())})}catch(e){throw new C(e)}}async pauseMic(){var i;const t=await L(this,bt,Wt).call(this,Ie.MIC),e=a(this,q).producers.get(t);if(!e){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(e.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}e.pause(),(i=a(this,Rt))==null||i.stop();const r={producerId:e.id,pause:!0};a(this,ht).sendMessage(a(this,Et).toggleProducer,Id.toBinary(r))}async pauseWebcam(){const t=await L(this,bt,Wt).call(this,Ie.WEBCAM),e=a(this,q).producers.get(t);if(!e){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}e.pause();const r={producerId:e.id,pause:!0};a(this,ht).sendMessage(a(this,Et).toggleProducer,Id.toBinary(r))}async resumeMic(){const t=await L(this,bt,Wt).call(this,Ie.MIC),e=a(this,q).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,ht).sendMessage(a(this,Et).toggleProducer,Id.toBinary(r))}async resumeWebcam(t=Ie.WEBCAM){const e=await L(this,bt,Wt).call(this,t),r=a(this,q).producers.get(e);if(!r){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!r.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}r.resume(),r.appData.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};a(this,ht).sendMessage(a(this,Et).toggleProducer,Id.toBinary(i))}async disableWebcam(){const t=Ie.WEBCAM,e=await L(this,bt,Wt).call(this,t);L(this,su,DS).call(this,t),e&&await a(this,q).closeProducer(e)}async disableMic(){var e;const t=await L(this,bt,Wt).call(this,Ie.MIC);t&&await a(this,q).closeProducer(t),(e=a(this,Rt))==null||e.stop(),a(this,pt).delete(Ie.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await L(this,bt,Wt).call(this,Ie.SCREENSHARE_VIDEO),e=await L(this,bt,Wt).call(this,Ie.SCREENSHARE_AUDIO);t&&await a(this,q).closeProducer(t),e&&await a(this,q).closeProducer(e),a(this,Bs).clear(),a(this,pt).delete(Ie.SCREENSHARE_VIDEO),a(this,pt).delete(Ie.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await L(this,bt,Wt).call(this,Ie.WEBCAM);await a(this,q).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await L(this,bt,Wt).call(this,Ie.SCREENSHARE_VIDEO);await a(this,q).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:e})}}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await a(this,q).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};a(this,q).socketHandler.kickPeer(e)}kickAll(){a(this,q).socketHandler.kickAll()}async muteAll(t){if(!await a(this,q).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,q).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await a(this,q).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await a(this,q).socketHandler.hostControlForPeer(t,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(t){const e={participantId:t!=null?t:""};try{await a(this,ht).sendMessagePromise(a(this,Et).globalPinPeer,_C.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&a(this,q).producers.get(t.producerId)&&a(this,Bs).add(t.consumerPeerId),a(this,Bs).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));a(this,q).switchConsumersToLayer(r,e)}async handleSocketEvents(){a(this,ht).on(a(this,Et).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:r}=IR.fromBinary(t);if(e===this.peerId)return;r!=null&&r.mimeType||(r.mimeType=r.kind===Ks.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===Ks.AUDIO?"audio":"video",producingPeerId:e}})}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),a(this,ht).on(a(this,Et).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:i,pause:n,producerId:o,screenShare:c}}=Yg.fromBinary(t);if(c)return;const d=i===Ks.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${o}, kind:${d}, paused:${n} payload: ${JSON.stringify(Yg.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&n&&this.context.getValue("peerSessionStore").emit(d==="audio"?k.MUTE_SELF:k.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(k.PRODUCER_TOGGLE,{peerId:e,producerId:o,paused:n,kind:d}),Array.from(this.getConsumers().values()).filter(u=>u.producerId===o).forEach(u=>{u.kind==="video"&&n||u.paused!==n&&(this.logger.debug(`consumer state mismatched for ${u.id}. updating consumer pause state ${u.paused} to ${n}`),n?(u.pause(),this.context.getValue("peerSessionStore").emit(k.CONSUMER_PAUSED,{id:u.id})):(u.resume(),this.context.getValue("peerSessionStore").emit(k.CONSUMER_RESUMED,{id:u.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,ht).on(a(this,Et).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=Yu.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,Bs).delete(e),a(this,q).consumers.forEach(r=>{r.peerId===e&&r.close()}),this.context.getValue("peerSessionStore").emit(k.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),a(this,ht).on(a(this,Et).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=OR.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(k.PRODUCER_CLOSED,{peerId:e,producerId:r});const i=a(this,q).producerIdToConsumerIdMap.get(r);if(!i){this.logger.warn(`no consumer found for producer:${r}`);return}this.logger.info(`closing consumer ${i}, producer id: ${r}`),a(this,q).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),a(this,q).producerIdToConsumerIdMap.delete(r),this.context.getValue("peerSessionStore").emit(k.CONSUMER_CLOSED,{id:i})}).catch(n=>{this.logger.error("error closing consumer",{error:n})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,ht).on(a(this,Et).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,an)&&!a(this,on)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(k.ROOM_NODE_DISCONNECTED),a(this,Ec).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=a(this,q).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(k.CONSUMER_SCORE_UPDATE,{id:r,kind:i.kind,peerId:i.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,r)=>{const i=Array.from(a(this,q).producers.values()).find(n=>n.id===r);i&&this.context.getValue("peerSessionStore").emit(k.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}}Tc=new WeakMap,yc=new WeakMap,ht=new WeakMap,q=new WeakMap,Yl=new WeakMap,Et=new WeakMap,an=new WeakMap,on=new WeakMap,cn=new WeakMap,Ec=new WeakMap,Ft=new WeakMap,Bs=new WeakMap,pt=new WeakMap,Rt=new WeakMap,br=new WeakSet,fn=function(){return this.context.getValue("connectionHandler")},Ql=new WeakSet,RS=async function(t,e,r,i){var o;f(this,yc,t);let n=!1;if(r){const{recv:c,send:d}=(o=a(this,br,fn).mediaState)!=null?o:{};(d==null?void 0:d.state)===Lr.CONNECTED&&(c==null?void 0:c.state)===Lr.CONNECTED?(this.logger.info("MediaNodeClient.joinRoom: transports healthy — partial reset (producers only)"),await a(this,q).closeAllProducersLocally(),a(this,pt).clear(),a(this,Bs).clear(),f(this,Ft,null),n=!0):(this.logger.info("MediaNodeClient.joinRoom: transports unhealthy — full reset"),this.reset({resetTransportQueue:!1}))}try{a(this,Ft)?await a(this,Ft):await L(this,bc,mp).call(this,t,e,r,i,n),L(this,Zl,AS).call(this,e);const{joined:c,error:d}=await L(this,Xl,IS).call(this);return{roomJoined:c,error:d}}catch(c){return this.logger.error("Failed to complete room join",{error:c}),{roomJoined:!1,error:c}}finally{f(this,Ft,null)}},Xl=new WeakSet,IS=async function(){try{this.mediaJoined=!0;const{roomState:t}=await a(this,q).socketHandler.notifySelfJoinComplete();return f(this,Tc,t.roomUuid),f(this,on,!0),f(this,an,!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,AS=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)},bc=new WeakSet,mp=async function(t,e,r,i,n=!1){try{const o=L(this,eu,MS).call(this);await L(this,tu,OS).call(this,t,e,r,o),n?this.logger.info("MediaNodeClient: reusing existing transports on rejoin"):await a(this,q).setupTransports({send:!0,recv:!0})}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},eu=new WeakSet,MS=function(){const t=LD("video/VP8");return f(this,Yl,t),t},tu=new WeakSet,OS=async function(t,e,r,i){await Zf(async(n,o)=>{if(!a(this,ht).isConnected){o(new Error("Socket is not connected"));return}n>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${n}`});try{await a(this,q).socketHandler.joinRoom(e,t,i,r)}catch(c){throw this.logger.error("Failed to send joinRoom message after retries",{error:c}),c}},{delayTime:1e3,strategy:"exponential",maxRetryCount:15})},bt=new WeakSet,Wt=function(t){return a(this,pt).get(t)},dn=new WeakSet,zc=function(t,e){return a(this,pt).set(t,e)},su=new WeakSet,DS=function(t){return a(this,pt).delete(t)},ru=new WeakSet,NS=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},iu=new WeakSet,VS=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 av(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 o1(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 c1=Object.defineProperty,d1=Object.getOwnPropertyDescriptor,_i=(s,t,e,r)=>{for(var i=r>1?void 0:r?d1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&c1(t,e,i),i};const ov=(Yv=class{constructor(s,t,e,r){g(this,It);p(this,"self");p(this,"authToken");g(this,Va,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,Va,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=wt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await Je.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");return navigator.product!=="ReactNative"?setTimeout(async()=>{const h=await d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(h)}),s.getValue("callstats").devices("AUDIO",h==null?void 0:h.filter(m=>m.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",h==null?void 0:h.filter(m=>m.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",h==null?void 0:h.filter(m=>m.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:Te.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:l,apiHostnames:A_(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 ov(s,d,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:n,screenShareTracks:o}=this.self;if(e.canProduceAudio===G.Allowed&&r)if((s==null?void 0:s.readyState)==="live")try{await a(this,It,os).shareMic(s),this.self.audioEnabled||a(this,It,os).pauseMic()}catch(d){this.self.disableAudio()}else this.logger.warn("shareMediaTracks: audio track is dead, disabling audio"),this.self.disableAudio();if(e.canProduceVideo===G.Allowed&&i)if((t==null?void 0:t.readyState)==="live")try{await a(this,It,os).shareWebcam(t),this.self.videoEnabled||a(this,It,os).pauseWebcam()}catch(d){this.self.disableVideo()}else this.logger.warn("shareMediaTracks: video track is dead, disabling video"),this.self.disableVideo();if(e.canProduceScreenshare===G.Allowed&&n){const d=o.video,l=o.audio;if((d==null?void 0:d.readyState)==="live")try{await((c=a(this,It,os))==null?void 0:c.shareScreen({video:d,audio:(l==null?void 0:l.readyState)==="live"?l:void 0}))}catch(u){this.self.disableScreenShare()}else this.logger.warn("shareMediaTracks: screenshare video track is dead, disabling screenshare"),this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){a(this,ee).getValue("callstats").callEnded(),s?(this.logger.info("Resetting Self post reconnect. Peer has earlier tried joining the meeting. State cleanup will be done during room rejoin."),await this.joinRoom(s)):(this.logger.info("Resetting Self post reconnect. User never joined the room so doing full reset."),a(this,It,os).reset({resetTransportQueue:!0}))}setupEvents(){a(this,ee).getValue("peerSessionStore").on(k.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,ee).getValue("peerSessionStore").on(k.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,ee).getValue("peerSessionStore").on(k.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,ee).getValue("peerSessionStore").on(k.ROOM_NODE_FAILED,()=>{this.logger.error("Room node failed. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,ee).getValue("peerSessionStore").on(k.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,ee).getValue("peerSessionStore").on(k.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;const{peerId:t}=this;a(this,Va).updateURL(t),a(this,ee).getValue("telemetry").resetPeerId(t),wt().setHeader("tracing-id",t),Cr.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(Vd.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=gh(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 C("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 Vr&&t.message==="ice connection failed"?new C("A firewall or network restriction may be blocking the connection.","0014"):new C("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===Gs.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}av(a(this,ee),{socket:a(this,Va),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:h}=(o=await((n=a(this,It,os))==null?void 0:n.joinRoom(this.self.name,r,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)throw h!=null?h:new Error("Could not connect to media server");this.logger.info(i==="ON_STAGE"?"Peer is on stage. Sharing media tracks":"Peer is not on stage. Not sharing media tracks"),i==="ON_STAGE"&&await this.shareMediaTracks(),this.logger.info(i==="ON_STAGE"?"Peer is on stage. Shared media tracks":"Peer is not on stage. Did not share media tracks"),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("SelfController.mediaRoomJoin",{error:c}),c}}async leaveMediaRoom(s){const t=a(this,ee).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===Gs.Webinar)&&a(this,It,os)&&(a(this,It,os).mediaJoined&&s!=="disconnected"&&await a(this,It,os).leaveRoom(),!(s==="stageLeft"&&t===Gs.Livestream)&&(a(this,It,os).mediaJoined=!1))}async cleanupSelf(){await this.self.disableAudio(),await this.self.disableVideo(),await this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()}},Va=new WeakMap,ws=new WeakMap,ee=new WeakMap,It=new WeakSet,os=function(){return a(this,ee).getValue("roomNodeClient")},Yv);let xr=ov;_i([E.trace("SelfController.resetSelf")],xr.prototype,"resetSelf",1),_i([E.trace("SelfController.setupEvents")],xr.prototype,"setupEvents",1),_i([E.trace("SelfController.joinRoom")],xr.prototype,"joinRoom",1),_i([E.trace("SelfController.leaveRoom")],xr.prototype,"leaveRoom",1),_i([E.trace("SelfController.joinMediaRoom")],xr.prototype,"joinMediaRoom",1),_i([E.trace("SelfController.leaveMediaRoom")],xr.prototype,"leaveMediaRoom",1),_i([E.trace("SelfController.init")],xr,"init",1);class l1{constructor(t){g(this,wc,void 0);f(this,wc,t)}on(t,e){let r;t===U.roomPeerCount?r=Zg.fromBinary.bind(Zg):r=mf.fromBinary.bind(mf),a(this,wc).on(t,({payload:i})=>{if(t===U.roomPeerCount&&!i)return;const n=r(i);e(n)})}}wc=new WeakMap;class u1{constructor(t,e){g(this,Pc,void 0);g(this,_c,void 0);f(this,Pc,e),f(this,_c,t)}get logger(){return a(this,_c).getValue("logger")}on(t,e){let r,i;switch(t){case U.transcript:{r=Qu.fromBinary.bind(Qu),i=Qu.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Pc).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)})}}Pc=new WeakMap,_c=new WeakMap;var h1=Object.defineProperty,p1=Object.getOwnPropertyDescriptor,xh=(s,t,e,r)=>{for(var i=r>1?void 0:r?p1(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&&h1(t,e,i),i};class Yd{constructor(t,e){g(this,wr,void 0);g(this,La,void 0);f(this,wr,e),f(this,La,t)}get logger(){return a(this,La).getValue("logger")}get telemetry(){return a(this,La).getValue("telemetry")}getPolls(){return a(this,wr).sendMessagePromise(Qs.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,wr).sendMessage(Qs.createPoll,oM.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,wr).sendMessage(Qs.votePoll,dM.toBinary(r))}on(t,e){let r,i;switch(t){case Qs.updatePoll:case Qs.createPoll:case Qs.votePoll:{r=dh.fromBinary.bind(dh),i=dh.create();break}}a(this,wr).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,wr).removeListeners(t)}}wr=new WeakMap,La=new WeakMap,xh([E.trace("PollSocketHandler.getPolls")],Yd.prototype,"getPolls",1),xh([E.trace("PollSocketHandler.createPoll")],Yd.prototype,"createPoll",1),xh([E.trace("PollSocketHandler.votePoll")],Yd.prototype,"votePoll",1);var m1=Object.defineProperty,g1=Object.getOwnPropertyDescriptor,f1=(s,t,e,r)=>{for(var i=r>1?void 0:r?g1(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};class cv{constructor(t,e){p(this,"socket");g(this,Ht,void 0);f(this,Ht,t),this.socket=e,this.handleSocketEvents(),a(this,Ht).setValue("roomSocketHandler",this)}get telemetry(){return a(this,Ht).getValue("telemetry")}get logger(){return a(this,Ht).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}async joinRoom(t){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(U.joinRoom,oI.toBinary(e));try{const{peer:n}=kn.fromBinary((await r).payload);a(this,Ht).getValue("connectionHandler").socketJoined=!0,a(this,Ht).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_ROOM_JOINED,{peer:n});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return a(this,Ht).getValue("peerSessionStore").emit(k.ROOM_STATE,d),a(this,Ht).getValue("peerSessionStore").emit(k.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),n}}async getAllAddedParticipants(){try{return GI.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=eh.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=eh.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=eh.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,sf.toBinary({peerId:t}));e=kn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=tf.create();try{const e=await this.socket.sendMessagePromise(U.getRoomInfo);t=tf.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=df.create();try{const e=await this.socket.sendMessagePromise(U.getRoomStageState);t=df.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,Za.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,Za.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,Za.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(U.leaveRoom,dI.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(U.kick,of.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(U.kickAll,Gg.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,ZI.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Vd.updateUserPreset,R0.toBinary(r))}handleSocketEvents(){this.socket.on(U.broadcastMessage,({payload:t})=>{try{const e=Za.fromBinary(t);a(this,Ht).getValue("peerSessionStore").emit(k.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on(U.broadcastToEntity,({payload:t})=>{try{const e=Za.fromBinary(t);a(this,Ht).getValue("peerSessionStore").emit(k.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case U.joinRoom:case U.leaveRoom:case U.kick:case U.kickAll:{r=kn.fromBinary.bind(kn),i=kn.create();break}case U.getWaitingRoomRequests:{r=(n,o)=>n?cf.fromBinary(n,o):{requests:[]},i=cf.create();break}case U.recordingPaused:case U.recordingStarted:case U.recordingStopped:{r=Sf.fromBinary.bind(Sf);break}case Vd.updateUserPreset:{r=uf.fromBinary.bind(uf);break}case hs.peerJoinedBroadcast:case Ar.peerJoinedBroadcast:{r=Kg.fromBinary.bind(Kg);break}case hs.selfJoinComplete:case Ar.selfJoinComplete:{r=zu.fromBinary.bind(zu);break}case hs.globalPeerPinBroadcast:case Ar.globalPeerPinBroadcast:{r=Qg.fromBinary.bind(Qg);break}case hs.selectedPeer:case Ar.selectedPeer:{r=Ku.fromBinary.bind(Ku);break}case hs.selectedPeerDiff:case Ar.selectedPeerDiff:{r=Jg.fromBinary.bind(Jg);break}case hs.leaveRoom:case Ar.leaveRoom:{r=Yu.fromBinary.bind(Yu);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(Vd.getUserPresets,E0.toBinary(e)),i=_0.fromBinary(r.payload).peerPresets[0],n=new TextDecoder().decode(i.preset),o=JSON.parse(n).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}}}Ht=new WeakMap,f1([E.trace("RoomSocketHandler.joinRoom")],cv.prototype,"joinRoom",1);class v1{constructor(t){g(this,At,void 0);f(this,At,t)}async getStageRequests(){const{payload:t}=await a(this,At).sendMessagePromise(U.getStageRequests);return t?ch.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,At).sendMessage(U.requestStageAccess)}cancelRequestAccess(){a(this,At).sendMessage(U.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,At).sendMessage(U.grantStageAccess,QA.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,At).sendMessage(U.denyStageAccess,ZA.toBinary(e))}joinStage(){return a(this,At).sendMessagePromise(U.joinStage,void 0,void 0,U.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,At).sendMessagePromise(U.leaveStage,ff.toBinary(e),void 0,U.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,At).sendMessagePromise(U.leaveStage,ff.toBinary(e))}on(t,e){let r;switch(t){case U.grantStageAccess:case U.denyStageAccess:{r=void 0;break}case U.getStagePeers:{r=gf.fromBinary.bind(gf);break}case U.getStageRequests:case U.requestStageAccess:case U.cancelStageRequest:{r=ch.fromBinary.bind(ch);break}case U.peerStageStatusUpdate:{r=Xg.fromBinary.bind(Xg);break}}a(this,At).on(t,({payload:i,id:n})=>{if(!i||!r)return e(void 0,n);const o=r(i);return e(o,n)})}async getPeerInfo(t){const e=await a(this,At).sendMessagePromise(U.getPeerInfo,sf.toBinary({peerId:t}));return kn.fromBinary(e.payload)}}At=new WeakMap;class S1{constructor(t,e){g(this,ai,void 0);g(this,xa,void 0);f(this,ai,e),f(this,xa,t)}get logger(){return a(this,xa).getValue("logger")}get peerId(){return a(this,xa).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(Ys.storeInsertKeys,MA.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(Ys.storeGetKeys,DA.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(Ys.storeDeleteKeys,VA.toBinary(n),i)}on(t,e){const r=pf.fromBinary.bind(pf);a(this,ai).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}ai=new WeakMap,xa=new WeakMap;var T1=Object.defineProperty,y1=(s,t,e)=>t in s?T1(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,E1=(s,t,e)=>(y1(s,typeof t!="symbol"?t+"":t,e),e),Uh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},M=(s,t,e)=>(Uh(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)=>(Uh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),ne=(s,t,e)=>(Uh(s,t,"access private method"),e),Qd={},b1={get exports(){return Qd},set exports(s){Qd=s}},On=typeof Reflect=="object"?Reflect:null,dv=On&&typeof On.apply=="function"?On.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},Xd;On&&typeof On.ownKeys=="function"?Xd=On.ownKeys:Object.getOwnPropertySymbols?Xd=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:Xd=function(s){return Object.getOwnPropertyNames(s)};function w1(s){console&&console.warn&&console.warn(s)}var lv=Number.isNaN||function(s){return s!==s};function ue(){ue.init.call(this)}b1.exports=ue,Qd.once=C1,ue.EventEmitter=ue,ue.prototype._events=void 0,ue.prototype._eventsCount=0,ue.prototype._maxListeners=void 0;var uv=10;function Zd(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ue,"defaultMaxListeners",{enumerable:!0,get:function(){return uv},set:function(s){if(typeof s!="number"||s<0||lv(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");uv=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||lv(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 hv(s){return s._maxListeners===void 0?ue.defaultMaxListeners:s._maxListeners}ue.prototype.getMaxListeners=function(){return hv(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")dv(c,this,t);else for(var d=c.length,l=vv(c,d),e=0;e<d;++e)dv(l[e],this,t);return!0};function pv(s,t,e,r){var i,n,o;if(Zd(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=hv(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,w1(c)}return s}ue.prototype.addListener=function(s,t){return pv(this,s,t,!1)},ue.prototype.on=ue.prototype.addListener,ue.prototype.prependListener=function(s,t){return pv(this,s,t,!0)};function P1(){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 mv(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=P1.bind(r);return i.listener=e,r.wrapFn=i,i}ue.prototype.once=function(s,t){return Zd(t),this.on(s,mv(this,s,t)),this},ue.prototype.prependOnceListener=function(s,t){return Zd(t),this.prependListener(s,mv(this,s,t)),this},ue.prototype.removeListener=function(s,t){var e,r,i,n,o;if(Zd(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,n=e.length-1;n>=0;n--)if(e[n]===t||e[n].listener===t){o=e[n].listener,i=n;break}if(i<0)return this;i===0?e.shift():_1(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 gv(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?k1(i):vv(i,i.length)}ue.prototype.listeners=function(s){return gv(this,s,!0)},ue.prototype.rawListeners=function(s){return gv(this,s,!1)},ue.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):fv.call(s,t)},ue.prototype.listenerCount=fv;function fv(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?Xd(this._events):[]};function vv(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function _1(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function k1(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function C1(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))}Sv(s,t,n,{once:!0}),t!=="error"&&R1(s,i,{once:!0})})}function R1(s,t,e){typeof s.on=="function"&&Sv(s,"error",t,e)}function Sv(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 I1 extends S{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const Tv=new I1;class yv{static encode(t){return Tv.toBinary(t)}static decode(t){return Tv.fromBinary(new Uint8Array(t))}}function A1(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Ur;class M1{constructor(t={}){E1(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=A1(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 ki,Ci;class O1{constructor(t){le(this,ki,void 0),le(this,Ci,void 0),ie(this,ki,console),ie(this,Ci,t)}debug(...t){$r[M(this,Ci)]>$r.debug||M(this,ki).debug("[Sockrates]:",...t)}info(...t){$r[M(this,Ci)]>$r.info||M(this,ki).info("[Sockrates]:",...t)}warn(...t){$r[M(this,Ci)]>$r.warn||M(this,ki).warn("[Sockrates]:",...t)}error(...t){$r[M(this,Ci)]>$r.error||M(this,ki).error("[Sockrates]:",...t)}}ki=new WeakMap,Ci=new WeakMap;var Ev=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(Ev||{});const bv="2",wv="3";var Me,Dn,he,ke,Br,Ke,rr,Fr,ms,Nn,Vn,ir,$h,Pv,mo,el,Bh,_v,tl,Fh,sl,Hh,qh,kv,go,rl,Ln,fo,il,jh,xn,vo,Gh,Cv,So,nl,To,al;class D1{constructor(t,e){var y,w,R,P,N,$,x,H,F,Z,je,jt;le(this,$h),le(this,mo),le(this,Bh),le(this,tl),le(this,sl),le(this,qh),le(this,go),le(this,Ln),le(this,il),le(this,xn),le(this,Gh),le(this,So),le(this,To),le(this,Me,void 0),le(this,Dn,void 0),le(this,he,void 0),le(this,ke,void 0),le(this,Br,void 0),le(this,Ke,void 0),le(this,rr,void 0),le(this,Fr,void 0),le(this,ms,void 0),le(this,Nn,void 0),le(this,Vn,void 0),le(this,ir,void 0);var r,i,n,o,c,d,l,u,h,m,v;ie(this,Dn,t),ie(this,Br,[]),ie(this,Ke,new Qd),ie(this,rr,!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),(R=(n=M(this,he)).pingTimeout)!=null||(n.pingTimeout=3e4),(P=(o=M(this,he)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(N=(c=M(this,he)).debug)!=null||(c.debug=!0),($=(d=M(this,he)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(x=(l=M(this,he)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(H=(u=M(this,he)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(F=(h=M(this,he)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),(Z=(m=M(this,he)).clientInitiatedPings)!=null||(m.clientInitiatedPings=!1),(je=(v=M(this,he)).clientInitiatedPingInterval)!=null||(v.clientInitiatedPingInterval=3e4),ie(this,Fr,{code:void 0,reason:void 0}),ie(this,ke,(jt=M(this,he).logger)!=null?jt:new O1(M(this,he).debug?"debug":"info")),ie(this,ir,new M1)}get readyState(){var t;return(t=M(this,Me))==null?void 0:t.readyState}get url(){return M(this,Dn)}updateURL(t){ie(this,Dn,t),ne(this,qh,kv).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,ke).debug("Websocket was already connecting or connected.");return}if(M(this,rr)!==!1)return new Promise((e,r)=>{ne(this,xn,vo).call(this),ne(this,To,al).call(this);try{ie(this,Me,new WebSocket(ne(this,$h,Pv).call(this,M(this,Dn)))),M(this,Me).binaryType="arraybuffer",M(this,ke).debug("Connecting");const i=setTimeout(()=>{M(this,ke).debug("Connection timeout. Closing socket"),ie(this,rr,!0),ne(this,To,al).call(this),M(this,Me).close(3001,"Connection Timeout"),M(this,he).autoReconnect&&!M(this,ms)&&(M(this,Ke).emit("reconnecting"),ne(this,go,rl).call(this)),r(new Error("Connection timed out!"))},M(this,he).connectionTimeout);M(this,Me).onopen=()=>{M(this,ke).debug(`Ready State: ${Ev[M(this,Me).readyState]}`),i&&clearTimeout(i),ne(this,il,jh).call(this),ne(this,Gh,Cv).call(this),ie(this,Fr,{code:void 0,reason:void 0}),M(this,Ke).emit("connected"),M(this,he).flushOnReconnect&&this.flush(),e()},M(this,Me).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),M(this,ke).debug("Socket closed. Close event:",{event:n}),M(this,ke).debug(`Connection closed code: ${o}`),M(this,ke).debug(`Connection closed reason: ${c}`),M(this,ms)||ne(this,sl,Hh).call(this,o,c)}catch(o){ne(this,mo,el).call(this,o)}},M(this,Me).onerror=n=>{ne(this,mo,el).call(this,n)},M(this,Me).onmessage=n=>ne(this,Bh,_v).call(this,n)}catch(i){ne(this,mo,el).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(M(this,he).queueOnDisconnect&&(!M(this,Me)||M(this,Me).readyState!==1))return M(this,ke).debug("Queuing message since socket is not connected!",n),M(this,Br).push(n),!1;const o=yv.encode(n);return ne(this,Ln,fo).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return ne(this,Ln,fo).call(this,t)}receive(t,e){return M(this,Ke).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){M(this,Ke).on(t,e);return}this.receive(t,e)}removeAllListeners(){M(this,Ke).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){M(this,Ke).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){M(this,Ke).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ie(this,rr,!1),ne(this,xn,vo).call(this),ne(this,So,nl).call(this),this.removeAllListeners(),ie(this,Fr,{code:1e3,reason:"Sockrates disconnect method called"}),M(this,Me).close(1e3,"Sockrates disconnect method called.")}}Me=new WeakMap,Dn=new WeakMap,he=new WeakMap,ke=new WeakMap,Br=new WeakMap,Ke=new WeakMap,rr=new WeakMap,Fr=new WeakMap,ms=new WeakMap,Nn=new WeakMap,Vn=new WeakMap,ir=new WeakMap,$h=new WeakSet,Pv=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)://.")},mo=new WeakSet,el=function(s,t){M(this,ke).error("Error:",{error:s}),M(this,Ke).emit("errored",{error:s}),t==null||t(s)},Bh=new WeakSet,_v=function(s){if(ne(this,il,jh).call(this),s.data===bv){M(this,ke).debug("Received ping from server"),ne(this,Ln,fo).call(this,wv);return}if(s.data===wv){M(this,ke).debug("Received pong from server");return}const t=yv.decode(s.data),{id:e,payload:r}=t;M(this,ke).debug("Received message",{event:t.event,messageID:e}),M(this,Ke).emit(t.event.toString(),{id:e,payload:r})},tl=new WeakSet,Fh=function(){return M(this,Me).readyState===1},sl=new WeakSet,Hh=function(s,t){ie(this,Fr,{reason:t,code:s}),M(this,Ke).emit("disconnected",{code:s,reason:t})},qh=new WeakSet,kv=function(){const{reason:s,code:t}=M(this,Fr);t&&t!==1e3&&M(this,rr)&&M(this,he).autoReconnect&&!M(this,ms)&&(M(this,ke).debug(`Triggering reconnection due to ${s}.`),M(this,Ke).emit("reconnecting"),ne(this,go,rl).call(this))},go=new WeakSet,rl=async function(s=!0){if(s&&M(this,ms)){M(this,ke).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(M(this,ms)||M(this,ir).reset(),M(this,he).maxReconnectionAttempts!==null&&M(this,ir).getAttempts()>=M(this,he).maxReconnectionAttempts){M(this,Ke).emit("failed"),ie(this,ms,!1);return}ie(this,ms,!0),ne(this,To,al).call(this),ne(this,xn,vo).call(this);try{if(await M(this,ir).wait(),M(this,rr)===!1)return;if(M(this,ke).debug(`Reconnection attempt ${M(this,ir).getAttempts()}`),M(this,Ke).emit("reconnectAttempt",{attempt:M(this,ir).getAttempts()}),await this.connect(),!ne(this,tl,Fh).call(this))throw Error("Reconnect Failed");ie(this,ms,!1),ie(this,Fr,{code:void 0,reason:void 0}),M(this,Ke).emit("reconnected")}catch(t){M(this,ke).debug("Failed to reconnect."),M(this,Ke).emit("reconnectFailure",{attempt:M(this,ir).getAttempts()}),ne(this,go,rl).call(this,!1)}},Ln=new WeakSet,fo=function(s){try{return M(this,Me).send(s),!0}catch(t){return M(this,ke).error(t.message),!1}},il=new WeakSet,jh=function(){this.config.disconnectOnPingTimeout&&(M(this,ke).debug("Resetting ping timeout"),ne(this,xn,vo).call(this),ie(this,Nn,setTimeout(()=>{var s;M(this,ke).debug("Disconnecting the socket due to ping timeout"),ie(this,rr,!0);const t=3002,e="Ping timeout";(s=M(this,Me))==null||s.close(t,e),ne(this,sl,Hh).call(this,t,e)},M(this,he).pingTimeout)))},xn=new WeakSet,vo=function(){M(this,Nn)&&(clearTimeout(M(this,Nn)),ie(this,Nn,void 0))},Gh=new WeakSet,Cv=function(){ne(this,So,nl).call(this),M(this,he).clientInitiatedPings&&ie(this,Vn,setInterval(()=>{ne(this,tl,Fh).call(this)&&(M(this,ke).debug("Sending client-initiated ping"),ne(this,Ln,fo).call(this,bv))},M(this,he).clientInitiatedPingInterval))},So=new WeakSet,nl=function(){M(this,Vn)&&(clearInterval(M(this,Vn)),ie(this,Vn,void 0))},To=new WeakSet,al=function(){ne(this,So,nl).call(this),M(this,Me)&&(M(this,Me).onopen=void 0,M(this,Me).onerror=void 0,M(this,Me).onmessage=void 0,M(this,Me).onclose=void 0)};var N1=Object.defineProperty,V1=Object.getOwnPropertyDescriptor,ol=(s,t,e,r)=>{for(var i=r>1?void 0:r?V1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&N1(t,e,i),i};const Rv=65535,L1=3e3,Iv=(Qv=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,Re);g(this,kc);g(this,Cc);g(this,oi,void 0);g(this,Ce,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");g(this,as,void 0);g(this,et,void 0);if(!t||!e||!r)throw new C("peerId, meetingId, or authToken can not be empty","0404");f(this,as,void 0),f(this,et,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,oi,L(this,kc,gp).call(this,t));const n=i.includes("PING");f(this,Ce,new D1(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,Re,Fe).socketJoinAttempted}set joinAttempted(s){a(this,Re,Fe).socketJoinAttempted=s}get telemetry(){return a(this,et).getValue("telemetry")}get logger(){return a(this,et).getValue("logger")}get peerId(){return a(this,et).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,oi,L(this,kc,gp).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Ce).updateURL(a(this,oi))}static getSocketEdgeDomain(s){return Pn({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,oi)}async connect(){a(this,Re,Fe).socketJoinAttempted=!0,await a(this,Ce).connect(),a(this,Re,Fe).socketJoinAttempted=!0,a(this,Re,Fe).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){a(this,Re,Fe).socketJoinAttempted=!1,a(this,Ce).disconnect(),a(this,Re,Fe).socketJoinAttempted=!0,a(this,Re,Fe).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Ce).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,et).getValue("telemetry").injectContext(r),a(this,Ce).send(s,e!=null?e:L(this,Cc,fp).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:i,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:i}){const n=i!=null?i:s;return new Promise((o,c)=>{const d=(y,w)=>{a(this,Ce).removeListener(n,y),a(this,Ce).removeListener(Rv,w),a(this,Ce).removeListener(Ar.errorResponse,w),a(this,Ce).removeListener(hs.errorResponse,w)},l=r!=null?r:L(this,Cc,fp).call(this),u={};a(this,et).getValue("telemetry").injectContext(u);const m=({id:y,payload:w})=>{if(l===y){let R;try{const P=qC.fromBinary(w);R=new Error(P.errorMessage)}catch(P){R=new Error("failed to parse error message",{cause:P});try{const N=jR.fromBinary(w);R=new Error(N.message)}catch(N){R=new Error("failed to parse error message",{cause:N})}}c(R),d(v,m)}},v=({id:y,payload:w})=>{l===y&&(o({id:y,payload:w}),d(v,m))};a(this,Ce).on(n,v),a(this,Ce).on(Rv,m),a(this,Ce).on(Ar.errorResponse,m),a(this,Ce).on(hs.errorResponse,m),setTimeout(()=>{d(v,m),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Ce).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){a(this,Ce).on(s,t)}onStateEvent(s,t){a(this,Ce).on(s,t)}removeListener(s,t){a(this,Ce).removeListener(s,t)}removeListeners(s){a(this,Ce).removeListeners(s)}flush(){return a(this,Ce).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),a(this,as)&&(clearTimeout(a(this,as)),f(this,as,void 0)),a(this,Re,Fe).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}});const{recv:e,send:r}=(i=a(this,Re,Fe).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Lr.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Lr.CONNECTED?a(this,et).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Re,Fe).joinAttempted}):f(this,as,setTimeout(()=>{a(this,et).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Re,Fe).joinAttempted}),f(this,as,void 0)},L1)),a(this,Re,Fe).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge"),a(this,Re,Fe).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,Re,Fe).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,Re,Fe).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Re,Fe).mediaJoinAttempted}}),a(this,as)&&(clearTimeout(a(this,as)),f(this,as,void 0)),a(this,et).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Re,Fe).mediaJoinAttempted}),a(this,Re,Fe).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge"),a(this,et).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_FAILED),a(this,Re,Fe).updateSocketConnectionState("failed")})}},oi=new WeakMap,Ce=new WeakMap,Re=new WeakSet,Fe=function(){return a(this,et).getValue("connectionHandler")},as=new WeakMap,et=new WeakMap,kc=new WeakSet,gp=function(s){const t=a(this,et).getValue("socketBaseURI")||a(this,et).getValue("baseURI");let e=Iv.getSocketEdgeDomain(t);typeof wn(a(this,et),"socket_server_base")=="string"&&(e=wn(a(this,et),"socket_server_base"));const r=`wss://${e}`,i=new URL(`${r}/ws`),n=this.peerId,o={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...n!==s&&{oldPeerID:n},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(c=>Ad[c]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(o).forEach(([c,d])=>{i.searchParams.append(c,d.toString())}),i.href},Cc=new WeakSet,fp=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Qv);let yo=Iv;ol([E.trace("SocketService.connect")],yo.prototype,"connect",1),ol([E.trace("SocketService.disconnect")],yo.prototype,"disconnect",1),ol([E.trace("SocketService.sendMessagePromise")],yo.prototype,"sendMessagePromise",1),ol([E.trace("SocketService.sendMessagePromiseWithTimeout")],yo.prototype,"sendMessagePromiseWithTimeout",1);class x1{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=vI.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=qI.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=af.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return nf.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return DI.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,EI.toBinary({payloads:t}));return nf.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,MI.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(U.movePeers,$I.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 U1=Object.defineProperty,$1=Object.getOwnPropertyDescriptor,B1=(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&&U1(t,e,i),i};class Av extends Ot{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);g(this,qt,void 0);f(this,qt,e)}get isActive(){return this.meetings.length!==0}validateAlterAction(){const e=a(this,qt).getValue("self").permissions.connectedMeetings;if(!(e!=null&&e.canAlterConnectedMeetings))throw new Error("You are not allowed to perform this action. Please enable canAlterConnectedMeetings permission in your preset.")}validateMoveAction(e,r){var d;if(!(r!=null&&r.length))throw new Error("You're trying to move participants with an empty list.");const i=a(this,qt).getValue("self").permissions.connectedMeetings;if(!i)throw new Error("You are not allowed to perform this action. Please enable connected meetings permissions in your preset.");if(i.canAlterConnectedMeetings)return;const n=a(this,qt).getValue("userId");if(!(r.length===1&&r[0]===n))throw new Error("You are not allowed to move other participants. Please enable canAlterConnectedMeetings permission in your preset.");if(e===((d=this.parentMeeting)==null?void 0:d.id)){if(!i.canSwitchToParentMeeting)throw new Error("You are not allowed to move to the parent meeting. Please enable canSwitchToParentMeeting permission in your preset.");return}if(!i.canSwitchConnectedMeetings)throw new Error("You are not allowed to move to a connected meeting. Please enable canSwitchConnectedMeetings permission in your preset.")}async getConnectedMeetings(){this.logger.info("Getting connected meetings dump");const e=await a(this,qt).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateAlterAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await a(this,qt).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateAlterAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await a(this,qt).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)}async deleteMeetings(e){this.validateAlterAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),await Promise.all(r);const i=await a(this,qt).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateMoveAction(r,i),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,qt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return n.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),n}async moveParticipantsWithCustomPreset(e,r,i){this.validateMoveAction(r,i.map(o=>o.id)),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,qt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return n.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),n}moveSuccessHandler(e,r,i){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>n.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>n.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>n.get(d)));return{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}qt=new WeakMap,B1([Dt({maxInvocations:60,period:60})],Av.prototype,"getConnectedMeetings",1);var F1=Object.defineProperty,H1=Object.getOwnPropertyDescriptor,Wh=(s,t,e,r)=>{for(var i=r>1?void 0:r?H1(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&&F1(t,e,i),i};const Mv=(Xv=class{constructor(s){p(this,"connectedMeetings");g(this,Se,void 0);f(this,Se,s),this.connectedMeetings=new Av(s)}get telemetry(){return a(this,Se).getValue("telemetry")}get logger(){return a(this,Se).getValue("logger")}static init(s){const t=new Mv(s);return s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings()),t.setupEvents(),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.transferPeer,this.handleTransferPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.movedPeer,this.handleMovedPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,Se).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,Se).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,n,o,c;this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:a(this,Se).getValue("self").videoEnabled,audio:a(this,Se).getValue("self").audioEnabled};try{a(this,Se).getValue("self").cleanupEvents(),await a(this,Se).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,Se).getValue("meeting"))==null?void 0:i.meta)==null?void 0:n.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await Dv.init({...a(this,Se).getValue("options"),cachedUserDetails:null,defaults:{...a(this,Se).getValue("options").defaults,...e,mediaHandler:a(this,Se).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=a(this,Se).getValue("self");r.self.setName(a(this,Se).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return a(this,Se).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s),e=new Map;this.connectedMeetings.meetings.forEach(r=>{e.set(r.id,r)}),t.forEach(r=>{e.has(r.id)?e.get(r.id).title=r.title:e.set(r.id,{...r,participants:[]})}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Se=new WeakMap,Xv);let cl=Mv;Wh([E.trace("ConnectedMeetingsController.getConnectedMeetings")],cl.prototype,"getConnectedMeetings",1),Wh([E.trace("ConnectedMeetingsController.setupEvents")],cl.prototype,"setupEvents",1),Wh([E.trace("ConnectedMeetingsController.switchMeeting")],cl.prototype,"switchMeeting",1);var q1=Object.defineProperty,j1=Object.getOwnPropertyDescriptor,Jh=(s,t,e,r)=>{for(var i=r>1?void 0:r?j1(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&&q1(t,e,i),i};const Eo=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,H;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(o1(s),Te.isSupported()===!1)throw new C("Browser not supported","0010",c,!0);const d=UM(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 yO(s);s.setValue("connectionHandler",l);let u="",h="",m=null;c.info("CF SFU is being used.");try{m=await d.getUserDetails(),u=(($=m.meeting)==null?void 0:$.title)||"",h=((x=m.socket)==null?void 0:x.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 uh?F.status===401?new C("Unauthorized. The auth token may be invalid or expired. (401)","0004"):F.status===403?new C("Access denied. Insufficient permissions to join the meeting. (403)","0004"):F.status===404?new C("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 C(`The server encountered an error. Try again. (${F.status})`,"0001"):F.isHttpError?new C(`Request rejected by the server. (${F.status})`,"0001"):F.isTimeout?new C("Connection timed out. Check the network and try again.","0001"):new C("Unable to connect to the server. Check the internet connection.","0001"):new C((F==null?void 0:F.message)||"Failed to initialize.","0001")}const v=Eo.createSocketService(s),y=v.connect();try{await y}catch(F){c.error("[Controller]: Failed to connect to socket server:",{error:F})}const w=Ph.init(m.preset,!s.getValue("modules").theme);s.setValue("theme",w);const R=kh.init(s,w.viewType,m.preset.permissions),P=Eo.setupControllers(v,s,m,u,w,R);cO(w)&&((H=Eo.createRoomNodeClient(s,v).initializeConnection(m.participant.name,i,!1,R))==null||H.catch(Z=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:Z})}));const{controllers:N}=await P;return Q_(),new Eo(e,N,s)}static async setupControllers(s,t,e,r,i,n){var Ve,V,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:(Ve=h.enableHighBitrate)!=null?Ve:!1,enableStereo:(V=h.enableStereo)!=null?V:!1}},...d}),t.setValue("maxPreferredStreams",Te.isMobile()?i.maxVideoStreams.mobile:i.maxVideoStreams.desktop);let m,v,y,w,R,P,N,$,x;const H=new u1(t,s),F=new x1(s);t.setValue("connectedMeetingsSocketHandler",F);const Z=new Yd(t,s),je=new Xs(t,s),jt=new v1(s),Ps=new cv(t,s),mn=new S1(t,s),A=new l1(s),T=await xr.init(t,Ps,c,n,i);t.setValue("selfController",T);const _=await Cf.init(t,T.self,Ps,H,r);o.participant&&($=new sr(t,T.self,Ps)),(I=o.e2ee)!=null&&I.enabled&&o.e2ee.manager.init(l,t.getValue("peerSessionStore")),o.chat&&(v=await to.init(t,je,T.self,$.participants)),o.internals&&(R=await Th.init(t)),o.livestream&&i.viewType===Gs.Livestream&&(N=new Kf(t,T.self,A)),o.poll&&(m=await wf.init(t,T.self,Z)),o.recording&&(P=new Df(t,T.self,Ps)),o.stage&&(y=new Rf(t,jt,Ps,T.self,$.participants));const B=new SD(t,mn);if(o.plugin){if(!$)throw new C("The plugin module cannot be initialized without the `participant` module","0102");const Be=d.plugins||[];w=await Of.init(t,Be,T.self,B)}if(o.connectedMeetings&&(x=await cl.init(t)),o.pip){const Be=await Fu._init(t,T.self);t.setValue("pip",Be)}return{theme:i,permissions:n,controllers:{storesManager:B,pollController:m,selfController:T,metaController:_,chatController:v,stageController:y,pluginController:w,recordingController:P,internalsController:R,livestreamController:N,participantController:$,connectedMeetingsController:x}}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return av(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 yo(s,{peerId:t,meetingId:e,authToken:r,capabilities:o})}};let dl=Eo;Jh([E.trace("Controller.init")],dl,"init",1),Jh([E.trace("Controller.createRoomNodeClient")],dl,"createRoomNodeClient",1),Jh([E.trace("Controller.createSocketService")],dl,"createSocketService",1);class G1{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 Ov=new G1;function W1(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://${Pn({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new C("Invalid auth token","0004")}}class J1{constructor(){g(this,nu);g(this,ci,new Audio);g(this,ln,new MediaStream);g(this,un,new Map);g(this,Rc,void 0);a(this,ci).srcObject=a(this,ln),a(this,ci).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,un).has(e.id)||(a(this,ln).addTrack(e),a(this,un).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,ci).setSinkId(t)}removeTrack(t){const e=a(this,un).get(t);e&&(a(this,ln).removeTrack(e),a(this,un).delete(t))}async play(){return a(this,ci).srcObject=a(this,ln),a(this,ci).play().catch(t=>{L(this,nu,LS).call(this,t)})}onError(t){f(this,Rc,t)}}ci=new WeakMap,ln=new WeakMap,un=new WeakMap,Rc=new WeakMap,nu=new WeakSet,LS=function(t){var e;(e=a(this,Rc))==null||e.call(this,t)};class K1 extends J1{constructor(){super();g(this,hn,void 0);f(this,hn,new Map)}addParticipantTrack(e,r){a(this,hn).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,hn).get(e);r&&this.removeTrack(r),a(this,hn).delete(e)}}hn=new WeakMap;var z1=Object.defineProperty,Y1=Object.getOwnPropertyDescriptor,ll=(s,t,e,r)=>{for(var i=r>1?void 0:r?Y1(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&&z1(t,e,i),i};let Hr=(Zv=class{constructor(t,e){g(this,He,void 0);g(this,pn,void 0);f(this,pn,t),f(this,He,e)}get peerId(){return a(this,pn).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:vn(),n=Cr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new Qf(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var m,v,y,w,R,P,N,$,x;Te.init();const e=(v=(m=t==null?void 0:t.cachedUserDetails)==null?void 0:m.peerId)!=null?v:vn(),{authToken:r,baseURI:i}=t,{meetingId:n,...o}=W1(r,i);if((y=o.baseURI)!=null&&y.includes("dyte.io"))throw new C("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");BS(l),Ov.init(l),d.init(c,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(R=(w=t.modules)==null?void 0:w.tracing)!=null?R:!0,(N=(P=t==null?void 0:t.modules)==null?void 0:P.devTools)==null?void 0:N.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:`${($=t.authToken)==null?void 0:$.slice(0,10)}...
|
|
18
|
-
${(x=t.authToken)==null?void 0:x.slice(-10)}`}});const u=await dl.init(c),h=new Hr(c,u);return c.setValue("meeting",h),h}static setupContext(t,e,r,i){var d,l;const n=Cr.createContext(t,e),o={...R_,...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",I_({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Is(e.cachedUserDetails)),n.setValue("sdkVersion","2.0.
|
|
18
|
+
${(x=t.authToken)==null?void 0:x.slice(-10)}`}});const u=await dl.init(c),h=new Hr(c,u);return c.setValue("meeting",h),h}static setupContext(t,e,r,i){var d,l;const n=Cr.createContext(t,e),o={...R_,...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",I_({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.1"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new K1),n}async join(){const{selfController:t}=a(this,He);return t.self.roomJoined?null:t.joinRoom()}async leave(t){var r;Ov.cleanup(),a(this,pn).getValue("peerSessionStore").reset(),(r=a(this,He).pluginController)==null||r.cleanup();const{selfController:e}=a(this,He);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,He).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,He).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,He).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,He).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,He).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,He).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,He).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,He).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,He).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,He).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,He).stageController)==null?void 0:t.stage}get stores(){return a(this,He).storesManager}get audio(){return a(this,pn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,He).internalsController)==null?void 0:t.internals}},He=new WeakMap,pn=new WeakMap,Zv);ll([ot("0002"),er.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Hr.prototype,"join",1),ll([ot("0003")],Hr.prototype,"leave",1),ll([ot("0001"),er.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Hr,"init",1),Hr=ll([ot("0000")],Hr);const Dv=Hr;return Dv}();
|
package/dist/dependencies.txt
CHANGED