@cloudflare/realtimekit 1.4.0-staging.5 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.js CHANGED
@@ -15,7 +15,7 @@ ${this.message}`;try{let d=n&&!!i;r&&r.endsWith("00")&&i&&(d=!0),d&&i.error("Cli
15
15
  `)+`\r
16
16
  `},Mi=tS,e1=ZD,rl=e1,Oi=Mi.parse;Mi.parseParams,Mi.parseFmtpConfig,Mi.parsePayloads,Mi.parseRemoteCandidates,Mi.parseImageAttributes,Mi.parseSimulcastStreamList;class il extends Lh{constructor(e,r){super(e);p(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new il(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,g)=>{var F;const S=Oi(h),y=S.media[S.media.length-1],w=y.rtp.filter(L=>g.some(B=>B.name===L.codec)),b=y.fmtp.filter(L=>w.some(B=>B.payload===L.payload)),C=(F=y.rtcpFb)==null?void 0:F.filter(L=>w.some(B=>B.payload===L.payload)),D=w.map(L=>L.payload);return S.media[S.media.length-1].rtp=w,S.media[S.media.length-1].fmtp=b,S.media[S.media.length-1].rtcpFb=C,S.media[S.media.length-1].payloads=D.join(" "),rl(S)},l=await this.pc.createOffer();if(l.sdp=d(l.sdp,i),this.logger.debug(`send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),await this.pc.setLocalDescription(l),e==="audio"||e.kind==="audio"){const{enableDtx:h,enableStereo:g}=this,S=this.enableHighBitrate?g?128e3:64e3:g?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${g?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${S}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:l,callback:async h=>(this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),await this.pc.setRemoteDescription(h),c.mid),sender:c.sender,mid:c.mid}}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters(),o=n.encodings.length-1-r;n.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),await i.sender.setParameters(n)}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 Fh extends Lh{static createFactory(t){return()=>new Fh(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 g;const h=o.codecs.find(S=>S.mimeType.includes(u.name));if(u.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(u.parameters)}`);const S=((g=h.sdpFmtpLine)==null?void 0:g.split(";"))||[];S.push(...u.parameters);const y=[...new Set(S).values()];h.sdpFmtpLine=y.join(";")}c.push(h)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(c)}`),n.setCodecPreferences(c);const d=await this.pc.createOffer();if(await this.pc.setLocalDescription(d),t==="audio"||t.kind==="audio"){const{enableStereo:u,enableDtx:h}=this,g=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=${g}`)}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 t1(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}class s1 extends tl{constructor(e,r){var i;super(e);m(this,Js);m(this,nc);m(this,Dl);m(this,Nl);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");m(this,ic,void 0);m(this,sn,void 0);m(this,Ws,void 0);m(this,Ol,void 0);this.id=r.id,this.localId=r.localId,f(this,ic,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,f(this,Ws,!1),this.producerId=r.producerId,this.track=r.track,f(this,sn,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,x(this,Dl,cv).call(this),f(this,Ol,e)}get closed(){return a(this,Ws)}get kind(){return this.track.kind}get paused(){return a(this,sn)}close(e,r){a(this,Ws)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,Js,mi)),f(this,Ws,!0),r&&(x(this,Nl,dv).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(a(this,Ws))throw new Nt("closed");return a(this,ic).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",a(this,Js,mi)),a(this,Ws)){this.logger.error("consumer::pause() | Consumer closed",a(this,Js,mi));return}f(this,sn,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,Js,mi)),a(this,Ws)){this.logger.error("Consumer::resume() | Consumer closed",a(this,Js,mi));return}f(this,sn,!1),this.track.enabled=!0,this.safeEmit("resume")}}ic=new WeakMap,sn=new WeakMap,Ws=new WeakMap,Ol=new WeakMap,Js=new WeakSet,mi=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},nc=new WeakSet,cp=function(){this.logger.debug('Consumer::track "ended" event',a(this,Js,mi)),this.safeEmit("trackended")},Dl=new WeakSet,cv=function(){this.track.addEventListener("ended",x(this,nc,cp).bind(this))},Nl=new WeakSet,dv=function(){try{this.track.removeEventListener("ended",x(this,nc,cp)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...a(this,Js,mi),error:e})}};class r1 extends tl{constructor(e,r){var i,n;super(e);m(this,Qt);p(this,"id");p(this,"localId");m(this,Is,void 0);p(this,"kind");p(this,"appData");p(this,"rtpSender");m(this,Ma,void 0);m(this,Oa,void 0);m(this,rn,void 0);m(this,hs,!1);m(this,ot,void 0);m(this,ci,void 0);m(this,Da,void 0);m(this,Vl,void 0);this.id=r.id,this.localId=r.localId,f(this,ot,r.track),this.kind=(i=r.track)==null?void 0:i.kind,f(this,ci,r.disableTrackOnPause?!((n=r.track)!=null&&n.enabled):!1),f(this,Da,void 0),f(this,Ma,r.stopTracks),f(this,Oa,r.disableTrackOnPause),f(this,rn,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),f(this,Is,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),f(this,Vl,e)}get closed(){return a(this,hs)}get track(){return a(this,ot)}get paused(){return a(this,ci)}get maxSpatialLayer(){return a(this,Da)}async close(e){if(a(this,hs))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,Qt,xs)),f(this,hs,!0),this._destroyTrack(),e===al){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await a(this,Is).stopSending(this.localId),{answer:n}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(n)}async getStats(){if(a(this,hs))throw new Nt("closed");return a(this,Is).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",a(this,Qt,xs)),a(this,hs)&&this.logger.error("Producer::pause() | Producer closed",a(this,Qt,xs)),f(this,ci,!0),a(this,ot)&&a(this,Oa)&&(a(this,ot).enabled=!1),a(this,rn)&&a(this,Is).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,Qt,xs)),a(this,hs)){this.logger.error("Producer::resume() | Producer closed",a(this,Qt,xs));return}f(this,ci,!1),a(this,ot)&&a(this,Oa)&&(a(this,ot).enabled=!0),a(this,rn)&&a(this,Is).replaceTrack(this.localId,a(this,ot)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,a(this,Qt,xs)),a(this,hs)){if(e&&a(this,Ma))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...a(this,Qt,xs),error:r})}throw new Nt("closed")}else if(e&&e.readyState==="ended")throw new Nt("track ended");if(e===a(this,ot)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,a(this,Qt,xs));return}(!a(this,rn)||!a(this,ci))&&await a(this,Is).replaceTrack(this.localId,e),this._destroyTrack(),f(this,ot,e),this._handleTrack()}async setMaxSpatialLayer(e){if(a(this,hs))throw new Nt("closed");if(this.kind!=="video")throw new wo("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await a(this,Is).setMaxSpatialLayer(this.localId,e),f(this,Da,e)}async setRtpEncodingParameters(e){if(a(this,hs))throw new Nt("closed");if(typeof e!="object")throw new TypeError("invalid params");await a(this,Is).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,Qt,xs)),this.safeEmit("trackended",this.track.id)}_handleTrack(){a(this,ot)&&a(this,ot).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(a(this,ot))try{a(this,ot).removeEventListener("ended",this._onTrackEnded),a(this,Ma)&&a(this,ot).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...a(this,Qt,xs),error:r})}}}Is=new WeakMap,Ma=new WeakMap,Oa=new WeakMap,rn=new WeakMap,hs=new WeakMap,ot=new WeakMap,ci=new WeakMap,Da=new WeakMap,Vl=new WeakMap,Qt=new WeakSet,xs=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function rS(s){return typeof s=="object"&&!Array.isArray(s)&&s!==null}function $h(s){return Math.random().toString(36).substring(2,2+s)}const nl=1;function iS(s){const t=s;return delete t.payload._bolt,t}function i1(s){return s.payload&&rS(s.payload)}function n1(s){var t,e;return i1(s)&&(e=(t=s.payload._bolt)==null?void 0:t.id)!=null?e:""}const Na=class extends lt.EventEmitter{constructor(e,r,i,n){super();p(this,"channel");p(this,"queue");p(this,"serverProtocolVersion");m(this,di,new Map);m(this,Ll,void 0);m(this,nn,void 0);p(this,"respond",(e,r,i=!1)=>{let n;i?n=Na.createErrorResponse(e,r):n=Na.createResponse(e,r),this.channel.send(JSON.stringify(n))});p(this,"notify",e=>{const r=Na.createNotification(e);this.channel.send(JSON.stringify(r))});p(this,"request",async e=>{const r=Na.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=fi();for(let l=0;l<o;l+=1){const u=c[l],g=JSON.stringify({id:d,count:o,chunkIndex:l,chunk:u});a(this,nn).debug(`Sending message chunk over dc: ${g}`),this.channel.send(g)}}else a(this,nn).debug(`Sending message over dc: ${r}`),this.channel.send(r)});p(this,"processMessage",e=>{var i;a(this,di).has(e.id)||a(this,di).set(e.id,[]);const r=a(this,di).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,di).get(e.id),o=n==null?void 0:n.reduce((d,l)=>d+l.chunk,"");a(this,di).delete(e.id);const c=JSON.parse(o);if(!c.payload||!rS(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,nn).debug(`resolving pending request with id: ${r}, complete response: ${JSON.stringify(e)}`),e.type==="error"?i.cancel(iS(e)):i.resolve(iS(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:$h(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1});this.label=i,this.transportId=n,f(this,Ll,e),f(this,nn,e.getValue("logger")),this.channel=r,this.queue=new Map}};let Di=Na;di=new WeakMap,Ll=new WeakMap,nn=new WeakMap,p(Di,"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:$h(8),type:"REQUEST",version:nl}}}}),p(Di,"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:nl}}}}),p(Di,"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:$h(8),type:"NOTIFY",version:nl}}}}),p(Di,"createErrorResponse",(e,r)=>({type:"error",payload:{error:r.message,_bolt:{id:e,type:"RESPONSE",version:nl}}}));const al="transport closed",Va=class extends tl{constructor(e,{id:r,direction:i,handlerFactory:n,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:h}){var w,b,C;super(e);p(this,"awaitQueue");p(this,"observer");p(this,"id");p(this,"serverId");p(this,"direction");p(this,"maxSctpMessageSize");p(this,"handler");p(this,"connectionState","new");p(this,"producers");p(this,"consumers");p(this,"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");m(this,an,void 0);f(this,an,e);const g=e.getValue("logger");g.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const S=t1(l,{});delete S.iceServers,delete S.iceTransportPolicy,delete S.bundlePolicy,delete S.rtcpMuxPolicy,delete S.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new Vh(g,!0),this.handler=n(),this.handler.enableHighBitrate=(w=h==null?void 0:h.enableHighBitrate)!=null?w:!1,this.handler.enableStereo=(b=h==null?void 0:h.enableStereo)!=null?b:!1,this.handler.enableDtx=(C=h==null?void 0:h.enableDtx)!=null?C:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=u||{};const y=3e4;this.transportConnectionPromise=new Promise(D=>{const F=setTimeout(()=>{g.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),D(!1)},y);this.once("connected",()=>{clearTimeout(F),D(!0)}),this.once("disconnect",()=>{clearTimeout(F),D(!1)}),this.once("close",()=>{clearTimeout(F),D(!1)})}),this.eventsDCReadyPromise=new Promise(D=>{this.eventsDCReadyPromiseResolver=D}),this.handler.on("@connectionstatechange",D=>{D!==this.connectionState&&(this.logger.debug(`connection state changed to ${D}`),this.connectionState=D,D==="connected"&&(this.connected=!0,this.emit("connected")),D==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(D==="failed"||D==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",D))}),this.handler.on("@icecandidate",({candidate:D})=>{this.closed||this.safeEmit("icecandidate",D)}),this.handler.on("dc_open",D=>{let F=this.datachannels.get(D.label);F||(F||(F=new Di(a(this,an),D,D.label,this.serverId),this.datachannels.set(D.label,F)),this.eventsDCFailureTimer=setTimeout(()=>{D.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",D.label))},5e3))}),this.handler.on("datachannel",(D,F)=>{D.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const L=this.datachannels.get(D.label);if(!L){this.logger.error("unregistered datachannel for message",{rtcChannel:{label:D.label,message:F}});return}try{const B=JSON.parse(F);this.logger.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:B.id,count:B.count,chunkIndex:B.chunkIndex,chunk:B.chunk,transprtId:this.serverId}});const Q=L.processMessage(B);if(!Q)return;this.logger.debug(`datachannel message with id:${B.id} on transport:${this.serverId}complete - ${JSON.stringify(Q)}`),this.emit(`datachannel:${D.label}`,L.label,Q)}catch(B){this.logger.error("error parsing message",{error:B})}})}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(al).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(al)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new Nt("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 Nt("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new wo("not a sending Transport");if(r.readyState==="ended")throw new Nt("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 Ai("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:g,localId:S,rtpSender:y}=await this.awaitQueue.push(async()=>{const{offerSdp:w,callback:b,sender:C,mid:D}=await this.handler.send({track:n,encodings:o,codecOptions:c,screenShare:h==null?void 0:h.screenShare}),{answer:F,producerId:L}=await r({offer:w,kind:n.kind,paused:l?!n.enabled||Object.hasOwn(n,"fakeTracks"):!1,appData:{...h||{},mid:D},codecOptions:c,producingTransportId:this.serverId}),B=await b(F);return{producerId:L,localId:B,rtpSender:C}},"Transport.produce");return this.createProducerObject({id:g,localId:S,track:n,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:h,handler:this.handler,rtpSender:y})}async createProducerObject(e){const r=new r1(a(this,an),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 Nt("closed");if(this.direction!=="recv")throw new wo("not a receiving transport");if(!await this.transportConnectionPromise)throw new Ai("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(g=>l.push(g)).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=Oi(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=Oi(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:rl(n)}}static parseHeaderExtensionMappings(e){const r=Oi(e.sdp),i={};return r.media.forEach(n=>{i[n.mid]=n.ext}),i}static setHeaderExtensionMappings(e,r){const i=Oi(e.sdp);return i.media=i.media.map(o=>{const c={...o};return c.ext=r[o.mid],c}),{...e,sdp:rl(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),n=Va.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=Va.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("Created offer for closing consumers",{sdp:c.sdp}),c=Va.setCodecAndFmtpMappings(c,i,n),c=Va.setHeaderExtensionMappings(c,o),this.logger.info("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("Received answer in close consumers",{sdp:d.sdp}),await this.setRemoteDescription(d),this.logger.info("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("Received offer from SFU",{sdp:e.sdp}),await this.setRemoteDescription(e);const r=await this.handler.pc.createAnswer();this.logger.info("Created answer corresponding to received offer",{sdp:r.sdp});const i=Oi(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=rl(i),this.logger.info("Setting munged SDP",{sdp:r.sdp}),await this.setLocalDescription(r),this.logger.info("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:g}=e,S=`${c}:${h}`,y={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(w,b)=>{const C=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${S} producingPeerId: ${n}`),this.consumerTrackEvents.delete(S),y.isTimedout=!0,b(y)},5e3),D=(L,B)=>{try{if(L.readyState==="ended")clearTimeout(C),b(y);else{const Q=L;Q.enabled=!0,this.handler.midTransceiverMap.set(B.mid,B);const se=new s1(a(this,an),{id:r,localId:B.mid,transceiver:B,track:Q,paused:d,producerId:i,producingPeerId:n,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:n},rtpReceiver:B.receiver,mimeType:g});this.consumers.set(r,se),se.once("close",()=>{this.consumers.delete(se.id),this.handler.midTransceiverMap.delete(B.mid)}),this.logger.info("consumer created for ",{consumer:{id:r,kind:h,appData:{screenShare:l},peerId:n,producerId:i}}),this.emit("newconsumer",se),clearTimeout(C),w(se)}}catch(Q){this.logger.warn("error while creating consumer:",Q),clearTimeout(C),b(y)}},F=this.unknownTracksMap.get(S);F?(this.logger.info(`track event already received [trackId: ${F.track.id}] [mid: ${F.transceiver.mid}]`),this.unknownTracksMap.delete(S),D(F.track,F.transceiver)):(this.logger.info(`Registering onTrack handler for key ${S} [producingPeerId: ${n}]`),this.consumerTrackEvents.set(S,D))})}async setRemoteDescription(e){await this.handler.pc.setRemoteDescription(e)}async setLocalDescription(e){this.logger.debug(`${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 qD("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 Bh=Va;an=new WeakMap;function a1(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=yp.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 o1{constructor(t,{handlerName:e,handlerFactory:r}={}){p(this,"handlerFactory");m(this,wr,void 0);m(this,on,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),f(this,wr,t),f(this,on,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,on).debug(`Device::constructor() | handler given: ${e}`);else if(e=a1(a(this,on)),e)a(this,on).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=xh.createFactory(a(this,wr));break;case"Safari12":this.handlerFactory=Fh.createFactory(a(this,wr));break;case"Firefox60":this.handlerFactory=il.createFactory(a(this,wr),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=il.createFactory(a(this,wr),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=fi();return new Bh(a(this,wr),{id:e,...t,handlerFactory:this.handlerFactory})}}wr=new WeakMap,on=new WeakMap;const c1=2e3;class d1 extends lt.EventEmitter{constructor(e,r){super();m(this,Fa);m(this,dc);m(this,xl);m(this,lc);m(this,Ul);m(this,Fl);m(this,$l);m(this,Bl);m(this,Hl);m(this,uc);m(this,hc);p(this,"context");m(this,La,void 0);m(this,ft,void 0);m(this,St,void 0);m(this,ac,void 0);m(this,oc,void 0);m(this,cn,void 0);m(this,xa,void 0);m(this,cc,void 0);m(this,Ua,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});m(this,dn,void 0);m(this,Ks,"all");this.context=e,f(this,cn,r),f(this,La,new o1(e)),f(this,xa,new JD(r)),f(this,cc,ys),a(this,Fa,Su).mediaState={send:{state:Bn.NEW},recv:{state:Bn.NEW}},(On(this.context,"forceRelay")||this.context.getValue("flagsmith").hasFeature(Z.FORCE_RELAY))&&f(this,Ks,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,Ks)}`),x(this,dc,dp).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,cn)}get socketHandler(){return a(this,xa)}get sendTransport(){return a(this,ft)}get recvTransport(){return a(this,St)}get events(){return a(this,cc)}set sendTransportConnectedCallback(e){f(this,ac,e)}set recvTransportConnectedCallback(e){f(this,oc,e)}async setupTransports(e){await x(this,xl,lv).call(this,e);let r,i;e.send&&(r=x(this,lc,lp).call(this,a(this,ft)).then(n=>{try{a(this,ac).call(this,n)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=x(this,lc,lp).call(this,a(this,St)).then(n=>{try{a(this,oc).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,ft);this.logger.info("Closing send transport",{transport:{id:n,serverId:o,type:c}}),a(this,ft).close(),a(this,ft).removeAllListeners(),f(this,ft,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,St);this.logger.info("Closing recv transport",{transport:{id:n,serverId:o,type:c}}),(r=a(this,St))==null||r.close(),(i=a(this,St))==null||i.removeAllListeners(),f(this,St,void 0)}x(this,dc,dp).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}La=new WeakMap,ft=new WeakMap,St=new WeakMap,ac=new WeakMap,oc=new WeakMap,cn=new WeakMap,xa=new WeakMap,cc=new WeakMap,Ua=new WeakMap,dn=new WeakMap,Ks=new WeakMap,Fa=new WeakSet,Su=function(){return this.context.getValue("connectionHandler")},dc=new WeakSet,dp=function(){f(this,dn,{send:void 0,recv:void 0})},xl=new WeakSet,lv=async function(e){var o,c,d,l,u,h,g,S;(On(this.context,"forceRelay")||this.context.getValue("flagsmith").hasFeature(Z.FORCE_RELAY))&&f(this,Ks,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,Ks)}`);const n=await yt().getICEServers().catch(y=>(this.logger.warn(`failed to get iceservers from server: ${y.message}`),[]));if(e.send){const y=this.context.getValue("flagsmith").hasFeature(Z.DISABLE_OPUS_DTX_CF);x(this,Fl,hv).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:(g=(h=(u=this.context.getValue("defaults").mediaConfiguration)==null?void 0:u.audio)==null?void 0:h.enableStereo)!=null?g:!1,enableDtx:!!y},iceTransportPolicy:a(this,Ks)})}e.recv&&x(this,$l,pv).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(S=this.context.getValue("modules").e2ee)==null?void 0:S.enabled},iceTransportPolicy:a(this,Ks)})},lc=new WeakSet,lp=async function(e){const{id:r,serverId:i,direction:n}=e;x(this,Bl,gv).call(this,e);try{return await eS(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 Ai("Cannot reconnect closed transport");await x(this,Ul,uv).call(this,e)}catch(l){if(l instanceof Ai){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}},Ul=new WeakSet,uv=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!a(this,cn).isConnected)throw new Ai("Socket is not connected");if(e.connectionState==="closed")throw new Ai("Transport is closed");try{await e.connect(n=>x(this,Hl,mv).call(this,i,n)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(n){throw a(this,Ua).transportFailureCount[i]+=1,n.message==="ice connection failed"?new Ai(n.message):n}},Fl=new WeakSet,hv=function(e){var r,i;if(a(this,ft)&&a(this,ft).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=a(this,ft))==null?void 0:r.id,serverId:(i=a(this,ft))==null?void 0:i.serverId,type:"send"}});return}f(this,ft,a(this,La).createTransport({...e,direction:"send"})),this.context.getValue("callstats").configureSendTransport(a(this,ft))},$l=new WeakSet,pv=function(e){var r,i;if(a(this,St)&&a(this,St).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=a(this,St))==null?void 0:r.id,serverId:(i=a(this,St))==null?void 0:i.serverId,type:"recv"}});return}f(this,St,a(this,La).createTransport({...e,direction:"recv"})),this.context.getValue("callstats").configureRecvTransport(a(this,St))},Bl=new WeakSet,gv=function(e){const{direction:r,id:i}=e;e.on("connectionstatechange",async n=>{x(this,hc,hp).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,dn)[r];c!==void 0&&(clearTimeout(c),a(this,dn)[r]=void 0)};switch(n){case"connected":o(),a(this,Ua).lastConnectionTime=performance.now();break;case"disconnected":a(this,dn)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await x(this,uc,up).call(this,e.direction)},c1);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 x(this,uc,up).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,n1(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"))})},Hl=new WeakSet,mv=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?ir.SUBSCRIBER:ir.PUBLISHER},producers:[]};return a(this,xa).connectTransport(c)}catch(n){throw this.logger.error(`Error in ${e} transport connection:`,{error:n}),n}},uc=new WeakSet,up=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),this.context.getValue("flagsmith").hasFeature(Z.CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED)&&a(this,cn).isConnected&&a(this,Ua).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),f(this,Ks,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:a(this,ft)}),this.context.getValue("peerSessionStore").emit(_.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,St)}),this.context.getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}x(this,hc,hp).call(this,{state:Bn.CONNECTED,direction:e})},hc=new WeakSet,hp=function(e){const{state:r,direction:i}=e;a(this,Fa,Su).mediaState[i]={state:r},this.context.getValue("peerSessionStore").emit(_.TRANSPORT_STATE_UPDATE,{transport:i,...a(this,Fa,Su).mediaState[i]})};class l1{constructor(t,e,r,i,n){m(this,ql,void 0);m(this,ps,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=n,f(this,ql,t),f(this,ps,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,g={simulcast:{preferredRid:"f",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}};e.set(u,l),r.push({producingPeerId:l,producerId:u,producingTransportId:h,...g})});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,ps).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(g){}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,ps).info("Negotiating socket consumer",{transport:this.recvTransport}),a(this,ps).debug(`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:ir.SUBSCRIBER}};return a(this,ps).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,qR.toBinary(r)),a(this,ps).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){a(this,ps).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,ps).info(`Closing consumers: ${JSON.stringify(n)}`);const o={description:{sdp:i.sdp,type:i.type,target:ir.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=fk.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,ps).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:n})=>n)})}}ql=new WeakMap,ps=new WeakMap;class Hh{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return Oi(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,g;const c=Hh.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:ir.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(h=i.screenShare)!=null?h:!1,mimeType:`${e}/${(g=n[0])==null?void 0:g.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}class u1 extends d1{constructor(e,r){super(e,r);m(this,gc);m(this,Gl);m(this,Wl);m(this,Jl);m(this,Kl);m(this,ln,void 0);m(this,li,void 0);m(this,$a,void 0);m(this,pc,void 0);m(this,zs,void 0);m(this,jl,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});m(this,Pr,[]);m(this,Ba,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{f(this,pc,new Hh(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{a(this,$a).clear(),f(this,zs,new l1(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,ln)}get consumers(){return a(this,li)}get producerIdToConsumerIdMap(){return a(this,$a)}get logger(){return this.context.getValue("logger")}reset(){f(this,ln,new Map),f(this,li,new Map),f(this,$a,new Map)}async createProducer(e,r){var i;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const n=await this.sendTransport.produce(e,x(this,Gl,fv).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(_.E2EE_ACTIVE_PRODUCER,n),x(this,Wl,Sv).call(this,n,r),n}catch(n){throw this.logger.error("Failed to create producer",{error:n}),a(this,jl).producerCreationFailureCount+=1,n}}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(_.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,ln).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){a(this,Ba)||clearTimeout(a(this,Ba)),f(this,Pr,a(this,Pr).concat(e)),await x(this,gc,pp).call(this)}closeConsumer(e){return this.closeConsumers([e])}async closeConsumers(e){if(!a(this,zs))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,zs).close(r);i!=null&&i.length&&this.logger.warn("Failed to close some consumers",{consumerIds:i})}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,li).keys()))}async switchConsumersToLayer(e,r){a(this,zs).switchConsumersToLayer(e,r)}}ln=new WeakMap,li=new WeakMap,$a=new WeakMap,pc=new WeakMap,zs=new WeakMap,jl=new WeakMap,Pr=new WeakMap,Ba=new WeakMap,gc=new WeakSet,pp=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=a(this,Pr).splice(0,a(this,Pr).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,x(this,Jl,vv).bind(this),a(this,zs).negotiate.bind(a(this,zs)));if(o.forEach(x(this,Kl,Tv).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,Pr,a(this,Pr).concat(d)),f(this,Ba,setTimeout(x(this,gc,pp).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})}}},Gl=new WeakSet,fv=function(e){return a(this,pc).create(e)},Wl=new WeakSet,Sv=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!==al){const d={producerId:e.id,description:{sdp:o.sdp,type:o.type,target:ir.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,ln).set(e.id,e)},Jl=new WeakSet,vv=async function(e){try{return await this.recvTransport.canConsume(),await a(this,zs).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},Kl=new WeakSet,Tv=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,li).delete(e.id),this.context.getValue("peerSessionStore").emit(_.CONSUMER_CLOSED,{id:e.id})}),a(this,li).set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),this.context.getValue("peerSessionStore").emit(_.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId})};const Zl=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}={}){m(this,zl);m(this,Yl);m(this,mc,void 0);m(this,fc,void 0);m(this,Sc,void 0);m(this,Ha,void 0);m(this,qa,void 0);m(this,ja,void 0);m(this,vc,void 0);m(this,Tc,void 0);m(this,Ga,void 0);m(this,Lt,void 0);m(this,As,void 0);m(this,Ms,!1);m(this,un,0);m(this,hn,0);m(this,_r,[]);m(this,yc,void 0);f(this,Ha,t),f(this,Lt,t),f(this,mc,e),f(this,fc,r),f(this,Sc,i),f(this,qa,n),f(this,ja,o),f(this,vc,c),f(this,Tc,d),f(this,Ga,l),f(this,yc,u),f(this,As,t/2)}get voiceDetected(){return a(this,Ms)}processAudioChunk(t){var o,c;const e=x(o=Zl,Ql,bv).call(o,t),r=x(c=Zl,Xl,wv).call(c,t);return x(this,zl,yv).call(this,e),e/a(this,As)>a(this,Ga)&&e>a(this,Lt)&&r>a(this,mc)?(f(this,un,a(this,un)+1),f(this,hn,a(this,Sc)),a(this,un)>=a(this,fc)&&f(this,Ms,!0)):(f(this,un,0),a(this,hn)>0?f(this,hn,a(this,hn)-1):a(this,Ms)&&f(this,Ms,!1),a(this,Ms)||x(this,Yl,Ev).call(this,e)),{energy:e,isVoice:a(this,Ms)}}reset(){f(this,Ms,!1),f(this,un,0),f(this,hn,0),f(this,Lt,a(this,Ha)),f(this,As,a(this,Ha)/2),f(this,_r,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,Lt),backgroundNoiseEnergy:a(this,As),energyRatioThreshold:a(this,Ga)}}};let _o=Zl;mc=new WeakMap,fc=new WeakMap,Sc=new WeakMap,Ha=new WeakMap,qa=new WeakMap,ja=new WeakMap,vc=new WeakMap,Tc=new WeakMap,Ga=new WeakMap,Lt=new WeakMap,As=new WeakMap,Ms=new WeakMap,un=new WeakMap,hn=new WeakMap,_r=new WeakMap,yc=new WeakMap,zl=new WeakSet,yv=function(t){a(this,Ms)?f(this,Lt,a(this,ja)*a(this,Lt)+(1-a(this,ja))*t):f(this,Lt,a(this,qa)*a(this,Lt)+(1-a(this,qa))*a(this,As)),f(this,Lt,Math.max(a(this,vc),Math.min(a(this,Tc),a(this,Lt))))},Yl=new WeakSet,Ev=function(t){if(t<a(this,Lt)*1.2)if(a(this,_r).push(t),a(this,_r).length>a(this,yc)&&a(this,_r).shift(),a(this,_r).length>=10){const e=[...a(this,_r)].sort((i,n)=>i-n),r=Math.floor(e.length/2);f(this,As,e[r])}else f(this,As,.95*a(this,As)+.05*t)},Ql=new WeakSet,bv=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Xl=new WeakSet,wv=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},m(_o,Ql),m(_o,Xl);class nS{constructor(t){p(this,"RNAudioSampleHandler");m(this,Ec,void 0);f(this,Ec,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,Ec).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()}}Ec=new WeakMap;class aS{constructor(t){p(this,"audioContext");p(this,"analyser");m(this,bc,void 0);f(this,bc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return a(this,bc).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)}}bc=new WeakMap;class h1{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 p1=60,g1=400,_c=class{constructor(t,e){m(this,eu);m(this,tu);m(this,Rr,void 0);m(this,Cr,void 0);m(this,Os,void 0);m(this,wc,void 0);m(this,pn,void 0);m(this,Wa,void 0);m(this,kr,void 0);m(this,ui,void 0);m(this,Ja,void 0);m(this,Ir,void 0);m(this,Ar,void 0);m(this,Ys,void 0);this.reportRequest=e,f(this,Ir,t),f(this,Wa,new _o);const{isReactNative:r}=navigator;f(this,Ar,r?new nS(a(this,Ir)):new aS(a(this,Ir))),f(this,Ys,r?h1:Bf)}get logger(){return a(this,Ir).getValue("logger")}set producerId(t){f(this,Os,t)}set audioTrack(t){f(this,wc,t),a(this,Ar)instanceof aS&&(a(this,Ar).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${a(this,Os)}`),a(this,Rr)&&a(this,Ys).clearInterval(a(this,Rr)),f(this,Rr,a(this,Ys).setInterval(async()=>{var i;if(!a(this,wc)||!a(this,Os))return;const{energy:t}=x(this,eu,Pv).call(this),e=x(i=_c,Pc,gp).call(i,t);let r=.9;a(this,Ja)!==e&&a(this,Ja)?r=.9:e?r=.3:r=.5,f(this,pn,(a(this,pn)||0)*(1-r)+t*r)},p1)),a(this,Cr)&&a(this,Ys).clearInterval(a(this,Cr)),f(this,Cr,a(this,Ys).setInterval(x(this,tu,_v).bind(this),g1))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${a(this,Os)}`),a(this,Rr)&&(a(this,Ys).clearInterval(a(this,Rr)),f(this,Rr,void 0)),a(this,Cr)&&(a(this,Ys).clearInterval(a(this,Cr)),f(this,Cr,void 0))}catch(t){}a(this,Wa).reset(),a(this,Ar)instanceof nS&&a(this,Ar).stop()}};let Ro=_c;Rr=new WeakMap,Cr=new WeakMap,Os=new WeakMap,wc=new WeakMap,pn=new WeakMap,Wa=new WeakMap,kr=new WeakMap,ui=new WeakMap,Ja=new WeakMap,Ir=new WeakMap,Ar=new WeakMap,Ys=new WeakMap,eu=new WeakSet,Pv=function(){var o;const{samples:t}=a(this,Ar),{energy:e,isVoice:r}=a(this,Wa).processAudioChunk(t),i=x(o=_c,su,Rv).call(o,e);return a(this,Ir).getValue("flagsmith").hasFeature(Z.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: producer: ${a(this,Os)}, energy: ${a(this,pn)},
17
17
  slogScale: ${i}, isVoice: ${r}, minEnergy: ${a(this,kr)},
18
- maxEnergy: ${a(this,ui)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,kr)||i<a(this,kr))&&f(this,kr,i),(!a(this,ui)||i>a(this,ui))&&f(this,ui,i),{energy:(i-a(this,kr))/(a(this,ui)-a(this,kr))*10||0,isVoice:r})},Pc=new WeakSet,gp=function(t){return t<5},tu=new WeakSet,_v=function(t=a(this,pn)){var r;if(!a(this,Os)||!t){a(this,Ir).getValue("flagsmith").hasFeature(Z.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,Os)}`);return}const e={producerId:a(this,Os),energy:Math.round(t),silent:x(r=_c,Pc,gp).call(r,t)};f(this,Ja,e.silent),this.reportRequest(e)},su=new WeakSet,Rv=function(t){const e=Math.log10(t);return Math.round(e)},m(Ro,Pc),m(Ro,su);const m1=(s=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const e=new window.MediaStreamTrackGenerator({kind:"audio"}),r=e.writable.getWriter(),i=48e3,n=128,o=1;let c=0,d=null;const l=async()=>{try{const g=new Float32Array(n*o),S=new window.AudioData({format:"f32",sampleRate:i,numberOfFrames:n,numberOfChannels:o,timestamp:c,data:g});c+=n/i*1e6,await r.ready,await r.write(S)}catch(g){d&&clearInterval(d),r.releaseLock(),e.writable.abort()}};d=window.setInterval(l,100);const h=new MediaStream([e]).getAudioTracks()[0];return h.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),e.writable.abort()}),Object.assign(h,{fakeTracks:"fakeTracks:fakeAudioTrack"}),h.enabled=s,h}catch(e){}const t=window.AudioContext||window.webkitAudioContext;if(t)try{const e=new t;if(!e||e.state!=="running"||!e.destination)return;const r=e.createOscillator();r.frequency.value=0,r.type="sine";const i=e.createGain();i.gain.value=0,r.connect(i);const n=e.createMediaStreamDestination();i.connect(n),r.start();const o=n.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=s,o):void 0}catch(e){return}},f1=(s=!1)=>{var n,o;const t=new MediaStream().getVideoTracks()[0],e=document.createElement("canvas");e.height=(n=t==null?void 0:t.getSettings().height)!=null?n:720,e.width=(o=t==null?void 0:t.getSettings().width)!=null?o:1280;const r=e.getContext("2d");r.fillStyle="black",r.fillRect(0,0,e.width,e.height),setInterval(()=>{r.fillStyle="black",r.fillRect(0,0,e.width,e.height)},1e3);const i=e.captureStream().getVideoTracks()[0];return Object.assign(i,{fakeTracks:"fakeTracks:fakeVideoTrack"}),i.enabled=s,i};var S1=Object.defineProperty,v1=Object.getOwnPropertyDescriptor,ce=(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&&S1(t,e,i),i};const Gt=["video/VP9","video/VP8"];class ie{constructor(t,e){m(this,hi);m(this,ru);m(this,iu);m(this,nu);m(this,Ic);m(this,au);m(this,ou);m(this,cu);m(this,ct);m(this,Tn);m(this,du);m(this,lu);m(this,uu);p(this,"context");p(this,"authToken");p(this,"e2ee");m(this,Rc,void 0);m(this,Cc,void 0);m(this,vt,void 0);m(this,j,void 0);m(this,Ka,void 0);m(this,kt,void 0);m(this,gn,void 0);m(this,mn,void 0);m(this,fn,void 0);m(this,kc,void 0);m(this,gs,null);m(this,Mr,void 0);m(this,Sn,void 0);m(this,vn,void 0);m(this,It,void 0);m(this,xt,void 0);var i,n;this.context=t;const{socket:r}=e;this.mediaJoined=!1,f(this,Sn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,vn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,vt,r),f(this,gn,!1),f(this,j,new u1(t,r)),f(this,kt,a(this,j).events),f(this,Mr,new Set),f(this,It,new Map),f(this,mn,!1),f(this,fn,new Vh(t.getValue("logger"))),f(this,xt,new Ro(this.context,a(this,j).socketHandler.audioActivity.bind(a(this,j).socketHandler))),this.e2ee=(n=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,kc,ju(async()=>{if(!a(this,hi,Qa).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(a(this,Cc),a(this,Rc),!0,!0);o&&(this.context.getValue("peerSessionStore").emit(_.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(_.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,hi,Qa).mediaJoined}set mediaJoined(t){a(this,hi,Qa).mediaJoined=t}reset(){a(this,j).closeAllProducers(),a(this,j).closeAllConsumers(),a(this,It).clear(),a(this,Mr).clear(),f(this,gs,null),a(this,fn).stop(),a(this,j).stopAllTransports(),a(this,j).reset(),f(this,fn,new Vh)}async joinRoom(t,e,r=!1,i=!1,n={}){a(this,hi,Qa).mediaJoinAttempted=!0,f(this,gn,!0),r&&this.reset();try{return await a(this,fn).push(()=>x(this,ru,Cv).call(this,t,e,i,n),"joinRoom")}catch(o){return this.logger.error("Error in room joining process",{error:o}),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_FAILED),{roomJoined:!1,error:o}}}async initializeConnection(t,e,r=!1,i={}){return a(this,gs)?a(this,gs):(f(this,gs,(async()=>{try{await x(this,Ic,mp).call(this,t,e,r,i)}catch(n){throw f(this,gs,null),n}})()),a(this,gs))}getConsumers(){return a(this,j).consumers}getProducers(){return a(this,j).producers}async leaveRoom(){a(this,j).stopAllTransports(),f(this,mn,!1),a(this,hi,Qa).mediaJoinAttempted=!1;const t={closeRoom:!1};a(this,vt).sendMessagePromise(a(this,kt).leaveRoom,gC.toBinary(t)).then(r=>{var i;(i=sk.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()}async activatePeers(t){return this.createConsumers(t)}async createConsumers(t){return t.length===0?Promise.resolve():a(this,j).createConsumers(t)}async closeConsumers(t){if(!t.length)return;const e=t.reduce((r,i)=>{const n=a(this,j).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,j).closeConsumers(e)}async _shareWebcam(t,e){var g,S,y,w;const r=e==="video/VP9"?me.WEBCAM:me.WEBCAM_BACKUP,i=x(this,ct,Mt).call(this,r);if(i){const b=await i;if(a(this,j).producers.has(b)){const C=a(this,j).producers.get(b);if(!C.closed)return await C.replaceTrack({track:t}),await this.resumeWebcam(r),t;await this.disableWebcam(e)}return this._shareWebcam(t,e)}const n=[e].concat(Gt.filter(b=>b!==e)),o=x(this,uu,Vv).call(this,t,n),c=On(this.context,"disableSimulcast"),d=(S=(g=this.context)==null?void 0:g.getValue("overrides"))==null?void 0:S.simulcastConfig;c||d&&d.disable||!((w=(y=this.context)==null?void 0:y.getValue("theme"))!=null&&w.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),o.encodings=YO(this.context,t),this.logger.info(`Simulcast encodings: ${JSON.stringify(o.encodings)}`)),this.context.getValue("flagsmith").hasFeature(Z.TRACK_HINT)&&(o.track.contentHint=this.context.getValue("flagsmith").getValue(Z.TRACK_HINT));const u=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,It).delete(r)},h=a(this,j).createProducer(o,u);return x(this,Tn,sd).call(this,r,h.then(b=>b.id)),h.then(b=>b.track)}async shareWebcam(t){var i;if(t===void 0)return null;const e=(i=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:i.toString();if(e)return this.logger.debug(`Calling _shareWebcam with forced video codec: ${e}`),this._shareWebcam(t,e);const r=Gt.filter(n=>{var o,c;return((c=(o=a(this,Ka).sender)==null?void 0:o.video)==null?void 0:c.codecs.findIndex(d=>d.mimeType===n))>=0&&a(this,vn).get(n).size>0});return r.length===0&&r.push(Gt[0]),await Promise.all(r.map(n=>(this.logger.debug(`Calling _shareWebcam with video codec: ${n}`),this._shareWebcam(t,n)))),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:we.isElectron()},stopTracks:!1},n=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,It).delete(me.SCREENSHARE_VIDEO),a(this,It).delete(me.SCREENSHARE_AUDIO)},o=a(this,j).createProducer(i,n);x(this,Tn,sd).call(this,me.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:we.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},l=()=>{};c=a(this,j).createProducer(d,l),x(this,Tn,sd).call(this,me.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 Nt("track undefined");const e=x(this,ct,Mt).call(this,me.MIC);if(e){const o=await e;if(a(this,j).producers.has(o)){const c=a(this,j).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),a(this,xt)&&(a(this,xt).audioTrack=t,a(this,xt).producerId=o,a(this,xt).start());return}await a(this,j).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=x(this,lu,Nv).call(this,t),i=()=>{a(this,It).delete(me.MIC)},n=a(this,j).createProducer(r,i);x(this,Tn,sd).call(this,me.MIC,n.then(o=>o.id)),await n.then(o=>{a(this,xt)&&(a(this,xt).audioTrack=o.track,a(this,xt).producerId=o.id,a(this,xt).start())})}catch(e){throw new k(e)}}async pauseMic(){var i;const t=await x(this,ct,Mt).call(this,me.MIC),e=a(this,j).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,xt))==null||i.stop();const r={producerId:e.id,pause:!0};a(this,vt).sendMessage(a(this,kt).toggleProducer,Ld.toBinary(r))}async pauseWebcam(){const t=await x(this,ct,Mt).call(this,me.WEBCAM),e=await x(this,ct,Mt).call(this,me.WEBCAM_BACKUP),r=a(this,j).producers.get(t),i=a(this,j).producers.get(e);if(!r&&!i){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const n=o=>{const c={producerId:o.id,pause:!0};a(this,vt).sendMessage(a(this,kt).toggleProducer,Ld.toBinary(c))};r&&(r.pause(),n(r)),i&&(i.pause(),n(i))}async resumeMic(){const t=await x(this,ct,Mt).call(this,me.MIC),e=a(this,j).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(_.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,vt).sendMessage(a(this,kt).toggleProducer,Ld.toBinary(r))}async resumeWebcam(t=me.WEBCAM){const e=await x(this,ct,Mt).call(this,t),r=a(this,j).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(_.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};a(this,vt).sendMessage(a(this,kt).toggleProducer,Ld.toBinary(i))}async disableWebcam(t){const e=t==="video/VP9"?me.WEBCAM:me.WEBCAM_BACKUP,r=await x(this,ct,Mt).call(this,e);x(this,du,Dv).call(this,e),r&&await a(this,j).closeProducer(r)}async disableMic(){var e;const t=await x(this,ct,Mt).call(this,me.MIC);t&&await a(this,j).closeProducer(t),(e=a(this,xt))==null||e.stop(),a(this,It).delete(me.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await x(this,ct,Mt).call(this,me.SCREENSHARE_VIDEO),e=await x(this,ct,Mt).call(this,me.SCREENSHARE_AUDIO);t&&await a(this,j).closeProducer(t),e&&await a(this,j).closeProducer(e),a(this,Mr).clear(),a(this,It).delete(me.SCREENSHARE_VIDEO),a(this,It).delete(me.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await x(this,ct,Mt).call(this,me.WEBCAM),i=await x(this,ct,Mt).call(this,me.WEBCAM_BACKUP);await a(this,j).closeProducer(r,{stopTrack:!1}),await a(this,j).closeProducer(i,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await x(this,ct,Mt).call(this,me.SCREENSHARE_VIDEO);await a(this,j).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,j).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};a(this,j).socketHandler.kickPeer(e)}kickAll(){a(this,j).socketHandler.kickAll()}async muteAll(t){if(!await a(this,j).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,j).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await a(this,j).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await a(this,j).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,vt).sendMessagePromise(a(this,kt).globalPinPeer,kC.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&a(this,j).producers.get(t.producerId)&&a(this,Mr).add(t.consumerPeerId),a(this,Mr).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));a(this,j).switchConsumersToLayer(r,e)}async handleSocketEvents(){a(this,vt).on(a(this,kt).peerProducerCreateBroadcast,({payload:t})=>{var e,r;if(this.mediaJoined)try{const{participantId:i,producerState:n}=Ok.fromBinary(t);if(i===this.peerId)return;if(n!=null&&n.mimeType||(n.mimeType=n.kind===Bs.AUDIO?"audio/opus":"video/VP8"),n.kind===Bs.VIDEO&&!n.screenShare&&((r=(e=a(this,Ka).receiver)==null?void 0:e.video)==null?void 0:r.codecs.findIndex(o=>o.mimeType===Gt[0]))>=0&&a(this,Sn).get(Gt[0]).has(i)&&n.mimeType!==Gt[0]){this.logger.warn(`Ignoring producer: ${n.producerId}`);return}this.logger.info(`producer created broadcast: ${i}, producer state: ${n}`),this.context.getValue("peerSessionStore").emit(_.NEW_PRODUCER,{peerId:i,producer:{...n,kind:n.kind===Bs.AUDIO?"audio":"video",producingPeerId:i}})}catch(i){this.logger.error("error in peer-producer-create-broadcast",{error:i})}}),a(this,vt).on(a(this,kt).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:i,pause:n,producerId:o,screenShare:c}}=zm.fromBinary(t);if(c)return;const d=i===Bs.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${o}, kind:${d}, paused:${n} payload: ${JSON.stringify(zm.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&n&&this.context.getValue("peerSessionStore").emit(d==="audio"?_.MUTE_SELF:_.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(_.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(_.CONSUMER_PAUSED,{id:u.id})):(u.resume(),this.context.getValue("peerSessionStore").emit(_.CONSUMER_RESUMED,{id:u.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,vt).on(a(this,kt).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=rh.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,Mr).delete(e),a(this,j).consumers.forEach(r=>{r.peerId===e&&r.close()}),this.context.getValue("peerSessionStore").emit(_.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),a(this,vt).on(a(this,kt).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=Vk.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(_.PRODUCER_CLOSED,{peerId:e,producerId:r});const i=a(this,j).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,j).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),a(this,j).producerIdToConsumerIdMap.delete(r),this.context.getValue("peerSessionStore").emit(_.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,vt).on(a(this,kt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,gn)&&!a(this,mn)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_DISCONNECTED),a(this,kc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=a(this,j).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(_.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,j).producers.values()).find(n=>n.id===r);i&&this.context.getValue("peerSessionStore").emit(_.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}handlePeerCapabilities(t,e){var r,i,n,o;for(let c=0;c<=Gt.length;c+=1){const d=Gt[c];if(((i=(r=e==null?void 0:e.receiver)==null?void 0:r.video)==null?void 0:i.codecs.findIndex(l=>l.mimeType===d))>=0||c===Gt.length-1){a(this,vn).get(d).add(t);break}}for(let c=0;c<=Gt.length;c+=1){const d=Gt[c];if(((o=(n=e==null?void 0:e.sender)==null?void 0:n.video)==null?void 0:o.codecs.findIndex(l=>l.mimeType===d))>=0||c===Gt.length-1){a(this,Sn).get(d).add(t);break}}}handlePeerLeaving(t){this.context.getValue("flagsmith").hasFeature(Z.FORCE_VIDEO_CODEC)||(a(this,Sn).forEach(e=>e.delete(t)),a(this,vn).forEach((e,r)=>{e.delete(t),!(e.size!==0||r===Gt[0])&&this.disableWebcam(r)}))}}Rc=new WeakMap,Cc=new WeakMap,vt=new WeakMap,j=new WeakMap,Ka=new WeakMap,kt=new WeakMap,gn=new WeakMap,mn=new WeakMap,fn=new WeakMap,kc=new WeakMap,gs=new WeakMap,Mr=new WeakMap,Sn=new WeakMap,vn=new WeakMap,It=new WeakMap,xt=new WeakMap,hi=new WeakSet,Qa=function(){return this.context.getValue("connectionHandler")},ru=new WeakSet,Cv=async function(t,e,r,i){f(this,Cc,t);try{return a(this,gs)?await a(this,gs):await x(this,Ic,mp).call(this,t,e,r,i),x(this,nu,Iv).call(this,e),{roomJoined:await x(this,iu,kv).call(this)}}catch(n){return this.logger.error("Failed to complete room join",{error:n}),{roomJoined:!1,error:n}}finally{f(this,gs,null)}},iu=new WeakSet,kv=async function(){try{this.mediaJoined=!0;const{roomState:t}=await a(this,j).socketHandler.notifySelfJoinComplete();return f(this,Rc,t.roomUuid),f(this,mn,!0),f(this,gn,!1),!0}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,!1}},nu=new WeakSet,Iv=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...we.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)},Ic=new WeakSet,mp=async function(t,e,r,i){try{const n=x(this,au,Av).call(this);await x(this,ou,Mv).call(this,t,e,r,n),await a(this,j).setupTransports({send:!0,recv:!0}),await x(this,cu,Ov).call(this,i)}catch(n){throw this.logger.error("Failed to initialize connection",{error:n}),n}},au=new WeakSet,Av=function(){var r;const t=(r=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:r.toString(),e=WD(t);return f(this,Ka,e),e},ou=new WeakSet,Mv=async function(t,e,r,i){await eS(async(n,o)=>{if(!a(this,vt).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,j).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})},cu=new WeakSet,Ov=async function(t){if(!(!this.context.getValue("flagsmith").hasFeature(Z.PRECREATE_PRODUCERS)||!t))try{const r=[];if(t.canProduceVideo===H.Allowed&&r.push(this.shareWebcam(f1(!1))),t.canProduceAudio===H.Allowed){const i=m1(!1);i&&r.push(this.shareMic(i))}r.length>0&&await Promise.all(r)}catch(r){this.logger.warn("Failed to precreate producers",{error:r})}},ct=new WeakSet,Mt=function(t){return a(this,It).get(t)},Tn=new WeakSet,sd=function(t,e){return a(this,It).set(t,e)},du=new WeakSet,Dv=function(t){return a(this,It).delete(t)},lu=new WeakSet,Nv=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},uu=new WeakSet,Vv=function(t,e){return{track:t,codecOptions:e?e.map(r=>({name:r.split("/")[1]})):[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},ce([E.trace("MediaNodeClient.reset")],ie.prototype,"reset",1),ce([E.trace("MediaNodeClient.joinRoom")],ie.prototype,"joinRoom",1),ce([E.trace("MediaNodeClient.leaveRoom")],ie.prototype,"leaveRoom",1),ce([E.trace("MediaNodeClient.activatePeers")],ie.prototype,"activatePeers",1),ce([E.trace("MediaNodeClient.createConsumers")],ie.prototype,"createConsumers",1),ce([E.trace("MediaNodeClient.closeConsumers")],ie.prototype,"closeConsumers",1),ce([E.trace("MediaNodeClient._shareWebcam")],ie.prototype,"_shareWebcam",1),ce([E.trace("MediaNodeClient.shareWebcam")],ie.prototype,"shareWebcam",1),ce([E.trace("MediaNodeClient.shareScreen")],ie.prototype,"shareScreen",1),ce([E.trace("MediaNodeClient.shareMic")],ie.prototype,"shareMic",1),ce([E.trace("MediaNodeClient.pauseMic")],ie.prototype,"pauseMic",1),ce([E.trace("MediaNodeClient.pauseWebcam")],ie.prototype,"pauseWebcam",1),ce([E.trace("MediaNodeClient.resumeMic")],ie.prototype,"resumeMic",1),ce([E.trace("MediaNodeClient.resumeWebcam")],ie.prototype,"resumeWebcam",1),ce([E.trace("MediaNodeClient.disableWebcam")],ie.prototype,"disableWebcam",1),ce([E.trace("MediaNodeClient.disableMic")],ie.prototype,"disableMic",1),ce([E.trace("MediaNodeClient.disableScreenShare")],ie.prototype,"disableScreenShare",1),ce([E.trace("MediaNodeClient.muteSelf")],ie.prototype,"muteSelf",1),ce([E.trace("MediaNodeClient.resetVideoProducers")],ie.prototype,"resetVideoProducers",1),ce([E.trace("MediaNodeClient.changeDisplayName")],ie.prototype,"changeDisplayName",1),ce([E.trace("MediaNodeClient.kickPeer")],ie.prototype,"kick",1),ce([E.trace("MediaNodeClient.kickAllPeers")],ie.prototype,"kickAll",1),ce([E.trace("MediaNodeClient.muteAll")],ie.prototype,"muteAll",1),ce([E.trace("MediaNodeClient.muteAllVideo")],ie.prototype,"muteAllVideo",1),ce([E.trace("MediaNodeClient.disableAudio")],ie.prototype,"disableAudio",1),ce([E.trace("MediaNodeClient.disableVideo")],ie.prototype,"disableVideo",1),ce([E.trace("MediaNodeClient.pinPeer")],ie.prototype,"pinPeer",1),ce([E.trace("MediaNodeClient.validateScreenShare")],ie.prototype,"validateScreenShare",1);function oS(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 ie(s,t);return s.setValue("roomNodeClient",r),r}function cS(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 T1=Object.defineProperty,y1=Object.getOwnPropertyDescriptor,Ni=(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&&T1(t,e,i),i};const dS=(YS=class{constructor(s,t,e,r){m(this,At);p(this,"self");p(this,"authToken");m(this,yn,void 0);p(this,"viewType");m(this,Ds,void 0);m(this,X,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,X,s),this.viewType=r,this.authToken=n,f(this,yn,i),f(this,Ds,e),this.setupEvents()}get peerId(){return a(this,X).getValue("peerId")}get telemetry(){return a(this,X).getValue("telemetry")}get logger(){return a(this,X).getValue("logger")}get mediaJoined(){return a(this,X).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=yt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await Ze.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");if(navigator.product!=="ReactNative"){const u=!s.getValue("flagsmith").hasFeature(Z.PRECALL_BANDWIDTH_TEST);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(g=>g.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",h==null?void 0:h.filter(g=>g.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",h==null?void 0:h.filter(g=>g.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:we.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:j_(s),skipConnectivityChecks:u,authToken:s.getValue("authToken")}),l.info("Callstats:: initialized")}catch(g){l.error("Callstats:: initialization failed",{error:g})}},0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new dS(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===H.Allowed&&r)try{await a(this,At,es).shareMic(s),this.self.audioEnabled||a(this,At,es).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===H.Allowed&&i)try{const d=await a(this,At,es).shareWebcam(t);d&&d.id!==t.id&&a(this,X).getValue("flagsmith").hasFeature(Z.EXP_RESHARE)&&await a(this,At,es).shareWebcam(d),this.self.videoEnabled||a(this,At,es).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===H.Allowed&&n)try{await((c=a(this,At,es))==null?void 0:c.shareScreen({video:o.video,audio:o.audio}))}catch(d){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,X).getValue("callstats").callEnded(),a(this,At,es).reset(),s&&await this.joinRoom(s)}setupEvents(){a(this,X).getValue("peerSessionStore").on(_.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,X).getValue("peerSessionStore").on(_.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,X).getValue("peerSessionStore").on(_.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,X).getValue("peerSessionStore").on(_.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,X).getValue("peerSessionStore").on(_.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,X).getValue("peerSessionStore").on(_.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&a(this,X).getValue("flagsmith").hasFeature(Z.REFRESH_ID_ON_DISCONNECTION)&&(t=fi()),a(this,yn).updateURL(t),a(this,X).getValue("telemetry").resetPeerId(t),yt().setHeader("tracing-id",t),sr.remapContext(t,a(this,X)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,X).getValue("peerSessionStore").on(_.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Ds).on(U.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Ds).on(Hd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,X).getValue("peerSessionStore").emit(_.UPDATE_PERMISSIONS,t.patch)})}),a(this,Ds).on(U.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Ds).on(U.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Ds).on(U.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,X).getValue("peerSessionStore").onAsync(_.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,X).getValue("peerSessionStore").on(_.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,X).getValue("peerSessionStore").on(_.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,X).getValue("callstats").audioOff())}),a(this,X).getValue("peerSessionStore").on(_.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,X).getValue("callstats").videoOff())}),a(this,X).getValue("peerSessionStore").onAsync(_.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,X).getValue("peerSessionStore").on(_.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await a(this,Ds).joinRoom(this.self);a(this,Ds).socket.flush();const e=bh(t.stageType);if(a(this,X).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}await this.joinMediaRoom(s),a(this,X).notify("stageStatus")}catch(t){throw this.logger.error("Error in joinRoom",{error:t}),t}}async leaveRoom(s="left"){var t,e;if(this.logger.info(`Leaving room with state: ${s}`),(t=a(this,X).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),a(this,X).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,X).notify("stageStatus");try{(e=a(this,yn))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}cS(a(this,X)),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,c;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,X).getAllValues();try{if(e===tr.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}oS(a(this,X),{socket:a(this,yn),peerId:t})}const{canProduceAudio:d,canProduceVideo:l,canProduceScreenshare:u}=this.self.permissions,{roomJoined:h,error:g}=(o=await((n=a(this,At,es))==null?void 0:n.joinRoom(this.self.name,r,s,s,{canProduceAudio:d,canProduceVideo:l,canProduceScreenshare:u})))!=null?o:{};if(!h)throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:g}),g;i==="ON_STAGE"&&await this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(d){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:d}),new k(`${(c=d==null?void 0:d.message)!=null?c:"could not connect to media servers"}`,"0002")}}async leaveMediaRoom(s){const t=a(this,X).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===tr.Webinar)&&a(this,At,es)&&(a(this,At,es).mediaJoined&&s!=="disconnected"&&await a(this,At,es).leaveRoom(),!(s==="stageLeft"&&t===tr.Livestream)&&(a(this,At,es).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()}},yn=new WeakMap,Ds=new WeakMap,X=new WeakMap,At=new WeakSet,es=function(){return a(this,X).getValue("roomNodeClient")},YS);let jr=dS;Ni([E.trace("SelfController.resetSelf")],jr.prototype,"resetSelf",1),Ni([E.trace("SelfController.setupEvents")],jr.prototype,"setupEvents",1),Ni([E.trace("SelfController.joinRoom")],jr.prototype,"joinRoom",1),Ni([E.trace("SelfController.leaveRoom")],jr.prototype,"leaveRoom",1),Ni([E.trace("SelfController.joinMediaRoom")],jr.prototype,"joinMediaRoom",1),Ni([E.trace("SelfController.leaveMediaRoom")],jr.prototype,"leaveMediaRoom",1),Ni([E.trace("SelfController.init")],jr,"init",1);class E1{constructor(t){m(this,Ac,void 0);f(this,Ac,t)}on(t,e){let r;t===U.roomPeerCount?r=Xm.fromBinary.bind(Xm):r=ff.fromBinary.bind(ff),a(this,Ac).on(t,({payload:i})=>{if(t===U.roomPeerCount&&!i)return;const n=r(i);e(n)})}}Ac=new WeakMap;class b1{constructor(t,e){m(this,Mc,void 0);m(this,Oc,void 0);f(this,Mc,e),f(this,Oc,t)}get logger(){return a(this,Oc).getValue("logger")}on(t,e){let r,i;switch(t){case U.transcript:{r=ih.fromBinary.bind(ih),i=ih.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Mc).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)})}}Mc=new WeakMap,Oc=new WeakMap;var w1=Object.defineProperty,P1=Object.getOwnPropertyDescriptor,qh=(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&&w1(t,e,i),i};class ol{constructor(t,e){m(this,Or,void 0);m(this,za,void 0);f(this,Or,e),f(this,za,t)}get logger(){return a(this,za).getValue("logger")}get telemetry(){return a(this,za).getValue("telemetry")}getPolls(){return a(this,Or).sendMessagePromise(ar.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Or).sendMessage(ar.createPoll,vM.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Or).sendMessage(ar.votePoll,yM.toBinary(r))}on(t,e){let r,i;switch(t){case ar.updatePoll:case ar.createPoll:case ar.votePoll:{r=Sh.fromBinary.bind(Sh),i=Sh.create();break}}a(this,Or).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,Or).removeListeners(t)}}Or=new WeakMap,za=new WeakMap,qh([E.trace("PollSocketHandler.getPolls")],ol.prototype,"getPolls",1),qh([E.trace("PollSocketHandler.createPoll")],ol.prototype,"createPoll",1),qh([E.trace("PollSocketHandler.votePoll")],ol.prototype,"votePoll",1);var _1=Object.defineProperty,R1=Object.getOwnPropertyDescriptor,C1=(s,t,e,r)=>{for(var i=r>1?void 0:r?R1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&_1(t,e,i),i};class lS{constructor(t,e){p(this,"socket");m(this,Xt,void 0);f(this,Xt,t),this.socket=e,this.handleSocketEvents(),a(this,Xt).setValue("roomSocketHandler",this)}get telemetry(){return a(this,Xt).getValue("telemetry")}get logger(){return a(this,Xt).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,lI.toBinary(e));try{const{peer:n}=Nn.fromBinary((await r).payload);a(this,Xt).getValue("connectionHandler").socketJoined=!0,a(this,Xt).getValue("peerSessionStore").emit(_.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,Xt).getValue("peerSessionStore").emit(_.ROOM_STATE,d),a(this,Xt).getValue("peerSessionStore").emit(_.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),new k("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,n)}}async getAllAddedParticipants(){try{return KI.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,eI.toBinary(n));i=oh.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=oh.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=oh.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,tf.toBinary({peerId:t}));e=Nn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=ef.create();try{const e=await this.socket.sendMessagePromise(U.getRoomInfo);t=ef.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=cf.create();try{const e=await this.socket.sendMessagePromise(U.getRoomStageState);t=cf.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,mo.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,mo.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,mo.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(U.leaveRoom,hI.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(U.kick,af.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(U.kickAll,jm.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(U.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.acceptWaitingRoomRequests,eA.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.denyWaitingRoomRequests,sA.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Hd.updateUserPreset,MA.toBinary(r))}handleSocketEvents(){this.socket.on(U.broadcastMessage,({payload:t})=>{try{const e=mo.fromBinary(t);a(this,Xt).getValue("peerSessionStore").emit(_.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=mo.fromBinary(t);a(this,Xt).getValue("peerSessionStore").emit(_.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=Nn.fromBinary.bind(Nn),i=Nn.create();break}case U.getWaitingRoomRequests:{r=(n,o)=>n?of.fromBinary(n,o):{requests:[]},i=of.create();break}case U.recordingPaused:case U.recordingStarted:case U.recordingStopped:{r=yf.fromBinary.bind(yf);break}case Hd.updateUserPreset:{r=lf.fromBinary.bind(lf);break}case ys.peerJoinedBroadcast:case Fr.peerJoinedBroadcast:{r=Jm.fromBinary.bind(Jm);break}case ys.selfJoinComplete:case Fr.selfJoinComplete:{r=sh.fromBinary.bind(sh);break}case ys.globalPeerPinBroadcast:case Fr.globalPeerPinBroadcast:{r=Ym.fromBinary.bind(Ym);break}case ys.selectedPeer:case Fr.selectedPeer:{r=th.fromBinary.bind(th);break}case ys.selectedPeerDiff:case Fr.selectedPeerDiff:{r=Wm.fromBinary.bind(Wm);break}case ys.leaveRoom:case Fr.leaveRoom:{r=rh.fromBinary.bind(rh);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(Hd.getUserPresets,PA.toBinary(e)),i=kA.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}}}Xt=new WeakMap,C1([E.trace("RoomSocketHandler.joinRoom")],lS.prototype,"joinRoom",1);class k1{constructor(t){m(this,Ut,void 0);f(this,Ut,t)}async getStageRequests(){const{payload:t}=await a(this,Ut).sendMessagePromise(U.getStageRequests);return t?fh.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,Ut).sendMessage(U.requestStageAccess)}cancelRequestAccess(){a(this,Ut).sendMessage(U.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,Ut).sendMessage(U.grantStageAccess,cM.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,Ut).sendMessage(U.denyStageAccess,lM.toBinary(e))}joinStage(){return a(this,Ut).sendMessagePromise(U.joinStage,void 0,void 0,U.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,Ut).sendMessagePromise(U.leaveStage,vf.toBinary(e),void 0,U.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,Ut).sendMessagePromise(U.leaveStage,vf.toBinary(e))}on(t,e){let r;switch(t){case U.grantStageAccess:case U.denyStageAccess:{r=void 0;break}case U.getStagePeers:{r=Sf.fromBinary.bind(Sf);break}case U.getStageRequests:case U.requestStageAccess:case U.cancelStageRequest:{r=fh.fromBinary.bind(fh);break}case U.peerStageStatusUpdate:{r=Qm.fromBinary.bind(Qm);break}}a(this,Ut).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,Ut).sendMessagePromise(U.getPeerInfo,tf.toBinary({peerId:t}));return Nn.fromBinary(e.payload)}}Ut=new WeakMap;class I1{constructor(t,e){m(this,Ye,void 0);m(this,Dc,void 0);f(this,Ye,e),f(this,Dc,t)}get logger(){return a(this,Dc).getValue("logger")}addPlugin(t,e){a(this,Ye).sendMessage(G.addPlugin,_0.toBinary({pluginId:t,staggered:e}))}removePlugin(t){a(this,Ye).sendMessage(G.removePlugin,C0.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await a(this,Ye).sendMessagePromise(G.getPlugins);return t?Y0.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};a(this,Ye).sendMessage(G.customPluginEventToRoom,x0.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const n={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,Ye).sendMessage(G.customPluginEventToPeers,F0.toBinary(n),i)}enablePluginForRoom(t,e){a(this,Ye).sendMessage(G.enablePluginForRoom,I0.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){a(this,Ye).sendMessage(G.enablePluginForPeers,D0.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){a(this,Ye).sendMessage(G.disablePluginForRoom,M0.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){a(this,Ye).sendMessage(G.disablePluginForPeers,V0.toBinary({pluginId:t,peerIds:e}),r)}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,Ye).sendMessage(G.storeInsertKeys,hf.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,Ye).sendMessage(G.storeGetKeys,q0.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,Ye).sendMessage(G.storeDeleteKeys,G0.toBinary(n),i)}storeDelete(t,e,r){a(this,Ye).sendMessage(G.storeDelete,J0.toBinary({pluginId:t,storeName:e}),r)}getPluginDataOld(t,e){this.logger.info("getPluginDataOld",{plugin:{id:t,storeName:e}})}storePluginDataOld(t,e,r){const i={pluginId:t,storeName:e,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};a(this,Ye).sendMessage(G.storeInsertKeys,hf.toBinary(i))}on(t,e){let r;switch(t){case G.addPlugin:case G.enablePluginForPeers:case G.enablePluginForRoom:{r=mh.fromBinary.bind(mh);break}case G.removePlugin:case G.disablePluginForPeers:case G.disablePluginForRoom:{r=pf.fromBinary.bind(pf);break}case G.customPluginEventToPeers:case G.customPluginEventToRoom:{r=mf.fromBinary.bind(mf);break}case G.storeInsertKeys:case G.storeGetKeys:case G.storeDeleteKeys:case G.storeDelete:{r=gf.fromBinary.bind(gf);break}}a(this,Ye).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}Ye=new WeakMap,Dc=new WeakMap;var A1=Object.defineProperty,M1=(s,t,e)=>t in s?A1(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,O1=(s,t,e)=>(M1(s,typeof t!="symbol"?t+"":t,e),e),jh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},O=(s,t,e)=>(jh(s,t,"read from private field"),e?e.call(s):t.get(s)),ye=(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)},ne=(s,t,e,r)=>(jh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),Pe=(s,t,e)=>(jh(s,t,"access private method"),e),cl={},D1={get exports(){return cl},set exports(s){cl=s}},Hn=typeof Reflect=="object"?Reflect:null,uS=Hn&&typeof Hn.apply=="function"?Hn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},dl;Hn&&typeof Hn.ownKeys=="function"?dl=Hn.ownKeys:Object.getOwnPropertySymbols?dl=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:dl=function(s){return Object.getOwnPropertyNames(s)};function N1(s){console&&console.warn&&console.warn(s)}var hS=Number.isNaN||function(s){return s!==s};function de(){de.init.call(this)}D1.exports=de,cl.once=U1,de.EventEmitter=de,de.prototype._events=void 0,de.prototype._eventsCount=0,de.prototype._maxListeners=void 0;var pS=10;function ll(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(de,"defaultMaxListeners",{enumerable:!0,get:function(){return pS},set:function(s){if(typeof s!="number"||s<0||hS(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");pS=s}}),de.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},de.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||hS(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 gS(s){return s._maxListeners===void 0?de.defaultMaxListeners:s._maxListeners}de.prototype.getMaxListeners=function(){return gS(this)},de.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")uS(c,this,t);else for(var d=c.length,l=TS(c,d),e=0;e<d;++e)uS(l[e],this,t);return!0};function mS(s,t,e,r){var i,n,o;if(ll(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=gS(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,N1(c)}return s}de.prototype.addListener=function(s,t){return mS(this,s,t,!1)},de.prototype.on=de.prototype.addListener,de.prototype.prependListener=function(s,t){return mS(this,s,t,!0)};function V1(){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 fS(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=V1.bind(r);return i.listener=e,r.wrapFn=i,i}de.prototype.once=function(s,t){return ll(t),this.on(s,fS(this,s,t)),this},de.prototype.prependOnceListener=function(s,t){return ll(t),this.prependListener(s,fS(this,s,t)),this},de.prototype.removeListener=function(s,t){var e,r,i,n,o;if(ll(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():L1(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this},de.prototype.off=de.prototype.removeListener,de.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 SS(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?x1(i):TS(i,i.length)}de.prototype.listeners=function(s){return SS(this,s,!0)},de.prototype.rawListeners=function(s){return SS(this,s,!1)},de.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):vS.call(s,t)},de.prototype.listenerCount=vS;function vS(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}de.prototype.eventNames=function(){return this._eventsCount>0?dl(this._events):[]};function TS(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function L1(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function x1(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function U1(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))}yS(s,t,n,{once:!0}),t!=="error"&&F1(s,i,{once:!0})})}function F1(s,t,e){typeof s.on=="function"&&yS(s,"error",t,e)}function yS(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 $1 extends v{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const ES=new $1;class bS{static encode(t){return ES.toBinary(t)}static decode(t){return ES.fromBinary(new Uint8Array(t))}}function B1(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Gr;class H1{constructor(t={}){O1(this,"opts"),ye(this,Gr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ne(this,Gr,0)}async wait(){ne(this,Gr,O(this,Gr)+1);const t=B1(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**O(this,Gr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return O(this,Gr)}reset(){ne(this,Gr,0)}}Gr=new WeakMap;const Wr={debug:0,info:1,warn:2,error:3};var Vi,Li;class q1{constructor(t){ye(this,Vi,void 0),ye(this,Li,void 0),ne(this,Vi,console),ne(this,Li,t)}debug(...t){Wr[O(this,Li)]>Wr.debug||O(this,Vi).debug("[Sockrates]:",...t)}info(...t){Wr[O(this,Li)]>Wr.info||O(this,Vi).info("[Sockrates]:",...t)}warn(...t){Wr[O(this,Li)]>Wr.warn||O(this,Vi).warn("[Sockrates]:",...t)}error(...t){Wr[O(this,Li)]>Wr.error||O(this,Vi).error("[Sockrates]:",...t)}}Vi=new WeakMap,Li=new WeakMap;var wS=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(wS||{});const j1="2",G1="3";var De,qn,_e,Ue,Jr,et,ur,Kr,Ps,jn,hr,Gh,PS,Co,ul,Wh,_S,Jh,RS,hl,Kh,zh,CS,ko,pl,Io,gl,ml,Yh,Gn,Ao,Mo,fl;class W1{constructor(t,e){var g,S,y,w,b,C,D,F,L,B;ye(this,Gh),ye(this,Co),ye(this,Wh),ye(this,Jh),ye(this,hl),ye(this,zh),ye(this,ko),ye(this,Io),ye(this,ml),ye(this,Gn),ye(this,Mo),ye(this,De,void 0),ye(this,qn,void 0),ye(this,_e,void 0),ye(this,Ue,void 0),ye(this,Jr,void 0),ye(this,et,void 0),ye(this,ur,void 0),ye(this,Kr,void 0),ye(this,Ps,void 0),ye(this,jn,void 0),ye(this,hr,void 0);var r,i,n,o,c,d,l,u,h;ne(this,qn,t),ne(this,Jr,[]),ne(this,et,new cl),ne(this,ur,!0),ne(this,Ps,!1),ne(this,_e,e!=null?e:{}),(g=(r=O(this,_e)).autoReconnect)!=null||(r.autoReconnect=!0),(S=(i=O(this,_e)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(y=(n=O(this,_e)).pingTimeout)!=null||(n.pingTimeout=3e4),(w=(o=O(this,_e)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(b=(c=O(this,_e)).debug)!=null||(c.debug=!0),(C=(d=O(this,_e)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(D=(l=O(this,_e)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(F=(u=O(this,_e)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(L=(h=O(this,_e)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),ne(this,Kr,{code:void 0,reason:void 0}),ne(this,Ue,(B=O(this,_e).logger)!=null?B:new q1(O(this,_e).debug?"debug":"info")),ne(this,hr,new H1)}get readyState(){var t;return(t=O(this,De))==null?void 0:t.readyState}get url(){return O(this,qn)}updateURL(t){ne(this,qn,t),Pe(this,zh,CS).call(this)}get config(){return O(this,_e)}get sendQueue(){return O(this,Jr)}flush(){if(!O(this,_e).queueOnDisconnect)return!1;const t=[];return O(this,Jr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ne(this,Jr,t),O(this,Jr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){O(this,Ue).debug("Websocket was already connecting or connected.");return}if(O(this,ur)!==!1)return new Promise((e,r)=>{Pe(this,Gn,Ao).call(this),Pe(this,Mo,fl).call(this);try{ne(this,De,new WebSocket(Pe(this,Gh,PS).call(this,O(this,qn)))),O(this,De).binaryType="arraybuffer",O(this,Ue).debug("Connecting");const i=setTimeout(()=>{O(this,Ue).debug("Connection timeout. Closing socket"),ne(this,ur,!0),Pe(this,Mo,fl).call(this),O(this,De).close(3001,"Connection Timeout"),O(this,_e).autoReconnect&&!O(this,Ps)&&(O(this,et).emit("reconnecting"),Pe(this,ko,pl).call(this)),r(new Error("Connection timed out!"))},O(this,_e).connectionTimeout);O(this,De).onopen=()=>{O(this,Ue).debug(`Ready State: ${wS[O(this,De).readyState]}`),i&&clearTimeout(i),Pe(this,ml,Yh).call(this),ne(this,Kr,{code:void 0,reason:void 0}),O(this,et).emit("connected"),O(this,_e).flushOnReconnect&&this.flush(),e()},O(this,De).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),O(this,Ue).debug("Socket closed. Close event:",{event:n}),O(this,Ue).debug(`Connection closed code: ${o}`),O(this,Ue).debug(`Connection closed reason: ${c}`),O(this,Ps)||Pe(this,hl,Kh).call(this,o,c)}catch(o){Pe(this,Co,ul).call(this,o)}},O(this,De).onerror=n=>{Pe(this,Co,ul).call(this,n)},O(this,De).onmessage=n=>Pe(this,Wh,_S).call(this,n)}catch(i){Pe(this,Co,ul).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(O(this,_e).queueOnDisconnect&&(!O(this,De)||O(this,De).readyState!==1))return O(this,Ue).debug("Queuing message since socket is not connected!",n),O(this,Jr).push(n),!1;const o=bS.encode(n);return Pe(this,Io,gl).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return Pe(this,Io,gl).call(this,t)}receive(t,e){return O(this,et).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")){O(this,et).on(t,e);return}this.receive(t,e)}removeAllListeners(){O(this,et).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){O(this,et).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){O(this,et).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ne(this,ur,!1),Pe(this,Gn,Ao).call(this),this.removeAllListeners(),ne(this,Kr,{code:1e3,reason:"Sockrates disconnect method called"}),O(this,De).close(1e3,"Sockrates disconnect method called.")}}De=new WeakMap,qn=new WeakMap,_e=new WeakMap,Ue=new WeakMap,Jr=new WeakMap,et=new WeakMap,ur=new WeakMap,Kr=new WeakMap,Ps=new WeakMap,jn=new WeakMap,hr=new WeakMap,Gh=new WeakSet,PS=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)://.")},Co=new WeakSet,ul=function(s,t){O(this,Ue).error("Error:",{error:s}),O(this,et).emit("errored",{error:s}),t==null||t(s)},Wh=new WeakSet,_S=function(s){if(Pe(this,ml,Yh).call(this),s.data===j1){O(this,Ue).debug("Received ping from server"),Pe(this,Io,gl).call(this,G1);return}const t=bS.decode(s.data),{id:e,payload:r}=t;O(this,Ue).debug("Received message",{event:t.event,messageID:e}),O(this,et).emit(t.event.toString(),{id:e,payload:r})},Jh=new WeakSet,RS=function(){return O(this,De).readyState===1},hl=new WeakSet,Kh=function(s,t){ne(this,Kr,{reason:t,code:s}),O(this,et).emit("disconnected",{code:s,reason:t})},zh=new WeakSet,CS=function(){const{reason:s,code:t}=O(this,Kr);t&&t!==1e3&&O(this,ur)&&O(this,_e).autoReconnect&&!O(this,Ps)&&(O(this,Ue).debug(`Triggering reconnection due to ${s}.`),O(this,et).emit("reconnecting"),Pe(this,ko,pl).call(this))},ko=new WeakSet,pl=async function(s=!0){if(s&&O(this,Ps)){O(this,Ue).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(O(this,Ps)||O(this,hr).reset(),O(this,_e).maxReconnectionAttempts!==null&&O(this,hr).getAttempts()>=O(this,_e).maxReconnectionAttempts){O(this,et).emit("failed"),ne(this,Ps,!1);return}ne(this,Ps,!0),Pe(this,Mo,fl).call(this),Pe(this,Gn,Ao).call(this);try{if(await O(this,hr).wait(),O(this,ur)===!1)return;if(O(this,Ue).debug(`Reconnection attempt ${O(this,hr).getAttempts()}`),O(this,et).emit("reconnectAttempt",{attempt:O(this,hr).getAttempts()}),await this.connect(),!Pe(this,Jh,RS).call(this))throw Error("Reconnect Failed");ne(this,Ps,!1),ne(this,Kr,{code:void 0,reason:void 0}),O(this,et).emit("reconnected")}catch(t){O(this,Ue).debug("Failed to reconnect."),O(this,et).emit("reconnectFailure",{attempt:O(this,hr).getAttempts()}),Pe(this,ko,pl).call(this,!1)}},Io=new WeakSet,gl=function(s){try{return O(this,De).send(s),!0}catch(t){return O(this,Ue).error(t.message),!1}},ml=new WeakSet,Yh=function(){this.config.disconnectOnPingTimeout&&(O(this,Ue).debug("Resetting ping timeout"),Pe(this,Gn,Ao).call(this),ne(this,jn,setTimeout(()=>{var s;O(this,Ue).debug("Disconnecting the socket due to ping timeout"),ne(this,ur,!0);const t=3002,e="Ping timeout";(s=O(this,De))==null||s.close(t,e),Pe(this,hl,Kh).call(this,t,e)},O(this,_e).pingTimeout)))},Gn=new WeakSet,Ao=function(){O(this,jn)&&(clearTimeout(O(this,jn)),ne(this,jn,void 0))},Mo=new WeakSet,fl=function(){O(this,De)&&(O(this,De).onopen=void 0,O(this,De).onerror=void 0,O(this,De).onmessage=void 0,O(this,De).onclose=void 0)};var J1=Object.defineProperty,K1=Object.getOwnPropertyDescriptor,Sl=(s,t,e,r)=>{for(var i=r>1?void 0:r?K1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&J1(t,e,i),i};const kS=65535,z1=3e3,IS=(QS=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,Me);m(this,Nc);m(this,Vc);m(this,pi,void 0);m(this,Ae,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");m(this,ms,void 0);m(this,it,void 0);var n;if(!t||!e||!r)throw new k("peerId, meetingId, or authToken can not be empty","0404");f(this,ms,void 0),f(this,it,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,pi,x(this,Nc,fp).call(this,t)),f(this,Ae,new W1(a(this,pi),{autoReconnect:!0,disconnectOnPingTimeout:(n=i.includes("PING"))!=null?n:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Me,je).socketJoinAttempted}set joinAttempted(s){a(this,Me,je).socketJoinAttempted=s}get telemetry(){return a(this,it).getValue("telemetry")}get logger(){return a(this,it).getValue("logger")}get peerId(){return a(this,it).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,pi,x(this,Nc,fp).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Ae).updateURL(a(this,pi))}static getSocketEdgeDomain(s){return bi({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,pi)}async connect(){a(this,Me,je).socketJoinAttempted=!0,await a(this,Ae).connect(),a(this,Me,je).socketJoinAttempted=!0,a(this,Me,je).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){a(this,Me,je).socketJoinAttempted=!1,a(this,Ae).disconnect(),a(this,Me,je).socketJoinAttempted=!0,a(this,Me,je).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Ae).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,it).getValue("telemetry").injectContext(r),a(this,Ae).send(s,e!=null?e:x(this,Vc,Sp).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,Ae).removeListener(n,y),a(this,Ae).removeListener(kS,w),a(this,Ae).removeListener(Fr.errorResponse,w),a(this,Ae).removeListener(ys.errorResponse,w)},l=r!=null?r:x(this,Vc,Sp).call(this),u={};a(this,it).getValue("telemetry").injectContext(u);const g=({id:y,payload:w})=>{if(l===y){let b;try{const C=WC.fromBinary(w);b=new Error(C.errorMessage)}catch(C){b=new Error("failed to parse error message",{cause:C});try{const D=Jk.fromBinary(w);b=new Error(D.message)}catch(D){b=new Error("failed to parse error message",{cause:D})}}c(b),d(S,g)}},S=({id:y,payload:w})=>{l===y&&(o({id:y,payload:w}),d(S,g))};a(this,Ae).on(n,S),a(this,Ae).on(kS,g),a(this,Ae).on(Fr.errorResponse,g),a(this,Ae).on(ys.errorResponse,g),setTimeout(()=>{d(S,g),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Ae).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){a(this,Ae).on(s,t)}onStateEvent(s,t){a(this,Ae).on(s,t)}removeListener(s,t){a(this,Ae).removeListener(s,t)}removeListeners(s){a(this,Ae).removeListeners(s)}flush(){return a(this,Ae).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),a(this,ms)&&(clearTimeout(a(this,ms)),f(this,ms,void 0)),a(this,Me,je).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,Me,je).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Bn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Bn.CONNECTED?a(this,it).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Me,je).joinAttempted}):f(this,ms,setTimeout(()=>{a(this,it).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Me,je).joinAttempted}),f(this,ms,void 0)},z1)),a(this,Me,je).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge"),a(this,Me,je).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,Me,je).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,Me,je).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Me,je).mediaJoinAttempted}}),a(this,ms)&&(clearTimeout(a(this,ms)),f(this,ms,void 0)),a(this,it).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Me,je).mediaJoinAttempted}),a(this,Me,je).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge"),a(this,it).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_FAILED),a(this,Me,je).updateSocketConnectionState("failed")})}},pi=new WeakMap,Ae=new WeakMap,Me=new WeakSet,je=function(){return a(this,it).getValue("connectionHandler")},ms=new WeakMap,it=new WeakMap,Nc=new WeakSet,fp=function(s){const t=a(this,it).getValue("socketBaseURI")||a(this,it).getValue("baseURI");let e=IS.getSocketEdgeDomain(t);typeof On(a(this,it),"socket_server_base")=="string"&&(e=On(a(this,it),"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=>xd[c]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(o).forEach(([c,d])=>{i.searchParams.append(c,d.toString())}),i.href},Vc=new WeakSet,Sp=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},QS);let Oo=IS;Sl([E.trace("SocketService.connect")],Oo.prototype,"connect",1),Sl([E.trace("SocketService.disconnect")],Oo.prototype,"disconnect",1),Sl([E.trace("SocketService.sendMessagePromise")],Oo.prototype,"sendMessagePromise",1),Sl([E.trace("SocketService.sendMessagePromiseWithTimeout")],Oo.prototype,"sendMessagePromiseWithTimeout",1);class Y1{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=yI.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=WI.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=nf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return rf.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return LI.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(U.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(U.createConnectedRooms,PI.toBinary({payloads:t}));return rf.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,NI.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(U.movePeers,HI.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 Q1=Object.defineProperty,X1=Object.getOwnPropertyDescriptor,Z1=(s,t,e,r)=>{for(var i=r>1?void 0:r?X1(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};class AS extends $t{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);m(this,Ns,void 0);f(this,Ns,e)}get supportsConnectedMeetings(){return a(this,Ns).getValue("self").id!==""}get isActive(){return this.meetings.length!==0}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
18
+ maxEnergy: ${a(this,ui)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,kr)||i<a(this,kr))&&f(this,kr,i),(!a(this,ui)||i>a(this,ui))&&f(this,ui,i),{energy:(i-a(this,kr))/(a(this,ui)-a(this,kr))*10||0,isVoice:r})},Pc=new WeakSet,gp=function(t){return t<5},tu=new WeakSet,_v=function(t=a(this,pn)){var r;if(!a(this,Os)||!t){a(this,Ir).getValue("flagsmith").hasFeature(Z.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,Os)}`);return}const e={producerId:a(this,Os),energy:Math.round(t),silent:x(r=_c,Pc,gp).call(r,t)};f(this,Ja,e.silent),this.reportRequest(e)},su=new WeakSet,Rv=function(t){const e=Math.log10(t);return Math.round(e)},m(Ro,Pc),m(Ro,su);const m1=(s=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const e=new window.MediaStreamTrackGenerator({kind:"audio"}),r=e.writable.getWriter(),i=48e3,n=128,o=1;let c=0,d=null;const l=async()=>{try{const g=new Float32Array(n*o),S=new window.AudioData({format:"f32",sampleRate:i,numberOfFrames:n,numberOfChannels:o,timestamp:c,data:g});c+=n/i*1e6,await r.ready,await r.write(S)}catch(g){d&&clearInterval(d),r.releaseLock(),e.writable.abort()}};d=window.setInterval(l,100);const h=new MediaStream([e]).getAudioTracks()[0];return h.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),e.writable.abort()}),Object.assign(h,{fakeTracks:"fakeTracks:fakeAudioTrack"}),h.enabled=s,h}catch(e){}const t=window.AudioContext||window.webkitAudioContext;if(t)try{const e=new t;if(!e||e.state!=="running"||!e.destination)return;const r=e.createOscillator();r.frequency.value=0,r.type="sine";const i=e.createGain();i.gain.value=0,r.connect(i);const n=e.createMediaStreamDestination();i.connect(n),r.start();const o=n.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=s,o):void 0}catch(e){return}},f1=(s=!1)=>{var n,o;const t=new MediaStream().getVideoTracks()[0],e=document.createElement("canvas");e.height=(n=t==null?void 0:t.getSettings().height)!=null?n:720,e.width=(o=t==null?void 0:t.getSettings().width)!=null?o:1280;const r=e.getContext("2d");r.fillStyle="black",r.fillRect(0,0,e.width,e.height),setInterval(()=>{r.fillStyle="black",r.fillRect(0,0,e.width,e.height)},1e3);const i=e.captureStream().getVideoTracks()[0];return Object.assign(i,{fakeTracks:"fakeTracks:fakeVideoTrack"}),i.enabled=s,i};var S1=Object.defineProperty,v1=Object.getOwnPropertyDescriptor,ce=(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&&S1(t,e,i),i};const Gt=["video/VP9","video/VP8"];class ie{constructor(t,e){m(this,hi);m(this,ru);m(this,iu);m(this,nu);m(this,Ic);m(this,au);m(this,ou);m(this,cu);m(this,ct);m(this,Tn);m(this,du);m(this,lu);m(this,uu);p(this,"context");p(this,"authToken");p(this,"e2ee");m(this,Rc,void 0);m(this,Cc,void 0);m(this,vt,void 0);m(this,j,void 0);m(this,Ka,void 0);m(this,kt,void 0);m(this,gn,void 0);m(this,mn,void 0);m(this,fn,void 0);m(this,kc,void 0);m(this,gs,null);m(this,Mr,void 0);m(this,Sn,void 0);m(this,vn,void 0);m(this,It,void 0);m(this,xt,void 0);var i,n;this.context=t;const{socket:r}=e;this.mediaJoined=!1,f(this,Sn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,vn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,vt,r),f(this,gn,!1),f(this,j,new u1(t,r)),f(this,kt,a(this,j).events),f(this,Mr,new Set),f(this,It,new Map),f(this,mn,!1),f(this,fn,new Vh(t.getValue("logger"))),f(this,xt,new Ro(this.context,a(this,j).socketHandler.audioActivity.bind(a(this,j).socketHandler))),this.e2ee=(n=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,kc,ju(async()=>{if(!a(this,hi,Qa).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(a(this,Cc),a(this,Rc),!0,!0);o&&(this.context.getValue("peerSessionStore").emit(_.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(_.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,hi,Qa).mediaJoined}set mediaJoined(t){a(this,hi,Qa).mediaJoined=t}reset(){a(this,j).closeAllProducers(),a(this,j).closeAllConsumers(),a(this,It).clear(),a(this,Mr).clear(),f(this,gs,null),a(this,fn).stop(),a(this,j).stopAllTransports(),a(this,j).reset(),f(this,fn,new Vh)}async joinRoom(t,e,r=!1,i=!1,n={}){a(this,hi,Qa).mediaJoinAttempted=!0,f(this,gn,!0),r&&this.reset();try{return await a(this,fn).push(()=>x(this,ru,Cv).call(this,t,e,i,n),"joinRoom")}catch(o){return this.logger.error("Error in room joining process",{error:o}),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_FAILED),{roomJoined:!1,error:o}}}async initializeConnection(t,e,r=!1,i={}){return a(this,gs)?a(this,gs):(f(this,gs,(async()=>{try{await x(this,Ic,mp).call(this,t,e,r,i)}catch(n){throw f(this,gs,null),n}})()),a(this,gs))}getConsumers(){return a(this,j).consumers}getProducers(){return a(this,j).producers}async leaveRoom(){a(this,j).stopAllTransports(),f(this,mn,!1),a(this,hi,Qa).mediaJoinAttempted=!1;const t={closeRoom:!1};a(this,vt).sendMessagePromise(a(this,kt).leaveRoom,gC.toBinary(t)).then(r=>{var i;(i=sk.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()}async activatePeers(t){return this.createConsumers(t)}async createConsumers(t){return t.length===0?Promise.resolve():a(this,j).createConsumers(t)}async closeConsumers(t){if(!t.length)return;const e=t.reduce((r,i)=>{const n=a(this,j).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,j).closeConsumers(e)}async _shareWebcam(t,e){var g,S,y,w;const r=e==="video/VP9"?me.WEBCAM:me.WEBCAM_BACKUP,i=x(this,ct,Mt).call(this,r);if(i){const b=await i;if(a(this,j).producers.has(b)){const C=a(this,j).producers.get(b);if(!C.closed)return await C.replaceTrack({track:t}),await this.resumeWebcam(r),t;await this.disableWebcam(e)}return this._shareWebcam(t,e)}const n=[e].concat(Gt.filter(b=>b!==e)),o=x(this,uu,Vv).call(this,t,n),c=On(this.context,"disableSimulcast"),d=(S=(g=this.context)==null?void 0:g.getValue("overrides"))==null?void 0:S.simulcastConfig;c||d&&d.disable||!((w=(y=this.context)==null?void 0:y.getValue("theme"))!=null&&w.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),o.encodings=YO(this.context,t),this.logger.info(`Simulcast encodings: ${JSON.stringify(o.encodings)}`)),this.context.getValue("flagsmith").hasFeature(Z.TRACK_HINT)&&(o.track.contentHint=this.context.getValue("flagsmith").getValue(Z.TRACK_HINT));const u=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,It).delete(r)},h=a(this,j).createProducer(o,u);return x(this,Tn,sd).call(this,r,h.then(b=>b.id)),h.then(b=>b.track)}async shareWebcam(t){var i;if(t===void 0)return null;const e=(i=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:i.toString();if(e)return this.logger.debug(`Calling _shareWebcam with forced video codec: ${e}`),this._shareWebcam(t,e);const r=Gt.filter(n=>{var o,c;return((c=(o=a(this,Ka).sender)==null?void 0:o.video)==null?void 0:c.codecs.findIndex(d=>d.mimeType===n))>=0&&a(this,vn).get(n).size>0});return r.length===0&&r.push(Gt[0]),await Promise.all(r.map(n=>(this.logger.debug(`Calling _shareWebcam with video codec: ${n}`),this._shareWebcam(t,n)))),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:we.isElectron()},stopTracks:!1},n=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,It).delete(me.SCREENSHARE_VIDEO),a(this,It).delete(me.SCREENSHARE_AUDIO)},o=a(this,j).createProducer(i,n);x(this,Tn,sd).call(this,me.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:we.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},l=()=>{};c=a(this,j).createProducer(d,l),x(this,Tn,sd).call(this,me.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 Nt("track undefined");const e=x(this,ct,Mt).call(this,me.MIC);if(e){const o=await e;if(a(this,j).producers.has(o)){const c=a(this,j).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),a(this,xt)&&(a(this,xt).audioTrack=t,a(this,xt).producerId=o,a(this,xt).start());return}await a(this,j).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=x(this,lu,Nv).call(this,t),i=()=>{a(this,It).delete(me.MIC)},n=a(this,j).createProducer(r,i);x(this,Tn,sd).call(this,me.MIC,n.then(o=>o.id)),await n.then(o=>{a(this,xt)&&(a(this,xt).audioTrack=o.track,a(this,xt).producerId=o.id,a(this,xt).start())})}catch(e){throw new k(e)}}async pauseMic(){var i;const t=await x(this,ct,Mt).call(this,me.MIC),e=a(this,j).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,xt))==null||i.stop();const r={producerId:e.id,pause:!0};a(this,vt).sendMessage(a(this,kt).toggleProducer,Ld.toBinary(r))}async pauseWebcam(){const t=await x(this,ct,Mt).call(this,me.WEBCAM),e=await x(this,ct,Mt).call(this,me.WEBCAM_BACKUP),r=a(this,j).producers.get(t),i=a(this,j).producers.get(e);if(!r&&!i){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const n=o=>{const c={producerId:o.id,pause:!0};a(this,vt).sendMessage(a(this,kt).toggleProducer,Ld.toBinary(c))};r&&(r.pause(),n(r)),i&&(i.pause(),n(i))}async resumeMic(){const t=await x(this,ct,Mt).call(this,me.MIC),e=a(this,j).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(_.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,vt).sendMessage(a(this,kt).toggleProducer,Ld.toBinary(r))}async resumeWebcam(t=me.WEBCAM){const e=await x(this,ct,Mt).call(this,t),r=a(this,j).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(_.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};a(this,vt).sendMessage(a(this,kt).toggleProducer,Ld.toBinary(i))}async disableWebcam(t){const e=t==="video/VP9"?me.WEBCAM:me.WEBCAM_BACKUP,r=await x(this,ct,Mt).call(this,e);x(this,du,Dv).call(this,e),r&&await a(this,j).closeProducer(r)}async disableMic(){var e;const t=await x(this,ct,Mt).call(this,me.MIC);t&&await a(this,j).closeProducer(t),(e=a(this,xt))==null||e.stop(),a(this,It).delete(me.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await x(this,ct,Mt).call(this,me.SCREENSHARE_VIDEO),e=await x(this,ct,Mt).call(this,me.SCREENSHARE_AUDIO);t&&await a(this,j).closeProducer(t),e&&await a(this,j).closeProducer(e),a(this,Mr).clear(),a(this,It).delete(me.SCREENSHARE_VIDEO),a(this,It).delete(me.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await x(this,ct,Mt).call(this,me.WEBCAM),i=await x(this,ct,Mt).call(this,me.WEBCAM_BACKUP);await a(this,j).closeProducer(r,{stopTrack:!1}),await a(this,j).closeProducer(i,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await x(this,ct,Mt).call(this,me.SCREENSHARE_VIDEO);await a(this,j).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,j).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};a(this,j).socketHandler.kickPeer(e)}kickAll(){a(this,j).socketHandler.kickAll()}async muteAll(t){if(!await a(this,j).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,j).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await a(this,j).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await a(this,j).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,vt).sendMessagePromise(a(this,kt).globalPinPeer,kC.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&a(this,j).producers.get(t.producerId)&&a(this,Mr).add(t.consumerPeerId),a(this,Mr).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));a(this,j).switchConsumersToLayer(r,e)}async handleSocketEvents(){a(this,vt).on(a(this,kt).peerProducerCreateBroadcast,({payload:t})=>{var e,r;if(this.mediaJoined)try{const{participantId:i,producerState:n}=Ok.fromBinary(t);if(i===this.peerId)return;if(n!=null&&n.mimeType||(n.mimeType=n.kind===Bs.AUDIO?"audio/opus":"video/VP8"),n.kind===Bs.VIDEO&&!n.screenShare&&((r=(e=a(this,Ka).receiver)==null?void 0:e.video)==null?void 0:r.codecs.findIndex(o=>o.mimeType===Gt[0]))>=0&&a(this,Sn).get(Gt[0]).has(i)&&n.mimeType!==Gt[0]){this.logger.warn(`Ignoring producer: ${n.producerId}`);return}this.logger.info(`producer created broadcast: ${i}, producer state: ${n}`),this.context.getValue("peerSessionStore").emit(_.NEW_PRODUCER,{peerId:i,producer:{...n,kind:n.kind===Bs.AUDIO?"audio":"video",producingPeerId:i}})}catch(i){this.logger.error("error in peer-producer-create-broadcast",{error:i})}}),a(this,vt).on(a(this,kt).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:i,pause:n,producerId:o,screenShare:c}}=zm.fromBinary(t);if(c)return;const d=i===Bs.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${o}, kind:${d}, paused:${n} payload: ${JSON.stringify(zm.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&n&&this.context.getValue("peerSessionStore").emit(d==="audio"?_.MUTE_SELF:_.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(_.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(_.CONSUMER_PAUSED,{id:u.id})):(u.resume(),this.context.getValue("peerSessionStore").emit(_.CONSUMER_RESUMED,{id:u.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,vt).on(a(this,kt).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=rh.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,Mr).delete(e),a(this,j).consumers.forEach(r=>{r.peerId===e&&r.close()}),this.context.getValue("peerSessionStore").emit(_.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),a(this,vt).on(a(this,kt).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=Vk.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(_.PRODUCER_CLOSED,{peerId:e,producerId:r});const i=a(this,j).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,j).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),a(this,j).producerIdToConsumerIdMap.delete(r),this.context.getValue("peerSessionStore").emit(_.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,vt).on(a(this,kt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,gn)&&!a(this,mn)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_DISCONNECTED),a(this,kc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=a(this,j).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(_.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,j).producers.values()).find(n=>n.id===r);i&&this.context.getValue("peerSessionStore").emit(_.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}handlePeerCapabilities(t,e){var r,i,n,o;for(let c=0;c<=Gt.length;c+=1){const d=Gt[c];if(((i=(r=e==null?void 0:e.receiver)==null?void 0:r.video)==null?void 0:i.codecs.findIndex(l=>l.mimeType===d))>=0||c===Gt.length-1){a(this,vn).get(d).add(t);break}}for(let c=0;c<=Gt.length;c+=1){const d=Gt[c];if(((o=(n=e==null?void 0:e.sender)==null?void 0:n.video)==null?void 0:o.codecs.findIndex(l=>l.mimeType===d))>=0||c===Gt.length-1){a(this,Sn).get(d).add(t);break}}}handlePeerLeaving(t){this.context.getValue("flagsmith").hasFeature(Z.FORCE_VIDEO_CODEC)||(a(this,Sn).forEach(e=>e.delete(t)),a(this,vn).forEach((e,r)=>{e.delete(t),!(e.size!==0||r===Gt[0])&&this.disableWebcam(r)}))}}Rc=new WeakMap,Cc=new WeakMap,vt=new WeakMap,j=new WeakMap,Ka=new WeakMap,kt=new WeakMap,gn=new WeakMap,mn=new WeakMap,fn=new WeakMap,kc=new WeakMap,gs=new WeakMap,Mr=new WeakMap,Sn=new WeakMap,vn=new WeakMap,It=new WeakMap,xt=new WeakMap,hi=new WeakSet,Qa=function(){return this.context.getValue("connectionHandler")},ru=new WeakSet,Cv=async function(t,e,r,i){f(this,Cc,t);try{a(this,gs)?await a(this,gs):await x(this,Ic,mp).call(this,t,e,r,i),x(this,nu,Iv).call(this,e);const{joined:n,error:o}=await x(this,iu,kv).call(this);return{roomJoined:n,error:o}}catch(n){return this.logger.error("Failed to complete room join",{error:n}),{roomJoined:!1,error:n}}finally{f(this,gs,null)}},iu=new WeakSet,kv=async function(){try{this.mediaJoined=!0;const{roomState:t}=await a(this,j).socketHandler.notifySelfJoinComplete();return f(this,Rc,t.roomUuid),f(this,mn,!0),f(this,gn,!1),{joined:!0}}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,{joined:!1,error:t}}},nu=new WeakSet,Iv=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...we.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)},Ic=new WeakSet,mp=async function(t,e,r,i){try{const n=x(this,au,Av).call(this);await x(this,ou,Mv).call(this,t,e,r,n),await a(this,j).setupTransports({send:!0,recv:!0}),await x(this,cu,Ov).call(this,i)}catch(n){throw this.logger.error("Failed to initialize connection",{error:n}),n}},au=new WeakSet,Av=function(){var r;const t=(r=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:r.toString(),e=WD(t);return f(this,Ka,e),e},ou=new WeakSet,Mv=async function(t,e,r,i){await eS(async(n,o)=>{if(!a(this,vt).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,j).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})},cu=new WeakSet,Ov=async function(t){if(!(!this.context.getValue("flagsmith").hasFeature(Z.PRECREATE_PRODUCERS)||!t))try{const r=[];if(t.canProduceVideo===H.Allowed&&r.push(this.shareWebcam(f1(!1))),t.canProduceAudio===H.Allowed){const i=m1(!1);i&&r.push(this.shareMic(i))}r.length>0&&await Promise.all(r)}catch(r){this.logger.warn("Failed to precreate producers",{error:r})}},ct=new WeakSet,Mt=function(t){return a(this,It).get(t)},Tn=new WeakSet,sd=function(t,e){return a(this,It).set(t,e)},du=new WeakSet,Dv=function(t){return a(this,It).delete(t)},lu=new WeakSet,Nv=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},uu=new WeakSet,Vv=function(t,e){return{track:t,codecOptions:e?e.map(r=>({name:r.split("/")[1]})):[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},ce([E.trace("MediaNodeClient.reset")],ie.prototype,"reset",1),ce([E.trace("MediaNodeClient.joinRoom")],ie.prototype,"joinRoom",1),ce([E.trace("MediaNodeClient.leaveRoom")],ie.prototype,"leaveRoom",1),ce([E.trace("MediaNodeClient.activatePeers")],ie.prototype,"activatePeers",1),ce([E.trace("MediaNodeClient.createConsumers")],ie.prototype,"createConsumers",1),ce([E.trace("MediaNodeClient.closeConsumers")],ie.prototype,"closeConsumers",1),ce([E.trace("MediaNodeClient._shareWebcam")],ie.prototype,"_shareWebcam",1),ce([E.trace("MediaNodeClient.shareWebcam")],ie.prototype,"shareWebcam",1),ce([E.trace("MediaNodeClient.shareScreen")],ie.prototype,"shareScreen",1),ce([E.trace("MediaNodeClient.shareMic")],ie.prototype,"shareMic",1),ce([E.trace("MediaNodeClient.pauseMic")],ie.prototype,"pauseMic",1),ce([E.trace("MediaNodeClient.pauseWebcam")],ie.prototype,"pauseWebcam",1),ce([E.trace("MediaNodeClient.resumeMic")],ie.prototype,"resumeMic",1),ce([E.trace("MediaNodeClient.resumeWebcam")],ie.prototype,"resumeWebcam",1),ce([E.trace("MediaNodeClient.disableWebcam")],ie.prototype,"disableWebcam",1),ce([E.trace("MediaNodeClient.disableMic")],ie.prototype,"disableMic",1),ce([E.trace("MediaNodeClient.disableScreenShare")],ie.prototype,"disableScreenShare",1),ce([E.trace("MediaNodeClient.muteSelf")],ie.prototype,"muteSelf",1),ce([E.trace("MediaNodeClient.resetVideoProducers")],ie.prototype,"resetVideoProducers",1),ce([E.trace("MediaNodeClient.changeDisplayName")],ie.prototype,"changeDisplayName",1),ce([E.trace("MediaNodeClient.kickPeer")],ie.prototype,"kick",1),ce([E.trace("MediaNodeClient.kickAllPeers")],ie.prototype,"kickAll",1),ce([E.trace("MediaNodeClient.muteAll")],ie.prototype,"muteAll",1),ce([E.trace("MediaNodeClient.muteAllVideo")],ie.prototype,"muteAllVideo",1),ce([E.trace("MediaNodeClient.disableAudio")],ie.prototype,"disableAudio",1),ce([E.trace("MediaNodeClient.disableVideo")],ie.prototype,"disableVideo",1),ce([E.trace("MediaNodeClient.pinPeer")],ie.prototype,"pinPeer",1),ce([E.trace("MediaNodeClient.validateScreenShare")],ie.prototype,"validateScreenShare",1);function oS(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 ie(s,t);return s.setValue("roomNodeClient",r),r}function cS(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 T1=Object.defineProperty,y1=Object.getOwnPropertyDescriptor,Ni=(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&&T1(t,e,i),i};const dS=(YS=class{constructor(s,t,e,r){m(this,At);p(this,"self");p(this,"authToken");m(this,yn,void 0);p(this,"viewType");m(this,Ds,void 0);m(this,X,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,X,s),this.viewType=r,this.authToken=n,f(this,yn,i),f(this,Ds,e),this.setupEvents()}get peerId(){return a(this,X).getValue("peerId")}get telemetry(){return a(this,X).getValue("telemetry")}get logger(){return a(this,X).getValue("logger")}get mediaJoined(){return a(this,X).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=yt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await Ze.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");if(navigator.product!=="ReactNative"){const u=!s.getValue("flagsmith").hasFeature(Z.PRECALL_BANDWIDTH_TEST);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(g=>g.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",h==null?void 0:h.filter(g=>g.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",h==null?void 0:h.filter(g=>g.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:we.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:j_(s),skipConnectivityChecks:u,authToken:s.getValue("authToken")}),l.info("Callstats:: initialized")}catch(g){l.error("Callstats:: initialization failed",{error:g})}},0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new dS(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===H.Allowed&&r)try{await a(this,At,es).shareMic(s),this.self.audioEnabled||a(this,At,es).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===H.Allowed&&i)try{const d=await a(this,At,es).shareWebcam(t);d&&d.id!==t.id&&a(this,X).getValue("flagsmith").hasFeature(Z.EXP_RESHARE)&&await a(this,At,es).shareWebcam(d),this.self.videoEnabled||a(this,At,es).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===H.Allowed&&n)try{await((c=a(this,At,es))==null?void 0:c.shareScreen({video:o.video,audio:o.audio}))}catch(d){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,X).getValue("callstats").callEnded(),a(this,At,es).reset(),s&&await this.joinRoom(s)}setupEvents(){a(this,X).getValue("peerSessionStore").on(_.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,X).getValue("peerSessionStore").on(_.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,X).getValue("peerSessionStore").on(_.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,X).getValue("peerSessionStore").on(_.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,X).getValue("peerSessionStore").on(_.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,X).getValue("peerSessionStore").on(_.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&a(this,X).getValue("flagsmith").hasFeature(Z.REFRESH_ID_ON_DISCONNECTION)&&(t=fi()),a(this,yn).updateURL(t),a(this,X).getValue("telemetry").resetPeerId(t),yt().setHeader("tracing-id",t),sr.remapContext(t,a(this,X)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,X).getValue("peerSessionStore").on(_.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Ds).on(U.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Ds).on(Hd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,X).getValue("peerSessionStore").emit(_.UPDATE_PERMISSIONS,t.patch)})}),a(this,Ds).on(U.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Ds).on(U.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Ds).on(U.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,X).getValue("peerSessionStore").onAsync(_.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,X).getValue("peerSessionStore").on(_.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,X).getValue("peerSessionStore").on(_.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,X).getValue("callstats").audioOff())}),a(this,X).getValue("peerSessionStore").on(_.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,X).getValue("callstats").videoOff())}),a(this,X).getValue("peerSessionStore").onAsync(_.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,X).getValue("peerSessionStore").on(_.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await a(this,Ds).joinRoom(this.self);a(this,Ds).socket.flush();const e=bh(t.stageType);if(a(this,X).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}}catch(t){throw this.logger.error("SelfController.joinRoom: socket join failed",{error:t}),new k("Could not connect to the room.","0002")}try{await this.joinMediaRoom(s),a(this,X).notify("stageStatus")}catch(t){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:t}),new k("Could not establish media connection.","0002")}}async leaveRoom(s="left"){var t,e;if(this.logger.info(`Leaving room with state: ${s}`),(t=a(this,X).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),a(this,X).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,X).notify("stageStatus");try{(e=a(this,yn))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}cS(a(this,X)),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,X).getAllValues();try{if(e===tr.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}oS(a(this,X),{socket:a(this,yn),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:h}=(o=await((n=a(this,At,es))==null?void 0:n.joinRoom(this.self.name,r,s,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)throw h!=null?h:new Error("Could not connect to media server");i==="ON_STAGE"&&await this.shareMediaTracks(),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,X).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===tr.Webinar)&&a(this,At,es)&&(a(this,At,es).mediaJoined&&s!=="disconnected"&&await a(this,At,es).leaveRoom(),!(s==="stageLeft"&&t===tr.Livestream)&&(a(this,At,es).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()}},yn=new WeakMap,Ds=new WeakMap,X=new WeakMap,At=new WeakSet,es=function(){return a(this,X).getValue("roomNodeClient")},YS);let jr=dS;Ni([E.trace("SelfController.resetSelf")],jr.prototype,"resetSelf",1),Ni([E.trace("SelfController.setupEvents")],jr.prototype,"setupEvents",1),Ni([E.trace("SelfController.joinRoom")],jr.prototype,"joinRoom",1),Ni([E.trace("SelfController.leaveRoom")],jr.prototype,"leaveRoom",1),Ni([E.trace("SelfController.joinMediaRoom")],jr.prototype,"joinMediaRoom",1),Ni([E.trace("SelfController.leaveMediaRoom")],jr.prototype,"leaveMediaRoom",1),Ni([E.trace("SelfController.init")],jr,"init",1);class E1{constructor(t){m(this,Ac,void 0);f(this,Ac,t)}on(t,e){let r;t===U.roomPeerCount?r=Xm.fromBinary.bind(Xm):r=ff.fromBinary.bind(ff),a(this,Ac).on(t,({payload:i})=>{if(t===U.roomPeerCount&&!i)return;const n=r(i);e(n)})}}Ac=new WeakMap;class b1{constructor(t,e){m(this,Mc,void 0);m(this,Oc,void 0);f(this,Mc,e),f(this,Oc,t)}get logger(){return a(this,Oc).getValue("logger")}on(t,e){let r,i;switch(t){case U.transcript:{r=ih.fromBinary.bind(ih),i=ih.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Mc).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)})}}Mc=new WeakMap,Oc=new WeakMap;var w1=Object.defineProperty,P1=Object.getOwnPropertyDescriptor,qh=(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&&w1(t,e,i),i};class ol{constructor(t,e){m(this,Or,void 0);m(this,za,void 0);f(this,Or,e),f(this,za,t)}get logger(){return a(this,za).getValue("logger")}get telemetry(){return a(this,za).getValue("telemetry")}getPolls(){return a(this,Or).sendMessagePromise(ar.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Or).sendMessage(ar.createPoll,vM.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Or).sendMessage(ar.votePoll,yM.toBinary(r))}on(t,e){let r,i;switch(t){case ar.updatePoll:case ar.createPoll:case ar.votePoll:{r=Sh.fromBinary.bind(Sh),i=Sh.create();break}}a(this,Or).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,Or).removeListeners(t)}}Or=new WeakMap,za=new WeakMap,qh([E.trace("PollSocketHandler.getPolls")],ol.prototype,"getPolls",1),qh([E.trace("PollSocketHandler.createPoll")],ol.prototype,"createPoll",1),qh([E.trace("PollSocketHandler.votePoll")],ol.prototype,"votePoll",1);var _1=Object.defineProperty,R1=Object.getOwnPropertyDescriptor,C1=(s,t,e,r)=>{for(var i=r>1?void 0:r?R1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&_1(t,e,i),i};class lS{constructor(t,e){p(this,"socket");m(this,Xt,void 0);f(this,Xt,t),this.socket=e,this.handleSocketEvents(),a(this,Xt).setValue("roomSocketHandler",this)}get telemetry(){return a(this,Xt).getValue("telemetry")}get logger(){return a(this,Xt).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,lI.toBinary(e));try{const{peer:n}=Nn.fromBinary((await r).payload);a(this,Xt).getValue("connectionHandler").socketJoined=!0,a(this,Xt).getValue("peerSessionStore").emit(_.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,Xt).getValue("peerSessionStore").emit(_.ROOM_STATE,d),a(this,Xt).getValue("peerSessionStore").emit(_.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),n}}async getAllAddedParticipants(){try{return KI.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,eI.toBinary(n));i=oh.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=oh.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=oh.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,tf.toBinary({peerId:t}));e=Nn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=ef.create();try{const e=await this.socket.sendMessagePromise(U.getRoomInfo);t=ef.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=cf.create();try{const e=await this.socket.sendMessagePromise(U.getRoomStageState);t=cf.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,mo.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,mo.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,mo.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(U.leaveRoom,hI.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(U.kick,af.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(U.kickAll,jm.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(U.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.acceptWaitingRoomRequests,eA.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.denyWaitingRoomRequests,sA.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Hd.updateUserPreset,MA.toBinary(r))}handleSocketEvents(){this.socket.on(U.broadcastMessage,({payload:t})=>{try{const e=mo.fromBinary(t);a(this,Xt).getValue("peerSessionStore").emit(_.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=mo.fromBinary(t);a(this,Xt).getValue("peerSessionStore").emit(_.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=Nn.fromBinary.bind(Nn),i=Nn.create();break}case U.getWaitingRoomRequests:{r=(n,o)=>n?of.fromBinary(n,o):{requests:[]},i=of.create();break}case U.recordingPaused:case U.recordingStarted:case U.recordingStopped:{r=yf.fromBinary.bind(yf);break}case Hd.updateUserPreset:{r=lf.fromBinary.bind(lf);break}case ys.peerJoinedBroadcast:case Fr.peerJoinedBroadcast:{r=Jm.fromBinary.bind(Jm);break}case ys.selfJoinComplete:case Fr.selfJoinComplete:{r=sh.fromBinary.bind(sh);break}case ys.globalPeerPinBroadcast:case Fr.globalPeerPinBroadcast:{r=Ym.fromBinary.bind(Ym);break}case ys.selectedPeer:case Fr.selectedPeer:{r=th.fromBinary.bind(th);break}case ys.selectedPeerDiff:case Fr.selectedPeerDiff:{r=Wm.fromBinary.bind(Wm);break}case ys.leaveRoom:case Fr.leaveRoom:{r=rh.fromBinary.bind(rh);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(Hd.getUserPresets,PA.toBinary(e)),i=kA.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}}}Xt=new WeakMap,C1([E.trace("RoomSocketHandler.joinRoom")],lS.prototype,"joinRoom",1);class k1{constructor(t){m(this,Ut,void 0);f(this,Ut,t)}async getStageRequests(){const{payload:t}=await a(this,Ut).sendMessagePromise(U.getStageRequests);return t?fh.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,Ut).sendMessage(U.requestStageAccess)}cancelRequestAccess(){a(this,Ut).sendMessage(U.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,Ut).sendMessage(U.grantStageAccess,cM.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,Ut).sendMessage(U.denyStageAccess,lM.toBinary(e))}joinStage(){return a(this,Ut).sendMessagePromise(U.joinStage,void 0,void 0,U.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,Ut).sendMessagePromise(U.leaveStage,vf.toBinary(e),void 0,U.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,Ut).sendMessagePromise(U.leaveStage,vf.toBinary(e))}on(t,e){let r;switch(t){case U.grantStageAccess:case U.denyStageAccess:{r=void 0;break}case U.getStagePeers:{r=Sf.fromBinary.bind(Sf);break}case U.getStageRequests:case U.requestStageAccess:case U.cancelStageRequest:{r=fh.fromBinary.bind(fh);break}case U.peerStageStatusUpdate:{r=Qm.fromBinary.bind(Qm);break}}a(this,Ut).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,Ut).sendMessagePromise(U.getPeerInfo,tf.toBinary({peerId:t}));return Nn.fromBinary(e.payload)}}Ut=new WeakMap;class I1{constructor(t,e){m(this,Ye,void 0);m(this,Dc,void 0);f(this,Ye,e),f(this,Dc,t)}get logger(){return a(this,Dc).getValue("logger")}addPlugin(t,e){a(this,Ye).sendMessage(G.addPlugin,_0.toBinary({pluginId:t,staggered:e}))}removePlugin(t){a(this,Ye).sendMessage(G.removePlugin,C0.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await a(this,Ye).sendMessagePromise(G.getPlugins);return t?Y0.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};a(this,Ye).sendMessage(G.customPluginEventToRoom,x0.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const n={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,Ye).sendMessage(G.customPluginEventToPeers,F0.toBinary(n),i)}enablePluginForRoom(t,e){a(this,Ye).sendMessage(G.enablePluginForRoom,I0.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){a(this,Ye).sendMessage(G.enablePluginForPeers,D0.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){a(this,Ye).sendMessage(G.disablePluginForRoom,M0.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){a(this,Ye).sendMessage(G.disablePluginForPeers,V0.toBinary({pluginId:t,peerIds:e}),r)}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,Ye).sendMessage(G.storeInsertKeys,hf.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,Ye).sendMessage(G.storeGetKeys,q0.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,Ye).sendMessage(G.storeDeleteKeys,G0.toBinary(n),i)}storeDelete(t,e,r){a(this,Ye).sendMessage(G.storeDelete,J0.toBinary({pluginId:t,storeName:e}),r)}getPluginDataOld(t,e){this.logger.info("getPluginDataOld",{plugin:{id:t,storeName:e}})}storePluginDataOld(t,e,r){const i={pluginId:t,storeName:e,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};a(this,Ye).sendMessage(G.storeInsertKeys,hf.toBinary(i))}on(t,e){let r;switch(t){case G.addPlugin:case G.enablePluginForPeers:case G.enablePluginForRoom:{r=mh.fromBinary.bind(mh);break}case G.removePlugin:case G.disablePluginForPeers:case G.disablePluginForRoom:{r=pf.fromBinary.bind(pf);break}case G.customPluginEventToPeers:case G.customPluginEventToRoom:{r=mf.fromBinary.bind(mf);break}case G.storeInsertKeys:case G.storeGetKeys:case G.storeDeleteKeys:case G.storeDelete:{r=gf.fromBinary.bind(gf);break}}a(this,Ye).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}Ye=new WeakMap,Dc=new WeakMap;var A1=Object.defineProperty,M1=(s,t,e)=>t in s?A1(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,O1=(s,t,e)=>(M1(s,typeof t!="symbol"?t+"":t,e),e),jh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},O=(s,t,e)=>(jh(s,t,"read from private field"),e?e.call(s):t.get(s)),ye=(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)},ne=(s,t,e,r)=>(jh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),Pe=(s,t,e)=>(jh(s,t,"access private method"),e),cl={},D1={get exports(){return cl},set exports(s){cl=s}},Hn=typeof Reflect=="object"?Reflect:null,uS=Hn&&typeof Hn.apply=="function"?Hn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},dl;Hn&&typeof Hn.ownKeys=="function"?dl=Hn.ownKeys:Object.getOwnPropertySymbols?dl=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:dl=function(s){return Object.getOwnPropertyNames(s)};function N1(s){console&&console.warn&&console.warn(s)}var hS=Number.isNaN||function(s){return s!==s};function de(){de.init.call(this)}D1.exports=de,cl.once=U1,de.EventEmitter=de,de.prototype._events=void 0,de.prototype._eventsCount=0,de.prototype._maxListeners=void 0;var pS=10;function ll(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(de,"defaultMaxListeners",{enumerable:!0,get:function(){return pS},set:function(s){if(typeof s!="number"||s<0||hS(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");pS=s}}),de.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},de.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||hS(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 gS(s){return s._maxListeners===void 0?de.defaultMaxListeners:s._maxListeners}de.prototype.getMaxListeners=function(){return gS(this)},de.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")uS(c,this,t);else for(var d=c.length,l=TS(c,d),e=0;e<d;++e)uS(l[e],this,t);return!0};function mS(s,t,e,r){var i,n,o;if(ll(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=gS(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,N1(c)}return s}de.prototype.addListener=function(s,t){return mS(this,s,t,!1)},de.prototype.on=de.prototype.addListener,de.prototype.prependListener=function(s,t){return mS(this,s,t,!0)};function V1(){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 fS(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=V1.bind(r);return i.listener=e,r.wrapFn=i,i}de.prototype.once=function(s,t){return ll(t),this.on(s,fS(this,s,t)),this},de.prototype.prependOnceListener=function(s,t){return ll(t),this.prependListener(s,fS(this,s,t)),this},de.prototype.removeListener=function(s,t){var e,r,i,n,o;if(ll(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():L1(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this},de.prototype.off=de.prototype.removeListener,de.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 SS(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?x1(i):TS(i,i.length)}de.prototype.listeners=function(s){return SS(this,s,!0)},de.prototype.rawListeners=function(s){return SS(this,s,!1)},de.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):vS.call(s,t)},de.prototype.listenerCount=vS;function vS(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}de.prototype.eventNames=function(){return this._eventsCount>0?dl(this._events):[]};function TS(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function L1(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function x1(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function U1(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))}yS(s,t,n,{once:!0}),t!=="error"&&F1(s,i,{once:!0})})}function F1(s,t,e){typeof s.on=="function"&&yS(s,"error",t,e)}function yS(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 $1 extends v{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const ES=new $1;class bS{static encode(t){return ES.toBinary(t)}static decode(t){return ES.fromBinary(new Uint8Array(t))}}function B1(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Gr;class H1{constructor(t={}){O1(this,"opts"),ye(this,Gr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ne(this,Gr,0)}async wait(){ne(this,Gr,O(this,Gr)+1);const t=B1(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**O(this,Gr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return O(this,Gr)}reset(){ne(this,Gr,0)}}Gr=new WeakMap;const Wr={debug:0,info:1,warn:2,error:3};var Vi,Li;class q1{constructor(t){ye(this,Vi,void 0),ye(this,Li,void 0),ne(this,Vi,console),ne(this,Li,t)}debug(...t){Wr[O(this,Li)]>Wr.debug||O(this,Vi).debug("[Sockrates]:",...t)}info(...t){Wr[O(this,Li)]>Wr.info||O(this,Vi).info("[Sockrates]:",...t)}warn(...t){Wr[O(this,Li)]>Wr.warn||O(this,Vi).warn("[Sockrates]:",...t)}error(...t){Wr[O(this,Li)]>Wr.error||O(this,Vi).error("[Sockrates]:",...t)}}Vi=new WeakMap,Li=new WeakMap;var wS=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(wS||{});const j1="2",G1="3";var De,qn,_e,Ue,Jr,et,ur,Kr,Ps,jn,hr,Gh,PS,Co,ul,Wh,_S,Jh,RS,hl,Kh,zh,CS,ko,pl,Io,gl,ml,Yh,Gn,Ao,Mo,fl;class W1{constructor(t,e){var g,S,y,w,b,C,D,F,L,B;ye(this,Gh),ye(this,Co),ye(this,Wh),ye(this,Jh),ye(this,hl),ye(this,zh),ye(this,ko),ye(this,Io),ye(this,ml),ye(this,Gn),ye(this,Mo),ye(this,De,void 0),ye(this,qn,void 0),ye(this,_e,void 0),ye(this,Ue,void 0),ye(this,Jr,void 0),ye(this,et,void 0),ye(this,ur,void 0),ye(this,Kr,void 0),ye(this,Ps,void 0),ye(this,jn,void 0),ye(this,hr,void 0);var r,i,n,o,c,d,l,u,h;ne(this,qn,t),ne(this,Jr,[]),ne(this,et,new cl),ne(this,ur,!0),ne(this,Ps,!1),ne(this,_e,e!=null?e:{}),(g=(r=O(this,_e)).autoReconnect)!=null||(r.autoReconnect=!0),(S=(i=O(this,_e)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(y=(n=O(this,_e)).pingTimeout)!=null||(n.pingTimeout=3e4),(w=(o=O(this,_e)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(b=(c=O(this,_e)).debug)!=null||(c.debug=!0),(C=(d=O(this,_e)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(D=(l=O(this,_e)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(F=(u=O(this,_e)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(L=(h=O(this,_e)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),ne(this,Kr,{code:void 0,reason:void 0}),ne(this,Ue,(B=O(this,_e).logger)!=null?B:new q1(O(this,_e).debug?"debug":"info")),ne(this,hr,new H1)}get readyState(){var t;return(t=O(this,De))==null?void 0:t.readyState}get url(){return O(this,qn)}updateURL(t){ne(this,qn,t),Pe(this,zh,CS).call(this)}get config(){return O(this,_e)}get sendQueue(){return O(this,Jr)}flush(){if(!O(this,_e).queueOnDisconnect)return!1;const t=[];return O(this,Jr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ne(this,Jr,t),O(this,Jr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){O(this,Ue).debug("Websocket was already connecting or connected.");return}if(O(this,ur)!==!1)return new Promise((e,r)=>{Pe(this,Gn,Ao).call(this),Pe(this,Mo,fl).call(this);try{ne(this,De,new WebSocket(Pe(this,Gh,PS).call(this,O(this,qn)))),O(this,De).binaryType="arraybuffer",O(this,Ue).debug("Connecting");const i=setTimeout(()=>{O(this,Ue).debug("Connection timeout. Closing socket"),ne(this,ur,!0),Pe(this,Mo,fl).call(this),O(this,De).close(3001,"Connection Timeout"),O(this,_e).autoReconnect&&!O(this,Ps)&&(O(this,et).emit("reconnecting"),Pe(this,ko,pl).call(this)),r(new Error("Connection timed out!"))},O(this,_e).connectionTimeout);O(this,De).onopen=()=>{O(this,Ue).debug(`Ready State: ${wS[O(this,De).readyState]}`),i&&clearTimeout(i),Pe(this,ml,Yh).call(this),ne(this,Kr,{code:void 0,reason:void 0}),O(this,et).emit("connected"),O(this,_e).flushOnReconnect&&this.flush(),e()},O(this,De).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),O(this,Ue).debug("Socket closed. Close event:",{event:n}),O(this,Ue).debug(`Connection closed code: ${o}`),O(this,Ue).debug(`Connection closed reason: ${c}`),O(this,Ps)||Pe(this,hl,Kh).call(this,o,c)}catch(o){Pe(this,Co,ul).call(this,o)}},O(this,De).onerror=n=>{Pe(this,Co,ul).call(this,n)},O(this,De).onmessage=n=>Pe(this,Wh,_S).call(this,n)}catch(i){Pe(this,Co,ul).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(O(this,_e).queueOnDisconnect&&(!O(this,De)||O(this,De).readyState!==1))return O(this,Ue).debug("Queuing message since socket is not connected!",n),O(this,Jr).push(n),!1;const o=bS.encode(n);return Pe(this,Io,gl).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return Pe(this,Io,gl).call(this,t)}receive(t,e){return O(this,et).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")){O(this,et).on(t,e);return}this.receive(t,e)}removeAllListeners(){O(this,et).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){O(this,et).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){O(this,et).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ne(this,ur,!1),Pe(this,Gn,Ao).call(this),this.removeAllListeners(),ne(this,Kr,{code:1e3,reason:"Sockrates disconnect method called"}),O(this,De).close(1e3,"Sockrates disconnect method called.")}}De=new WeakMap,qn=new WeakMap,_e=new WeakMap,Ue=new WeakMap,Jr=new WeakMap,et=new WeakMap,ur=new WeakMap,Kr=new WeakMap,Ps=new WeakMap,jn=new WeakMap,hr=new WeakMap,Gh=new WeakSet,PS=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)://.")},Co=new WeakSet,ul=function(s,t){O(this,Ue).error("Error:",{error:s}),O(this,et).emit("errored",{error:s}),t==null||t(s)},Wh=new WeakSet,_S=function(s){if(Pe(this,ml,Yh).call(this),s.data===j1){O(this,Ue).debug("Received ping from server"),Pe(this,Io,gl).call(this,G1);return}const t=bS.decode(s.data),{id:e,payload:r}=t;O(this,Ue).debug("Received message",{event:t.event,messageID:e}),O(this,et).emit(t.event.toString(),{id:e,payload:r})},Jh=new WeakSet,RS=function(){return O(this,De).readyState===1},hl=new WeakSet,Kh=function(s,t){ne(this,Kr,{reason:t,code:s}),O(this,et).emit("disconnected",{code:s,reason:t})},zh=new WeakSet,CS=function(){const{reason:s,code:t}=O(this,Kr);t&&t!==1e3&&O(this,ur)&&O(this,_e).autoReconnect&&!O(this,Ps)&&(O(this,Ue).debug(`Triggering reconnection due to ${s}.`),O(this,et).emit("reconnecting"),Pe(this,ko,pl).call(this))},ko=new WeakSet,pl=async function(s=!0){if(s&&O(this,Ps)){O(this,Ue).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(O(this,Ps)||O(this,hr).reset(),O(this,_e).maxReconnectionAttempts!==null&&O(this,hr).getAttempts()>=O(this,_e).maxReconnectionAttempts){O(this,et).emit("failed"),ne(this,Ps,!1);return}ne(this,Ps,!0),Pe(this,Mo,fl).call(this),Pe(this,Gn,Ao).call(this);try{if(await O(this,hr).wait(),O(this,ur)===!1)return;if(O(this,Ue).debug(`Reconnection attempt ${O(this,hr).getAttempts()}`),O(this,et).emit("reconnectAttempt",{attempt:O(this,hr).getAttempts()}),await this.connect(),!Pe(this,Jh,RS).call(this))throw Error("Reconnect Failed");ne(this,Ps,!1),ne(this,Kr,{code:void 0,reason:void 0}),O(this,et).emit("reconnected")}catch(t){O(this,Ue).debug("Failed to reconnect."),O(this,et).emit("reconnectFailure",{attempt:O(this,hr).getAttempts()}),Pe(this,ko,pl).call(this,!1)}},Io=new WeakSet,gl=function(s){try{return O(this,De).send(s),!0}catch(t){return O(this,Ue).error(t.message),!1}},ml=new WeakSet,Yh=function(){this.config.disconnectOnPingTimeout&&(O(this,Ue).debug("Resetting ping timeout"),Pe(this,Gn,Ao).call(this),ne(this,jn,setTimeout(()=>{var s;O(this,Ue).debug("Disconnecting the socket due to ping timeout"),ne(this,ur,!0);const t=3002,e="Ping timeout";(s=O(this,De))==null||s.close(t,e),Pe(this,hl,Kh).call(this,t,e)},O(this,_e).pingTimeout)))},Gn=new WeakSet,Ao=function(){O(this,jn)&&(clearTimeout(O(this,jn)),ne(this,jn,void 0))},Mo=new WeakSet,fl=function(){O(this,De)&&(O(this,De).onopen=void 0,O(this,De).onerror=void 0,O(this,De).onmessage=void 0,O(this,De).onclose=void 0)};var J1=Object.defineProperty,K1=Object.getOwnPropertyDescriptor,Sl=(s,t,e,r)=>{for(var i=r>1?void 0:r?K1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&J1(t,e,i),i};const kS=65535,z1=3e3,IS=(QS=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,Me);m(this,Nc);m(this,Vc);m(this,pi,void 0);m(this,Ae,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");m(this,ms,void 0);m(this,it,void 0);var n;if(!t||!e||!r)throw new k("peerId, meetingId, or authToken can not be empty","0404");f(this,ms,void 0),f(this,it,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,pi,x(this,Nc,fp).call(this,t)),f(this,Ae,new W1(a(this,pi),{autoReconnect:!0,disconnectOnPingTimeout:(n=i.includes("PING"))!=null?n:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Me,je).socketJoinAttempted}set joinAttempted(s){a(this,Me,je).socketJoinAttempted=s}get telemetry(){return a(this,it).getValue("telemetry")}get logger(){return a(this,it).getValue("logger")}get peerId(){return a(this,it).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,pi,x(this,Nc,fp).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Ae).updateURL(a(this,pi))}static getSocketEdgeDomain(s){return bi({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,pi)}async connect(){a(this,Me,je).socketJoinAttempted=!0,await a(this,Ae).connect(),a(this,Me,je).socketJoinAttempted=!0,a(this,Me,je).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){a(this,Me,je).socketJoinAttempted=!1,a(this,Ae).disconnect(),a(this,Me,je).socketJoinAttempted=!0,a(this,Me,je).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Ae).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,it).getValue("telemetry").injectContext(r),a(this,Ae).send(s,e!=null?e:x(this,Vc,Sp).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,Ae).removeListener(n,y),a(this,Ae).removeListener(kS,w),a(this,Ae).removeListener(Fr.errorResponse,w),a(this,Ae).removeListener(ys.errorResponse,w)},l=r!=null?r:x(this,Vc,Sp).call(this),u={};a(this,it).getValue("telemetry").injectContext(u);const g=({id:y,payload:w})=>{if(l===y){let b;try{const C=WC.fromBinary(w);b=new Error(C.errorMessage)}catch(C){b=new Error("failed to parse error message",{cause:C});try{const D=Jk.fromBinary(w);b=new Error(D.message)}catch(D){b=new Error("failed to parse error message",{cause:D})}}c(b),d(S,g)}},S=({id:y,payload:w})=>{l===y&&(o({id:y,payload:w}),d(S,g))};a(this,Ae).on(n,S),a(this,Ae).on(kS,g),a(this,Ae).on(Fr.errorResponse,g),a(this,Ae).on(ys.errorResponse,g),setTimeout(()=>{d(S,g),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Ae).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){a(this,Ae).on(s,t)}onStateEvent(s,t){a(this,Ae).on(s,t)}removeListener(s,t){a(this,Ae).removeListener(s,t)}removeListeners(s){a(this,Ae).removeListeners(s)}flush(){return a(this,Ae).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),a(this,ms)&&(clearTimeout(a(this,ms)),f(this,ms,void 0)),a(this,Me,je).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,Me,je).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Bn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Bn.CONNECTED?a(this,it).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Me,je).joinAttempted}):f(this,ms,setTimeout(()=>{a(this,it).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Me,je).joinAttempted}),f(this,ms,void 0)},z1)),a(this,Me,je).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge"),a(this,Me,je).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,Me,je).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,Me,je).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Me,je).mediaJoinAttempted}}),a(this,ms)&&(clearTimeout(a(this,ms)),f(this,ms,void 0)),a(this,it).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Me,je).mediaJoinAttempted}),a(this,Me,je).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge"),a(this,it).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_FAILED),a(this,Me,je).updateSocketConnectionState("failed")})}},pi=new WeakMap,Ae=new WeakMap,Me=new WeakSet,je=function(){return a(this,it).getValue("connectionHandler")},ms=new WeakMap,it=new WeakMap,Nc=new WeakSet,fp=function(s){const t=a(this,it).getValue("socketBaseURI")||a(this,it).getValue("baseURI");let e=IS.getSocketEdgeDomain(t);typeof On(a(this,it),"socket_server_base")=="string"&&(e=On(a(this,it),"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=>xd[c]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(o).forEach(([c,d])=>{i.searchParams.append(c,d.toString())}),i.href},Vc=new WeakSet,Sp=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},QS);let Oo=IS;Sl([E.trace("SocketService.connect")],Oo.prototype,"connect",1),Sl([E.trace("SocketService.disconnect")],Oo.prototype,"disconnect",1),Sl([E.trace("SocketService.sendMessagePromise")],Oo.prototype,"sendMessagePromise",1),Sl([E.trace("SocketService.sendMessagePromiseWithTimeout")],Oo.prototype,"sendMessagePromiseWithTimeout",1);class Y1{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=yI.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=WI.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=nf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return rf.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return LI.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(U.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(U.createConnectedRooms,PI.toBinary({payloads:t}));return rf.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,NI.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(U.movePeers,HI.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 Q1=Object.defineProperty,X1=Object.getOwnPropertyDescriptor,Z1=(s,t,e,r)=>{for(var i=r>1?void 0:r?X1(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};class AS extends $t{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);m(this,Ns,void 0);f(this,Ns,e)}get supportsConnectedMeetings(){return a(this,Ns).getValue("self").id!==""}get isActive(){return this.meetings.length!==0}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
19
19
  Please connect with our support team to enable connected meetings.`)}async getConnectedMeetings(){this.validateConnectedMeetingsAction(),this.logger.info("Getting connected meetings dump");const e=await a(this,Ns).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await a(this,Ns).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.validateConnectedMeetingsAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await a(this,Ns).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.validateConnectedMeetingsAction(),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,Ns).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,Ns).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.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,Ns).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})}}Ns=new WeakMap,Z1([Ot({maxInvocations:60,period:60})],AS.prototype,"getConnectedMeetings",1);var eN=Object.defineProperty,tN=Object.getOwnPropertyDescriptor,Qh=(s,t,e,r)=>{for(var i=r>1?void 0:r?tN(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&&eN(t,e,i),i};const MS=(XS=class{constructor(s){p(this,"connectedMeetings");m(this,Se,void 0);f(this,Se,s),this.connectedMeetings=new AS(s)}get telemetry(){return a(this,Se).getValue("telemetry")}get logger(){return a(this,Se).getValue("logger")}static init(s){const t=new MS(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),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;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
20
20
  Please connect with our support team to enable connected meetings.`);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 DS.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,XS);let vl=MS;Qh([E.trace("ConnectedMeetingsController.getConnectedMeetings")],vl.prototype,"getConnectedMeetings",1),Qh([E.trace("ConnectedMeetingsController.setupEvents")],vl.prototype,"setupEvents",1),Qh([E.trace("ConnectedMeetingsController.switchMeeting")],vl.prototype,"switchMeeting",1);var sN=Object.defineProperty,rN=Object.getOwnPropertyDescriptor,Tl=(s,t,e,r)=>{for(var i=r>1?void 0:r?rN(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&&sN(t,e,i),i};const Wn=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 L,B,Q;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(cS(s),we.isSupported()===!1)throw new k("Browser not supported","0010",c,!0);const d=zM(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 AO(s);s.setValue("connectionHandler",l);let u="",h="",g=null;c.info("CF SFU is being used.");try{g=await d.getUserDetails(),u=((L=g.meeting)==null?void 0:L.title)||"",h=((B=g.socket)==null?void 0:B.baseUri)||s.getValue("baseURI"),s.setValue("presetName",g.preset.name),s.setValue("socketBaseURI",h),c.info(`Socket Base URI ${h} is being used`)}catch(se){throw c.error("Failed to get user details",{error:se}),new k("SDK initialization failed: /participant-details API request failed","0001")}const S=Wn.createSocketService(s),y=S.connect(),w=d.getPlugins();try{await Wn.setupFlagsmith(s)}catch(se){c.error("Failed to setup flagsmith",{error:se})}try{await y}catch(se){c.error("[Controller]: Failed to connect to socket server:",{error:se})}const b=Ah.init(g.preset,!s.getValue("modules").theme);s.setValue("theme",b);const C=Oh.init(s,b.viewType,g.preset.permissions),D=Wn.setupControllers(S,s,g,w,u,b,C);TO(b)&&((Q=Wn.createRoomNodeClient(s,S).initializeConnection(g.participant.name,i,!1,C))==null||Q.catch(nt=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:nt})}));const{controllers:F}=await D;return eR(),new Wn(e,F,s)}static async setupFlagsmith(s){var l;const{peerId:t,baseURI:e,overrides:r,meetingId:i,organizationId:n,logger:o}=s.getAllValues(),c=Z_(i),d={entity:Ju.PEER,clientId:n,isAnonUser:!n,sdkVersion:s.getValue("sdkVersion"),presetName:s.getValue("presetName"),meetingHash:c,roomName:i,...we.getDeviceInfo(),isReactNative:navigator.isReactNative};try{const u=(l=r==null?void 0:r.whitelabelled_flags_endpoint)==null||l?bi({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";await s.getValue("flagsmith").identify(`${Ju.PEER}_${t}`,JSON.parse(JSON.stringify(d)),!1,5e3,u,o),o.info("flagsmith::allFlags",{flags:JSON.stringify(s.getValue("flagsmith").getAllFlags())},!0)}catch(u){o.error("Failed to fetch flagsmith flags")}}static async setupControllers(s,t,e,r,i,n,o){var V,R,Je;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),u=t.getValue("logger"),{viewType:h,mediaConstraints:{audio:g}}=n;t.setValue("viewType",h),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(V=g.enableHighBitrate)!=null?V:!1,enableStereo:(R=g.enableStereo)!=null?R:!1}},...l}),t.setValue("maxPreferredStreams",we.isMobile()?n.maxVideoStreams.mobile:n.maxVideoStreams.desktop);let S,y,w,b,C,D,F,L,B;const Q=new b1(t,s),se=new Y1(s);t.setValue("connectedMeetingsSocketHandler",se);const nt=new ol(t,s),Vs=new or(t,s),_n=new k1(s),Ls=new lS(t,s),I=new I1(t,s),T=new E1(s),P=await jr.init(t,Ls,d,o,n);t.setValue("selfController",P);const $=await If.init(t,P.self,Ls,Q,i);if(c.participant&&(L=new lr(t,P.self,Ls)),(Je=c.e2ee)!=null&&Je.enabled&&c.e2ee.manager.init(u,t.getValue("peerSessionStore")),c.chat&&(y=await is.init(t,Vs,P.self,L.participants)),c.internals&&(C=await _h.init(t)),c.livestream&&n.viewType===tr.Livestream&&t.getValue("flagsmith").hasFeature(Z.LIVESTREAM)&&(F=new zf(t,P.self,T)),c.poll&&(S=await _f.init(t,P.self,nt)),c.recording&&(D=new Nf(t,P.self,Ls)),c.stage&&(w=new Af(t,_n,Ls,P.self,L.participants)),c.plugin){if(!L)throw new k("The plugin module cannot be initialized without the `participant` module","0102");const Dr=await r;b=await vo.init(t,Dr,I,Vs,y==null?void 0:y.chat,P.self,L.participants,i)}if(c.connectedMeetings&&(B=await vl.init(t)),c.pip){const Dr=await Ku._init(t,P.self);t.setValue("pip",Dr)}const qe={storesManager:new kD(t,I),pollController:S,selfController:P,metaController:$,chatController:y,stageController:w,pluginController:b,recordingController:D,internalsController:C,livestreamController:F,participantController:L,connectedMeetingsController:B};return{theme:n,permissions:o,controllers:qe}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return oS(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 Oo(s,{peerId:t,meetingId:e,authToken:r,capabilities:o})}};let Do=Wn;Tl([E.trace("Controller.init")],Do,"init",1),Tl([E.trace("setupFlagsmith")],Do,"setupFlagsmith",1),Tl([E.trace("Controller.createRoomNodeClient")],Do,"createRoomNodeClient",1),Tl([E.trace("Controller.createSocketService")],Do,"createSocketService",1);class iN{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 OS=new iN;function nN(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=wi.baseURI.prod;t&&(n=t);const o=`https://${bi({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new k("Invalid auth token","0004")}}class aN{constructor(){m(this,hu);m(this,gi,new Audio);m(this,En,new MediaStream);m(this,bn,new Map);m(this,Lc,void 0);a(this,gi).srcObject=a(this,En),a(this,gi).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,bn).has(e.id)||(a(this,En).addTrack(e),a(this,bn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,gi).setSinkId(t)}removeTrack(t){const e=a(this,bn).get(t);e&&(a(this,En).removeTrack(e),a(this,bn).delete(t))}async play(){return a(this,gi).srcObject=a(this,En),a(this,gi).play().catch(t=>{x(this,hu,Lv).call(this,t)})}onError(t){f(this,Lc,t)}}gi=new WeakMap,En=new WeakMap,bn=new WeakMap,Lc=new WeakMap,hu=new WeakSet,Lv=function(t){var e;(e=a(this,Lc))==null||e.call(this,t)};class oN extends aN{constructor(){super();m(this,wn,void 0);f(this,wn,new Map)}addParticipantTrack(e,r){a(this,wn).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,wn).get(e);r&&this.removeTrack(r),a(this,wn).delete(e)}}wn=new WeakMap;var cN=Object.defineProperty,dN=Object.getOwnPropertyDescriptor,yl=(s,t,e,r)=>{for(var i=r>1?void 0:r?dN(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&&cN(t,e,i),i};let zr=(ZS=class{constructor(t,e){m(this,Qe,void 0);m(this,Pn,void 0);f(this,Pn,t),f(this,Qe,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:fi(),n=sr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new Xf(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var g,S,y,w,b,C,D;we.init();const e=(S=(g=t==null?void 0:t.cachedUserDetails)==null?void 0:g.peerId)!=null?S:fi(),{authToken:r,baseURI:i}=t,{meetingId:n,...o}=nN(r,i);if((y=o.baseURI)!=null&&y.includes("dyte.io"))throw new k("Dyte Base URIs are no longer supported. Please use RealtimeKit Base URIs. Eg: realtime.cloudflare.com","0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=zr.setupContext(e,t,n,o),d=c.getValue("telemetry"),l=c.getValue("logger");$v(l),OS.init(l),d.init(c,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(b=(w=t.modules)==null?void 0:w.tracing)!=null?b:!0),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(C=t.authToken)==null?void 0:C.slice(0,10)}...
21
- ${(D=t.authToken)==null?void 0:D.slice(-10)}`}});const u=await Do.init(c),h=new zr(c,u);return c.setValue("meeting",h),h}static setupContext(t,e,r,i){var d,l;const n=sr.createContext(t,e),o={...H_,...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",q_({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Hs(e.cachedUserDetails)),n.setValue("sdkVersion","1.4.0-staging.5"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new oN),n}async join(){const{selfController:t}=a(this,Qe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){OS.cleanup(),a(this,Pn).getValue("peerSessionStore").reset();const{selfController:e}=a(this,Qe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,Qe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Qe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Qe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Qe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Qe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Qe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Qe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Qe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Qe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Qe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Qe).stageController)==null?void 0:t.stage}get stores(){return a(this,Qe).storesManager}get audio(){return a(this,Pn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Qe).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Qe=new WeakMap,Pn=new WeakMap,ZS);yl([ut("0002"),cr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],zr.prototype,"join",1),yl([ut("0003")],zr.prototype,"leave",1),yl([ut("0001"),cr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],zr,"init",1),zr=yl([ut("0000")],zr);const DS=zr;return DS}();
21
+ ${(D=t.authToken)==null?void 0:D.slice(-10)}`}});const u=await Do.init(c),h=new zr(c,u);return c.setValue("meeting",h),h}static setupContext(t,e,r,i){var d,l;const n=sr.createContext(t,e),o={...H_,...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",q_({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Hs(e.cachedUserDetails)),n.setValue("sdkVersion","1.4.0"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new oN),n}async join(){const{selfController:t}=a(this,Qe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){OS.cleanup(),a(this,Pn).getValue("peerSessionStore").reset();const{selfController:e}=a(this,Qe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,Qe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Qe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Qe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Qe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Qe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Qe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Qe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Qe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Qe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Qe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Qe).stageController)==null?void 0:t.stage}get stores(){return a(this,Qe).storesManager}get audio(){return a(this,Pn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Qe).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Qe=new WeakMap,Pn=new WeakMap,ZS);yl([ut("0002"),cr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],zr.prototype,"join",1),yl([ut("0003")],zr.prototype,"leave",1),yl([ut("0001"),cr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],zr,"init",1),zr=yl([ut("0000")],zr);const DS=zr;return DS}();
@@ -1,5 +1,5 @@
1
1
  Name: @cloudflare/realtimekit
2
- Version: 1.4.0-staging.4
2
+ Version: 1.4.0-staging.5
3
3
  License: Apache-2.0
4
4
  Private: false
5
5
  Description: A real-time video and audio SDK for building custom, collaborative communication experiences.