@cloudflare/realtimekit 1.2.2-staging.3 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  Name: @cloudflare/realtimekit
2
- Version: 1.2.2-staging.2
2
+ Version: 1.2.2-staging.4
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.
package/dist/index.cjs.js CHANGED
@@ -10,6 +10,6 @@ ${s}`}const Ba={maxInvocations:5,period:1};function Mt(s,t){return function(e,r,
10
10
  `}this.midTransceiverMap.set(o.mid,o);const d=l=>u(this,null,function*(){return this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(l)}]`),yield this.pc.setRemoteDescription(l),o.mid});return this.logger.debug(`send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(c,void 0,2)}]`),{offerSdp:c,callback:d,sender:o.sender,mid:o.mid}})}addCustomEventListeners(){this.pc.addEventListener("datachannel",t=>{const{channel:e}=t;e.onmessage=r=>{this.safeEmit("datachannel",t.channel,String.fromCharCode(...new Uint8Array(r.data)))}})}}class Id extends Bh{constructor(e,r){super(e);h(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new Id(e,r)}get name(){return"Firefox60"}send(o){return u(this,arguments,function*({track:e,encodings:r,codecOptions:i,screenShare:a}){this._assertSendDirection();const c=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},d=this.pc.addTransceiver(e,D({direction:"sendonly",streams:[a?this._sendScreenShareStream:this._sendWebStream]},c));if(!this.supportsSendEncodings&&r){r.reverse();const T=d.sender.getParameters();T.encodings=r,yield d.sender.setParameters(T)}const l=(T,v)=>{var N;const P=hs.parse(T),_=P.media[P.media.length-1],C=_.rtp.filter(B=>v.some(G=>G.name===B.codec)),w=_.fmtp.filter(B=>C.some(G=>G.payload===B.payload)),V=(N=_.rtcpFb)==null?void 0:N.filter(B=>C.some(G=>G.payload===B.payload)),F=C.map(B=>B.payload);return P.media[P.media.length-1].rtp=C,P.media[P.media.length-1].fmtp=w,P.media[P.media.length-1].rtcpFb=V,P.media[P.media.length-1].payloads=F.join(" "),hs.write(P)},p=yield this.pc.createOffer();if(p.sdp=l(p.sdp,i),this.logger.debug(`send() | calling pc.setLocalDescription() [offer:${JSON.stringify(p)}]`),yield this.pc.setLocalDescription(p),e==="audio"||e.kind==="audio"){const{enableDtx:T,enableStereo:v}=this,P=this.enableHighBitrate?v?128e3:64e3:v?64e3:32e3;p.sdp=p.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${T?"usedtx=1;":""}${v?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${P}`)}return this.midTransceiverMap.set(d.mid,d),{offerSdp:p,callback:T=>u(this,null,function*(){return this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(T)}]`),yield this.pc.setRemoteDescription(T),d.mid}),sender:d.sender,mid:d.mid}})}setMaxSpatialLayer(e,r){return u(this,null,function*(){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 a=i.sender.getParameters(),o=a.encodings.length-1-r;a.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),yield i.sender.setParameters(a)})}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:r}=e;r.onmessage=i=>u(this,null,function*(){const a=yield i.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(a)))})})}}class qh extends Bh{static createFactory(t){return()=>new qh(t)}get name(){return"Safari12"}send(a){return u(this,arguments,function*({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection(),this.logger.debug("Safari12::creating new transceiver");const o=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e}),c=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`Safari12::senders available params: ${JSON.stringify(c)}`);const d=[];r&&r.length>0&&r.forEach(g=>{var v;const T=c.codecs.find(P=>P.mimeType.includes(g.name));if(g.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(g.parameters)}`);const P=((v=T.sdpFmtpLine)==null?void 0:v.split(";"))||[];P.push(...g.parameters);const _=[...new Set(P).values()];T.sdpFmtpLine=_.join(";")}d.push(T)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(d)}`),o.setCodecPreferences(d);const l=yield this.pc.createOffer();if(yield this.pc.setLocalDescription(l),t==="audio"||t.kind==="audio"){const{enableStereo:g,enableDtx:T}=this,v=this.enableHighBitrate?g?128e3:64e3:g?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${T?"usedtx=1;":""}${g?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${v}`)}return this.midTransceiverMap.set(o.mid,o),{offerSdp:l,callback:g=>u(this,null,function*(){return this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(g)}]`),yield this.pc.setRemoteDescription(g),o.mid}),sender:o.sender,mid:o.mid}})}addCustomEventListeners(){this.pc.ondatachannel=t=>{const{channel:e}=t;e.onmessage=r=>u(this,null,function*(){const i=String.fromCharCode(...new Uint8Array(r.data));this.safeEmit("datachannel",t.channel,i)})}}}function GD(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}var sc,Vi,Ls,Jd,Vs,kr,rc,Ku,Kd,sT,zd,rT;class WD extends Gl{constructor(e,r){var i;super(e);m(this,Vs);m(this,rc);m(this,Kd);m(this,zd);h(this,"rtpReceiver");h(this,"id");h(this,"localId");h(this,"producerId");h(this,"producingTransportId");h(this,"mimeType");h(this,"track");h(this,"peerId");h(this,"appData");h(this,"transceiver");m(this,sc,void 0);m(this,Vi,void 0);m(this,Ls,void 0);m(this,Jd,void 0);this.id=r.id,this.localId=r.localId,f(this,sc,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,f(this,Ls,!1),this.producerId=r.producerId,this.track=r.track,f(this,Vi,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,U(this,Kd,sT).call(this),f(this,Jd,e)}get closed(){return n(this,Ls)}get kind(){return this.track.kind}get paused(){return n(this,Vi)}close(e,r){n(this,Ls)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,n(this,Vs,kr)),f(this,Ls,!0),r&&(U(this,zd,rT).call(this),this.transceiver.stop()),this.safeEmit("close",e))}getStats(){return u(this,null,function*(){if(n(this,Ls))throw new It("closed");return n(this,sc).getReceiverStats(this.localId)})}pause(){if(this.logger.debug("consumer::pause()",n(this,Vs,kr)),n(this,Ls)){this.logger.error("consumer::pause() | Consumer closed",n(this,Vs,kr));return}f(this,Vi,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",n(this,Vs,kr)),n(this,Ls)){this.logger.error("Consumer::resume() | Consumer closed",n(this,Vs,kr));return}f(this,Vi,!1),this.track.enabled=!0,this.safeEmit("resume")}}sc=new WeakMap,Vi=new WeakMap,Ls=new WeakMap,Jd=new WeakMap,Vs=new WeakSet,kr=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},rc=new WeakSet,Ku=function(){this.logger.debug('Consumer::track "ended" event',n(this,Vs,kr)),this.safeEmit("trackended")},Kd=new WeakSet,sT=function(){this.track.addEventListener("ended",U(this,rc,Ku).bind(this))},zd=new WeakSet,rT=function(){try{this.track.removeEventListener("ended",U(this,rc,Ku)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",H(D({},n(this,Vs,kr)),{error:e}))}};var Ts,Ta,va,xi,ss,Xe,Gr,ya,Yd,$t,us;class JD extends Gl{constructor(e,r){var i,a;super(e);m(this,$t);h(this,"id");h(this,"localId");m(this,Ts,void 0);h(this,"kind");h(this,"appData");h(this,"rtpSender");m(this,Ta,void 0);m(this,va,void 0);m(this,xi,void 0);m(this,ss,!1);m(this,Xe,void 0);m(this,Gr,void 0);m(this,ya,void 0);m(this,Yd,void 0);this.id=r.id,this.localId=r.localId,f(this,Xe,r.track),this.kind=(i=r.track)==null?void 0:i.kind,f(this,Gr,r.disableTrackOnPause?!((a=r.track)!=null&&a.enabled):!1),f(this,ya,void 0),f(this,Ta,r.stopTracks),f(this,va,r.disableTrackOnPause),f(this,xi,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),f(this,Ts,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),f(this,Yd,e)}get closed(){return n(this,ss)}get track(){return n(this,Xe)}get paused(){return n(this,Gr)}get maxSpatialLayer(){return n(this,ya)}close(e){return u(this,null,function*(){if(n(this,ss))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,n(this,$t,us)),f(this,ss,!0),this._destroyTrack(),e===Ad){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=yield n(this,Ts).stopSending(this.localId),{answer:a}=yield this.safeEmitAsPromise("close",{offer:r,reason:e});i(a)})}getStats(){return u(this,null,function*(){if(n(this,ss))throw new It("closed");return n(this,Ts).getSenderStats(this.localId)})}pause(){this.logger.debug("Producer::pause()",n(this,$t,us)),n(this,ss)&&this.logger.error("Producer::pause() | Producer closed",n(this,$t,us)),f(this,Gr,!0),n(this,Xe)&&n(this,va)&&(n(this,Xe).enabled=!1),n(this,xi)&&n(this,Ts).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",n(this,$t,us)),n(this,ss)){this.logger.error("Producer::resume() | Producer closed",n(this,$t,us));return}f(this,Gr,!1),n(this,Xe)&&n(this,va)&&(n(this,Xe).enabled=!0),n(this,xi)&&n(this,Ts).replaceTrack(this.localId,n(this,Xe)),this.emit("resume")}replaceTrack(r){return u(this,arguments,function*({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,n(this,$t,us)),n(this,ss)){if(e&&n(this,Ta))try{e.stop()}catch(i){this.logger.error("Producer::replaceTrack",H(D({},n(this,$t,us)),{error:i}))}throw new It("closed")}else if(e&&e.readyState==="ended")throw new It("track ended");if(e===n(this,Xe)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,n(this,$t,us));return}(!n(this,xi)||!n(this,Gr))&&(yield n(this,Ts).replaceTrack(this.localId,e)),this._destroyTrack(),f(this,Xe,e),this._handleTrack()})}setMaxSpatialLayer(e){return u(this,null,function*(){if(n(this,ss))throw new It("closed");if(this.kind!=="video")throw new Mo("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");yield n(this,Ts).setMaxSpatialLayer(this.localId,e),f(this,ya,e)})}setRtpEncodingParameters(e){return u(this,null,function*(){if(n(this,ss))throw new It("closed");if(typeof e!="object")throw new TypeError("invalid params");yield n(this,Ts).setRtpEncodingParameters(this.localId,e)})}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,n(this,$t,us)),this.safeEmit("trackended",this.track.id)}_handleTrack(){n(this,Xe)&&n(this,Xe).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(n(this,Xe))try{n(this,Xe).removeEventListener("ended",this._onTrackEnded),n(this,Ta)&&n(this,Xe).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,H(D({},n(this,$t,us)),{error:r}))}}}Ts=new WeakMap,Ta=new WeakMap,va=new WeakMap,xi=new WeakMap,ss=new WeakMap,Xe=new WeakMap,Gr=new WeakMap,ya=new WeakMap,Yd=new WeakMap,$t=new WeakSet,us=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function iT(s){return typeof s=="object"&&!Array.isArray(s)&&s!==null}function gu(s){return Math.random().toString(36).substring(2,2+s)}const rd=1;function vg(s){const t=s;return delete t.payload._bolt,t}function KD(s){return s.payload&&iT(s.payload)}function zD(s){var t,e;return KD(s)&&(e=(t=s.payload._bolt)==null?void 0:t.id)!=null?e:""}var Wr,Qd,Ui;const kn=class extends lt.EventEmitter{constructor(e,r,i,a){super();h(this,"channel");h(this,"queue");h(this,"serverProtocolVersion");m(this,Wr,new Map);m(this,Qd,void 0);m(this,Ui,void 0);h(this,"respond",(e,r,i=!1)=>{let a;i?a=kn.createErrorResponse(e,r):a=kn.createResponse(e,r),this.channel.send(JSON.stringify(a))});h(this,"notify",e=>{const r=kn.createNotification(e);this.channel.send(JSON.stringify(r))});h(this,"request",e=>u(this,null,function*(){const r=kn.createRequest(e),i=new Promise((a,o)=>{const{id:d}=r.payload._bolt,l={id:d,method:r.type,resolve:p=>{this.queue.delete(d)&&(clearTimeout(l.timer),a(p))},timer:setTimeout(()=>{this.queue.delete(d)&&o(new Error(`request timeout for message id: ${d}`))},2e4),cancel:p=>{this.queue.delete(d)&&(clearTimeout(l.timer),o(p))}};this.queue.set(d,l)});return this.channel.send(JSON.stringify(r)),i}));h(this,"send",e=>{const r=JSON.stringify(e),i=16384;if(r.length>i){const a=i-200,o=Math.ceil(r.length/a),c=[];for(let l=0;l<o;l+=1){const p=l*a,g=(l+1)*a;c.push(r.slice(p,g))}const d=Tr.v4();for(let l=0;l<o;l+=1){const p=c[l],T=JSON.stringify({id:d,count:o,chunkIndex:l,chunk:p});n(this,Ui).debug(`Sending message chunk over dc: ${T}`),this.channel.send(T)}}else n(this,Ui).debug(`Sending message over dc: ${r}`),this.channel.send(r)});h(this,"processMessage",e=>{var i;n(this,Wr).has(e.id)||n(this,Wr).set(e.id,[]);const r=n(this,Wr).get(e.id);if(r[e.chunkIndex]=e,(r==null?void 0:r.length)===e.count&&!r.some(a=>a===void 0)){const a=n(this,Wr).get(e.id),o=a==null?void 0:a.reduce((d,l)=>d+l.chunk,"");n(this,Wr).delete(e.id);const c=JSON.parse(o);if(!c.payload||!iT(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}});h(this,"processResponseMsg",e=>{const{id:r}=e.payload._bolt,i=this.queue.get(r);return i?(n(this,Ui).debug(`resolving pending request with id: ${r}, complete response: ${JSON.stringify(e)}`),e.type==="error"?i.cancel(vg(e)):i.resolve(vg(e)),!0):!1});h(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:gu(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1});this.label=i,this.transportId=a,f(this,Qd,e),f(this,Ui,e.getValue("logger")),this.channel=r,this.queue=new Map}};let di=kn;Wr=new WeakMap,Qd=new WeakMap,Ui=new WeakMap,h(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:H(D({},e.payload),{_bolt:{id:gu(8),type:"REQUEST",version:rd}})}}),h(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:H(D({},r.payload),{_bolt:{id:e,type:"RESPONSE",version:rd}})}}),h(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:H(D({},e.payload),{bolt:{id:gu(8),type:"NOTIFY",version:rd}})}}),h(di,"createErrorResponse",(e,r)=>({type:"error",payload:{error:r.message,_bolt:{id:e,type:"RESPONSE",version:rd}}}));const Ad="transport closed";var $i;const In=class extends Gl{constructor(e,{id:r,direction:i,handlerFactory:a,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:p,config:g}){var P,_,C;super(e);h(this,"awaitQueue");h(this,"observer");h(this,"id");h(this,"serverId");h(this,"direction");h(this,"maxSctpMessageSize");h(this,"handler");h(this,"connectionState","new");h(this,"producers");h(this,"consumers");h(this,"datachannels");h(this,"connected",!1);h(this,"eventsDCReadyPromise");h(this,"eventsDCReadyPromiseResolver");h(this,"eventsDCFailureTimer");h(this,"transportConnectionPromise");h(this,"consumerTrackEvents");h(this,"unknownTracksMap");h(this,"appData");m(this,$i,void 0);f(this,$i,e);const T=e.getValue("logger");T.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const v=GD(l,{});delete v.iceServers,delete v.iceTransportPolicy,delete v.bundlePolicy,delete v.rtcpMuxPolicy,delete v.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new Ju(T,!0),this.handler=a(),this.handler.enableHighBitrate=(P=g==null?void 0:g.enableHighBitrate)!=null?P:!1,this.handler.enableStereo=(_=g==null?void 0:g.enableStereo)!=null?_:!1,this.handler.enableDtx=(C=g==null?void 0:g.enableDtx)!=null?C:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=p||{},this.transportConnectionPromise=new Promise(w=>{this.once("connected",()=>{w(!0)}),this.once("disconnect",()=>{w(!1)}),this.once("close",()=>{w(!1)})}),this.eventsDCReadyPromise=new Promise(w=>{this.eventsDCReadyPromiseResolver=w}),this.handler.on("@connectionstatechange",w=>{w!==this.connectionState&&(this.logger.debug(`connection state changed to ${w}`),this.connectionState=w,w==="connected"&&(this.connected=!0,this.emit("connected")),w==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(w==="failed"||w==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",w))}),this.handler.on("@icecandidate",({candidate:w})=>{this.closed||this.safeEmit("icecandidate",w)}),this.handler.on("dc_open",w=>{let V=this.datachannels.get(w.label);V||(V||(V=new di(n(this,$i),w,w.label,this.serverId),this.datachannels.set(w.label,V)),this.eventsDCFailureTimer=setTimeout(()=>{w.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",w.label))},5e3))}),this.handler.on("datachannel",(w,V)=>{w.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const F=this.datachannels.get(w.label);if(!F){this.logger.error("unregistered datachannel for message",{rtcChannel:{label:w.label,message:V}});return}try{const N=JSON.parse(V);this.logger.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:N.id,count:N.count,chunkIndex:N.chunkIndex,chunk:N.chunk,transprtId:this.serverId}});const B=F.processMessage(N);if(!B)return;this.logger.debug(`datachannel message with id:${N.id} on transport:${this.serverId}complete - ${JSON.stringify(B)}`),this.emit(`datachannel:${w.label}`,F.label,B)}catch(N){this.logger.error("error parsing message",{error:N})}})}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(Ad).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(Ad)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}getStats(){return u(this,null,function*(){if(this.closed)throw new It("closed");return this.handler.getTransportStats()})}connect(e){return u(this,null,function*(){try{if(yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:r,callback:i}=yield this.handler.connect(),{transportId:a,answer:o}=yield e(r);this.setServerId(a),yield i(o)})),!(yield this.transportConnectionPromise))throw new Error("ice connection failed")}catch(r){throw this.logger.error("transport failed to connect:",{error:r}),r}})}restartIce(){return u(this,null,function*(){if(this.logger.debug("restartIce()"),this.closed)throw new It("closed");return this.handler.restartIce()})}canProduce(e){return u(this,null,function*(){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new Mo("not a sending Transport");if(r.readyState==="ended")throw new It("track ended");if(i&&typeof i!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!(yield this.transportConnectionPromise))throw new gi("transport not connected");return!0})}produce(e,r){return u(this,null,function*(){if(!(yield this.canProduce(e)))throw new Error("Cannot produce");const{track:a,encodings:o,codecOptions:c,stopTracks:d=!0,disableTrackOnPause:l=!0,zeroRtpOnPause:p=!1,appData:g={}}=e;this.logger.debug(`produce() [track:${a.id}]`);const{producerId:T,localId:v,rtpSender:P}=yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:_,callback:C,sender:w,mid:V}=yield this.handler.send({track:a,encodings:o,codecOptions:c,screenShare:g==null?void 0:g.screenShare}),{answer:F,producerId:N}=yield r({offer:_,kind:a.kind,paused:l?!a.enabled||Object.hasOwn(a,"fakeTracks"):!1,appData:H(D({},g||{}),{mid:V}),codecOptions:c,producingTransportId:this.serverId}),B=yield C(F);return{producerId:N,localId:B,rtpSender:w}}),"Transport.produce");return this.createProducerObject({id:T,localId:v,track:a,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:p,appData:g,handler:this.handler,rtpSender:P})})}createProducerObject(e){return u(this,null,function*(){const r=new JD(n(this,$i),e);return this.producers.set(r.id,r),r.once("close",()=>{this.producers.delete(r.id)}),this.emit("newproducer",r),r})}closeProducer(e){return u(this,null,function*(){yield this.awaitQueue.push(e.close.bind(e),"Transport.closeProducer")})}canConsume(){return u(this,null,function*(){if(this.closed)throw new It("closed");if(this.direction!=="recv")throw new Mo("not a receiving transport");if(!(yield this.transportConnectionPromise))throw new gi("transport not connected");return!0})}consume(e,r,i){return u(this,null,function*(){return this.awaitQueue.push(()=>u(this,null,function*(){const a={},{consumerStates:o,sessionDescription:c,failedProducers:d}=yield r(e);o.forEach((p,g)=>{a[g]=this.createConsumerObjectAndWaitForTrack(H(D({},p),{producerId:g}))}),c&&(this.logger.info("Session description found, sending negotiation request"),yield i(c));const l=[];return yield Promise.all(Object.entries(a).map(([p,g])=>g.then(T=>l.push(T)).catch(()=>{this.logger.error(`Failed to create consumer object, producer: ${p}`,{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=hs.parse(e.sdp),a={};return i.media.forEach(o=>{r.includes(o.mid.toString())&&(a[o.mid.toString()]={rtp:o.rtp,fmtp:o.fmtp,payloads:o.payloads,rtcpFb:o.rtcpFb})}),a}static setCodecAndFmtpMappings(e,r,i){const a=hs.parse(e.sdp);return a.media=a.media.map(c=>{if(r.includes(c.mid.toString())){const d=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}),H(D({},e),{sdp:hs.write(a)})}static parseHeaderExtensionMappings(e){const r=hs.parse(e.sdp),i={};return r.media.forEach(a=>{i[a.mid]=a.ext}),i}static setHeaderExtensionMappings(e,r){const i=hs.parse(e.sdp);return i.media=i.media.map(o=>{const c=D({},o);return c.ext=r[o.mid],c}),H(D({},e),{sdp:hs.write(i)})}closeConsumers(e,r){return u(this,null,function*(){try{const i=e.map(l=>l.transceiver.mid),a=In.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=In.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=yield this.handler.pc.createOffer();this.logger.info("Created offer for closing consumers",{sdp:c.sdp}),c=In.setCodecAndFmtpMappings(c,i,a),c=In.setHeaderExtensionMappings(c,o),this.logger.info("Updated codec and fmtp mappings in close consumer offer",{sdp:c.sdp}),yield this.setLocalDescription(c),this.logger.info("Successfully set local description in close consumers");const d=yield r(e,c);this.logger.info("Received answer in close consumers",{sdp:d.sdp}),yield 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})}})}setRemoteOffer(e){return u(this,null,function*(){try{this.logger.info("Received offer from SFU",{sdp:e.sdp}),yield this.setRemoteDescription(e);const r=yield this.handler.pc.createAnswer();this.logger.info("Created answer corresponding to received offer",{sdp:r.sdp});const i=hs.parse(r.sdp);return i.media=i.media.map(a=>{if(a.type==="audio"){const o=D({},a),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 a}),r.sdp=hs.write(i),this.logger.info("Setting munged SDP",{sdp:r.sdp}),yield 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 a=`${i.mid}:${r.kind}`;r.addEventListener("ended",()=>{this.logger.info(`rtc consumer track ended [trackId: ${r.id}]`),this.unknownTracksMap.delete(a)});const o=this.consumerTrackEvents.get(a);o?(o(r,i),this.consumerTrackEvents.delete(a)):(this.logger.warn(`track event handler not found ${a}`),this.unknownTracksMap.set(a,e))}sendErrorOverDC(e,r,i){const a=this.getDatachannel(e);if(!a)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});a.respond(r,i,!0)}sendResponseOverDC(e,r,i){const a=this.getDatachannel(e);if(!a)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});a.respond(r,i)}createConsumerObjectAndWaitForTrack(e){return u(this,null,function*(){const{consumerId:r,producerId:i,producingPeerId:a,producingTransportId:o,streamId:c,paused:d,screenShare:l,appData:p,kind:g,mimeType:T}=e,v=`${c}:${g}`,P=H(D({},e),{name:"consumer creation task error",message:"consumer creation failed"});return new Promise((_,C)=>u(this,null,function*(){const w=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${v} producingPeerId: ${a}`),this.consumerTrackEvents.delete(v),P.isTimedout=!0,C(P)},5e3),V=(N,B)=>{try{if(N.readyState==="ended")clearTimeout(w),C(P);else{const G=N;G.enabled=!0,this.handler.midTransceiverMap.set(B.mid,B);const re=new WD(n(this,$i),{id:r,localId:B.mid,transceiver:B,track:G,paused:d,producerId:i,producingPeerId:a,producingTransportId:o,handler:this.handler,appData:H(D({},p),{screenShare:l,peerId:a}),rtpReceiver:B.receiver,mimeType:T});this.consumers.set(r,re),re.once("close",()=>{this.consumers.delete(re.id),this.handler.midTransceiverMap.delete(B.mid)}),this.logger.info("consumer created for ",{consumer:{id:r,kind:g,appData:{screenShare:l},peerId:a,producerId:i}}),this.emit("newconsumer",re),clearTimeout(w),_(re)}}catch(G){this.logger.warn("error while creating consumer:",G),clearTimeout(w),C(P)}},F=this.unknownTracksMap.get(v);F?(this.logger.info(`track event already received [trackId: ${F.track.id}] [mid: ${F.transceiver.mid}]`),this.unknownTracksMap.delete(v),V(F.track,F.transceiver)):(this.logger.info(`Registering onTrack handler for key ${v} [producingPeerId: ${a}]`),this.consumerTrackEvents.set(v,V))}))})}setRemoteDescription(e){return u(this,null,function*(){yield this.handler.pc.setRemoteDescription(e)})}setLocalDescription(e){return u(this,null,function*(){this.logger.debug(`${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),yield this.handler.pc.setLocalDescription(e)})}sendDataChannelMessage(e,r){return u(this,null,function*(){const i=this.getDatachannel(e);if(!i)throw FD("DC_NOT_READY",`${e} datachannel not ready`);const a=(yield i.request(r)).payload;return this.logger.info(`sendDataChannelMessage::response ${JSON.stringify(a)}`),a})}};let zu=In;$i=new WeakMap;function YD(s){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){s.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return s.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=Kg.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")}var rr,Fi;class QD{constructor(t,{handlerName:e,handlerFactory:r}={}){h(this,"handlerFactory");m(this,rr,void 0);m(this,Fi,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),f(this,rr,t),f(this,Fi,i),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)n(this,Fi).debug(`Device::constructor() | handler given: ${e}`);else if(e=YD(n(this,Fi)),e)n(this,Fi).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=Hh.createFactory(n(this,rr));break;case"Safari12":this.handlerFactory=qh.createFactory(n(this,rr));break;case"Firefox60":this.handlerFactory=Id.createFactory(n(this,rr),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=Id.createFactory(n(this,rr),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=Tr.v4();return new zu(n(this,rr),H(D({id:e},t),{handlerFactory:this.handlerFactory}))}}rr=new WeakMap,Fi=new WeakMap;const XD=2e3;var Sa,at,ot,ic,nc,Bi,Ea,ac,Pa,Hi,xs,_a,md,oc,Yu,Xd,nT,cc,Qu,Zd,aT,el,oT,tl,cT,sl,dT,rl,lT,dc,Xu,lc,Zu;class ZD extends lt.EventEmitter{constructor(e,r){super();m(this,_a);m(this,oc);m(this,Xd);m(this,cc);m(this,Zd);m(this,el);m(this,tl);m(this,sl);m(this,rl);m(this,dc);m(this,lc);h(this,"context");m(this,Sa,void 0);m(this,at,void 0);m(this,ot,void 0);m(this,ic,void 0);m(this,nc,void 0);m(this,Bi,void 0);m(this,Ea,void 0);m(this,ac,void 0);m(this,Pa,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});m(this,Hi,void 0);m(this,xs,"all");this.context=e,f(this,Bi,r),f(this,Sa,new QD(e)),f(this,Ea,new jD(r)),f(this,ac,Cs),n(this,_a,md).mediaState={send:{state:Dn.NEW},recv:{state:Dn.NEW}},(xa(this.context,"forceRelay")||this.context.getValue("flagsmith").hasFeature(ee.FORCE_RELAY))&&f(this,xs,"relay"),this.logger.info(`ICE Transport Policy initially set to ${n(this,xs)}`),U(this,oc,Yu).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return n(this,Bi)}get socketHandler(){return n(this,Ea)}get sendTransport(){return n(this,at)}get recvTransport(){return n(this,ot)}get events(){return n(this,ac)}set sendTransportConnectedCallback(e){f(this,ic,e)}set recvTransportConnectedCallback(e){f(this,nc,e)}setupTransports(e){return u(this,null,function*(){yield U(this,Xd,nT).call(this,e);let r,i;e.send&&(r=U(this,cc,Qu).call(this,n(this,at)).then(a=>{try{n(this,ic).call(this,a)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=U(this,cc,Qu).call(this,n(this,ot)).then(a=>{try{n(this,nc).call(this,a)}catch(o){this.logger.error("Failed to run recv transport callback")}})),yield Promise.all([r,i])})}stopTransports(e){var r,i;if(e.send&&this.sendTransport!==void 0){const{id:a,serverId:o,direction:c}=n(this,at);this.logger.info("Closing send transport",{transport:{id:a,serverId:o,type:c}}),n(this,at).close(),n(this,at).removeAllListeners(),f(this,at,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:a,serverId:o,direction:c}=n(this,ot);this.logger.info("Closing recv transport",{transport:{id:a,serverId:o,type:c}}),(r=n(this,ot))==null||r.close(),(i=n(this,ot))==null||i.removeAllListeners(),f(this,ot,void 0)}U(this,oc,Yu).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}Sa=new WeakMap,at=new WeakMap,ot=new WeakMap,ic=new WeakMap,nc=new WeakMap,Bi=new WeakMap,Ea=new WeakMap,ac=new WeakMap,Pa=new WeakMap,Hi=new WeakMap,xs=new WeakMap,_a=new WeakSet,md=function(){return this.context.getValue("connectionHandler")},oc=new WeakSet,Yu=function(){f(this,Hi,{send:void 0,recv:void 0})},Xd=new WeakSet,nT=function(e){return u(this,null,function*(){var o,c,d,l,p,g,T,v;(xa(this.context,"forceRelay")||this.context.getValue("flagsmith").hasFeature(ee.FORCE_RELAY))&&f(this,xs,"relay"),this.logger.info(`ICE Transport Policy set to ${n(this,xs)}`);const a=yield dt().getICEServers().catch(P=>(this.logger.warn(`failed to get iceservers from server: ${P.message}`),[]));if(e.send){const P=this.context.getValue("flagsmith").hasFeature(ee.DISABLE_OPUS_DTX_CF);U(this,el,oT).call(this,{iceServers:a,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:(T=(g=(p=this.context.getValue("defaults").mediaConfiguration)==null?void 0:p.audio)==null?void 0:g.enableStereo)!=null?T:!1,enableDtx:!!P},iceTransportPolicy:n(this,xs)})}e.recv&&U(this,tl,cT).call(this,{iceServers:a,additionalSettings:{encodedInsertableStreams:(v=this.context.getValue("modules").e2ee)==null?void 0:v.enabled},iceTransportPolicy:n(this,xs)})})},cc=new WeakSet,Qu=function(e){return u(this,null,function*(){const{id:r,serverId:i,direction:a}=e;U(this,sl,dT).call(this,e);try{return yield tT((c,d)=>u(this,null,function*(){c>0&&this.logger.debug(`Retrying transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:a}});try{if(e.closed)throw new gi("Cannot reconnect closed transport");yield U(this,Zd,aT).call(this,e)}catch(l){if(l instanceof gi){d(l);return}throw this.logger.error("Failed to connect transport, retrying",{transport:e,error:l}),l}}),{delayTime:100,strategy:"exponential",maxRetryCount:1/0}),e}catch(o){throw this.logger.error(`Failed to connect send transport after retry: ${e.id}`,{error:o,transport:{id:r,serverId:i,type:a}}),e.close(),e.removeAllListeners(),o}})},Zd=new WeakSet,aT=function(e){return u(this,null,function*(){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!n(this,Bi).isConnected)throw new gi("Socket is not connected");if(e.connectionState==="closed")throw new gi("Transport is closed");try{yield e.connect(a=>U(this,rl,lT).call(this,i,a)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(a){throw n(this,Pa).transportFailureCount[i]+=1,a.message==="ice connection failed"?new gi(a.message):a}})},el=new WeakSet,oT=function(e){var r,i;if(n(this,at)&&n(this,at).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=n(this,at))==null?void 0:r.id,serverId:(i=n(this,at))==null?void 0:i.serverId,type:"send"}});return}f(this,at,n(this,Sa).createTransport(H(D({},e),{direction:"send"}))),this.context.getValue("callstats").configureSendTransport(n(this,at))},tl=new WeakSet,cT=function(e){var r,i;if(n(this,ot)&&n(this,ot).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=n(this,ot))==null?void 0:r.id,serverId:(i=n(this,ot))==null?void 0:i.serverId,type:"recv"}});return}f(this,ot,n(this,Sa).createTransport(H(D({},e),{direction:"recv"}))),this.context.getValue("callstats").configureRecvTransport(n(this,ot))},sl=new WeakSet,dT=function(e){const{direction:r,id:i}=e;e.on("connectionstatechange",a=>u(this,null,function*(){U(this,lc,Zu).call(this,{state:a,direction:r}),this.logger.info(`Transport connection state changed for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:a}});const o=()=>{const c=n(this,Hi)[r];c!==void 0&&(clearTimeout(c),n(this,Hi)[r]=void 0)};switch(a){case"connected":o(),n(this,Pa).lastConnectionTime=performance.now();break;case"disconnected":n(this,Hi)[r]=setTimeout(()=>u(this,null,function*(){this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),yield U(this,dc,Xu).call(this,e.direction)}),XD);break;case"failed":if(e.closed)return;o(),this.logger.warn(`${r} transport is in failed state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),yield U(this,dc,Xu).call(this,e.direction);break}})),e.on("icecandidate",a=>u(this,null,function*(){this.logger.debug("Sending iceCandidate:",{iceCandidate:a})})),e.on("datachannel:events",(a,o)=>u(this,null,function*(){var c,d;this.logger.debug("Got data channel message on event:",{rtcChannel:{label:a,message:o}});try{switch(o.type){case"handshake":{const l={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(a,zD(o),l);break}case"hub-disconnect":{this.logger.debug(`media hub disconnected, full_reconnect: ${(c=o.payload)==null?void 0:c.full_reconnect}`),((d=o.payload)==null?void 0:d.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":break;default:break}}catch(l){this.logger.error(`Unable to handle the incoming datachannel message on channel ${a}`)}})),e.on("dc_error",()=>{e.direction==="recv"&&(this.logger.warn("Events datachannel did not open in 5s",{country:E.location.country}),this.handleErrors("reconnectRecvTransport"))})},rl=new WeakSet,lT=function(e,r){return u(this,null,function*(){const i=e==="recv";try{const{sdp:a,type:o}=r,c={consuming:i,description:{sdp:a,type:o,target:i?yr.SUBSCRIBER:yr.PUBLISHER},producers:[]};return n(this,Ea).connectTransport(c)}catch(a){throw this.logger.error(`Error in ${e} transport connection:`,{error:a,country:E.location.country}),a}})},dc=new WeakSet,Xu=function(e){return u(this,null,function*(){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),this.context.getValue("flagsmith").hasFeature(ee.CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED)&&n(this,Bi).isConnected&&n(this,Pa).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),f(this,xs,"relay")),yield this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:n(this,at)}),this.context.getValue("peerSessionStore").emit(k.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:n(this,ot)}),this.context.getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}U(this,lc,Zu).call(this,{state:Dn.CONNECTED,direction:e})})},lc=new WeakSet,Zu=function(e){const{state:r,direction:i}=e;n(this,_a,md).mediaState[i]={state:r},this.context.getValue("peerSessionStore").emit(k.TRANSPORT_STATE_UPDATE,D({transport:i},n(this,_a,md).mediaState[i]))};var uc,rs;class eO{constructor(t,e,r,i,a){m(this,uc,void 0);m(this,rs,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=a,f(this,uc,t),f(this,rs,t.getValue("logger"))}create(t){return u(this,null,function*(){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:p,producingTransportId:g}=d,T=n(this,uc).getValue("flagsmith").hasFeature(ee.ENABLE_CF_SIMULCAST)?{simulcast:{preferredRid:"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}}:{};e.set(p,l),r.push(D({producingPeerId:l,producerId:p,producingTransportId:g},T))});const i=yield this.socketHandler.consume({requests:r,consumingTransportId:this.recvTransport.serverId}),a=new Map;t.forEach(d=>a.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const p=a.get(d);if(!p)return;if(l.errorCode){n(this,rs).warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),c.push(H(D({},p),{errorCode:l.errorCode}));return}let g={};try{g=JSON.parse(l.producerState.appData)}catch(T){}o.set(d,{consumerId:l.consumerId,producingTransportId:p.producingTransportId,producingPeerId:p.producingPeerId,kind:p.kind,paused:p.pause,streamId:l.producerTrack.streamId,trackId:l.producerTrack.trackId,screenShare:p.screenShare,mimeType:p.mimeType,appData:g})}),{consumerStates:o,sessionDescription:i.sessionDescription,failedProducers:c}})}negotiate(t){return u(this,null,function*(){try{n(this,rs).info("Negotiating socket consumer",{transport:this.recvTransport}),n(this,rs).debug(`setting remote offer: ${JSON.stringify(t)} on recvTransport`,{transport:this.recvTransport});const e=yield this.recvTransport.setRemoteOffer(t),r={transportId:this.recvTransport.serverId,description:{sdp:e.sdp,type:e.type,target:yr.SUBSCRIBER}};return n(this,rs).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),yield this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,xw.toBinary(r)),n(this,rs).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){n(this,rs).error("Failed to renegotiate",{error:e});return}})}close(t){return u(this,null,function*(){if(!t.length)return{};const e=(r,i)=>u(this,null,function*(){const a=r.map(l=>l.localId);n(this,rs).info(`Closing consumers: ${JSON.stringify(a)}`);const o={description:{sdp:i.sdp,type:i.type,target:yr.SUBSCRIBER},consumerIds:a,consumingTransportId:this.recvTransport.serverId},c=yield this.socketHandler.closeConsumer(o),d=lb.fromBinary(c).description;return{sdp:d.sdp,type:d.type}});return yield this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(t,e),"ConsumerStrategy.close",{consumersLength:t.length}),{}})}switchConsumersToLayer(t,e){return u(this,null,function*(){const r={requests:[],consumingTransportId:this.recvTransport.serverId},i=t.filter(a=>a&&a.id);i.forEach(({id:a,producingTransportId:o,localId:c})=>{r.requests.push({producerId:a,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),yield this.socketHandler.updateConsumersSimulcastConfig(r),n(this,rs).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:a})=>a)})})}}uc=new WeakMap,rs=new WeakMap;class jh{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return hs.parse(t).media.filter(a=>e==="video"?a.type==="video":a.type==="audio").at(-1).msid}create(c){return u(this,arguments,function*({offer:t,kind:e,paused:r,appData:i,codecOptions:a,producingTransportId:o}){var T,v;const d=jh.getMSIDFromSDP(t.sdp,e),l={description:{sdp:t.sdp,type:t.type,target:yr.PUBLISHER},paused:r,kind:e,msid:d,appData:JSON.stringify(i),screenShare:(T=i.screenShare)!=null?T:!1,mimeType:`${e}/${(v=a[0])==null?void 0:v.name}`,producingTransportId:o},{answer:p,producerId:g}=yield this.socketHandler.produce(l);return{answer:p,producerId:g}})}}var qi,Jr,Ca,hc,Us,il,ir,wa,pc,eh,nl,uT,al,hT,ol,pT,cl,gT;class tO extends ZD{constructor(e,r){super(e,r);m(this,pc);m(this,nl);m(this,al);m(this,ol);m(this,cl);m(this,qi,void 0);m(this,Jr,void 0);m(this,Ca,void 0);m(this,hc,void 0);m(this,Us,void 0);m(this,il,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});m(this,ir,[]);m(this,wa,void 0);this.context=e,this.sendTransportConnectedCallback=()=>u(this,null,function*(){f(this,hc,new jh(this.socketHandler))}),this.recvTransportConnectedCallback=i=>u(this,null,function*(){n(this,Ca).clear(),f(this,Us,new eO(this.context,this.events,i,this.socket,this.socketHandler))}),this.reset()}get socketHandler(){return super.socketHandler}get producers(){return n(this,qi)}get consumers(){return n(this,Jr)}get producerIdToConsumerIdMap(){return n(this,Ca)}get logger(){return this.context.getValue("logger")}reset(){f(this,qi,new Map),f(this,Jr,new Map),f(this,Ca,new Map)}createProducer(e,r){return u(this,null,function*(){var i;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const a=yield this.sendTransport.produce(e,U(this,nl,uT).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_PRODUCER,a),U(this,al,hT).call(this,a,r),a}catch(a){throw this.logger.error("Failed to create producer",{error:a}),n(this,il).producerCreationFailureCount+=1,a}})}closeProducer(e,r){return u(this,null,function*(){var a;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{yield this.sendTransport.closeProducer(i),(a=this.context.getValue("modules").e2ee)!=null&&a.enabled&&this.context.getValue("peerSessionStore").emit(k.E2EE_INACTIVE_PRODUCER,i)}catch(o){this.logger.error("Failed to close producer on server",{error:o,producer:i})}})}closeAllProducers(){return Promise.all(Array.from(n(this,qi).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}createConsumers(e){return u(this,null,function*(){n(this,wa)||clearTimeout(n(this,wa)),f(this,ir,n(this,ir).concat(e)),yield U(this,pc,eh).call(this)})}closeConsumer(e){return this.closeConsumers([e])}closeConsumers(e){return u(this,null,function*(){if(!n(this,Us))return;const r=e.map(a=>this.consumers.get(a)).filter(a=>a!==void 0);if(r.length===0)return;const{failedConsumers:i}=yield n(this,Us).close(r);i!=null&&i.length&&this.logger.warn("Failed to close some consumers",{consumerIds:i})})}closeAllConsumers(){return this.closeConsumers(Array.from(n(this,Jr).keys()))}switchConsumersToLayer(e,r){return u(this,null,function*(){n(this,Us).switchConsumersToLayer(e,r)})}}qi=new WeakMap,Jr=new WeakMap,Ca=new WeakMap,hc=new WeakMap,Us=new WeakMap,il=new WeakMap,ir=new WeakMap,wa=new WeakMap,pc=new WeakSet,eh=function(){return u(this,null,function*(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=n(this,ir).splice(0,n(this,ir).length);try{const i=new Set(Array.from(this.consumers.values()).map(({producerId:d})=>d)),a=r.filter(({producerId:d})=>!this.producers.get(d)&&!i.has(d));if(a.length===0)return;const{consumers:o,failedProducers:c}=yield this.recvTransport.consume(a,U(this,ol,pT).bind(this),n(this,Us).negotiate.bind(n(this,Us)));if(o.forEach(U(this,cl,gT).bind(this)),c!=null&&c.length){this.logger.error("Failed to create consumers for producers",{producers:c});const d=c.filter(({errorCode:l,producerId:p})=>l==="not_found_track_error"?(this.logger.error(`Track not found for producer: ${p}. This will not be retried.`),!1):l==="backend_error"?(this.logger.error("Unrecoverable error: backend error"),!1):!0);f(this,ir,n(this,ir).concat(d)),f(this,wa,setTimeout(U(this,pc,eh).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(a){}yield this.setupTransports({recv:!0})}}})},nl=new WeakSet,uT=function(e){return n(this,hc).create(e)},al=new WeakSet,hT=function(e,r){e.on("close",(i,a)=>u(this,null,function*(){const{offer:o,reason:c}=i;if(this.logger.info("producer::closing",{debuggingHint:c,producer:H(D({},e),{status:"closing"})}),c!==Ad){const d={producerId:e.id,description:{sdp:o.sdp,type:o.type,target:yr.PUBLISHER}};try{const l=yield this.socketHandler.closeProducer(d),p={sdp:l==null?void 0:l.sdp,type:l==null?void 0:l.type};this.logger.info("producer::closed",{producer:H(D({},e),{status:"closed"})}),a({answer:p})}catch(l){this.logger.error("producer close error",l)}}this.producers.delete(e.id),r()})),e.on("trackended",()=>{this.logger.info("producer::trackended",{producer:H(D({},e),{status:"UNKNOWN"})})}),n(this,qi).set(e.id,e)},ol=new WeakSet,pT=function(e){return u(this,null,function*(){try{return yield this.recvTransport.canConsume(),yield n(this,Us).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}})},cl=new WeakSet,gT=function(e){e.on("close",r=>u(this,null,function*(){this.logger.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),n(this,Jr).delete(e.id),this.context.getValue("peerSessionStore").emit(k.CONSUMER_CLOSED,{id:e.id})})),n(this,Jr).set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),this.context.getValue("peerSessionStore").emit(k.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId})};var gc,mc,fc,Ra,ba,ka,Tc,vc,Ia,Rt,vs,ys,ji,Gi,nr,yc,dl,mT,ll,fT,ul,TT,hl,vT;const pl=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:a=.95,voiceAdaptationRate:o=.99,minEnergyThreshold:c=.005,maxEnergyThreshold:d=.2,energyRatioThreshold:l=1.5,noiseHistorySize:p=50}={}){m(this,dl);m(this,ll);m(this,gc,void 0);m(this,mc,void 0);m(this,fc,void 0);m(this,Ra,void 0);m(this,ba,void 0);m(this,ka,void 0);m(this,Tc,void 0);m(this,vc,void 0);m(this,Ia,void 0);m(this,Rt,void 0);m(this,vs,void 0);m(this,ys,!1);m(this,ji,0);m(this,Gi,0);m(this,nr,[]);m(this,yc,void 0);f(this,Ra,t),f(this,Rt,t),f(this,gc,e),f(this,mc,r),f(this,fc,i),f(this,ba,a),f(this,ka,o),f(this,Tc,c),f(this,vc,d),f(this,Ia,l),f(this,yc,p),f(this,vs,t/2)}get voiceDetected(){return n(this,ys)}processAudioChunk(t){var o,c;const e=U(o=pl,ul,TT).call(o,t),r=U(c=pl,hl,vT).call(c,t);return U(this,dl,mT).call(this,e),e/n(this,vs)>n(this,Ia)&&e>n(this,Rt)&&r>n(this,gc)?(f(this,ji,n(this,ji)+1),f(this,Gi,n(this,fc)),n(this,ji)>=n(this,mc)&&f(this,ys,!0)):(f(this,ji,0),n(this,Gi)>0?f(this,Gi,n(this,Gi)-1):n(this,ys)&&f(this,ys,!1),n(this,ys)||U(this,ll,fT).call(this,e)),{energy:e,isVoice:n(this,ys)}}reset(){f(this,ys,!1),f(this,ji,0),f(this,Gi,0),f(this,Rt,n(this,Ra)),f(this,vs,n(this,Ra)/2),f(this,nr,[])}getThresholdInfo(){return{currentEnergyThreshold:n(this,Rt),backgroundNoiseEnergy:n(this,vs),energyRatioThreshold:n(this,Ia)}}};let mo=pl;gc=new WeakMap,mc=new WeakMap,fc=new WeakMap,Ra=new WeakMap,ba=new WeakMap,ka=new WeakMap,Tc=new WeakMap,vc=new WeakMap,Ia=new WeakMap,Rt=new WeakMap,vs=new WeakMap,ys=new WeakMap,ji=new WeakMap,Gi=new WeakMap,nr=new WeakMap,yc=new WeakMap,dl=new WeakSet,mT=function(t){n(this,ys)?f(this,Rt,n(this,ka)*n(this,Rt)+(1-n(this,ka))*t):f(this,Rt,n(this,ba)*n(this,Rt)+(1-n(this,ba))*n(this,vs)),f(this,Rt,Math.max(n(this,Tc),Math.min(n(this,vc),n(this,Rt))))},ll=new WeakSet,fT=function(t){if(t<n(this,Rt)*1.2)if(n(this,nr).push(t),n(this,nr).length>n(this,yc)&&n(this,nr).shift(),n(this,nr).length>=10){const e=[...n(this,nr)].sort((i,a)=>i-a),r=Math.floor(e.length/2);f(this,vs,e[r])}else f(this,vs,.95*n(this,vs)+.05*t)},ul=new WeakSet,TT=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},hl=new WeakSet,vT=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(mo,ul),m(mo,hl);var Sc;class yg{constructor(t){h(this,"RNAudioSampleHandler");m(this,Sc,void 0);f(this,Sc,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 n(this,Sc).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()}}Sc=new WeakMap;var Ec;class Sg{constructor(t){h(this,"audioContext");h(this,"analyser");m(this,Ec,void 0);f(this,Ec,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return n(this,Ec).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)}}Ec=new WeakMap;class sO{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 rO=60,iO=400;var ar,or,Ss,Pc,Wi,Aa,cr,Kr,Ma,dr,lr,$s,gl,yT,_c,th,ml,ST,fl,ET;const wo=class{constructor(t,e){m(this,gl);m(this,ml);m(this,ar,void 0);m(this,or,void 0);m(this,Ss,void 0);m(this,Pc,void 0);m(this,Wi,void 0);m(this,Aa,void 0);m(this,cr,void 0);m(this,Kr,void 0);m(this,Ma,void 0);m(this,dr,void 0);m(this,lr,void 0);m(this,$s,void 0);this.reportRequest=e,f(this,dr,t),f(this,Aa,new mo);const{isReactNative:r}=navigator;f(this,lr,r?new yg(n(this,dr)):new Sg(n(this,dr))),f(this,$s,r?sO:id)}get logger(){return n(this,dr).getValue("logger")}set producerId(t){f(this,Ss,t)}set audioTrack(t){f(this,Pc,t),n(this,lr)instanceof Sg&&(n(this,lr).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${n(this,Ss)}`),n(this,ar)&&n(this,$s).clearInterval(n(this,ar)),f(this,ar,n(this,$s).setInterval(()=>u(this,null,function*(){var i;if(!n(this,Pc)||!n(this,Ss))return;const{energy:t}=U(this,gl,yT).call(this),e=U(i=wo,_c,th).call(i,t);let r=.9;n(this,Ma)!==e&&n(this,Ma)?r=.9:e?r=.3:r=.5,f(this,Wi,(n(this,Wi)||0)*(1-r)+t*r)}),rO)),n(this,or)&&n(this,$s).clearInterval(n(this,or)),f(this,or,n(this,$s).setInterval(U(this,ml,ST).bind(this),iO))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${n(this,Ss)}`),n(this,ar)&&(n(this,$s).clearInterval(n(this,ar)),f(this,ar,void 0)),n(this,or)&&(n(this,$s).clearInterval(n(this,or)),f(this,or,void 0))}catch(t){}n(this,Aa).reset(),n(this,lr)instanceof yg&&n(this,lr).stop()}};let fo=wo;ar=new WeakMap,or=new WeakMap,Ss=new WeakMap,Pc=new WeakMap,Wi=new WeakMap,Aa=new WeakMap,cr=new WeakMap,Kr=new WeakMap,Ma=new WeakMap,dr=new WeakMap,lr=new WeakMap,$s=new WeakMap,gl=new WeakSet,yT=function(){var o;const{samples:t}=n(this,lr),{energy:e,isVoice:r}=n(this,Aa).processAudioChunk(t),i=U(o=wo,fl,ET).call(o,e);return n(this,dr).getValue("flagsmith").hasFeature(ee.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: producer: ${n(this,Ss)}, energy: ${n(this,Wi)},
11
11
  slogScale: ${i}, isVoice: ${r}, minEnergy: ${n(this,cr)},
12
12
  maxEnergy: ${n(this,Kr)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!n(this,cr)||i<n(this,cr))&&f(this,cr,i),(!n(this,Kr)||i>n(this,Kr))&&f(this,Kr,i),{energy:(i-n(this,cr))/(n(this,Kr)-n(this,cr))*10||0,isVoice:r})},_c=new WeakSet,th=function(t){return t<5},ml=new WeakSet,ST=function(t=n(this,Wi)){var r;if(!n(this,Ss)||!t){n(this,dr).getValue("flagsmith").hasFeature(ee.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${n(this,Ss)}`);return}const e={producerId:n(this,Ss),energy:Math.round(t),silent:U(r=wo,_c,th).call(r,t)};f(this,Ma,e.silent),this.reportRequest(e)},fl=new WeakSet,ET=function(t){const e=Math.log10(t);return Math.round(e)},m(fo,_c),m(fo,fl);const nO=(s=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const e=new window.MediaStreamTrackGenerator({kind:"audio"}),r=e.writable.getWriter(),i=48e3,a=128,o=1;let c=0,d=null;const l=()=>u(exports,null,function*(){try{const T=new Float32Array(a*o),v=new window.AudioData({format:"f32",sampleRate:i,numberOfFrames:a,numberOfChannels:o,timestamp:c,data:T});c+=a/i*1e6,yield r.ready,yield r.write(v)}catch(T){d&&clearInterval(d),r.releaseLock(),e.writable.abort()}});d=window.setInterval(l,100);const g=new MediaStream([e]).getAudioTracks()[0];return g.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),e.writable.abort()}),Object.assign(g,{fakeTracks:"fakeTracks:fakeAudioTrack"}),g.enabled=s,g}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 a=e.createMediaStreamDestination();i.connect(a),r.start();const o=a.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=s,o):void 0}catch(e){return}},aO=(s=!1)=>{var a,o;const t=new MediaStream().getVideoTracks()[0],e=document.createElement("canvas");e.height=(a=t==null?void 0:t.getSettings().height)!=null?a: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 oO=Object.defineProperty,cO=Object.getOwnPropertyDescriptor,de=(s,t,e,r)=>{for(var i=r>1?void 0:r?cO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&oO(t,e,i),i};const Ot=["video/VP9","video/VP8"];var Cc,wc,ct,W,Da,vt,Ji,Ki,zi,Rc,is,ur,bc,Yi,Qi,yt,bt,zr,Pn,Tl,_T,vl,CT,yl,wT,kc,sh,Sl,mu,RT,El,bT,Pl,kT,_l,IT,Ze,pt,Xi,To,Cl,AT,wl,MT,Rl,DT;const PT=(mu=class{constructor(s,t){m(this,zr);m(this,Tl);m(this,vl);m(this,yl);m(this,kc);m(this,El);m(this,Pl);m(this,_l);m(this,Ze);m(this,Xi);m(this,Cl);m(this,wl);m(this,Rl);h(this,"context");h(this,"authToken");h(this,"e2ee");m(this,Cc,void 0);m(this,wc,void 0);m(this,ct,void 0);m(this,W,void 0);m(this,Da,void 0);m(this,vt,void 0);m(this,Ji,void 0);m(this,Ki,void 0);m(this,zi,void 0);m(this,Rc,void 0);m(this,is,null);m(this,ur,void 0);m(this,bc,void 0);m(this,Yi,void 0);m(this,Qi,void 0);m(this,yt,void 0);m(this,bt,void 0);var r,i;this.context=s;const{socket:e}=t;this.mediaJoined=!1,f(this,Yi,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,Qi,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,ct,e),f(this,Ji,!1),f(this,W,new tO(s,e)),f(this,vt,n(this,W).events),f(this,ur,new Set),f(this,yt,new Map),f(this,Ki,!1),f(this,zi,new Ju(s.getValue("logger"))),f(this,bt,new fo(this.context,n(this,W).socketHandler.audioActivity.bind(n(this,W).socketHandler))),this.e2ee=(i=(r=s.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?i:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,Rc,kh(()=>u(this,null,function*(){if(!n(this,zr,Pn).mediaJoinAttempted)return;const{roomJoined:a}=yield this.joinRoom(n(this,wc),n(this,Cc),!0,!0);a&&(this.context.getValue("peerSessionStore").emit(k.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(k.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return n(this,zr,Pn).mediaJoined}set mediaJoined(s){n(this,zr,Pn).mediaJoined=s}reset(){n(this,W).closeAllProducers(),n(this,W).closeAllConsumers(),n(this,yt).clear(),n(this,ur).clear(),f(this,is,null),n(this,zi).stop(),n(this,W).stopAllTransports(),n(this,W).reset(),f(this,zi,new Ju)}joinRoom(a,o){return u(this,arguments,function*(s,t,e=!1,r=!1,i={}){n(this,zr,Pn).mediaJoinAttempted=!0,f(this,Ji,!0),e&&this.reset();try{return yield n(this,zi).push(()=>U(this,Tl,_T).call(this,s,t,r,i),"joinRoom")}catch(c){return this.logger.error("Error in room joining process",{error:c}),this.context.getValue("peerSessionStore").emit(k.ROOM_NODE_FAILED),{roomJoined:!1}}})}initializeConnection(i,a){return u(this,arguments,function*(s,t,e=!1,r={}){return n(this,is)?n(this,is):(f(this,is,(()=>u(this,null,function*(){try{yield U(this,kc,sh).call(this,s,t,e,r)}catch(o){throw f(this,is,null),o}}))()),n(this,is))})}getConsumers(){return n(this,W).consumers}getProducers(){return n(this,W).producers}leaveRoom(){return u(this,null,function*(){n(this,W).stopAllTransports(),f(this,Ki,!1),n(this,zr,Pn).mediaJoinAttempted=!1;const s={closeRoom:!1};n(this,ct).sendMessagePromise(n(this,vt).leaveRoom,cR.toBinary(s)).then(e=>{var r;(r=YR.fromBinary(e.payload))!=null&&r.closed&&this.logger.warn("Weird state on peer closed and should not happen")}).catch(e=>{this.logger.error("error on sending leave room request",{error:e})}),this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct()})}activatePeers(s){return u(this,null,function*(){return this.createConsumers(s)})}createConsumers(s){return u(this,null,function*(){return s.length===0?Promise.resolve():n(this,W).createConsumers(s)})}closeConsumers(s){return u(this,null,function*(){if(!s.length)return;const t=s.reduce((e,r)=>{const i=n(this,W).producerIdToConsumerIdMap.get(r.producerId);return i?(e.push(i),e):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),e)},[]);yield n(this,W).closeConsumers(t)})}_shareWebcam(s,t){return u(this,null,function*(){var g,T;const e=t==="video/VP9"?he.WEBCAM:he.WEBCAM_BACKUP,r=U(this,Ze,pt).call(this,e);if(r){const v=yield r;if(n(this,W).producers.has(v)){const P=n(this,W).producers.get(v);if(!P.closed)return yield P.replaceTrack({track:s}),yield this.resumeWebcam(e),s;yield this.disableWebcam(t)}return this._shareWebcam(s,t)}const i=[t].concat(Ot.filter(v=>v!==t)),a=U(this,Rl,DT).call(this,s,i),o=xa(this.context,"disableSimulcast"),c=(T=(g=this.context)==null?void 0:g.getValue("overrides"))==null?void 0:T.simulcastConfig;!(o||c&&c.disable)&&this.context.getValue("flagsmith").hasFeature(ee.ENABLE_CF_SIMULCAST)?(this.logger.info("Simulcast enabled for SFU: CF"),a.encodings=J0(this.context,s)):this.logger.info("Simulcast disabled for webcam producer, SFU: CF"),this.context.getValue("flagsmith").hasFeature(ee.TRACK_HINT)&&(a.track.contentHint=this.context.getValue("flagsmith").getValue(ee.TRACK_HINT));const l=()=>{this.logger.info("Disabling video due to the producer closure"),n(this,yt).delete(e)},p=n(this,W).createProducer(a,l);return U(this,Xi,To).call(this,e,p.then(v=>v.id)),p.then(v=>v.track)})}shareWebcam(s){return u(this,null,function*(){var r;if(s===void 0)return null;const t=(r=this.context.getValue("flagsmith").getValue(ee.FORCE_VIDEO_CODEC))==null?void 0:r.toString();if(t)return this.logger.debug(`Calling _shareWebcam with forced video codec: ${t}`),this._shareWebcam(s,t);const e=Ot.filter(i=>{var a,o;return((o=(a=n(this,Da).sender)==null?void 0:a.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===i))>=0&&n(this,Qi).get(i).size>0});return e.length===0&&e.push(Ot[0]),yield Promise.all(e.map(i=>(this.logger.debug(`Calling _shareWebcam with video codec: ${i}`),this._shareWebcam(s,i)))),s})}shareScreen(s){return u(this,null,function*(){const{video:t,audio:e}=s;if(t===void 0)return;const r={track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Se.isElectron()},stopTracks:!1},i=()=>{this.logger.info("Disabling screenShare due to the producer closure"),n(this,yt).delete(he.SCREENSHARE_VIDEO),n(this,yt).delete(he.SCREENSHARE_AUDIO)},a=n(this,W).createProducer(r,i);U(this,Xi,To).call(this,he.SCREENSHARE_VIDEO,a.then(c=>c.id));let o;if(e){const c={track:e,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Se.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},d=()=>{};o=n(this,W).createProducer(c,d),U(this,Xi,To).call(this,he.SCREENSHARE_AUDIO,o.then(l=>l.id))}yield Promise.all([a,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()})}shareMic(s){return u(this,null,function*(){try{if(s===void 0)throw new It("track undefined");const t=U(this,Ze,pt).call(this,he.MIC);if(t){const a=yield t;if(n(this,W).producers.has(a)){const o=n(this,W).producers.get(a);if(!o.closed){yield o.replaceTrack({track:s}),yield this.resumeMic(),n(this,bt)&&(n(this,bt).audioTrack=s,n(this,bt).producerId=a,n(this,bt).start());return}yield n(this,W).closeProducer(a,{stopTrack:!1})}yield this.shareMic(s);return}const e=U(this,wl,MT).call(this,s),r=()=>{n(this,yt).delete(he.MIC)},i=n(this,W).createProducer(e,r);U(this,Xi,To).call(this,he.MIC,i.then(a=>a.id)),yield i.then(a=>{n(this,bt)&&(n(this,bt).audioTrack=a.track,n(this,bt).producerId=a.id,n(this,bt).start())})}catch(t){throw new b(t)}})}pauseMic(){return u(this,null,function*(){var r;const s=yield U(this,Ze,pt).call(this,he.MIC),t=n(this,W).producers.get(s);if(!t){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}t.pause(),(r=n(this,bt))==null||r.stop();const e={producerId:t.id,pause:!0};n(this,ct).sendMessage(n(this,vt).toggleProducer,Qc.toBinary(e))})}pauseWebcam(){return u(this,null,function*(){const s=yield U(this,Ze,pt).call(this,he.WEBCAM),t=yield U(this,Ze,pt).call(this,he.WEBCAM_BACKUP),e=n(this,W).producers.get(s),r=n(this,W).producers.get(t);if(!e&&!r){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const i=a=>{const o={producerId:a.id,pause:!0};n(this,ct).sendMessage(n(this,vt).toggleProducer,Qc.toBinary(o))};e&&(e.pause(),i(e)),r&&(r.pause(),i(r))})}resumeMic(){return u(this,null,function*(){const s=yield U(this,Ze,pt).call(this,he.MIC),t=n(this,W).producers.get(s);if(!t){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};n(this,ct).sendMessage(n(this,vt).toggleProducer,Qc.toBinary(e))})}resumeWebcam(){return u(this,arguments,function*(s=he.WEBCAM){const t=yield U(this,Ze,pt).call(this,s),e=n(this,W).producers.get(t);if(!e){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!e.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};n(this,ct).sendMessage(n(this,vt).toggleProducer,Qc.toBinary(r))})}disableWebcam(s){return u(this,null,function*(){const t=s==="video/VP9"?he.WEBCAM:he.WEBCAM_BACKUP,e=yield U(this,Ze,pt).call(this,t);U(this,Cl,AT).call(this,t),e&&(yield n(this,W).closeProducer(e))})}disableMic(){return u(this,null,function*(){var t;const s=yield U(this,Ze,pt).call(this,he.MIC);s&&(yield n(this,W).closeProducer(s)),(t=n(this,bt))==null||t.stop(),n(this,yt).delete(he.MIC)})}disableScreenShare(){return u(this,null,function*(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=yield U(this,Ze,pt).call(this,he.SCREENSHARE_VIDEO),t=yield U(this,Ze,pt).call(this,he.SCREENSHARE_AUDIO);s&&(yield n(this,W).closeProducer(s)),t&&(yield n(this,W).closeProducer(t)),n(this,ur).clear(),n(this,yt).delete(he.SCREENSHARE_VIDEO),n(this,yt).delete(he.SCREENSHARE_AUDIO)})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}resetVideoProducers(s,t){return u(this,null,function*(){if(s){const e=yield U(this,Ze,pt).call(this,he.WEBCAM),r=yield U(this,Ze,pt).call(this,he.WEBCAM_BACKUP);yield n(this,W).closeProducer(e,{stopTrack:!1}),yield n(this,W).closeProducer(r,{stopTrack:!1}),this.shareWebcam(s)}if(t){const e=yield U(this,Ze,pt).call(this,he.SCREENSHARE_VIDEO);yield n(this,W).closeProducer(e,{stopTrack:!1}),this.shareScreen({video:t})}})}changeDisplayName(s,t){return u(this,null,function*(){const e={displayName:s,participantId:t!=null?t:this.peerId};if(!(yield n(this,W).socketHandler.changeDisplayName(e)))throw new Error("failed to change display name!")})}kick(s){const t={peerIds:[s]};n(this,W).socketHandler.kickPeer(t)}kickAll(){n(this,W).socketHandler.kickAll()}muteAll(s){return u(this,null,function*(){if(!(yield n(this,W).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield n(this,W).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(s){return u(this,null,function*(){if(!(yield n(this,W).socketHandler.hostControlForPeer(s,"audio")))throw new Error("failed to mute given participant")})}disableVideo(s){return u(this,null,function*(){if(!(yield n(this,W).socketHandler.hostControlForPeer(s,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(s){return u(this,null,function*(){const t={participantId:s!=null?s:""};try{yield n(this,ct).sendMessagePromise(n(this,vt).globalPinPeer,PR.toBinary(t))}catch(e){this.logger.error("Error in pinning peer:",{error:e})}})}validateScreenShare(s){return this.peerId===s.peerId&&n(this,W).producers.get(s.producerId)&&n(this,ur).add(s.consumerPeerId),n(this,ur).size}switchConsumersToLayer(s,t){return u(this,null,function*(){const e=s.map(r=>this.getConsumers().get(r));n(this,W).switchConsumersToLayer(e,t)})}handleSocketEvents(){return u(this,null,function*(){n(this,ct).on(n(this,vt).peerProducerCreateBroadcast,({payload:s})=>{var t,e;if(this.mediaJoined)try{const{participantId:r,producerState:i}=Rb.fromBinary(s);if(r===this.peerId)return;if(i!=null&&i.mimeType||(i.mimeType=i.kind===Fs.AUDIO?"audio/opus":"video/VP8"),i.kind===Fs.VIDEO&&!i.screenShare&&((e=(t=n(this,Da).receiver)==null?void 0:t.video)==null?void 0:e.codecs.findIndex(a=>a.mimeType===Ot[0]))>=0&&n(this,Yi).get(Ot[0]).has(r)&&i.mimeType!==Ot[0]){this.logger.warn(`Ignoring producer: ${i.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${i}`),this.context.getValue("peerSessionStore").emit(k.NEW_PRODUCER,{peerId:r,producer:H(D({},i),{kind:i.kind===Fs.AUDIO?"audio":"video",producingPeerId:r})})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),n(this,ct).on(n(this,vt).peerProducerToggleBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,initiatorParticipantId:e,producerState:{kind:r,pause:i,producerId:a,screenShare:o}}=Jp.fromBinary(s);if(o)return;const c=r===Fs.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${t}, producerId: ${a}, kind:${c}, paused:${i} payload: ${JSON.stringify(Jp.fromBinary(s))}`),t===this.peerId&&e!==this.peerId&&i&&this.context.getValue("peerSessionStore").emit(c==="audio"?k.MUTE_SELF:k.MUTE_SELF_VIDEO),t===this.peerId)return;this.context.getValue("peerSessionStore").emit(k.PRODUCER_TOGGLE,{peerId:t,producerId:a,paused:i,kind:c}),Array.from(this.getConsumers().values()).filter(l=>l.producerId===a).forEach(l=>{l.kind==="video"&&i||l.paused!==i&&(this.logger.debug(`consumer state mismatched for ${l.id}. updating consumer pause state ${l.paused} to ${i}`),i?(l.pause(),this.context.getValue("peerSessionStore").emit(k.CONSUMER_PAUSED,{id:l.id})):(l.resume(),this.context.getValue("peerSessionStore").emit(k.CONSUMER_RESUMED,{id:l.id})))})}catch(t){this.logger.error("error in producer toggle broadcast handler",{error:t})}}),n(this,ct).on(n(this,vt).peerLeaveBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t}=bu.fromBinary(s);if(t===this.peerId)return;this.logger.info(`peer left broadcast:${t}`),n(this,ur).delete(t),n(this,W).consumers.forEach(e=>{e.peerId===t&&e.close()}),this.context.getValue("peerSessionStore").emit(k.PEER_CLOSED,{id:t})}catch(t){this.logger.error("error in peer left broadcast",{error:t})}}),n(this,ct).on(n(this,vt).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=Ib.fromBinary(s);if(t===this.peerId)return;this.logger.info(`producer closed broadcast:${t}`),this.context.getValue("peerSessionStore").emit(k.PRODUCER_CLOSED,{peerId:t,producerId:e});const r=n(this,W).producerIdToConsumerIdMap.get(e);if(!r){this.logger.warn(`no consumer found for producer:${e}`);return}this.logger.info(`closing consumer ${r}, producer id: ${e}`),n(this,W).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),n(this,W).producerIdToConsumerIdMap.delete(e),this.context.getValue("peerSessionStore").emit(k.CONSUMER_CLOSED,{id:r})}).catch(i=>{this.logger.error("error closing consumer",{error:i})})}catch(t){this.logger.error("error on producer close broadcast",{error:t})}}),n(this,ct).on(n(this,vt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!n(this,Ji)&&!n(this,Ki)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(k.ROOM_NODE_DISCONNECTED),n(this,Rc).call(this))})})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(s=>{s.forEach((t,e)=>{const r=n(this,W).consumers.get(e);r&&this.context.getValue("peerSessionStore").emit(k.CONSUMER_SCORE_UPDATE,{id:e,kind:r.kind,peerId:r.peerId,score:t.score,scoreStats:t})})}),this.context.getValue("callstats").onProducerScore(s=>{s.forEach((t,e)=>{const r=Array.from(n(this,W).producers.values()).find(i=>i.id===e);r&&this.context.getValue("peerSessionStore").emit(k.PRODUCER_SCORE_UPDATE,{id:e,kind:r.kind,appData:r.appData,score:t.score,scoreStats:t})})})}handlePeerCapabilities(s,t){var e,r,i,a;for(let o=0;o<=Ot.length;o+=1){const c=Ot[o];if(((r=(e=t==null?void 0:t.receiver)==null?void 0:e.video)==null?void 0:r.codecs.findIndex(d=>d.mimeType===c))>=0||o===Ot.length-1){n(this,Qi).get(c).add(s);break}}for(let o=0;o<=Ot.length;o+=1){const c=Ot[o];if(((a=(i=t==null?void 0:t.sender)==null?void 0:i.video)==null?void 0:a.codecs.findIndex(d=>d.mimeType===c))>=0||o===Ot.length-1){n(this,Yi).get(c).add(s);break}}}handlePeerLeaving(s){this.context.getValue("flagsmith").hasFeature(ee.FORCE_VIDEO_CODEC)||(n(this,Yi).forEach(t=>t.delete(s)),n(this,Qi).forEach((t,e)=>{t.delete(s),!(t.size!==0||e===Ot[0])&&this.disableWebcam(e)}))}},Cc=new WeakMap,wc=new WeakMap,ct=new WeakMap,W=new WeakMap,Da=new WeakMap,vt=new WeakMap,Ji=new WeakMap,Ki=new WeakMap,zi=new WeakMap,Rc=new WeakMap,is=new WeakMap,ur=new WeakMap,bc=new WeakMap,Yi=new WeakMap,Qi=new WeakMap,yt=new WeakMap,bt=new WeakMap,zr=new WeakSet,Pn=function(){return this.context.getValue("connectionHandler")},Tl=new WeakSet,_T=function(s,t,e,r){return u(this,null,function*(){f(this,wc,s);try{return n(this,is)?yield n(this,is):yield U(this,kc,sh).call(this,s,t,e,r),U(this,yl,wT).call(this,t),{roomJoined:yield U(this,vl,CT).call(this)}}catch(i){return this.logger.error("Failed to complete room join",{error:i}),{roomJoined:!1}}finally{f(this,is,null)}})},vl=new WeakSet,CT=function(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:s}=yield n(this,W).socketHandler.notifySelfJoinComplete();return f(this,Cc,s.roomUuid),f(this,Ki,!0),f(this,Ji,!1),!0}catch(s){return this.logger.error("Error completing room join",{error:s}),this.mediaJoined=!1,!1}})},yl=new WeakSet,wT=function(s){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:H(D({},Se.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(e)}catch(t){this.logger.error("Error reporting room joined analytics",{error:t})}},0)},kc=new WeakSet,sh=function(s,t,e,r){return u(this,null,function*(){var i,a;try{(a=n(this,bc))!=null||f(this,bc,U(i=PT,Sl,RT).call(i));const o=U(this,El,bT).call(this);yield U(this,Pl,kT).call(this,s,t,e,o),yield n(this,W).setupTransports({send:!0,recv:!0}),yield U(this,_l,IT).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}})},Sl=new WeakSet,RT=function(){const{ipInfo:s}=dt();if(!(s!=null&&s.loc))return;const[t,e]=s.loc.split(",").map(parseFloat);return{latitude:t,longitude:e}},El=new WeakSet,bT=function(){var e;const s=(e=this.context.getValue("flagsmith").getValue(ee.FORCE_VIDEO_CODEC))==null?void 0:e.toString(),t=qD(s);return f(this,Da,t),t},Pl=new WeakSet,kT=function(s,t,e,r){return u(this,null,function*(){yield tT((i,a)=>u(this,null,function*(){if(!n(this,ct).isConnected){a(new Error("Socket is not connected"));return}i>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${i}`});try{yield n(this,W).socketHandler.joinRoom(t,s,r,e,n(this,bc))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:1/0})})},_l=new WeakSet,IT=function(s){return u(this,null,function*(){if(!(!this.context.getValue("flagsmith").hasFeature(ee.PRECREATE_PRODUCERS)||!s))try{const e=[];if(s.canProduceVideo===j.Allowed&&e.push(this.shareWebcam(aO(!1))),s.canProduceAudio===j.Allowed){const r=nO(!1);r&&e.push(this.shareMic(r))}e.length>0&&(yield Promise.all(e))}catch(e){this.logger.warn("Failed to precreate producers",{error:e})}})},Ze=new WeakSet,pt=function(s){return n(this,yt).get(s)},Xi=new WeakSet,To=function(s,t){return n(this,yt).set(s,t)},Cl=new WeakSet,AT=function(s){return n(this,yt).delete(s)},wl=new WeakSet,MT=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},Rl=new WeakSet,DT=function(s,t){return{track:s,codecOptions:t?t.map(e=>({name:e.split("/")[1]})):[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},m(mu,Sl),mu);let ae=PT;de([E.trace("MediaNodeClient.reset",{country:E.location.country})],ae.prototype,"reset",1);de([E.trace("MediaNodeClient.joinRoom")],ae.prototype,"joinRoom",1);de([E.trace("MediaNodeClient.leaveRoom")],ae.prototype,"leaveRoom",1);de([E.trace("MediaNodeClient.activatePeers")],ae.prototype,"activatePeers",1);de([E.trace("MediaNodeClient.createConsumers")],ae.prototype,"createConsumers",1);de([E.trace("MediaNodeClient.closeConsumers")],ae.prototype,"closeConsumers",1);de([E.trace("MediaNodeClient._shareWebcam")],ae.prototype,"_shareWebcam",1);de([E.trace("MediaNodeClient.shareWebcam")],ae.prototype,"shareWebcam",1);de([E.trace("MediaNodeClient.shareScreen")],ae.prototype,"shareScreen",1);de([E.trace("MediaNodeClient.shareMic")],ae.prototype,"shareMic",1);de([E.trace("MediaNodeClient.pauseMic")],ae.prototype,"pauseMic",1);de([E.trace("MediaNodeClient.pauseWebcam")],ae.prototype,"pauseWebcam",1);de([E.trace("MediaNodeClient.resumeMic")],ae.prototype,"resumeMic",1);de([E.trace("MediaNodeClient.resumeWebcam")],ae.prototype,"resumeWebcam",1);de([E.trace("MediaNodeClient.disableWebcam")],ae.prototype,"disableWebcam",1);de([E.trace("MediaNodeClient.disableMic")],ae.prototype,"disableMic",1);de([E.trace("MediaNodeClient.disableScreenShare")],ae.prototype,"disableScreenShare",1);de([E.trace("MediaNodeClient.muteSelf")],ae.prototype,"muteSelf",1);de([E.trace("MediaNodeClient.resetVideoProducers")],ae.prototype,"resetVideoProducers",1);de([E.trace("MediaNodeClient.changeDisplayName")],ae.prototype,"changeDisplayName",1);de([E.trace("MediaNodeClient.kickPeer")],ae.prototype,"kick",1);de([E.trace("MediaNodeClient.kickAllPeers")],ae.prototype,"kickAll",1);de([E.trace("MediaNodeClient.muteAll")],ae.prototype,"muteAll",1);de([E.trace("MediaNodeClient.muteAllVideo")],ae.prototype,"muteAllVideo",1);de([E.trace("MediaNodeClient.disableAudio")],ae.prototype,"disableAudio",1);de([E.trace("MediaNodeClient.disableVideo")],ae.prototype,"disableVideo",1);de([E.trace("MediaNodeClient.pinPeer")],ae.prototype,"pinPeer",1);de([E.trace("MediaNodeClient.validateScreenShare")],ae.prototype,"validateScreenShare",1);function OT(s,t){const e=s.getValue("roomNodeClient");if(e){if(e)return e;throw new Error("Room node client already set up.")}const r=new ae(s,t);return s.setValue("roomNodeClient",r),r}function NT(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 dO=Object.defineProperty,lO=Object.getOwnPropertyDescriptor,Tn=(s,t,e,r)=>{for(var i=r>1?void 0:r?lO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&dO(t,e,i),i},Zi,Es,te,St,Lt,jg;const LT=(jg=class{constructor(s,t,e,r){m(this,St);h(this,"self");h(this,"authToken");m(this,Zi,void 0);h(this,"viewType");m(this,Es,void 0);m(this,te,void 0);const{socket:i}=e,a=s.getValue("authToken");this.self=t,f(this,te,s),this.viewType=r,this.authToken=a,f(this,Zi,i),f(this,Es,e),t.config.viewType!==At.Chat&&this.setupEvents()}get peerId(){return n(this,te).getValue("peerId")}get telemetry(){return n(this,te).getValue("telemetry")}get logger(){return n(this,te).getValue("logger")}get mediaJoined(){return n(this,te).getValue("connectionHandler").mediaJoined}static init(s,t,e,r,i){return u(this,null,function*(){const a=dt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=yield Ye.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");if(navigator.product!=="ReactNative"){const p=!s.getValue("flagsmith").hasFeature(ee.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const g=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(g)}),s.getValue("callstats").devices("AUDIO",g==null?void 0:g.filter(T=>T.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",g==null?void 0:g.filter(T=>T.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",g==null?void 0:g.filter(T=>T.kind==="audiooutput")),l.info("Callstats:: initializing");try{yield s.getValue("callstats").initialize({peerId:o,engineName:Se.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:yield a.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:uf(s),skipConnectivityChecks:p}),l.info("Callstats:: initialized")}catch(T){l.error("Callstats:: initialization failed",{error:T})}}),0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new LT(s,d,t,i.viewType)})}shareMediaTracks(){return u(this,null,function*(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:a,screenShareTracks:o}=this.self;if(e.canProduceAudio===j.Allowed&&r)try{yield n(this,St,Lt).shareMic(s),this.self.audioEnabled||n(this,St,Lt).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===j.Allowed&&i)try{const d=yield n(this,St,Lt).shareWebcam(t);d&&d.id!==t.id&&n(this,te).getValue("flagsmith").hasFeature(ee.EXP_RESHARE)&&(yield n(this,St,Lt).shareWebcam(d)),this.self.videoEnabled||n(this,St,Lt).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===j.Allowed&&a)try{yield(c=n(this,St,Lt))==null?void 0:c.shareScreen({video:o.video,audio:o.audio})}catch(d){this.self.disableScreenShare()}})}kickHandler(s){return u(this,null,function*(){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")}resetSelf(s){return u(this,null,function*(){n(this,te).getValue("callstats").callEnded(),n(this,St,Lt).reset(),s&&(yield this.joinRoom(s))})}setupEvents(){n(this,te).getValue("peerSessionStore").on(k.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),n(this,te).getValue("peerSessionStore").on(k.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),n(this,te).getValue("peerSessionStore").on(k.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),n(this,te).getValue("peerSessionStore").on(k.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,te).getValue("peerSessionStore").on(k.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),n(this,te).getValue("peerSessionStore").on(k.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&n(this,te).getValue("flagsmith").hasFeature(ee.REFRESH_ID_ON_DISCONNECTION)&&(t=Tr.v4()),n(this,Zi).updateURL(t),n(this,te).getValue("telemetry").resetPeerId(t),dt().setHeader("tracing-id",t),mr.remapContext(t,n(this,te)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),n(this,te).getValue("peerSessionStore").on(k.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,Es).on($.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),n(this,Es).on(dd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&n(this,te).getValue("peerSessionStore").emit(k.UPDATE_PERMISSIONS,t.patch)})}),n(this,Es).on($.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),n(this,Es).on($.kick,()=>{this.kickHandler({kickType:"kick"})}),n(this,Es).on($.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),n(this,te).getValue("peerSessionStore").onAsync(k.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),n(this,te).getValue("peerSessionStore").on(k.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var a;const i=(a=e==null?void 0:e.screenShare)!=null?a:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),n(this,te).getValue("peerSessionStore").on(k.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),n(this,te).getValue("callstats").audioOff())})),n(this,te).getValue("peerSessionStore").on(k.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),n(this,te).getValue("callstats").videoOff())})),n(this,te).getValue("peerSessionStore").onAsync(k.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),n(this,te).getValue("peerSessionStore").on(k.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(s=!1){return u(this,null,function*(){try{const{peer:t}=yield n(this,Es).joinRoom(this.self);n(this,Es).socket.flush();const e=Oh(t.stageType);if(n(this,te).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(s),n(this,te).notify("stageStatus")}catch(t){throw this.logger.error("Error in joinRoom",{error:t}),t}})}leaveRoom(s="left"){return u(this,null,function*(){var t,e;if(this.logger.info(`Leaving room with state: ${s}`),(t=n(this,te).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),n(this,te).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(s),n(this,te).notify("stageStatus");try{(e=n(this,Zi))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}NT(n(this,te)),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)})}joinMediaRoom(s=!1){return u(this,null,function*(){var a,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=n(this,te).getAllValues();try{if(e===At.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}OT(n(this,te),{socket:n(this,Zi),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:p}=(o=yield(a=n(this,St,Lt))==null?void 0:a.joinRoom(this.self.name,r,s,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}))!=null?o:{};if(!p)return;i==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:c}),new b("Error: could not join media room","0002")}})}leaveMediaRoom(s){return u(this,null,function*(){const t=n(this,te).getValue("viewType");s!=="connected-meeting"&&(yield this.cleanupSelf()),!(s==="stageLeft"&&t===At.Webinar)&&n(this,St,Lt)&&(n(this,St,Lt).mediaJoined&&s!=="disconnected"&&(yield n(this,St,Lt).leaveRoom()),!(s==="stageLeft"&&t===At.Livestream)&&(n(this,St,Lt).mediaJoined=!1))})}cleanupSelf(){return u(this,null,function*(){yield this.self.disableAudio(),yield this.self.disableVideo(),yield this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()})}},Zi=new WeakMap,Es=new WeakMap,te=new WeakMap,St=new WeakSet,Lt=function(){return n(this,te).getValue("roomNodeClient")},jg);let ii=LT;Tn([E.trace("SelfController.resetSelf")],ii.prototype,"resetSelf",1);Tn([E.trace("SelfController.setupEvents")],ii.prototype,"setupEvents",1);Tn([E.trace("SelfController.joinRoom")],ii.prototype,"joinRoom",1);Tn([E.trace("SelfController.leaveRoom")],ii.prototype,"leaveRoom",1);Tn([E.trace("SelfController.joinMediaRoom")],ii.prototype,"joinMediaRoom",1);Tn([E.trace("SelfController.leaveMediaRoom")],ii.prototype,"leaveMediaRoom",1);Tn([E.trace("SelfController.init")],ii,"init",1);var Ic;class uO{constructor(t){m(this,Ic,void 0);f(this,Ic,t)}on(t,e){let r;t===$.roomPeerCount?r=Yp.fromBinary.bind(Yp):r=og.fromBinary.bind(og),n(this,Ic).on(t,({payload:i})=>{if(t===$.roomPeerCount&&!i)return;const a=r(i);e(a)})}}Ic=new WeakMap;var Ac,Mc;class hO{constructor(t,e){m(this,Ac,void 0);m(this,Mc,void 0);f(this,Ac,e),f(this,Mc,t)}get logger(){return n(this,Mc).getValue("logger")}on(t,e){let r,i;switch(t){case $.transcript:{r=nu.fromBinary.bind(nu),i=nu.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}n(this,Ac).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}Ac=new WeakMap,Mc=new WeakMap;var pO=Object.defineProperty,gO=Object.getOwnPropertyDescriptor,Gh=(s,t,e,r)=>{for(var i=r>1?void 0:r?gO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&pO(t,e,i),i},hr,Oa;class Wl{constructor(t,e){m(this,hr,void 0);m(this,Oa,void 0);f(this,hr,e),f(this,Oa,t)}get logger(){return n(this,Oa).getValue("logger")}get telemetry(){return n(this,Oa).getValue("telemetry")}getPolls(){return n(this,hr).sendMessagePromise(Ws.getPolls)}createPoll(t,e,r=!1,i=!1){const a={anonymous:r,hideVotes:i,question:t,options:e};return n(this,hr).sendMessage(Ws.createPoll,TM.toBinary(a))}votePoll(t,e){const r={index:e,pollId:t};return n(this,hr).sendMessage(Ws.votePoll,yM.toBinary(r))}on(t,e){let r,i;switch(t){case Ws.updatePoll:case Ws.createPoll:case Ws.votePoll:{r=uu.fromBinary.bind(uu),i=uu.create();break}}n(this,hr).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){n(this,hr).removeListeners(t)}}hr=new WeakMap,Oa=new WeakMap;Gh([E.trace("PollSocketHandler.getPolls")],Wl.prototype,"getPolls",1);Gh([E.trace("PollSocketHandler.createPoll")],Wl.prototype,"createPoll",1);Gh([E.trace("PollSocketHandler.votePoll")],Wl.prototype,"votePoll",1);var mO=Object.defineProperty,fO=Object.getOwnPropertyDescriptor,TO=(s,t,e,r)=>{for(var i=r>1?void 0:r?fO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&mO(t,e,i),i},Ft;class VT{constructor(t,e){h(this,"socket");m(this,Ft,void 0);f(this,Ft,t),this.socket=e,this.handleSocketEvents(),n(this,Ft).setValue("roomSocketHandler",this)}get telemetry(){return n(this,Ft).getValue("telemetry")}get logger(){return n(this,Ft).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}joinRoom(t){return u(this,null,function*(){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($.joinRoom,ik.toBinary(e));try{const{peer:a}=yn.fromBinary((yield r).payload);n(this,Ft).getValue("connectionHandler").socketJoined=!0,n(this,Ft).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_ROOM_JOINED,{peer:a});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=yield Promise.all([o,c]);return n(this,Ft).getValue("peerSessionStore").emit(k.ROOM_STATE,d),n(this,Ft).getValue("peerSessionStore").emit(k.SOCKET_PEERS,l),{peer:a}}catch(a){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:a}),new b("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,a)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return Hk.fromBinary((yield this.socket.sendMessagePromise($.getAllAddedParticipants)).payload).participants.map(i=>{var a=i,{id:e}=a,r=io(a,["id"]);return H(D({},r),{userId:e})})}catch(t){return[]}})}getRoomPeers(t,e,r){return u(this,null,function*(){let i;try{const a={seachQuery:t,limit:e,offset:r},o=yield this.socket.sendMessagePromise($.getRoomPeersInfo,Kb.toBinary(a));i=au.fromBinary(o.payload)}catch(a){this.logger.error("getRoomPeers::binary_decode_error",{error:a})}return i})}getRoomPeersNonPaginated(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise($.getRoomPeersInfo);t=au.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getStagePeers(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise($.getRoomPeersInfo);t=au.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getPeerInfo(t){return u(this,null,function*(){let e;try{const r=yield this.socket.sendMessagePromise($.getPeerInfo,Ef.toBinary({peerId:t}));e=yn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e})}getRoomState(){return u(this,null,function*(){let t=Qp.create();try{const e=yield this.socket.sendMessagePromise($.getRoomInfo);t=Qp.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t})}getRoomStageState(){return u(this,null,function*(){let t=tg.create();try{const e=yield this.socket.sendMessagePromise($.getRoomStageState);t=tg.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t})}broadcastMessage(t,e){return u(this,null,function*(){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise($.broadcastMessage,oo.toBinary(r))})}broadcastToMeetings(t,e,r){return u(this,null,function*(){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise($.broadcastToEntity,oo.toBinary(i))})}broadcastToPeers(t,e,r){return u(this,null,function*(){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage($.broadcastToEntity,oo.toBinary(i))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise($.leaveRoom,ak.toBinary({}))})}kick(t){return u(this,null,function*(){const e={peerIds:[t]};this.socket.sendMessage($.kick,_f.toBinary(e))})}kickAll(t=!1){return u(this,null,function*(){const e={propagateKickAcrossRooms:t};this.socket.sendMessage($.kickAll,vf.toBinary(e))})}getWaitingRoomRequests(){this.socket.sendMessage($.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage($.acceptWaitingRoomRequests,Kk.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage($.denyWaitingRoomRequests,Yk.toBinary(e))}updatePermissions(t,e){return u(this,null,function*(){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(dd.updateUserPreset,wI.toBinary(r))})}handleSocketEvents(){this.socket.on($.broadcastMessage,({payload:t})=>{try{const e=oo.fromBinary(t);n(this,Ft).getValue("peerSessionStore").emit(k.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on($.broadcastToEntity,({payload:t})=>{try{const e=oo.fromBinary(t);n(this,Ft).getValue("peerSessionStore").emit(k.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case $.joinRoom:case $.leaveRoom:case $.kick:case $.kickAll:{r=yn.fromBinary.bind(yn),i=yn.create();break}case $.getWaitingRoomRequests:{r=(a,o)=>a?eg.fromBinary(a,o):{requests:[]},i=eg.create();break}case $.recordingPaused:case $.recordingStarted:case $.recordingStopped:{r=lg.fromBinary.bind(lg);break}case dd.updateUserPreset:{r=sg.fromBinary.bind(sg);break}case Cs.peerJoinedBroadcast:case Mr.peerJoinedBroadcast:{r=Gp.fromBinary.bind(Gp);break}case Cs.selfJoinComplete:case Mr.selfJoinComplete:{r=Ru.fromBinary.bind(Ru);break}case Cs.globalPeerPinBroadcast:case Mr.globalPeerPinBroadcast:{r=Kp.fromBinary.bind(Kp);break}case Cs.selectedPeer:case Mr.selectedPeer:{r=wu.fromBinary.bind(wu);break}case Cs.selectedPeerDiff:case Mr.selectedPeerDiff:{r=jp.fromBinary.bind(jp);break}case Cs.leaveRoom:case Mr.leaveRoom:{r=bu.fromBinary.bind(bu);break}}this.socket.on(t,({payload:a})=>{let o=i;if(!r)return e(void 0);try{o=r(a)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}getUserPermissions(t){return u(this,null,function*(){const e={userIds:[t]};try{const r=yield this.socket.sendMessagePromise(dd.getUserPresets,vI.toBinary(e)),i=PI.fromBinary(r.payload).peerPresets[0],a=new TextDecoder().decode(i.preset),o=JSON.parse(a).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}})}}Ft=new WeakMap;TO([E.trace("RoomSocketHandler.joinRoom")],VT.prototype,"joinRoom",1);var kt;class vO{constructor(t){m(this,kt,void 0);f(this,kt,t)}getStageRequests(){return u(this,null,function*(){const{payload:t}=yield n(this,kt).sendMessagePromise($.getStageRequests);return t?lu.fromBinary(t):{stageRequests:[]}})}requestAccess(){n(this,kt).sendMessage($.requestStageAccess)}cancelRequestAccess(){n(this,kt).sendMessage($.cancelStageRequest)}grantAccess(t){return u(this,null,function*(){const e={userIds:t};n(this,kt).sendMessage($.grantStageAccess,oM.toBinary(e))})}denyAccess(t){return u(this,null,function*(){const e={userIds:t};n(this,kt).sendMessage($.denyStageAccess,dM.toBinary(e))})}joinStage(){return n(this,kt).sendMessagePromise($.joinStage,void 0,void 0,$.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return n(this,kt).sendMessagePromise($.leaveStage,dg.toBinary(e),void 0,$.peerStageStatusUpdate)}kick(t){const e={userIds:t};return n(this,kt).sendMessagePromise($.leaveStage,dg.toBinary(e))}on(t,e){let r;switch(t){case $.grantStageAccess:case $.denyStageAccess:{r=void 0;break}case $.getStagePeers:{r=cg.fromBinary.bind(cg);break}case $.getStageRequests:case $.requestStageAccess:case $.cancelStageRequest:{r=lu.fromBinary.bind(lu);break}case $.peerStageStatusUpdate:{r=zp.fromBinary.bind(zp);break}}n(this,kt).on(t,({payload:i,id:a})=>{if(!i||!r)return e(void 0,a);const o=r(i);return e(o,a)})}getPeerInfo(t){return u(this,null,function*(){const e=yield n(this,kt).sendMessagePromise($.getPeerInfo,Ef.toBinary({peerId:t}));return yn.fromBinary(e.payload)})}}kt=new WeakMap;var je,Dc;class yO{constructor(t,e){m(this,je,void 0);m(this,Dc,void 0);f(this,je,e),f(this,Dc,t)}get logger(){return n(this,Dc).getValue("logger")}addPlugin(t,e){n(this,je).sendMessage(J.addPlugin,CA.toBinary({pluginId:t,staggered:e}))}removePlugin(t){n(this,je).sendMessage(J.removePlugin,RA.toBinary({pluginId:t,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:t}=yield n(this,je).sendMessagePromise(J.getPlugins);return t?zA.fromBinary(t):{plugins:[]}})}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};n(this,je).sendMessage(J.customPluginEventToRoom,VA.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const a={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};n(this,je).sendMessage(J.customPluginEventToPeers,UA.toBinary(a),i)}enablePluginForRoom(t,e){n(this,je).sendMessage(J.enablePluginForRoom,kA.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){n(this,je).sendMessage(J.enablePluginForPeers,DA.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){n(this,je).sendMessage(J.disablePluginForRoom,AA.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){n(this,je).sendMessage(J.disablePluginForPeers,NA.toBinary({pluginId:t,peerIds:e}),r)}storeInsertKeys(t,e,r,i){const a={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};n(this,je).sendMessage(J.storeInsertKeys,rg.toBinary(a),i)}storeGetKeys(t,e,r,i){const a={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};n(this,je).sendMessage(J.storeGetKeys,HA.toBinary(a),i)}storeDeleteKeys(t,e,r,i){const a={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};n(this,je).sendMessage(J.storeDeleteKeys,jA.toBinary(a),i)}storeDelete(t,e,r){n(this,je).sendMessage(J.storeDelete,WA.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))}]};n(this,je).sendMessage(J.storeInsertKeys,rg.toBinary(i))}on(t,e){let r;switch(t){case J.addPlugin:case J.enablePluginForPeers:case J.enablePluginForRoom:{r=Mu.fromBinary.bind(Mu);break}case J.removePlugin:case J.disablePluginForPeers:case J.disablePluginForRoom:{r=ig.fromBinary.bind(ig);break}case J.customPluginEventToPeers:case J.customPluginEventToRoom:{r=ag.fromBinary.bind(ag);break}case J.storeInsertKeys:case J.storeGetKeys:case J.storeDeleteKeys:case J.storeDelete:{r=ng.fromBinary.bind(ng);break}}n(this,je).on(t,({payload:i,id:a})=>{const o=r(i);return e(o,a)})}}je=new WeakMap,Dc=new WeakMap;var SO=Object.defineProperty,EO=(s,t,e)=>t in s?SO(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,PO=(s,t,e)=>(EO(s,typeof t!="symbol"?t+"":t,e),e),Wh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},M=(s,t,e)=>(Wh(s,t,"read from private field"),e?e.call(s):t.get(s)),Te=(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)=>(Wh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),_e=(s,t,e)=>(Wh(s,t,"access private method"),e),Md={},_O={get exports(){return Md},set exports(s){Md=s}},On=typeof Reflect=="object"?Reflect:null,Eg=On&&typeof On.apply=="function"?On.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},fd;On&&typeof On.ownKeys=="function"?fd=On.ownKeys:Object.getOwnPropertySymbols?fd=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:fd=function(s){return Object.getOwnPropertyNames(s)};function CO(s){console&&console.warn&&console.warn(s)}var xT=Number.isNaN||function(s){return s!==s};function ce(){ce.init.call(this)}_O.exports=ce;Md.once=kO;ce.EventEmitter=ce;ce.prototype._events=void 0;ce.prototype._eventsCount=0;ce.prototype._maxListeners=void 0;var Pg=10;function Jl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ce,"defaultMaxListeners",{enumerable:!0,get:function(){return Pg},set:function(s){if(typeof s!="number"||s<0||xT(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Pg=s}});ce.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};ce.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||xT(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 UT(s){return s._maxListeners===void 0?ce.defaultMaxListeners:s._maxListeners}ce.prototype.getMaxListeners=function(){return UT(this)};ce.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 a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")Eg(c,this,t);else for(var d=c.length,l=qT(c,d),e=0;e<d;++e)Eg(l[e],this,t);return!0};function $T(s,t,e,r){var i,a,o;if(Jl(e),a=s._events,a===void 0?(a=s._events=Object.create(null),s._eventsCount=0):(a.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),a=s._events),o=a[t]),o===void 0)o=a[t]=e,++s._eventsCount;else if(typeof o=="function"?o=a[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=UT(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,CO(c)}return s}ce.prototype.addListener=function(s,t){return $T(this,s,t,!1)};ce.prototype.on=ce.prototype.addListener;ce.prototype.prependListener=function(s,t){return $T(this,s,t,!0)};function wO(){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 FT(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=wO.bind(r);return i.listener=e,r.wrapFn=i,i}ce.prototype.once=function(s,t){return Jl(t),this.on(s,FT(this,s,t)),this};ce.prototype.prependOnceListener=function(s,t){return Jl(t),this.prependListener(s,FT(this,s,t)),this};ce.prototype.removeListener=function(s,t){var e,r,i,a,o;if(Jl(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,a=e.length-1;a>=0;a--)if(e[a]===t||e[a].listener===t){o=e[a].listener,i=a;break}if(i<0)return this;i===0?e.shift():RO(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this};ce.prototype.off=ce.prototype.removeListener;ce.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),a;for(r=0;r<i.length;++r)a=i[r],a!=="removeListener"&&this.removeAllListeners(a);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 BT(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?bO(i):qT(i,i.length)}ce.prototype.listeners=function(s){return BT(this,s,!0)};ce.prototype.rawListeners=function(s){return BT(this,s,!1)};ce.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):HT.call(s,t)};ce.prototype.listenerCount=HT;function HT(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}ce.prototype.eventNames=function(){return this._eventsCount>0?fd(this._events):[]};function qT(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function RO(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function bO(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function kO(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,a),r(o)}function a(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}jT(s,t,a,{once:!0}),t!=="error"&&IO(s,i,{once:!0})})}function IO(s,t,e){typeof s.on=="function"&&jT(s,"error",t,e)}function jT(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(a){r.once&&s.removeEventListener(t,i),e(a)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class AO extends y.MessageType{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 _g=new AO;class GT{static encode(t){return _g.toBinary(t)}static decode(t){return _g.fromBinary(new Uint8Array(t))}}function MO(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Ir;class DO{constructor(t={}){PO(this,"opts"),Te(this,Ir,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ne(this,Ir,0)}wait(){return u(this,null,function*(){ne(this,Ir,M(this,Ir)+1);const t=MO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*Zh(2,M(this,Ir))));yield new Promise(e=>{setTimeout(e,t)})})}getAttempts(){return M(this,Ir)}reset(){ne(this,Ir,0)}}Ir=new WeakMap;const Rr={debug:0,info:1,warn:2,error:3};var li,ui;class OO{constructor(t){Te(this,li,void 0),Te(this,ui,void 0),ne(this,li,console),ne(this,ui,t)}debug(...t){Rr[M(this,ui)]>Rr.debug||M(this,li).debug("[Sockrates]:",...t)}info(...t){Rr[M(this,ui)]>Rr.info||M(this,li).info("[Sockrates]:",...t)}warn(...t){Rr[M(this,ui)]>Rr.warn||M(this,li).warn("[Sockrates]:",...t)}error(...t){Rr[M(this,ui)]>Rr.error||M(this,li).error("[Sockrates]:",...t)}}li=new WeakMap,ui=new WeakMap;var WT=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(WT||{});const NO="2",LO="3";var Ae,_n,Pe,Ve,Ar,Ke,gr,Zr,_s,Cn,Gs,rh,JT,vo,Td,ih,KT,nh,Cg,Dd,ah,oh,zT,Eo,vd,Po,Od,Nd,ch,Nn,_o,Co,Ld;class VO{constructor(t,e){var T,v,P,_,C,w,V,F,N,B;Te(this,rh),Te(this,vo),Te(this,ih),Te(this,nh),Te(this,Dd),Te(this,oh),Te(this,Eo),Te(this,Po),Te(this,Nd),Te(this,Nn),Te(this,Co),Te(this,Ae,void 0),Te(this,_n,void 0),Te(this,Pe,void 0),Te(this,Ve,void 0),Te(this,Ar,void 0),Te(this,Ke,void 0),Te(this,gr,void 0),Te(this,Zr,void 0),Te(this,_s,void 0),Te(this,Cn,void 0),Te(this,Gs,void 0);var r,i,a,o,c,d,l,p,g;ne(this,_n,t),ne(this,Ar,[]),ne(this,Ke,new Md),ne(this,gr,!0),ne(this,_s,!1),ne(this,Pe,e!=null?e:{}),(T=(r=M(this,Pe)).autoReconnect)!=null||(r.autoReconnect=!0),(v=(i=M(this,Pe)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(P=(a=M(this,Pe)).pingTimeout)!=null||(a.pingTimeout=3e4),(_=(o=M(this,Pe)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(C=(c=M(this,Pe)).debug)!=null||(c.debug=!0),(w=(d=M(this,Pe)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(V=(l=M(this,Pe)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(F=(p=M(this,Pe)).queueOnDisconnect)!=null||(p.queueOnDisconnect=!1),(N=(g=M(this,Pe)).flushOnReconnect)!=null||(g.flushOnReconnect=!1),ne(this,Zr,{code:void 0,reason:void 0}),ne(this,Ve,(B=M(this,Pe).logger)!=null?B:new OO(M(this,Pe).debug?"debug":"info")),ne(this,Gs,new DO)}get readyState(){var t;return(t=M(this,Ae))==null?void 0:t.readyState}get url(){return M(this,_n)}updateURL(t){ne(this,_n,t),_e(this,oh,zT).call(this)}get config(){return M(this,Pe)}get sendQueue(){return M(this,Ar)}flush(){if(!M(this,Pe).queueOnDisconnect)return!1;const t=[];return M(this,Ar).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ne(this,Ar,t),M(this,Ar)}connect(t=!1){return u(this,null,function*(){if(!t&&[0,1].includes(this.readyState)){M(this,Ve).debug("Websocket was already connecting or connected.");return}if(M(this,gr)!==!1)return new Promise((e,r)=>{_e(this,Nn,_o).call(this),_e(this,Co,Ld).call(this);try{ne(this,Ae,new WebSocket(_e(this,rh,JT).call(this,M(this,_n)))),M(this,Ae).binaryType="arraybuffer",M(this,Ve).debug("Connecting");const i=setTimeout(()=>{M(this,Ve).debug("Connection timeout. Closing socket"),ne(this,gr,!0),_e(this,Co,Ld).call(this),M(this,Ae).close(3001,"Connection Timeout"),M(this,Pe).autoReconnect&&!M(this,_s)&&(M(this,Ke).emit("reconnecting"),_e(this,Eo,vd).call(this)),r(new Error("Connection timed out!"))},M(this,Pe).connectionTimeout);M(this,Ae).onopen=()=>{M(this,Ve).debug(`Ready State: ${WT[M(this,Ae).readyState]}`),i&&clearTimeout(i),_e(this,Nd,ch).call(this),ne(this,Zr,{code:void 0,reason:void 0}),M(this,Ke).emit("connected"),M(this,Pe).flushOnReconnect&&this.flush(),e()},M(this,Ae).onclose=a=>{try{i&&clearTimeout(i);const{code:o,reason:c}=a;r(c),M(this,Ve).debug("Socket closed. Close event:",{event:a}),M(this,Ve).debug(`Connection closed code: ${o}`),M(this,Ve).debug(`Connection closed reason: ${c}`),M(this,_s)||_e(this,Dd,ah).call(this,o,c)}catch(o){_e(this,vo,Td).call(this,o)}},M(this,Ae).onerror=a=>{_e(this,vo,Td).call(this,a)},M(this,Ae).onmessage=a=>_e(this,ih,KT).call(this,a)}catch(i){_e(this,vo,Td).call(this,i,r)}})})}send(t,e,r,i){const a={event:t,id:e,payload:r,metadata:i};if(M(this,Pe).queueOnDisconnect&&(!M(this,Ae)||M(this,Ae).readyState!==1))return M(this,Ve).debug("Queuing message since socket is not connected!",a),M(this,Ar).push(a),!1;const o=GT.encode(a);return _e(this,Po,Od).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return _e(this,Po,Od).call(this,t)}receive(t,e){return M(this,Ke).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){M(this,Ke).on(t,e);return}this.receive(t,e)}removeAllListeners(){M(this,Ke).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){M(this,Ke).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){M(this,Ke).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ne(this,gr,!1),_e(this,Nn,_o).call(this),this.removeAllListeners(),ne(this,Zr,{code:1e3,reason:"Sockrates disconnect method called"}),M(this,Ae).close(1e3,"Sockrates disconnect method called.")}}Ae=new WeakMap,_n=new WeakMap,Pe=new WeakMap,Ve=new WeakMap,Ar=new WeakMap,Ke=new WeakMap,gr=new WeakMap,Zr=new WeakMap,_s=new WeakMap,Cn=new WeakMap,Gs=new WeakMap,rh=new WeakSet,JT=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)://.")},vo=new WeakSet,Td=function(s,t){M(this,Ve).error("Error:",{error:s}),M(this,Ke).emit("errored",{error:s}),t==null||t(s)},ih=new WeakSet,KT=function(s){if(_e(this,Nd,ch).call(this),s.data===NO){M(this,Ve).debug("Received ping from server"),_e(this,Po,Od).call(this,LO);return}const t=GT.decode(s.data),{id:e,payload:r}=t;M(this,Ve).debug("Received message",{event:t.event,messageID:e}),M(this,Ke).emit(t.event.toString(),{id:e,payload:r})},nh=new WeakSet,Cg=function(){return M(this,Ae).readyState===1},Dd=new WeakSet,ah=function(s,t){ne(this,Zr,{reason:t,code:s}),M(this,Ke).emit("disconnected",{code:s,reason:t})},oh=new WeakSet,zT=function(){const{reason:s,code:t}=M(this,Zr);t&&t!==1e3&&M(this,gr)&&M(this,Pe).autoReconnect&&!M(this,_s)&&(M(this,Ve).debug(`Triggering reconnection due to ${s}.`),M(this,Ke).emit("reconnecting"),_e(this,Eo,vd).call(this))},Eo=new WeakSet,vd=function(s=!0){return u(this,null,function*(){if(s&&M(this,_s)){M(this,Ve).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(M(this,_s)||M(this,Gs).reset(),M(this,Pe).maxReconnectionAttempts!==null&&M(this,Gs).getAttempts()>=M(this,Pe).maxReconnectionAttempts){M(this,Ke).emit("failed"),ne(this,_s,!1);return}ne(this,_s,!0),_e(this,Co,Ld).call(this),_e(this,Nn,_o).call(this);try{if(yield M(this,Gs).wait(),M(this,gr)===!1)return;if(M(this,Ve).debug(`Reconnection attempt ${M(this,Gs).getAttempts()}`),M(this,Ke).emit("reconnectAttempt",{attempt:M(this,Gs).getAttempts()}),yield this.connect(),!_e(this,nh,Cg).call(this))throw Error("Reconnect Failed");ne(this,_s,!1),ne(this,Zr,{code:void 0,reason:void 0}),M(this,Ke).emit("reconnected")}catch(t){M(this,Ve).debug("Failed to reconnect."),M(this,Ke).emit("reconnectFailure",{attempt:M(this,Gs).getAttempts()}),_e(this,Eo,vd).call(this,!1)}})},Po=new WeakSet,Od=function(s){try{return M(this,Ae).send(s),!0}catch(t){return M(this,Ve).error(t.message),!1}},Nd=new WeakSet,ch=function(){this.config.disconnectOnPingTimeout&&(M(this,Ve).debug("Resetting ping timeout"),_e(this,Nn,_o).call(this),ne(this,Cn,setTimeout(()=>{var s;M(this,Ve).debug("Disconnecting the socket due to ping timeout"),ne(this,gr,!0);const t=3002,e="Ping timeout";(s=M(this,Ae))==null||s.close(t,e),_e(this,Dd,ah).call(this,t,e)},M(this,Pe).pingTimeout)))},Nn=new WeakSet,_o=function(){M(this,Cn)&&(clearTimeout(M(this,Cn)),ne(this,Cn,void 0))},Co=new WeakSet,Ld=function(){M(this,Ae)&&(M(this,Ae).onopen=void 0,M(this,Ae).onerror=void 0,M(this,Ae).onmessage=void 0,M(this,Ae).onclose=void 0)};var xO=Object.defineProperty,UO=Object.getOwnPropertyDescriptor,Kl=(s,t,e,r)=>{for(var i=r>1?void 0:r?UO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&xO(t,e,i),i};const wg=65535,$O=3e3;var Yr,Ce,we,Me,ns,et,Oc,dh,Nc,lh,Gg;const YT=(Gg=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,we);m(this,Oc);m(this,Nc);m(this,Yr,void 0);m(this,Ce,void 0);h(this,"roomName");h(this,"authToken");h(this,"capabilities");m(this,ns,void 0);m(this,et,void 0);var a;if(!t||!e||!r)throw new b("peerId, meetingId, or authToken can not be empty","0404");f(this,ns,void 0),f(this,et,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,Yr,U(this,Oc,dh).call(this,t)),f(this,Ce,new VO(n(this,Yr),{autoReconnect:!0,disconnectOnPingTimeout:(a=i.includes("PING"))!=null?a:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return n(this,we,Me).socketJoinAttempted}set joinAttempted(s){n(this,we,Me).socketJoinAttempted=s}get telemetry(){return n(this,et).getValue("telemetry")}get logger(){return n(this,et).getValue("logger")}get peerId(){return n(this,et).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,Yr,U(this,Oc,dh).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),n(this,Ce).updateURL(n(this,Yr))}static getSocketEdgeDomain(s){return nn({servicePrefix:"socket-edge",baseURI:s})}get url(){return n(this,Yr)}connect(){return u(this,null,function*(){n(this,we,Me).socketJoinAttempted=!0,yield n(this,Ce).connect(),n(this,we,Me).socketJoinAttempted=!0,n(this,we,Me).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){n(this,we,Me).socketJoinAttempted=!1,n(this,Ce).disconnect(),n(this,we,Me).socketJoinAttempted=!0,n(this,we,Me).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return n(this,Ce).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return n(this,et).getValue("telemetry").injectContext(r),n(this,Ce).send(s,e!=null?e:U(this,Nc,lh).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 a=i!=null?i:s;return new Promise((o,c)=>{const d=(P,_)=>{n(this,Ce).removeListener(a,P),n(this,Ce).removeListener(wg,_),n(this,Ce).removeListener(Mr.errorResponse,_),n(this,Ce).removeListener(Cs.errorResponse,_)},l=r!=null?r:U(this,Nc,lh).call(this),p={};n(this,et).getValue("telemetry").injectContext(p);const T=({id:P,payload:_})=>{if(l===P){let C;try{const w=FR.fromBinary(_);C=new Error(w.errorMessage)}catch(w){C=new Error("failed to parse error message",{cause:w});try{const V=Bb.fromBinary(_);C=new Error(V.message)}catch(V){C=new Error("failed to parse error message",{cause:V})}}c(C),d(v,T)}},v=({id:P,payload:_})=>{l===P&&(o({id:P,payload:_}),d(v,T))};n(this,Ce).on(a,v),n(this,Ce).on(wg,T),n(this,Ce).on(Mr.errorResponse,T),n(this,Ce).on(Cs.errorResponse,T),setTimeout(()=>{d(v,T),c(new Error(`request timeout for callback eventId:${s}`))},t),n(this,Ce).send(s,l,e,new TextEncoder().encode(JSON.stringify(p)))})}on(s,t){n(this,Ce).on(s,t)}onStateEvent(s,t){n(this,Ce).on(s,t)}removeListener(s,t){n(this,Ce).removeListener(s,t)}removeListeners(s){n(this,Ce).removeListeners(s)}flush(){return n(this,Ce).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){this.logger.info("SocketService::Connected to socket-edge"),n(this,ns)&&(clearTimeout(n(this,ns)),f(this,ns,void 0)),n(this,we,Me).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:s,reason:t})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t},country:E.location.country});const{recv:e,send:r}=(i=n(this,we,Me).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Dn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Dn.CONNECTED?n(this,et).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,we,Me).joinAttempted}):f(this,ns,setTimeout(()=>{n(this,et).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,we,Me).joinAttempted}),f(this,ns,void 0)},$O)),n(this,we,Me).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnecting to socket-edge",{country:E.location.country}),n(this,we,Me).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:s}){this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),n(this,we,Me).updateSocketConnectionState("reconnectAttempt",s)})),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),n(this,we,Me).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:n(this,we,Me).mediaJoinAttempted}}),n(this,ns)&&(clearTimeout(n(this,ns)),f(this,ns,void 0)),n(this,et).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:n(this,we,Me).mediaJoinAttempted}),n(this,we,Me).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){this.logger.info("SocketService::Failed to connect to socket-edge",{country:E.location.country}),n(this,et).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_FAILED),n(this,we,Me).updateSocketConnectionState("failed")}))}},Yr=new WeakMap,Ce=new WeakMap,we=new WeakSet,Me=function(){return n(this,et).getValue("connectionHandler")},ns=new WeakMap,et=new WeakMap,Oc=new WeakSet,dh=function(s){let t=YT.getSocketEdgeDomain(n(this,et).getValue("baseURI"));typeof xa(n(this,et),"socket_server_base")=="string"&&(t=xa(n(this,et),"socket_server_base"));const e=`wss://${t}`,r=new URL(`${e}/ws`),i=this.peerId,a=H(D({roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0},i!==s&&{oldPeerID:i}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>wd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0});return Object.entries(a).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},Nc=new WeakSet,lh=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Gg);let Gc=YT;Kl([E.trace("SocketService.connect")],Gc.prototype,"connect",1);Kl([E.trace("SocketService.disconnect")],Gc.prototype,"disconnect",1);Kl([E.trace("SocketService.sendMessagePromise")],Gc.prototype,"sendMessagePromise",1);Kl([E.trace("SocketService.sendMessagePromiseWithTimeout")],Gc.prototype,"sendMessagePromiseWithTimeout",1);class FO{constructor(t){h(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var a;const e=gk.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:(a=e.parentMeeting.participants)!=null?a:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=Fk.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=Pf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return Zp.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return Ak.fromBinary(t).payloads}getConnectedRoomsDump(){return u(this,null,function*(){const t=yield this.socketService.sendMessagePromise($.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)})}createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield this.socketService.sendMessagePromise($.createConnectedRooms,vk.toBinary({payloads:t}));return Zp.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))})}updateConnectedRooms(t){return u(this,null,function*(){})}disableConnectedRooms(t){return u(this,null,function*(){const e=t.map(i=>({id:i})),r=yield this.socketService.sendMessagePromise($.deleteConnectedRooms,kk.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)})}movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield this.socketService.sendMessagePromise($.movePeers,Vk.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 BO=Object.defineProperty,HO=Object.getOwnPropertyDescriptor,qO=(s,t,e,r)=>{for(var i=r>1?void 0:r?HO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&BO(t,e,i),i},Ps;class QT extends qt{constructor(e){const r=e.getValue("logger");super(r);h(this,"meetings",[]);h(this,"parentMeeting",null);m(this,Ps,void 0);f(this,Ps,e)}get supportsConnectedMeetings(){return n(this,Ps).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.
13
- Please connect with our support team to enable connected meetings.`)}getConnectedMeetings(){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),yield n(this,Ps).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield n(this,Ps).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e)).map(i=>({id:i.id,title:i.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield n(this,Ps).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const r=this.meetings.map(a=>e.includes(a.id)&&a.participants.length!==0?this.moveParticipants(a.id,this.parentMeeting.id,a.participants.map(o=>o.id)):Promise.resolve());return yield Promise.all(r),yield n(this,Ps).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e)})}moveParticipants(e,r,i){return u(this,null,function*(){this.validateConnectedMeetingsAction();const a=yield n(this,Ps).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return a.success&&this.moveSuccessHandler(e,r,i),a})}moveParticipantsWithCustomPreset(e,r,i){return u(this,null,function*(){this.validateConnectedMeetingsAction();const a=yield n(this,Ps).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return a.success&&this.moveSuccessHandler(e,r,i.map(o=>o.id)),a})}moveSuccessHandler(e,r,i){const a=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>a.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>a.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=>a.get(d)));return H(D({},o),{participants:c})}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return H(D({},o),{participants:c})}return o})}}Ps=new WeakMap;qO([Mt({maxInvocations:60,period:60})],QT.prototype,"getConnectedMeetings",1);var jO=Object.defineProperty,GO=Object.getOwnPropertyDescriptor,Jh=(s,t,e,r)=>{for(var i=r>1?void 0:r?GO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&jO(t,e,i),i},ge,Wg;const XT=(Wg=class{constructor(s){h(this,"connectedMeetings");m(this,ge,void 0);f(this,ge,s),this.connectedMeetings=new QT(s)}get telemetry(){return n(this,ge).getValue("telemetry")}get logger(){return n(this,ge).getValue("logger")}static init(s){const t=new XT(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){n(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on($.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),n(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on($.transferPeer,this.handleTransferPeer.bind(this)),n(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on($.movedPeer,this.handleMovedPeer.bind(this)),n(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on($.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),n(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on($.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){const t=n(this,ge).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.switchMeeting(t)}switchMeeting(e){return u(this,arguments,function*({authToken:s,meetingId:t}){var a,o,c,d;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
13
+ Please connect with our support team to enable connected meetings.`)}getConnectedMeetings(){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info("Getting connected meetings dump");const e=yield n(this,Ps).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e})}createMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=yield n(this,Ps).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),yield n(this,Ps).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(a=>e.includes(a.id)&&a.participants.length!==0?this.moveParticipants(a.id,this.parentMeeting.id,a.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),yield Promise.all(r);const i=yield n(this,Ps).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i})}moveParticipants(e,r,i){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const a=yield n(this,Ps).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return a.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}`),a})}moveParticipantsWithCustomPreset(e,r,i){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const a=yield n(this,Ps).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return a.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}`),a})}moveSuccessHandler(e,r,i){const a=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>a.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>a.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=>a.get(d)));return H(D({},o),{participants:c})}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return H(D({},o),{participants:c})}return o})}}Ps=new WeakMap;qO([Mt({maxInvocations:60,period:60})],QT.prototype,"getConnectedMeetings",1);var jO=Object.defineProperty,GO=Object.getOwnPropertyDescriptor,Jh=(s,t,e,r)=>{for(var i=r>1?void 0:r?GO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&jO(t,e,i),i},ge,Wg;const XT=(Wg=class{constructor(s){h(this,"connectedMeetings");m(this,ge,void 0);f(this,ge,s),this.connectedMeetings=new QT(s)}get telemetry(){return n(this,ge).getValue("telemetry")}get logger(){return n(this,ge).getValue("logger")}static init(s){const t=new XT(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){n(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on($.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),n(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on($.transferPeer,this.handleTransferPeer.bind(this)),n(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on($.movedPeer,this.handleMovedPeer.bind(this)),n(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on($.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),n(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on($.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=n(this,ge).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)}switchMeeting(e){return u(this,arguments,function*({authToken:s,meetingId:t}){var a,o,c,d;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
14
14
  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 r={video:n(this,ge).getValue("self").videoEnabled,audio:n(this,ge).getValue("self").audioEnabled};try{n(this,ge).getValue("self").cleanupEvents(),yield n(this,ge).getValue("meeting").leave("connected-meeting")}catch(l){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(o=(a=n(this,ge).getValue("meeting"))==null?void 0:a.meta)==null?void 0:o.meetingId}`,{error:l})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const i=yield ev.init(H(D({},n(this,ge).getValue("options")),{cachedUserDetails:null,defaults:H(D(D({},n(this,ge).getValue("options").defaults),r),{mediaHandler:n(this,ge).getValue("self")}),authToken:s}));this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(c=i==null?void 0:i.meta)==null?void 0:c.meetingId}`);try{const{hidden:l}=n(this,ge).getValue("self");i.self.setName(n(this,ge).getValue("self").name),yield i.join(),l&&i.self.hide()}catch(l){this.logger.error("ConnectedMeetingsController.joinRoom",{error:l})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(d=i==null?void 0:i.meta)==null?void 0:d.meetingId}`),this.connectedMeetings.emit("meetingChanged",i),i})}handleConnectedRoomsDump(s){const t=n(this,ge).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 n(this,ge).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=n(this,ge).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,H(D({},r),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=n(this,ge).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})}},ge=new WeakMap,Wg);let zl=XT;Jh([E.trace("ConnectedMeetingsController.getConnectedMeetings")],zl.prototype,"getConnectedMeetings",1);Jh([E.trace("ConnectedMeetingsController.setupEvents")],zl.prototype,"setupEvents",1);Jh([E.trace("ConnectedMeetingsController.switchMeeting")],zl.prototype,"switchMeeting",1);var WO=Object.defineProperty,JO=Object.getOwnPropertyDescriptor,Yl=(s,t,e,r)=>{for(var i=r>1?void 0:r?JO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&WO(t,e,i),i};const wn=class{constructor(s,t,e){h(this,"apiBase");h(this,"selfController");h(this,"pollController");h(this,"chatController");h(this,"metaController");h(this,"storesManager");h(this,"stageController");h(this,"pluginController");h(this,"internalsController");h(this,"recordingController");h(this,"livestreamController");h(this,"participantController");h(this,"connectedMeetingsController");h(this,"telemetry");h(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 init(s){return u(this,null,function*(){var N,B;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:a,cachedUserDetails:o,logger:c}=s.getAllValues();if(NT(s),Se.isSupported()===!1)throw new b("Browser not supported","0010",c,!0);const d=XM(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(a),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new N0(s);s.setValue("connectionHandler",l);const p=wn.createSocketService(s),g=p.connect(),T=d.getUserDetails(),v=d.getPlugins();let P,_="";try{yield wn.setupFlagsmith(s)}catch(G){c.error("Failed to setup flagsmith",{error:G})}try{yield g}catch(G){c.error("[Controller]: Failed to connect to socket server:",{error:G})}try{({meetingTitle:_}=yield d.getRoomNodeData()),P=yield T,c.info("CF SFU is being used."),s.setValue("presetName",P.preset.name)}catch(G){c.error("Failed to get room metadata",{error:G})}const C=Bu.init(P.preset,!s.getValue("modules").theme),w=Gu.init(s,C.viewType,P.preset.permissions),V=wn.setupControllers(p,s,P,v,_,C,w);_0(C)&&((N=wn.createRoomNodeClient(s,p).initializeConnection(P.participant.name,i,!1,w))==null||N.catch(re=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:re})})),E.location.country=(B=d.ipInfo)==null?void 0:B.country;const{controllers:F}=yield V;return Ew(),new wn(e,F,s)})}static setupFlagsmith(s){return u(this,null,function*(){var l;const{peerId:t,baseURI:e,overrides:r,meetingId:i,organizationId:a,logger:o}=s.getAllValues(),c=Sw(i),d=H(D({entity:_u.PEER,clientId:a,isAnonUser:!a,sdkVersion:s.getValue("sdkVersion"),presetName:s.getValue("presetName"),meetingHash:c,roomName:i},Se.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const p=(l=r==null?void 0:r.whitelabelled_flags_endpoint)==null||l?nn({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";yield s.getValue("flagsmith").identify(`${_u.PEER}_${t}`,JSON.parse(JSON.stringify(d)),!1,5e3,p,o),o.info("flagsmith::allFlags",{flags:JSON.stringify(s.getValue("flagsmith").getAllFlags())},!0)}catch(p){o.error("Failed to fetch flagsmith flags")}})}static setupControllers(s,t,e,r,i,a,o){return u(this,null,function*(){var I,Ue,wr;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),p=t.getValue("logger"),{viewType:g,mediaConstraints:{audio:T}}=a;t.setValue("viewType",g),t.setValue("defaults",D({mediaConfiguration:{audio:{enableHighBitrate:(I=T.enableHighBitrate)!=null?I:!1,enableStereo:(Ue=T.enableStereo)!=null?Ue:!1}}},l)),t.setValue("maxPreferredStreams",Se.isMobile()?a.maxVideoStreams.mobile:a.maxVideoStreams.desktop);let v,P,_,C,w,V,F,N,B;const G=new hO(t,s),re=new FO(s);t.setValue("connectedMeetingsSocketHandler",re);const tt=new Wl(t,s),ds=new os(t,s),ni=new vO(s),ls=new VT(t,s),A=new yO(t,s),S=new uO(s),R=new dn(t,s),x=yield ii.init(t,ls,d,o,a);t.setValue("selfController",x);const fe=yield xf.init(t,x.self,ls,G,i);if(c.participant&&(N=new Cr(t,x.self,ls)),(wr=c.e2ee)!=null&&wr.enabled&&c.e2ee.manager.init(p,t.getValue("peerSessionStore")),c.chat&&(P=yield ws.init(t,ds,R,x.self,N.participants)),c.internals&&(w=yield Lh.init(t)),c.livestream&&a.viewType===At.Livestream&&t.getValue("flagsmith").hasFeature(ee.LIVESTREAM)&&(F=new Wf(t,x.self,S)),a.viewType!==At.Chat){if(c.poll&&(v=yield Of.init(t,x.self,tt)),c.recording&&(V=new Bf(t,x.self,ls)),c.stage&&(_=new Uf(t,ni,ls,x.self,N.participants)),c.plugin){if(!N)throw new b("The plugin module cannot be initialized without the `participant` module","0102");const qs=yield r;C=yield Bc.init(t,qs,A,ds,P==null?void 0:P.chat,x.self,N.participants,i)}if(c.connectedMeetings&&(B=yield zl.init(t)),c.pip){const qs=yield Cu._init(t,x.self);t.setValue("pip",qs)}}const L={storesManager:new wD(t,A),pollController:v,selfController:x,metaController:fe,chatController:P,stageController:_,pluginController:C,recordingController:V,internalsController:w,livestreamController:F,participantController:N,connectedMeetingsController:B};return{theme:a,permissions:o,controllers:L}})}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return OT(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=["PING"];return new Gc(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Wc=wn;Yl([E.trace("Controller.init")],Wc,"init",1);Yl([E.trace("setupFlagsmith")],Wc,"setupFlagsmith",1);Yl([E.trace("Controller.createRoomNodeClient")],Wc,"createRoomNodeClient",1);Yl([E.trace("Controller.createSocketService")],Wc,"createSocketService",1);class KO{constructor(){h(this,"battery");h(this,"logger");h(this,"init",t=>u(this,null,function*(){this.logger=t;try{"getBattery"in navigator&&(this.battery=yield 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)}}));h(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});h(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});h(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 Rg=new KO;function zO(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 a=mi.baseURI.prod;t&&(a=t);const o=`https://${nn({servicePrefix:"api",baseURI:a})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:a,apiBase:o}}catch(e){throw new b("Invalid auth token","0004")}}var Qr,en,tn,Lc,bl,ZT;class YO{constructor(){m(this,bl);m(this,Qr,new Audio);m(this,en,new MediaStream);m(this,tn,new Map);m(this,Lc,void 0);n(this,Qr).srcObject=n(this,en),n(this,Qr).autoplay=!0}playTracks(t){return u(this,null,function*(){return t.forEach(e=>{n(this,tn).has(e.id)||(n(this,en).addTrack(e),n(this,tn).set(e.id,e))}),this.play()})}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&n(this,Qr).setSinkId(t)}removeTrack(t){const e=n(this,tn).get(t);e&&(n(this,en).removeTrack(e),n(this,tn).delete(t))}play(){return u(this,null,function*(){return n(this,Qr).srcObject=n(this,en),n(this,Qr).play().catch(t=>{U(this,bl,ZT).call(this,t)})})}onError(t){f(this,Lc,t)}}Qr=new WeakMap,en=new WeakMap,tn=new WeakMap,Lc=new WeakMap,bl=new WeakSet,ZT=function(t){var e;(e=n(this,Lc))==null||e.call(this,t)};var sn;class QO extends YO{constructor(){super();m(this,sn,void 0);f(this,sn,new Map)}addParticipantTrack(e,r){n(this,sn).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=n(this,sn).get(e);r&&this.removeTrack(r),n(this,sn).delete(e)}}sn=new WeakMap;var XO=Object.defineProperty,ZO=Object.getOwnPropertyDescriptor,Ql=(s,t,e,r)=>{for(var i=r>1?void 0:r?ZO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&XO(t,e,i),i},Ge,rn,Jg;let si=(Jg=class{constructor(t,e){m(this,Ge,void 0);m(this,rn,void 0);f(this,rn,t),f(this,Ge,e)}get peerId(){return n(this,rn).getValue("peerId")}static initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:Tr.v4(),a=mr.createContext(i,{peerId:i}),o=a.getValue("logger");o.init(a);const c=new eT(o);return c.init(t,e,a),a.setValue("defaults",{mediaHandler:c}),c}static init(t){return u(this,null,function*(){var v,P,_,w,V,F,N;Se.init();const{mediaHandler:e}=(v=t.defaults)!=null?v:{},r=(e==null?void 0:e.peerId)||((_=(P=t==null?void 0:t.cachedUserDetails)==null?void 0:P.peerId)!=null?_:Tr.v4()),{authToken:i,baseURI:a}=t,C=zO(i,a),{meetingId:o}=C,c=io(C,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const d=si.setupContext(r,t,o,c),l=d.getValue("telemetry"),p=d.getValue("logger");lv(p),Rg.init(p),l.init(d,{roomName:o,userId:c.participantId,organizationId:c.orgId,peerId:r},(V=(w=t.modules)==null?void 0:w.tracing)!=null?V:!0),p.init(d),p.info("Client::init::options",{clientInitOptions:H(D({},t),{authToken:`${(F=t.authToken)==null?void 0:F.slice(0,10)}...
15
- ${(N=t.authToken)==null?void 0:N.slice(-10)}`})});const g=yield Wc.init(d),T=new si(d,g);return d.setValue("meeting",T),T})}static setupContext(t,e,r,i){var d,l;const a=mr.createContext(t,e),o=D(D({},lw),e==null?void 0:e.modules),c=e.defaults||{audio:!0,video:!0};return a.setValue("options",e),a.setValue("peerId",t),a.setValue("modules",o),a.setValue("sdkName","web-core"),a.setValue("meetingId",r),a.setValue("apiBase",i.apiBase),a.setValue("baseURI",i.baseURI),a.setValue("userId",i.participantId),a.setValue("organizationId",i.orgId),a.setValue("authToken",e.authToken),a.setValue("overrides",(d=e.overrides)!=null?d:{}),a.setValue("env",uw({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",Rs(e.cachedUserDetails)),a.setValue("sdkVersion","1.2.2-staging.3"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new QO),a}join(){return u(this,null,function*(){const{selfController:t}=n(this,Ge);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){Rg.cleanup(),n(this,rn).getValue("peerSessionStore").reset();const{selfController:e}=n(this,Ge);return e.leaveRoom(t)})}get participants(){var t;return(t=n(this,Ge).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,Ge).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,Ge).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,Ge).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,Ge).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,Ge).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,Ge).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,Ge).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,Ge).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,Ge).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,Ge).stageController)==null?void 0:t.stage}get stores(){return n(this,Ge).storesManager}get audio(){return n(this,rn).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,Ge).internalsController)==null?void 0:t.internals}joinRoom(){return u(this,null,function*(){return this.join()})}leaveRoom(t){return u(this,null,function*(){return this.leave(t)})}},Ge=new WeakMap,rn=new WeakMap,Jg);Ql([ut("0002"),_r.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],si.prototype,"join",1);Ql([ut("0003")],si.prototype,"leave",1);Ql([ut("0001"),_r.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],si,"init",1);si=Ql([ut("0000")],si);const ev=si;module.exports=ev;
15
+ ${(N=t.authToken)==null?void 0:N.slice(-10)}`})});const g=yield Wc.init(d),T=new si(d,g);return d.setValue("meeting",T),T})}static setupContext(t,e,r,i){var d,l;const a=mr.createContext(t,e),o=D(D({},lw),e==null?void 0:e.modules),c=e.defaults||{audio:!0,video:!0};return a.setValue("options",e),a.setValue("peerId",t),a.setValue("modules",o),a.setValue("sdkName","web-core"),a.setValue("meetingId",r),a.setValue("apiBase",i.apiBase),a.setValue("baseURI",i.baseURI),a.setValue("userId",i.participantId),a.setValue("organizationId",i.orgId),a.setValue("authToken",e.authToken),a.setValue("overrides",(d=e.overrides)!=null?d:{}),a.setValue("env",uw({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",Rs(e.cachedUserDetails)),a.setValue("sdkVersion","1.2.2"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new QO),a}join(){return u(this,null,function*(){const{selfController:t}=n(this,Ge);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){Rg.cleanup(),n(this,rn).getValue("peerSessionStore").reset();const{selfController:e}=n(this,Ge);return e.leaveRoom(t)})}get participants(){var t;return(t=n(this,Ge).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,Ge).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,Ge).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,Ge).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,Ge).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,Ge).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,Ge).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,Ge).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,Ge).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,Ge).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,Ge).stageController)==null?void 0:t.stage}get stores(){return n(this,Ge).storesManager}get audio(){return n(this,rn).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,Ge).internalsController)==null?void 0:t.internals}joinRoom(){return u(this,null,function*(){return this.join()})}leaveRoom(t){return u(this,null,function*(){return this.leave(t)})}},Ge=new WeakMap,rn=new WeakMap,Jg);Ql([ut("0002"),_r.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],si.prototype,"join",1);Ql([ut("0003")],si.prototype,"leave",1);Ql([ut("0001"),_r.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],si,"init",1);si=Ql([ut("0000")],si);const ev=si;module.exports=ev;
package/dist/index.es.js CHANGED
@@ -27686,7 +27686,9 @@ class Xv extends qt {
27686
27686
  }
27687
27687
  getConnectedMeetings() {
27688
27688
  return u(this, null, function* () {
27689
- return this.validateConnectedMeetingsAction(), yield n(this, Ps).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();
27689
+ this.validateConnectedMeetingsAction(), this.logger.info("Getting connected meetings dump");
27690
+ const e = yield n(this, Ps).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();
27691
+ return this.logger.info("Got connected meetings dump"), e;
27690
27692
  });
27691
27693
  }
27692
27694
  /**
@@ -27694,9 +27696,11 @@ class Xv extends qt {
27694
27696
  */
27695
27697
  createMeetings(e) {
27696
27698
  return u(this, null, function* () {
27697
- return this.validateConnectedMeetingsAction(), (yield n(this, Ps).getValue("connectedMeetingsSocketHandler").createConnectedRooms(
27699
+ this.validateConnectedMeetingsAction(), this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);
27700
+ const r = yield n(this, Ps).getValue("connectedMeetingsSocketHandler").createConnectedRooms(
27698
27701
  e
27699
- )).map((i) => ({
27702
+ );
27703
+ return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`), r.map((i) => ({
27700
27704
  id: i.id,
27701
27705
  title: i.title
27702
27706
  }));
@@ -27707,9 +27711,9 @@ class Xv extends qt {
27707
27711
  */
27708
27712
  updateMeetings(e) {
27709
27713
  return u(this, null, function* () {
27710
- this.validateConnectedMeetingsAction(), yield n(this, Ps).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(
27714
+ this.validateConnectedMeetingsAction(), this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`), yield n(this, Ps).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(
27711
27715
  e.map((r) => ({ meetingId: r.id, title: r.title }))
27712
- );
27716
+ ), this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`);
27713
27717
  });
27714
27718
  }
27715
27719
  /**
@@ -27717,15 +27721,17 @@ class Xv extends qt {
27717
27721
  */
27718
27722
  deleteMeetings(e) {
27719
27723
  return u(this, null, function* () {
27720
- this.validateConnectedMeetingsAction();
27724
+ this.validateConnectedMeetingsAction(), this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);
27721
27725
  const r = this.meetings.map((a) => e.includes(a.id) && a.participants.length !== 0 ? this.moveParticipants(
27722
27726
  a.id,
27723
27727
  this.parentMeeting.id,
27724
27728
  a.participants.map((o) => o.id)
27725
27729
  ) : Promise.resolve());
27726
- return yield Promise.all(r), yield n(this, Ps).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(
27730
+ this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`), yield Promise.all(r);
27731
+ const i = yield n(this, Ps).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(
27727
27732
  e
27728
27733
  );
27734
+ return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`), i;
27729
27735
  });
27730
27736
  }
27731
27737
  /**
@@ -27737,7 +27743,7 @@ class Xv extends qt {
27737
27743
  */
27738
27744
  moveParticipants(e, r, i) {
27739
27745
  return u(this, null, function* () {
27740
- this.validateConnectedMeetingsAction();
27746
+ this.validateConnectedMeetingsAction(), this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);
27741
27747
  const a = yield n(this, Ps).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms(
27742
27748
  {
27743
27749
  sourceMeetingId: e,
@@ -27747,7 +27753,7 @@ class Xv extends qt {
27747
27753
  }))
27748
27754
  }
27749
27755
  );
27750
- return a.success && this.moveSuccessHandler(e, r, i), a;
27756
+ return a.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}`), a;
27751
27757
  });
27752
27758
  }
27753
27759
  /**
@@ -27755,7 +27761,7 @@ class Xv extends qt {
27755
27761
  */
27756
27762
  moveParticipantsWithCustomPreset(e, r, i) {
27757
27763
  return u(this, null, function* () {
27758
- this.validateConnectedMeetingsAction();
27764
+ this.validateConnectedMeetingsAction(), this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);
27759
27765
  const a = yield n(this, Ps).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms(
27760
27766
  {
27761
27767
  sourceMeetingId: e,
@@ -27763,7 +27769,7 @@ class Xv extends qt {
27763
27769
  participants: i
27764
27770
  }
27765
27771
  );
27766
- return a.success && this.moveSuccessHandler(e, r, i.map((o) => o.id)), a;
27772
+ return a.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}`), a;
27767
27773
  });
27768
27774
  }
27769
27775
  moveSuccessHandler(e, r, i) {
@@ -27857,8 +27863,9 @@ const Zv = (Jg = class {
27857
27863
  }
27858
27864
  // event handlers
27859
27865
  handleTransferPeer(s) {
27866
+ this.logger.info("Received backend request to switch connected meetings");
27860
27867
  const t = n(this, ge).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);
27861
- return this.switchMeeting(t);
27868
+ return this.logger.info(`Honoring request to switch connected meetings. Going to ${t == null ? void 0 : t.meetingId}`), this.switchMeeting(t);
27862
27869
  }
27863
27870
  switchMeeting(e) {
27864
27871
  return u(this, arguments, function* ({
@@ -28412,7 +28419,7 @@ let ti = (Kg = class {
28412
28419
  video: !0
28413
28420
  };
28414
28421
  return a.setValue("options", e), a.setValue("peerId", t), a.setValue("modules", o), a.setValue("sdkName", "web-core"), a.setValue("meetingId", r), a.setValue("apiBase", i.apiBase), a.setValue("baseURI", i.baseURI), a.setValue("userId", i.participantId), a.setValue("organizationId", i.orgId), a.setValue("authToken", e.authToken), a.setValue("overrides", (d = e.overrides) != null ? d : {}), a.setValue("env", lw({ baseURI: i.baseURI })), a.setValue("defaults", c), a.setValue("onError", e.onError || (() => {
28415
- })), a.setValue("cachedUserDetails", Rs(e.cachedUserDetails)), a.setValue("sdkVersion", "1.2.2-staging.3"), (l = e.modules) != null && l.experimentalAudioPlayback && a.setValue("audioPlayback", new YO()), a;
28422
+ })), a.setValue("cachedUserDetails", Rs(e.cachedUserDetails)), a.setValue("sdkVersion", "1.2.2"), (l = e.modules) != null && l.experimentalAudioPlayback && a.setValue("audioPlayback", new YO()), a;
28416
28423
  }
28417
28424
  join() {
28418
28425
  return u(this, null, function* () {