@cloudflare/realtimekit 1.2.4 → 1.2.5-staging.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.js CHANGED
@@ -18,4 +18,4 @@ slogScale: ${i}, isVoice: ${r}, minEnergy: ${a(this,Ir)},
18
18
  maxEnergy: ${a(this,ui)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,Ir)||i<a(this,Ir))&&f(this,Ir,i),(!a(this,ui)||i>a(this,ui))&&f(this,ui,i),{energy:(i-a(this,Ir))/(a(this,ui)-a(this,Ir))*10||0,isVoice:r})},Pc=new WeakSet,Tp=function(t){return t<5},su=new WeakSet,Dv=function(t=a(this,pn)){var r;if(!a(this,Ns)||!t){a(this,Ar).getValue("flagsmith").hasFeature(X.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,Ns)}`);return}const e={producerId:a(this,Ns),energy:Math.round(t),silent:x(r=_c,Pc,Tp).call(r,t)};f(this,Ja,e.silent),this.reportRequest(e)},ru=new WeakSet,Nv=function(t){const e=Math.log10(t);return Math.round(e)},m(_o,Pc),m(_o,ru);const P1=(s=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const e=new window.MediaStreamTrackGenerator({kind:"audio"}),r=e.writable.getWriter(),i=48e3,n=128,o=1;let c=0,d=null;const l=async()=>{try{const g=new Float32Array(n*o),S=new window.AudioData({format:"f32",sampleRate:i,numberOfFrames:n,numberOfChannels:o,timestamp:c,data:g});c+=n/i*1e6,await r.ready,await r.write(S)}catch(g){d&&clearInterval(d),r.releaseLock(),e.writable.abort()}};d=window.setInterval(l,100);const h=new MediaStream([e]).getAudioTracks()[0];return h.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),e.writable.abort()}),Object.assign(h,{fakeTracks:"fakeTracks:fakeAudioTrack"}),h.enabled=s,h}catch(e){}const t=window.AudioContext||window.webkitAudioContext;if(t)try{const e=new t;if(!e||e.state!=="running"||!e.destination)return;const r=e.createOscillator();r.frequency.value=0,r.type="sine";const i=e.createGain();i.gain.value=0,r.connect(i);const n=e.createMediaStreamDestination();i.connect(n),r.start();const o=n.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=s,o):void 0}catch(e){return}},_1=(s=!1)=>{var n,o;const t=new MediaStream().getVideoTracks()[0],e=document.createElement("canvas");e.height=(n=t==null?void 0:t.getSettings().height)!=null?n:720,e.width=(o=t==null?void 0:t.getSettings().width)!=null?o:1280;const r=e.getContext("2d");r.fillStyle="black",r.fillRect(0,0,e.width,e.height),setInterval(()=>{r.fillStyle="black",r.fillRect(0,0,e.width,e.height)},1e3);const i=e.captureStream().getVideoTracks()[0];return Object.assign(i,{fakeTracks:"fakeTracks:fakeVideoTrack"}),i.enabled=s,i};var C1=Object.defineProperty,R1=Object.getOwnPropertyDescriptor,ce=(s,t,e,r)=>{for(var i=r>1?void 0:r?R1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&C1(t,e,i),i};const Wt=["video/VP9","video/VP8"],gS=(rp=class{constructor(s,t){m(this,hi);m(this,iu);m(this,nu);m(this,au);m(this,Ac);m(this,cu);m(this,du);m(this,lu);m(this,at);m(this,Tn);m(this,uu);m(this,hu);m(this,pu);p(this,"context");p(this,"authToken");p(this,"e2ee");m(this,Cc,void 0);m(this,Rc,void 0);m(this,vt,void 0);m(this,j,void 0);m(this,Ka,void 0);m(this,Rt,void 0);m(this,gn,void 0);m(this,mn,void 0);m(this,fn,void 0);m(this,kc,void 0);m(this,fs,null);m(this,Or,void 0);m(this,Ic,void 0);m(this,Sn,void 0);m(this,vn,void 0);m(this,kt,void 0);m(this,xt,void 0);var r,i;this.context=s;const{socket:e}=t;this.mediaJoined=!1,f(this,Sn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,vn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,vt,e),f(this,gn,!1),f(this,j,new y1(s,e)),f(this,Rt,a(this,j).events),f(this,Or,new Set),f(this,kt,new Map),f(this,mn,!1),f(this,fn,new Uh(s.getValue("logger"))),f(this,xt,new _o(this.context,a(this,j).socketHandler.audioActivity.bind(a(this,j).socketHandler))),this.e2ee=(i=(r=s.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?i:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,kc,Ju(async()=>{if(!a(this,hi,Qa).mediaJoinAttempted)return;const{roomJoined:n}=await this.joinRoom(a(this,Rc),a(this,Cc),!0,!0);n&&(this.context.getValue("peerSessionStore").emit(C.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(C.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return a(this,hi,Qa).mediaJoined}set mediaJoined(s){a(this,hi,Qa).mediaJoined=s}reset(){a(this,j).closeAllProducers(),a(this,j).closeAllConsumers(),a(this,kt).clear(),a(this,Or).clear(),f(this,fs,null),a(this,fn).stop(),a(this,j).stopAllTransports(),a(this,j).reset(),f(this,fn,new Uh)}async joinRoom(s,t,e=!1,r=!1,i={}){a(this,hi,Qa).mediaJoinAttempted=!0,f(this,gn,!0),e&&this.reset();try{return await a(this,fn).push(()=>x(this,iu,Vv).call(this,s,t,r,i),"joinRoom")}catch(n){return this.logger.error("Error in room joining process",{error:n}),this.context.getValue("peerSessionStore").emit(C.ROOM_NODE_FAILED),{roomJoined:!1}}}async initializeConnection(s,t,e=!1,r={}){return a(this,fs)?a(this,fs):(f(this,fs,(async()=>{try{await x(this,Ac,yp).call(this,s,t,e,r)}catch(i){throw f(this,fs,null),i}})()),a(this,fs))}getConsumers(){return a(this,j).consumers}getProducers(){return a(this,j).producers}async leaveRoom(){a(this,j).stopAllTransports(),f(this,mn,!1),a(this,hi,Qa).mediaJoinAttempted=!1;const s={closeRoom:!1};a(this,vt).sendMessagePromise(a(this,Rt).leaveRoom,PR.toBinary(s)).then(e=>{var r;(r=hk.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()}async activatePeers(s){return this.createConsumers(s)}async createConsumers(s){return s.length===0?Promise.resolve():a(this,j).createConsumers(s)}async closeConsumers(s){if(!s.length)return;const t=s.reduce((e,r)=>{const i=a(this,j).producerIdToConsumerIdMap.get(r.producerId);return i?(e.push(i),e):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),e)},[]);await a(this,j).closeConsumers(t)}async _shareWebcam(s,t){var h,g;const e=t==="video/VP9"?me.WEBCAM:me.WEBCAM_BACKUP,r=x(this,at,At).call(this,e);if(r){const S=await r;if(a(this,j).producers.has(S)){const y=a(this,j).producers.get(S);if(!y.closed)return await y.replaceTrack({track:s}),await this.resumeWebcam(e),s;await this.disableWebcam(t)}return this._shareWebcam(s,t)}const i=[t].concat(Wt.filter(S=>S!==t)),n=x(this,pu,jv).call(this,s,i),o=On(this.context,"disableSimulcast"),c=(g=(h=this.context)==null?void 0:h.getValue("overrides"))==null?void 0:g.simulcastConfig;!(o||c&&c.disable)&&this.context.getValue("flagsmith").hasFeature(X.ENABLE_CF_SIMULCAST)?(this.logger.info("Simulcast enabled for SFU: CF"),n.encodings=nD(this.context,s)):this.logger.info("Simulcast disabled for webcam producer, SFU: CF"),this.context.getValue("flagsmith").hasFeature(X.TRACK_HINT)&&(n.track.contentHint=this.context.getValue("flagsmith").getValue(X.TRACK_HINT));const l=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,kt).delete(e)},u=a(this,j).createProducer(n,l);return x(this,Tn,rd).call(this,e,u.then(S=>S.id)),u.then(S=>S.track)}async shareWebcam(s){var r;if(s===void 0)return null;const t=(r=this.context.getValue("flagsmith").getValue(X.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=Wt.filter(i=>{var n,o;return((o=(n=a(this,Ka).sender)==null?void 0:n.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===i))>=0&&a(this,vn).get(i).size>0});return e.length===0&&e.push(Wt[0]),await Promise.all(e.map(i=>(this.logger.debug(`Calling _shareWebcam with video codec: ${i}`),this._shareWebcam(s,i)))),s}async shareScreen(s){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:ve.isElectron()},stopTracks:!1},i=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,kt).delete(me.SCREENSHARE_VIDEO),a(this,kt).delete(me.SCREENSHARE_AUDIO)},n=a(this,j).createProducer(r,i);x(this,Tn,rd).call(this,me.SCREENSHARE_VIDEO,n.then(c=>c.id));let o;if(e){const c={track:e,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ve.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},d=()=>{};o=a(this,j).createProducer(c,d),x(this,Tn,rd).call(this,me.SCREENSHARE_AUDIO,o.then(l=>l.id))}await Promise.all([n,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()}async shareMic(s){try{if(s===void 0)throw new Dt("track undefined");const t=x(this,at,At).call(this,me.MIC);if(t){const n=await t;if(a(this,j).producers.has(n)){const o=a(this,j).producers.get(n);if(!o.closed){await o.replaceTrack({track:s}),await this.resumeMic(),a(this,xt)&&(a(this,xt).audioTrack=s,a(this,xt).producerId=n,a(this,xt).start());return}await a(this,j).closeProducer(n,{stopTrack:!1})}await this.shareMic(s);return}const e=x(this,hu,qv).call(this,s),r=()=>{a(this,kt).delete(me.MIC)},i=a(this,j).createProducer(e,r);x(this,Tn,rd).call(this,me.MIC,i.then(n=>n.id)),await i.then(n=>{a(this,xt)&&(a(this,xt).audioTrack=n.track,a(this,xt).producerId=n.id,a(this,xt).start())})}catch(t){throw new k(t)}}async pauseMic(){var r;const s=await x(this,at,At).call(this,me.MIC),t=a(this,j).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=a(this,xt))==null||r.stop();const e={producerId:t.id,pause:!0};a(this,vt).sendMessage(a(this,Rt).toggleProducer,Ud.toBinary(e))}async pauseWebcam(){const s=await x(this,at,At).call(this,me.WEBCAM),t=await x(this,at,At).call(this,me.WEBCAM_BACKUP),e=a(this,j).producers.get(s),r=a(this,j).producers.get(t);if(!e&&!r){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const i=n=>{const o={producerId:n.id,pause:!0};a(this,vt).sendMessage(a(this,Rt).toggleProducer,Ud.toBinary(o))};e&&(e.pause(),i(e)),r&&(r.pause(),i(r))}async resumeMic(){const s=await x(this,at,At).call(this,me.MIC),t=a(this,j).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(C.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};a(this,vt).sendMessage(a(this,Rt).toggleProducer,Ud.toBinary(e))}async resumeWebcam(s=me.WEBCAM){const t=await x(this,at,At).call(this,s),e=a(this,j).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(C.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,vt).sendMessage(a(this,Rt).toggleProducer,Ud.toBinary(r))}async disableWebcam(s){const t=s==="video/VP9"?me.WEBCAM:me.WEBCAM_BACKUP,e=await x(this,at,At).call(this,t);x(this,uu,Hv).call(this,t),e&&await a(this,j).closeProducer(e)}async disableMic(){var t;const s=await x(this,at,At).call(this,me.MIC);s&&await a(this,j).closeProducer(s),(t=a(this,xt))==null||t.stop(),a(this,kt).delete(me.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=await x(this,at,At).call(this,me.SCREENSHARE_VIDEO),t=await x(this,at,At).call(this,me.SCREENSHARE_AUDIO);s&&await a(this,j).closeProducer(s),t&&await a(this,j).closeProducer(t),a(this,Or).clear(),a(this,kt).delete(me.SCREENSHARE_VIDEO),a(this,kt).delete(me.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(s,t){if(s){const e=await x(this,at,At).call(this,me.WEBCAM),r=await x(this,at,At).call(this,me.WEBCAM_BACKUP);await a(this,j).closeProducer(e,{stopTrack:!1}),await a(this,j).closeProducer(r,{stopTrack:!1}),this.shareWebcam(s)}if(t){const e=await x(this,at,At).call(this,me.SCREENSHARE_VIDEO);await a(this,j).closeProducer(e,{stopTrack:!1}),this.shareScreen({video:t})}}async changeDisplayName(s,t){const e={displayName:s,participantId:t!=null?t:this.peerId};if(!await a(this,j).socketHandler.changeDisplayName(e))throw new Error("failed to change display name!")}kick(s){const t={peerIds:[s]};a(this,j).socketHandler.kickPeer(t)}kickAll(){a(this,j).socketHandler.kickAll()}async muteAll(s){if(!await a(this,j).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,j).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(s){if(!await a(this,j).socketHandler.hostControlForPeer(s,"audio"))throw new Error("failed to mute given participant")}async disableVideo(s){if(!await a(this,j).socketHandler.hostControlForPeer(s,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(s){const t={participantId:s!=null?s:""};try{await a(this,vt).sendMessagePromise(a(this,Rt).globalPinPeer,UR.toBinary(t))}catch(e){this.logger.error("Error in pinning peer:",{error:e})}}validateScreenShare(s){return this.peerId===s.peerId&&a(this,j).producers.get(s.producerId)&&a(this,Or).add(s.consumerPeerId),a(this,Or).size}async switchConsumersToLayer(s,t){const e=s.map(r=>this.getConsumers().get(r));a(this,j).switchConsumersToLayer(e,t)}async handleSocketEvents(){a(this,vt).on(a(this,Rt).peerProducerCreateBroadcast,({payload:s})=>{var t,e;if(this.mediaJoined)try{const{participantId:r,producerState:i}=Hk.fromBinary(s);if(r===this.peerId)return;if(i!=null&&i.mimeType||(i.mimeType=i.kind===qs.AUDIO?"audio/opus":"video/VP8"),i.kind===qs.VIDEO&&!i.screenShare&&((e=(t=a(this,Ka).receiver)==null?void 0:t.video)==null?void 0:e.codecs.findIndex(n=>n.mimeType===Wt[0]))>=0&&a(this,Sn).get(Wt[0]).has(r)&&i.mimeType!==Wt[0]){this.logger.warn(`Ignoring producer: ${i.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${i}`),this.context.getValue("peerSessionStore").emit(C.NEW_PRODUCER,{peerId:r,producer:{...i,kind:i.kind===qs.AUDIO?"audio":"video",producingPeerId:r}})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),a(this,vt).on(a(this,Rt).peerProducerToggleBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,initiatorParticipantId:e,producerState:{kind:r,pause:i,producerId:n,screenShare:o}}=tf.fromBinary(s);if(o)return;const c=r===qs.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${t}, producerId: ${n}, kind:${c}, paused:${i} payload: ${JSON.stringify(tf.fromBinary(s))}`),t===this.peerId&&e!==this.peerId&&i&&this.context.getValue("peerSessionStore").emit(c==="audio"?C.MUTE_SELF:C.MUTE_SELF_VIDEO),t===this.peerId)return;this.context.getValue("peerSessionStore").emit(C.PRODUCER_TOGGLE,{peerId:t,producerId:n,paused:i,kind:c}),Array.from(this.getConsumers().values()).filter(l=>l.producerId===n).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(C.CONSUMER_PAUSED,{id:l.id})):(l.resume(),this.context.getValue("peerSessionStore").emit(C.CONSUMER_RESUMED,{id:l.id})))})}catch(t){this.logger.error("error in producer toggle broadcast handler",{error:t})}}),a(this,vt).on(a(this,Rt).peerLeaveBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t}=ah.fromBinary(s);if(t===this.peerId)return;this.logger.info(`peer left broadcast:${t}`),a(this,Or).delete(t),a(this,j).consumers.forEach(e=>{e.peerId===t&&e.close()}),this.context.getValue("peerSessionStore").emit(C.PEER_CLOSED,{id:t})}catch(t){this.logger.error("error in peer left broadcast",{error:t})}}),a(this,vt).on(a(this,Rt).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=Gk.fromBinary(s);if(t===this.peerId)return;this.logger.info(`producer closed broadcast:${t}`),this.context.getValue("peerSessionStore").emit(C.PRODUCER_CLOSED,{peerId:t,producerId:e});const r=a(this,j).producerIdToConsumerIdMap.get(e);if(!r){this.logger.warn(`no consumer found for producer:${e}`);return}this.logger.info(`closing consumer ${r}, producer id: ${e}`),a(this,j).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),a(this,j).producerIdToConsumerIdMap.delete(e),this.context.getValue("peerSessionStore").emit(C.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})}}),a(this,vt).on(a(this,Rt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,gn)&&!a(this,mn)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(C.ROOM_NODE_DISCONNECTED),a(this,kc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(s=>{s.forEach((t,e)=>{const r=a(this,j).consumers.get(e);r&&this.context.getValue("peerSessionStore").emit(C.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(a(this,j).producers.values()).find(i=>i.id===e);r&&this.context.getValue("peerSessionStore").emit(C.PRODUCER_SCORE_UPDATE,{id:e,kind:r.kind,appData:r.appData,score:t.score,scoreStats:t})})})}handlePeerCapabilities(s,t){var e,r,i,n;for(let o=0;o<=Wt.length;o+=1){const c=Wt[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===Wt.length-1){a(this,vn).get(c).add(s);break}}for(let o=0;o<=Wt.length;o+=1){const c=Wt[o];if(((n=(i=t==null?void 0:t.sender)==null?void 0:i.video)==null?void 0:n.codecs.findIndex(d=>d.mimeType===c))>=0||o===Wt.length-1){a(this,Sn).get(c).add(s);break}}}handlePeerLeaving(s){this.context.getValue("flagsmith").hasFeature(X.FORCE_VIDEO_CODEC)||(a(this,Sn).forEach(t=>t.delete(s)),a(this,vn).forEach((t,e)=>{t.delete(s),!(t.size!==0||e===Wt[0])&&this.disableWebcam(e)}))}},Cc=new WeakMap,Rc=new WeakMap,vt=new WeakMap,j=new WeakMap,Ka=new WeakMap,Rt=new WeakMap,gn=new WeakMap,mn=new WeakMap,fn=new WeakMap,kc=new WeakMap,fs=new WeakMap,Or=new WeakMap,Ic=new WeakMap,Sn=new WeakMap,vn=new WeakMap,kt=new WeakMap,xt=new WeakMap,hi=new WeakSet,Qa=function(){return this.context.getValue("connectionHandler")},iu=new WeakSet,Vv=async function(s,t,e,r){f(this,Rc,s);try{return a(this,fs)?await a(this,fs):await x(this,Ac,yp).call(this,s,t,e,r),x(this,au,xv).call(this,t),{roomJoined:await x(this,nu,Lv).call(this)}}catch(i){return this.logger.error("Failed to complete room join",{error:i}),{roomJoined:!1}}finally{f(this,fs,null)}},nu=new WeakSet,Lv=async function(){try{this.mediaJoined=!0;const{roomState:s}=await a(this,j).socketHandler.notifySelfJoinComplete();return f(this,Cc,s.roomUuid),f(this,mn,!0),f(this,gn,!1),!0}catch(s){return this.logger.error("Error completing room join",{error:s}),this.mediaJoined=!1,!1}},au=new WeakSet,xv=function(s){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:{...ve.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)},Ac=new WeakSet,yp=async function(s,t,e,r){var i,n;try{(n=a(this,Ic))!=null||f(this,Ic,x(i=gS,ou,Uv).call(i));const o=x(this,cu,Fv).call(this);await x(this,du,$v).call(this,s,t,e,o),await a(this,j).setupTransports({send:!0,recv:!0}),await x(this,lu,Bv).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},ou=new WeakSet,Uv=function(){const{ipInfo:s}=ht();if(!(s!=null&&s.loc))return;const[t,e]=s.loc.split(",").map(parseFloat);return{latitude:t,longitude:e}},cu=new WeakSet,Fv=function(){var e;const s=(e=this.context.getValue("flagsmith").getValue(X.FORCE_VIDEO_CODEC))==null?void 0:e.toString(),t=t1(s);return f(this,Ka,t),t},du=new WeakSet,$v=async function(s,t,e,r){await oS(async(i,n)=>{if(!a(this,vt).isConnected){n(new Error("Socket is not connected"));return}i>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${i}`});try{await a(this,j).socketHandler.joinRoom(t,s,r,e,a(this,Ic))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}},{delayTime:1e3,strategy:"exponential",maxRetryCount:1/0})},lu=new WeakSet,Bv=async function(s){if(!(!this.context.getValue("flagsmith").hasFeature(X.PRECREATE_PRODUCERS)||!s))try{const e=[];if(s.canProduceVideo===H.Allowed&&e.push(this.shareWebcam(_1(!1))),s.canProduceAudio===H.Allowed){const r=P1(!1);r&&e.push(this.shareMic(r))}e.length>0&&await Promise.all(e)}catch(e){this.logger.warn("Failed to precreate producers",{error:e})}},at=new WeakSet,At=function(s){return a(this,kt).get(s)},Tn=new WeakSet,rd=function(s,t){return a(this,kt).set(s,t)},uu=new WeakSet,Hv=function(s){return a(this,kt).delete(s)},hu=new WeakSet,qv=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},pu=new WeakSet,jv=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(rp,ou),rp);let re=gS;ce([E.trace("MediaNodeClient.reset",{country:E.location.country})],re.prototype,"reset",1),ce([E.trace("MediaNodeClient.joinRoom")],re.prototype,"joinRoom",1),ce([E.trace("MediaNodeClient.leaveRoom")],re.prototype,"leaveRoom",1),ce([E.trace("MediaNodeClient.activatePeers")],re.prototype,"activatePeers",1),ce([E.trace("MediaNodeClient.createConsumers")],re.prototype,"createConsumers",1),ce([E.trace("MediaNodeClient.closeConsumers")],re.prototype,"closeConsumers",1),ce([E.trace("MediaNodeClient._shareWebcam")],re.prototype,"_shareWebcam",1),ce([E.trace("MediaNodeClient.shareWebcam")],re.prototype,"shareWebcam",1),ce([E.trace("MediaNodeClient.shareScreen")],re.prototype,"shareScreen",1),ce([E.trace("MediaNodeClient.shareMic")],re.prototype,"shareMic",1),ce([E.trace("MediaNodeClient.pauseMic")],re.prototype,"pauseMic",1),ce([E.trace("MediaNodeClient.pauseWebcam")],re.prototype,"pauseWebcam",1),ce([E.trace("MediaNodeClient.resumeMic")],re.prototype,"resumeMic",1),ce([E.trace("MediaNodeClient.resumeWebcam")],re.prototype,"resumeWebcam",1),ce([E.trace("MediaNodeClient.disableWebcam")],re.prototype,"disableWebcam",1),ce([E.trace("MediaNodeClient.disableMic")],re.prototype,"disableMic",1),ce([E.trace("MediaNodeClient.disableScreenShare")],re.prototype,"disableScreenShare",1),ce([E.trace("MediaNodeClient.muteSelf")],re.prototype,"muteSelf",1),ce([E.trace("MediaNodeClient.resetVideoProducers")],re.prototype,"resetVideoProducers",1),ce([E.trace("MediaNodeClient.changeDisplayName")],re.prototype,"changeDisplayName",1),ce([E.trace("MediaNodeClient.kickPeer")],re.prototype,"kick",1),ce([E.trace("MediaNodeClient.kickAllPeers")],re.prototype,"kickAll",1),ce([E.trace("MediaNodeClient.muteAll")],re.prototype,"muteAll",1),ce([E.trace("MediaNodeClient.muteAllVideo")],re.prototype,"muteAllVideo",1),ce([E.trace("MediaNodeClient.disableAudio")],re.prototype,"disableAudio",1),ce([E.trace("MediaNodeClient.disableVideo")],re.prototype,"disableVideo",1),ce([E.trace("MediaNodeClient.pinPeer")],re.prototype,"pinPeer",1),ce([E.trace("MediaNodeClient.validateScreenShare")],re.prototype,"validateScreenShare",1);function mS(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 re(s,t);return s.setValue("roomNodeClient",r),r}function fS(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 k1=Object.defineProperty,I1=Object.getOwnPropertyDescriptor,Ni=(s,t,e,r)=>{for(var i=r>1?void 0:r?I1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&k1(t,e,i),i};const SS=(iv=class{constructor(s,t,e,r){m(this,It);p(this,"self");p(this,"authToken");m(this,yn,void 0);p(this,"viewType");m(this,Vs,void 0);m(this,Z,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,Z,s),this.viewType=r,this.authToken=n,f(this,yn,i),f(this,Vs,e),this.setupEvents()}get peerId(){return a(this,Z).getValue("peerId")}get telemetry(){return a(this,Z).getValue("telemetry")}get logger(){return a(this,Z).getValue("logger")}get mediaJoined(){return a(this,Z).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=ht(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await Ze.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");if(navigator.product!=="ReactNative"){const u=!s.getValue("flagsmith").hasFeature(X.PRECALL_BANDWIDTH_TEST);setTimeout(async()=>{const h=await d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(h)}),s.getValue("callstats").devices("AUDIO",h==null?void 0:h.filter(g=>g.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",h==null?void 0:h.filter(g=>g.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",h==null?void 0:h.filter(g=>g.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:ve.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:wm(s),skipConnectivityChecks:u}),l.info("Callstats:: initialized")}catch(g){l.error("Callstats:: initialization failed",{error:g})}},0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new SS(s,d,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:n,screenShareTracks:o}=this.self;if(e.canProduceAudio===H.Allowed&&r)try{await a(this,It,ts).shareMic(s),this.self.audioEnabled||a(this,It,ts).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===H.Allowed&&i)try{const d=await a(this,It,ts).shareWebcam(t);d&&d.id!==t.id&&a(this,Z).getValue("flagsmith").hasFeature(X.EXP_RESHARE)&&await a(this,It,ts).shareWebcam(d),this.self.videoEnabled||a(this,It,ts).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===H.Allowed&&n)try{await((c=a(this,It,ts))==null?void 0:c.shareScreen({video:o.video,audio:o.audio}))}catch(d){this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){a(this,Z).getValue("callstats").callEnded(),a(this,It,ts).reset(),s&&await this.joinRoom(s)}setupEvents(){a(this,Z).getValue("peerSessionStore").on(C.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,Z).getValue("peerSessionStore").on(C.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,Z).getValue("peerSessionStore").on(C.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,Z).getValue("peerSessionStore").on(C.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Z).getValue("peerSessionStore").on(C.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,Z).getValue("peerSessionStore").on(C.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&a(this,Z).getValue("flagsmith").hasFeature(X.REFRESH_ID_ON_DISCONNECTION)&&(t=fi()),a(this,yn).updateURL(t),a(this,Z).getValue("telemetry").resetPeerId(t),ht().setHeader("tracing-id",t),rr.remapContext(t,a(this,Z)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,Z).getValue("peerSessionStore").on(C.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Vs).on(U.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Vs).on(jd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,Z).getValue("peerSessionStore").emit(C.UPDATE_PERMISSIONS,t.patch)})}),a(this,Vs).on(U.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Vs).on(U.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Vs).on(U.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,Z).getValue("peerSessionStore").onAsync(C.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,Z).getValue("peerSessionStore").on(C.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var n;const i=(n=e==null?void 0:e.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),a(this,Z).getValue("peerSessionStore").on(C.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,Z).getValue("callstats").audioOff())}),a(this,Z).getValue("peerSessionStore").on(C.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,Z).getValue("callstats").videoOff())}),a(this,Z).getValue("peerSessionStore").onAsync(C.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,Z).getValue("peerSessionStore").on(C.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await a(this,Vs).joinRoom(this.self);a(this,Vs).socket.flush();const e=_h(t.stageType);if(a(this,Z).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}await this.joinMediaRoom(s),a(this,Z).notify("stageStatus")}catch(t){throw this.logger.error("Error in joinRoom",{error:t}),t}}async leaveRoom(s="left"){var t,e;if(this.logger.info(`Leaving room with state: ${s}`),(t=a(this,Z).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),a(this,Z).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,Z).notify("stageStatus");try{(e=a(this,yn))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}fS(a(this,Z)),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var n,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,Z).getAllValues();try{if(e===sr.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}mS(a(this,Z),{socket:a(this,yn),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u}=(o=await((n=a(this,It,ts))==null?void 0:n.joinRoom(this.self.name,r,s,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)return;i==="ON_STAGE"&&await this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:c}),new k("Error: could not join media room","0002")}}async leaveMediaRoom(s){const t=a(this,Z).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===sr.Webinar)&&a(this,It,ts)&&(a(this,It,ts).mediaJoined&&s!=="disconnected"&&await a(this,It,ts).leaveRoom(),!(s==="stageLeft"&&t===sr.Livestream)&&(a(this,It,ts).mediaJoined=!1))}async cleanupSelf(){await this.self.disableAudio(),await this.self.disableVideo(),await this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()}},yn=new WeakMap,Vs=new WeakMap,Z=new WeakMap,It=new WeakSet,ts=function(){return a(this,Z).getValue("roomNodeClient")},iv);let Gr=SS;Ni([E.trace("SelfController.resetSelf")],Gr.prototype,"resetSelf",1),Ni([E.trace("SelfController.setupEvents")],Gr.prototype,"setupEvents",1),Ni([E.trace("SelfController.joinRoom")],Gr.prototype,"joinRoom",1),Ni([E.trace("SelfController.leaveRoom")],Gr.prototype,"leaveRoom",1),Ni([E.trace("SelfController.joinMediaRoom")],Gr.prototype,"joinMediaRoom",1),Ni([E.trace("SelfController.leaveMediaRoom")],Gr.prototype,"leaveMediaRoom",1),Ni([E.trace("SelfController.init")],Gr,"init",1);class A1{constructor(t){m(this,Mc,void 0);f(this,Mc,t)}on(t,e){let r;t===U.roomPeerCount?r=nf.fromBinary.bind(nf):r=bf.fromBinary.bind(bf),a(this,Mc).on(t,({payload:i})=>{if(t===U.roomPeerCount&&!i)return;const n=r(i);e(n)})}}Mc=new WeakMap;class M1{constructor(t,e){m(this,Oc,void 0);m(this,Dc,void 0);f(this,Oc,e),f(this,Dc,t)}get logger(){return a(this,Dc).getValue("logger")}on(t,e){let r,i;switch(t){case U.transcript:{r=oh.fromBinary.bind(oh),i=oh.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Oc).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}Oc=new WeakMap,Dc=new WeakMap;var O1=Object.defineProperty,D1=Object.getOwnPropertyDescriptor,Wh=(s,t,e,r)=>{for(var i=r>1?void 0:r?D1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&O1(t,e,i),i};class dl{constructor(t,e){m(this,Dr,void 0);m(this,za,void 0);f(this,Dr,e),f(this,za,t)}get logger(){return a(this,za).getValue("logger")}get telemetry(){return a(this,za).getValue("telemetry")}getPolls(){return a(this,Dr).sendMessagePromise(or.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Dr).sendMessage(or.createPoll,kM.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Dr).sendMessage(or.votePoll,AM.toBinary(r))}on(t,e){let r,i;switch(t){case or.updatePoll:case or.createPoll:case or.votePoll:{r=yh.fromBinary.bind(yh),i=yh.create();break}}a(this,Dr).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){a(this,Dr).removeListeners(t)}}Dr=new WeakMap,za=new WeakMap,Wh([E.trace("PollSocketHandler.getPolls")],dl.prototype,"getPolls",1),Wh([E.trace("PollSocketHandler.createPoll")],dl.prototype,"createPoll",1),Wh([E.trace("PollSocketHandler.votePoll")],dl.prototype,"votePoll",1);var N1=Object.defineProperty,V1=Object.getOwnPropertyDescriptor,L1=(s,t,e,r)=>{for(var i=r>1?void 0:r?V1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&N1(t,e,i),i};class vS{constructor(t,e){p(this,"socket");m(this,Zt,void 0);f(this,Zt,t),this.socket=e,this.handleSocketEvents(),a(this,Zt).setValue("roomSocketHandler",this)}get telemetry(){return a(this,Zt).getValue("telemetry")}get logger(){return a(this,Zt).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}async joinRoom(t){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(U.joinRoom,yI.toBinary(e));try{const{peer:n}=Nn.fromBinary((await r).payload);a(this,Zt).getValue("connectionHandler").socketJoined=!0,a(this,Zt).getValue("peerSessionStore").emit(C.SOCKET_SERVICE_ROOM_JOINED,{peer:n});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return a(this,Zt).getValue("peerSessionStore").emit(C.ROOM_STATE,d),a(this,Zt).getValue("peerSessionStore").emit(C.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),new k("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,n)}}async getAllAddedParticipants(){try{return iA.fromBinary((await this.socket.sendMessagePromise(U.getAllAddedParticipants)).payload).participants.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}async getRoomPeers(t,e,r){let i;try{const n={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise(U.getRoomPeersInfo,lI.toBinary(n));i=lh.fromBinary(o.payload)}catch(n){this.logger.error("getRoomPeers::binary_decode_error",{error:n})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise(U.getRoomPeersInfo);t=lh.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getStagePeers(){let t;try{const e=await this.socket.sendMessagePromise(U.getRoomPeersInfo);t=lh.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getPeerInfo(t){let e;try{const r=await this.socket.sendMessagePromise(U.getPeerInfo,cf.toBinary({peerId:t}));e=Nn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=of.create();try{const e=await this.socket.sendMessagePromise(U.getRoomInfo);t=of.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=gf.create();try{const e=await this.socket.sendMessagePromise(U.getRoomStageState);t=gf.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t}async broadcastMessage(t,e){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(U.broadcastMessage,go.toBinary(r))}async broadcastToMeetings(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(U.broadcastToEntity,go.toBinary(i))}async broadcastToPeers(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(U.broadcastToEntity,go.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(U.leaveRoom,bI.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(U.kick,hf.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(U.kickAll,Ym.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(U.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.acceptWaitingRoomRequests,lA.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.denyWaitingRoomRequests,hA.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(jd.updateUserPreset,BA.toBinary(r))}handleSocketEvents(){this.socket.on(U.broadcastMessage,({payload:t})=>{try{const e=go.fromBinary(t);a(this,Zt).getValue("peerSessionStore").emit(C.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on(U.broadcastToEntity,({payload:t})=>{try{const e=go.fromBinary(t);a(this,Zt).getValue("peerSessionStore").emit(C.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case U.joinRoom:case U.leaveRoom:case U.kick:case U.kickAll:{r=Nn.fromBinary.bind(Nn),i=Nn.create();break}case U.getWaitingRoomRequests:{r=(n,o)=>n?pf.fromBinary(n,o):{requests:[]},i=pf.create();break}case U.recordingPaused:case U.recordingStarted:case U.recordingStopped:{r=Cf.fromBinary.bind(Cf);break}case jd.updateUserPreset:{r=ff.fromBinary.bind(ff);break}case bs.peerJoinedBroadcast:case $r.peerJoinedBroadcast:{r=Zm.fromBinary.bind(Zm);break}case bs.selfJoinComplete:case $r.selfJoinComplete:{r=nh.fromBinary.bind(nh);break}case bs.globalPeerPinBroadcast:case $r.globalPeerPinBroadcast:{r=sf.fromBinary.bind(sf);break}case bs.selectedPeer:case $r.selectedPeer:{r=ih.fromBinary.bind(ih);break}case bs.selectedPeerDiff:case $r.selectedPeerDiff:{r=Xm.fromBinary.bind(Xm);break}case bs.leaveRoom:case $r.leaveRoom:{r=ah.fromBinary.bind(ah);break}}this.socket.on(t,({payload:n})=>{let o=i;if(!r)return e(void 0);try{o=r(n)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}async getUserPermissions(t){const e={userIds:[t]};try{const r=await this.socket.sendMessagePromise(jd.getUserPresets,NA.toBinary(e)),i=UA.fromBinary(r.payload).peerPresets[0],n=new TextDecoder().decode(i.preset),o=JSON.parse(n).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}}}Zt=new WeakMap,L1([E.trace("RoomSocketHandler.joinRoom")],vS.prototype,"joinRoom",1);class x1{constructor(t){m(this,Ut,void 0);f(this,Ut,t)}async getStageRequests(){const{payload:t}=await a(this,Ut).sendMessagePromise(U.getStageRequests);return t?Th.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,Ut).sendMessage(U.requestStageAccess)}cancelRequestAccess(){a(this,Ut).sendMessage(U.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,Ut).sendMessage(U.grantStageAccess,vM.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,Ut).sendMessage(U.denyStageAccess,yM.toBinary(e))}joinStage(){return a(this,Ut).sendMessagePromise(U.joinStage,void 0,void 0,U.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,Ut).sendMessagePromise(U.leaveStage,Pf.toBinary(e),void 0,U.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,Ut).sendMessagePromise(U.leaveStage,Pf.toBinary(e))}on(t,e){let r;switch(t){case U.grantStageAccess:case U.denyStageAccess:{r=void 0;break}case U.getStagePeers:{r=wf.fromBinary.bind(wf);break}case U.getStageRequests:case U.requestStageAccess:case U.cancelStageRequest:{r=Th.fromBinary.bind(Th);break}case U.peerStageStatusUpdate:{r=rf.fromBinary.bind(rf);break}}a(this,Ut).on(t,({payload:i,id:n})=>{if(!i||!r)return e(void 0,n);const o=r(i);return e(o,n)})}async getPeerInfo(t){const e=await a(this,Ut).sendMessagePromise(U.getPeerInfo,cf.toBinary({peerId:t}));return Nn.fromBinary(e.payload)}}Ut=new WeakMap;class U1{constructor(t,e){m(this,Ye,void 0);m(this,Nc,void 0);f(this,Ye,e),f(this,Nc,t)}get logger(){return a(this,Nc).getValue("logger")}addPlugin(t,e){a(this,Ye).sendMessage(G.addPlugin,V0.toBinary({pluginId:t,staggered:e}))}removePlugin(t){a(this,Ye).sendMessage(G.removePlugin,x0.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await a(this,Ye).sendMessagePromise(G.getPlugins);return t?aM.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};a(this,Ye).sendMessage(G.customPluginEventToRoom,J0.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const n={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,Ye).sendMessage(G.customPluginEventToPeers,z0.toBinary(n),i)}enablePluginForRoom(t,e){a(this,Ye).sendMessage(G.enablePluginForRoom,F0.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){a(this,Ye).sendMessage(G.enablePluginForPeers,q0.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){a(this,Ye).sendMessage(G.disablePluginForRoom,B0.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){a(this,Ye).sendMessage(G.disablePluginForPeers,G0.toBinary({pluginId:t,peerIds:e}),r)}storeInsertKeys(t,e,r,i){const n={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,Ye).sendMessage(G.storeInsertKeys,vf.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,Ye).sendMessage(G.storeGetKeys,Z0.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,Ye).sendMessage(G.storeDeleteKeys,tM.toBinary(n),i)}storeDelete(t,e,r){a(this,Ye).sendMessage(G.storeDelete,rM.toBinary({pluginId:t,storeName:e}),r)}getPluginDataOld(t,e){this.logger.info("getPluginDataOld",{plugin:{id:t,storeName:e}})}storePluginDataOld(t,e,r){const i={pluginId:t,storeName:e,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};a(this,Ye).sendMessage(G.storeInsertKeys,vf.toBinary(i))}on(t,e){let r;switch(t){case G.addPlugin:case G.enablePluginForPeers:case G.enablePluginForRoom:{r=vh.fromBinary.bind(vh);break}case G.removePlugin:case G.disablePluginForPeers:case G.disablePluginForRoom:{r=Tf.fromBinary.bind(Tf);break}case G.customPluginEventToPeers:case G.customPluginEventToRoom:{r=Ef.fromBinary.bind(Ef);break}case G.storeInsertKeys:case G.storeGetKeys:case G.storeDeleteKeys:case G.storeDelete:{r=yf.fromBinary.bind(yf);break}}a(this,Ye).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}Ye=new WeakMap,Nc=new WeakMap;var F1=Object.defineProperty,$1=(s,t,e)=>t in s?F1(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,B1=(s,t,e)=>($1(s,typeof t!="symbol"?t+"":t,e),e),Jh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},O=(s,t,e)=>(Jh(s,t,"read from private field"),e?e.call(s):t.get(s)),Ee=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},ie=(s,t,e,r)=>(Jh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),Pe=(s,t,e)=>(Jh(s,t,"access private method"),e),ll={},H1={get exports(){return ll},set exports(s){ll=s}},Hn=typeof Reflect=="object"?Reflect:null,TS=Hn&&typeof Hn.apply=="function"?Hn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},ul;Hn&&typeof Hn.ownKeys=="function"?ul=Hn.ownKeys:Object.getOwnPropertySymbols?ul=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:ul=function(s){return Object.getOwnPropertyNames(s)};function q1(s){console&&console.warn&&console.warn(s)}var yS=Number.isNaN||function(s){return s!==s};function de(){de.init.call(this)}H1.exports=de,ll.once=J1,de.EventEmitter=de,de.prototype._events=void 0,de.prototype._eventsCount=0,de.prototype._maxListeners=void 0;var ES=10;function hl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(de,"defaultMaxListeners",{enumerable:!0,get:function(){return ES},set:function(s){if(typeof s!="number"||s<0||yS(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");ES=s}}),de.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},de.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||yS(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 bS(s){return s._maxListeners===void 0?de.defaultMaxListeners:s._maxListeners}de.prototype.getMaxListeners=function(){return bS(this)},de.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var n;if(t.length>0&&(n=t[0]),n instanceof Error)throw n;var o=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw o.context=n,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")TS(c,this,t);else for(var d=c.length,l=RS(c,d),e=0;e<d;++e)TS(l[e],this,t);return!0};function wS(s,t,e,r){var i,n,o;if(hl(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=bS(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,q1(c)}return s}de.prototype.addListener=function(s,t){return wS(this,s,t,!1)},de.prototype.on=de.prototype.addListener,de.prototype.prependListener=function(s,t){return wS(this,s,t,!0)};function j1(){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 PS(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=j1.bind(r);return i.listener=e,r.wrapFn=i,i}de.prototype.once=function(s,t){return hl(t),this.on(s,PS(this,s,t)),this},de.prototype.prependOnceListener=function(s,t){return hl(t),this.prependListener(s,PS(this,s,t)),this},de.prototype.removeListener=function(s,t){var e,r,i,n,o;if(hl(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,n=e.length-1;n>=0;n--)if(e[n]===t||e[n].listener===t){o=e[n].listener,i=n;break}if(i<0)return this;i===0?e.shift():G1(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this},de.prototype.off=de.prototype.removeListener,de.prototype.removeAllListeners=function(s){var t,e,r;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[s]),this;if(arguments.length===0){var i=Object.keys(e),n;for(r=0;r<i.length;++r)n=i[r],n!=="removeListener"&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=e[s],typeof t=="function")this.removeListener(s,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(s,t[r]);return this};function _S(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?W1(i):RS(i,i.length)}de.prototype.listeners=function(s){return _S(this,s,!0)},de.prototype.rawListeners=function(s){return _S(this,s,!1)},de.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):CS.call(s,t)},de.prototype.listenerCount=CS;function CS(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}de.prototype.eventNames=function(){return this._eventsCount>0?ul(this._events):[]};function RS(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function G1(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function W1(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function J1(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,n),r(o)}function n(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}kS(s,t,n,{once:!0}),t!=="error"&&K1(s,i,{once:!0})})}function K1(s,t,e){typeof s.on=="function"&&kS(s,"error",t,e)}function kS(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(n){r.once&&s.removeEventListener(t,i),e(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class z1 extends v{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const IS=new z1;class AS{static encode(t){return IS.toBinary(t)}static decode(t){return IS.fromBinary(new Uint8Array(t))}}function Y1(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Wr;class Q1{constructor(t={}){B1(this,"opts"),Ee(this,Wr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ie(this,Wr,0)}async wait(){ie(this,Wr,O(this,Wr)+1);const t=Y1(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**O(this,Wr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return O(this,Wr)}reset(){ie(this,Wr,0)}}Wr=new WeakMap;const Jr={debug:0,info:1,warn:2,error:3};var Vi,Li;class X1{constructor(t){Ee(this,Vi,void 0),Ee(this,Li,void 0),ie(this,Vi,console),ie(this,Li,t)}debug(...t){Jr[O(this,Li)]>Jr.debug||O(this,Vi).debug("[Sockrates]:",...t)}info(...t){Jr[O(this,Li)]>Jr.info||O(this,Vi).info("[Sockrates]:",...t)}warn(...t){Jr[O(this,Li)]>Jr.warn||O(this,Vi).warn("[Sockrates]:",...t)}error(...t){Jr[O(this,Li)]>Jr.error||O(this,Vi).error("[Sockrates]:",...t)}}Vi=new WeakMap,Li=new WeakMap;var MS=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(MS||{});const Z1="2",eN="3";var De,qn,_e,Ue,Kr,et,hr,zr,Cs,jn,pr,Kh,OS,Co,pl,zh,DS,Yh,NS,gl,Qh,Xh,VS,Ro,ml,ko,fl,Sl,Zh,Gn,Io,Ao,vl;class tN{constructor(t,e){var g,S,y,_,w,b,L,$,N,B;Ee(this,Kh),Ee(this,Co),Ee(this,zh),Ee(this,Yh),Ee(this,gl),Ee(this,Xh),Ee(this,Ro),Ee(this,ko),Ee(this,Sl),Ee(this,Gn),Ee(this,Ao),Ee(this,De,void 0),Ee(this,qn,void 0),Ee(this,_e,void 0),Ee(this,Ue,void 0),Ee(this,Kr,void 0),Ee(this,et,void 0),Ee(this,hr,void 0),Ee(this,zr,void 0),Ee(this,Cs,void 0),Ee(this,jn,void 0),Ee(this,pr,void 0);var r,i,n,o,c,d,l,u,h;ie(this,qn,t),ie(this,Kr,[]),ie(this,et,new ll),ie(this,hr,!0),ie(this,Cs,!1),ie(this,_e,e!=null?e:{}),(g=(r=O(this,_e)).autoReconnect)!=null||(r.autoReconnect=!0),(S=(i=O(this,_e)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(y=(n=O(this,_e)).pingTimeout)!=null||(n.pingTimeout=3e4),(_=(o=O(this,_e)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(w=(c=O(this,_e)).debug)!=null||(c.debug=!0),(b=(d=O(this,_e)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(L=(l=O(this,_e)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),($=(u=O(this,_e)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(N=(h=O(this,_e)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),ie(this,zr,{code:void 0,reason:void 0}),ie(this,Ue,(B=O(this,_e).logger)!=null?B:new X1(O(this,_e).debug?"debug":"info")),ie(this,pr,new Q1)}get readyState(){var t;return(t=O(this,De))==null?void 0:t.readyState}get url(){return O(this,qn)}updateURL(t){ie(this,qn,t),Pe(this,Xh,VS).call(this)}get config(){return O(this,_e)}get sendQueue(){return O(this,Kr)}flush(){if(!O(this,_e).queueOnDisconnect)return!1;const t=[];return O(this,Kr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ie(this,Kr,t),O(this,Kr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){O(this,Ue).debug("Websocket was already connecting or connected.");return}if(O(this,hr)!==!1)return new Promise((e,r)=>{Pe(this,Gn,Io).call(this),Pe(this,Ao,vl).call(this);try{ie(this,De,new WebSocket(Pe(this,Kh,OS).call(this,O(this,qn)))),O(this,De).binaryType="arraybuffer",O(this,Ue).debug("Connecting");const i=setTimeout(()=>{O(this,Ue).debug("Connection timeout. Closing socket"),ie(this,hr,!0),Pe(this,Ao,vl).call(this),O(this,De).close(3001,"Connection Timeout"),O(this,_e).autoReconnect&&!O(this,Cs)&&(O(this,et).emit("reconnecting"),Pe(this,Ro,ml).call(this)),r(new Error("Connection timed out!"))},O(this,_e).connectionTimeout);O(this,De).onopen=()=>{O(this,Ue).debug(`Ready State: ${MS[O(this,De).readyState]}`),i&&clearTimeout(i),Pe(this,Sl,Zh).call(this),ie(this,zr,{code:void 0,reason:void 0}),O(this,et).emit("connected"),O(this,_e).flushOnReconnect&&this.flush(),e()},O(this,De).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),O(this,Ue).debug("Socket closed. Close event:",{event:n}),O(this,Ue).debug(`Connection closed code: ${o}`),O(this,Ue).debug(`Connection closed reason: ${c}`),O(this,Cs)||Pe(this,gl,Qh).call(this,o,c)}catch(o){Pe(this,Co,pl).call(this,o)}},O(this,De).onerror=n=>{Pe(this,Co,pl).call(this,n)},O(this,De).onmessage=n=>Pe(this,zh,DS).call(this,n)}catch(i){Pe(this,Co,pl).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(O(this,_e).queueOnDisconnect&&(!O(this,De)||O(this,De).readyState!==1))return O(this,Ue).debug("Queuing message since socket is not connected!",n),O(this,Kr).push(n),!1;const o=AS.encode(n);return Pe(this,ko,fl).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return Pe(this,ko,fl).call(this,t)}receive(t,e){return O(this,et).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){O(this,et).on(t,e);return}this.receive(t,e)}removeAllListeners(){O(this,et).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){O(this,et).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){O(this,et).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ie(this,hr,!1),Pe(this,Gn,Io).call(this),this.removeAllListeners(),ie(this,zr,{code:1e3,reason:"Sockrates disconnect method called"}),O(this,De).close(1e3,"Sockrates disconnect method called.")}}De=new WeakMap,qn=new WeakMap,_e=new WeakMap,Ue=new WeakMap,Kr=new WeakMap,et=new WeakMap,hr=new WeakMap,zr=new WeakMap,Cs=new WeakMap,jn=new WeakMap,pr=new WeakMap,Kh=new WeakSet,OS=function(s){if(s.startsWith("ws://")||s.startsWith("wss://"))return s;if(s.startsWith("https://"))return`wss://${s.substring(8)}`;if(s.startsWith("http://"))return`ws://${s.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},Co=new WeakSet,pl=function(s,t){O(this,Ue).error("Error:",{error:s}),O(this,et).emit("errored",{error:s}),t==null||t(s)},zh=new WeakSet,DS=function(s){if(Pe(this,Sl,Zh).call(this),s.data===Z1){O(this,Ue).debug("Received ping from server"),Pe(this,ko,fl).call(this,eN);return}const t=AS.decode(s.data),{id:e,payload:r}=t;O(this,Ue).debug("Received message",{event:t.event,messageID:e}),O(this,et).emit(t.event.toString(),{id:e,payload:r})},Yh=new WeakSet,NS=function(){return O(this,De).readyState===1},gl=new WeakSet,Qh=function(s,t){ie(this,zr,{reason:t,code:s}),O(this,et).emit("disconnected",{code:s,reason:t})},Xh=new WeakSet,VS=function(){const{reason:s,code:t}=O(this,zr);t&&t!==1e3&&O(this,hr)&&O(this,_e).autoReconnect&&!O(this,Cs)&&(O(this,Ue).debug(`Triggering reconnection due to ${s}.`),O(this,et).emit("reconnecting"),Pe(this,Ro,ml).call(this))},Ro=new WeakSet,ml=async function(s=!0){if(s&&O(this,Cs)){O(this,Ue).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(O(this,Cs)||O(this,pr).reset(),O(this,_e).maxReconnectionAttempts!==null&&O(this,pr).getAttempts()>=O(this,_e).maxReconnectionAttempts){O(this,et).emit("failed"),ie(this,Cs,!1);return}ie(this,Cs,!0),Pe(this,Ao,vl).call(this),Pe(this,Gn,Io).call(this);try{if(await O(this,pr).wait(),O(this,hr)===!1)return;if(O(this,Ue).debug(`Reconnection attempt ${O(this,pr).getAttempts()}`),O(this,et).emit("reconnectAttempt",{attempt:O(this,pr).getAttempts()}),await this.connect(),!Pe(this,Yh,NS).call(this))throw Error("Reconnect Failed");ie(this,Cs,!1),ie(this,zr,{code:void 0,reason:void 0}),O(this,et).emit("reconnected")}catch(t){O(this,Ue).debug("Failed to reconnect."),O(this,et).emit("reconnectFailure",{attempt:O(this,pr).getAttempts()}),Pe(this,Ro,ml).call(this,!1)}},ko=new WeakSet,fl=function(s){try{return O(this,De).send(s),!0}catch(t){return O(this,Ue).error(t.message),!1}},Sl=new WeakSet,Zh=function(){this.config.disconnectOnPingTimeout&&(O(this,Ue).debug("Resetting ping timeout"),Pe(this,Gn,Io).call(this),ie(this,jn,setTimeout(()=>{var s;O(this,Ue).debug("Disconnecting the socket due to ping timeout"),ie(this,hr,!0);const t=3002,e="Ping timeout";(s=O(this,De))==null||s.close(t,e),Pe(this,gl,Qh).call(this,t,e)},O(this,_e).pingTimeout)))},Gn=new WeakSet,Io=function(){O(this,jn)&&(clearTimeout(O(this,jn)),ie(this,jn,void 0))},Ao=new WeakSet,vl=function(){O(this,De)&&(O(this,De).onopen=void 0,O(this,De).onerror=void 0,O(this,De).onmessage=void 0,O(this,De).onclose=void 0)};var sN=Object.defineProperty,rN=Object.getOwnPropertyDescriptor,Tl=(s,t,e,r)=>{for(var i=r>1?void 0:r?rN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&sN(t,e,i),i};const LS=65535,iN=3e3,xS=(nv=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,Me);m(this,Vc);m(this,Lc);m(this,pi,void 0);m(this,Ae,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");m(this,Ss,void 0);m(this,ot,void 0);var n;if(!t||!e||!r)throw new k("peerId, meetingId, or authToken can not be empty","0404");f(this,Ss,void 0),f(this,ot,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,pi,x(this,Vc,Ep).call(this,t)),f(this,Ae,new tN(a(this,pi),{autoReconnect:!0,disconnectOnPingTimeout:(n=i.includes("PING"))!=null?n:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Me,je).socketJoinAttempted}set joinAttempted(s){a(this,Me,je).socketJoinAttempted=s}get telemetry(){return a(this,ot).getValue("telemetry")}get logger(){return a(this,ot).getValue("logger")}get peerId(){return a(this,ot).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,pi,x(this,Vc,Ep).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Ae).updateURL(a(this,pi))}static getSocketEdgeDomain(s){return bi({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,pi)}async connect(){a(this,Me,je).socketJoinAttempted=!0,await a(this,Ae).connect(),a(this,Me,je).socketJoinAttempted=!0,a(this,Me,je).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){a(this,Me,je).socketJoinAttempted=!1,a(this,Ae).disconnect(),a(this,Me,je).socketJoinAttempted=!0,a(this,Me,je).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Ae).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,ot).getValue("telemetry").injectContext(r),a(this,Ae).send(s,e!=null?e:x(this,Lc,bp).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:i,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:i}){const n=i!=null?i:s;return new Promise((o,c)=>{const d=(y,_)=>{a(this,Ae).removeListener(n,y),a(this,Ae).removeListener(LS,_),a(this,Ae).removeListener($r.errorResponse,_),a(this,Ae).removeListener(bs.errorResponse,_)},l=r!=null?r:x(this,Lc,bp).call(this),u={};a(this,ot).getValue("telemetry").injectContext(u);const g=({id:y,payload:_})=>{if(l===y){let w;try{const b=sk.fromBinary(_);w=new Error(b.errorMessage)}catch(b){w=new Error("failed to parse error message",{cause:b});try{const L=rI.fromBinary(_);w=new Error(L.message)}catch(L){w=new Error("failed to parse error message",{cause:L})}}c(w),d(S,g)}},S=({id:y,payload:_})=>{l===y&&(o({id:y,payload:_}),d(S,g))};a(this,Ae).on(n,S),a(this,Ae).on(LS,g),a(this,Ae).on($r.errorResponse,g),a(this,Ae).on(bs.errorResponse,g),setTimeout(()=>{d(S,g),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Ae).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){a(this,Ae).on(s,t)}onStateEvent(s,t){a(this,Ae).on(s,t)}removeListener(s,t){a(this,Ae).removeListener(s,t)}removeListeners(s){a(this,Ae).removeListeners(s)}flush(){return a(this,Ae).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),a(this,Ss)&&(clearTimeout(a(this,Ss)),f(this,Ss,void 0)),a(this,Me,je).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t},country:E.location.country});const{recv:e,send:r}=(i=a(this,Me,je).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Bn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Bn.CONNECTED?a(this,ot).getValue("peerSessionStore").emit(C.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Me,je).joinAttempted}):f(this,Ss,setTimeout(()=>{a(this,ot).getValue("peerSessionStore").emit(C.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Me,je).joinAttempted}),f(this,Ss,void 0)},iN)),a(this,Me,je).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge",{country:E.location.country}),a(this,Me,je).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,Me,je).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,Me,je).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Me,je).mediaJoinAttempted}}),a(this,Ss)&&(clearTimeout(a(this,Ss)),f(this,Ss,void 0)),a(this,ot).getValue("peerSessionStore").emit(C.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Me,je).mediaJoinAttempted}),a(this,Me,je).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge",{country:E.location.country}),a(this,ot).getValue("peerSessionStore").emit(C.SOCKET_SERVICE_FAILED),a(this,Me,je).updateSocketConnectionState("failed")})}},pi=new WeakMap,Ae=new WeakMap,Me=new WeakSet,je=function(){return a(this,ot).getValue("connectionHandler")},Ss=new WeakMap,ot=new WeakMap,Vc=new WeakSet,Ep=function(s){let t=xS.getSocketEdgeDomain(a(this,ot).getValue("baseURI"));typeof On(a(this,ot),"socket_server_base")=="string"&&(t=On(a(this,ot),"socket_server_base"));const e=`wss://${t}`,r=new URL(`${e}/ws`),i=this.peerId,n={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...i!==s&&{oldPeerID:i},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>Fd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(n).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},Lc=new WeakSet,bp=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},nv);let Mo=xS;Tl([E.trace("SocketService.connect")],Mo.prototype,"connect",1),Tl([E.trace("SocketService.disconnect")],Mo.prototype,"disconnect",1),Tl([E.trace("SocketService.sendMessagePromise")],Mo.prototype,"sendMessagePromise",1),Tl([E.trace("SocketService.sendMessagePromiseWithTimeout")],Mo.prototype,"sendMessagePromiseWithTimeout",1);class nN{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=AI.fromBinary(t),r=e.meetings.map(o=>{var c;return{id:o.id,title:o.title,participants:(c=o.participants)!=null?c:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(n=e.parentMeeting.participants)!=null?n:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=sA.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=uf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return lf.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return WI.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(U.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(U.createConnectedRooms,NI.toBinary({payloads:t}));return lf.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}async updateConnectedRooms(t){}async disableConnectedRooms(t){const e=t.map(i=>({id:i})),r=await this.socketService.sendMessagePromise(U.deleteConnectedRooms,jI.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(U.movePeers,XI.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 aN=Object.defineProperty,oN=Object.getOwnPropertyDescriptor,cN=(s,t,e,r)=>{for(var i=r>1?void 0:r?oN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&aN(t,e,i),i};class US extends $t{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);m(this,Ls,void 0);f(this,Ls,e)}get supportsConnectedMeetings(){return a(this,Ls).getValue("self").id!==""}get isActive(){return this.meetings.length!==0}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
19
19
  Please connect with our support team to enable connected meetings.`)}async getConnectedMeetings(){this.validateConnectedMeetingsAction(),this.logger.info("Getting connected meetings dump");const e=await a(this,Ls).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await a(this,Ls).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await a(this,Ls).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)}async deleteMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),await Promise.all(r);const i=await a(this,Ls).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,Ls).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return n.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),n}async moveParticipantsWithCustomPreset(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,Ls).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return n.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),n}moveSuccessHandler(e,r,i){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>n.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>n.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>n.get(d)));return{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}Ls=new WeakMap,cN([Mt({maxInvocations:60,period:60})],US.prototype,"getConnectedMeetings",1);var dN=Object.defineProperty,lN=Object.getOwnPropertyDescriptor,ep=(s,t,e,r)=>{for(var i=r>1?void 0:r?lN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&dN(t,e,i),i};const FS=(av=class{constructor(s){p(this,"connectedMeetings");m(this,Se,void 0);f(this,Se,s),this.connectedMeetings=new US(s)}get telemetry(){return a(this,Se).getValue("telemetry")}get logger(){return a(this,Se).getValue("logger")}static init(s){const t=new FS(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.transferPeer,this.handleTransferPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.movedPeer,this.handleMovedPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,n,o,c;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
20
20
  Please connect with our support team to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:a(this,Se).getValue("self").videoEnabled,audio:a(this,Se).getValue("self").audioEnabled};try{a(this,Se).getValue("self").cleanupEvents(),await a(this,Se).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,Se).getValue("meeting"))==null?void 0:i.meta)==null?void 0:n.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await BS.init({...a(this,Se).getValue("options"),cachedUserDetails:null,defaults:{...a(this,Se).getValue("options").defaults,...e,mediaHandler:a(this,Se).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=a(this,Se).getValue("self");r.self.setName(a(this,Se).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return a(this,Se).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s),e=new Map;this.connectedMeetings.meetings.forEach(r=>{e.set(r.id,r)}),t.forEach(r=>{e.has(r.id)?e.get(r.id).title=r.title:e.set(r.id,{...r,participants:[]})}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Se=new WeakMap,av);let yl=FS;ep([E.trace("ConnectedMeetingsController.getConnectedMeetings")],yl.prototype,"getConnectedMeetings",1),ep([E.trace("ConnectedMeetingsController.setupEvents")],yl.prototype,"setupEvents",1),ep([E.trace("ConnectedMeetingsController.switchMeeting")],yl.prototype,"switchMeeting",1);var uN=Object.defineProperty,hN=Object.getOwnPropertyDescriptor,El=(s,t,e,r)=>{for(var i=r>1?void 0:r?hN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&uN(t,e,i),i};const Wn=class{constructor(s,t,e){p(this,"apiBase");p(this,"selfController");p(this,"pollController");p(this,"chatController");p(this,"metaController");p(this,"storesManager");p(this,"stageController");p(this,"pluginController");p(this,"internalsController");p(this,"recordingController");p(this,"livestreamController");p(this,"participantController");p(this,"connectedMeetingsController");p(this,"telemetry");p(this,"logger");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController,this.connectedMeetingsController=t.connectedMeetingsController,this.telemetry=e.getValue("telemetry"),this.logger=e.getValue("logger")}static async init(s){var N,B;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(fS(s),ve.isSupported()===!1)throw new k("Browser not supported","0010",c,!0);const d=nO(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(n),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new $O(s);s.setValue("connectionHandler",l);const u=Wn.createSocketService(s),h=u.connect(),g=d.getUserDetails(),S=d.getPlugins();let y,_="";try{await Wn.setupFlagsmith(s)}catch(Y){c.error("Failed to setup flagsmith",{error:Y})}try{await h}catch(Y){c.error("[Controller]: Failed to connect to socket server:",{error:Y})}try{({meetingTitle:_}=await d.getRoomNodeData()),y=await g,c.info("CF SFU is being used."),s.setValue("presetName",y.preset.name)}catch(Y){c.error("Failed to get room metadata",{error:Y})}const w=Dh.init(y.preset,!s.getValue("modules").theme),b=Vh.init(s,w.viewType,y.preset.permissions),L=Wn.setupControllers(u,s,y,S,_,w,b);IO(w)&&((N=Wn.createRoomNodeClient(s,u).initializeConnection(y.participant.name,i,!1,b))==null||N.catch(ae=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:ae})})),E.location.country=(B=d.ipInfo)==null?void 0:B.country;const{controllers:$}=await L;return lC(),new Wn(e,$,s)}static async setupFlagsmith(s){var l;const{peerId:t,baseURI:e,overrides:r,meetingId:i,organizationId:n,logger:o}=s.getAllValues(),c=dC(i),d={entity:Yu.PEER,clientId:n,isAnonUser:!n,sdkVersion:s.getValue("sdkVersion"),presetName:s.getValue("presetName"),meetingHash:c,roomName:i,...ve.getDeviceInfo(),isReactNative:navigator.isReactNative};try{const u=(l=r==null?void 0:r.whitelabelled_flags_endpoint)==null||l?bi({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";await s.getValue("flagsmith").identify(`${Yu.PEER}_${t}`,JSON.parse(JSON.stringify(d)),!1,5e3,u,o),o.info("flagsmith::allFlags",{flags:JSON.stringify(s.getValue("flagsmith").getAllFlags())},!0)}catch(u){o.error("Failed to fetch flagsmith flags")}}static async setupControllers(s,t,e,r,i,n,o){var V,R,Je;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),u=t.getValue("logger"),{viewType:h,mediaConstraints:{audio:g}}=n;t.setValue("viewType",h),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(V=g.enableHighBitrate)!=null?V:!1,enableStereo:(R=g.enableStereo)!=null?R:!1}},...l}),t.setValue("maxPreferredStreams",ve.isMobile()?n.maxVideoStreams.mobile:n.maxVideoStreams.desktop);let S,y,_,w,b,L,$,N,B;const Y=new M1(t,s),ae=new nN(s);t.setValue("connectedMeetingsSocketHandler",ae);const Tt=new dl(t,s),xs=new cr(t,s),_n=new x1(s),Us=new vS(t,s),I=new U1(t,s),T=new A1(s),P=await Gr.init(t,Us,d,o,n);t.setValue("selfController",P);const F=await Vf.init(t,P.self,Us,Y,i);if(c.participant&&(N=new ur(t,P.self,Us)),(Je=c.e2ee)!=null&&Je.enabled&&c.e2ee.manager.init(u,t.getValue("peerSessionStore")),c.chat&&(y=await as.init(t,xs,P.self,N.participants)),c.internals&&(b=await kh.init(t)),c.livestream&&n.viewType===sr.Livestream&&t.getValue("flagsmith").hasFeature(X.LIVESTREAM)&&($=new sS(t,P.self,T)),c.poll&&(S=await Mf.init(t,P.self,Tt)),c.recording&&(L=new $f(t,P.self,Us)),c.stage&&(_=new Lf(t,_n,Us,P.self,N.participants)),c.plugin){if(!N)throw new k("The plugin module cannot be initialized without the `participant` module","0102");const Nr=await r;w=await So.init(t,Nr,I,xs,y==null?void 0:y.chat,P.self,N.participants,i)}if(c.connectedMeetings&&(B=await yl.init(t)),c.pip){const Nr=await Qu._init(t,P.self);t.setValue("pip",Nr)}const qe={storesManager:new xD(t,I),pollController:S,selfController:P,metaController:F,chatController:y,stageController:_,pluginController:w,recordingController:L,internalsController:b,livestreamController:$,participantController:N,connectedMeetingsController:B};return{theme:n,permissions:o,controllers:qe}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return mS(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=["PING"];return new Mo(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Oo=Wn;El([E.trace("Controller.init")],Oo,"init",1),El([E.trace("setupFlagsmith")],Oo,"setupFlagsmith",1),El([E.trace("Controller.createRoomNodeClient")],Oo,"createRoomNodeClient",1),El([E.trace("Controller.createSocketService")],Oo,"createSocketService",1);class pN{constructor(){p(this,"battery");p(this,"logger");p(this,"init",async t=>{this.logger=t;try{"getBattery"in navigator&&(this.battery=await navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){t.error("Error getting battery",e)}});p(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});p(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});p(this,"cleanup",()=>{var t,e;"getBattery"in navigator&&((t=this.battery)==null||t.removeEventListener("chargingchange",this.updateChargeInfo),(e=this.battery)==null||e.removeEventListener("levelchange",this.updateLevelInfo))})}}const $S=new pN;function gN(s,t){s.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c — not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.realtime.cloudflare.com/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:e,orgId:r,participantId:i}=JSON.parse(atob(s.split(".")[1]));if(!e)throw Error(`Received V1 auth token ${s}`);let n=wi.baseURI.prod;t&&(n=t);const o=`https://${bi({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new k("Invalid auth token","0004")}}class mN{constructor(){m(this,gu);m(this,gi,new Audio);m(this,En,new MediaStream);m(this,bn,new Map);m(this,xc,void 0);a(this,gi).srcObject=a(this,En),a(this,gi).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,bn).has(e.id)||(a(this,En).addTrack(e),a(this,bn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,gi).setSinkId(t)}removeTrack(t){const e=a(this,bn).get(t);e&&(a(this,En).removeTrack(e),a(this,bn).delete(t))}async play(){return a(this,gi).srcObject=a(this,En),a(this,gi).play().catch(t=>{x(this,gu,Gv).call(this,t)})}onError(t){f(this,xc,t)}}gi=new WeakMap,En=new WeakMap,bn=new WeakMap,xc=new WeakMap,gu=new WeakSet,Gv=function(t){var e;(e=a(this,xc))==null||e.call(this,t)};class fN extends mN{constructor(){super();m(this,wn,void 0);f(this,wn,new Map)}addParticipantTrack(e,r){a(this,wn).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,wn).get(e);r&&this.removeTrack(r),a(this,wn).delete(e)}}wn=new WeakMap;var SN=Object.defineProperty,vN=Object.getOwnPropertyDescriptor,bl=(s,t,e,r)=>{for(var i=r>1?void 0:r?vN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&SN(t,e,i),i};let Yr=(ov=class{constructor(t,e){m(this,Qe,void 0);m(this,Pn,void 0);f(this,Pn,t),f(this,Qe,e)}get peerId(){return a(this,Pn).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:fi(),n=rr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new nS(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var S,y,_,w,b,L,$;ve.init();const{mediaHandler:e}=(S=t.defaults)!=null?S:{},r=(e==null?void 0:e.peerId)||((_=(y=t==null?void 0:t.cachedUserDetails)==null?void 0:y.peerId)!=null?_:fi()),{authToken:i,baseURI:n}=t,{meetingId:o,...c}=gN(i,n);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const d=Yr.setupContext(r,t,o,c),l=d.getValue("telemetry"),u=d.getValue("logger");zv(u),$S.init(u),l.init(d,{roomName:o,userId:c.participantId,organizationId:c.orgId,peerId:r},(b=(w=t.modules)==null?void 0:w.tracing)!=null?b:!0),u.init(d),u.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(L=t.authToken)==null?void 0:L.slice(0,10)}...
21
- ${($=t.authToken)==null?void 0:$.slice(-10)}`}});const h=await Oo.init(d),g=new Yr(d,h);return d.setValue("meeting",g),g}static setupContext(t,e,r,i){var d,l;const n=rr.createContext(t,e),o={...Z_,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return n.setValue("options",e),n.setValue("peerId",t),n.setValue("modules",o),n.setValue("sdkName","web-core"),n.setValue("meetingId",r),n.setValue("apiBase",i.apiBase),n.setValue("baseURI",i.baseURI),n.setValue("userId",i.participantId),n.setValue("organizationId",i.orgId),n.setValue("authToken",e.authToken),n.setValue("overrides",(d=e.overrides)!=null?d:{}),n.setValue("env",eC({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",ws(e.cachedUserDetails)),n.setValue("sdkVersion","1.2.4"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new fN),n}async join(){const{selfController:t}=a(this,Qe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){$S.cleanup(),a(this,Pn).getValue("peerSessionStore").reset();const{selfController:e}=a(this,Qe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,Qe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Qe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Qe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Qe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Qe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Qe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Qe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Qe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Qe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Qe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Qe).stageController)==null?void 0:t.stage}get stores(){return a(this,Qe).storesManager}get audio(){return a(this,Pn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Qe).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Qe=new WeakMap,Pn=new WeakMap,ov);bl([lt("0002"),dr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Yr.prototype,"join",1),bl([lt("0003")],Yr.prototype,"leave",1),bl([lt("0001"),dr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Yr,"init",1),Yr=bl([lt("0000")],Yr);const BS=Yr;return BS}();
21
+ ${($=t.authToken)==null?void 0:$.slice(-10)}`}});const h=await Oo.init(d),g=new Yr(d,h);return d.setValue("meeting",g),g}static setupContext(t,e,r,i){var d,l;const n=rr.createContext(t,e),o={...Z_,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return n.setValue("options",e),n.setValue("peerId",t),n.setValue("modules",o),n.setValue("sdkName","web-core"),n.setValue("meetingId",r),n.setValue("apiBase",i.apiBase),n.setValue("baseURI",i.baseURI),n.setValue("userId",i.participantId),n.setValue("organizationId",i.orgId),n.setValue("authToken",e.authToken),n.setValue("overrides",(d=e.overrides)!=null?d:{}),n.setValue("env",eC({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",ws(e.cachedUserDetails)),n.setValue("sdkVersion","1.2.5-staging.1"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new fN),n}async join(){const{selfController:t}=a(this,Qe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){$S.cleanup(),a(this,Pn).getValue("peerSessionStore").reset();const{selfController:e}=a(this,Qe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,Qe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Qe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Qe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Qe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Qe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Qe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Qe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Qe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Qe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Qe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Qe).stageController)==null?void 0:t.stage}get stores(){return a(this,Qe).storesManager}get audio(){return a(this,Pn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Qe).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Qe=new WeakMap,Pn=new WeakMap,ov);bl([lt("0002"),dr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Yr.prototype,"join",1),bl([lt("0003")],Yr.prototype,"leave",1),bl([lt("0001"),dr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Yr,"init",1),Yr=bl([lt("0000")],Yr);const BS=Yr;return BS}();
@@ -1,5 +1,5 @@
1
1
  Name: @cloudflare/realtimekit
2
- Version: 1.2.4-staging.10
2
+ Version: 1.2.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,4 +10,4 @@ ${this.message}`;try{let o=a&&!!i;r&&r.endsWith("00")&&i&&(o=!0),o&&i.error("Cli
10
10
  maxEnergy: ${n(this,jr)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!n(this,ir)||i<n(this,ir))&&f(this,ir,i),(!n(this,jr)||i>n(this,jr))&&f(this,jr,i),{energy:(i-n(this,ir))/(n(this,jr)-n(this,ir))*10||0,isVoice:r})},mc=new WeakSet,Ku=function(t){return t<5},dl=new WeakSet,uT=function(t=n(this,Bi)){var r;if(!n(this,vs)||!t){n(this,nr).getValue("flagsmith").hasFeature(Z.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${n(this,vs)}`);return}const e={producerId:n(this,vs),energy:Math.round(t),silent:x(r=To,mc,Ku).call(r,t)};f(this,Ca,e.silent),this.reportRequest(e)},ll=new WeakSet,hT=function(t){const e=Math.log10(t);return Math.round(e)},m(oo,mc),m(oo,ll);const FD=(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}},BD=(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 HD=Object.defineProperty,qD=Object.getOwnPropertyDescriptor,de=(s,t,e,r)=>{for(var i=r>1?void 0:r?qD(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&&HD(t,e,i),i};const kt=["video/VP9","video/VP8"];var fc,Tc,at,W,wa,mt,Hi,qi,ji,vc,ts,or,Sc,Gi,Wi,ft,_t,Gr,mn,ul,gT,hl,mT,pl,fT,yc,zu,gl,du,TT,ml,vT,fl,ST,Tl,yT,Xe,lt,Ji,co,vl,ET,Sl,PT,yl,_T;const pT=(du=class{constructor(s,t){m(this,Gr);m(this,ul);m(this,hl);m(this,pl);m(this,yc);m(this,ml);m(this,fl);m(this,Tl);m(this,Xe);m(this,Ji);m(this,vl);m(this,Sl);m(this,yl);h(this,"context");h(this,"authToken");h(this,"e2ee");m(this,fc,void 0);m(this,Tc,void 0);m(this,at,void 0);m(this,W,void 0);m(this,wa,void 0);m(this,mt,void 0);m(this,Hi,void 0);m(this,qi,void 0);m(this,ji,void 0);m(this,vc,void 0);m(this,ts,null);m(this,or,void 0);m(this,Sc,void 0);m(this,Gi,void 0);m(this,Wi,void 0);m(this,ft,void 0);m(this,_t,void 0);var r,i;this.context=s;const{socket:e}=t;this.mediaJoined=!1,f(this,Gi,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,Wi,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,at,e),f(this,Hi,!1),f(this,W,new LD(s,e)),f(this,mt,n(this,W).events),f(this,or,new Set),f(this,ft,new Map),f(this,qi,!1),f(this,ji,new Fu(s.getValue("logger"))),f(this,_t,new oo(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,vc,Eh(()=>u(this,null,function*(){if(!n(this,Gr,mn).mediaJoinAttempted)return;const{roomJoined:a}=yield this.joinRoom(n(this,Tc),n(this,fc),!0,!0);a&&(this.context.getValue("peerSessionStore").emit(b.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(b.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,Gr,mn).mediaJoined}set mediaJoined(s){n(this,Gr,mn).mediaJoined=s}reset(){n(this,W).closeAllProducers(),n(this,W).closeAllConsumers(),n(this,ft).clear(),n(this,or).clear(),f(this,ts,null),n(this,ji).stop(),n(this,W).stopAllTransports(),n(this,W).reset(),f(this,ji,new Fu)}joinRoom(a,o){return u(this,arguments,function*(s,t,e=!1,r=!1,i={}){n(this,Gr,mn).mediaJoinAttempted=!0,f(this,Hi,!0),e&&this.reset();try{return yield n(this,ji).push(()=>x(this,ul,gT).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(b.ROOM_NODE_FAILED),{roomJoined:!1}}})}initializeConnection(i,a){return u(this,arguments,function*(s,t,e=!1,r={}){return n(this,ts)?n(this,ts):(f(this,ts,(()=>u(this,null,function*(){try{yield x(this,yc,zu).call(this,s,t,e,r)}catch(o){throw f(this,ts,null),o}}))()),n(this,ts))})}getConsumers(){return n(this,W).consumers}getProducers(){return n(this,W).producers}leaveRoom(){return u(this,null,function*(){n(this,W).stopAllTransports(),f(this,qi,!1),n(this,Gr,mn).mediaJoinAttempted=!1;const s={closeRoom:!1};n(this,at).sendMessagePromise(n(this,mt).leaveRoom,Zw.toBinary(s)).then(e=>{var r;(r=BR.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"?ue.WEBCAM:ue.WEBCAM_BACKUP,r=x(this,Xe,lt).call(this,e);if(r){const v=yield r;if(n(this,W).producers.has(v)){const E=n(this,W).producers.get(v);if(!E.closed)return yield E.replaceTrack({track:s}),yield this.resumeWebcam(e),s;yield this.disableWebcam(t)}return this._shareWebcam(s,t)}const i=[t].concat(kt.filter(v=>v!==t)),a=x(this,yl,_T).call(this,s,i),o=Ia(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(Z.ENABLE_CF_SIMULCAST)?(this.logger.info("Simulcast enabled for SFU: CF"),a.encodings=k0(this.context,s)):this.logger.info("Simulcast disabled for webcam producer, SFU: CF"),this.context.getValue("flagsmith").hasFeature(Z.TRACK_HINT)&&(a.track.contentHint=this.context.getValue("flagsmith").getValue(Z.TRACK_HINT));const l=()=>{this.logger.info("Disabling video due to the producer closure"),n(this,ft).delete(e)},p=n(this,W).createProducer(a,l);return x(this,Ji,co).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(Z.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=kt.filter(i=>{var a,o;return((o=(a=n(this,wa).sender)==null?void 0:a.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===i))>=0&&n(this,Wi).get(i).size>0});return e.length===0&&e.push(kt[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,ft).delete(ue.SCREENSHARE_VIDEO),n(this,ft).delete(ue.SCREENSHARE_AUDIO)},a=n(this,W).createProducer(r,i);x(this,Ji,co).call(this,ue.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),x(this,Ji,co).call(this,ue.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 wt("track undefined");const t=x(this,Xe,lt).call(this,ue.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,_t)&&(n(this,_t).audioTrack=s,n(this,_t).producerId=a,n(this,_t).start());return}yield n(this,W).closeProducer(a,{stopTrack:!1})}yield this.shareMic(s);return}const e=x(this,Sl,PT).call(this,s),r=()=>{n(this,ft).delete(ue.MIC)},i=n(this,W).createProducer(e,r);x(this,Ji,co).call(this,ue.MIC,i.then(a=>a.id)),yield i.then(a=>{n(this,_t)&&(n(this,_t).audioTrack=a.track,n(this,_t).producerId=a.id,n(this,_t).start())})}catch(t){throw new A(t)}})}pauseMic(){return u(this,null,function*(){var r;const s=yield x(this,Xe,lt).call(this,ue.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,_t))==null||r.stop();const e={producerId:t.id,pause:!0};n(this,at).sendMessage(n(this,mt).toggleProducer,Gc.toBinary(e))})}pauseWebcam(){return u(this,null,function*(){const s=yield x(this,Xe,lt).call(this,ue.WEBCAM),t=yield x(this,Xe,lt).call(this,ue.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,at).sendMessage(n(this,mt).toggleProducer,Gc.toBinary(o))};e&&(e.pause(),i(e)),r&&(r.pause(),i(r))})}resumeMic(){return u(this,null,function*(){const s=yield x(this,Xe,lt).call(this,ue.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(b.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};n(this,at).sendMessage(n(this,mt).toggleProducer,Gc.toBinary(e))})}resumeWebcam(){return u(this,arguments,function*(s=ue.WEBCAM){const t=yield x(this,Xe,lt).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(b.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};n(this,at).sendMessage(n(this,mt).toggleProducer,Gc.toBinary(r))})}disableWebcam(s){return u(this,null,function*(){const t=s==="video/VP9"?ue.WEBCAM:ue.WEBCAM_BACKUP,e=yield x(this,Xe,lt).call(this,t);x(this,vl,ET).call(this,t),e&&(yield n(this,W).closeProducer(e))})}disableMic(){return u(this,null,function*(){var t;const s=yield x(this,Xe,lt).call(this,ue.MIC);s&&(yield n(this,W).closeProducer(s)),(t=n(this,_t))==null||t.stop(),n(this,ft).delete(ue.MIC)})}disableScreenShare(){return u(this,null,function*(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=yield x(this,Xe,lt).call(this,ue.SCREENSHARE_VIDEO),t=yield x(this,Xe,lt).call(this,ue.SCREENSHARE_AUDIO);s&&(yield n(this,W).closeProducer(s)),t&&(yield n(this,W).closeProducer(t)),n(this,or).clear(),n(this,ft).delete(ue.SCREENSHARE_VIDEO),n(this,ft).delete(ue.SCREENSHARE_AUDIO)})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}resetVideoProducers(s,t){return u(this,null,function*(){if(s){const e=yield x(this,Xe,lt).call(this,ue.WEBCAM),r=yield x(this,Xe,lt).call(this,ue.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 x(this,Xe,lt).call(this,ue.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,at).sendMessagePromise(n(this,mt).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,or).add(s.consumerPeerId),n(this,or).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,at).on(n(this,mt).peerProducerCreateBroadcast,({payload:s})=>{var t,e;if(this.mediaJoined)try{const{participantId:r,producerState:i}=Tb.fromBinary(s);if(r===this.peerId)return;if(i!=null&&i.mimeType||(i.mimeType=i.kind===xs.AUDIO?"audio/opus":"video/VP8"),i.kind===xs.VIDEO&&!i.screenShare&&((e=(t=n(this,wa).receiver)==null?void 0:t.video)==null?void 0:e.codecs.findIndex(a=>a.mimeType===kt[0]))>=0&&n(this,Gi).get(kt[0]).has(r)&&i.mimeType!==kt[0]){this.logger.warn(`Ignoring producer: ${i.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${i}`),this.context.getValue("peerSessionStore").emit(b.NEW_PRODUCER,{peerId:r,producer:G(D({},i),{kind:i.kind===xs.AUDIO?"audio":"video",producingPeerId:r})})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),n(this,at).on(n(this,mt).peerProducerToggleBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,initiatorParticipantId:e,producerState:{kind:r,pause:i,producerId:a,screenShare:o}}=$p.fromBinary(s);if(o)return;const c=r===xs.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${t}, producerId: ${a}, kind:${c}, paused:${i} payload: ${JSON.stringify($p.fromBinary(s))}`),t===this.peerId&&e!==this.peerId&&i&&this.context.getValue("peerSessionStore").emit(c==="audio"?b.MUTE_SELF:b.MUTE_SELF_VIDEO),t===this.peerId)return;this.context.getValue("peerSessionStore").emit(b.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(b.CONSUMER_PAUSED,{id:l.id})):(l.resume(),this.context.getValue("peerSessionStore").emit(b.CONSUMER_RESUMED,{id:l.id})))})}catch(t){this.logger.error("error in producer toggle broadcast handler",{error:t})}}),n(this,at).on(n(this,mt).peerLeaveBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t}=Eu.fromBinary(s);if(t===this.peerId)return;this.logger.info(`peer left broadcast:${t}`),n(this,or).delete(t),n(this,W).consumers.forEach(e=>{e.peerId===t&&e.close()}),this.context.getValue("peerSessionStore").emit(b.PEER_CLOSED,{id:t})}catch(t){this.logger.error("error in peer left broadcast",{error:t})}}),n(this,at).on(n(this,mt).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=yb.fromBinary(s);if(t===this.peerId)return;this.logger.info(`producer closed broadcast:${t}`),this.context.getValue("peerSessionStore").emit(b.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(b.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,at).on(n(this,mt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!n(this,Hi)&&!n(this,qi)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(b.ROOM_NODE_DISCONNECTED),n(this,vc).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(b.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(b.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<=kt.length;o+=1){const c=kt[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===kt.length-1){n(this,Wi).get(c).add(s);break}}for(let o=0;o<=kt.length;o+=1){const c=kt[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===kt.length-1){n(this,Gi).get(c).add(s);break}}}handlePeerLeaving(s){this.context.getValue("flagsmith").hasFeature(Z.FORCE_VIDEO_CODEC)||(n(this,Gi).forEach(t=>t.delete(s)),n(this,Wi).forEach((t,e)=>{t.delete(s),!(t.size!==0||e===kt[0])&&this.disableWebcam(e)}))}},fc=new WeakMap,Tc=new WeakMap,at=new WeakMap,W=new WeakMap,wa=new WeakMap,mt=new WeakMap,Hi=new WeakMap,qi=new WeakMap,ji=new WeakMap,vc=new WeakMap,ts=new WeakMap,or=new WeakMap,Sc=new WeakMap,Gi=new WeakMap,Wi=new WeakMap,ft=new WeakMap,_t=new WeakMap,Gr=new WeakSet,mn=function(){return this.context.getValue("connectionHandler")},ul=new WeakSet,gT=function(s,t,e,r){return u(this,null,function*(){f(this,Tc,s);try{return n(this,ts)?yield n(this,ts):yield x(this,yc,zu).call(this,s,t,e,r),x(this,pl,fT).call(this,t),{roomJoined:yield x(this,hl,mT).call(this)}}catch(i){return this.logger.error("Failed to complete room join",{error:i}),{roomJoined:!1}}finally{f(this,ts,null)}})},hl=new WeakSet,mT=function(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:s}=yield n(this,W).socketHandler.notifySelfJoinComplete();return f(this,fc,s.roomUuid),f(this,qi,!0),f(this,Hi,!1),!0}catch(s){return this.logger.error("Error completing room join",{error:s}),this.mediaJoined=!1,!1}})},pl=new WeakSet,fT=function(s){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:G(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)},yc=new WeakSet,zu=function(s,t,e,r){return u(this,null,function*(){var i,a;try{(a=n(this,Sc))!=null||f(this,Sc,x(i=pT,gl,TT).call(i));const o=x(this,ml,vT).call(this);yield x(this,fl,ST).call(this,s,t,e,o),yield n(this,W).setupTransports({send:!0,recv:!0}),yield x(this,Tl,yT).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}})},gl=new WeakSet,TT=function(){const{ipInfo:s}=ot();if(!(s!=null&&s.loc))return;const[t,e]=s.loc.split(",").map(parseFloat);return{latitude:t,longitude:e}},ml=new WeakSet,vT=function(){var e;const s=(e=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:e.toString(),t=CD(s);return f(this,wa,t),t},fl=new WeakSet,ST=function(s,t,e,r){return u(this,null,function*(){yield Wf((i,a)=>u(this,null,function*(){if(!n(this,at).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,Sc))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:1/0})})},Tl=new WeakSet,yT=function(s){return u(this,null,function*(){if(!(!this.context.getValue("flagsmith").hasFeature(Z.PRECREATE_PRODUCERS)||!s))try{const e=[];if(s.canProduceVideo===H.Allowed&&e.push(this.shareWebcam(BD(!1))),s.canProduceAudio===H.Allowed){const r=FD(!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})}})},Xe=new WeakSet,lt=function(s){return n(this,ft).get(s)},Ji=new WeakSet,co=function(s,t){return n(this,ft).set(s,t)},vl=new WeakSet,ET=function(s){return n(this,ft).delete(s)},Sl=new WeakSet,PT=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},yl=new WeakSet,_T=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(du,gl),du);let ae=pT;de([P.trace("MediaNodeClient.reset",{country:P.location.country})],ae.prototype,"reset",1);de([P.trace("MediaNodeClient.joinRoom")],ae.prototype,"joinRoom",1);de([P.trace("MediaNodeClient.leaveRoom")],ae.prototype,"leaveRoom",1);de([P.trace("MediaNodeClient.activatePeers")],ae.prototype,"activatePeers",1);de([P.trace("MediaNodeClient.createConsumers")],ae.prototype,"createConsumers",1);de([P.trace("MediaNodeClient.closeConsumers")],ae.prototype,"closeConsumers",1);de([P.trace("MediaNodeClient._shareWebcam")],ae.prototype,"_shareWebcam",1);de([P.trace("MediaNodeClient.shareWebcam")],ae.prototype,"shareWebcam",1);de([P.trace("MediaNodeClient.shareScreen")],ae.prototype,"shareScreen",1);de([P.trace("MediaNodeClient.shareMic")],ae.prototype,"shareMic",1);de([P.trace("MediaNodeClient.pauseMic")],ae.prototype,"pauseMic",1);de([P.trace("MediaNodeClient.pauseWebcam")],ae.prototype,"pauseWebcam",1);de([P.trace("MediaNodeClient.resumeMic")],ae.prototype,"resumeMic",1);de([P.trace("MediaNodeClient.resumeWebcam")],ae.prototype,"resumeWebcam",1);de([P.trace("MediaNodeClient.disableWebcam")],ae.prototype,"disableWebcam",1);de([P.trace("MediaNodeClient.disableMic")],ae.prototype,"disableMic",1);de([P.trace("MediaNodeClient.disableScreenShare")],ae.prototype,"disableScreenShare",1);de([P.trace("MediaNodeClient.muteSelf")],ae.prototype,"muteSelf",1);de([P.trace("MediaNodeClient.resetVideoProducers")],ae.prototype,"resetVideoProducers",1);de([P.trace("MediaNodeClient.changeDisplayName")],ae.prototype,"changeDisplayName",1);de([P.trace("MediaNodeClient.kickPeer")],ae.prototype,"kick",1);de([P.trace("MediaNodeClient.kickAllPeers")],ae.prototype,"kickAll",1);de([P.trace("MediaNodeClient.muteAll")],ae.prototype,"muteAll",1);de([P.trace("MediaNodeClient.muteAllVideo")],ae.prototype,"muteAllVideo",1);de([P.trace("MediaNodeClient.disableAudio")],ae.prototype,"disableAudio",1);de([P.trace("MediaNodeClient.disableVideo")],ae.prototype,"disableVideo",1);de([P.trace("MediaNodeClient.pinPeer")],ae.prototype,"pinPeer",1);de([P.trace("MediaNodeClient.validateScreenShare")],ae.prototype,"validateScreenShare",1);function CT(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 wT(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 jD=Object.defineProperty,GD=Object.getOwnPropertyDescriptor,ln=(s,t,e,r)=>{for(var i=r>1?void 0:r?GD(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&&jD(t,e,i),i},Ki,Ss,ee,Tt,It,Vg;const RT=(Vg=class{constructor(s,t,e,r){m(this,Tt);h(this,"self");h(this,"authToken");m(this,Ki,void 0);h(this,"viewType");m(this,Ss,void 0);m(this,ee,void 0);const{socket:i}=e,a=s.getValue("authToken");this.self=t,f(this,ee,s),this.viewType=r,this.authToken=a,f(this,Ki,i),f(this,Ss,e),this.setupEvents()}get peerId(){return n(this,ee).getValue("peerId")}get telemetry(){return n(this,ee).getValue("telemetry")}get logger(){return n(this,ee).getValue("logger")}get mediaJoined(){return n(this,ee).getValue("connectionHandler").mediaJoined}static init(s,t,e,r,i){return u(this,null,function*(){const a=ot(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=yield ze.__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(Z.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:tf(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 RT(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===H.Allowed&&r)try{yield n(this,Tt,It).shareMic(s),this.self.audioEnabled||n(this,Tt,It).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===H.Allowed&&i)try{const d=yield n(this,Tt,It).shareWebcam(t);d&&d.id!==t.id&&n(this,ee).getValue("flagsmith").hasFeature(Z.EXP_RESHARE)&&(yield n(this,Tt,It).shareWebcam(d)),this.self.videoEnabled||n(this,Tt,It).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===H.Allowed&&a)try{yield(c=n(this,Tt,It))==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,ee).getValue("callstats").callEnded(),n(this,Tt,It).reset(),s&&(yield this.joinRoom(s))})}setupEvents(){n(this,ee).getValue("peerSessionStore").on(b.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),n(this,ee).getValue("peerSessionStore").on(b.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),n(this,ee).getValue("peerSessionStore").on(b.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),n(this,ee).getValue("peerSessionStore").on(b.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,ee).getValue("peerSessionStore").on(b.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),n(this,ee).getValue("peerSessionStore").on(b.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&n(this,ee).getValue("flagsmith").hasFeature(Z.REFRESH_ID_ON_DISCONNECTION)&&(t=gr.v4()),n(this,Ki).updateURL(t),n(this,ee).getValue("telemetry").resetPeerId(t),ot().setHeader("tracing-id",t),ur.remapContext(t,n(this,ee)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),n(this,ee).getValue("peerSessionStore").on(b.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,Ss).on(U.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),n(this,Ss).on(rd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&n(this,ee).getValue("peerSessionStore").emit(b.UPDATE_PERMISSIONS,t.patch)})}),n(this,Ss).on(U.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),n(this,Ss).on(U.kick,()=>{this.kickHandler({kickType:"kick"})}),n(this,Ss).on(U.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),n(this,ee).getValue("peerSessionStore").onAsync(b.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),n(this,ee).getValue("peerSessionStore").on(b.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,ee).getValue("peerSessionStore").on(b.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),n(this,ee).getValue("callstats").audioOff())})),n(this,ee).getValue("peerSessionStore").on(b.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),n(this,ee).getValue("callstats").videoOff())})),n(this,ee).getValue("peerSessionStore").onAsync(b.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),n(this,ee).getValue("peerSessionStore").on(b.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(s=!1){return u(this,null,function*(){try{const{peer:t}=yield n(this,Ss).joinRoom(this.self);n(this,Ss).socket.flush();const e=wh(t.stageType);if(n(this,ee).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(s),n(this,ee).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,ee).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),n(this,ee).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(s),n(this,ee).notify("stageStatus");try{(e=n(this,Ki))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}wT(n(this,ee)),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,ee).getAllValues();try{if(e===pr.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}CT(n(this,ee),{socket:n(this,Ki),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:p}=(o=yield(a=n(this,Tt,It))==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 A("Error: could not join media room","0002")}})}leaveMediaRoom(s){return u(this,null,function*(){const t=n(this,ee).getValue("viewType");s!=="connected-meeting"&&(yield this.cleanupSelf()),!(s==="stageLeft"&&t===pr.Webinar)&&n(this,Tt,It)&&(n(this,Tt,It).mediaJoined&&s!=="disconnected"&&(yield n(this,Tt,It).leaveRoom()),!(s==="stageLeft"&&t===pr.Livestream)&&(n(this,Tt,It).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()})}},Ki=new WeakMap,Ss=new WeakMap,ee=new WeakMap,Tt=new WeakSet,It=function(){return n(this,ee).getValue("roomNodeClient")},Vg);let si=RT;ln([P.trace("SelfController.resetSelf")],si.prototype,"resetSelf",1);ln([P.trace("SelfController.setupEvents")],si.prototype,"setupEvents",1);ln([P.trace("SelfController.joinRoom")],si.prototype,"joinRoom",1);ln([P.trace("SelfController.leaveRoom")],si.prototype,"leaveRoom",1);ln([P.trace("SelfController.joinMediaRoom")],si.prototype,"joinMediaRoom",1);ln([P.trace("SelfController.leaveMediaRoom")],si.prototype,"leaveMediaRoom",1);ln([P.trace("SelfController.init")],si,"init",1);var Ec;class WD{constructor(t){m(this,Ec,void 0);f(this,Ec,t)}on(t,e){let r;t===U.roomPeerCount?r=Hp.fromBinary.bind(Hp):r=Zp.fromBinary.bind(Zp),n(this,Ec).on(t,({payload:i})=>{if(t===U.roomPeerCount&&!i)return;const a=r(i);e(a)})}}Ec=new WeakMap;var Pc,_c;class JD{constructor(t,e){m(this,Pc,void 0);m(this,_c,void 0);f(this,Pc,e),f(this,_c,t)}get logger(){return n(this,_c).getValue("logger")}on(t,e){let r,i;switch(t){case U.transcript:{r=Zl.fromBinary.bind(Zl),i=Zl.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}n(this,Pc).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)})}}Pc=new WeakMap,_c=new WeakMap;var KD=Object.defineProperty,zD=Object.getOwnPropertyDescriptor,xh=(s,t,e,r)=>{for(var i=r>1?void 0:r?zD(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&&KD(t,e,i),i},cr,Ra;class Fl{constructor(t,e){m(this,cr,void 0);m(this,Ra,void 0);f(this,cr,e),f(this,Ra,t)}get logger(){return n(this,Ra).getValue("logger")}get telemetry(){return n(this,Ra).getValue("telemetry")}getPolls(){return n(this,cr).sendMessagePromise(Hs.getPolls)}createPoll(t,e,r=!1,i=!1){const a={anonymous:r,hideVotes:i,question:t,options:e};return n(this,cr).sendMessage(Hs.createPoll,rM.toBinary(a))}votePoll(t,e){const r={index:e,pollId:t};return n(this,cr).sendMessage(Hs.votePoll,nM.toBinary(r))}on(t,e){let r,i;switch(t){case Hs.updatePoll:case Hs.createPoll:case Hs.votePoll:{r=nu.fromBinary.bind(nu),i=nu.create();break}}n(this,cr).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,cr).removeListeners(t)}}cr=new WeakMap,Ra=new WeakMap;xh([P.trace("PollSocketHandler.getPolls")],Fl.prototype,"getPolls",1);xh([P.trace("PollSocketHandler.createPoll")],Fl.prototype,"createPoll",1);xh([P.trace("PollSocketHandler.votePoll")],Fl.prototype,"votePoll",1);var YD=Object.defineProperty,QD=Object.getOwnPropertyDescriptor,XD=(s,t,e,r)=>{for(var i=r>1?void 0:r?QD(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&&YD(t,e,i),i},xt;class bT{constructor(t,e){h(this,"socket");m(this,xt,void 0);f(this,xt,t),this.socket=e,this.handleSocketEvents(),n(this,xt).setValue("roomSocketHandler",this)}get telemetry(){return n(this,xt).getValue("telemetry")}get logger(){return n(this,xt).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(U.joinRoom,zb.toBinary(e));try{const{peer:a}=hn.fromBinary((yield r).payload);n(this,xt).getValue("connectionHandler").socketJoined=!0,n(this,xt).getValue("peerSessionStore").emit(b.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,xt).getValue("peerSessionStore").emit(b.ROOM_STATE,d),n(this,xt).getValue("peerSessionStore").emit(b.SOCKET_PEERS,l),{peer:a}}catch(a){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:a}),new A("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,a)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return Ok.fromBinary((yield this.socket.sendMessagePromise(U.getAllAddedParticipants)).payload).participants.map(i=>{var a=i,{id:e}=a,r=Bc(a,["id"]);return G(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(U.getRoomPeersInfo,$b.toBinary(a));i=eu.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(U.getRoomPeersInfo);t=eu.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(U.getRoomPeersInfo);t=eu.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(U.getPeerInfo,hf.toBinary({peerId:t}));e=hn.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(U.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=Jp.create();try{const e=yield this.socket.sendMessagePromise(U.getRoomStageState);t=Jp.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(U.broadcastMessage,Za.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(U.broadcastToEntity,Za.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(U.broadcastToEntity,Za.toBinary(i))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(U.leaveRoom,Qb.toBinary({}))})}kick(t){return u(this,null,function*(){const e={peerIds:[t]};this.socket.sendMessage(U.kick,gf.toBinary(e))})}kickAll(t=!1){return u(this,null,function*(){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(U.kickAll,df.toBinary(e))})}getWaitingRoomRequests(){this.socket.sendMessage(U.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.acceptWaitingRoomRequests,$k.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.denyWaitingRoomRequests,Bk.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(rd.updateUserPreset,fA.toBinary(r))})}handleSocketEvents(){this.socket.on(U.broadcastMessage,({payload:t})=>{try{const e=Za.fromBinary(t);n(this,xt).getValue("peerSessionStore").emit(b.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on(U.broadcastToEntity,({payload:t})=>{try{const e=Za.fromBinary(t);n(this,xt).getValue("peerSessionStore").emit(b.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case U.joinRoom:case U.leaveRoom:case U.kick:case U.kickAll:{r=hn.fromBinary.bind(hn),i=hn.create();break}case U.getWaitingRoomRequests:{r=(a,o)=>a?Wp.fromBinary(a,o):{requests:[]},i=Wp.create();break}case U.recordingPaused:case U.recordingStarted:case U.recordingStopped:{r=sg.fromBinary.bind(sg);break}case rd.updateUserPreset:{r=Kp.fromBinary.bind(Kp);break}case Ps.peerJoinedBroadcast:case Ar.peerJoinedBroadcast:{r=xp.fromBinary.bind(xp);break}case Ps.selfJoinComplete:case Ar.selfJoinComplete:{r=yu.fromBinary.bind(yu);break}case Ps.globalPeerPinBroadcast:case Ar.globalPeerPinBroadcast:{r=Fp.fromBinary.bind(Fp);break}case Ps.selectedPeer:case Ar.selectedPeer:{r=Su.fromBinary.bind(Su);break}case Ps.selectedPeerDiff:case Ar.selectedPeerDiff:{r=Lp.fromBinary.bind(Lp);break}case Ps.leaveRoom:case Ar.leaveRoom:{r=Eu.fromBinary.bind(Eu);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(rd.getUserPresets,dA.toBinary(e)),i=pA.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}})}}xt=new WeakMap;XD([P.trace("RoomSocketHandler.joinRoom")],bT.prototype,"joinRoom",1);var Ct;class ZD{constructor(t){m(this,Ct,void 0);f(this,Ct,t)}getStageRequests(){return u(this,null,function*(){const{payload:t}=yield n(this,Ct).sendMessagePromise(U.getStageRequests);return t?iu.fromBinary(t):{stageRequests:[]}})}requestAccess(){n(this,Ct).sendMessage(U.requestStageAccess)}cancelRequestAccess(){n(this,Ct).sendMessage(U.cancelStageRequest)}grantAccess(t){return u(this,null,function*(){const e={userIds:t};n(this,Ct).sendMessage(U.grantStageAccess,JI.toBinary(e))})}denyAccess(t){return u(this,null,function*(){const e={userIds:t};n(this,Ct).sendMessage(U.denyStageAccess,zI.toBinary(e))})}joinStage(){return n(this,Ct).sendMessagePromise(U.joinStage,void 0,void 0,U.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return n(this,Ct).sendMessagePromise(U.leaveStage,tg.toBinary(e),void 0,U.peerStageStatusUpdate)}kick(t){const e={userIds:t};return n(this,Ct).sendMessagePromise(U.leaveStage,tg.toBinary(e))}on(t,e){let r;switch(t){case U.grantStageAccess:case U.denyStageAccess:{r=void 0;break}case U.getStagePeers:{r=eg.fromBinary.bind(eg);break}case U.getStageRequests:case U.requestStageAccess:case U.cancelStageRequest:{r=iu.fromBinary.bind(iu);break}case U.peerStageStatusUpdate:{r=Bp.fromBinary.bind(Bp);break}}n(this,Ct).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,Ct).sendMessagePromise(U.getPeerInfo,hf.toBinary({peerId:t}));return hn.fromBinary(e.payload)})}}Ct=new WeakMap;var qe,Cc;class eO{constructor(t,e){m(this,qe,void 0);m(this,Cc,void 0);f(this,qe,e),f(this,Cc,t)}get logger(){return n(this,Cc).getValue("logger")}addPlugin(t,e){n(this,qe).sendMessage(J.addPlugin,lI.toBinary({pluginId:t,staggered:e}))}removePlugin(t){n(this,qe).sendMessage(J.removePlugin,hI.toBinary({pluginId:t,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:t}=yield n(this,qe).sendMessagePromise(J.getPlugins);return t?VI.fromBinary(t):{plugins:[]}})}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};n(this,qe).sendMessage(J.customPluginEventToRoom,PI.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const a={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};n(this,qe).sendMessage(J.customPluginEventToPeers,CI.toBinary(a),i)}enablePluginForRoom(t,e){n(this,qe).sendMessage(J.enablePluginForRoom,gI.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){n(this,qe).sendMessage(J.enablePluginForPeers,vI.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){n(this,qe).sendMessage(J.disablePluginForRoom,fI.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){n(this,qe).sendMessage(J.disablePluginForPeers,yI.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,qe).sendMessage(J.storeInsertKeys,zp.toBinary(a),i)}storeGetKeys(t,e,r,i){const a={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};n(this,qe).sendMessage(J.storeGetKeys,kI.toBinary(a),i)}storeDeleteKeys(t,e,r,i){const a={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};n(this,qe).sendMessage(J.storeDeleteKeys,II.toBinary(a),i)}storeDelete(t,e,r){n(this,qe).sendMessage(J.storeDelete,DI.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,qe).sendMessage(J.storeInsertKeys,zp.toBinary(i))}on(t,e){let r;switch(t){case J.addPlugin:case J.enablePluginForPeers:case J.enablePluginForRoom:{r=wu.fromBinary.bind(wu);break}case J.removePlugin:case J.disablePluginForPeers:case J.disablePluginForRoom:{r=Yp.fromBinary.bind(Yp);break}case J.customPluginEventToPeers:case J.customPluginEventToRoom:{r=Xp.fromBinary.bind(Xp);break}case J.storeInsertKeys:case J.storeGetKeys:case J.storeDeleteKeys:case J.storeDelete:{r=Qp.fromBinary.bind(Qp);break}}n(this,qe).on(t,({payload:i,id:a})=>{const o=r(i);return e(o,a)})}}qe=new WeakMap,Cc=new WeakMap;var tO=Object.defineProperty,sO=(s,t,e)=>t in s?tO(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,rO=(s,t,e)=>(sO(s,typeof t!="symbol"?t+"":t,e),e),Uh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},M=(s,t,e)=>(Uh(s,t,"read from private field"),e?e.call(s):t.get(s)),fe=(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)=>(Uh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),_e=(s,t,e)=>(Uh(s,t,"access private method"),e),wd={},iO={get exports(){return wd},set exports(s){wd=s}},Rn=typeof Reflect=="object"?Reflect:null,pg=Rn&&typeof Rn.apply=="function"?Rn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},ld;Rn&&typeof Rn.ownKeys=="function"?ld=Rn.ownKeys:Object.getOwnPropertySymbols?ld=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:ld=function(s){return Object.getOwnPropertyNames(s)};function nO(s){console&&console.warn&&console.warn(s)}var kT=Number.isNaN||function(s){return s!==s};function ce(){ce.init.call(this)}iO.exports=ce;wd.once=dO;ce.EventEmitter=ce;ce.prototype._events=void 0;ce.prototype._eventsCount=0;ce.prototype._maxListeners=void 0;var gg=10;function Bl(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 gg},set:function(s){if(typeof s!="number"||s<0||kT(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");gg=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||kT(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 AT(s){return s._maxListeners===void 0?ce.defaultMaxListeners:s._maxListeners}ce.prototype.getMaxListeners=function(){return AT(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")pg(c,this,t);else for(var d=c.length,l=NT(c,d),e=0;e<d;++e)pg(l[e],this,t);return!0};function IT(s,t,e,r){var i,a,o;if(Bl(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=AT(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,nO(c)}return s}ce.prototype.addListener=function(s,t){return IT(this,s,t,!1)};ce.prototype.on=ce.prototype.addListener;ce.prototype.prependListener=function(s,t){return IT(this,s,t,!0)};function aO(){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 MT(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=aO.bind(r);return i.listener=e,r.wrapFn=i,i}ce.prototype.once=function(s,t){return Bl(t),this.on(s,MT(this,s,t)),this};ce.prototype.prependOnceListener=function(s,t){return Bl(t),this.prependListener(s,MT(this,s,t)),this};ce.prototype.removeListener=function(s,t){var e,r,i,a,o;if(Bl(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():oO(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 DT(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?cO(i):NT(i,i.length)}ce.prototype.listeners=function(s){return DT(this,s,!0)};ce.prototype.rawListeners=function(s){return DT(this,s,!1)};ce.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):OT.call(s,t)};ce.prototype.listenerCount=OT;function OT(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?ld(this._events):[]};function NT(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function oO(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function cO(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function dO(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))}VT(s,t,a,{once:!0}),t!=="error"&&lO(s,i,{once:!0})})}function lO(s,t,e){typeof s.on=="function"&&VT(s,"error",t,e)}function VT(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 uO extends S.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 mg=new uO;class LT{static encode(t){return mg.toBinary(t)}static decode(t){return mg.fromBinary(new Uint8Array(t))}}function hO(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var br;class pO{constructor(t={}){rO(this,"opts"),fe(this,br,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ne(this,br,0)}wait(){return u(this,null,function*(){ne(this,br,M(this,br)+1);const t=hO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*Gh(2,M(this,br))));yield new Promise(e=>{setTimeout(e,t)})})}getAttempts(){return M(this,br)}reset(){ne(this,br,0)}}br=new WeakMap;const _r={debug:0,info:1,warn:2,error:3};var oi,ci;class gO{constructor(t){fe(this,oi,void 0),fe(this,ci,void 0),ne(this,oi,console),ne(this,ci,t)}debug(...t){_r[M(this,ci)]>_r.debug||M(this,oi).debug("[Sockrates]:",...t)}info(...t){_r[M(this,ci)]>_r.info||M(this,oi).info("[Sockrates]:",...t)}warn(...t){_r[M(this,ci)]>_r.warn||M(this,oi).warn("[Sockrates]:",...t)}error(...t){_r[M(this,ci)]>_r.error||M(this,oi).error("[Sockrates]:",...t)}}oi=new WeakMap,ci=new WeakMap;var xT=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(xT||{});const mO="2",fO="3";var Ae,fn,Pe,Le,kr,Ke,lr,zr,Es,Tn,Bs,Yu,UT,lo,ud,Qu,$T,Xu,fg,Rd,Zu,eh,FT,po,hd,go,bd,kd,th,bn,mo,fo,Ad;class TO{constructor(t,e){var T,v,E,_,C,R,L,F,N,B;fe(this,Yu),fe(this,lo),fe(this,Qu),fe(this,Xu),fe(this,Rd),fe(this,eh),fe(this,po),fe(this,go),fe(this,kd),fe(this,bn),fe(this,fo),fe(this,Ae,void 0),fe(this,fn,void 0),fe(this,Pe,void 0),fe(this,Le,void 0),fe(this,kr,void 0),fe(this,Ke,void 0),fe(this,lr,void 0),fe(this,zr,void 0),fe(this,Es,void 0),fe(this,Tn,void 0),fe(this,Bs,void 0);var r,i,a,o,c,d,l,p,g;ne(this,fn,t),ne(this,kr,[]),ne(this,Ke,new wd),ne(this,lr,!0),ne(this,Es,!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),(E=(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),(R=(d=M(this,Pe)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(L=(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,Le,(B=M(this,Pe).logger)!=null?B:new gO(M(this,Pe).debug?"debug":"info")),ne(this,Bs,new pO)}get readyState(){var t;return(t=M(this,Ae))==null?void 0:t.readyState}get url(){return M(this,fn)}updateURL(t){ne(this,fn,t),_e(this,eh,FT).call(this)}get config(){return M(this,Pe)}get sendQueue(){return M(this,kr)}flush(){if(!M(this,Pe).queueOnDisconnect)return!1;const t=[];return M(this,kr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ne(this,kr,t),M(this,kr)}connect(t=!1){return u(this,null,function*(){if(!t&&[0,1].includes(this.readyState)){M(this,Le).debug("Websocket was already connecting or connected.");return}if(M(this,lr)!==!1)return new Promise((e,r)=>{_e(this,bn,mo).call(this),_e(this,fo,Ad).call(this);try{ne(this,Ae,new WebSocket(_e(this,Yu,UT).call(this,M(this,fn)))),M(this,Ae).binaryType="arraybuffer",M(this,Le).debug("Connecting");const i=setTimeout(()=>{M(this,Le).debug("Connection timeout. Closing socket"),ne(this,lr,!0),_e(this,fo,Ad).call(this),M(this,Ae).close(3001,"Connection Timeout"),M(this,Pe).autoReconnect&&!M(this,Es)&&(M(this,Ke).emit("reconnecting"),_e(this,po,hd).call(this)),r(new Error("Connection timed out!"))},M(this,Pe).connectionTimeout);M(this,Ae).onopen=()=>{M(this,Le).debug(`Ready State: ${xT[M(this,Ae).readyState]}`),i&&clearTimeout(i),_e(this,kd,th).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,Le).debug("Socket closed. Close event:",{event:a}),M(this,Le).debug(`Connection closed code: ${o}`),M(this,Le).debug(`Connection closed reason: ${c}`),M(this,Es)||_e(this,Rd,Zu).call(this,o,c)}catch(o){_e(this,lo,ud).call(this,o)}},M(this,Ae).onerror=a=>{_e(this,lo,ud).call(this,a)},M(this,Ae).onmessage=a=>_e(this,Qu,$T).call(this,a)}catch(i){_e(this,lo,ud).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,Le).debug("Queuing message since socket is not connected!",a),M(this,kr).push(a),!1;const o=LT.encode(a);return _e(this,go,bd).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return _e(this,go,bd).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,lr,!1),_e(this,bn,mo).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,fn=new WeakMap,Pe=new WeakMap,Le=new WeakMap,kr=new WeakMap,Ke=new WeakMap,lr=new WeakMap,zr=new WeakMap,Es=new WeakMap,Tn=new WeakMap,Bs=new WeakMap,Yu=new WeakSet,UT=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)://.")},lo=new WeakSet,ud=function(s,t){M(this,Le).error("Error:",{error:s}),M(this,Ke).emit("errored",{error:s}),t==null||t(s)},Qu=new WeakSet,$T=function(s){if(_e(this,kd,th).call(this),s.data===mO){M(this,Le).debug("Received ping from server"),_e(this,go,bd).call(this,fO);return}const t=LT.decode(s.data),{id:e,payload:r}=t;M(this,Le).debug("Received message",{event:t.event,messageID:e}),M(this,Ke).emit(t.event.toString(),{id:e,payload:r})},Xu=new WeakSet,fg=function(){return M(this,Ae).readyState===1},Rd=new WeakSet,Zu=function(s,t){ne(this,zr,{reason:t,code:s}),M(this,Ke).emit("disconnected",{code:s,reason:t})},eh=new WeakSet,FT=function(){const{reason:s,code:t}=M(this,zr);t&&t!==1e3&&M(this,lr)&&M(this,Pe).autoReconnect&&!M(this,Es)&&(M(this,Le).debug(`Triggering reconnection due to ${s}.`),M(this,Ke).emit("reconnecting"),_e(this,po,hd).call(this))},po=new WeakSet,hd=function(s=!0){return u(this,null,function*(){if(s&&M(this,Es)){M(this,Le).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(M(this,Es)||M(this,Bs).reset(),M(this,Pe).maxReconnectionAttempts!==null&&M(this,Bs).getAttempts()>=M(this,Pe).maxReconnectionAttempts){M(this,Ke).emit("failed"),ne(this,Es,!1);return}ne(this,Es,!0),_e(this,fo,Ad).call(this),_e(this,bn,mo).call(this);try{if(yield M(this,Bs).wait(),M(this,lr)===!1)return;if(M(this,Le).debug(`Reconnection attempt ${M(this,Bs).getAttempts()}`),M(this,Ke).emit("reconnectAttempt",{attempt:M(this,Bs).getAttempts()}),yield this.connect(),!_e(this,Xu,fg).call(this))throw Error("Reconnect Failed");ne(this,Es,!1),ne(this,zr,{code:void 0,reason:void 0}),M(this,Ke).emit("reconnected")}catch(t){M(this,Le).debug("Failed to reconnect."),M(this,Ke).emit("reconnectFailure",{attempt:M(this,Bs).getAttempts()}),_e(this,po,hd).call(this,!1)}})},go=new WeakSet,bd=function(s){try{return M(this,Ae).send(s),!0}catch(t){return M(this,Le).error(t.message),!1}},kd=new WeakSet,th=function(){this.config.disconnectOnPingTimeout&&(M(this,Le).debug("Resetting ping timeout"),_e(this,bn,mo).call(this),ne(this,Tn,setTimeout(()=>{var s;M(this,Le).debug("Disconnecting the socket due to ping timeout"),ne(this,lr,!0);const t=3002,e="Ping timeout";(s=M(this,Ae))==null||s.close(t,e),_e(this,Rd,Zu).call(this,t,e)},M(this,Pe).pingTimeout)))},bn=new WeakSet,mo=function(){M(this,Tn)&&(clearTimeout(M(this,Tn)),ne(this,Tn,void 0))},fo=new WeakSet,Ad=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 vO=Object.defineProperty,SO=Object.getOwnPropertyDescriptor,Hl=(s,t,e,r)=>{for(var i=r>1?void 0:r?SO(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&&vO(t,e,i),i};const Tg=65535,yO=3e3;var Wr,Ce,we,Me,ss,Ze,wc,sh,Rc,rh,Lg;const BT=(Lg=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,we);m(this,wc);m(this,Rc);m(this,Wr,void 0);m(this,Ce,void 0);h(this,"roomName");h(this,"authToken");h(this,"capabilities");m(this,ss,void 0);m(this,Ze,void 0);var a;if(!t||!e||!r)throw new A("peerId, meetingId, or authToken can not be empty","0404");f(this,ss,void 0),f(this,Ze,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,Wr,x(this,wc,sh).call(this,t)),f(this,Ce,new TO(n(this,Wr),{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,Ze).getValue("telemetry")}get logger(){return n(this,Ze).getValue("logger")}get peerId(){return n(this,Ze).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,Wr,x(this,wc,sh).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),n(this,Ce).updateURL(n(this,Wr))}static getSocketEdgeDomain(s){return Zi({servicePrefix:"socket-edge",baseURI:s})}get url(){return n(this,Wr)}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,Ze).getValue("telemetry").injectContext(r),n(this,Ce).send(s,e!=null?e:x(this,Rc,rh).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=(E,_)=>{n(this,Ce).removeListener(a,E),n(this,Ce).removeListener(Tg,_),n(this,Ce).removeListener(Ar.errorResponse,_),n(this,Ce).removeListener(Ps.errorResponse,_)},l=r!=null?r:x(this,Rc,rh).call(this),p={};n(this,Ze).getValue("telemetry").injectContext(p);const T=({id:E,payload:_})=>{if(l===E){let C;try{const R=MR.fromBinary(_);C=new Error(R.errorMessage)}catch(R){C=new Error("failed to parse error message",{cause:R});try{const L=Db.fromBinary(_);C=new Error(L.message)}catch(L){C=new Error("failed to parse error message",{cause:L})}}c(C),d(v,T)}},v=({id:E,payload:_})=>{l===E&&(o({id:E,payload:_}),d(v,T))};n(this,Ce).on(a,v),n(this,Ce).on(Tg,T),n(this,Ce).on(Ar.errorResponse,T),n(this,Ce).on(Ps.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,ss)&&(clearTimeout(n(this,ss)),f(this,ss,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:P.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)!==wn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==wn.CONNECTED?n(this,Ze).getValue("peerSessionStore").emit(b.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,we,Me).joinAttempted}):f(this,ss,setTimeout(()=>{n(this,Ze).getValue("peerSessionStore").emit(b.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,we,Me).joinAttempted}),f(this,ss,void 0)},yO)),n(this,we,Me).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnecting to socket-edge",{country:P.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,ss)&&(clearTimeout(n(this,ss)),f(this,ss,void 0)),n(this,Ze).getValue("peerSessionStore").emit(b.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:P.location.country}),n(this,Ze).getValue("peerSessionStore").emit(b.SOCKET_SERVICE_FAILED),n(this,we,Me).updateSocketConnectionState("failed")}))}},Wr=new WeakMap,Ce=new WeakMap,we=new WeakSet,Me=function(){return n(this,Ze).getValue("connectionHandler")},ss=new WeakMap,Ze=new WeakMap,wc=new WeakSet,sh=function(s){let t=BT.getSocketEdgeDomain(n(this,Ze).getValue("baseURI"));typeof Ia(n(this,Ze),"socket_server_base")=="string"&&(t=Ia(n(this,Ze),"socket_server_base"));const e=`wss://${t}`,r=new URL(`${e}/ws`),i=this.peerId,a=G(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=>Sd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0});return Object.entries(a).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},Rc=new WeakSet,rh=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Lg);let Uc=BT;Hl([P.trace("SocketService.connect")],Uc.prototype,"connect",1);Hl([P.trace("SocketService.disconnect")],Uc.prototype,"disconnect",1);Hl([P.trace("SocketService.sendMessagePromise")],Uc.prototype,"sendMessagePromise",1);Hl([P.trace("SocketService.sendMessagePromiseWithTimeout")],Uc.prototype,"sendMessagePromiseWithTimeout",1);class EO{constructor(t){h(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var a;const e=nk.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=Mk.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 Gp.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return Ek.fromBinary(t).payloads}getConnectedRoomsDump(){return u(this,null,function*(){const t=yield this.socketService.sendMessagePromise(U.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)})}createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield this.socketService.sendMessagePromise(U.createConnectedRooms,dk.toBinary({payloads:t}));return Gp.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(U.deleteConnectedRooms,Sk.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)})}movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield this.socketService.sendMessagePromise(U.movePeers,bk.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 PO=Object.defineProperty,_O=Object.getOwnPropertyDescriptor,CO=(s,t,e,r)=>{for(var i=r>1?void 0:r?_O(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},ys;class HT extends Bt{constructor(e){const r=e.getValue("logger");super(r);h(this,"meetings",[]);h(this,"parentMeeting",null);m(this,ys,void 0);f(this,ys,e)}get supportsConnectedMeetings(){return n(this,ys).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.
11
11
  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,ys).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,ys).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,ys).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,ys).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,ys).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,ys).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 G(D({},o),{participants:c})}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return G(D({},o),{participants:c})}return o})}}ys=new WeakMap;CO([Rt({maxInvocations:60,period:60})],HT.prototype,"getConnectedMeetings",1);var wO=Object.defineProperty,RO=Object.getOwnPropertyDescriptor,$h=(s,t,e,r)=>{for(var i=r>1?void 0:r?RO(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},pe,xg;const qT=(xg=class{constructor(s){h(this,"connectedMeetings");m(this,pe,void 0);f(this,pe,s),this.connectedMeetings=new HT(s)}get telemetry(){return n(this,pe).getValue("telemetry")}get logger(){return n(this,pe).getValue("logger")}static init(s){const t=new qT(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){n(this,pe).getValue("connectedMeetingsSocketHandler").socketService.on(U.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),n(this,pe).getValue("connectedMeetingsSocketHandler").socketService.on(U.transferPeer,this.handleTransferPeer.bind(this)),n(this,pe).getValue("connectedMeetingsSocketHandler").socketService.on(U.movedPeer,this.handleMovedPeer.bind(this)),n(this,pe).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),n(this,pe).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=n(this,pe).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.
12
12
  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,pe).getValue("self").videoEnabled,audio:n(this,pe).getValue("self").audioEnabled};try{n(this,pe).getValue("self").cleanupEvents(),yield n(this,pe).getValue("meeting").leave("connected-meeting")}catch(l){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(o=(a=n(this,pe).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 GT.init(G(D({},n(this,pe).getValue("options")),{cachedUserDetails:null,defaults:G(D(D({},n(this,pe).getValue("options").defaults),r),{mediaHandler:n(this,pe).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,pe).getValue("self");i.self.setName(n(this,pe).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,pe).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,pe).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=n(this,pe).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,G(D({},r),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=n(this,pe).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})}},pe=new WeakMap,xg);let ql=qT;$h([P.trace("ConnectedMeetingsController.getConnectedMeetings")],ql.prototype,"getConnectedMeetings",1);$h([P.trace("ConnectedMeetingsController.setupEvents")],ql.prototype,"setupEvents",1);$h([P.trace("ConnectedMeetingsController.switchMeeting")],ql.prototype,"switchMeeting",1);var bO=Object.defineProperty,kO=Object.getOwnPropertyDescriptor,jl=(s,t,e,r)=>{for(var i=r>1?void 0:r?kO(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};const vn=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(wT(s),Se.isSupported()===!1)throw new A("Browser not supported","0010",c,!0);const d=NM(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 m0(s);s.setValue("connectionHandler",l);const p=vn.createSocketService(s),g=p.connect(),T=d.getUserDetails(),v=d.getPlugins();let E,_="";try{yield vn.setupFlagsmith(s)}catch(j){c.error("Failed to setup flagsmith",{error:j})}try{yield g}catch(j){c.error("[Controller]: Failed to connect to socket server:",{error:j})}try{({meetingTitle:_}=yield d.getRoomNodeData()),E=yield T,c.info("CF SFU is being used."),s.setValue("presetName",E.preset.name)}catch(j){c.error("Failed to get room metadata",{error:j})}const C=Nu.init(E.preset,!s.getValue("modules").theme),R=Uu.init(s,C.viewType,E.preset.permissions),L=vn.setupControllers(p,s,E,v,_,C,R);i0(C)&&((N=vn.createRoomNodeClient(s,p).initializeConnection(E.participant.name,i,!1,R))==null||N.catch(re=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:re})})),P.location.country=(B=d.ipInfo)==null?void 0:B.country;const{controllers:F}=yield L;return hw(),new vn(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=uw(i),d=G(D({entity:Tu.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?Zi({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";yield s.getValue("flagsmith").identify(`${Tu.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 V,k,xe;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:(V=T.enableHighBitrate)!=null?V:!1,enableStereo:(k=T.enableStereo)!=null?k:!1}}},l)),t.setValue("maxPreferredStreams",Se.isMobile()?a.maxVideoStreams.mobile:a.maxVideoStreams.desktop);let v,E,_,C,R,L,F,N,B;const j=new JD(t,s),re=new EO(s);t.setValue("connectedMeetingsSocketHandler",re);const et=new Fl(t,s),os=new yr(t,s),ri=new ZD(s),cs=new bT(t,s),I=new eO(t,s),y=new WD(s),w=yield si.init(t,cs,d,o,a);t.setValue("selfController",w);const $=yield kf.init(t,w.self,cs,j,i);if(c.participant&&(N=new Pr(t,w.self,cs)),(xe=c.e2ee)!=null&&xe.enabled&&c.e2ee.manager.init(p,t.getValue("peerSessionStore")),c.chat&&(E=yield is.init(t,os,w.self,N.participants)),c.internals&&(R=yield bh.init(t)),c.livestream&&a.viewType===pr.Livestream&&t.getValue("flagsmith").hasFeature(Z.LIVESTREAM)&&(F=new xf(t,w.self,y)),c.poll&&(v=yield Cf.init(t,w.self,et)),c.recording&&(L=new Df(t,w.self,cs)),c.stage&&(_=new Af(t,ri,cs,w.self,N.participants)),c.plugin){if(!N)throw new A("The plugin module cannot be initialized without the `participant` module","0102");const Fs=yield r;C=yield Nc.init(t,Fs,I,os,E==null?void 0:E.chat,w.self,N.participants,i)}if(c.connectedMeetings&&(B=yield ql.init(t)),c.pip){const Fs=yield vu._init(t,w.self);t.setValue("pip",Fs)}const Ie={storesManager:new aD(t,I),pollController:v,selfController:w,metaController:$,chatController:E,stageController:_,pluginController:C,recordingController:L,internalsController:R,livestreamController:F,participantController:N,connectedMeetingsController:B};return{theme:a,permissions:o,controllers:Ie}})}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return CT(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=["PING"];return new Uc(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let $c=vn;jl([P.trace("Controller.init")],$c,"init",1);jl([P.trace("setupFlagsmith")],$c,"setupFlagsmith",1);jl([P.trace("Controller.createRoomNodeClient")],$c,"createRoomNodeClient",1);jl([P.trace("Controller.createSocketService")],$c,"createSocketService",1);class AO{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 vg=new AO;function IO(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=ui.baseURI.prod;t&&(a=t);const o=`https://${Zi({servicePrefix:"api",baseURI:a})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:a,apiBase:o}}catch(e){throw new A("Invalid auth token","0004")}}var Jr,zi,Yi,bc,El,jT;class MO{constructor(){m(this,El);m(this,Jr,new Audio);m(this,zi,new MediaStream);m(this,Yi,new Map);m(this,bc,void 0);n(this,Jr).srcObject=n(this,zi),n(this,Jr).autoplay=!0}playTracks(t){return u(this,null,function*(){return t.forEach(e=>{n(this,Yi).has(e.id)||(n(this,zi).addTrack(e),n(this,Yi).set(e.id,e))}),this.play()})}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&n(this,Jr).setSinkId(t)}removeTrack(t){const e=n(this,Yi).get(t);e&&(n(this,zi).removeTrack(e),n(this,Yi).delete(t))}play(){return u(this,null,function*(){return n(this,Jr).srcObject=n(this,zi),n(this,Jr).play().catch(t=>{x(this,El,jT).call(this,t)})})}onError(t){f(this,bc,t)}}Jr=new WeakMap,zi=new WeakMap,Yi=new WeakMap,bc=new WeakMap,El=new WeakSet,jT=function(t){var e;(e=n(this,bc))==null||e.call(this,t)};var Qi;class DO extends MO{constructor(){super();m(this,Qi,void 0);f(this,Qi,new Map)}addParticipantTrack(e,r){n(this,Qi).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=n(this,Qi).get(e);r&&this.removeTrack(r),n(this,Qi).delete(e)}}Qi=new WeakMap;var OO=Object.defineProperty,NO=Object.getOwnPropertyDescriptor,Gl=(s,t,e,r)=>{for(var i=r>1?void 0:r?NO(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},je,Xi,Ug;let Xr=(Ug=class{constructor(t,e){m(this,je,void 0);m(this,Xi,void 0);f(this,Xi,t),f(this,je,e)}get peerId(){return n(this,Xi).getValue("peerId")}static initMedia(){return u(this,arguments,function*(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:gr.v4(),a=ur.createContext(i,{peerId:i}),o=a.getValue("logger");o.init(a);const c=new Gf(a,o);return yield c.init(t,e,a),a.setValue("defaults",{mediaHandler:c}),c})}static init(t){return u(this,null,function*(){var v,E,_,R,L,F,N;Se.init();const{mediaHandler:e}=(v=t.defaults)!=null?v:{},r=(e==null?void 0:e.peerId)||((_=(E=t==null?void 0:t.cachedUserDetails)==null?void 0:E.peerId)!=null?_:gr.v4()),{authToken:i,baseURI:a}=t,C=IO(i,a),{meetingId:o}=C,c=Bc(C,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const d=Xr.setupContext(r,t,o,c),l=d.getValue("telemetry"),p=d.getValue("logger");tv(p),vg.init(p),l.init(d,{roomName:o,userId:c.participantId,organizationId:c.orgId,peerId:r},(L=(R=t.modules)==null?void 0:R.tracing)!=null?L:!0),p.init(d),p.info("Client::init::options",{clientInitOptions:G(D({},t),{authToken:`${(F=t.authToken)==null?void 0:F.slice(0,10)}...
13
- ${(N=t.authToken)==null?void 0:N.slice(-10)}`})});const g=yield $c.init(d),T=new Xr(d,g);return d.setValue("meeting",T),T})}static setupContext(t,e,r,i){var d,l;const a=ur.createContext(t,e),o=D(D({},tw),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",sw({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",_s(e.cachedUserDetails)),a.setValue("sdkVersion","1.2.4"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new DO),a}join(){return u(this,null,function*(){const{selfController:t}=n(this,je);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){vg.cleanup(),n(this,Xi).getValue("peerSessionStore").reset();const{selfController:e}=n(this,je);return e.leaveRoom(t)})}get participants(){var t;return(t=n(this,je).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,je).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,je).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,je).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,je).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,je).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,je).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,je).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,je).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,je).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,je).stageController)==null?void 0:t.stage}get stores(){return n(this,je).storesManager}get audio(){return n(this,Xi).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,je).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)})}},je=new WeakMap,Xi=new WeakMap,Ug);Gl([dt("0002"),Er.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Xr.prototype,"join",1);Gl([dt("0003")],Xr.prototype,"leave",1);Gl([dt("0001"),Er.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Xr,"init",1);Xr=Gl([dt("0000")],Xr);const GT=Xr;module.exports=GT;
13
+ ${(N=t.authToken)==null?void 0:N.slice(-10)}`})});const g=yield $c.init(d),T=new Xr(d,g);return d.setValue("meeting",T),T})}static setupContext(t,e,r,i){var d,l;const a=ur.createContext(t,e),o=D(D({},tw),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",sw({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",_s(e.cachedUserDetails)),a.setValue("sdkVersion","1.2.5-staging.1"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new DO),a}join(){return u(this,null,function*(){const{selfController:t}=n(this,je);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){vg.cleanup(),n(this,Xi).getValue("peerSessionStore").reset();const{selfController:e}=n(this,je);return e.leaveRoom(t)})}get participants(){var t;return(t=n(this,je).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,je).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,je).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,je).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,je).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,je).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,je).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,je).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,je).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,je).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,je).stageController)==null?void 0:t.stage}get stores(){return n(this,je).storesManager}get audio(){return n(this,Xi).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,je).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)})}},je=new WeakMap,Xi=new WeakMap,Ug);Gl([dt("0002"),Er.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Xr.prototype,"join",1);Gl([dt("0003")],Xr.prototype,"leave",1);Gl([dt("0001"),Er.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Xr,"init",1);Xr=Gl([dt("0000")],Xr);const GT=Xr;module.exports=GT;
package/dist/index.es.js CHANGED
@@ -28378,7 +28378,7 @@ let Qr = ($g = class {
28378
28378
  video: !0
28379
28379
  };
28380
28380
  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", tw({ baseURI: i.baseURI })), a.setValue("defaults", c), a.setValue("onError", e.onError || (() => {
28381
- })), a.setValue("cachedUserDetails", _s(e.cachedUserDetails)), a.setValue("sdkVersion", "1.2.4"), (l = e.modules) != null && l.experimentalAudioPlayback && a.setValue("audioPlayback", new MO()), a;
28381
+ })), a.setValue("cachedUserDetails", _s(e.cachedUserDetails)), a.setValue("sdkVersion", "1.2.5-staging.1"), (l = e.modules) != null && l.experimentalAudioPlayback && a.setValue("audioPlayback", new MO()), a;
28382
28382
  }
28383
28383
  join() {
28384
28384
  return u(this, null, function* () {
package/dist/index.rn.js CHANGED
@@ -10,4 +10,4 @@ ${this.message}`;try{let o=a&&!!i;r&&r.endsWith("00")&&i&&(o=!0),o&&i.error("Cli
10
10
  maxEnergy: ${n(this,Br)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!n(this,tr)||i<n(this,tr))&&m(this,tr,i),(!n(this,Br)||i>n(this,Br))&&m(this,Br,i),{energy:(i-n(this,tr))/(n(this,Br)-n(this,tr))*10||0,isVoice:r})},hc=new WeakSet,Bu=function(t){return t<5},il=new WeakSet,Zf=function(t=n(this,Ui)){var r;if(!n(this,ms)||!t){n(this,sr).getValue("flagsmith").hasFeature(Y.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${n(this,ms)}`);return}const e={producerId:n(this,ms),energy:Math.round(t),silent:V(r=go,hc,Bu).call(r,t)};m(this,Ea,e.silent),this.reportRequest(e)},nl=new WeakSet,eT=function(t){const e=Math.log10(t);return Math.round(e)},g(io,hc),g(io,nl);const RD=(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=async()=>{try{const f=new Float32Array(a*o),T=new window.AudioData({format:"f32",sampleRate:i,numberOfFrames:a,numberOfChannels:o,timestamp:c,data:f});c+=a/i*1e6,await r.ready,await r.write(T)}catch(f){d&&clearInterval(d),r.releaseLock(),e.writable.abort()}};d=window.setInterval(l,100);const p=new MediaStream([e]).getAudioTracks()[0];return p.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),e.writable.abort()}),Object.assign(p,{fakeTracks:"fakeTracks:fakeAudioTrack"}),p.enabled=s,p}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}},bD=(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 kD=Object.defineProperty,AD=Object.getOwnPropertyDescriptor,ae=(s,t,e,r)=>{for(var i=r>1?void 0:r?AD(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&&kD(t,e,i),i};const wt=["video/VP9","video/VP8"];var pc,gc,rt,H,Pa,ht,$i,Fi,Bi,mc,Xt,ir,fc,Hi,qi,pt,yt,Hr,hn,al,sT,ol,rT,cl,iT,Tc,Hu,dl,ru,nT,ll,aT,ul,oT,hl,cT,ze,ot,ji,no,pl,dT,gl,lT,ml,uT;const tT=(ru=class{constructor(s,t){g(this,Hr);g(this,al);g(this,ol);g(this,cl);g(this,Tc);g(this,ll);g(this,ul);g(this,hl);g(this,ze);g(this,ji);g(this,pl);g(this,gl);g(this,ml);u(this,"context");u(this,"authToken");u(this,"e2ee");g(this,pc,void 0);g(this,gc,void 0);g(this,rt,void 0);g(this,H,void 0);g(this,Pa,void 0);g(this,ht,void 0);g(this,$i,void 0);g(this,Fi,void 0);g(this,Bi,void 0);g(this,mc,void 0);g(this,Xt,null);g(this,ir,void 0);g(this,fc,void 0);g(this,Hi,void 0);g(this,qi,void 0);g(this,pt,void 0);g(this,yt,void 0);var r,i;this.context=s;const{socket:e}=t;this.mediaJoined=!1,m(this,Hi,new Map([["video/VP9",new Set],["video/VP8",new Set]])),m(this,qi,new Map([["video/VP9",new Set],["video/VP8",new Set]])),m(this,rt,e),m(this,$i,!1),m(this,H,new PD(s,e)),m(this,ht,n(this,H).events),m(this,ir,new Set),m(this,pt,new Map),m(this,Fi,!1),m(this,Bi,new Ou(s.getValue("logger"))),m(this,yt,new io(this.context,n(this,H).socketHandler.audioActivity.bind(n(this,H).socketHandler))),this.e2ee=(i=(r=s.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?i:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),m(this,mc,gh(async()=>{if(!n(this,Hr,hn).mediaJoinAttempted)return;const{roomJoined:a}=await this.joinRoom(n(this,gc),n(this,pc),!0,!0);a&&(this.context.getValue("peerSessionStore").emit(R.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(R.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,Hr,hn).mediaJoined}set mediaJoined(s){n(this,Hr,hn).mediaJoined=s}reset(){n(this,H).closeAllProducers(),n(this,H).closeAllConsumers(),n(this,pt).clear(),n(this,ir).clear(),m(this,Xt,null),n(this,Bi).stop(),n(this,H).stopAllTransports(),n(this,H).reset(),m(this,Bi,new Ou)}async joinRoom(s,t,e=!1,r=!1,i={}){n(this,Hr,hn).mediaJoinAttempted=!0,m(this,$i,!0),e&&this.reset();try{return await n(this,Bi).push(()=>V(this,al,sT).call(this,s,t,r,i),"joinRoom")}catch(a){return this.logger.error("Error in room joining process",{error:a}),this.context.getValue("peerSessionStore").emit(R.ROOM_NODE_FAILED),{roomJoined:!1}}}async initializeConnection(s,t,e=!1,r={}){return n(this,Xt)?n(this,Xt):(m(this,Xt,(async()=>{try{await V(this,Tc,Hu).call(this,s,t,e,r)}catch(i){throw m(this,Xt,null),i}})()),n(this,Xt))}getConsumers(){return n(this,H).consumers}getProducers(){return n(this,H).producers}async leaveRoom(){n(this,H).stopAllTransports(),m(this,Fi,!1),n(this,Hr,hn).mediaJoinAttempted=!1;const s={closeRoom:!1};n(this,rt).sendMessagePromise(n(this,ht).leaveRoom,$w.toBinary(s)).then(e=>{var r;(r=bR.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()}async activatePeers(s){return this.createConsumers(s)}async createConsumers(s){return s.length===0?Promise.resolve():n(this,H).createConsumers(s)}async closeConsumers(s){if(!s.length)return;const t=s.reduce((e,r)=>{const i=n(this,H).producerIdToConsumerIdMap.get(r.producerId);return i?(e.push(i),e):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),e)},[]);await n(this,H).closeConsumers(t)}async _shareWebcam(s,t){var p,f;const e=t==="video/VP9"?ce.WEBCAM:ce.WEBCAM_BACKUP,r=V(this,ze,ot).call(this,e);if(r){const T=await r;if(n(this,H).producers.has(T)){const E=n(this,H).producers.get(T);if(!E.closed)return await E.replaceTrack({track:s}),await this.resumeWebcam(e),s;await this.disableWebcam(t)}return this._shareWebcam(s,t)}const i=[t].concat(wt.filter(T=>T!==t)),a=V(this,ml,uT).call(this,s,i),o=ba(this.context,"disableSimulcast"),c=(f=(p=this.context)==null?void 0:p.getValue("overrides"))==null?void 0:f.simulcastConfig;!(o||c&&c.disable)&&this.context.getValue("flagsmith").hasFeature(Y.ENABLE_CF_SIMULCAST)?(this.logger.info("Simulcast enabled for SFU: CF"),a.encodings=g0(this.context,s)):this.logger.info("Simulcast disabled for webcam producer, SFU: CF"),this.context.getValue("flagsmith").hasFeature(Y.TRACK_HINT)&&(a.track.contentHint=this.context.getValue("flagsmith").getValue(Y.TRACK_HINT));const l=()=>{this.logger.info("Disabling video due to the producer closure"),n(this,pt).delete(e)},h=n(this,H).createProducer(a,l);return V(this,ji,no).call(this,e,h.then(T=>T.id)),h.then(T=>T.track)}async shareWebcam(s){var r;if(s===void 0)return null;const t=(r=this.context.getValue("flagsmith").getValue(Y.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=wt.filter(i=>{var a,o;return((o=(a=n(this,Pa).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(wt[0]),await Promise.all(e.map(i=>(this.logger.debug(`Calling _shareWebcam with video codec: ${i}`),this._shareWebcam(s,i)))),s}async shareScreen(s){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:fe.isElectron()},stopTracks:!1},i=()=>{this.logger.info("Disabling screenShare due to the producer closure"),n(this,pt).delete(ce.SCREENSHARE_VIDEO),n(this,pt).delete(ce.SCREENSHARE_AUDIO)},a=n(this,H).createProducer(r,i);V(this,ji,no).call(this,ce.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:fe.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},d=()=>{};o=n(this,H).createProducer(c,d),V(this,ji,no).call(this,ce.SCREENSHARE_AUDIO,o.then(l=>l.id))}await Promise.all([a,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()}async shareMic(s){try{if(s===void 0)throw new Pt("track undefined");const t=V(this,ze,ot).call(this,ce.MIC);if(t){const a=await t;if(n(this,H).producers.has(a)){const o=n(this,H).producers.get(a);if(!o.closed){await o.replaceTrack({track:s}),await this.resumeMic(),n(this,yt)&&(n(this,yt).audioTrack=s,n(this,yt).producerId=a,n(this,yt).start());return}await n(this,H).closeProducer(a,{stopTrack:!1})}await this.shareMic(s);return}const e=V(this,gl,lT).call(this,s),r=()=>{n(this,pt).delete(ce.MIC)},i=n(this,H).createProducer(e,r);V(this,ji,no).call(this,ce.MIC,i.then(a=>a.id)),await i.then(a=>{n(this,yt)&&(n(this,yt).audioTrack=a.track,n(this,yt).producerId=a.id,n(this,yt).start())})}catch(t){throw new k(t)}}async pauseMic(){var r;const s=await V(this,ze,ot).call(this,ce.MIC),t=n(this,H).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,yt))==null||r.stop();const e={producerId:t.id,pause:!0};n(this,rt).sendMessage(n(this,ht).toggleProducer,Fc.toBinary(e))}async pauseWebcam(){const s=await V(this,ze,ot).call(this,ce.WEBCAM),t=await V(this,ze,ot).call(this,ce.WEBCAM_BACKUP),e=n(this,H).producers.get(s),r=n(this,H).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,rt).sendMessage(n(this,ht).toggleProducer,Fc.toBinary(o))};e&&(e.pause(),i(e)),r&&(r.pause(),i(r))}async resumeMic(){const s=await V(this,ze,ot).call(this,ce.MIC),t=n(this,H).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(R.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};n(this,rt).sendMessage(n(this,ht).toggleProducer,Fc.toBinary(e))}async resumeWebcam(s=ce.WEBCAM){const t=await V(this,ze,ot).call(this,s),e=n(this,H).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(R.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};n(this,rt).sendMessage(n(this,ht).toggleProducer,Fc.toBinary(r))}async disableWebcam(s){const t=s==="video/VP9"?ce.WEBCAM:ce.WEBCAM_BACKUP,e=await V(this,ze,ot).call(this,t);V(this,pl,dT).call(this,t),e&&await n(this,H).closeProducer(e)}async disableMic(){var t;const s=await V(this,ze,ot).call(this,ce.MIC);s&&await n(this,H).closeProducer(s),(t=n(this,yt))==null||t.stop(),n(this,pt).delete(ce.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=await V(this,ze,ot).call(this,ce.SCREENSHARE_VIDEO),t=await V(this,ze,ot).call(this,ce.SCREENSHARE_AUDIO);s&&await n(this,H).closeProducer(s),t&&await n(this,H).closeProducer(t),n(this,ir).clear(),n(this,pt).delete(ce.SCREENSHARE_VIDEO),n(this,pt).delete(ce.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(s,t){if(s){const e=await V(this,ze,ot).call(this,ce.WEBCAM),r=await V(this,ze,ot).call(this,ce.WEBCAM_BACKUP);await n(this,H).closeProducer(e,{stopTrack:!1}),await n(this,H).closeProducer(r,{stopTrack:!1}),this.shareWebcam(s)}if(t){const e=await V(this,ze,ot).call(this,ce.SCREENSHARE_VIDEO);await n(this,H).closeProducer(e,{stopTrack:!1}),this.shareScreen({video:t})}}async changeDisplayName(s,t){const e={displayName:s,participantId:t!=null?t:this.peerId};if(!await n(this,H).socketHandler.changeDisplayName(e))throw new Error("failed to change display name!")}kick(s){const t={peerIds:[s]};n(this,H).socketHandler.kickPeer(t)}kickAll(){n(this,H).socketHandler.kickAll()}async muteAll(s){if(!await n(this,H).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await n(this,H).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(s){if(!await n(this,H).socketHandler.hostControlForPeer(s,"audio"))throw new Error("failed to mute given participant")}async disableVideo(s){if(!await n(this,H).socketHandler.hostControlForPeer(s,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(s){const t={participantId:s!=null?s:""};try{await n(this,rt).sendMessagePromise(n(this,ht).globalPinPeer,Zw.toBinary(t))}catch(e){this.logger.error("Error in pinning peer:",{error:e})}}validateScreenShare(s){return this.peerId===s.peerId&&n(this,H).producers.get(s.producerId)&&n(this,ir).add(s.consumerPeerId),n(this,ir).size}async switchConsumersToLayer(s,t){const e=s.map(r=>this.getConsumers().get(r));n(this,H).switchConsumersToLayer(e,t)}async handleSocketEvents(){n(this,rt).on(n(this,ht).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===Ns.AUDIO?"audio/opus":"video/VP8"),i.kind===Ns.VIDEO&&!i.screenShare&&((e=(t=n(this,Pa).receiver)==null?void 0:t.video)==null?void 0:e.codecs.findIndex(a=>a.mimeType===wt[0]))>=0&&n(this,Hi).get(wt[0]).has(r)&&i.mimeType!==wt[0]){this.logger.warn(`Ignoring producer: ${i.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${i}`),this.context.getValue("peerSessionStore").emit(R.NEW_PRODUCER,{peerId:r,producer:{...i,kind:i.kind===Ns.AUDIO?"audio":"video",producingPeerId:r}})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),n(this,rt).on(n(this,ht).peerProducerToggleBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,initiatorParticipantId:e,producerState:{kind:r,pause:i,producerId:a,screenShare:o}}=bp.fromBinary(s);if(o)return;const c=r===Ns.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${t}, producerId: ${a}, kind:${c}, paused:${i} payload: ${JSON.stringify(bp.fromBinary(s))}`),t===this.peerId&&e!==this.peerId&&i&&this.context.getValue("peerSessionStore").emit(c==="audio"?R.MUTE_SELF:R.MUTE_SELF_VIDEO),t===this.peerId)return;this.context.getValue("peerSessionStore").emit(R.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(R.CONSUMER_PAUSED,{id:l.id})):(l.resume(),this.context.getValue("peerSessionStore").emit(R.CONSUMER_RESUMED,{id:l.id})))})}catch(t){this.logger.error("error in producer toggle broadcast handler",{error:t})}}),n(this,rt).on(n(this,ht).peerLeaveBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t}=gu.fromBinary(s);if(t===this.peerId)return;this.logger.info(`peer left broadcast:${t}`),n(this,ir).delete(t),n(this,H).consumers.forEach(e=>{e.peerId===t&&e.close()}),this.context.getValue("peerSessionStore").emit(R.PEER_CLOSED,{id:t})}catch(t){this.logger.error("error in peer left broadcast",{error:t})}}),n(this,rt).on(n(this,ht).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=ab.fromBinary(s);if(t===this.peerId)return;this.logger.info(`producer closed broadcast:${t}`),this.context.getValue("peerSessionStore").emit(R.PRODUCER_CLOSED,{peerId:t,producerId:e});const r=n(this,H).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,H).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),n(this,H).producerIdToConsumerIdMap.delete(e),this.context.getValue("peerSessionStore").emit(R.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,rt).on(n(this,ht).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!n(this,$i)&&!n(this,Fi)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(R.ROOM_NODE_DISCONNECTED),n(this,mc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(s=>{s.forEach((t,e)=>{const r=n(this,H).consumers.get(e);r&&this.context.getValue("peerSessionStore").emit(R.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,H).producers.values()).find(i=>i.id===e);r&&this.context.getValue("peerSessionStore").emit(R.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<=wt.length;o+=1){const c=wt[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===wt.length-1){n(this,qi).get(c).add(s);break}}for(let o=0;o<=wt.length;o+=1){const c=wt[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===wt.length-1){n(this,Hi).get(c).add(s);break}}}handlePeerLeaving(s){this.context.getValue("flagsmith").hasFeature(Y.FORCE_VIDEO_CODEC)||(n(this,Hi).forEach(t=>t.delete(s)),n(this,qi).forEach((t,e)=>{t.delete(s),!(t.size!==0||e===wt[0])&&this.disableWebcam(e)}))}},pc=new WeakMap,gc=new WeakMap,rt=new WeakMap,H=new WeakMap,Pa=new WeakMap,ht=new WeakMap,$i=new WeakMap,Fi=new WeakMap,Bi=new WeakMap,mc=new WeakMap,Xt=new WeakMap,ir=new WeakMap,fc=new WeakMap,Hi=new WeakMap,qi=new WeakMap,pt=new WeakMap,yt=new WeakMap,Hr=new WeakSet,hn=function(){return this.context.getValue("connectionHandler")},al=new WeakSet,sT=async function(s,t,e,r){m(this,gc,s);try{return n(this,Xt)?await n(this,Xt):await V(this,Tc,Hu).call(this,s,t,e,r),V(this,cl,iT).call(this,t),{roomJoined:await V(this,ol,rT).call(this)}}catch(i){return this.logger.error("Failed to complete room join",{error:i}),{roomJoined:!1}}finally{m(this,Xt,null)}},ol=new WeakSet,rT=async function(){try{this.mediaJoined=!0;const{roomState:s}=await n(this,H).socketHandler.notifySelfJoinComplete();return m(this,pc,s.roomUuid),m(this,Fi,!0),m(this,$i,!1),!0}catch(s){return this.logger.error("Error completing room join",{error:s}),this.mediaJoined=!1,!1}},cl=new WeakSet,iT=function(s){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:{...fe.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)},Tc=new WeakSet,Hu=async function(s,t,e,r){var i,a;try{(a=n(this,fc))!=null||m(this,fc,V(i=tT,dl,nT).call(i));const o=V(this,ll,aT).call(this);await V(this,ul,oT).call(this,s,t,e,o),await n(this,H).setupTransports({send:!0,recv:!0}),await V(this,hl,cT).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},dl=new WeakSet,nT=function(){const{ipInfo:s}=it();if(!(s!=null&&s.loc))return;const[t,e]=s.loc.split(",").map(parseFloat);return{latitude:t,longitude:e}},ll=new WeakSet,aT=function(){var e;const s=(e=this.context.getValue("flagsmith").getValue(Y.FORCE_VIDEO_CODEC))==null?void 0:e.toString(),t=lD(s);return m(this,Pa,t),t},ul=new WeakSet,oT=async function(s,t,e,r){await Nf(async(i,a)=>{if(!n(this,rt).isConnected){a(new Error("Socket is not connected"));return}i>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${i}`});try{await n(this,H).socketHandler.joinRoom(t,s,r,e,n(this,fc))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}},{delayTime:1e3,strategy:"exponential",maxRetryCount:1/0})},hl=new WeakSet,cT=async function(s){if(!(!this.context.getValue("flagsmith").hasFeature(Y.PRECREATE_PRODUCERS)||!s))try{const e=[];if(s.canProduceVideo===F.Allowed&&e.push(this.shareWebcam(bD(!1))),s.canProduceAudio===F.Allowed){const r=RD(!1);r&&e.push(this.shareMic(r))}e.length>0&&await Promise.all(e)}catch(e){this.logger.warn("Failed to precreate producers",{error:e})}},ze=new WeakSet,ot=function(s){return n(this,pt).get(s)},ji=new WeakSet,no=function(s,t){return n(this,pt).set(s,t)},pl=new WeakSet,dT=function(s){return n(this,pt).delete(s)},gl=new WeakSet,lT=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},ml=new WeakSet,uT=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}},g(ru,dl),ru);let re=tT;ae([y.trace("MediaNodeClient.reset",{country:y.location.country})],re.prototype,"reset",1);ae([y.trace("MediaNodeClient.joinRoom")],re.prototype,"joinRoom",1);ae([y.trace("MediaNodeClient.leaveRoom")],re.prototype,"leaveRoom",1);ae([y.trace("MediaNodeClient.activatePeers")],re.prototype,"activatePeers",1);ae([y.trace("MediaNodeClient.createConsumers")],re.prototype,"createConsumers",1);ae([y.trace("MediaNodeClient.closeConsumers")],re.prototype,"closeConsumers",1);ae([y.trace("MediaNodeClient._shareWebcam")],re.prototype,"_shareWebcam",1);ae([y.trace("MediaNodeClient.shareWebcam")],re.prototype,"shareWebcam",1);ae([y.trace("MediaNodeClient.shareScreen")],re.prototype,"shareScreen",1);ae([y.trace("MediaNodeClient.shareMic")],re.prototype,"shareMic",1);ae([y.trace("MediaNodeClient.pauseMic")],re.prototype,"pauseMic",1);ae([y.trace("MediaNodeClient.pauseWebcam")],re.prototype,"pauseWebcam",1);ae([y.trace("MediaNodeClient.resumeMic")],re.prototype,"resumeMic",1);ae([y.trace("MediaNodeClient.resumeWebcam")],re.prototype,"resumeWebcam",1);ae([y.trace("MediaNodeClient.disableWebcam")],re.prototype,"disableWebcam",1);ae([y.trace("MediaNodeClient.disableMic")],re.prototype,"disableMic",1);ae([y.trace("MediaNodeClient.disableScreenShare")],re.prototype,"disableScreenShare",1);ae([y.trace("MediaNodeClient.muteSelf")],re.prototype,"muteSelf",1);ae([y.trace("MediaNodeClient.resetVideoProducers")],re.prototype,"resetVideoProducers",1);ae([y.trace("MediaNodeClient.changeDisplayName")],re.prototype,"changeDisplayName",1);ae([y.trace("MediaNodeClient.kickPeer")],re.prototype,"kick",1);ae([y.trace("MediaNodeClient.kickAllPeers")],re.prototype,"kickAll",1);ae([y.trace("MediaNodeClient.muteAll")],re.prototype,"muteAll",1);ae([y.trace("MediaNodeClient.muteAllVideo")],re.prototype,"muteAllVideo",1);ae([y.trace("MediaNodeClient.disableAudio")],re.prototype,"disableAudio",1);ae([y.trace("MediaNodeClient.disableVideo")],re.prototype,"disableVideo",1);ae([y.trace("MediaNodeClient.pinPeer")],re.prototype,"pinPeer",1);ae([y.trace("MediaNodeClient.validateScreenShare")],re.prototype,"validateScreenShare",1);function hT(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 re(s,t);return s.setValue("roomNodeClient",r),r}function pT(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 ID=Object.defineProperty,MD=Object.getOwnPropertyDescriptor,on=(s,t,e,r)=>{for(var i=r>1?void 0:r?MD(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&&ID(t,e,i),i},Gi,fs,Q,gt,bt,_g;const gT=(_g=class{constructor(s,t,e,r){g(this,gt);u(this,"self");u(this,"authToken");g(this,Gi,void 0);u(this,"viewType");g(this,fs,void 0);g(this,Q,void 0);const{socket:i}=e,a=s.getValue("authToken");this.self=t,m(this,Q,s),this.viewType=r,this.authToken=a,m(this,Gi,i),m(this,fs,e),this.setupEvents()}get peerId(){return n(this,Q).getValue("peerId")}get telemetry(){return n(this,Q).getValue("telemetry")}get logger(){return n(this,Q).getValue("logger")}get mediaJoined(){return n(this,Q).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const a=it(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await We.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");if(navigator.product!=="ReactNative"){const h=!s.getValue("flagsmith").hasFeature(Y.PRECALL_BANDWIDTH_TEST);setTimeout(async()=>{const p=await d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(p)}),s.getValue("callstats").devices("AUDIO",p==null?void 0:p.filter(f=>f.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",p==null?void 0:p.filter(f=>f.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",p==null?void 0:p.filter(f=>f.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:fe.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:await a.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:qm(s),skipConnectivityChecks:h}),l.info("Callstats:: initialized")}catch(f){l.error("Callstats:: initialization failed",{error:f})}},0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new gT(s,d,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:a,screenShareTracks:o}=this.self;if(e.canProduceAudio===F.Allowed&&r)try{await n(this,gt,bt).shareMic(s),this.self.audioEnabled||n(this,gt,bt).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===F.Allowed&&i)try{const d=await n(this,gt,bt).shareWebcam(t);d&&d.id!==t.id&&n(this,Q).getValue("flagsmith").hasFeature(Y.EXP_RESHARE)&&await n(this,gt,bt).shareWebcam(d),this.self.videoEnabled||n(this,gt,bt).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===F.Allowed&&a)try{await((c=n(this,gt,bt))==null?void 0:c.shareScreen({video:o.video,audio:o.audio}))}catch(d){this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){n(this,Q).getValue("callstats").callEnded(),n(this,gt,bt).reset(),s&&await this.joinRoom(s)}setupEvents(){n(this,Q).getValue("peerSessionStore").on(R.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),n(this,Q).getValue("peerSessionStore").on(R.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),n(this,Q).getValue("peerSessionStore").on(R.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),n(this,Q).getValue("peerSessionStore").on(R.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,Q).getValue("peerSessionStore").on(R.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),n(this,Q).getValue("peerSessionStore").on(R.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&n(this,Q).getValue("flagsmith").hasFeature(Y.REFRESH_ID_ON_DISCONNECTION)&&(t=ur.v4()),n(this,Gi).updateURL(t),n(this,Q).getValue("telemetry").resetPeerId(t),it().setHeader("tracing-id",t),cr.remapContext(t,n(this,Q)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),n(this,Q).getValue("peerSessionStore").on(R.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,fs).on(L.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),n(this,fs).on(Xc.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&n(this,Q).getValue("peerSessionStore").emit(R.UPDATE_PERMISSIONS,t.patch)})}),n(this,fs).on(L.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),n(this,fs).on(L.kick,()=>{this.kickHandler({kickType:"kick"})}),n(this,fs).on(L.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),n(this,Q).getValue("peerSessionStore").onAsync(R.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),n(this,Q).getValue("peerSessionStore").on(R.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,Q).getValue("peerSessionStore").on(R.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),n(this,Q).getValue("callstats").audioOff())}),n(this,Q).getValue("peerSessionStore").on(R.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),n(this,Q).getValue("callstats").videoOff())}),n(this,Q).getValue("peerSessionStore").onAsync(R.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),n(this,Q).getValue("peerSessionStore").on(R.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await n(this,fs).joinRoom(this.self);n(this,fs).socket.flush();const e=vh(t.stageType);if(n(this,Q).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}await this.joinMediaRoom(s),n(this,Q).notify("stageStatus")}catch(t){throw this.logger.error("Error in joinRoom",{error:t}),t}}async leaveRoom(s="left"){var t,e;if(this.logger.info(`Leaving room with state: ${s}`),(t=n(this,Q).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),n(this,Q).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),n(this,Q).notify("stageStatus");try{(e=n(this,Gi))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}pT(n(this,Q)),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var a,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=n(this,Q).getAllValues();try{if(e===lr.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}hT(n(this,Q),{socket:n(this,Gi),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:h}=(o=await((a=n(this,gt,bt))==null?void 0:a.joinRoom(this.self.name,r,s,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!h)return;i==="ON_STAGE"&&await this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:c}),new k("Error: could not join media room","0002")}}async leaveMediaRoom(s){const t=n(this,Q).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===lr.Webinar)&&n(this,gt,bt)&&(n(this,gt,bt).mediaJoined&&s!=="disconnected"&&await n(this,gt,bt).leaveRoom(),!(s==="stageLeft"&&t===lr.Livestream)&&(n(this,gt,bt).mediaJoined=!1))}async cleanupSelf(){await this.self.disableAudio(),await this.self.disableVideo(),await this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()}},Gi=new WeakMap,fs=new WeakMap,Q=new WeakMap,gt=new WeakSet,bt=function(){return n(this,Q).getValue("roomNodeClient")},_g);let Zr=gT;on([y.trace("SelfController.resetSelf")],Zr.prototype,"resetSelf",1);on([y.trace("SelfController.setupEvents")],Zr.prototype,"setupEvents",1);on([y.trace("SelfController.joinRoom")],Zr.prototype,"joinRoom",1);on([y.trace("SelfController.leaveRoom")],Zr.prototype,"leaveRoom",1);on([y.trace("SelfController.joinMediaRoom")],Zr.prototype,"joinMediaRoom",1);on([y.trace("SelfController.leaveMediaRoom")],Zr.prototype,"leaveMediaRoom",1);on([y.trace("SelfController.init")],Zr,"init",1);var vc;class DD{constructor(t){g(this,vc,void 0);m(this,vc,t)}on(t,e){let r;t===L.roomPeerCount?r=Ip.fromBinary.bind(Ip):r=Bp.fromBinary.bind(Bp),n(this,vc).on(t,({payload:i})=>{if(t===L.roomPeerCount&&!i)return;const a=r(i);e(a)})}}vc=new WeakMap;var Sc,yc;class OD{constructor(t,e){g(this,Sc,void 0);g(this,yc,void 0);m(this,Sc,e),m(this,yc,t)}get logger(){return n(this,yc).getValue("logger")}on(t,e){let r,i;switch(t){case L.transcript:{r=Jl.fromBinary.bind(Jl),i=Jl.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}n(this,Sc).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)})}}Sc=new WeakMap,yc=new WeakMap;var ND=Object.defineProperty,VD=Object.getOwnPropertyDescriptor,Ih=(s,t,e,r)=>{for(var i=r>1?void 0:r?VD(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&&ND(t,e,i),i},nr,_a;class Vl{constructor(t,e){g(this,nr,void 0);g(this,_a,void 0);m(this,nr,e),m(this,_a,t)}get logger(){return n(this,_a).getValue("logger")}get telemetry(){return n(this,_a).getValue("telemetry")}getPolls(){return n(this,nr).sendMessagePromise($s.getPolls)}createPoll(t,e,r=!1,i=!1){const a={anonymous:r,hideVotes:i,question:t,options:e};return n(this,nr).sendMessage($s.createPoll,qI.toBinary(a))}votePoll(t,e){const r={index:e,pollId:t};return n(this,nr).sendMessage($s.votePoll,GI.toBinary(r))}on(t,e){let r,i;switch(t){case $s.updatePoll:case $s.createPoll:case $s.votePoll:{r=Zl.fromBinary.bind(Zl),i=Zl.create();break}}n(this,nr).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,nr).removeListeners(t)}}nr=new WeakMap,_a=new WeakMap;Ih([y.trace("PollSocketHandler.getPolls")],Vl.prototype,"getPolls",1);Ih([y.trace("PollSocketHandler.createPoll")],Vl.prototype,"createPoll",1);Ih([y.trace("PollSocketHandler.votePoll")],Vl.prototype,"votePoll",1);var LD=Object.defineProperty,xD=Object.getOwnPropertyDescriptor,UD=(s,t,e,r)=>{for(var i=r>1?void 0:r?xD(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&&LD(t,e,i),i},Nt;class mT{constructor(t,e){u(this,"socket");g(this,Nt,void 0);m(this,Nt,t),this.socket=e,this.handleSocketEvents(),n(this,Nt).setValue("roomSocketHandler",this)}get telemetry(){return n(this,Nt).getValue("telemetry")}get logger(){return n(this,Nt).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}async joinRoom(t){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(L.joinRoom,Vb.toBinary(e));try{const{peer:a}=dn.fromBinary((await r).payload);n(this,Nt).getValue("connectionHandler").socketJoined=!0,n(this,Nt).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_ROOM_JOINED,{peer:a});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return n(this,Nt).getValue("peerSessionStore").emit(R.ROOM_STATE,d),n(this,Nt).getValue("peerSessionStore").emit(R.SOCKET_PEERS,l),{peer:a}}catch(a){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:a}),new k("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,a)}}async getAllAddedParticipants(){try{return Sk.fromBinary((await this.socket.sendMessagePromise(L.getAllAddedParticipants)).payload).participants.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}async getRoomPeers(t,e,r){let i;try{const a={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise(L.getRoomPeersInfo,wb.toBinary(a));i=Kl.fromBinary(o.payload)}catch(a){this.logger.error("getRoomPeers::binary_decode_error",{error:a})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise(L.getRoomPeersInfo);t=Kl.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getStagePeers(){let t;try{const e=await this.socket.sendMessagePromise(L.getRoomPeersInfo);t=Kl.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getPeerInfo(t){let e;try{const r=await this.socket.sendMessagePromise(L.getPeerInfo,Zm.toBinary({peerId:t}));e=dn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=Mp.create();try{const e=await this.socket.sendMessagePromise(L.getRoomInfo);t=Mp.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=Vp.create();try{const e=await this.socket.sendMessagePromise(L.getRoomStageState);t=Vp.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t}async broadcastMessage(t,e){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(L.broadcastMessage,Ya.toBinary(r))}async broadcastToMeetings(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(L.broadcastToEntity,Ya.toBinary(i))}async broadcastToPeers(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(L.broadcastToEntity,Ya.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(L.leaveRoom,xb.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(L.kick,tf.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(L.kickAll,Ym.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(L.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(L.acceptWaitingRoomRequests,wk.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(L.denyWaitingRoomRequests,bk.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Xc.updateUserPreset,sA.toBinary(r))}handleSocketEvents(){this.socket.on(L.broadcastMessage,({payload:t})=>{try{const e=Ya.fromBinary(t);n(this,Nt).getValue("peerSessionStore").emit(R.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(L.broadcastToEntity,({payload:t})=>{try{const e=Ya.fromBinary(t);n(this,Nt).getValue("peerSessionStore").emit(R.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 L.joinRoom:case L.leaveRoom:case L.kick:case L.kickAll:{r=dn.fromBinary.bind(dn),i=dn.create();break}case L.getWaitingRoomRequests:{r=(a,o)=>a?Np.fromBinary(a,o):{requests:[]},i=Np.create();break}case L.recordingPaused:case L.recordingStarted:case L.recordingStopped:{r=jp.fromBinary.bind(jp);break}case Xc.updateUserPreset:{r=Lp.fromBinary.bind(Lp);break}case Ss.peerJoinedBroadcast:case Rr.peerJoinedBroadcast:{r=wp.fromBinary.bind(wp);break}case Ss.selfJoinComplete:case Rr.selfJoinComplete:{r=pu.fromBinary.bind(pu);break}case Ss.globalPeerPinBroadcast:case Rr.globalPeerPinBroadcast:{r=kp.fromBinary.bind(kp);break}case Ss.selectedPeer:case Rr.selectedPeer:{r=hu.fromBinary.bind(hu);break}case Ss.selectedPeerDiff:case Rr.selectedPeerDiff:{r=Cp.fromBinary.bind(Cp);break}case Ss.leaveRoom:case Rr.leaveRoom:{r=gu.fromBinary.bind(gu);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)})}async getUserPermissions(t){const e={userIds:[t]};try{const r=await this.socket.sendMessagePromise(Xc.getUserPresets,zk.toBinary(e)),i=Zk.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}}}Nt=new WeakMap;UD([y.trace("RoomSocketHandler.joinRoom")],mT.prototype,"joinRoom",1);var Et;class $D{constructor(t){g(this,Et,void 0);m(this,Et,t)}async getStageRequests(){const{payload:t}=await n(this,Et).sendMessagePromise(L.getStageRequests);return t?Xl.fromBinary(t):{stageRequests:[]}}requestAccess(){n(this,Et).sendMessage(L.requestStageAccess)}cancelRequestAccess(){n(this,Et).sendMessage(L.cancelStageRequest)}async grantAccess(t){const e={userIds:t};n(this,Et).sendMessage(L.grantStageAccess,OI.toBinary(e))}async denyAccess(t){const e={userIds:t};n(this,Et).sendMessage(L.denyStageAccess,VI.toBinary(e))}joinStage(){return n(this,Et).sendMessagePromise(L.joinStage,void 0,void 0,L.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return n(this,Et).sendMessagePromise(L.leaveStage,qp.toBinary(e),void 0,L.peerStageStatusUpdate)}kick(t){const e={userIds:t};return n(this,Et).sendMessagePromise(L.leaveStage,qp.toBinary(e))}on(t,e){let r;switch(t){case L.grantStageAccess:case L.denyStageAccess:{r=void 0;break}case L.getStagePeers:{r=Hp.fromBinary.bind(Hp);break}case L.getStageRequests:case L.requestStageAccess:case L.cancelStageRequest:{r=Xl.fromBinary.bind(Xl);break}case L.peerStageStatusUpdate:{r=Ap.fromBinary.bind(Ap);break}}n(this,Et).on(t,({payload:i,id:a})=>{if(!i||!r)return e(void 0,a);const o=r(i);return e(o,a)})}async getPeerInfo(t){const e=await n(this,Et).sendMessagePromise(L.getPeerInfo,Zm.toBinary({peerId:t}));return dn.fromBinary(e.payload)}}Et=new WeakMap;var Fe,Ec;class FD{constructor(t,e){g(this,Fe,void 0);g(this,Ec,void 0);m(this,Fe,e),m(this,Ec,t)}get logger(){return n(this,Ec).getValue("logger")}addPlugin(t,e){n(this,Fe).sendMessage(q.addPlugin,YA.toBinary({pluginId:t,staggered:e}))}removePlugin(t){n(this,Fe).sendMessage(q.removePlugin,XA.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await n(this,Fe).sendMessagePromise(q.getPlugins);return t?EI.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};n(this,Fe).sendMessage(q.customPluginEventToRoom,cI.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const a={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};n(this,Fe).sendMessage(q.customPluginEventToPeers,lI.toBinary(a),i)}enablePluginForRoom(t,e){n(this,Fe).sendMessage(q.enablePluginForRoom,eI.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){n(this,Fe).sendMessage(q.enablePluginForPeers,iI.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){n(this,Fe).sendMessage(q.disablePluginForRoom,sI.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){n(this,Fe).sendMessage(q.disablePluginForPeers,aI.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,Fe).sendMessage(q.storeInsertKeys,xp.toBinary(a),i)}storeGetKeys(t,e,r,i){const a={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};n(this,Fe).sendMessage(q.storeGetKeys,gI.toBinary(a),i)}storeDeleteKeys(t,e,r,i){const a={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};n(this,Fe).sendMessage(q.storeDeleteKeys,fI.toBinary(a),i)}storeDelete(t,e,r){n(this,Fe).sendMessage(q.storeDelete,vI.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,Fe).sendMessage(q.storeInsertKeys,xp.toBinary(i))}on(t,e){let r;switch(t){case q.addPlugin:case q.enablePluginForPeers:case q.enablePluginForRoom:{r=vu.fromBinary.bind(vu);break}case q.removePlugin:case q.disablePluginForPeers:case q.disablePluginForRoom:{r=Up.fromBinary.bind(Up);break}case q.customPluginEventToPeers:case q.customPluginEventToRoom:{r=Fp.fromBinary.bind(Fp);break}case q.storeInsertKeys:case q.storeGetKeys:case q.storeDeleteKeys:case q.storeDelete:{r=$p.fromBinary.bind($p);break}}n(this,Fe).on(t,({payload:i,id:a})=>{const o=r(i);return e(o,a)})}}Fe=new WeakMap,Ec=new WeakMap;var BD=Object.defineProperty,HD=(s,t,e)=>t in s?BD(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,qD=(s,t,e)=>(HD(s,typeof t!="symbol"?t+"":t,e),e),Mh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},I=(s,t,e)=>(Mh(s,t,"read from private field"),e?e.call(s):t.get(s)),pe=(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)},se=(s,t,e,r)=>(Mh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),ye=(s,t,e)=>(Mh(s,t,"access private method"),e),yd={},jD={get exports(){return yd},set exports(s){yd=s}},_n=typeof Reflect=="object"?Reflect:null,tg=_n&&typeof _n.apply=="function"?_n.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},nd;_n&&typeof _n.ownKeys=="function"?nd=_n.ownKeys:Object.getOwnPropertySymbols?nd=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:nd=function(s){return Object.getOwnPropertyNames(s)};function GD(s){console&&console.warn&&console.warn(s)}var fT=Number.isNaN||function(s){return s!==s};function ne(){ne.init.call(this)}jD.exports=ne;yd.once=zD;ne.EventEmitter=ne;ne.prototype._events=void 0;ne.prototype._eventsCount=0;ne.prototype._maxListeners=void 0;var sg=10;function Ll(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ne,"defaultMaxListeners",{enumerable:!0,get:function(){return sg},set:function(s){if(typeof s!="number"||s<0||fT(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");sg=s}});ne.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};ne.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||fT(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 TT(s){return s._maxListeners===void 0?ne.defaultMaxListeners:s._maxListeners}ne.prototype.getMaxListeners=function(){return TT(this)};ne.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")tg(c,this,t);else for(var d=c.length,l=PT(c,d),e=0;e<d;++e)tg(l[e],this,t);return!0};function vT(s,t,e,r){var i,a,o;if(Ll(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=TT(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,GD(c)}return s}ne.prototype.addListener=function(s,t){return vT(this,s,t,!1)};ne.prototype.on=ne.prototype.addListener;ne.prototype.prependListener=function(s,t){return vT(this,s,t,!0)};function WD(){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 ST(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=WD.bind(r);return i.listener=e,r.wrapFn=i,i}ne.prototype.once=function(s,t){return Ll(t),this.on(s,ST(this,s,t)),this};ne.prototype.prependOnceListener=function(s,t){return Ll(t),this.prependListener(s,ST(this,s,t)),this};ne.prototype.removeListener=function(s,t){var e,r,i,a,o;if(Ll(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,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():JD(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this};ne.prototype.off=ne.prototype.removeListener;ne.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 yT(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?KD(i):PT(i,i.length)}ne.prototype.listeners=function(s){return yT(this,s,!0)};ne.prototype.rawListeners=function(s){return yT(this,s,!1)};ne.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):ET.call(s,t)};ne.prototype.listenerCount=ET;function ET(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}ne.prototype.eventNames=function(){return this._eventsCount>0?nd(this._events):[]};function PT(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function JD(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function KD(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function zD(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))}_T(s,t,a,{once:!0}),t!=="error"&&YD(s,i,{once:!0})})}function YD(s,t,e){typeof s.on=="function"&&_T(s,"error",t,e)}function _T(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 QD extends v.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 rg=new QD;class CT{static encode(t){return rg.toBinary(t)}static decode(t){return rg.fromBinary(new Uint8Array(t))}}function XD(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Cr;class ZD{constructor(t={}){qD(this,"opts"),pe(this,Cr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},se(this,Cr,0)}async wait(){se(this,Cr,I(this,Cr)+1);const t=XD(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**I(this,Cr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return I(this,Cr)}reset(){se(this,Cr,0)}}Cr=new WeakMap;const yr={debug:0,info:1,warn:2,error:3};var ii,ni;class eO{constructor(t){pe(this,ii,void 0),pe(this,ni,void 0),se(this,ii,console),se(this,ni,t)}debug(...t){yr[I(this,ni)]>yr.debug||I(this,ii).debug("[Sockrates]:",...t)}info(...t){yr[I(this,ni)]>yr.info||I(this,ii).info("[Sockrates]:",...t)}warn(...t){yr[I(this,ni)]>yr.warn||I(this,ii).warn("[Sockrates]:",...t)}error(...t){yr[I(this,ni)]>yr.error||I(this,ii).error("[Sockrates]:",...t)}}ii=new WeakMap,ni=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 tO="2",sO="3";var Re,pn,Se,Oe,wr,Ge,or,Wr,vs,gn,Us,qu,RT,ao,ad,ju,bT,Gu,ig,Ed,Wu,Ju,kT,lo,od,uo,Pd,_d,Ku,Cn,ho,po,Cd;class rO{constructor(t,e){var f,T,E,w,C,_,N,U,D,$;pe(this,qu),pe(this,ao),pe(this,ju),pe(this,Gu),pe(this,Ed),pe(this,Ju),pe(this,lo),pe(this,uo),pe(this,_d),pe(this,Cn),pe(this,po),pe(this,Re,void 0),pe(this,pn,void 0),pe(this,Se,void 0),pe(this,Oe,void 0),pe(this,wr,void 0),pe(this,Ge,void 0),pe(this,or,void 0),pe(this,Wr,void 0),pe(this,vs,void 0),pe(this,gn,void 0),pe(this,Us,void 0);var r,i,a,o,c,d,l,h,p;se(this,pn,t),se(this,wr,[]),se(this,Ge,new yd),se(this,or,!0),se(this,vs,!1),se(this,Se,e!=null?e:{}),(f=(r=I(this,Se)).autoReconnect)!=null||(r.autoReconnect=!0),(T=(i=I(this,Se)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(E=(a=I(this,Se)).pingTimeout)!=null||(a.pingTimeout=3e4),(w=(o=I(this,Se)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(C=(c=I(this,Se)).debug)!=null||(c.debug=!0),(_=(d=I(this,Se)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(N=(l=I(this,Se)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(U=(h=I(this,Se)).queueOnDisconnect)!=null||(h.queueOnDisconnect=!1),(D=(p=I(this,Se)).flushOnReconnect)!=null||(p.flushOnReconnect=!1),se(this,Wr,{code:void 0,reason:void 0}),se(this,Oe,($=I(this,Se).logger)!=null?$:new eO(I(this,Se).debug?"debug":"info")),se(this,Us,new ZD)}get readyState(){var t;return(t=I(this,Re))==null?void 0:t.readyState}get url(){return I(this,pn)}updateURL(t){se(this,pn,t),ye(this,Ju,kT).call(this)}get config(){return I(this,Se)}get sendQueue(){return I(this,wr)}flush(){if(!I(this,Se).queueOnDisconnect)return!1;const t=[];return I(this,wr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),se(this,wr,t),I(this,wr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){I(this,Oe).debug("Websocket was already connecting or connected.");return}if(I(this,or)!==!1)return new Promise((e,r)=>{ye(this,Cn,ho).call(this),ye(this,po,Cd).call(this);try{se(this,Re,new WebSocket(ye(this,qu,RT).call(this,I(this,pn)))),I(this,Re).binaryType="arraybuffer",I(this,Oe).debug("Connecting");const i=setTimeout(()=>{I(this,Oe).debug("Connection timeout. Closing socket"),se(this,or,!0),ye(this,po,Cd).call(this),I(this,Re).close(3001,"Connection Timeout"),I(this,Se).autoReconnect&&!I(this,vs)&&(I(this,Ge).emit("reconnecting"),ye(this,lo,od).call(this)),r(new Error("Connection timed out!"))},I(this,Se).connectionTimeout);I(this,Re).onopen=()=>{I(this,Oe).debug(`Ready State: ${wT[I(this,Re).readyState]}`),i&&clearTimeout(i),ye(this,_d,Ku).call(this),se(this,Wr,{code:void 0,reason:void 0}),I(this,Ge).emit("connected"),I(this,Se).flushOnReconnect&&this.flush(),e()},I(this,Re).onclose=a=>{try{i&&clearTimeout(i);const{code:o,reason:c}=a;r(c),I(this,Oe).debug("Socket closed. Close event:",{event:a}),I(this,Oe).debug(`Connection closed code: ${o}`),I(this,Oe).debug(`Connection closed reason: ${c}`),I(this,vs)||ye(this,Ed,Wu).call(this,o,c)}catch(o){ye(this,ao,ad).call(this,o)}},I(this,Re).onerror=a=>{ye(this,ao,ad).call(this,a)},I(this,Re).onmessage=a=>ye(this,ju,bT).call(this,a)}catch(i){ye(this,ao,ad).call(this,i,r)}})}send(t,e,r,i){const a={event:t,id:e,payload:r,metadata:i};if(I(this,Se).queueOnDisconnect&&(!I(this,Re)||I(this,Re).readyState!==1))return I(this,Oe).debug("Queuing message since socket is not connected!",a),I(this,wr).push(a),!1;const o=CT.encode(a);return ye(this,uo,Pd).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return ye(this,uo,Pd).call(this,t)}receive(t,e){return I(this,Ge).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")){I(this,Ge).on(t,e);return}this.receive(t,e)}removeAllListeners(){I(this,Ge).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){I(this,Ge).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){I(this,Ge).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){se(this,or,!1),ye(this,Cn,ho).call(this),this.removeAllListeners(),se(this,Wr,{code:1e3,reason:"Sockrates disconnect method called"}),I(this,Re).close(1e3,"Sockrates disconnect method called.")}}Re=new WeakMap,pn=new WeakMap,Se=new WeakMap,Oe=new WeakMap,wr=new WeakMap,Ge=new WeakMap,or=new WeakMap,Wr=new WeakMap,vs=new WeakMap,gn=new WeakMap,Us=new WeakMap,qu=new WeakSet,RT=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)://.")},ao=new WeakSet,ad=function(s,t){I(this,Oe).error("Error:",{error:s}),I(this,Ge).emit("errored",{error:s}),t==null||t(s)},ju=new WeakSet,bT=function(s){if(ye(this,_d,Ku).call(this),s.data===tO){I(this,Oe).debug("Received ping from server"),ye(this,uo,Pd).call(this,sO);return}const t=CT.decode(s.data),{id:e,payload:r}=t;I(this,Oe).debug("Received message",{event:t.event,messageID:e}),I(this,Ge).emit(t.event.toString(),{id:e,payload:r})},Gu=new WeakSet,ig=function(){return I(this,Re).readyState===1},Ed=new WeakSet,Wu=function(s,t){se(this,Wr,{reason:t,code:s}),I(this,Ge).emit("disconnected",{code:s,reason:t})},Ju=new WeakSet,kT=function(){const{reason:s,code:t}=I(this,Wr);t&&t!==1e3&&I(this,or)&&I(this,Se).autoReconnect&&!I(this,vs)&&(I(this,Oe).debug(`Triggering reconnection due to ${s}.`),I(this,Ge).emit("reconnecting"),ye(this,lo,od).call(this))},lo=new WeakSet,od=async function(s=!0){if(s&&I(this,vs)){I(this,Oe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(I(this,vs)||I(this,Us).reset(),I(this,Se).maxReconnectionAttempts!==null&&I(this,Us).getAttempts()>=I(this,Se).maxReconnectionAttempts){I(this,Ge).emit("failed"),se(this,vs,!1);return}se(this,vs,!0),ye(this,po,Cd).call(this),ye(this,Cn,ho).call(this);try{if(await I(this,Us).wait(),I(this,or)===!1)return;if(I(this,Oe).debug(`Reconnection attempt ${I(this,Us).getAttempts()}`),I(this,Ge).emit("reconnectAttempt",{attempt:I(this,Us).getAttempts()}),await this.connect(),!ye(this,Gu,ig).call(this))throw Error("Reconnect Failed");se(this,vs,!1),se(this,Wr,{code:void 0,reason:void 0}),I(this,Ge).emit("reconnected")}catch(t){I(this,Oe).debug("Failed to reconnect."),I(this,Ge).emit("reconnectFailure",{attempt:I(this,Us).getAttempts()}),ye(this,lo,od).call(this,!1)}},uo=new WeakSet,Pd=function(s){try{return I(this,Re).send(s),!0}catch(t){return I(this,Oe).error(t.message),!1}},_d=new WeakSet,Ku=function(){this.config.disconnectOnPingTimeout&&(I(this,Oe).debug("Resetting ping timeout"),ye(this,Cn,ho).call(this),se(this,gn,setTimeout(()=>{var s;I(this,Oe).debug("Disconnecting the socket due to ping timeout"),se(this,or,!0);const t=3002,e="Ping timeout";(s=I(this,Re))==null||s.close(t,e),ye(this,Ed,Wu).call(this,t,e)},I(this,Se).pingTimeout)))},Cn=new WeakSet,ho=function(){I(this,gn)&&(clearTimeout(I(this,gn)),se(this,gn,void 0))},po=new WeakSet,Cd=function(){I(this,Re)&&(I(this,Re).onopen=void 0,I(this,Re).onerror=void 0,I(this,Re).onmessage=void 0,I(this,Re).onclose=void 0)};var iO=Object.defineProperty,nO=Object.getOwnPropertyDescriptor,xl=(s,t,e,r)=>{for(var i=r>1?void 0:r?nO(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&&iO(t,e,i),i};const ng=65535,aO=3e3;var qr,Ee,Pe,ke,Zt,Ye,Pc,zu,_c,Yu,Cg;const AT=(Cg=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,Pe);g(this,Pc);g(this,_c);g(this,qr,void 0);g(this,Ee,void 0);u(this,"roomName");u(this,"authToken");u(this,"capabilities");g(this,Zt,void 0);g(this,Ye,void 0);var a;if(!t||!e||!r)throw new k("peerId, meetingId, or authToken can not be empty","0404");m(this,Zt,void 0),m(this,Ye,s),this.capabilities=i,this.roomName=e,this.authToken=r,m(this,qr,V(this,Pc,zu).call(this,t)),m(this,Ee,new rO(n(this,qr),{autoReconnect:!0,disconnectOnPingTimeout:(a=i.includes("PING"))!=null?a:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return n(this,Pe,ke).socketJoinAttempted}set joinAttempted(s){n(this,Pe,ke).socketJoinAttempted=s}get telemetry(){return n(this,Ye).getValue("telemetry")}get logger(){return n(this,Ye).getValue("logger")}get peerId(){return n(this,Ye).getValue("peerId")}updateURL(s){s!==this.peerId&&(m(this,qr,V(this,Pc,zu).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),n(this,Ee).updateURL(n(this,qr))}static getSocketEdgeDomain(s){return Yi({servicePrefix:"socket-edge",baseURI:s})}get url(){return n(this,qr)}async connect(){n(this,Pe,ke).socketJoinAttempted=!0,await n(this,Ee).connect(),n(this,Pe,ke).socketJoinAttempted=!0,n(this,Pe,ke).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){n(this,Pe,ke).socketJoinAttempted=!1,n(this,Ee).disconnect(),n(this,Pe,ke).socketJoinAttempted=!0,n(this,Pe,ke).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return n(this,Ee).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return n(this,Ye).getValue("telemetry").injectContext(r),n(this,Ee).send(s,e!=null?e:V(this,_c,Yu).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=(E,w)=>{n(this,Ee).removeListener(a,E),n(this,Ee).removeListener(ng,w),n(this,Ee).removeListener(Rr.errorResponse,w),n(this,Ee).removeListener(Ss.errorResponse,w)},l=r!=null?r:V(this,_c,Yu).call(this),h={};n(this,Ye).getValue("telemetry").injectContext(h);const f=({id:E,payload:w})=>{if(l===E){let C;try{const _=TR.fromBinary(w);C=new Error(_.errorMessage)}catch(_){C=new Error("failed to parse error message",{cause:_});try{const N=vb.fromBinary(w);C=new Error(N.message)}catch(N){C=new Error("failed to parse error message",{cause:N})}}c(C),d(T,f)}},T=({id:E,payload:w})=>{l===E&&(o({id:E,payload:w}),d(T,f))};n(this,Ee).on(a,T),n(this,Ee).on(ng,f),n(this,Ee).on(Rr.errorResponse,f),n(this,Ee).on(Ss.errorResponse,f),setTimeout(()=>{d(T,f),c(new Error(`request timeout for callback eventId:${s}`))},t),n(this,Ee).send(s,l,e,new TextEncoder().encode(JSON.stringify(h)))})}on(s,t){n(this,Ee).on(s,t)}onStateEvent(s,t){n(this,Ee).on(s,t)}removeListener(s,t){n(this,Ee).removeListener(s,t)}removeListeners(s){n(this,Ee).removeListeners(s)}flush(){return n(this,Ee).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),n(this,Zt)&&(clearTimeout(n(this,Zt)),m(this,Zt,void 0)),n(this,Pe,ke).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:y.location.country});const{recv:e,send:r}=(i=n(this,Pe,ke).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Pn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Pn.CONNECTED?n(this,Ye).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,Pe,ke).joinAttempted}):m(this,Zt,setTimeout(()=>{n(this,Ye).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,Pe,ke).joinAttempted}),m(this,Zt,void 0)},aO)),n(this,Pe,ke).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge",{country:y.location.country}),n(this,Pe,ke).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),n(this,Pe,ke).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),n(this,Pe,ke).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:n(this,Pe,ke).mediaJoinAttempted}}),n(this,Zt)&&(clearTimeout(n(this,Zt)),m(this,Zt,void 0)),n(this,Ye).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:n(this,Pe,ke).mediaJoinAttempted}),n(this,Pe,ke).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge",{country:y.location.country}),n(this,Ye).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_FAILED),n(this,Pe,ke).updateSocketConnectionState("failed")})}},qr=new WeakMap,Ee=new WeakMap,Pe=new WeakSet,ke=function(){return n(this,Ye).getValue("connectionHandler")},Zt=new WeakMap,Ye=new WeakMap,Pc=new WeakSet,zu=function(s){let t=AT.getSocketEdgeDomain(n(this,Ye).getValue("baseURI"));typeof ba(n(this,Ye),"socket_server_base")=="string"&&(t=ba(n(this,Ye),"socket_server_base"));const e=`wss://${t}`,r=new URL(`${e}/ws`),i=this.peerId,a={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...i!==s&&{oldPeerID:i},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>gd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(a).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},_c=new WeakSet,Yu=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Cg);let Vc=AT;xl([y.trace("SocketService.connect")],Vc.prototype,"connect",1);xl([y.trace("SocketService.disconnect")],Vc.prototype,"disconnect",1);xl([y.trace("SocketService.sendMessagePromise")],Vc.prototype,"sendMessagePromise",1);xl([y.trace("SocketService.sendMessagePromiseWithTimeout")],Vc.prototype,"sendMessagePromiseWithTimeout",1);class oO{constructor(t){u(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var a;const e=Gb.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=Tk.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=ef.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return Op.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return ok.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(L.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(L.createConnectedRooms,zb.toBinary({payloads:t}));return Op.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}async updateConnectedRooms(t){}async disableConnectedRooms(t){const e=t.map(i=>({id:i})),r=await this.socketService.sendMessagePromise(L.deleteConnectedRooms,nk.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(L.movePeers,pk.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 cO=Object.defineProperty,dO=Object.getOwnPropertyDescriptor,lO=(s,t,e,r)=>{for(var i=r>1?void 0:r?dO(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&&cO(t,e,i),i},Ts;class IT extends Ut{constructor(e){const r=e.getValue("logger");super(r);u(this,"meetings",[]);u(this,"parentMeeting",null);g(this,Ts,void 0);m(this,Ts,e)}get supportsConnectedMeetings(){return n(this,Ts).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.
11
11
  Please connect with our support team to enable connected meetings.`)}async getConnectedMeetings(){this.validateConnectedMeetingsAction(),this.logger.info("Getting connected meetings dump");const e=await n(this,Ts).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await n(this,Ts).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await n(this,Ts).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)}async deleteMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(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.`),await Promise.all(r);const i=await n(this,Ts).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const a=await n(this,Ts).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}async moveParticipantsWithCustomPreset(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const a=await n(this,Ts).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{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}Ts=new WeakMap;lO([_t({maxInvocations:60,period:60})],IT.prototype,"getConnectedMeetings",1);var uO=Object.defineProperty,hO=Object.getOwnPropertyDescriptor,Dh=(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&&uO(t,e,i),i},le,wg;const MT=(wg=class{constructor(s){u(this,"connectedMeetings");g(this,le,void 0);m(this,le,s),this.connectedMeetings=new IT(s)}get telemetry(){return n(this,le).getValue("telemetry")}get logger(){return n(this,le).getValue("logger")}static init(s){const t=new MT(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){n(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(L.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),n(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(L.transferPeer,this.handleTransferPeer.bind(this)),n(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(L.movedPeer,this.handleMovedPeer.bind(this)),n(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(L.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),n(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(L.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=n(this,le).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,a,o,c;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
12
12
  Please connect with our support team to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:n(this,le).getValue("self").videoEnabled,audio:n(this,le).getValue("self").audioEnabled};try{n(this,le).getValue("self").cleanupEvents(),await n(this,le).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(a=(i=n(this,le).getValue("meeting"))==null?void 0:i.meta)==null?void 0:a.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await OT.init({...n(this,le).getValue("options"),cachedUserDetails:null,defaults:{...n(this,le).getValue("options").defaults,...e,mediaHandler:n(this,le).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=n(this,le).getValue("self");r.self.setName(n(this,le).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=n(this,le).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,le).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=n(this,le).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s),e=new Map;this.connectedMeetings.meetings.forEach(r=>{e.set(r.id,r)}),t.forEach(r=>{e.has(r.id)?e.get(r.id).title=r.title:e.set(r.id,{...r,participants:[]})}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=n(this,le).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})}},le=new WeakMap,wg);let Ul=MT;Dh([y.trace("ConnectedMeetingsController.getConnectedMeetings")],Ul.prototype,"getConnectedMeetings",1);Dh([y.trace("ConnectedMeetingsController.setupEvents")],Ul.prototype,"setupEvents",1);Dh([y.trace("ConnectedMeetingsController.switchMeeting")],Ul.prototype,"switchMeeting",1);var pO=Object.defineProperty,gO=Object.getOwnPropertyDescriptor,$l=(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};const mn=class{constructor(s,t,e){u(this,"apiBase");u(this,"selfController");u(this,"pollController");u(this,"chatController");u(this,"metaController");u(this,"storesManager");u(this,"stageController");u(this,"pluginController");u(this,"internalsController");u(this,"recordingController");u(this,"livestreamController");u(this,"participantController");u(this,"connectedMeetingsController");u(this,"telemetry");u(this,"logger");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController,this.connectedMeetingsController=t.connectedMeetingsController,this.telemetry=e.getValue("telemetry"),this.logger=e.getValue("logger")}static async init(s){var D,$;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:a,cachedUserDetails:o,logger:c}=s.getAllValues();if(pT(s),fe.isSupported()===!1)throw new k("Browser not supported","0010",c,!0);const d=yM(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 t0(s);s.setValue("connectionHandler",l);const h=mn.createSocketService(s),p=h.connect(),f=d.getUserDetails(),T=d.getPlugins();let E,w="";try{await mn.setupFlagsmith(s)}catch(G){c.error("Failed to setup flagsmith",{error:G})}try{await p}catch(G){c.error("[Controller]: Failed to connect to socket server:",{error:G})}try{({meetingTitle:w}=await d.getRoomNodeData()),E=await f,c.info("CF SFU is being used."),s.setValue("presetName",E.preset.name)}catch(G){c.error("Failed to get room metadata",{error:G})}const C=bu.init(E.preset,!s.getValue("modules").theme),_=Mu.init(s,C.viewType,E.preset.permissions),N=mn.setupControllers(h,s,E,T,w,C,_);jM(C)&&((D=mn.createRoomNodeClient(s,h).initializeConnection(E.participant.name,i,!1,_))==null||D.catch(ee=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:ee})})),y.location.country=($=d.ipInfo)==null?void 0:$.country;const{controllers:U}=await N;return XC(),new mn(e,U,s)}static async setupFlagsmith(s){var l;const{peerId:t,baseURI:e,overrides:r,meetingId:i,organizationId:a,logger:o}=s.getAllValues(),c=QC(i),d={entity:lu.PEER,clientId:a,isAnonUser:!a,sdkVersion:s.getValue("sdkVersion"),presetName:s.getValue("presetName"),meetingHash:c,roomName:i,...fe.getDeviceInfo(),isReactNative:navigator.isReactNative};try{const h=(l=r==null?void 0:r.whitelabelled_flags_endpoint)==null||l?Yi({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";await s.getValue("flagsmith").identify(`${lu.PEER}_${t}`,JSON.parse(JSON.stringify(d)),!1,5e3,h,o),o.info("flagsmith::allFlags",{flags:JSON.stringify(s.getValue("flagsmith").getAllFlags())},!0)}catch(h){o.error("Failed to fetch flagsmith flags")}}static async setupControllers(s,t,e,r,i,a,o){var O,b,Ne;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),h=t.getValue("logger"),{viewType:p,mediaConstraints:{audio:f}}=a;t.setValue("viewType",p),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(O=f.enableHighBitrate)!=null?O:!1,enableStereo:(b=f.enableStereo)!=null?b:!1}},...l}),t.setValue("maxPreferredStreams",fe.isMobile()?a.maxVideoStreams.mobile:a.maxVideoStreams.desktop);let T,E,w,C,_,N,U,D,$;const G=new OD(t,s),ee=new oO(s);t.setValue("connectedMeetingsSocketHandler",ee);const Qe=new Vl(t,s),is=new Tr(t,s),ei=new $D(s),ns=new mT(t,s),A=new FD(t,s),S=new DD(s),P=await Zr.init(t,ns,d,o,a);t.setValue("selfController",P);const x=await ff.init(t,P.self,ns,G,i);if(c.participant&&(D=new Sr(t,P.self,ns)),(Ne=c.e2ee)!=null&&Ne.enabled&&c.e2ee.manager.init(h,t.getValue("peerSessionStore")),c.chat&&(E=await ts.init(t,is,P.self,D.participants)),c.internals&&(_=await yh.init(t)),c.livestream&&a.viewType===lr.Livestream&&t.getValue("flagsmith").hasFeature(Y.LIVESTREAM)&&(U=new wf(t,P.self,S)),c.poll&&(T=await hf.init(t,P.self,Qe)),c.recording&&(N=new yf(t,P.self,ns)),c.stage&&(w=new Tf(t,ei,ns,P.self,D.participants)),c.plugin){if(!D)throw new k("The plugin module cannot be initialized without the `participant` module","0102");const xs=await r;C=await Mc.init(t,xs,A,is,E==null?void 0:E.chat,P.self,D.participants,i)}if(c.connectedMeetings&&($=await Ul.init(t)),c.pip){const xs=await uu._init(t,P.self);t.setValue("pip",xs)}const be={storesManager:new W0(t,A),pollController:T,selfController:P,metaController:x,chatController:E,stageController:w,pluginController:C,recordingController:N,internalsController:_,livestreamController:U,participantController:D,connectedMeetingsController:$};return{theme:a,permissions:o,controllers:be}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return hT(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=["PING"];return new Vc(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Lc=mn;$l([y.trace("Controller.init")],Lc,"init",1);$l([y.trace("setupFlagsmith")],Lc,"setupFlagsmith",1);$l([y.trace("Controller.createRoomNodeClient")],Lc,"createRoomNodeClient",1);$l([y.trace("Controller.createSocketService")],Lc,"createSocketService",1);class mO{constructor(){u(this,"battery");u(this,"logger");u(this,"init",async t=>{this.logger=t;try{"getBattery"in navigator&&(this.battery=await navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){t.error("Error getting battery",e)}});u(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});u(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});u(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 ag=new mO;function fO(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=ci.baseURI.prod;t&&(a=t);const o=`https://${Yi({servicePrefix:"api",baseURI:a})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:a,apiBase:o}}catch(e){throw new k("Invalid auth token","0004")}}var jr,Wi,Ji,Cc,fl,DT;class TO{constructor(){g(this,fl);g(this,jr,new Audio);g(this,Wi,new MediaStream);g(this,Ji,new Map);g(this,Cc,void 0);n(this,jr).srcObject=n(this,Wi),n(this,jr).autoplay=!0}async playTracks(t){return t.forEach(e=>{n(this,Ji).has(e.id)||(n(this,Wi).addTrack(e),n(this,Ji).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&n(this,jr).setSinkId(t)}removeTrack(t){const e=n(this,Ji).get(t);e&&(n(this,Wi).removeTrack(e),n(this,Ji).delete(t))}async play(){return n(this,jr).srcObject=n(this,Wi),n(this,jr).play().catch(t=>{V(this,fl,DT).call(this,t)})}onError(t){m(this,Cc,t)}}jr=new WeakMap,Wi=new WeakMap,Ji=new WeakMap,Cc=new WeakMap,fl=new WeakSet,DT=function(t){var e;(e=n(this,Cc))==null||e.call(this,t)};var Ki;class vO extends TO{constructor(){super();g(this,Ki,void 0);m(this,Ki,new Map)}addParticipantTrack(e,r){n(this,Ki).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=n(this,Ki).get(e);r&&this.removeTrack(r),n(this,Ki).delete(e)}}Ki=new WeakMap;var SO=Object.defineProperty,yO=Object.getOwnPropertyDescriptor,Fl=(s,t,e,r)=>{for(var i=r>1?void 0:r?yO(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&&SO(t,e,i),i},Be,zi,Rg;let zr=(Rg=class{constructor(t,e){g(this,Be,void 0);g(this,zi,void 0);m(this,zi,t),m(this,Be,e)}get peerId(){return n(this,zi).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:ur.v4(),a=cr.createContext(i,{peerId:i}),o=a.getValue("logger");o.init(a);const c=new Of(a,o);return await c.init(t,e,a),a.setValue("defaults",{mediaHandler:c}),c}static async init(t){var T,E,w,C,_,N,U;fe.init();const{mediaHandler:e}=(T=t.defaults)!=null?T:{},r=(e==null?void 0:e.peerId)||((w=(E=t==null?void 0:t.cachedUserDetails)==null?void 0:E.peerId)!=null?w:ur.v4()),{authToken:i,baseURI:a}=t,{meetingId:o,...c}=fO(i,a);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const d=zr.setupContext(r,t,o,c),l=d.getValue("telemetry"),h=d.getValue("logger");FT(h),ag.init(h),l.init(d,{roomName:o,userId:c.participantId,organizationId:c.orgId,peerId:r},(_=(C=t.modules)==null?void 0:C.tracing)!=null?_:!0),h.init(d),h.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(N=t.authToken)==null?void 0:N.slice(0,10)}...
13
- ${(U=t.authToken)==null?void 0:U.slice(-10)}`}});const p=await Lc.init(d),f=new zr(d,p);return d.setValue("meeting",f),f}static setupContext(t,e,r,i){var d,l;const a=cr.createContext(t,e),o={...BC,...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",HC({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",ys(e.cachedUserDetails)),a.setValue("sdkVersion","1.2.4"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new vO),a}async join(){const{selfController:t}=n(this,Be);return t.self.roomJoined?null:t.joinRoom()}async leave(t){ag.cleanup(),n(this,zi).getValue("peerSessionStore").reset();const{selfController:e}=n(this,Be);return e.leaveRoom(t)}get participants(){var t;return(t=n(this,Be).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,Be).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,Be).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,Be).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,Be).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,Be).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,Be).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,Be).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,Be).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,Be).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,Be).stageController)==null?void 0:t.stage}get stores(){return n(this,Be).storesManager}get audio(){return n(this,zi).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,Be).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Be=new WeakMap,zi=new WeakMap,Rg);Fl([at("0002"),vr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],zr.prototype,"join",1);Fl([at("0003")],zr.prototype,"leave",1);Fl([at("0001"),vr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],zr,"init",1);zr=Fl([at("0000")],zr);const OT=zr;module.exports=OT;
13
+ ${(U=t.authToken)==null?void 0:U.slice(-10)}`}});const p=await Lc.init(d),f=new zr(d,p);return d.setValue("meeting",f),f}static setupContext(t,e,r,i){var d,l;const a=cr.createContext(t,e),o={...BC,...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",HC({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",ys(e.cachedUserDetails)),a.setValue("sdkVersion","1.2.5-staging.1"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new vO),a}async join(){const{selfController:t}=n(this,Be);return t.self.roomJoined?null:t.joinRoom()}async leave(t){ag.cleanup(),n(this,zi).getValue("peerSessionStore").reset();const{selfController:e}=n(this,Be);return e.leaveRoom(t)}get participants(){var t;return(t=n(this,Be).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,Be).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,Be).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,Be).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,Be).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,Be).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,Be).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,Be).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,Be).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,Be).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,Be).stageController)==null?void 0:t.stage}get stores(){return n(this,Be).storesManager}get audio(){return n(this,zi).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,Be).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Be=new WeakMap,zi=new WeakMap,Rg);Fl([at("0002"),vr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],zr.prototype,"join",1);Fl([at("0003")],zr.prototype,"leave",1);Fl([at("0001"),vr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],zr,"init",1);zr=Fl([at("0000")],zr);const OT=zr;module.exports=OT;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/realtimekit",
3
- "version": "1.2.4",
3
+ "version": "1.2.5-staging.1",
4
4
  "description": "A real-time video and audio SDK for building custom, collaborative communication experiences.",
5
5
  "main": "./dist/index.cjs.js",
6
6
  "module": "./dist/index.es.js",
@@ -86,8 +86,7 @@
86
86
  "worker-timers": "7.0.60"
87
87
  },
88
88
  "publishConfig": {
89
- "access": "public",
90
- "tag": "latest"
89
+ "tag": "staging"
91
90
  },
92
91
  "devDependencies": {
93
92
  "@types/events": "^3.0.0",