@cloudflare/realtimekit 1.2.3-staging.3 → 1.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.js +1 -1
- package/dist/dependencies.txt +1 -1
- package/dist/index.cjs.js +1 -1
- package/dist/index.es.js +1 -1
- package/dist/index.rn.js +1 -1
- package/package.json +3 -2
package/dist/browser.js
CHANGED
|
@@ -20,4 +20,4 @@ slogScale: ${i}, isVoice: ${r}, minEnergy: ${a(this,Mr)},
|
|
|
20
20
|
maxEnergy: ${a(this,hi)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,Mr)||i<a(this,Mr))&&f(this,Mr,i),(!a(this,hi)||i>a(this,hi))&&f(this,hi,i),{energy:(i-a(this,Mr))/(a(this,hi)-a(this,Mr))*10||0,isVoice:r})},Mc=new WeakSet,Rp=function(t){return t<5},cu=new WeakSet,HS=function(t=a(this,yn)){var r;if(!a(this,xs)||!t){a(this,Or).getValue("flagsmith").hasFeature(X.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,xs)}`);return}const e={producerId:a(this,xs),energy:Math.round(t),silent:U(r=Oc,Mc,Rp).call(r,t)};f(this,to,e.silent),this.reportRequest(e)},du=new WeakSet,qS=function(t){const e=Math.log10(t);return Math.round(e)},m(Oo,Mc),m(Oo,du);const q1=(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),v=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(v)}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}},j1=(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 G1=Object.defineProperty,W1=Object.getOwnPropertyDescriptor,ce=(s,t,e,r)=>{for(var i=r>1?void 0:r?W1(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&&G1(t,e,i),i};const Yt=["video/VP9","video/VP8"],bv=(up=class{constructor(s,t){m(this,pi);m(this,lu);m(this,uu);m(this,hu);m(this,xc);m(this,gu);m(this,mu);m(this,fu);m(this,ot);m(this,Cn);m(this,vu);m(this,Su);m(this,Tu);p(this,"context");p(this,"authToken");p(this,"e2ee");m(this,Dc,void 0);m(this,Nc,void 0);m(this,Et,void 0);m(this,j,void 0);m(this,so,void 0);m(this,Mt,void 0);m(this,En,void 0);m(this,bn,void 0);m(this,wn,void 0);m(this,Vc,void 0);m(this,Ss,null);m(this,Nr,void 0);m(this,Lc,void 0);m(this,_n,void 0);m(this,Pn,void 0);m(this,Ot,void 0);m(this,Ht,void 0);var r,i;this.context=s;const{socket:e}=t;this.mediaJoined=!1,f(this,_n,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,Pn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,Et,e),f(this,En,!1),f(this,j,new F1(s,e)),f(this,Mt,a(this,j).events),f(this,Nr,new Set),f(this,Ot,new Map),f(this,bn,!1),f(this,wn,new Wh(s.getValue("logger"))),f(this,Ht,new Oo(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,Vc,Zu(async()=>{if(!a(this,pi,no).mediaJoinAttempted)return;const{roomJoined:n}=await this.joinRoom(a(this,Nc),a(this,Dc),!0,!0);n&&(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 a(this,pi,no).mediaJoined}set mediaJoined(s){a(this,pi,no).mediaJoined=s}reset(){a(this,j).closeAllProducers(),a(this,j).closeAllConsumers(),a(this,Ot).clear(),a(this,Nr).clear(),f(this,Ss,null),a(this,wn).stop(),a(this,j).stopAllTransports(),a(this,j).reset(),f(this,wn,new Wh)}async joinRoom(s,t,e=!1,r=!1,i={}){a(this,pi,no).mediaJoinAttempted=!0,f(this,En,!0),e&&this.reset();try{return await a(this,wn).push(()=>U(this,lu,jS).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(R.ROOM_NODE_FAILED),{roomJoined:!1}}}async initializeConnection(s,t,e=!1,r={}){return a(this,Ss)?a(this,Ss):(f(this,Ss,(async()=>{try{await U(this,xc,kp).call(this,s,t,e,r)}catch(i){throw f(this,Ss,null),i}})()),a(this,Ss))}getConsumers(){return a(this,j).consumers}getProducers(){return a(this,j).producers}async leaveRoom(){a(this,j).stopAllTransports(),f(this,bn,!1),a(this,pi,no).mediaJoinAttempted=!1;const s={closeRoom:!1};a(this,Et).sendMessagePromise(a(this,Mt).leaveRoom,DR.toBinary(s)).then(e=>{var r;(r=Ek.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"?fe.WEBCAM:fe.WEBCAM_BACKUP,r=U(this,ot,Nt).call(this,e);if(r){const v=await r;if(a(this,j).producers.has(v)){const E=a(this,j).producers.get(v);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(Yt.filter(v=>v!==t)),n=U(this,Tu,ZS).call(this,s,i),o=Fn(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=_D(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,Ot).delete(e)},u=a(this,j).createProducer(n,l);return U(this,Cn,dd).call(this,e,u.then(v=>v.id)),u.then(v=>v.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=Yt.filter(i=>{var n,o;return((o=(n=a(this,so).sender)==null?void 0:n.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===i))>=0&&a(this,Pn).get(i).size>0});return e.length===0&&e.push(Yt[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:Te.isElectron()},stopTracks:!1},i=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Ot).delete(fe.SCREENSHARE_VIDEO),a(this,Ot).delete(fe.SCREENSHARE_AUDIO)},n=a(this,j).createProducer(r,i);U(this,Cn,dd).call(this,fe.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:Te.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},d=()=>{};o=a(this,j).createProducer(c,d),U(this,Cn,dd).call(this,fe.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 Ut("track undefined");const t=U(this,ot,Nt).call(this,fe.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,Ht)&&(a(this,Ht).audioTrack=s,a(this,Ht).producerId=n,a(this,Ht).start());return}await a(this,j).closeProducer(n,{stopTrack:!1})}await this.shareMic(s);return}const e=U(this,Su,XS).call(this,s),r=()=>{a(this,Ot).delete(fe.MIC)},i=a(this,j).createProducer(e,r);U(this,Cn,dd).call(this,fe.MIC,i.then(n=>n.id)),await i.then(n=>{a(this,Ht)&&(a(this,Ht).audioTrack=n.track,a(this,Ht).producerId=n.id,a(this,Ht).start())})}catch(t){throw new C(t)}}async pauseMic(){var r;const s=await U(this,ot,Nt).call(this,fe.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,Ht))==null||r.stop();const e={producerId:t.id,pause:!0};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(e))}async pauseWebcam(){const s=await U(this,ot,Nt).call(this,fe.WEBCAM),t=await U(this,ot,Nt).call(this,fe.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,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(o))};e&&(e.pause(),i(e)),r&&(r.pause(),i(r))}async resumeMic(){const s=await U(this,ot,Nt).call(this,fe.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(R.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(e))}async resumeWebcam(s=fe.WEBCAM){const t=await U(this,ot,Nt).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(R.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(r))}async disableWebcam(s){const t=s==="video/VP9"?fe.WEBCAM:fe.WEBCAM_BACKUP,e=await U(this,ot,Nt).call(this,t);U(this,vu,QS).call(this,t),e&&await a(this,j).closeProducer(e)}async disableMic(){var t;const s=await U(this,ot,Nt).call(this,fe.MIC);s&&await a(this,j).closeProducer(s),(t=a(this,Ht))==null||t.stop(),a(this,Ot).delete(fe.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=await U(this,ot,Nt).call(this,fe.SCREENSHARE_VIDEO),t=await U(this,ot,Nt).call(this,fe.SCREENSHARE_AUDIO);s&&await a(this,j).closeProducer(s),t&&await a(this,j).closeProducer(t),a(this,Nr).clear(),a(this,Ot).delete(fe.SCREENSHARE_VIDEO),a(this,Ot).delete(fe.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(s,t){if(s){const e=await U(this,ot,Nt).call(this,fe.WEBCAM),r=await U(this,ot,Nt).call(this,fe.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 U(this,ot,Nt).call(this,fe.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,Et).sendMessagePromise(a(this,Mt).globalPinPeer,JR.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,Nr).add(s.consumerPeerId),a(this,Nr).size}async switchConsumersToLayer(s,t){const e=s.map(r=>this.getConsumers().get(r));a(this,j).switchConsumersToLayer(e,t)}async handleSocketEvents(){a(this,Et).on(a(this,Mt).peerProducerCreateBroadcast,({payload:s})=>{var t,e;if(this.mediaJoined)try{const{participantId:r,producerState:i}=Qk.fromBinary(s);if(r===this.peerId)return;if(i!=null&&i.mimeType||(i.mimeType=i.kind===Ws.AUDIO?"audio/opus":"video/VP8"),i.kind===Ws.VIDEO&&!i.screenShare&&((e=(t=a(this,so).receiver)==null?void 0:t.video)==null?void 0:e.codecs.findIndex(n=>n.mimeType===Yt[0]))>=0&&a(this,_n).get(Yt[0]).has(r)&&i.mimeType!==Yt[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===Ws.AUDIO?"audio":"video",producingPeerId:r}})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),a(this,Et).on(a(this,Mt).peerProducerToggleBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,initiatorParticipantId:e,producerState:{kind:r,pause:i,producerId:n,screenShare:o}}=lf.fromBinary(s);if(o)return;const c=r===Ws.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${t}, producerId: ${n}, kind:${c}, paused:${i} payload: ${JSON.stringify(lf.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: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(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})}}),a(this,Et).on(a(this,Mt).peerLeaveBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t}=hh.fromBinary(s);if(t===this.peerId)return;this.logger.info(`peer left broadcast:${t}`),a(this,Nr).delete(t),a(this,j).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})}}),a(this,Et).on(a(this,Mt).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=eI.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=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(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})}}),a(this,Et).on(a(this,Mt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,En)&&!a(this,bn)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(R.ROOM_NODE_DISCONNECTED),a(this,Vc).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(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(a(this,j).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,n;for(let o=0;o<=Yt.length;o+=1){const c=Yt[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===Yt.length-1){a(this,Pn).get(c).add(s);break}}for(let o=0;o<=Yt.length;o+=1){const c=Yt[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===Yt.length-1){a(this,_n).get(c).add(s);break}}}handlePeerLeaving(s){this.context.getValue("flagsmith").hasFeature(X.FORCE_VIDEO_CODEC)||(a(this,_n).forEach(t=>t.delete(s)),a(this,Pn).forEach((t,e)=>{t.delete(s),!(t.size!==0||e===Yt[0])&&this.disableWebcam(e)}))}},Dc=new WeakMap,Nc=new WeakMap,Et=new WeakMap,j=new WeakMap,so=new WeakMap,Mt=new WeakMap,En=new WeakMap,bn=new WeakMap,wn=new WeakMap,Vc=new WeakMap,Ss=new WeakMap,Nr=new WeakMap,Lc=new WeakMap,_n=new WeakMap,Pn=new WeakMap,Ot=new WeakMap,Ht=new WeakMap,pi=new WeakSet,no=function(){return this.context.getValue("connectionHandler")},lu=new WeakSet,jS=async function(s,t,e,r){f(this,Nc,s);try{return a(this,Ss)?await a(this,Ss):await U(this,xc,kp).call(this,s,t,e,r),U(this,hu,WS).call(this,t),{roomJoined:await U(this,uu,GS).call(this)}}catch(i){return this.logger.error("Failed to complete room join",{error:i}),{roomJoined:!1}}finally{f(this,Ss,null)}},uu=new WeakSet,GS=async function(){try{this.mediaJoined=!0;const{roomState:s}=await a(this,j).socketHandler.notifySelfJoinComplete();return f(this,Dc,s.roomUuid),f(this,bn,!0),f(this,En,!1),!0}catch(s){return this.logger.error("Error completing room join",{error:s}),this.mediaJoined=!1,!1}},hu=new WeakSet,WS=function(s){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:{...Te.getDeviceInfo(),userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency},sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};this.context.getValue("callstats").roomJoined(e)}catch(t){this.logger.error("Error reporting room joined analytics",{error:t})}},0)},xc=new WeakSet,kp=async function(s,t,e,r){var i,n;try{(n=a(this,Lc))!=null||f(this,Lc,U(i=bv,pu,JS).call(i));const o=U(this,gu,KS).call(this);await U(this,mu,zS).call(this,s,t,e,o),await a(this,j).setupTransports({send:!0,recv:!0}),await U(this,fu,YS).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},pu=new WeakSet,JS=function(){const{ipInfo:s}=pt();if(!(s!=null&&s.loc))return;const[t,e]=s.loc.split(",").map(parseFloat);return{latitude:t,longitude:e}},gu=new WeakSet,KS=function(){var e;const s=(e=this.context.getValue("flagsmith").getValue(X.FORCE_VIDEO_CODEC))==null?void 0:e.toString(),t=y1(s);return f(this,so,t),t},mu=new WeakSet,zS=async function(s,t,e,r){await mv(async(i,n)=>{if(!a(this,Et).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,Lc))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}},{delayTime:1e3,strategy:"exponential",maxRetryCount:1/0})},fu=new WeakSet,YS=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(j1(!1))),s.canProduceAudio===H.Allowed){const r=q1(!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})}},ot=new WeakSet,Nt=function(s){return a(this,Ot).get(s)},Cn=new WeakSet,dd=function(s,t){return a(this,Ot).set(s,t)},vu=new WeakSet,QS=function(s){return a(this,Ot).delete(s)},Su=new WeakSet,XS=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},Tu=new WeakSet,ZS=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(up,pu),up);let re=bv;ce([y.trace("MediaNodeClient.reset",{country:y.location.country})],re.prototype,"reset",1),ce([y.trace("MediaNodeClient.joinRoom")],re.prototype,"joinRoom",1),ce([y.trace("MediaNodeClient.leaveRoom")],re.prototype,"leaveRoom",1),ce([y.trace("MediaNodeClient.activatePeers")],re.prototype,"activatePeers",1),ce([y.trace("MediaNodeClient.createConsumers")],re.prototype,"createConsumers",1),ce([y.trace("MediaNodeClient.closeConsumers")],re.prototype,"closeConsumers",1),ce([y.trace("MediaNodeClient._shareWebcam")],re.prototype,"_shareWebcam",1),ce([y.trace("MediaNodeClient.shareWebcam")],re.prototype,"shareWebcam",1),ce([y.trace("MediaNodeClient.shareScreen")],re.prototype,"shareScreen",1),ce([y.trace("MediaNodeClient.shareMic")],re.prototype,"shareMic",1),ce([y.trace("MediaNodeClient.pauseMic")],re.prototype,"pauseMic",1),ce([y.trace("MediaNodeClient.pauseWebcam")],re.prototype,"pauseWebcam",1),ce([y.trace("MediaNodeClient.resumeMic")],re.prototype,"resumeMic",1),ce([y.trace("MediaNodeClient.resumeWebcam")],re.prototype,"resumeWebcam",1),ce([y.trace("MediaNodeClient.disableWebcam")],re.prototype,"disableWebcam",1),ce([y.trace("MediaNodeClient.disableMic")],re.prototype,"disableMic",1),ce([y.trace("MediaNodeClient.disableScreenShare")],re.prototype,"disableScreenShare",1),ce([y.trace("MediaNodeClient.muteSelf")],re.prototype,"muteSelf",1),ce([y.trace("MediaNodeClient.resetVideoProducers")],re.prototype,"resetVideoProducers",1),ce([y.trace("MediaNodeClient.changeDisplayName")],re.prototype,"changeDisplayName",1),ce([y.trace("MediaNodeClient.kickPeer")],re.prototype,"kick",1),ce([y.trace("MediaNodeClient.kickAllPeers")],re.prototype,"kickAll",1),ce([y.trace("MediaNodeClient.muteAll")],re.prototype,"muteAll",1),ce([y.trace("MediaNodeClient.muteAllVideo")],re.prototype,"muteAllVideo",1),ce([y.trace("MediaNodeClient.disableAudio")],re.prototype,"disableAudio",1),ce([y.trace("MediaNodeClient.disableVideo")],re.prototype,"disableVideo",1),ce([y.trace("MediaNodeClient.pinPeer")],re.prototype,"pinPeer",1),ce([y.trace("MediaNodeClient.validateScreenShare")],re.prototype,"validateScreenShare",1);function wv(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 _v(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 J1=Object.defineProperty,K1=Object.getOwnPropertyDescriptor,$i=(s,t,e,r)=>{for(var i=r>1?void 0:r?K1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&J1(t,e,i),i};const Pv=(pS=class{constructor(s,t,e,r){m(this,Dt);p(this,"self");p(this,"authToken");m(this,Rn,void 0);p(this,"viewType");m(this,Us,void 0);m(this,ee,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,ee,s),this.viewType=r,this.authToken=n,f(this,Rn,i),f(this,Us,e),t.config.viewType!==Vt.Chat&&this.setupEvents()}get peerId(){return a(this,ee).getValue("peerId")}get telemetry(){return a(this,ee).getValue("telemetry")}get logger(){return a(this,ee).getValue("logger")}get mediaJoined(){return a(this,ee).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=pt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await tt.__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:Te.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:Mm(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 Pv(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,Dt,is).shareMic(s),this.self.audioEnabled||a(this,Dt,is).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===H.Allowed&&i)try{const d=await a(this,Dt,is).shareWebcam(t);d&&d.id!==t.id&&a(this,ee).getValue("flagsmith").hasFeature(X.EXP_RESHARE)&&await a(this,Dt,is).shareWebcam(d),this.self.videoEnabled||a(this,Dt,is).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===H.Allowed&&n)try{await((c=a(this,Dt,is))==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,ee).getValue("callstats").callEnded(),a(this,Dt,is).reset(),s&&await this.joinRoom(s)}setupEvents(){a(this,ee).getValue("peerSessionStore").on(R.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,ee).getValue("peerSessionStore").on(R.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,ee).getValue("peerSessionStore").on(R.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,ee).getValue("peerSessionStore").on(R.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,ee).getValue("peerSessionStore").on(R.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,ee).getValue("peerSessionStore").on(R.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&a(this,ee).getValue("flagsmith").hasFeature(X.REFRESH_ID_ON_DISCONNECTION)&&(t=Si()),a(this,Rn).updateURL(t),a(this,ee).getValue("telemetry").resetPeerId(t),pt().setHeader("tracing-id",t),nr.remapContext(t,a(this,ee)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,ee).getValue("peerSessionStore").on(R.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Us).on(F.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Us).on(Yd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,ee).getValue("peerSessionStore").emit(R.UPDATE_PERMISSIONS,t.patch)})}),a(this,Us).on(F.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Us).on(F.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Us).on(F.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,ee).getValue("peerSessionStore").onAsync(R.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,ee).getValue("peerSessionStore").on(R.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var n;const i=(n=e==null?void 0:e.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),a(this,ee).getValue("peerSessionStore").on(R.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,ee).getValue("callstats").audioOff())}),a(this,ee).getValue("peerSessionStore").on(R.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,ee).getValue("callstats").videoOff())}),a(this,ee).getValue("peerSessionStore").onAsync(R.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,ee).getValue("peerSessionStore").on(R.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await a(this,Us).joinRoom(this.self);a(this,Us).socket.flush();const e=Dh(t.stageType);if(a(this,ee).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}await this.joinMediaRoom(s),a(this,ee).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,ee).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),a(this,ee).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,ee).notify("stageStatus");try{(e=a(this,Rn))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}_v(a(this,ee)),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var n,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,ee).getAllValues();try{if(e===Vt.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}wv(a(this,ee),{socket:a(this,Rn),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u}=(o=await((n=a(this,Dt,is))==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 C("Error: could not join media room","0002")}}async leaveMediaRoom(s){const t=a(this,ee).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===Vt.Webinar)&&a(this,Dt,is)&&(a(this,Dt,is).mediaJoined&&s!=="disconnected"&&await a(this,Dt,is).leaveRoom(),!(s==="stageLeft"&&t===Vt.Livestream)&&(a(this,Dt,is).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()}},Rn=new WeakMap,Us=new WeakMap,ee=new WeakMap,Dt=new WeakSet,is=function(){return a(this,ee).getValue("roomNodeClient")},pS);let jr=Pv;$i([y.trace("SelfController.resetSelf")],jr.prototype,"resetSelf",1),$i([y.trace("SelfController.setupEvents")],jr.prototype,"setupEvents",1),$i([y.trace("SelfController.joinRoom")],jr.prototype,"joinRoom",1),$i([y.trace("SelfController.leaveRoom")],jr.prototype,"leaveRoom",1),$i([y.trace("SelfController.joinMediaRoom")],jr.prototype,"joinMediaRoom",1),$i([y.trace("SelfController.leaveMediaRoom")],jr.prototype,"leaveMediaRoom",1),$i([y.trace("SelfController.init")],jr,"init",1);class z1{constructor(t){m(this,Uc,void 0);f(this,Uc,t)}on(t,e){let r;t===F.roomPeerCount?r=pf.fromBinary.bind(pf):r=Af.fromBinary.bind(Af),a(this,Uc).on(t,({payload:i})=>{if(t===F.roomPeerCount&&!i)return;const n=r(i);e(n)})}}Uc=new WeakMap;class Y1{constructor(t,e){m(this,Fc,void 0);m(this,$c,void 0);f(this,Fc,e),f(this,$c,t)}get logger(){return a(this,$c).getValue("logger")}on(t,e){let r,i;switch(t){case F.transcript:{r=ph.fromBinary.bind(ph),i=ph.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Fc).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)})}}Fc=new WeakMap,$c=new WeakMap;var Q1=Object.defineProperty,X1=Object.getOwnPropertyDescriptor,ep=(s,t,e,r)=>{for(var i=r>1?void 0:r?X1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&Q1(t,e,i),i};class ml{constructor(t,e){m(this,Vr,void 0);m(this,ro,void 0);f(this,Vr,e),f(this,ro,t)}get logger(){return a(this,ro).getValue("logger")}get telemetry(){return a(this,ro).getValue("telemetry")}getPolls(){return a(this,Vr).sendMessagePromise(lr.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Vr).sendMessage(lr.createPoll,HM.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Vr).sendMessage(lr.votePoll,jM.toBinary(r))}on(t,e){let r,i;switch(t){case lr.updatePoll:case lr.createPoll:case lr.votePoll:{r=Ch.fromBinary.bind(Ch),i=Ch.create();break}}a(this,Vr).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,Vr).removeListeners(t)}}Vr=new WeakMap,ro=new WeakMap,ep([y.trace("PollSocketHandler.getPolls")],ml.prototype,"getPolls",1),ep([y.trace("PollSocketHandler.createPoll")],ml.prototype,"createPoll",1),ep([y.trace("PollSocketHandler.votePoll")],ml.prototype,"votePoll",1);var Z1=Object.defineProperty,eN=Object.getOwnPropertyDescriptor,tN=(s,t,e,r)=>{for(var i=r>1?void 0:r?eN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&Z1(t,e,i),i};class Cv{constructor(t,e){p(this,"socket");m(this,ss,void 0);f(this,ss,t),this.socket=e,this.handleSocketEvents(),a(this,ss).setValue("roomSocketHandler",this)}get telemetry(){return a(this,ss).getValue("telemetry")}get logger(){return a(this,ss).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(F.joinRoom,II.toBinary(e));try{const{peer:n}=Bn.fromBinary((await r).payload);a(this,ss).getValue("connectionHandler").socketJoined=!0,a(this,ss).getValue("peerSessionStore").emit(R.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,ss).getValue("peerSessionStore").emit(R.ROOM_STATE,d),a(this,ss).getValue("peerSessionStore").emit(R.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),new C("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,n)}}async getAllAddedParticipants(){try{return pA.fromBinary((await this.socket.sendMessagePromise(F.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(F.getRoomPeersInfo,TI.toBinary(n));i=fh.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(F.getRoomPeersInfo);t=fh.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(F.getRoomPeersInfo);t=fh.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(F.getPeerInfo,ff.toBinary({peerId:t}));e=Bn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=mf.create();try{const e=await this.socket.sendMessagePromise(F.getRoomInfo);t=mf.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=bf.create();try{const e=await this.socket.sendMessagePromise(F.getRoomStageState);t=bf.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(F.broadcastMessage,bo.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(F.broadcastToEntity,bo.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(F.broadcastToEntity,bo.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(F.leaveRoom,MI.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(F.kick,yf.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(F.kickAll,nf.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(F.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(F.acceptWaitingRoomRequests,TA.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(F.denyWaitingRoomRequests,EA.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Yd.updateUserPreset,YA.toBinary(r))}handleSocketEvents(){this.socket.on(F.broadcastMessage,({payload:t})=>{try{const e=bo.fromBinary(t);a(this,ss).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(F.broadcastToEntity,({payload:t})=>{try{const e=bo.fromBinary(t);a(this,ss).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 F.joinRoom:case F.leaveRoom:case F.kick:case F.kickAll:{r=Bn.fromBinary.bind(Bn),i=Bn.create();break}case F.getWaitingRoomRequests:{r=(n,o)=>n?Ef.fromBinary(n,o):{requests:[]},i=Ef.create();break}case F.recordingPaused:case F.recordingStarted:case F.recordingStopped:{r=Nf.fromBinary.bind(Nf);break}case Yd.updateUserPreset:{r=_f.fromBinary.bind(_f);break}case _s.peerJoinedBroadcast:case Br.peerJoinedBroadcast:{r=cf.fromBinary.bind(cf);break}case _s.selfJoinComplete:case Br.selfJoinComplete:{r=uh.fromBinary.bind(uh);break}case _s.globalPeerPinBroadcast:case Br.globalPeerPinBroadcast:{r=uf.fromBinary.bind(uf);break}case _s.selectedPeer:case Br.selectedPeer:{r=lh.fromBinary.bind(lh);break}case _s.selectedPeerDiff:case Br.selectedPeerDiff:{r=of.fromBinary.bind(of);break}case _s.leaveRoom:case Br.leaveRoom:{r=hh.fromBinary.bind(hh);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(Yd.getUserPresets,qA.toBinary(e)),i=JA.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}}}ss=new WeakMap,tN([y.trace("RoomSocketHandler.joinRoom")],Cv.prototype,"joinRoom",1);class sN{constructor(t){m(this,qt,void 0);f(this,qt,t)}async getStageRequests(){const{payload:t}=await a(this,qt).sendMessagePromise(F.getStageRequests);return t?Ph.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,qt).sendMessage(F.requestStageAccess)}cancelRequestAccess(){a(this,qt).sendMessage(F.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,qt).sendMessage(F.grantStageAccess,OM.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,qt).sendMessage(F.denyStageAccess,NM.toBinary(e))}joinStage(){return a(this,qt).sendMessagePromise(F.joinStage,void 0,void 0,F.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,qt).sendMessagePromise(F.leaveStage,Of.toBinary(e),void 0,F.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,qt).sendMessagePromise(F.leaveStage,Of.toBinary(e))}on(t,e){let r;switch(t){case F.grantStageAccess:case F.denyStageAccess:{r=void 0;break}case F.getStagePeers:{r=Mf.fromBinary.bind(Mf);break}case F.getStageRequests:case F.requestStageAccess:case F.cancelStageRequest:{r=Ph.fromBinary.bind(Ph);break}case F.peerStageStatusUpdate:{r=hf.fromBinary.bind(hf);break}}a(this,qt).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,qt).sendMessagePromise(F.getPeerInfo,ff.toBinary({peerId:t}));return Bn.fromBinary(e.payload)}}qt=new WeakMap;class rN{constructor(t,e){m(this,Qe,void 0);m(this,Bc,void 0);f(this,Qe,e),f(this,Bc,t)}get logger(){return a(this,Bc).getValue("logger")}addPlugin(t,e){a(this,Qe).sendMessage(G.addPlugin,z0.toBinary({pluginId:t,staggered:e}))}removePlugin(t){a(this,Qe).sendMessage(G.removePlugin,Q0.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await a(this,Qe).sendMessagePromise(G.getPlugins);return t?yM.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};a(this,Qe).sendMessage(G.customPluginEventToRoom,oM.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const n={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,Qe).sendMessage(G.customPluginEventToPeers,dM.toBinary(n),i)}enablePluginForRoom(t,e){a(this,Qe).sendMessage(G.enablePluginForRoom,Z0.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){a(this,Qe).sendMessage(G.enablePluginForPeers,rM.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){a(this,Qe).sendMessage(G.disablePluginForRoom,tM.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){a(this,Qe).sendMessage(G.disablePluginForPeers,nM.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,Qe).sendMessage(G.storeInsertKeys,Cf.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,Qe).sendMessage(G.storeGetKeys,pM.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,Qe).sendMessage(G.storeDeleteKeys,mM.toBinary(n),i)}storeDelete(t,e,r){a(this,Qe).sendMessage(G.storeDelete,vM.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,Qe).sendMessage(G.storeInsertKeys,Cf.toBinary(i))}on(t,e){let r;switch(t){case G.addPlugin:case G.enablePluginForPeers:case G.enablePluginForRoom:{r=_h.fromBinary.bind(_h);break}case G.removePlugin:case G.disablePluginForPeers:case G.disablePluginForRoom:{r=Rf.fromBinary.bind(Rf);break}case G.customPluginEventToPeers:case G.customPluginEventToRoom:{r=If.fromBinary.bind(If);break}case G.storeInsertKeys:case G.storeGetKeys:case G.storeDeleteKeys:case G.storeDelete:{r=kf.fromBinary.bind(kf);break}}a(this,Qe).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}Qe=new WeakMap,Bc=new WeakMap;var iN=Object.defineProperty,nN=(s,t,e)=>t in s?iN(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,aN=(s,t,e)=>(nN(s,typeof t!="symbol"?t+"":t,e),e),tp=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},O=(s,t,e)=>(tp(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)=>(tp(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),Pe=(s,t,e)=>(tp(s,t,"access private method"),e),fl={},oN={get exports(){return fl},set exports(s){fl=s}},Yn=typeof Reflect=="object"?Reflect:null,Rv=Yn&&typeof Yn.apply=="function"?Yn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},vl;Yn&&typeof Yn.ownKeys=="function"?vl=Yn.ownKeys:Object.getOwnPropertySymbols?vl=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:vl=function(s){return Object.getOwnPropertyNames(s)};function cN(s){console&&console.warn&&console.warn(s)}var kv=Number.isNaN||function(s){return s!==s};function de(){de.init.call(this)}oN.exports=de,fl.once=hN,de.EventEmitter=de,de.prototype._events=void 0,de.prototype._eventsCount=0,de.prototype._maxListeners=void 0;var Iv=10;function Sl(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 Iv},set:function(s){if(typeof s!="number"||s<0||kv(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Iv=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||kv(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 Av(s){return s._maxListeners===void 0?de.defaultMaxListeners:s._maxListeners}de.prototype.getMaxListeners=function(){return Av(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")Rv(c,this,t);else for(var d=c.length,l=Vv(c,d),e=0;e<d;++e)Rv(l[e],this,t);return!0};function Mv(s,t,e,r){var i,n,o;if(Sl(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=Av(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,cN(c)}return s}de.prototype.addListener=function(s,t){return Mv(this,s,t,!1)},de.prototype.on=de.prototype.addListener,de.prototype.prependListener=function(s,t){return Mv(this,s,t,!0)};function dN(){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 Ov(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=dN.bind(r);return i.listener=e,r.wrapFn=i,i}de.prototype.once=function(s,t){return Sl(t),this.on(s,Ov(this,s,t)),this},de.prototype.prependOnceListener=function(s,t){return Sl(t),this.prependListener(s,Ov(this,s,t)),this},de.prototype.removeListener=function(s,t){var e,r,i,n,o;if(Sl(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():lN(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 Dv(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?uN(i):Vv(i,i.length)}de.prototype.listeners=function(s){return Dv(this,s,!0)},de.prototype.rawListeners=function(s){return Dv(this,s,!1)},de.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):Nv.call(s,t)},de.prototype.listenerCount=Nv;function Nv(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?vl(this._events):[]};function Vv(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function lN(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function uN(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function hN(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))}Lv(s,t,n,{once:!0}),t!=="error"&&pN(s,i,{once:!0})})}function pN(s,t,e){typeof s.on=="function"&&Lv(s,"error",t,e)}function Lv(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 gN extends S{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const xv=new gN;class Uv{static encode(t){return xv.toBinary(t)}static decode(t){return xv.fromBinary(new Uint8Array(t))}}function mN(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Gr;class fN{constructor(t={}){aN(this,"opts"),Ee(this,Gr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ie(this,Gr,0)}async wait(){ie(this,Gr,O(this,Gr)+1);const t=mN(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**O(this,Gr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return O(this,Gr)}reset(){ie(this,Gr,0)}}Gr=new WeakMap;const Wr={debug:0,info:1,warn:2,error:3};var Bi,Hi;class vN{constructor(t){Ee(this,Bi,void 0),Ee(this,Hi,void 0),ie(this,Bi,console),ie(this,Hi,t)}debug(...t){Wr[O(this,Hi)]>Wr.debug||O(this,Bi).debug("[Sockrates]:",...t)}info(...t){Wr[O(this,Hi)]>Wr.info||O(this,Bi).info("[Sockrates]:",...t)}warn(...t){Wr[O(this,Hi)]>Wr.warn||O(this,Bi).warn("[Sockrates]:",...t)}error(...t){Wr[O(this,Hi)]>Wr.error||O(this,Bi).error("[Sockrates]:",...t)}}Bi=new WeakMap,Hi=new WeakMap;var Fv=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(Fv||{});const SN="2",TN="3";var Ne,Qn,Ce,Fe,Jr,st,gr,Kr,Is,Xn,mr,sp,$v,Do,Tl,rp,Bv,ip,Hv,yl,np,ap,qv,No,El,Vo,bl,wl,op,Zn,Lo,xo,_l;class yN{constructor(t,e){var g,v,E,b,_,w,L,$,N,B;Ee(this,sp),Ee(this,Do),Ee(this,rp),Ee(this,ip),Ee(this,yl),Ee(this,ap),Ee(this,No),Ee(this,Vo),Ee(this,wl),Ee(this,Zn),Ee(this,xo),Ee(this,Ne,void 0),Ee(this,Qn,void 0),Ee(this,Ce,void 0),Ee(this,Fe,void 0),Ee(this,Jr,void 0),Ee(this,st,void 0),Ee(this,gr,void 0),Ee(this,Kr,void 0),Ee(this,Is,void 0),Ee(this,Xn,void 0),Ee(this,mr,void 0);var r,i,n,o,c,d,l,u,h;ie(this,Qn,t),ie(this,Jr,[]),ie(this,st,new fl),ie(this,gr,!0),ie(this,Is,!1),ie(this,Ce,e!=null?e:{}),(g=(r=O(this,Ce)).autoReconnect)!=null||(r.autoReconnect=!0),(v=(i=O(this,Ce)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(E=(n=O(this,Ce)).pingTimeout)!=null||(n.pingTimeout=3e4),(b=(o=O(this,Ce)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(_=(c=O(this,Ce)).debug)!=null||(c.debug=!0),(w=(d=O(this,Ce)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(L=(l=O(this,Ce)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),($=(u=O(this,Ce)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(N=(h=O(this,Ce)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),ie(this,Kr,{code:void 0,reason:void 0}),ie(this,Fe,(B=O(this,Ce).logger)!=null?B:new vN(O(this,Ce).debug?"debug":"info")),ie(this,mr,new fN)}get readyState(){var t;return(t=O(this,Ne))==null?void 0:t.readyState}get url(){return O(this,Qn)}updateURL(t){ie(this,Qn,t),Pe(this,ap,qv).call(this)}get config(){return O(this,Ce)}get sendQueue(){return O(this,Jr)}flush(){if(!O(this,Ce).queueOnDisconnect)return!1;const t=[];return O(this,Jr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ie(this,Jr,t),O(this,Jr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){O(this,Fe).debug("Websocket was already connecting or connected.");return}if(O(this,gr)!==!1)return new Promise((e,r)=>{Pe(this,Zn,Lo).call(this),Pe(this,xo,_l).call(this);try{ie(this,Ne,new WebSocket(Pe(this,sp,$v).call(this,O(this,Qn)))),O(this,Ne).binaryType="arraybuffer",O(this,Fe).debug("Connecting");const i=setTimeout(()=>{O(this,Fe).debug("Connection timeout. Closing socket"),ie(this,gr,!0),Pe(this,xo,_l).call(this),O(this,Ne).close(3001,"Connection Timeout"),O(this,Ce).autoReconnect&&!O(this,Is)&&(O(this,st).emit("reconnecting"),Pe(this,No,El).call(this)),r(new Error("Connection timed out!"))},O(this,Ce).connectionTimeout);O(this,Ne).onopen=()=>{O(this,Fe).debug(`Ready State: ${Fv[O(this,Ne).readyState]}`),i&&clearTimeout(i),Pe(this,wl,op).call(this),ie(this,Kr,{code:void 0,reason:void 0}),O(this,st).emit("connected"),O(this,Ce).flushOnReconnect&&this.flush(),e()},O(this,Ne).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),O(this,Fe).debug("Socket closed. Close event:",{event:n}),O(this,Fe).debug(`Connection closed code: ${o}`),O(this,Fe).debug(`Connection closed reason: ${c}`),O(this,Is)||Pe(this,yl,np).call(this,o,c)}catch(o){Pe(this,Do,Tl).call(this,o)}},O(this,Ne).onerror=n=>{Pe(this,Do,Tl).call(this,n)},O(this,Ne).onmessage=n=>Pe(this,rp,Bv).call(this,n)}catch(i){Pe(this,Do,Tl).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(O(this,Ce).queueOnDisconnect&&(!O(this,Ne)||O(this,Ne).readyState!==1))return O(this,Fe).debug("Queuing message since socket is not connected!",n),O(this,Jr).push(n),!1;const o=Uv.encode(n);return Pe(this,Vo,bl).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return Pe(this,Vo,bl).call(this,t)}receive(t,e){return O(this,st).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,st).on(t,e);return}this.receive(t,e)}removeAllListeners(){O(this,st).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){O(this,st).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){O(this,st).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ie(this,gr,!1),Pe(this,Zn,Lo).call(this),this.removeAllListeners(),ie(this,Kr,{code:1e3,reason:"Sockrates disconnect method called"}),O(this,Ne).close(1e3,"Sockrates disconnect method called.")}}Ne=new WeakMap,Qn=new WeakMap,Ce=new WeakMap,Fe=new WeakMap,Jr=new WeakMap,st=new WeakMap,gr=new WeakMap,Kr=new WeakMap,Is=new WeakMap,Xn=new WeakMap,mr=new WeakMap,sp=new WeakSet,$v=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)://.")},Do=new WeakSet,Tl=function(s,t){O(this,Fe).error("Error:",{error:s}),O(this,st).emit("errored",{error:s}),t==null||t(s)},rp=new WeakSet,Bv=function(s){if(Pe(this,wl,op).call(this),s.data===SN){O(this,Fe).debug("Received ping from server"),Pe(this,Vo,bl).call(this,TN);return}const t=Uv.decode(s.data),{id:e,payload:r}=t;O(this,Fe).debug("Received message",{event:t.event,messageID:e}),O(this,st).emit(t.event.toString(),{id:e,payload:r})},ip=new WeakSet,Hv=function(){return O(this,Ne).readyState===1},yl=new WeakSet,np=function(s,t){ie(this,Kr,{reason:t,code:s}),O(this,st).emit("disconnected",{code:s,reason:t})},ap=new WeakSet,qv=function(){const{reason:s,code:t}=O(this,Kr);t&&t!==1e3&&O(this,gr)&&O(this,Ce).autoReconnect&&!O(this,Is)&&(O(this,Fe).debug(`Triggering reconnection due to ${s}.`),O(this,st).emit("reconnecting"),Pe(this,No,El).call(this))},No=new WeakSet,El=async function(s=!0){if(s&&O(this,Is)){O(this,Fe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(O(this,Is)||O(this,mr).reset(),O(this,Ce).maxReconnectionAttempts!==null&&O(this,mr).getAttempts()>=O(this,Ce).maxReconnectionAttempts){O(this,st).emit("failed"),ie(this,Is,!1);return}ie(this,Is,!0),Pe(this,xo,_l).call(this),Pe(this,Zn,Lo).call(this);try{if(await O(this,mr).wait(),O(this,gr)===!1)return;if(O(this,Fe).debug(`Reconnection attempt ${O(this,mr).getAttempts()}`),O(this,st).emit("reconnectAttempt",{attempt:O(this,mr).getAttempts()}),await this.connect(),!Pe(this,ip,Hv).call(this))throw Error("Reconnect Failed");ie(this,Is,!1),ie(this,Kr,{code:void 0,reason:void 0}),O(this,st).emit("reconnected")}catch(t){O(this,Fe).debug("Failed to reconnect."),O(this,st).emit("reconnectFailure",{attempt:O(this,mr).getAttempts()}),Pe(this,No,El).call(this,!1)}},Vo=new WeakSet,bl=function(s){try{return O(this,Ne).send(s),!0}catch(t){return O(this,Fe).error(t.message),!1}},wl=new WeakSet,op=function(){this.config.disconnectOnPingTimeout&&(O(this,Fe).debug("Resetting ping timeout"),Pe(this,Zn,Lo).call(this),ie(this,Xn,setTimeout(()=>{var s;O(this,Fe).debug("Disconnecting the socket due to ping timeout"),ie(this,gr,!0);const t=3002,e="Ping timeout";(s=O(this,Ne))==null||s.close(t,e),Pe(this,yl,np).call(this,t,e)},O(this,Ce).pingTimeout)))},Zn=new WeakSet,Lo=function(){O(this,Xn)&&(clearTimeout(O(this,Xn)),ie(this,Xn,void 0))},xo=new WeakSet,_l=function(){O(this,Ne)&&(O(this,Ne).onopen=void 0,O(this,Ne).onerror=void 0,O(this,Ne).onmessage=void 0,O(this,Ne).onclose=void 0)};var EN=Object.defineProperty,bN=Object.getOwnPropertyDescriptor,Pl=(s,t,e,r)=>{for(var i=r>1?void 0:r?bN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&EN(t,e,i),i};const jv=65535,wN=3e3,Gv=(gS=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,Oe);m(this,Hc);m(this,qc);m(this,gi,void 0);m(this,Me,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");m(this,Ts,void 0);m(this,ct,void 0);var n;if(!t||!e||!r)throw new C("peerId, meetingId, or authToken can not be empty","0404");f(this,Ts,void 0),f(this,ct,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,gi,U(this,Hc,Ip).call(this,t)),f(this,Me,new yN(a(this,gi),{autoReconnect:!0,disconnectOnPingTimeout:(n=i.includes("PING"))!=null?n:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Oe,je).socketJoinAttempted}set joinAttempted(s){a(this,Oe,je).socketJoinAttempted=s}get telemetry(){return a(this,ct).getValue("telemetry")}get logger(){return a(this,ct).getValue("logger")}get peerId(){return a(this,ct).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,gi,U(this,Hc,Ip).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Me).updateURL(a(this,gi))}static getSocketEdgeDomain(s){return _i({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,gi)}async connect(){a(this,Oe,je).socketJoinAttempted=!0,await a(this,Me).connect(),a(this,Oe,je).socketJoinAttempted=!0,a(this,Oe,je).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){a(this,Oe,je).socketJoinAttempted=!1,a(this,Me).disconnect(),a(this,Oe,je).socketJoinAttempted=!0,a(this,Oe,je).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Me).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,ct).getValue("telemetry").injectContext(r),a(this,Me).send(s,e!=null?e:U(this,qc,Ap).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=(E,b)=>{a(this,Me).removeListener(n,E),a(this,Me).removeListener(jv,b),a(this,Me).removeListener(Br.errorResponse,b),a(this,Me).removeListener(_s.errorResponse,b)},l=r!=null?r:U(this,qc,Ap).call(this),u={};a(this,ct).getValue("telemetry").injectContext(u);const g=({id:E,payload:b})=>{if(l===E){let _;try{const w=uk.fromBinary(b);_=new Error(w.errorMessage)}catch(w){_=new Error("failed to parse error message",{cause:w});try{const L=hI.fromBinary(b);_=new Error(L.message)}catch(L){_=new Error("failed to parse error message",{cause:L})}}c(_),d(v,g)}},v=({id:E,payload:b})=>{l===E&&(o({id:E,payload:b}),d(v,g))};a(this,Me).on(n,v),a(this,Me).on(jv,g),a(this,Me).on(Br.errorResponse,g),a(this,Me).on(_s.errorResponse,g),setTimeout(()=>{d(v,g),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Me).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){a(this,Me).on(s,t)}onStateEvent(s,t){a(this,Me).on(s,t)}removeListener(s,t){a(this,Me).removeListener(s,t)}removeListeners(s){a(this,Me).removeListeners(s)}flush(){return a(this,Me).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),a(this,Ts)&&(clearTimeout(a(this,Ts)),f(this,Ts,void 0)),a(this,Oe,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:y.location.country});const{recv:e,send:r}=(i=a(this,Oe,je).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==zn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==zn.CONNECTED?a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Oe,je).joinAttempted}):f(this,Ts,setTimeout(()=>{a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Oe,je).joinAttempted}),f(this,Ts,void 0)},wN)),a(this,Oe,je).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge",{country:y.location.country}),a(this,Oe,je).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,Oe,je).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,Oe,je).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Oe,je).mediaJoinAttempted}}),a(this,Ts)&&(clearTimeout(a(this,Ts)),f(this,Ts,void 0)),a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Oe,je).mediaJoinAttempted}),a(this,Oe,je).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge",{country:y.location.country}),a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_FAILED),a(this,Oe,je).updateSocketConnectionState("failed")})}},gi=new WeakMap,Me=new WeakMap,Oe=new WeakSet,je=function(){return a(this,ct).getValue("connectionHandler")},Ts=new WeakMap,ct=new WeakMap,Hc=new WeakSet,Ip=function(s){let t=Gv.getSocketEdgeDomain(a(this,ct).getValue("baseURI"));typeof Fn(a(this,ct),"socket_server_base")=="string"&&(t=Fn(a(this,ct),"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=>Gd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(n).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},qc=new WeakSet,Ap=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},gS);let Uo=Gv;Pl([y.trace("SocketService.connect")],Uo.prototype,"connect",1),Pl([y.trace("SocketService.disconnect")],Uo.prototype,"disconnect",1),Pl([y.trace("SocketService.sendMessagePromise")],Uo.prototype,"sendMessagePromise",1),Pl([y.trace("SocketService.sendMessagePromiseWithTimeout")],Uo.prototype,"sendMessagePromiseWithTimeout",1);class _N{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=FI.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=uA.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=Tf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return Sf.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return tA.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(F.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(F.createConnectedRooms,qI.toBinary({payloads:t}));return Sf.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(F.deleteConnectedRooms,ZI.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(F.movePeers,oA.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 PN=Object.defineProperty,CN=Object.getOwnPropertyDescriptor,RN=(s,t,e,r)=>{for(var i=r>1?void 0:r?CN(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&&PN(t,e,i),i};class Wv extends Gt{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);m(this,Fs,void 0);f(this,Fs,e)}get supportsConnectedMeetings(){return a(this,Fs).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.
|
|
21
21
|
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,Fs).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,Fs).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,Fs).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,Fs).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,Fs).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,Fs).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})}}Fs=new WeakMap,RN([Lt({maxInvocations:60,period:60})],Wv.prototype,"getConnectedMeetings",1);var kN=Object.defineProperty,IN=Object.getOwnPropertyDescriptor,cp=(s,t,e,r)=>{for(var i=r>1?void 0:r?IN(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&&kN(t,e,i),i};const Jv=(mS=class{constructor(s){p(this,"connectedMeetings");m(this,Se,void 0);f(this,Se,s),this.connectedMeetings=new Wv(s)}get telemetry(){return a(this,Se).getValue("telemetry")}get logger(){return a(this,Se).getValue("logger")}static init(s){const t=new Jv(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(F.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(F.transferPeer,this.handleTransferPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(F.movedPeer,this.handleMovedPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(F.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(F.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.
|
|
22
22
|
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 zv.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,mS);let Cl=Jv;cp([y.trace("ConnectedMeetingsController.getConnectedMeetings")],Cl.prototype,"getConnectedMeetings",1),cp([y.trace("ConnectedMeetingsController.setupEvents")],Cl.prototype,"setupEvents",1),cp([y.trace("ConnectedMeetingsController.switchMeeting")],Cl.prototype,"switchMeeting",1);var AN=Object.defineProperty,MN=Object.getOwnPropertyDescriptor,Rl=(s,t,e,r)=>{for(var i=r>1?void 0:r?MN(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};const ea=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(_v(s),Te.isSupported()===!1)throw new C("Browser not supported","0010",c,!0);const d=wO(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 nD(s);s.setValue("connectionHandler",l);const u=ea.createSocketService(s),h=u.connect(),g=d.getUserDetails(),v=d.getPlugins();let E,b="";try{await ea.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:b}=await d.getRoomNodeData()),E=await g,c.info("CF SFU is being used."),s.setValue("presetName",E.preset.name)}catch(Y){c.error("Failed to get room metadata",{error:Y})}const _=Bh.init(E.preset,!s.getValue("modules").theme),w=qh.init(s,_.viewType,E.preset.permissions),L=ea.setupControllers(u,s,E,v,b,_,w);KO(_)&&((N=ea.createRoomNodeClient(s,u).initializeConnection(E.participant.name,i,!1,w))==null||N.catch(ae=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:ae})})),y.location.country=(B=d.ipInfo)==null?void 0:B.country;const{controllers:$}=await L;return TC(),new ea(e,$,s)}static async setupFlagsmith(s){var l;const{peerId:t,baseURI:e,overrides:r,meetingId:i,organizationId:n,logger:o}=s.getAllValues(),c=SC(i),d={entity:sh.PEER,clientId:n,isAnonUser:!n,sdkVersion:s.getValue("sdkVersion"),presetName:s.getValue("presetName"),meetingHash:c,roomName:i,...Te.getDeviceInfo(),isReactNative:navigator.isReactNative};try{const u=(l=r==null?void 0:r.whitelabelled_flags_endpoint)==null||l?_i({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";await s.getValue("flagsmith").identify(`${sh.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 k,Ke,fi;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:(k=g.enableHighBitrate)!=null?k:!1,enableStereo:(Ke=g.enableStereo)!=null?Ke:!1}},...l}),t.setValue("maxPreferredStreams",Te.isMobile()?n.maxVideoStreams.mobile:n.maxVideoStreams.desktop);let v,E,b,_,w,L,$,N,B;const Y=new Y1(t,s),ae=new _N(s);t.setValue("connectedMeetingsSocketHandler",ae);const bt=new ml(t,s),$s=new os(t,s),On=new sN(s),Bs=new Cv(t,s),I=new rN(t,s),T=new z1(s),P=new Ii(t,s),x=await jr.init(t,Bs,d,o,n);t.setValue("selfController",x);const we=await qf.init(t,x.self,Bs,Y,i);if(c.participant&&(N=new pr(t,x.self,Bs)),(fi=c.e2ee)!=null&&fi.enabled&&c.e2ee.manager.init(u,t.getValue("peerSessionStore")),c.chat&&(E=await Rs.init(t,$s,P,x.self,N.participants)),c.internals&&(w=await Lh.init(t)),c.livestream&&n.viewType===Vt.Livestream&&t.getValue("flagsmith").hasFeature(X.LIVESTREAM)&&($=new lv(t,x.self,T)),n.viewType!==Vt.Chat){if(c.poll&&(v=await Ff.init(t,x.self,bt)),c.recording&&(L=new Kf(t,x.self,Bs)),c.stage&&(b=new jf(t,On,Bs,x.self,N.participants)),c.plugin){if(!N)throw new C("The plugin module cannot be initialized without the `participant` module","0102");const Lr=await r;_=await _o.init(t,Lr,I,$s,E==null?void 0:E.chat,x.self,N.participants,i)}if(c.connectedMeetings&&(B=await Cl.init(t)),c.pip){const Lr=await rh._init(t,x.self);t.setValue("pip",Lr)}}const V={storesManager:new s1(t,I),pollController:v,selfController:x,metaController:we,chatController:E,stageController:b,pluginController:_,recordingController:L,internalsController:w,livestreamController:$,participantController:N,connectedMeetingsController:B};return{theme:n,permissions:o,controllers:V}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return wv(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=["PING"];return new Uo(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Fo=ea;Rl([y.trace("Controller.init")],Fo,"init",1),Rl([y.trace("setupFlagsmith")],Fo,"setupFlagsmith",1),Rl([y.trace("Controller.createRoomNodeClient")],Fo,"createRoomNodeClient",1),Rl([y.trace("Controller.createSocketService")],Fo,"createSocketService",1);class ON{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 Kv=new ON;function DN(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=Pi.baseURI.prod;t&&(n=t);const o=`https://${_i({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new C("Invalid auth token","0004")}}class NN{constructor(){m(this,yu);m(this,mi,new Audio);m(this,kn,new MediaStream);m(this,In,new Map);m(this,jc,void 0);a(this,mi).srcObject=a(this,kn),a(this,mi).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,In).has(e.id)||(a(this,kn).addTrack(e),a(this,In).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,mi).setSinkId(t)}removeTrack(t){const e=a(this,In).get(t);e&&(a(this,kn).removeTrack(e),a(this,In).delete(t))}async play(){return a(this,mi).srcObject=a(this,kn),a(this,mi).play().catch(t=>{U(this,yu,eT).call(this,t)})}onError(t){f(this,jc,t)}}mi=new WeakMap,kn=new WeakMap,In=new WeakMap,jc=new WeakMap,yu=new WeakSet,eT=function(t){var e;(e=a(this,jc))==null||e.call(this,t)};class VN extends NN{constructor(){super();m(this,An,void 0);f(this,An,new Map)}addParticipantTrack(e,r){a(this,An).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,An).get(e);r&&this.removeTrack(r),a(this,An).delete(e)}}An=new WeakMap;var LN=Object.defineProperty,xN=Object.getOwnPropertyDescriptor,kl=(s,t,e,r)=>{for(var i=r>1?void 0:r?xN(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&&LN(t,e,i),i};let zr=(fS=class{constructor(t,e){m(this,Xe,void 0);m(this,Mn,void 0);f(this,Mn,t),f(this,Xe,e)}get peerId(){return a(this,Mn).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:Si(),n=nr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new pv(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var v,E,b,_,w,L,$;Te.init();const{mediaHandler:e}=(v=t.defaults)!=null?v:{},r=(e==null?void 0:e.peerId)||((b=(E=t==null?void 0:t.cachedUserDetails)==null?void 0:E.peerId)!=null?b:Si()),{authToken:i,baseURI:n}=t,{meetingId:o,...c}=DN(i,n);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const d=zr.setupContext(r,t,o,c),l=d.getValue("telemetry"),u=d.getValue("logger");iT(u),Kv.init(u),l.init(d,{roomName:o,userId:c.participantId,organizationId:c.orgId,peerId:r},(w=(_=t.modules)==null?void 0:_.tracing)!=null?w:!0),u.init(d),u.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(L=t.authToken)==null?void 0:L.slice(0,10)}...
|
|
23
|
-
${($=t.authToken)==null?void 0:$.slice(-10)}`}});const h=await Fo.init(d),g=new zr(d,h);return d.setValue("meeting",g),g}static setupContext(t,e,r,i){var d,l;const n=nr.createContext(t,e),o={...cC,...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",dC({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Cs(e.cachedUserDetails)),n.setValue("sdkVersion","1.2.3
|
|
23
|
+
${($=t.authToken)==null?void 0:$.slice(-10)}`}});const h=await Fo.init(d),g=new zr(d,h);return d.setValue("meeting",g),g}static setupContext(t,e,r,i){var d,l;const n=nr.createContext(t,e),o={...cC,...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",dC({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Cs(e.cachedUserDetails)),n.setValue("sdkVersion","1.2.3"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new VN),n}async join(){const{selfController:t}=a(this,Xe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){Kv.cleanup(),a(this,Mn).getValue("peerSessionStore").reset();const{selfController:e}=a(this,Xe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,Xe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Xe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Xe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Xe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Xe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Xe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Xe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Xe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Xe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Xe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Xe).stageController)==null?void 0:t.stage}get stores(){return a(this,Xe).storesManager}get audio(){return a(this,Mn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Xe).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Xe=new WeakMap,Mn=new WeakMap,fS);kl([ut("0002"),ur.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],zr.prototype,"join",1),kl([ut("0003")],zr.prototype,"leave",1),kl([ut("0001"),ur.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],zr,"init",1),zr=kl([ut("0000")],zr);const zv=zr;return zv}();
|
package/dist/dependencies.txt
CHANGED
package/dist/index.cjs.js
CHANGED
|
@@ -12,4 +12,4 @@ ${s}`}const Ba={maxInvocations:5,period:1};function Mt(s,t){return function(e,r,
|
|
|
12
12
|
maxEnergy: ${n(this,Kr)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!n(this,cr)||i<n(this,cr))&&f(this,cr,i),(!n(this,Kr)||i>n(this,Kr))&&f(this,Kr,i),{energy:(i-n(this,cr))/(n(this,Kr)-n(this,cr))*10||0,isVoice:r})},_c=new WeakSet,th=function(t){return t<5},ml=new WeakSet,ST=function(t=n(this,Wi)){var r;if(!n(this,Ss)||!t){n(this,dr).getValue("flagsmith").hasFeature(ee.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${n(this,Ss)}`);return}const e={producerId:n(this,Ss),energy:Math.round(t),silent:U(r=wo,_c,th).call(r,t)};f(this,Ma,e.silent),this.reportRequest(e)},fl=new WeakSet,ET=function(t){const e=Math.log10(t);return Math.round(e)},m(fo,_c),m(fo,fl);const nO=(s=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const e=new window.MediaStreamTrackGenerator({kind:"audio"}),r=e.writable.getWriter(),i=48e3,a=128,o=1;let c=0,d=null;const l=()=>u(exports,null,function*(){try{const T=new Float32Array(a*o),v=new window.AudioData({format:"f32",sampleRate:i,numberOfFrames:a,numberOfChannels:o,timestamp:c,data:T});c+=a/i*1e6,yield r.ready,yield r.write(v)}catch(T){d&&clearInterval(d),r.releaseLock(),e.writable.abort()}});d=window.setInterval(l,100);const g=new MediaStream([e]).getAudioTracks()[0];return g.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),e.writable.abort()}),Object.assign(g,{fakeTracks:"fakeTracks:fakeAudioTrack"}),g.enabled=s,g}catch(e){}const t=window.AudioContext||window.webkitAudioContext;if(t)try{const e=new t;if(!e||e.state!=="running"||!e.destination)return;const r=e.createOscillator();r.frequency.value=0,r.type="sine";const i=e.createGain();i.gain.value=0,r.connect(i);const a=e.createMediaStreamDestination();i.connect(a),r.start();const o=a.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=s,o):void 0}catch(e){return}},aO=(s=!1)=>{var a,o;const t=new MediaStream().getVideoTracks()[0],e=document.createElement("canvas");e.height=(a=t==null?void 0:t.getSettings().height)!=null?a:720,e.width=(o=t==null?void 0:t.getSettings().width)!=null?o:1280;const r=e.getContext("2d");r.fillStyle="black",r.fillRect(0,0,e.width,e.height),setInterval(()=>{r.fillStyle="black",r.fillRect(0,0,e.width,e.height)},1e3);const i=e.captureStream().getVideoTracks()[0];return Object.assign(i,{fakeTracks:"fakeTracks:fakeVideoTrack"}),i.enabled=s,i};var oO=Object.defineProperty,cO=Object.getOwnPropertyDescriptor,de=(s,t,e,r)=>{for(var i=r>1?void 0:r?cO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&oO(t,e,i),i};const Ot=["video/VP9","video/VP8"];var Cc,wc,ct,W,Da,vt,Ji,Ki,zi,Rc,is,ur,bc,Yi,Qi,yt,bt,zr,Pn,Tl,_T,vl,CT,yl,wT,kc,sh,Sl,mu,RT,El,bT,Pl,kT,_l,IT,Ze,pt,Xi,To,Cl,AT,wl,MT,Rl,DT;const PT=(mu=class{constructor(s,t){m(this,zr);m(this,Tl);m(this,vl);m(this,yl);m(this,kc);m(this,El);m(this,Pl);m(this,_l);m(this,Ze);m(this,Xi);m(this,Cl);m(this,wl);m(this,Rl);h(this,"context");h(this,"authToken");h(this,"e2ee");m(this,Cc,void 0);m(this,wc,void 0);m(this,ct,void 0);m(this,W,void 0);m(this,Da,void 0);m(this,vt,void 0);m(this,Ji,void 0);m(this,Ki,void 0);m(this,zi,void 0);m(this,Rc,void 0);m(this,is,null);m(this,ur,void 0);m(this,bc,void 0);m(this,Yi,void 0);m(this,Qi,void 0);m(this,yt,void 0);m(this,bt,void 0);var r,i;this.context=s;const{socket:e}=t;this.mediaJoined=!1,f(this,Yi,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,Qi,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,ct,e),f(this,Ji,!1),f(this,W,new tO(s,e)),f(this,vt,n(this,W).events),f(this,ur,new Set),f(this,yt,new Map),f(this,Ki,!1),f(this,zi,new Ju(s.getValue("logger"))),f(this,bt,new fo(this.context,n(this,W).socketHandler.audioActivity.bind(n(this,W).socketHandler))),this.e2ee=(i=(r=s.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?i:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,Rc,kh(()=>u(this,null,function*(){if(!n(this,zr,Pn).mediaJoinAttempted)return;const{roomJoined:a}=yield this.joinRoom(n(this,wc),n(this,Cc),!0,!0);a&&(this.context.getValue("peerSessionStore").emit(k.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(k.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return n(this,zr,Pn).mediaJoined}set mediaJoined(s){n(this,zr,Pn).mediaJoined=s}reset(){n(this,W).closeAllProducers(),n(this,W).closeAllConsumers(),n(this,yt).clear(),n(this,ur).clear(),f(this,is,null),n(this,zi).stop(),n(this,W).stopAllTransports(),n(this,W).reset(),f(this,zi,new Ju)}joinRoom(a,o){return u(this,arguments,function*(s,t,e=!1,r=!1,i={}){n(this,zr,Pn).mediaJoinAttempted=!0,f(this,Ji,!0),e&&this.reset();try{return yield n(this,zi).push(()=>U(this,Tl,_T).call(this,s,t,r,i),"joinRoom")}catch(c){return this.logger.error("Error in room joining process",{error:c}),this.context.getValue("peerSessionStore").emit(k.ROOM_NODE_FAILED),{roomJoined:!1}}})}initializeConnection(i,a){return u(this,arguments,function*(s,t,e=!1,r={}){return n(this,is)?n(this,is):(f(this,is,(()=>u(this,null,function*(){try{yield U(this,kc,sh).call(this,s,t,e,r)}catch(o){throw f(this,is,null),o}}))()),n(this,is))})}getConsumers(){return n(this,W).consumers}getProducers(){return n(this,W).producers}leaveRoom(){return u(this,null,function*(){n(this,W).stopAllTransports(),f(this,Ki,!1),n(this,zr,Pn).mediaJoinAttempted=!1;const s={closeRoom:!1};n(this,ct).sendMessagePromise(n(this,vt).leaveRoom,cR.toBinary(s)).then(e=>{var r;(r=YR.fromBinary(e.payload))!=null&&r.closed&&this.logger.warn("Weird state on peer closed and should not happen")}).catch(e=>{this.logger.error("error on sending leave room request",{error:e})}),this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct()})}activatePeers(s){return u(this,null,function*(){return this.createConsumers(s)})}createConsumers(s){return u(this,null,function*(){return s.length===0?Promise.resolve():n(this,W).createConsumers(s)})}closeConsumers(s){return u(this,null,function*(){if(!s.length)return;const t=s.reduce((e,r)=>{const i=n(this,W).producerIdToConsumerIdMap.get(r.producerId);return i?(e.push(i),e):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),e)},[]);yield n(this,W).closeConsumers(t)})}_shareWebcam(s,t){return u(this,null,function*(){var g,T;const e=t==="video/VP9"?he.WEBCAM:he.WEBCAM_BACKUP,r=U(this,Ze,pt).call(this,e);if(r){const v=yield r;if(n(this,W).producers.has(v)){const P=n(this,W).producers.get(v);if(!P.closed)return yield P.replaceTrack({track:s}),yield this.resumeWebcam(e),s;yield this.disableWebcam(t)}return this._shareWebcam(s,t)}const i=[t].concat(Ot.filter(v=>v!==t)),a=U(this,Rl,DT).call(this,s,i),o=xa(this.context,"disableSimulcast"),c=(T=(g=this.context)==null?void 0:g.getValue("overrides"))==null?void 0:T.simulcastConfig;!(o||c&&c.disable)&&this.context.getValue("flagsmith").hasFeature(ee.ENABLE_CF_SIMULCAST)?(this.logger.info("Simulcast enabled for SFU: CF"),a.encodings=J0(this.context,s)):this.logger.info("Simulcast disabled for webcam producer, SFU: CF"),this.context.getValue("flagsmith").hasFeature(ee.TRACK_HINT)&&(a.track.contentHint=this.context.getValue("flagsmith").getValue(ee.TRACK_HINT));const l=()=>{this.logger.info("Disabling video due to the producer closure"),n(this,yt).delete(e)},p=n(this,W).createProducer(a,l);return U(this,Xi,To).call(this,e,p.then(v=>v.id)),p.then(v=>v.track)})}shareWebcam(s){return u(this,null,function*(){var r;if(s===void 0)return null;const t=(r=this.context.getValue("flagsmith").getValue(ee.FORCE_VIDEO_CODEC))==null?void 0:r.toString();if(t)return this.logger.debug(`Calling _shareWebcam with forced video codec: ${t}`),this._shareWebcam(s,t);const e=Ot.filter(i=>{var a,o;return((o=(a=n(this,Da).sender)==null?void 0:a.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===i))>=0&&n(this,Qi).get(i).size>0});return e.length===0&&e.push(Ot[0]),yield Promise.all(e.map(i=>(this.logger.debug(`Calling _shareWebcam with video codec: ${i}`),this._shareWebcam(s,i)))),s})}shareScreen(s){return u(this,null,function*(){const{video:t,audio:e}=s;if(t===void 0)return;const r={track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Se.isElectron()},stopTracks:!1},i=()=>{this.logger.info("Disabling screenShare due to the producer closure"),n(this,yt).delete(he.SCREENSHARE_VIDEO),n(this,yt).delete(he.SCREENSHARE_AUDIO)},a=n(this,W).createProducer(r,i);U(this,Xi,To).call(this,he.SCREENSHARE_VIDEO,a.then(c=>c.id));let o;if(e){const c={track:e,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Se.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},d=()=>{};o=n(this,W).createProducer(c,d),U(this,Xi,To).call(this,he.SCREENSHARE_AUDIO,o.then(l=>l.id))}yield Promise.all([a,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()})}shareMic(s){return u(this,null,function*(){try{if(s===void 0)throw new It("track undefined");const t=U(this,Ze,pt).call(this,he.MIC);if(t){const a=yield t;if(n(this,W).producers.has(a)){const o=n(this,W).producers.get(a);if(!o.closed){yield o.replaceTrack({track:s}),yield this.resumeMic(),n(this,bt)&&(n(this,bt).audioTrack=s,n(this,bt).producerId=a,n(this,bt).start());return}yield n(this,W).closeProducer(a,{stopTrack:!1})}yield this.shareMic(s);return}const e=U(this,wl,MT).call(this,s),r=()=>{n(this,yt).delete(he.MIC)},i=n(this,W).createProducer(e,r);U(this,Xi,To).call(this,he.MIC,i.then(a=>a.id)),yield i.then(a=>{n(this,bt)&&(n(this,bt).audioTrack=a.track,n(this,bt).producerId=a.id,n(this,bt).start())})}catch(t){throw new b(t)}})}pauseMic(){return u(this,null,function*(){var r;const s=yield U(this,Ze,pt).call(this,he.MIC),t=n(this,W).producers.get(s);if(!t){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}t.pause(),(r=n(this,bt))==null||r.stop();const e={producerId:t.id,pause:!0};n(this,ct).sendMessage(n(this,vt).toggleProducer,Qc.toBinary(e))})}pauseWebcam(){return u(this,null,function*(){const s=yield U(this,Ze,pt).call(this,he.WEBCAM),t=yield U(this,Ze,pt).call(this,he.WEBCAM_BACKUP),e=n(this,W).producers.get(s),r=n(this,W).producers.get(t);if(!e&&!r){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const i=a=>{const o={producerId:a.id,pause:!0};n(this,ct).sendMessage(n(this,vt).toggleProducer,Qc.toBinary(o))};e&&(e.pause(),i(e)),r&&(r.pause(),i(r))})}resumeMic(){return u(this,null,function*(){const s=yield U(this,Ze,pt).call(this,he.MIC),t=n(this,W).producers.get(s);if(!t){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};n(this,ct).sendMessage(n(this,vt).toggleProducer,Qc.toBinary(e))})}resumeWebcam(){return u(this,arguments,function*(s=he.WEBCAM){const t=yield U(this,Ze,pt).call(this,s),e=n(this,W).producers.get(t);if(!e){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!e.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};n(this,ct).sendMessage(n(this,vt).toggleProducer,Qc.toBinary(r))})}disableWebcam(s){return u(this,null,function*(){const t=s==="video/VP9"?he.WEBCAM:he.WEBCAM_BACKUP,e=yield U(this,Ze,pt).call(this,t);U(this,Cl,AT).call(this,t),e&&(yield n(this,W).closeProducer(e))})}disableMic(){return u(this,null,function*(){var t;const s=yield U(this,Ze,pt).call(this,he.MIC);s&&(yield n(this,W).closeProducer(s)),(t=n(this,bt))==null||t.stop(),n(this,yt).delete(he.MIC)})}disableScreenShare(){return u(this,null,function*(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=yield U(this,Ze,pt).call(this,he.SCREENSHARE_VIDEO),t=yield U(this,Ze,pt).call(this,he.SCREENSHARE_AUDIO);s&&(yield n(this,W).closeProducer(s)),t&&(yield n(this,W).closeProducer(t)),n(this,ur).clear(),n(this,yt).delete(he.SCREENSHARE_VIDEO),n(this,yt).delete(he.SCREENSHARE_AUDIO)})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}resetVideoProducers(s,t){return u(this,null,function*(){if(s){const e=yield U(this,Ze,pt).call(this,he.WEBCAM),r=yield U(this,Ze,pt).call(this,he.WEBCAM_BACKUP);yield n(this,W).closeProducer(e,{stopTrack:!1}),yield n(this,W).closeProducer(r,{stopTrack:!1}),this.shareWebcam(s)}if(t){const e=yield U(this,Ze,pt).call(this,he.SCREENSHARE_VIDEO);yield n(this,W).closeProducer(e,{stopTrack:!1}),this.shareScreen({video:t})}})}changeDisplayName(s,t){return u(this,null,function*(){const e={displayName:s,participantId:t!=null?t:this.peerId};if(!(yield n(this,W).socketHandler.changeDisplayName(e)))throw new Error("failed to change display name!")})}kick(s){const t={peerIds:[s]};n(this,W).socketHandler.kickPeer(t)}kickAll(){n(this,W).socketHandler.kickAll()}muteAll(s){return u(this,null,function*(){if(!(yield n(this,W).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield n(this,W).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(s){return u(this,null,function*(){if(!(yield n(this,W).socketHandler.hostControlForPeer(s,"audio")))throw new Error("failed to mute given participant")})}disableVideo(s){return u(this,null,function*(){if(!(yield n(this,W).socketHandler.hostControlForPeer(s,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(s){return u(this,null,function*(){const t={participantId:s!=null?s:""};try{yield n(this,ct).sendMessagePromise(n(this,vt).globalPinPeer,PR.toBinary(t))}catch(e){this.logger.error("Error in pinning peer:",{error:e})}})}validateScreenShare(s){return this.peerId===s.peerId&&n(this,W).producers.get(s.producerId)&&n(this,ur).add(s.consumerPeerId),n(this,ur).size}switchConsumersToLayer(s,t){return u(this,null,function*(){const e=s.map(r=>this.getConsumers().get(r));n(this,W).switchConsumersToLayer(e,t)})}handleSocketEvents(){return u(this,null,function*(){n(this,ct).on(n(this,vt).peerProducerCreateBroadcast,({payload:s})=>{var t,e;if(this.mediaJoined)try{const{participantId:r,producerState:i}=Rb.fromBinary(s);if(r===this.peerId)return;if(i!=null&&i.mimeType||(i.mimeType=i.kind===Fs.AUDIO?"audio/opus":"video/VP8"),i.kind===Fs.VIDEO&&!i.screenShare&&((e=(t=n(this,Da).receiver)==null?void 0:t.video)==null?void 0:e.codecs.findIndex(a=>a.mimeType===Ot[0]))>=0&&n(this,Yi).get(Ot[0]).has(r)&&i.mimeType!==Ot[0]){this.logger.warn(`Ignoring producer: ${i.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${i}`),this.context.getValue("peerSessionStore").emit(k.NEW_PRODUCER,{peerId:r,producer:H(D({},i),{kind:i.kind===Fs.AUDIO?"audio":"video",producingPeerId:r})})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),n(this,ct).on(n(this,vt).peerProducerToggleBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,initiatorParticipantId:e,producerState:{kind:r,pause:i,producerId:a,screenShare:o}}=Jp.fromBinary(s);if(o)return;const c=r===Fs.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${t}, producerId: ${a}, kind:${c}, paused:${i} payload: ${JSON.stringify(Jp.fromBinary(s))}`),t===this.peerId&&e!==this.peerId&&i&&this.context.getValue("peerSessionStore").emit(c==="audio"?k.MUTE_SELF:k.MUTE_SELF_VIDEO),t===this.peerId)return;this.context.getValue("peerSessionStore").emit(k.PRODUCER_TOGGLE,{peerId:t,producerId:a,paused:i,kind:c}),Array.from(this.getConsumers().values()).filter(l=>l.producerId===a).forEach(l=>{l.kind==="video"&&i||l.paused!==i&&(this.logger.debug(`consumer state mismatched for ${l.id}. updating consumer pause state ${l.paused} to ${i}`),i?(l.pause(),this.context.getValue("peerSessionStore").emit(k.CONSUMER_PAUSED,{id:l.id})):(l.resume(),this.context.getValue("peerSessionStore").emit(k.CONSUMER_RESUMED,{id:l.id})))})}catch(t){this.logger.error("error in producer toggle broadcast handler",{error:t})}}),n(this,ct).on(n(this,vt).peerLeaveBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t}=bu.fromBinary(s);if(t===this.peerId)return;this.logger.info(`peer left broadcast:${t}`),n(this,ur).delete(t),n(this,W).consumers.forEach(e=>{e.peerId===t&&e.close()}),this.context.getValue("peerSessionStore").emit(k.PEER_CLOSED,{id:t})}catch(t){this.logger.error("error in peer left broadcast",{error:t})}}),n(this,ct).on(n(this,vt).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=Ib.fromBinary(s);if(t===this.peerId)return;this.logger.info(`producer closed broadcast:${t}`),this.context.getValue("peerSessionStore").emit(k.PRODUCER_CLOSED,{peerId:t,producerId:e});const r=n(this,W).producerIdToConsumerIdMap.get(e);if(!r){this.logger.warn(`no consumer found for producer:${e}`);return}this.logger.info(`closing consumer ${r}, producer id: ${e}`),n(this,W).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),n(this,W).producerIdToConsumerIdMap.delete(e),this.context.getValue("peerSessionStore").emit(k.CONSUMER_CLOSED,{id:r})}).catch(i=>{this.logger.error("error closing consumer",{error:i})})}catch(t){this.logger.error("error on producer close broadcast",{error:t})}}),n(this,ct).on(n(this,vt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!n(this,Ji)&&!n(this,Ki)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(k.ROOM_NODE_DISCONNECTED),n(this,Rc).call(this))})})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(s=>{s.forEach((t,e)=>{const r=n(this,W).consumers.get(e);r&&this.context.getValue("peerSessionStore").emit(k.CONSUMER_SCORE_UPDATE,{id:e,kind:r.kind,peerId:r.peerId,score:t.score,scoreStats:t})})}),this.context.getValue("callstats").onProducerScore(s=>{s.forEach((t,e)=>{const r=Array.from(n(this,W).producers.values()).find(i=>i.id===e);r&&this.context.getValue("peerSessionStore").emit(k.PRODUCER_SCORE_UPDATE,{id:e,kind:r.kind,appData:r.appData,score:t.score,scoreStats:t})})})}handlePeerCapabilities(s,t){var e,r,i,a;for(let o=0;o<=Ot.length;o+=1){const c=Ot[o];if(((r=(e=t==null?void 0:t.receiver)==null?void 0:e.video)==null?void 0:r.codecs.findIndex(d=>d.mimeType===c))>=0||o===Ot.length-1){n(this,Qi).get(c).add(s);break}}for(let o=0;o<=Ot.length;o+=1){const c=Ot[o];if(((a=(i=t==null?void 0:t.sender)==null?void 0:i.video)==null?void 0:a.codecs.findIndex(d=>d.mimeType===c))>=0||o===Ot.length-1){n(this,Yi).get(c).add(s);break}}}handlePeerLeaving(s){this.context.getValue("flagsmith").hasFeature(ee.FORCE_VIDEO_CODEC)||(n(this,Yi).forEach(t=>t.delete(s)),n(this,Qi).forEach((t,e)=>{t.delete(s),!(t.size!==0||e===Ot[0])&&this.disableWebcam(e)}))}},Cc=new WeakMap,wc=new WeakMap,ct=new WeakMap,W=new WeakMap,Da=new WeakMap,vt=new WeakMap,Ji=new WeakMap,Ki=new WeakMap,zi=new WeakMap,Rc=new WeakMap,is=new WeakMap,ur=new WeakMap,bc=new WeakMap,Yi=new WeakMap,Qi=new WeakMap,yt=new WeakMap,bt=new WeakMap,zr=new WeakSet,Pn=function(){return this.context.getValue("connectionHandler")},Tl=new WeakSet,_T=function(s,t,e,r){return u(this,null,function*(){f(this,wc,s);try{return n(this,is)?yield n(this,is):yield U(this,kc,sh).call(this,s,t,e,r),U(this,yl,wT).call(this,t),{roomJoined:yield U(this,vl,CT).call(this)}}catch(i){return this.logger.error("Failed to complete room join",{error:i}),{roomJoined:!1}}finally{f(this,is,null)}})},vl=new WeakSet,CT=function(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:s}=yield n(this,W).socketHandler.notifySelfJoinComplete();return f(this,Cc,s.roomUuid),f(this,Ki,!0),f(this,Ji,!1),!0}catch(s){return this.logger.error("Error completing room join",{error:s}),this.mediaJoined=!1,!1}})},yl=new WeakSet,wT=function(s){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:H(D({},Se.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};this.context.getValue("callstats").roomJoined(e)}catch(t){this.logger.error("Error reporting room joined analytics",{error:t})}},0)},kc=new WeakSet,sh=function(s,t,e,r){return u(this,null,function*(){var i,a;try{(a=n(this,bc))!=null||f(this,bc,U(i=PT,Sl,RT).call(i));const o=U(this,El,bT).call(this);yield U(this,Pl,kT).call(this,s,t,e,o),yield n(this,W).setupTransports({send:!0,recv:!0}),yield U(this,_l,IT).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}})},Sl=new WeakSet,RT=function(){const{ipInfo:s}=dt();if(!(s!=null&&s.loc))return;const[t,e]=s.loc.split(",").map(parseFloat);return{latitude:t,longitude:e}},El=new WeakSet,bT=function(){var e;const s=(e=this.context.getValue("flagsmith").getValue(ee.FORCE_VIDEO_CODEC))==null?void 0:e.toString(),t=qD(s);return f(this,Da,t),t},Pl=new WeakSet,kT=function(s,t,e,r){return u(this,null,function*(){yield tT((i,a)=>u(this,null,function*(){if(!n(this,ct).isConnected){a(new Error("Socket is not connected"));return}i>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${i}`});try{yield n(this,W).socketHandler.joinRoom(t,s,r,e,n(this,bc))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:1/0})})},_l=new WeakSet,IT=function(s){return u(this,null,function*(){if(!(!this.context.getValue("flagsmith").hasFeature(ee.PRECREATE_PRODUCERS)||!s))try{const e=[];if(s.canProduceVideo===j.Allowed&&e.push(this.shareWebcam(aO(!1))),s.canProduceAudio===j.Allowed){const r=nO(!1);r&&e.push(this.shareMic(r))}e.length>0&&(yield Promise.all(e))}catch(e){this.logger.warn("Failed to precreate producers",{error:e})}})},Ze=new WeakSet,pt=function(s){return n(this,yt).get(s)},Xi=new WeakSet,To=function(s,t){return n(this,yt).set(s,t)},Cl=new WeakSet,AT=function(s){return n(this,yt).delete(s)},wl=new WeakSet,MT=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},Rl=new WeakSet,DT=function(s,t){return{track:s,codecOptions:t?t.map(e=>({name:e.split("/")[1]})):[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},m(mu,Sl),mu);let ae=PT;de([E.trace("MediaNodeClient.reset",{country:E.location.country})],ae.prototype,"reset",1);de([E.trace("MediaNodeClient.joinRoom")],ae.prototype,"joinRoom",1);de([E.trace("MediaNodeClient.leaveRoom")],ae.prototype,"leaveRoom",1);de([E.trace("MediaNodeClient.activatePeers")],ae.prototype,"activatePeers",1);de([E.trace("MediaNodeClient.createConsumers")],ae.prototype,"createConsumers",1);de([E.trace("MediaNodeClient.closeConsumers")],ae.prototype,"closeConsumers",1);de([E.trace("MediaNodeClient._shareWebcam")],ae.prototype,"_shareWebcam",1);de([E.trace("MediaNodeClient.shareWebcam")],ae.prototype,"shareWebcam",1);de([E.trace("MediaNodeClient.shareScreen")],ae.prototype,"shareScreen",1);de([E.trace("MediaNodeClient.shareMic")],ae.prototype,"shareMic",1);de([E.trace("MediaNodeClient.pauseMic")],ae.prototype,"pauseMic",1);de([E.trace("MediaNodeClient.pauseWebcam")],ae.prototype,"pauseWebcam",1);de([E.trace("MediaNodeClient.resumeMic")],ae.prototype,"resumeMic",1);de([E.trace("MediaNodeClient.resumeWebcam")],ae.prototype,"resumeWebcam",1);de([E.trace("MediaNodeClient.disableWebcam")],ae.prototype,"disableWebcam",1);de([E.trace("MediaNodeClient.disableMic")],ae.prototype,"disableMic",1);de([E.trace("MediaNodeClient.disableScreenShare")],ae.prototype,"disableScreenShare",1);de([E.trace("MediaNodeClient.muteSelf")],ae.prototype,"muteSelf",1);de([E.trace("MediaNodeClient.resetVideoProducers")],ae.prototype,"resetVideoProducers",1);de([E.trace("MediaNodeClient.changeDisplayName")],ae.prototype,"changeDisplayName",1);de([E.trace("MediaNodeClient.kickPeer")],ae.prototype,"kick",1);de([E.trace("MediaNodeClient.kickAllPeers")],ae.prototype,"kickAll",1);de([E.trace("MediaNodeClient.muteAll")],ae.prototype,"muteAll",1);de([E.trace("MediaNodeClient.muteAllVideo")],ae.prototype,"muteAllVideo",1);de([E.trace("MediaNodeClient.disableAudio")],ae.prototype,"disableAudio",1);de([E.trace("MediaNodeClient.disableVideo")],ae.prototype,"disableVideo",1);de([E.trace("MediaNodeClient.pinPeer")],ae.prototype,"pinPeer",1);de([E.trace("MediaNodeClient.validateScreenShare")],ae.prototype,"validateScreenShare",1);function OT(s,t){const e=s.getValue("roomNodeClient");if(e){if(e)return e;throw new Error("Room node client already set up.")}const r=new ae(s,t);return s.setValue("roomNodeClient",r),r}function NT(s){const t=s.getValue("roomNodeClient");try{t==null||t.leaveRoom()}catch(e){s.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}s.setValue("roomNodeClient",void 0)}var dO=Object.defineProperty,lO=Object.getOwnPropertyDescriptor,Tn=(s,t,e,r)=>{for(var i=r>1?void 0:r?lO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&dO(t,e,i),i},Zi,Es,te,St,Lt,jg;const LT=(jg=class{constructor(s,t,e,r){m(this,St);h(this,"self");h(this,"authToken");m(this,Zi,void 0);h(this,"viewType");m(this,Es,void 0);m(this,te,void 0);const{socket:i}=e,a=s.getValue("authToken");this.self=t,f(this,te,s),this.viewType=r,this.authToken=a,f(this,Zi,i),f(this,Es,e),t.config.viewType!==At.Chat&&this.setupEvents()}get peerId(){return n(this,te).getValue("peerId")}get telemetry(){return n(this,te).getValue("telemetry")}get logger(){return n(this,te).getValue("logger")}get mediaJoined(){return n(this,te).getValue("connectionHandler").mediaJoined}static init(s,t,e,r,i){return u(this,null,function*(){const a=dt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=yield Ye.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");if(navigator.product!=="ReactNative"){const p=!s.getValue("flagsmith").hasFeature(ee.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const g=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(g)}),s.getValue("callstats").devices("AUDIO",g==null?void 0:g.filter(T=>T.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",g==null?void 0:g.filter(T=>T.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",g==null?void 0:g.filter(T=>T.kind==="audiooutput")),l.info("Callstats:: initializing");try{yield s.getValue("callstats").initialize({peerId:o,engineName:Se.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:yield a.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:uf(s),skipConnectivityChecks:p}),l.info("Callstats:: initialized")}catch(T){l.error("Callstats:: initialization failed",{error:T})}}),0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new LT(s,d,t,i.viewType)})}shareMediaTracks(){return u(this,null,function*(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:a,screenShareTracks:o}=this.self;if(e.canProduceAudio===j.Allowed&&r)try{yield n(this,St,Lt).shareMic(s),this.self.audioEnabled||n(this,St,Lt).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===j.Allowed&&i)try{const d=yield n(this,St,Lt).shareWebcam(t);d&&d.id!==t.id&&n(this,te).getValue("flagsmith").hasFeature(ee.EXP_RESHARE)&&(yield n(this,St,Lt).shareWebcam(d)),this.self.videoEnabled||n(this,St,Lt).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===j.Allowed&&a)try{yield(c=n(this,St,Lt))==null?void 0:c.shareScreen({video:o.video,audio:o.audio})}catch(d){this.self.disableScreenShare()}})}kickHandler(s){return u(this,null,function*(){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)})}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(s){return u(this,null,function*(){n(this,te).getValue("callstats").callEnded(),n(this,St,Lt).reset(),s&&(yield this.joinRoom(s))})}setupEvents(){n(this,te).getValue("peerSessionStore").on(k.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),n(this,te).getValue("peerSessionStore").on(k.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),n(this,te).getValue("peerSessionStore").on(k.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),n(this,te).getValue("peerSessionStore").on(k.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,te).getValue("peerSessionStore").on(k.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),n(this,te).getValue("peerSessionStore").on(k.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&n(this,te).getValue("flagsmith").hasFeature(ee.REFRESH_ID_ON_DISCONNECTION)&&(t=Tr.v4()),n(this,Zi).updateURL(t),n(this,te).getValue("telemetry").resetPeerId(t),dt().setHeader("tracing-id",t),mr.remapContext(t,n(this,te)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),n(this,te).getValue("peerSessionStore").on(k.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,Es).on($.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),n(this,Es).on(dd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&n(this,te).getValue("peerSessionStore").emit(k.UPDATE_PERMISSIONS,t.patch)})}),n(this,Es).on($.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),n(this,Es).on($.kick,()=>{this.kickHandler({kickType:"kick"})}),n(this,Es).on($.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),n(this,te).getValue("peerSessionStore").onAsync(k.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),n(this,te).getValue("peerSessionStore").on(k.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var a;const i=(a=e==null?void 0:e.screenShare)!=null?a:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),n(this,te).getValue("peerSessionStore").on(k.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),n(this,te).getValue("callstats").audioOff())})),n(this,te).getValue("peerSessionStore").on(k.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),n(this,te).getValue("callstats").videoOff())})),n(this,te).getValue("peerSessionStore").onAsync(k.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),n(this,te).getValue("peerSessionStore").on(k.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(s=!1){return u(this,null,function*(){try{const{peer:t}=yield n(this,Es).joinRoom(this.self);n(this,Es).socket.flush();const e=Oh(t.stageType);if(n(this,te).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(s),n(this,te).notify("stageStatus")}catch(t){throw this.logger.error("Error in joinRoom",{error:t}),t}})}leaveRoom(s="left"){return u(this,null,function*(){var t,e;if(this.logger.info(`Leaving room with state: ${s}`),(t=n(this,te).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),n(this,te).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(s),n(this,te).notify("stageStatus");try{(e=n(this,Zi))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}NT(n(this,te)),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)})}joinMediaRoom(s=!1){return u(this,null,function*(){var a,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=n(this,te).getAllValues();try{if(e===At.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}OT(n(this,te),{socket:n(this,Zi),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:p}=(o=yield(a=n(this,St,Lt))==null?void 0:a.joinRoom(this.self.name,r,s,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}))!=null?o:{};if(!p)return;i==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:c}),new b("Error: could not join media room","0002")}})}leaveMediaRoom(s){return u(this,null,function*(){const t=n(this,te).getValue("viewType");s!=="connected-meeting"&&(yield this.cleanupSelf()),!(s==="stageLeft"&&t===At.Webinar)&&n(this,St,Lt)&&(n(this,St,Lt).mediaJoined&&s!=="disconnected"&&(yield n(this,St,Lt).leaveRoom()),!(s==="stageLeft"&&t===At.Livestream)&&(n(this,St,Lt).mediaJoined=!1))})}cleanupSelf(){return u(this,null,function*(){yield this.self.disableAudio(),yield this.self.disableVideo(),yield this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()})}},Zi=new WeakMap,Es=new WeakMap,te=new WeakMap,St=new WeakSet,Lt=function(){return n(this,te).getValue("roomNodeClient")},jg);let ii=LT;Tn([E.trace("SelfController.resetSelf")],ii.prototype,"resetSelf",1);Tn([E.trace("SelfController.setupEvents")],ii.prototype,"setupEvents",1);Tn([E.trace("SelfController.joinRoom")],ii.prototype,"joinRoom",1);Tn([E.trace("SelfController.leaveRoom")],ii.prototype,"leaveRoom",1);Tn([E.trace("SelfController.joinMediaRoom")],ii.prototype,"joinMediaRoom",1);Tn([E.trace("SelfController.leaveMediaRoom")],ii.prototype,"leaveMediaRoom",1);Tn([E.trace("SelfController.init")],ii,"init",1);var Ic;class uO{constructor(t){m(this,Ic,void 0);f(this,Ic,t)}on(t,e){let r;t===$.roomPeerCount?r=Yp.fromBinary.bind(Yp):r=og.fromBinary.bind(og),n(this,Ic).on(t,({payload:i})=>{if(t===$.roomPeerCount&&!i)return;const a=r(i);e(a)})}}Ic=new WeakMap;var Ac,Mc;class hO{constructor(t,e){m(this,Ac,void 0);m(this,Mc,void 0);f(this,Ac,e),f(this,Mc,t)}get logger(){return n(this,Mc).getValue("logger")}on(t,e){let r,i;switch(t){case $.transcript:{r=nu.fromBinary.bind(nu),i=nu.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}n(this,Ac).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}Ac=new WeakMap,Mc=new WeakMap;var pO=Object.defineProperty,gO=Object.getOwnPropertyDescriptor,Gh=(s,t,e,r)=>{for(var i=r>1?void 0:r?gO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&pO(t,e,i),i},hr,Oa;class Wl{constructor(t,e){m(this,hr,void 0);m(this,Oa,void 0);f(this,hr,e),f(this,Oa,t)}get logger(){return n(this,Oa).getValue("logger")}get telemetry(){return n(this,Oa).getValue("telemetry")}getPolls(){return n(this,hr).sendMessagePromise(Ws.getPolls)}createPoll(t,e,r=!1,i=!1){const a={anonymous:r,hideVotes:i,question:t,options:e};return n(this,hr).sendMessage(Ws.createPoll,TM.toBinary(a))}votePoll(t,e){const r={index:e,pollId:t};return n(this,hr).sendMessage(Ws.votePoll,yM.toBinary(r))}on(t,e){let r,i;switch(t){case Ws.updatePoll:case Ws.createPoll:case Ws.votePoll:{r=uu.fromBinary.bind(uu),i=uu.create();break}}n(this,hr).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){n(this,hr).removeListeners(t)}}hr=new WeakMap,Oa=new WeakMap;Gh([E.trace("PollSocketHandler.getPolls")],Wl.prototype,"getPolls",1);Gh([E.trace("PollSocketHandler.createPoll")],Wl.prototype,"createPoll",1);Gh([E.trace("PollSocketHandler.votePoll")],Wl.prototype,"votePoll",1);var mO=Object.defineProperty,fO=Object.getOwnPropertyDescriptor,TO=(s,t,e,r)=>{for(var i=r>1?void 0:r?fO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&mO(t,e,i),i},Bt;class VT{constructor(t,e){h(this,"socket");m(this,Bt,void 0);f(this,Bt,t),this.socket=e,this.handleSocketEvents(),n(this,Bt).setValue("roomSocketHandler",this)}get telemetry(){return n(this,Bt).getValue("telemetry")}get logger(){return n(this,Bt).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}joinRoom(t){return u(this,null,function*(){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise($.joinRoom,ik.toBinary(e));try{const{peer:a}=yn.fromBinary((yield r).payload);n(this,Bt).getValue("connectionHandler").socketJoined=!0,n(this,Bt).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_ROOM_JOINED,{peer:a});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=yield Promise.all([o,c]);return n(this,Bt).getValue("peerSessionStore").emit(k.ROOM_STATE,d),n(this,Bt).getValue("peerSessionStore").emit(k.SOCKET_PEERS,l),{peer:a}}catch(a){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:a}),new b("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,a)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return Hk.fromBinary((yield this.socket.sendMessagePromise($.getAllAddedParticipants)).payload).participants.map(i=>{var a=i,{id:e}=a,r=io(a,["id"]);return H(D({},r),{userId:e})})}catch(t){return[]}})}getRoomPeers(t,e,r){return u(this,null,function*(){let i;try{const a={seachQuery:t,limit:e,offset:r},o=yield this.socket.sendMessagePromise($.getRoomPeersInfo,Kb.toBinary(a));i=au.fromBinary(o.payload)}catch(a){this.logger.error("getRoomPeers::binary_decode_error",{error:a})}return i})}getRoomPeersNonPaginated(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise($.getRoomPeersInfo);t=au.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getStagePeers(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise($.getRoomPeersInfo);t=au.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getPeerInfo(t){return u(this,null,function*(){let e;try{const r=yield this.socket.sendMessagePromise($.getPeerInfo,Ef.toBinary({peerId:t}));e=yn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e})}getRoomState(){return u(this,null,function*(){let t=Qp.create();try{const e=yield this.socket.sendMessagePromise($.getRoomInfo);t=Qp.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t})}getRoomStageState(){return u(this,null,function*(){let t=tg.create();try{const e=yield this.socket.sendMessagePromise($.getRoomStageState);t=tg.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t})}broadcastMessage(t,e){return u(this,null,function*(){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise($.broadcastMessage,oo.toBinary(r))})}broadcastToMeetings(t,e,r){return u(this,null,function*(){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise($.broadcastToEntity,oo.toBinary(i))})}broadcastToPeers(t,e,r){return u(this,null,function*(){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage($.broadcastToEntity,oo.toBinary(i))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise($.leaveRoom,ak.toBinary({}))})}kick(t){return u(this,null,function*(){const e={peerIds:[t]};this.socket.sendMessage($.kick,_f.toBinary(e))})}kickAll(t=!1){return u(this,null,function*(){const e={propagateKickAcrossRooms:t};this.socket.sendMessage($.kickAll,vf.toBinary(e))})}getWaitingRoomRequests(){this.socket.sendMessage($.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage($.acceptWaitingRoomRequests,Kk.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage($.denyWaitingRoomRequests,Yk.toBinary(e))}updatePermissions(t,e){return u(this,null,function*(){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(dd.updateUserPreset,wI.toBinary(r))})}handleSocketEvents(){this.socket.on($.broadcastMessage,({payload:t})=>{try{const e=oo.fromBinary(t);n(this,Bt).getValue("peerSessionStore").emit(k.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on($.broadcastToEntity,({payload:t})=>{try{const e=oo.fromBinary(t);n(this,Bt).getValue("peerSessionStore").emit(k.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case $.joinRoom:case $.leaveRoom:case $.kick:case $.kickAll:{r=yn.fromBinary.bind(yn),i=yn.create();break}case $.getWaitingRoomRequests:{r=(a,o)=>a?eg.fromBinary(a,o):{requests:[]},i=eg.create();break}case $.recordingPaused:case $.recordingStarted:case $.recordingStopped:{r=lg.fromBinary.bind(lg);break}case dd.updateUserPreset:{r=sg.fromBinary.bind(sg);break}case Cs.peerJoinedBroadcast:case Mr.peerJoinedBroadcast:{r=Gp.fromBinary.bind(Gp);break}case Cs.selfJoinComplete:case Mr.selfJoinComplete:{r=Ru.fromBinary.bind(Ru);break}case Cs.globalPeerPinBroadcast:case Mr.globalPeerPinBroadcast:{r=Kp.fromBinary.bind(Kp);break}case Cs.selectedPeer:case Mr.selectedPeer:{r=wu.fromBinary.bind(wu);break}case Cs.selectedPeerDiff:case Mr.selectedPeerDiff:{r=jp.fromBinary.bind(jp);break}case Cs.leaveRoom:case Mr.leaveRoom:{r=bu.fromBinary.bind(bu);break}}this.socket.on(t,({payload:a})=>{let o=i;if(!r)return e(void 0);try{o=r(a)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}getUserPermissions(t){return u(this,null,function*(){const e={userIds:[t]};try{const r=yield this.socket.sendMessagePromise(dd.getUserPresets,vI.toBinary(e)),i=PI.fromBinary(r.payload).peerPresets[0],a=new TextDecoder().decode(i.preset),o=JSON.parse(a).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}})}}Bt=new WeakMap;TO([E.trace("RoomSocketHandler.joinRoom")],VT.prototype,"joinRoom",1);var kt;class vO{constructor(t){m(this,kt,void 0);f(this,kt,t)}getStageRequests(){return u(this,null,function*(){const{payload:t}=yield n(this,kt).sendMessagePromise($.getStageRequests);return t?lu.fromBinary(t):{stageRequests:[]}})}requestAccess(){n(this,kt).sendMessage($.requestStageAccess)}cancelRequestAccess(){n(this,kt).sendMessage($.cancelStageRequest)}grantAccess(t){return u(this,null,function*(){const e={userIds:t};n(this,kt).sendMessage($.grantStageAccess,oM.toBinary(e))})}denyAccess(t){return u(this,null,function*(){const e={userIds:t};n(this,kt).sendMessage($.denyStageAccess,dM.toBinary(e))})}joinStage(){return n(this,kt).sendMessagePromise($.joinStage,void 0,void 0,$.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return n(this,kt).sendMessagePromise($.leaveStage,dg.toBinary(e),void 0,$.peerStageStatusUpdate)}kick(t){const e={userIds:t};return n(this,kt).sendMessagePromise($.leaveStage,dg.toBinary(e))}on(t,e){let r;switch(t){case $.grantStageAccess:case $.denyStageAccess:{r=void 0;break}case $.getStagePeers:{r=cg.fromBinary.bind(cg);break}case $.getStageRequests:case $.requestStageAccess:case $.cancelStageRequest:{r=lu.fromBinary.bind(lu);break}case $.peerStageStatusUpdate:{r=zp.fromBinary.bind(zp);break}}n(this,kt).on(t,({payload:i,id:a})=>{if(!i||!r)return e(void 0,a);const o=r(i);return e(o,a)})}getPeerInfo(t){return u(this,null,function*(){const e=yield n(this,kt).sendMessagePromise($.getPeerInfo,Ef.toBinary({peerId:t}));return yn.fromBinary(e.payload)})}}kt=new WeakMap;var je,Dc;class yO{constructor(t,e){m(this,je,void 0);m(this,Dc,void 0);f(this,je,e),f(this,Dc,t)}get logger(){return n(this,Dc).getValue("logger")}addPlugin(t,e){n(this,je).sendMessage(J.addPlugin,CA.toBinary({pluginId:t,staggered:e}))}removePlugin(t){n(this,je).sendMessage(J.removePlugin,RA.toBinary({pluginId:t,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:t}=yield n(this,je).sendMessagePromise(J.getPlugins);return t?zA.fromBinary(t):{plugins:[]}})}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};n(this,je).sendMessage(J.customPluginEventToRoom,VA.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const a={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};n(this,je).sendMessage(J.customPluginEventToPeers,UA.toBinary(a),i)}enablePluginForRoom(t,e){n(this,je).sendMessage(J.enablePluginForRoom,kA.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){n(this,je).sendMessage(J.enablePluginForPeers,DA.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){n(this,je).sendMessage(J.disablePluginForRoom,AA.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){n(this,je).sendMessage(J.disablePluginForPeers,NA.toBinary({pluginId:t,peerIds:e}),r)}storeInsertKeys(t,e,r,i){const a={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};n(this,je).sendMessage(J.storeInsertKeys,rg.toBinary(a),i)}storeGetKeys(t,e,r,i){const a={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};n(this,je).sendMessage(J.storeGetKeys,HA.toBinary(a),i)}storeDeleteKeys(t,e,r,i){const a={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};n(this,je).sendMessage(J.storeDeleteKeys,jA.toBinary(a),i)}storeDelete(t,e,r){n(this,je).sendMessage(J.storeDelete,WA.toBinary({pluginId:t,storeName:e}),r)}getPluginDataOld(t,e){this.logger.info("getPluginDataOld",{plugin:{id:t,storeName:e}})}storePluginDataOld(t,e,r){const i={pluginId:t,storeName:e,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};n(this,je).sendMessage(J.storeInsertKeys,rg.toBinary(i))}on(t,e){let r;switch(t){case J.addPlugin:case J.enablePluginForPeers:case J.enablePluginForRoom:{r=Mu.fromBinary.bind(Mu);break}case J.removePlugin:case J.disablePluginForPeers:case J.disablePluginForRoom:{r=ig.fromBinary.bind(ig);break}case J.customPluginEventToPeers:case J.customPluginEventToRoom:{r=ag.fromBinary.bind(ag);break}case J.storeInsertKeys:case J.storeGetKeys:case J.storeDeleteKeys:case J.storeDelete:{r=ng.fromBinary.bind(ng);break}}n(this,je).on(t,({payload:i,id:a})=>{const o=r(i);return e(o,a)})}}je=new WeakMap,Dc=new WeakMap;var SO=Object.defineProperty,EO=(s,t,e)=>t in s?SO(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,PO=(s,t,e)=>(EO(s,typeof t!="symbol"?t+"":t,e),e),Wh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},M=(s,t,e)=>(Wh(s,t,"read from private field"),e?e.call(s):t.get(s)),Te=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},ne=(s,t,e,r)=>(Wh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),_e=(s,t,e)=>(Wh(s,t,"access private method"),e),Md={},_O={get exports(){return Md},set exports(s){Md=s}},On=typeof Reflect=="object"?Reflect:null,Eg=On&&typeof On.apply=="function"?On.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},fd;On&&typeof On.ownKeys=="function"?fd=On.ownKeys:Object.getOwnPropertySymbols?fd=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:fd=function(s){return Object.getOwnPropertyNames(s)};function CO(s){console&&console.warn&&console.warn(s)}var xT=Number.isNaN||function(s){return s!==s};function ce(){ce.init.call(this)}_O.exports=ce;Md.once=kO;ce.EventEmitter=ce;ce.prototype._events=void 0;ce.prototype._eventsCount=0;ce.prototype._maxListeners=void 0;var Pg=10;function Jl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ce,"defaultMaxListeners",{enumerable:!0,get:function(){return Pg},set:function(s){if(typeof s!="number"||s<0||xT(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Pg=s}});ce.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};ce.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||xT(s))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+s+".");return this._maxListeners=s,this};function UT(s){return s._maxListeners===void 0?ce.defaultMaxListeners:s._maxListeners}ce.prototype.getMaxListeners=function(){return UT(this)};ce.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")Eg(c,this,t);else for(var d=c.length,l=qT(c,d),e=0;e<d;++e)Eg(l[e],this,t);return!0};function $T(s,t,e,r){var i,a,o;if(Jl(e),a=s._events,a===void 0?(a=s._events=Object.create(null),s._eventsCount=0):(a.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),a=s._events),o=a[t]),o===void 0)o=a[t]=e,++s._eventsCount;else if(typeof o=="function"?o=a[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=UT(s),i>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=s,c.type=t,c.count=o.length,CO(c)}return s}ce.prototype.addListener=function(s,t){return $T(this,s,t,!1)};ce.prototype.on=ce.prototype.addListener;ce.prototype.prependListener=function(s,t){return $T(this,s,t,!0)};function wO(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function FT(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=wO.bind(r);return i.listener=e,r.wrapFn=i,i}ce.prototype.once=function(s,t){return Jl(t),this.on(s,FT(this,s,t)),this};ce.prototype.prependOnceListener=function(s,t){return Jl(t),this.prependListener(s,FT(this,s,t)),this};ce.prototype.removeListener=function(s,t){var e,r,i,a,o;if(Jl(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,a=e.length-1;a>=0;a--)if(e[a]===t||e[a].listener===t){o=e[a].listener,i=a;break}if(i<0)return this;i===0?e.shift():RO(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this};ce.prototype.off=ce.prototype.removeListener;ce.prototype.removeAllListeners=function(s){var t,e,r;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[s]),this;if(arguments.length===0){var i=Object.keys(e),a;for(r=0;r<i.length;++r)a=i[r],a!=="removeListener"&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=e[s],typeof t=="function")this.removeListener(s,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(s,t[r]);return this};function BT(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?bO(i):qT(i,i.length)}ce.prototype.listeners=function(s){return BT(this,s,!0)};ce.prototype.rawListeners=function(s){return BT(this,s,!1)};ce.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):HT.call(s,t)};ce.prototype.listenerCount=HT;function HT(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}ce.prototype.eventNames=function(){return this._eventsCount>0?fd(this._events):[]};function qT(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function RO(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function bO(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function kO(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,a),r(o)}function a(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}jT(s,t,a,{once:!0}),t!=="error"&&IO(s,i,{once:!0})})}function IO(s,t,e){typeof s.on=="function"&&jT(s,"error",t,e)}function jT(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(a){r.once&&s.removeEventListener(t,i),e(a)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class AO extends y.MessageType{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const _g=new AO;class GT{static encode(t){return _g.toBinary(t)}static decode(t){return _g.fromBinary(new Uint8Array(t))}}function MO(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Ir;class DO{constructor(t={}){PO(this,"opts"),Te(this,Ir,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ne(this,Ir,0)}wait(){return u(this,null,function*(){ne(this,Ir,M(this,Ir)+1);const t=MO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*Zh(2,M(this,Ir))));yield new Promise(e=>{setTimeout(e,t)})})}getAttempts(){return M(this,Ir)}reset(){ne(this,Ir,0)}}Ir=new WeakMap;const Rr={debug:0,info:1,warn:2,error:3};var li,ui;class OO{constructor(t){Te(this,li,void 0),Te(this,ui,void 0),ne(this,li,console),ne(this,ui,t)}debug(...t){Rr[M(this,ui)]>Rr.debug||M(this,li).debug("[Sockrates]:",...t)}info(...t){Rr[M(this,ui)]>Rr.info||M(this,li).info("[Sockrates]:",...t)}warn(...t){Rr[M(this,ui)]>Rr.warn||M(this,li).warn("[Sockrates]:",...t)}error(...t){Rr[M(this,ui)]>Rr.error||M(this,li).error("[Sockrates]:",...t)}}li=new WeakMap,ui=new WeakMap;var WT=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(WT||{});const NO="2",LO="3";var Ae,_n,Pe,Ve,Ar,Ke,gr,Zr,_s,Cn,Gs,rh,JT,vo,Td,ih,KT,nh,Cg,Dd,ah,oh,zT,Eo,vd,Po,Od,Nd,ch,Nn,_o,Co,Ld;class VO{constructor(t,e){var T,v,P,_,C,w,V,F,N,B;Te(this,rh),Te(this,vo),Te(this,ih),Te(this,nh),Te(this,Dd),Te(this,oh),Te(this,Eo),Te(this,Po),Te(this,Nd),Te(this,Nn),Te(this,Co),Te(this,Ae,void 0),Te(this,_n,void 0),Te(this,Pe,void 0),Te(this,Ve,void 0),Te(this,Ar,void 0),Te(this,Ke,void 0),Te(this,gr,void 0),Te(this,Zr,void 0),Te(this,_s,void 0),Te(this,Cn,void 0),Te(this,Gs,void 0);var r,i,a,o,c,d,l,p,g;ne(this,_n,t),ne(this,Ar,[]),ne(this,Ke,new Md),ne(this,gr,!0),ne(this,_s,!1),ne(this,Pe,e!=null?e:{}),(T=(r=M(this,Pe)).autoReconnect)!=null||(r.autoReconnect=!0),(v=(i=M(this,Pe)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(P=(a=M(this,Pe)).pingTimeout)!=null||(a.pingTimeout=3e4),(_=(o=M(this,Pe)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(C=(c=M(this,Pe)).debug)!=null||(c.debug=!0),(w=(d=M(this,Pe)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(V=(l=M(this,Pe)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(F=(p=M(this,Pe)).queueOnDisconnect)!=null||(p.queueOnDisconnect=!1),(N=(g=M(this,Pe)).flushOnReconnect)!=null||(g.flushOnReconnect=!1),ne(this,Zr,{code:void 0,reason:void 0}),ne(this,Ve,(B=M(this,Pe).logger)!=null?B:new OO(M(this,Pe).debug?"debug":"info")),ne(this,Gs,new DO)}get readyState(){var t;return(t=M(this,Ae))==null?void 0:t.readyState}get url(){return M(this,_n)}updateURL(t){ne(this,_n,t),_e(this,oh,zT).call(this)}get config(){return M(this,Pe)}get sendQueue(){return M(this,Ar)}flush(){if(!M(this,Pe).queueOnDisconnect)return!1;const t=[];return M(this,Ar).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ne(this,Ar,t),M(this,Ar)}connect(t=!1){return u(this,null,function*(){if(!t&&[0,1].includes(this.readyState)){M(this,Ve).debug("Websocket was already connecting or connected.");return}if(M(this,gr)!==!1)return new Promise((e,r)=>{_e(this,Nn,_o).call(this),_e(this,Co,Ld).call(this);try{ne(this,Ae,new WebSocket(_e(this,rh,JT).call(this,M(this,_n)))),M(this,Ae).binaryType="arraybuffer",M(this,Ve).debug("Connecting");const i=setTimeout(()=>{M(this,Ve).debug("Connection timeout. Closing socket"),ne(this,gr,!0),_e(this,Co,Ld).call(this),M(this,Ae).close(3001,"Connection Timeout"),M(this,Pe).autoReconnect&&!M(this,_s)&&(M(this,Ke).emit("reconnecting"),_e(this,Eo,vd).call(this)),r(new Error("Connection timed out!"))},M(this,Pe).connectionTimeout);M(this,Ae).onopen=()=>{M(this,Ve).debug(`Ready State: ${WT[M(this,Ae).readyState]}`),i&&clearTimeout(i),_e(this,Nd,ch).call(this),ne(this,Zr,{code:void 0,reason:void 0}),M(this,Ke).emit("connected"),M(this,Pe).flushOnReconnect&&this.flush(),e()},M(this,Ae).onclose=a=>{try{i&&clearTimeout(i);const{code:o,reason:c}=a;r(c),M(this,Ve).debug("Socket closed. Close event:",{event:a}),M(this,Ve).debug(`Connection closed code: ${o}`),M(this,Ve).debug(`Connection closed reason: ${c}`),M(this,_s)||_e(this,Dd,ah).call(this,o,c)}catch(o){_e(this,vo,Td).call(this,o)}},M(this,Ae).onerror=a=>{_e(this,vo,Td).call(this,a)},M(this,Ae).onmessage=a=>_e(this,ih,KT).call(this,a)}catch(i){_e(this,vo,Td).call(this,i,r)}})})}send(t,e,r,i){const a={event:t,id:e,payload:r,metadata:i};if(M(this,Pe).queueOnDisconnect&&(!M(this,Ae)||M(this,Ae).readyState!==1))return M(this,Ve).debug("Queuing message since socket is not connected!",a),M(this,Ar).push(a),!1;const o=GT.encode(a);return _e(this,Po,Od).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return _e(this,Po,Od).call(this,t)}receive(t,e){return M(this,Ke).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){M(this,Ke).on(t,e);return}this.receive(t,e)}removeAllListeners(){M(this,Ke).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){M(this,Ke).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){M(this,Ke).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ne(this,gr,!1),_e(this,Nn,_o).call(this),this.removeAllListeners(),ne(this,Zr,{code:1e3,reason:"Sockrates disconnect method called"}),M(this,Ae).close(1e3,"Sockrates disconnect method called.")}}Ae=new WeakMap,_n=new WeakMap,Pe=new WeakMap,Ve=new WeakMap,Ar=new WeakMap,Ke=new WeakMap,gr=new WeakMap,Zr=new WeakMap,_s=new WeakMap,Cn=new WeakMap,Gs=new WeakMap,rh=new WeakSet,JT=function(s){if(s.startsWith("ws://")||s.startsWith("wss://"))return s;if(s.startsWith("https://"))return`wss://${s.substring(8)}`;if(s.startsWith("http://"))return`ws://${s.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},vo=new WeakSet,Td=function(s,t){M(this,Ve).error("Error:",{error:s}),M(this,Ke).emit("errored",{error:s}),t==null||t(s)},ih=new WeakSet,KT=function(s){if(_e(this,Nd,ch).call(this),s.data===NO){M(this,Ve).debug("Received ping from server"),_e(this,Po,Od).call(this,LO);return}const t=GT.decode(s.data),{id:e,payload:r}=t;M(this,Ve).debug("Received message",{event:t.event,messageID:e}),M(this,Ke).emit(t.event.toString(),{id:e,payload:r})},nh=new WeakSet,Cg=function(){return M(this,Ae).readyState===1},Dd=new WeakSet,ah=function(s,t){ne(this,Zr,{reason:t,code:s}),M(this,Ke).emit("disconnected",{code:s,reason:t})},oh=new WeakSet,zT=function(){const{reason:s,code:t}=M(this,Zr);t&&t!==1e3&&M(this,gr)&&M(this,Pe).autoReconnect&&!M(this,_s)&&(M(this,Ve).debug(`Triggering reconnection due to ${s}.`),M(this,Ke).emit("reconnecting"),_e(this,Eo,vd).call(this))},Eo=new WeakSet,vd=function(s=!0){return u(this,null,function*(){if(s&&M(this,_s)){M(this,Ve).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(M(this,_s)||M(this,Gs).reset(),M(this,Pe).maxReconnectionAttempts!==null&&M(this,Gs).getAttempts()>=M(this,Pe).maxReconnectionAttempts){M(this,Ke).emit("failed"),ne(this,_s,!1);return}ne(this,_s,!0),_e(this,Co,Ld).call(this),_e(this,Nn,_o).call(this);try{if(yield M(this,Gs).wait(),M(this,gr)===!1)return;if(M(this,Ve).debug(`Reconnection attempt ${M(this,Gs).getAttempts()}`),M(this,Ke).emit("reconnectAttempt",{attempt:M(this,Gs).getAttempts()}),yield this.connect(),!_e(this,nh,Cg).call(this))throw Error("Reconnect Failed");ne(this,_s,!1),ne(this,Zr,{code:void 0,reason:void 0}),M(this,Ke).emit("reconnected")}catch(t){M(this,Ve).debug("Failed to reconnect."),M(this,Ke).emit("reconnectFailure",{attempt:M(this,Gs).getAttempts()}),_e(this,Eo,vd).call(this,!1)}})},Po=new WeakSet,Od=function(s){try{return M(this,Ae).send(s),!0}catch(t){return M(this,Ve).error(t.message),!1}},Nd=new WeakSet,ch=function(){this.config.disconnectOnPingTimeout&&(M(this,Ve).debug("Resetting ping timeout"),_e(this,Nn,_o).call(this),ne(this,Cn,setTimeout(()=>{var s;M(this,Ve).debug("Disconnecting the socket due to ping timeout"),ne(this,gr,!0);const t=3002,e="Ping timeout";(s=M(this,Ae))==null||s.close(t,e),_e(this,Dd,ah).call(this,t,e)},M(this,Pe).pingTimeout)))},Nn=new WeakSet,_o=function(){M(this,Cn)&&(clearTimeout(M(this,Cn)),ne(this,Cn,void 0))},Co=new WeakSet,Ld=function(){M(this,Ae)&&(M(this,Ae).onopen=void 0,M(this,Ae).onerror=void 0,M(this,Ae).onmessage=void 0,M(this,Ae).onclose=void 0)};var xO=Object.defineProperty,UO=Object.getOwnPropertyDescriptor,Kl=(s,t,e,r)=>{for(var i=r>1?void 0:r?UO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&xO(t,e,i),i};const wg=65535,$O=3e3;var Yr,Ce,we,Me,ns,et,Oc,dh,Nc,lh,Gg;const YT=(Gg=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,we);m(this,Oc);m(this,Nc);m(this,Yr,void 0);m(this,Ce,void 0);h(this,"roomName");h(this,"authToken");h(this,"capabilities");m(this,ns,void 0);m(this,et,void 0);var a;if(!t||!e||!r)throw new b("peerId, meetingId, or authToken can not be empty","0404");f(this,ns,void 0),f(this,et,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,Yr,U(this,Oc,dh).call(this,t)),f(this,Ce,new VO(n(this,Yr),{autoReconnect:!0,disconnectOnPingTimeout:(a=i.includes("PING"))!=null?a:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return n(this,we,Me).socketJoinAttempted}set joinAttempted(s){n(this,we,Me).socketJoinAttempted=s}get telemetry(){return n(this,et).getValue("telemetry")}get logger(){return n(this,et).getValue("logger")}get peerId(){return n(this,et).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,Yr,U(this,Oc,dh).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),n(this,Ce).updateURL(n(this,Yr))}static getSocketEdgeDomain(s){return nn({servicePrefix:"socket-edge",baseURI:s})}get url(){return n(this,Yr)}connect(){return u(this,null,function*(){n(this,we,Me).socketJoinAttempted=!0,yield n(this,Ce).connect(),n(this,we,Me).socketJoinAttempted=!0,n(this,we,Me).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){n(this,we,Me).socketJoinAttempted=!1,n(this,Ce).disconnect(),n(this,we,Me).socketJoinAttempted=!0,n(this,we,Me).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return n(this,Ce).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return n(this,et).getValue("telemetry").injectContext(r),n(this,Ce).send(s,e!=null?e:U(this,Nc,lh).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:i,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:i}){const a=i!=null?i:s;return new Promise((o,c)=>{const d=(P,_)=>{n(this,Ce).removeListener(a,P),n(this,Ce).removeListener(wg,_),n(this,Ce).removeListener(Mr.errorResponse,_),n(this,Ce).removeListener(Cs.errorResponse,_)},l=r!=null?r:U(this,Nc,lh).call(this),p={};n(this,et).getValue("telemetry").injectContext(p);const T=({id:P,payload:_})=>{if(l===P){let C;try{const w=FR.fromBinary(_);C=new Error(w.errorMessage)}catch(w){C=new Error("failed to parse error message",{cause:w});try{const V=Bb.fromBinary(_);C=new Error(V.message)}catch(V){C=new Error("failed to parse error message",{cause:V})}}c(C),d(v,T)}},v=({id:P,payload:_})=>{l===P&&(o({id:P,payload:_}),d(v,T))};n(this,Ce).on(a,v),n(this,Ce).on(wg,T),n(this,Ce).on(Mr.errorResponse,T),n(this,Ce).on(Cs.errorResponse,T),setTimeout(()=>{d(v,T),c(new Error(`request timeout for callback eventId:${s}`))},t),n(this,Ce).send(s,l,e,new TextEncoder().encode(JSON.stringify(p)))})}on(s,t){n(this,Ce).on(s,t)}onStateEvent(s,t){n(this,Ce).on(s,t)}removeListener(s,t){n(this,Ce).removeListener(s,t)}removeListeners(s){n(this,Ce).removeListeners(s)}flush(){return n(this,Ce).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){this.logger.info("SocketService::Connected to socket-edge"),n(this,ns)&&(clearTimeout(n(this,ns)),f(this,ns,void 0)),n(this,we,Me).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:s,reason:t})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t},country:E.location.country});const{recv:e,send:r}=(i=n(this,we,Me).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Dn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Dn.CONNECTED?n(this,et).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,we,Me).joinAttempted}):f(this,ns,setTimeout(()=>{n(this,et).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,we,Me).joinAttempted}),f(this,ns,void 0)},$O)),n(this,we,Me).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnecting to socket-edge",{country:E.location.country}),n(this,we,Me).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:s}){this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),n(this,we,Me).updateSocketConnectionState("reconnectAttempt",s)})),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),n(this,we,Me).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:n(this,we,Me).mediaJoinAttempted}}),n(this,ns)&&(clearTimeout(n(this,ns)),f(this,ns,void 0)),n(this,et).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:n(this,we,Me).mediaJoinAttempted}),n(this,we,Me).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){this.logger.info("SocketService::Failed to connect to socket-edge",{country:E.location.country}),n(this,et).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_FAILED),n(this,we,Me).updateSocketConnectionState("failed")}))}},Yr=new WeakMap,Ce=new WeakMap,we=new WeakSet,Me=function(){return n(this,et).getValue("connectionHandler")},ns=new WeakMap,et=new WeakMap,Oc=new WeakSet,dh=function(s){let t=YT.getSocketEdgeDomain(n(this,et).getValue("baseURI"));typeof xa(n(this,et),"socket_server_base")=="string"&&(t=xa(n(this,et),"socket_server_base"));const e=`wss://${t}`,r=new URL(`${e}/ws`),i=this.peerId,a=H(D({roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0},i!==s&&{oldPeerID:i}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>wd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0});return Object.entries(a).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},Nc=new WeakSet,lh=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Gg);let Gc=YT;Kl([E.trace("SocketService.connect")],Gc.prototype,"connect",1);Kl([E.trace("SocketService.disconnect")],Gc.prototype,"disconnect",1);Kl([E.trace("SocketService.sendMessagePromise")],Gc.prototype,"sendMessagePromise",1);Kl([E.trace("SocketService.sendMessagePromiseWithTimeout")],Gc.prototype,"sendMessagePromiseWithTimeout",1);class FO{constructor(t){h(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var a;const e=gk.fromBinary(t),r=e.meetings.map(o=>{var c;return{id:o.id,title:o.title,participants:(c=o.participants)!=null?c:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(a=e.parentMeeting.participants)!=null?a:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=Fk.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=Pf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return Zp.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return Ak.fromBinary(t).payloads}getConnectedRoomsDump(){return u(this,null,function*(){const t=yield this.socketService.sendMessagePromise($.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)})}createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield this.socketService.sendMessagePromise($.createConnectedRooms,vk.toBinary({payloads:t}));return Zp.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))})}updateConnectedRooms(t){return u(this,null,function*(){})}disableConnectedRooms(t){return u(this,null,function*(){const e=t.map(i=>({id:i})),r=yield this.socketService.sendMessagePromise($.deleteConnectedRooms,kk.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)})}movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield this.socketService.sendMessagePromise($.movePeers,Vk.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}})}}var BO=Object.defineProperty,HO=Object.getOwnPropertyDescriptor,qO=(s,t,e,r)=>{for(var i=r>1?void 0:r?HO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&BO(t,e,i),i},Ps;class QT extends jt{constructor(e){const r=e.getValue("logger");super(r);h(this,"meetings",[]);h(this,"parentMeeting",null);m(this,Ps,void 0);f(this,Ps,e)}get supportsConnectedMeetings(){return n(this,Ps).getValue("self").id!==""}get isActive(){return this.meetings.length!==0}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
|
|
13
13
|
Please connect with our support team to enable connected meetings.`)}getConnectedMeetings(){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info("Getting connected meetings dump");const e=yield n(this,Ps).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e})}createMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=yield n(this,Ps).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),yield n(this,Ps).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(a=>e.includes(a.id)&&a.participants.length!==0?this.moveParticipants(a.id,this.parentMeeting.id,a.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),yield Promise.all(r);const i=yield n(this,Ps).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i})}moveParticipants(e,r,i){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const a=yield n(this,Ps).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return a.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),a})}moveParticipantsWithCustomPreset(e,r,i){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const a=yield n(this,Ps).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return a.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),a})}moveSuccessHandler(e,r,i){const a=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>a.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>a.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>a.get(d)));return H(D({},o),{participants:c})}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return H(D({},o),{participants:c})}return o})}}Ps=new WeakMap;qO([Mt({maxInvocations:60,period:60})],QT.prototype,"getConnectedMeetings",1);var jO=Object.defineProperty,GO=Object.getOwnPropertyDescriptor,Jh=(s,t,e,r)=>{for(var i=r>1?void 0:r?GO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&jO(t,e,i),i},ge,Wg;const XT=(Wg=class{constructor(s){h(this,"connectedMeetings");m(this,ge,void 0);f(this,ge,s),this.connectedMeetings=new QT(s)}get telemetry(){return n(this,ge).getValue("telemetry")}get logger(){return n(this,ge).getValue("logger")}static init(s){const t=new XT(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){n(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on($.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),n(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on($.transferPeer,this.handleTransferPeer.bind(this)),n(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on($.movedPeer,this.handleMovedPeer.bind(this)),n(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on($.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),n(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on($.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=n(this,ge).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}switchMeeting(e){return u(this,arguments,function*({authToken:s,meetingId:t}){var a,o,c,d;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
|
|
14
14
|
Please connect with our support team to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const r={video:n(this,ge).getValue("self").videoEnabled,audio:n(this,ge).getValue("self").audioEnabled};try{n(this,ge).getValue("self").cleanupEvents(),yield n(this,ge).getValue("meeting").leave("connected-meeting")}catch(l){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(o=(a=n(this,ge).getValue("meeting"))==null?void 0:a.meta)==null?void 0:o.meetingId}`,{error:l})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const i=yield ev.init(H(D({},n(this,ge).getValue("options")),{cachedUserDetails:null,defaults:H(D(D({},n(this,ge).getValue("options").defaults),r),{mediaHandler:n(this,ge).getValue("self")}),authToken:s}));this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(c=i==null?void 0:i.meta)==null?void 0:c.meetingId}`);try{const{hidden:l}=n(this,ge).getValue("self");i.self.setName(n(this,ge).getValue("self").name),yield i.join(),l&&i.self.hide()}catch(l){this.logger.error("ConnectedMeetingsController.joinRoom",{error:l})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(d=i==null?void 0:i.meta)==null?void 0:d.meetingId}`),this.connectedMeetings.emit("meetingChanged",i),i})}handleConnectedRoomsDump(s){const t=n(this,ge).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return n(this,ge).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=n(this,ge).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s),e=new Map;this.connectedMeetings.meetings.forEach(r=>{e.set(r.id,r)}),t.forEach(r=>{e.has(r.id)?e.get(r.id).title=r.title:e.set(r.id,H(D({},r),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=n(this,ge).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},ge=new WeakMap,Wg);let zl=XT;Jh([E.trace("ConnectedMeetingsController.getConnectedMeetings")],zl.prototype,"getConnectedMeetings",1);Jh([E.trace("ConnectedMeetingsController.setupEvents")],zl.prototype,"setupEvents",1);Jh([E.trace("ConnectedMeetingsController.switchMeeting")],zl.prototype,"switchMeeting",1);var WO=Object.defineProperty,JO=Object.getOwnPropertyDescriptor,Yl=(s,t,e,r)=>{for(var i=r>1?void 0:r?JO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&WO(t,e,i),i};const wn=class{constructor(s,t,e){h(this,"apiBase");h(this,"selfController");h(this,"pollController");h(this,"chatController");h(this,"metaController");h(this,"storesManager");h(this,"stageController");h(this,"pluginController");h(this,"internalsController");h(this,"recordingController");h(this,"livestreamController");h(this,"participantController");h(this,"connectedMeetingsController");h(this,"telemetry");h(this,"logger");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController,this.connectedMeetingsController=t.connectedMeetingsController,this.telemetry=e.getValue("telemetry"),this.logger=e.getValue("logger")}static init(s){return u(this,null,function*(){var N,B;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:a,cachedUserDetails:o,logger:c}=s.getAllValues();if(NT(s),Se.isSupported()===!1)throw new b("Browser not supported","0010",c,!0);const d=XM(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(a),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new N0(s);s.setValue("connectionHandler",l);const p=wn.createSocketService(s),g=p.connect(),T=d.getUserDetails(),v=d.getPlugins();let P,_="";try{yield wn.setupFlagsmith(s)}catch(G){c.error("Failed to setup flagsmith",{error:G})}try{yield g}catch(G){c.error("[Controller]: Failed to connect to socket server:",{error:G})}try{({meetingTitle:_}=yield d.getRoomNodeData()),P=yield T,c.info("CF SFU is being used."),s.setValue("presetName",P.preset.name)}catch(G){c.error("Failed to get room metadata",{error:G})}const C=Bu.init(P.preset,!s.getValue("modules").theme),w=Gu.init(s,C.viewType,P.preset.permissions),V=wn.setupControllers(p,s,P,v,_,C,w);_0(C)&&((N=wn.createRoomNodeClient(s,p).initializeConnection(P.participant.name,i,!1,w))==null||N.catch(re=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:re})})),E.location.country=(B=d.ipInfo)==null?void 0:B.country;const{controllers:F}=yield V;return Ew(),new wn(e,F,s)})}static setupFlagsmith(s){return u(this,null,function*(){var l;const{peerId:t,baseURI:e,overrides:r,meetingId:i,organizationId:a,logger:o}=s.getAllValues(),c=Sw(i),d=H(D({entity:_u.PEER,clientId:a,isAnonUser:!a,sdkVersion:s.getValue("sdkVersion"),presetName:s.getValue("presetName"),meetingHash:c,roomName:i},Se.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const p=(l=r==null?void 0:r.whitelabelled_flags_endpoint)==null||l?nn({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";yield s.getValue("flagsmith").identify(`${_u.PEER}_${t}`,JSON.parse(JSON.stringify(d)),!1,5e3,p,o),o.info("flagsmith::allFlags",{flags:JSON.stringify(s.getValue("flagsmith").getAllFlags())},!0)}catch(p){o.error("Failed to fetch flagsmith flags")}})}static setupControllers(s,t,e,r,i,a,o){return u(this,null,function*(){var I,Ue,wr;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),p=t.getValue("logger"),{viewType:g,mediaConstraints:{audio:T}}=a;t.setValue("viewType",g),t.setValue("defaults",D({mediaConfiguration:{audio:{enableHighBitrate:(I=T.enableHighBitrate)!=null?I:!1,enableStereo:(Ue=T.enableStereo)!=null?Ue:!1}}},l)),t.setValue("maxPreferredStreams",Se.isMobile()?a.maxVideoStreams.mobile:a.maxVideoStreams.desktop);let v,P,_,C,w,V,F,N,B;const G=new hO(t,s),re=new FO(s);t.setValue("connectedMeetingsSocketHandler",re);const tt=new Wl(t,s),ds=new os(t,s),ni=new vO(s),ls=new VT(t,s),A=new yO(t,s),S=new uO(s),R=new dn(t,s),x=yield ii.init(t,ls,d,o,a);t.setValue("selfController",x);const fe=yield xf.init(t,x.self,ls,G,i);if(c.participant&&(N=new Cr(t,x.self,ls)),(wr=c.e2ee)!=null&&wr.enabled&&c.e2ee.manager.init(p,t.getValue("peerSessionStore")),c.chat&&(P=yield ws.init(t,ds,R,x.self,N.participants)),c.internals&&(w=yield Lh.init(t)),c.livestream&&a.viewType===At.Livestream&&t.getValue("flagsmith").hasFeature(ee.LIVESTREAM)&&(F=new Wf(t,x.self,S)),a.viewType!==At.Chat){if(c.poll&&(v=yield Of.init(t,x.self,tt)),c.recording&&(V=new Bf(t,x.self,ls)),c.stage&&(_=new Uf(t,ni,ls,x.self,N.participants)),c.plugin){if(!N)throw new b("The plugin module cannot be initialized without the `participant` module","0102");const qs=yield r;C=yield Bc.init(t,qs,A,ds,P==null?void 0:P.chat,x.self,N.participants,i)}if(c.connectedMeetings&&(B=yield zl.init(t)),c.pip){const qs=yield Cu._init(t,x.self);t.setValue("pip",qs)}}const L={storesManager:new wD(t,A),pollController:v,selfController:x,metaController:fe,chatController:P,stageController:_,pluginController:C,recordingController:V,internalsController:w,livestreamController:F,participantController:N,connectedMeetingsController:B};return{theme:a,permissions:o,controllers:L}})}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return OT(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=["PING"];return new Gc(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Wc=wn;Yl([E.trace("Controller.init")],Wc,"init",1);Yl([E.trace("setupFlagsmith")],Wc,"setupFlagsmith",1);Yl([E.trace("Controller.createRoomNodeClient")],Wc,"createRoomNodeClient",1);Yl([E.trace("Controller.createSocketService")],Wc,"createSocketService",1);class KO{constructor(){h(this,"battery");h(this,"logger");h(this,"init",t=>u(this,null,function*(){this.logger=t;try{"getBattery"in navigator&&(this.battery=yield navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){t.error("Error getting battery",e)}}));h(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});h(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});h(this,"cleanup",()=>{var t,e;"getBattery"in navigator&&((t=this.battery)==null||t.removeEventListener("chargingchange",this.updateChargeInfo),(e=this.battery)==null||e.removeEventListener("levelchange",this.updateLevelInfo))})}}const Rg=new KO;function zO(s,t){s.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c — not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.realtime.cloudflare.com/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:e,orgId:r,participantId:i}=JSON.parse(atob(s.split(".")[1]));if(!e)throw Error(`Received V1 auth token ${s}`);let a=mi.baseURI.prod;t&&(a=t);const o=`https://${nn({servicePrefix:"api",baseURI:a})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:a,apiBase:o}}catch(e){throw new b("Invalid auth token","0004")}}var Qr,en,tn,Lc,bl,ZT;class YO{constructor(){m(this,bl);m(this,Qr,new Audio);m(this,en,new MediaStream);m(this,tn,new Map);m(this,Lc,void 0);n(this,Qr).srcObject=n(this,en),n(this,Qr).autoplay=!0}playTracks(t){return u(this,null,function*(){return t.forEach(e=>{n(this,tn).has(e.id)||(n(this,en).addTrack(e),n(this,tn).set(e.id,e))}),this.play()})}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&n(this,Qr).setSinkId(t)}removeTrack(t){const e=n(this,tn).get(t);e&&(n(this,en).removeTrack(e),n(this,tn).delete(t))}play(){return u(this,null,function*(){return n(this,Qr).srcObject=n(this,en),n(this,Qr).play().catch(t=>{U(this,bl,ZT).call(this,t)})})}onError(t){f(this,Lc,t)}}Qr=new WeakMap,en=new WeakMap,tn=new WeakMap,Lc=new WeakMap,bl=new WeakSet,ZT=function(t){var e;(e=n(this,Lc))==null||e.call(this,t)};var sn;class QO extends YO{constructor(){super();m(this,sn,void 0);f(this,sn,new Map)}addParticipantTrack(e,r){n(this,sn).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=n(this,sn).get(e);r&&this.removeTrack(r),n(this,sn).delete(e)}}sn=new WeakMap;var XO=Object.defineProperty,ZO=Object.getOwnPropertyDescriptor,Ql=(s,t,e,r)=>{for(var i=r>1?void 0:r?ZO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&XO(t,e,i),i},Ge,rn,Jg;let si=(Jg=class{constructor(t,e){m(this,Ge,void 0);m(this,rn,void 0);f(this,rn,t),f(this,Ge,e)}get peerId(){return n(this,rn).getValue("peerId")}static initMedia(){return u(this,arguments,function*(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:Tr.v4(),a=mr.createContext(i,{peerId:i}),o=a.getValue("logger");o.init(a);const c=new eT(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,P,_,w,V,F,N;Se.init();const{mediaHandler:e}=(v=t.defaults)!=null?v:{},r=(e==null?void 0:e.peerId)||((_=(P=t==null?void 0:t.cachedUserDetails)==null?void 0:P.peerId)!=null?_:Tr.v4()),{authToken:i,baseURI:a}=t,C=zO(i,a),{meetingId:o}=C,c=io(C,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const d=si.setupContext(r,t,o,c),l=d.getValue("telemetry"),p=d.getValue("logger");lv(p),Rg.init(p),l.init(d,{roomName:o,userId:c.participantId,organizationId:c.orgId,peerId:r},(V=(w=t.modules)==null?void 0:w.tracing)!=null?V:!0),p.init(d),p.info("Client::init::options",{clientInitOptions:H(D({},t),{authToken:`${(F=t.authToken)==null?void 0:F.slice(0,10)}...
|
|
15
|
-
${(N=t.authToken)==null?void 0:N.slice(-10)}`})});const g=yield Wc.init(d),T=new si(d,g);return d.setValue("meeting",T),T})}static setupContext(t,e,r,i){var d,l;const a=mr.createContext(t,e),o=D(D({},lw),e==null?void 0:e.modules),c=e.defaults||{audio:!0,video:!0};return a.setValue("options",e),a.setValue("peerId",t),a.setValue("modules",o),a.setValue("sdkName","web-core"),a.setValue("meetingId",r),a.setValue("apiBase",i.apiBase),a.setValue("baseURI",i.baseURI),a.setValue("userId",i.participantId),a.setValue("organizationId",i.orgId),a.setValue("authToken",e.authToken),a.setValue("overrides",(d=e.overrides)!=null?d:{}),a.setValue("env",uw({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",Rs(e.cachedUserDetails)),a.setValue("sdkVersion","1.2.3
|
|
15
|
+
${(N=t.authToken)==null?void 0:N.slice(-10)}`})});const g=yield Wc.init(d),T=new si(d,g);return d.setValue("meeting",T),T})}static setupContext(t,e,r,i){var d,l;const a=mr.createContext(t,e),o=D(D({},lw),e==null?void 0:e.modules),c=e.defaults||{audio:!0,video:!0};return a.setValue("options",e),a.setValue("peerId",t),a.setValue("modules",o),a.setValue("sdkName","web-core"),a.setValue("meetingId",r),a.setValue("apiBase",i.apiBase),a.setValue("baseURI",i.baseURI),a.setValue("userId",i.participantId),a.setValue("organizationId",i.orgId),a.setValue("authToken",e.authToken),a.setValue("overrides",(d=e.overrides)!=null?d:{}),a.setValue("env",uw({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",Rs(e.cachedUserDetails)),a.setValue("sdkVersion","1.2.3"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new QO),a}join(){return u(this,null,function*(){const{selfController:t}=n(this,Ge);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){Rg.cleanup(),n(this,rn).getValue("peerSessionStore").reset();const{selfController:e}=n(this,Ge);return e.leaveRoom(t)})}get participants(){var t;return(t=n(this,Ge).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,Ge).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,Ge).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,Ge).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,Ge).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,Ge).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,Ge).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,Ge).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,Ge).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,Ge).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,Ge).stageController)==null?void 0:t.stage}get stores(){return n(this,Ge).storesManager}get audio(){return n(this,rn).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,Ge).internalsController)==null?void 0:t.internals}joinRoom(){return u(this,null,function*(){return this.join()})}leaveRoom(t){return u(this,null,function*(){return this.leave(t)})}},Ge=new WeakMap,rn=new WeakMap,Jg);Ql([ut("0002"),_r.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],si.prototype,"join",1);Ql([ut("0003")],si.prototype,"leave",1);Ql([ut("0001"),_r.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],si,"init",1);si=Ql([ut("0000")],si);const ev=si;module.exports=ev;
|
package/dist/index.es.js
CHANGED
|
@@ -28422,7 +28422,7 @@ let ti = (Kg = class {
|
|
|
28422
28422
|
video: !0
|
|
28423
28423
|
};
|
|
28424
28424
|
return a.setValue("options", e), a.setValue("peerId", t), a.setValue("modules", o), a.setValue("sdkName", "web-core"), a.setValue("meetingId", r), a.setValue("apiBase", i.apiBase), a.setValue("baseURI", i.baseURI), a.setValue("userId", i.participantId), a.setValue("organizationId", i.orgId), a.setValue("authToken", e.authToken), a.setValue("overrides", (d = e.overrides) != null ? d : {}), a.setValue("env", lw({ baseURI: i.baseURI })), a.setValue("defaults", c), a.setValue("onError", e.onError || (() => {
|
|
28425
|
-
})), a.setValue("cachedUserDetails", Rs(e.cachedUserDetails)), a.setValue("sdkVersion", "1.2.3
|
|
28425
|
+
})), a.setValue("cachedUserDetails", Rs(e.cachedUserDetails)), a.setValue("sdkVersion", "1.2.3"), (l = e.modules) != null && l.experimentalAudioPlayback && a.setValue("audioPlayback", new YO()), a;
|
|
28426
28426
|
}
|
|
28427
28427
|
join() {
|
|
28428
28428
|
return u(this, null, function* () {
|
package/dist/index.rn.js
CHANGED
|
@@ -12,4 +12,4 @@ ${s}`}const Ua={maxInvocations:5,period:1};function kt(s,t){return function(e,r,
|
|
|
12
12
|
maxEnergy: ${n(this,Gr)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!n(this,nr)||i<n(this,nr))&&m(this,nr,i),(!n(this,Gr)||i>n(this,Gr))&&m(this,Gr,i),{energy:(i-n(this,nr))/(n(this,Gr)-n(this,nr))*10||0,isVoice:r})},yc=new WeakSet,Ku=function(t){return t<5},ll=new WeakSet,cT=function(t=n(this,qi)){var r;if(!n(this,Ts)||!t){n(this,ar).getValue("flagsmith").hasFeature(Q.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${n(this,Ts)}`);return}const e={producerId:n(this,Ts),energy:Math.round(t),silent:V(r=Eo,yc,Ku).call(r,t)};m(this,ka,e.silent),this.reportRequest(e)},ul=new WeakSet,dT=function(t){const e=Math.log10(t);return Math.round(e)},g(ho,yc),g(ho,ul);const GD=(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}},WD=(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 JD=Object.defineProperty,KD=Object.getOwnPropertyDescriptor,ae=(s,t,e,r)=>{for(var i=r>1?void 0:r?KD(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};const At=["video/VP9","video/VP8"];var Sc,Ec,nt,H,Ia,mt,ji,Gi,Wi,Pc,ts,cr,_c,Ji,Ki,ft,Ct,Wr,yn,hl,uT,pl,hT,gl,pT,Cc,zu,ml,du,gT,fl,mT,Tl,fT,vl,TT,Ye,lt,zi,po,yl,vT,Sl,yT,El,ST;const lT=(du=class{constructor(s,t){g(this,Wr);g(this,hl);g(this,pl);g(this,gl);g(this,Cc);g(this,fl);g(this,Tl);g(this,vl);g(this,Ye);g(this,zi);g(this,yl);g(this,Sl);g(this,El);u(this,"context");u(this,"authToken");u(this,"e2ee");g(this,Sc,void 0);g(this,Ec,void 0);g(this,nt,void 0);g(this,H,void 0);g(this,Ia,void 0);g(this,mt,void 0);g(this,ji,void 0);g(this,Gi,void 0);g(this,Wi,void 0);g(this,Pc,void 0);g(this,ts,null);g(this,cr,void 0);g(this,_c,void 0);g(this,Ji,void 0);g(this,Ki,void 0);g(this,ft,void 0);g(this,Ct,void 0);var r,i;this.context=s;const{socket:e}=t;this.mediaJoined=!1,m(this,Ji,new Map([["video/VP9",new Set],["video/VP8",new Set]])),m(this,Ki,new Map([["video/VP9",new Set],["video/VP8",new Set]])),m(this,nt,e),m(this,ji,!1),m(this,H,new BD(s,e)),m(this,mt,n(this,H).events),m(this,cr,new Set),m(this,ft,new Map),m(this,Gi,!1),m(this,Wi,new Fu(s.getValue("logger"))),m(this,Ct,new ho(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,Pc,Eh(async()=>{if(!n(this,Wr,yn).mediaJoinAttempted)return;const{roomJoined:a}=await this.joinRoom(n(this,Ec),n(this,Sc),!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,Wr,yn).mediaJoined}set mediaJoined(s){n(this,Wr,yn).mediaJoined=s}reset(){n(this,H).closeAllProducers(),n(this,H).closeAllConsumers(),n(this,ft).clear(),n(this,cr).clear(),m(this,ts,null),n(this,Wi).stop(),n(this,H).stopAllTransports(),n(this,H).reset(),m(this,Wi,new Fu)}async joinRoom(s,t,e=!1,r=!1,i={}){n(this,Wr,yn).mediaJoinAttempted=!0,m(this,ji,!0),e&&this.reset();try{return await n(this,Wi).push(()=>V(this,hl,uT).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(b.ROOM_NODE_FAILED),{roomJoined:!1}}}async initializeConnection(s,t,e=!1,r={}){return n(this,ts)?n(this,ts):(m(this,ts,(async()=>{try{await V(this,Cc,zu).call(this,s,t,e,r)}catch(i){throw m(this,ts,null),i}})()),n(this,ts))}getConsumers(){return n(this,H).consumers}getProducers(){return n(this,H).producers}async leaveRoom(){n(this,H).stopAllTransports(),m(this,Gi,!1),n(this,Wr,yn).mediaJoinAttempted=!1;const s={closeRoom:!1};n(this,nt).sendMessagePromise(n(this,mt).leaveRoom,Kw.toBinary(s)).then(e=>{var r;(r=VR.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"?de.WEBCAM:de.WEBCAM_BACKUP,r=V(this,Ye,lt).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(At.filter(T=>T!==t)),a=V(this,El,ST).call(this,s,i),o=Na(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(Q.ENABLE_CF_SIMULCAST)?(this.logger.info("Simulcast enabled for SFU: CF"),a.encodings=O0(this.context,s)):this.logger.info("Simulcast disabled for webcam producer, SFU: CF"),this.context.getValue("flagsmith").hasFeature(Q.TRACK_HINT)&&(a.track.contentHint=this.context.getValue("flagsmith").getValue(Q.TRACK_HINT));const l=()=>{this.logger.info("Disabling video due to the producer closure"),n(this,ft).delete(e)},h=n(this,H).createProducer(a,l);return V(this,zi,po).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(Q.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=At.filter(i=>{var a,o;return((o=(a=n(this,Ia).sender)==null?void 0:a.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===i))>=0&&n(this,Ki).get(i).size>0});return e.length===0&&e.push(At[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:Te.isElectron()},stopTracks:!1},i=()=>{this.logger.info("Disabling screenShare due to the producer closure"),n(this,ft).delete(de.SCREENSHARE_VIDEO),n(this,ft).delete(de.SCREENSHARE_AUDIO)},a=n(this,H).createProducer(r,i);V(this,zi,po).call(this,de.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:Te.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},d=()=>{};o=n(this,H).createProducer(c,d),V(this,zi,po).call(this,de.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 Rt("track undefined");const t=V(this,Ye,lt).call(this,de.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,Ct)&&(n(this,Ct).audioTrack=s,n(this,Ct).producerId=a,n(this,Ct).start());return}await n(this,H).closeProducer(a,{stopTrack:!1})}await this.shareMic(s);return}const e=V(this,Sl,yT).call(this,s),r=()=>{n(this,ft).delete(de.MIC)},i=n(this,H).createProducer(e,r);V(this,zi,po).call(this,de.MIC,i.then(a=>a.id)),await i.then(a=>{n(this,Ct)&&(n(this,Ct).audioTrack=a.track,n(this,Ct).producerId=a.id,n(this,Ct).start())})}catch(t){throw new R(t)}}async pauseMic(){var r;const s=await V(this,Ye,lt).call(this,de.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,Ct))==null||r.stop();const e={producerId:t.id,pause:!0};n(this,nt).sendMessage(n(this,mt).toggleProducer,Wc.toBinary(e))}async pauseWebcam(){const s=await V(this,Ye,lt).call(this,de.WEBCAM),t=await V(this,Ye,lt).call(this,de.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,nt).sendMessage(n(this,mt).toggleProducer,Wc.toBinary(o))};e&&(e.pause(),i(e)),r&&(r.pause(),i(r))}async resumeMic(){const s=await V(this,Ye,lt).call(this,de.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(b.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};n(this,nt).sendMessage(n(this,mt).toggleProducer,Wc.toBinary(e))}async resumeWebcam(s=de.WEBCAM){const t=await V(this,Ye,lt).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(b.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};n(this,nt).sendMessage(n(this,mt).toggleProducer,Wc.toBinary(r))}async disableWebcam(s){const t=s==="video/VP9"?de.WEBCAM:de.WEBCAM_BACKUP,e=await V(this,Ye,lt).call(this,t);V(this,yl,vT).call(this,t),e&&await n(this,H).closeProducer(e)}async disableMic(){var t;const s=await V(this,Ye,lt).call(this,de.MIC);s&&await n(this,H).closeProducer(s),(t=n(this,Ct))==null||t.stop(),n(this,ft).delete(de.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=await V(this,Ye,lt).call(this,de.SCREENSHARE_VIDEO),t=await V(this,Ye,lt).call(this,de.SCREENSHARE_AUDIO);s&&await n(this,H).closeProducer(s),t&&await n(this,H).closeProducer(t),n(this,cr).clear(),n(this,ft).delete(de.SCREENSHARE_VIDEO),n(this,ft).delete(de.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(s,t){if(s){const e=await V(this,Ye,lt).call(this,de.WEBCAM),r=await V(this,Ye,lt).call(this,de.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,Ye,lt).call(this,de.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,nt).sendMessagePromise(n(this,mt).globalPinPeer,cR.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,cr).add(s.consumerPeerId),n(this,cr).size}async switchConsumersToLayer(s,t){const e=s.map(r=>this.getConsumers().get(r));n(this,H).switchConsumersToLayer(e,t)}async handleSocketEvents(){n(this,nt).on(n(this,mt).peerProducerCreateBroadcast,({payload:s})=>{var t,e;if(this.mediaJoined)try{const{participantId:r,producerState:i}=hb.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,Ia).receiver)==null?void 0:t.video)==null?void 0:e.codecs.findIndex(a=>a.mimeType===At[0]))>=0&&n(this,Ji).get(At[0]).has(r)&&i.mimeType!==At[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:{...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,nt).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}}=Lp.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(Lp.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,nt).on(n(this,mt).peerLeaveBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t}=Su.fromBinary(s);if(t===this.peerId)return;this.logger.info(`peer left broadcast:${t}`),n(this,cr).delete(t),n(this,H).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,nt).on(n(this,mt).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=mb.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,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(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,nt).on(n(this,mt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!n(this,ji)&&!n(this,Gi)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(b.ROOM_NODE_DISCONNECTED),n(this,Pc).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(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,H).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<=At.length;o+=1){const c=At[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===At.length-1){n(this,Ki).get(c).add(s);break}}for(let o=0;o<=At.length;o+=1){const c=At[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===At.length-1){n(this,Ji).get(c).add(s);break}}}handlePeerLeaving(s){this.context.getValue("flagsmith").hasFeature(Q.FORCE_VIDEO_CODEC)||(n(this,Ji).forEach(t=>t.delete(s)),n(this,Ki).forEach((t,e)=>{t.delete(s),!(t.size!==0||e===At[0])&&this.disableWebcam(e)}))}},Sc=new WeakMap,Ec=new WeakMap,nt=new WeakMap,H=new WeakMap,Ia=new WeakMap,mt=new WeakMap,ji=new WeakMap,Gi=new WeakMap,Wi=new WeakMap,Pc=new WeakMap,ts=new WeakMap,cr=new WeakMap,_c=new WeakMap,Ji=new WeakMap,Ki=new WeakMap,ft=new WeakMap,Ct=new WeakMap,Wr=new WeakSet,yn=function(){return this.context.getValue("connectionHandler")},hl=new WeakSet,uT=async function(s,t,e,r){m(this,Ec,s);try{return n(this,ts)?await n(this,ts):await V(this,Cc,zu).call(this,s,t,e,r),V(this,gl,pT).call(this,t),{roomJoined:await V(this,pl,hT).call(this)}}catch(i){return this.logger.error("Failed to complete room join",{error:i}),{roomJoined:!1}}finally{m(this,ts,null)}},pl=new WeakSet,hT=async function(){try{this.mediaJoined=!0;const{roomState:s}=await n(this,H).socketHandler.notifySelfJoinComplete();return m(this,Sc,s.roomUuid),m(this,Gi,!0),m(this,ji,!1),!0}catch(s){return this.logger.error("Error completing room join",{error:s}),this.mediaJoined=!1,!1}},gl=new WeakSet,pT=function(s){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:{...Te.getDeviceInfo(),userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency},sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};this.context.getValue("callstats").roomJoined(e)}catch(t){this.logger.error("Error reporting room joined analytics",{error:t})}},0)},Cc=new WeakSet,zu=async function(s,t,e,r){var i,a;try{(a=n(this,_c))!=null||m(this,_c,V(i=lT,ml,gT).call(i));const o=V(this,fl,mT).call(this);await V(this,Tl,fT).call(this,s,t,e,o),await n(this,H).setupTransports({send:!0,recv:!0}),await V(this,vl,TT).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},ml=new WeakSet,gT=function(){const{ipInfo:s}=at();if(!(s!=null&&s.loc))return;const[t,e]=s.loc.split(",").map(parseFloat);return{latitude:t,longitude:e}},fl=new WeakSet,mT=function(){var e;const s=(e=this.context.getValue("flagsmith").getValue(Q.FORCE_VIDEO_CODEC))==null?void 0:e.toString(),t=ID(s);return m(this,Ia,t),t},Tl=new WeakSet,fT=async function(s,t,e,r){await qf(async(i,a)=>{if(!n(this,nt).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,_c))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}},{delayTime:1e3,strategy:"exponential",maxRetryCount:1/0})},vl=new WeakSet,TT=async function(s){if(!(!this.context.getValue("flagsmith").hasFeature(Q.PRECREATE_PRODUCERS)||!s))try{const e=[];if(s.canProduceVideo===B.Allowed&&e.push(this.shareWebcam(WD(!1))),s.canProduceAudio===B.Allowed){const r=GD(!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})}},Ye=new WeakSet,lt=function(s){return n(this,ft).get(s)},zi=new WeakSet,po=function(s,t){return n(this,ft).set(s,t)},yl=new WeakSet,vT=function(s){return n(this,ft).delete(s)},Sl=new WeakSet,yT=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},El=new WeakSet,ST=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(du,ml),du);let re=lT;ae([S.trace("MediaNodeClient.reset",{country:S.location.country})],re.prototype,"reset",1);ae([S.trace("MediaNodeClient.joinRoom")],re.prototype,"joinRoom",1);ae([S.trace("MediaNodeClient.leaveRoom")],re.prototype,"leaveRoom",1);ae([S.trace("MediaNodeClient.activatePeers")],re.prototype,"activatePeers",1);ae([S.trace("MediaNodeClient.createConsumers")],re.prototype,"createConsumers",1);ae([S.trace("MediaNodeClient.closeConsumers")],re.prototype,"closeConsumers",1);ae([S.trace("MediaNodeClient._shareWebcam")],re.prototype,"_shareWebcam",1);ae([S.trace("MediaNodeClient.shareWebcam")],re.prototype,"shareWebcam",1);ae([S.trace("MediaNodeClient.shareScreen")],re.prototype,"shareScreen",1);ae([S.trace("MediaNodeClient.shareMic")],re.prototype,"shareMic",1);ae([S.trace("MediaNodeClient.pauseMic")],re.prototype,"pauseMic",1);ae([S.trace("MediaNodeClient.pauseWebcam")],re.prototype,"pauseWebcam",1);ae([S.trace("MediaNodeClient.resumeMic")],re.prototype,"resumeMic",1);ae([S.trace("MediaNodeClient.resumeWebcam")],re.prototype,"resumeWebcam",1);ae([S.trace("MediaNodeClient.disableWebcam")],re.prototype,"disableWebcam",1);ae([S.trace("MediaNodeClient.disableMic")],re.prototype,"disableMic",1);ae([S.trace("MediaNodeClient.disableScreenShare")],re.prototype,"disableScreenShare",1);ae([S.trace("MediaNodeClient.muteSelf")],re.prototype,"muteSelf",1);ae([S.trace("MediaNodeClient.resetVideoProducers")],re.prototype,"resetVideoProducers",1);ae([S.trace("MediaNodeClient.changeDisplayName")],re.prototype,"changeDisplayName",1);ae([S.trace("MediaNodeClient.kickPeer")],re.prototype,"kick",1);ae([S.trace("MediaNodeClient.kickAllPeers")],re.prototype,"kickAll",1);ae([S.trace("MediaNodeClient.muteAll")],re.prototype,"muteAll",1);ae([S.trace("MediaNodeClient.muteAllVideo")],re.prototype,"muteAllVideo",1);ae([S.trace("MediaNodeClient.disableAudio")],re.prototype,"disableAudio",1);ae([S.trace("MediaNodeClient.disableVideo")],re.prototype,"disableVideo",1);ae([S.trace("MediaNodeClient.pinPeer")],re.prototype,"pinPeer",1);ae([S.trace("MediaNodeClient.validateScreenShare")],re.prototype,"validateScreenShare",1);function ET(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 zD=Object.defineProperty,YD=Object.getOwnPropertyDescriptor,gn=(s,t,e,r)=>{for(var i=r>1?void 0:r?YD(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&&zD(t,e,i),i},Yi,vs,X,Tt,Dt,Dg;const _T=(Dg=class{constructor(s,t,e,r){g(this,Tt);u(this,"self");u(this,"authToken");g(this,Yi,void 0);u(this,"viewType");g(this,vs,void 0);g(this,X,void 0);const{socket:i}=e,a=s.getValue("authToken");this.self=t,m(this,X,s),this.viewType=r,this.authToken=a,m(this,Yi,i),m(this,vs,e),t.config.viewType!==bt.Chat&&this.setupEvents()}get peerId(){return n(this,X).getValue("peerId")}get telemetry(){return n(this,X).getValue("telemetry")}get logger(){return n(this,X).getValue("logger")}get mediaJoined(){return n(this,X).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const a=at(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await Je.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");if(navigator.product!=="ReactNative"){const h=!s.getValue("flagsmith").hasFeature(Q.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:Te.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:await a.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:Xm(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 _T(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===B.Allowed&&r)try{await n(this,Tt,Dt).shareMic(s),this.self.audioEnabled||n(this,Tt,Dt).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===B.Allowed&&i)try{const d=await n(this,Tt,Dt).shareWebcam(t);d&&d.id!==t.id&&n(this,X).getValue("flagsmith").hasFeature(Q.EXP_RESHARE)&&await n(this,Tt,Dt).shareWebcam(d),this.self.videoEnabled||n(this,Tt,Dt).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===B.Allowed&&a)try{await((c=n(this,Tt,Dt))==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,X).getValue("callstats").callEnded(),n(this,Tt,Dt).reset(),s&&await this.joinRoom(s)}setupEvents(){n(this,X).getValue("peerSessionStore").on(b.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),n(this,X).getValue("peerSessionStore").on(b.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),n(this,X).getValue("peerSessionStore").on(b.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),n(this,X).getValue("peerSessionStore").on(b.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,X).getValue("peerSessionStore").on(b.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),n(this,X).getValue("peerSessionStore").on(b.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&n(this,X).getValue("flagsmith").hasFeature(Q.REFRESH_ID_ON_DISCONNECTION)&&(t=gr.v4()),n(this,Yi).updateURL(t),n(this,X).getValue("telemetry").resetPeerId(t),at().setHeader("tracing-id",t),hr.remapContext(t,n(this,X)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),n(this,X).getValue("peerSessionStore").on(b.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,vs).on(x.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),n(this,vs).on(id.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&n(this,X).getValue("peerSessionStore").emit(b.UPDATE_PERMISSIONS,t.patch)})}),n(this,vs).on(x.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),n(this,vs).on(x.kick,()=>{this.kickHandler({kickType:"kick"})}),n(this,vs).on(x.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),n(this,X).getValue("peerSessionStore").onAsync(b.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),n(this,X).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,X).getValue("peerSessionStore").on(b.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),n(this,X).getValue("callstats").audioOff())}),n(this,X).getValue("peerSessionStore").on(b.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),n(this,X).getValue("callstats").videoOff())}),n(this,X).getValue("peerSessionStore").onAsync(b.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),n(this,X).getValue("peerSessionStore").on(b.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await n(this,vs).joinRoom(this.self);n(this,vs).socket.flush();const e=Rh(t.stageType);if(n(this,X).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}await this.joinMediaRoom(s),n(this,X).notify("stageStatus")}catch(t){throw this.logger.error("Error in joinRoom",{error:t}),t}}async leaveRoom(s="left"){var t,e;if(this.logger.info(`Leaving room with state: ${s}`),(t=n(this,X).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),n(this,X).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),n(this,X).notify("stageStatus");try{(e=n(this,Yi))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}PT(n(this,X)),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var a,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=n(this,X).getAllValues();try{if(e===bt.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}ET(n(this,X),{socket:n(this,Yi),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:h}=(o=await((a=n(this,Tt,Dt))==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 R("Error: could not join media room","0002")}}async leaveMediaRoom(s){const t=n(this,X).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===bt.Webinar)&&n(this,Tt,Dt)&&(n(this,Tt,Dt).mediaJoined&&s!=="disconnected"&&await n(this,Tt,Dt).leaveRoom(),!(s==="stageLeft"&&t===bt.Livestream)&&(n(this,Tt,Dt).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()}},Yi=new WeakMap,vs=new WeakMap,X=new WeakMap,Tt=new WeakSet,Dt=function(){return n(this,X).getValue("roomNodeClient")},Dg);let ti=_T;gn([S.trace("SelfController.resetSelf")],ti.prototype,"resetSelf",1);gn([S.trace("SelfController.setupEvents")],ti.prototype,"setupEvents",1);gn([S.trace("SelfController.joinRoom")],ti.prototype,"joinRoom",1);gn([S.trace("SelfController.leaveRoom")],ti.prototype,"leaveRoom",1);gn([S.trace("SelfController.joinMediaRoom")],ti.prototype,"joinMediaRoom",1);gn([S.trace("SelfController.leaveMediaRoom")],ti.prototype,"leaveMediaRoom",1);gn([S.trace("SelfController.init")],ti,"init",1);var wc;class QD{constructor(t){g(this,wc,void 0);m(this,wc,t)}on(t,e){let r;t===x.roomPeerCount?r=Up.fromBinary.bind(Up):r=zp.fromBinary.bind(zp),n(this,wc).on(t,({payload:i})=>{if(t===x.roomPeerCount&&!i)return;const a=r(i);e(a)})}}wc=new WeakMap;var Rc,bc;class XD{constructor(t,e){g(this,Rc,void 0);g(this,bc,void 0);m(this,Rc,e),m(this,bc,t)}get logger(){return n(this,bc).getValue("logger")}on(t,e){let r,i;switch(t){case x.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,Rc).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)})}}Rc=new WeakMap,bc=new WeakMap;var ZD=Object.defineProperty,eO=Object.getOwnPropertyDescriptor,Uh=(s,t,e,r)=>{for(var i=r>1?void 0:r?eO(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&&ZD(t,e,i),i},dr,Aa;class Bl{constructor(t,e){g(this,dr,void 0);g(this,Aa,void 0);m(this,dr,e),m(this,Aa,t)}get logger(){return n(this,Aa).getValue("logger")}get telemetry(){return n(this,Aa).getValue("telemetry")}getPolls(){return n(this,dr).sendMessagePromise(qs.getPolls)}createPoll(t,e,r=!1,i=!1){const a={anonymous:r,hideVotes:i,question:t,options:e};return n(this,dr).sendMessage(qs.createPoll,rM.toBinary(a))}votePoll(t,e){const r={index:e,pollId:t};return n(this,dr).sendMessage(qs.votePoll,nM.toBinary(r))}on(t,e){let r,i;switch(t){case qs.updatePoll:case qs.createPoll:case qs.votePoll:{r=nu.fromBinary.bind(nu),i=nu.create();break}}n(this,dr).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,dr).removeListeners(t)}}dr=new WeakMap,Aa=new WeakMap;Uh([S.trace("PollSocketHandler.getPolls")],Bl.prototype,"getPolls",1);Uh([S.trace("PollSocketHandler.createPoll")],Bl.prototype,"createPoll",1);Uh([S.trace("PollSocketHandler.votePoll")],Bl.prototype,"votePoll",1);var tO=Object.defineProperty,sO=Object.getOwnPropertyDescriptor,rO=(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&&tO(t,e,i),i},Ut;class CT{constructor(t,e){u(this,"socket");g(this,Ut,void 0);m(this,Ut,t),this.socket=e,this.handleSocketEvents(),n(this,Ut).setValue("roomSocketHandler",this)}get telemetry(){return n(this,Ut).getValue("telemetry")}get logger(){return n(this,Ut).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(x.joinRoom,jb.toBinary(e));try{const{peer:a}=fn.fromBinary((await r).payload);n(this,Ut).getValue("connectionHandler").socketJoined=!0,n(this,Ut).getValue("peerSessionStore").emit(b.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,Ut).getValue("peerSessionStore").emit(b.ROOM_STATE,d),n(this,Ut).getValue("peerSessionStore").emit(b.SOCKET_PEERS,l),{peer:a}}catch(a){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:a}),new R("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,a)}}async getAllAddedParticipants(){try{return kk.fromBinary((await this.socket.sendMessagePromise(x.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(x.getRoomPeersInfo,Nb.toBinary(a));i=eu.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(x.getRoomPeersInfo);t=eu.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(x.getRoomPeersInfo);t=eu.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(x.getPeerInfo,df.toBinary({peerId:t}));e=fn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=$p.create();try{const e=await this.socket.sendMessagePromise(x.getRoomInfo);t=$p.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=qp.create();try{const e=await this.socket.sendMessagePromise(x.getRoomStageState);t=qp.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(x.broadcastMessage,ro.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(x.broadcastToEntity,ro.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(x.broadcastToEntity,ro.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(x.leaveRoom,Wb.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(x.kick,uf.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(x.kickAll,af.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(x.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(x.acceptWaitingRoomRequests,Nk.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(x.denyWaitingRoomRequests,Vk.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(id.updateUserPreset,uI.toBinary(r))}handleSocketEvents(){this.socket.on(x.broadcastMessage,({payload:t})=>{try{const e=ro.fromBinary(t);n(this,Ut).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(x.broadcastToEntity,({payload:t})=>{try{const e=ro.fromBinary(t);n(this,Ut).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 x.joinRoom:case x.leaveRoom:case x.kick:case x.kickAll:{r=fn.fromBinary.bind(fn),i=fn.create();break}case x.getWaitingRoomRequests:{r=(a,o)=>a?Hp.fromBinary(a,o):{requests:[]},i=Hp.create();break}case x.recordingPaused:case x.recordingStarted:case x.recordingStopped:{r=Xp.fromBinary.bind(Xp);break}case id.updateUserPreset:{r=jp.fromBinary.bind(jp);break}case Es.peerJoinedBroadcast:case kr.peerJoinedBroadcast:{r=Op.fromBinary.bind(Op);break}case Es.selfJoinComplete:case kr.selfJoinComplete:{r=yu.fromBinary.bind(yu);break}case Es.globalPeerPinBroadcast:case kr.globalPeerPinBroadcast:{r=Vp.fromBinary.bind(Vp);break}case Es.selectedPeer:case kr.selectedPeer:{r=vu.fromBinary.bind(vu);break}case Es.selectedPeerDiff:case kr.selectedPeerDiff:{r=Dp.fromBinary.bind(Dp);break}case Es.leaveRoom:case kr.leaveRoom:{r=Su.fromBinary.bind(Su);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(id.getUserPresets,iI.toBinary(e)),i=cI.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}}}Ut=new WeakMap;rO([S.trace("RoomSocketHandler.joinRoom")],CT.prototype,"joinRoom",1);var wt;class iO{constructor(t){g(this,wt,void 0);m(this,wt,t)}async getStageRequests(){const{payload:t}=await n(this,wt).sendMessagePromise(x.getStageRequests);return t?iu.fromBinary(t):{stageRequests:[]}}requestAccess(){n(this,wt).sendMessage(x.requestStageAccess)}cancelRequestAccess(){n(this,wt).sendMessage(x.cancelStageRequest)}async grantAccess(t){const e={userIds:t};n(this,wt).sendMessage(x.grantStageAccess,JA.toBinary(e))}async denyAccess(t){const e={userIds:t};n(this,wt).sendMessage(x.denyStageAccess,zA.toBinary(e))}joinStage(){return n(this,wt).sendMessagePromise(x.joinStage,void 0,void 0,x.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return n(this,wt).sendMessagePromise(x.leaveStage,Qp.toBinary(e),void 0,x.peerStageStatusUpdate)}kick(t){const e={userIds:t};return n(this,wt).sendMessagePromise(x.leaveStage,Qp.toBinary(e))}on(t,e){let r;switch(t){case x.grantStageAccess:case x.denyStageAccess:{r=void 0;break}case x.getStagePeers:{r=Yp.fromBinary.bind(Yp);break}case x.getStageRequests:case x.requestStageAccess:case x.cancelStageRequest:{r=iu.fromBinary.bind(iu);break}case x.peerStageStatusUpdate:{r=xp.fromBinary.bind(xp);break}}n(this,wt).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,wt).sendMessagePromise(x.getPeerInfo,df.toBinary({peerId:t}));return fn.fromBinary(e.payload)}}wt=new WeakMap;var Be,kc;class nO{constructor(t,e){g(this,Be,void 0);g(this,kc,void 0);m(this,Be,e),m(this,kc,t)}get logger(){return n(this,kc).getValue("logger")}addPlugin(t,e){n(this,Be).sendMessage(q.addPlugin,lA.toBinary({pluginId:t,staggered:e}))}removePlugin(t){n(this,Be).sendMessage(q.removePlugin,hA.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await n(this,Be).sendMessagePromise(q.getPlugins);return t?LA.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};n(this,Be).sendMessage(q.customPluginEventToRoom,PA.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const a={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};n(this,Be).sendMessage(q.customPluginEventToPeers,CA.toBinary(a),i)}enablePluginForRoom(t,e){n(this,Be).sendMessage(q.enablePluginForRoom,gA.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){n(this,Be).sendMessage(q.enablePluginForPeers,vA.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){n(this,Be).sendMessage(q.disablePluginForRoom,fA.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){n(this,Be).sendMessage(q.disablePluginForPeers,SA.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,Be).sendMessage(q.storeInsertKeys,Gp.toBinary(a),i)}storeGetKeys(t,e,r,i){const a={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};n(this,Be).sendMessage(q.storeGetKeys,kA.toBinary(a),i)}storeDeleteKeys(t,e,r,i){const a={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};n(this,Be).sendMessage(q.storeDeleteKeys,AA.toBinary(a),i)}storeDelete(t,e,r){n(this,Be).sendMessage(q.storeDelete,DA.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,Be).sendMessage(q.storeInsertKeys,Gp.toBinary(i))}on(t,e){let r;switch(t){case q.addPlugin:case q.enablePluginForPeers:case q.enablePluginForRoom:{r=Cu.fromBinary.bind(Cu);break}case q.removePlugin:case q.disablePluginForPeers:case q.disablePluginForRoom:{r=Wp.fromBinary.bind(Wp);break}case q.customPluginEventToPeers:case q.customPluginEventToRoom:{r=Kp.fromBinary.bind(Kp);break}case q.storeInsertKeys:case q.storeGetKeys:case q.storeDeleteKeys:case q.storeDelete:{r=Jp.fromBinary.bind(Jp);break}}n(this,Be).on(t,({payload:i,id:a})=>{const o=r(i);return e(o,a)})}}Be=new WeakMap,kc=new WeakMap;var aO=Object.defineProperty,oO=(s,t,e)=>t in s?aO(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,cO=(s,t,e)=>(oO(s,typeof t!="symbol"?t+"":t,e),e),$h=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},A=(s,t,e)=>($h(s,t,"read from private field"),e?e.call(s):t.get(s)),ge=(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)=>($h(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),Se=(s,t,e)=>($h(s,t,"access private method"),e),Rd={},dO={get exports(){return Rd},set exports(s){Rd=s}},An=typeof Reflect=="object"?Reflect:null,dg=An&&typeof An.apply=="function"?An.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},ud;An&&typeof An.ownKeys=="function"?ud=An.ownKeys:Object.getOwnPropertySymbols?ud=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:ud=function(s){return Object.getOwnPropertyNames(s)};function lO(s){console&&console.warn&&console.warn(s)}var wT=Number.isNaN||function(s){return s!==s};function ne(){ne.init.call(this)}dO.exports=ne;Rd.once=gO;ne.EventEmitter=ne;ne.prototype._events=void 0;ne.prototype._eventsCount=0;ne.prototype._maxListeners=void 0;var lg=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(ne,"defaultMaxListeners",{enumerable:!0,get:function(){return lg},set:function(s){if(typeof s!="number"||s<0||wT(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");lg=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||wT(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 RT(s){return s._maxListeners===void 0?ne.defaultMaxListeners:s._maxListeners}ne.prototype.getMaxListeners=function(){return RT(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")dg(c,this,t);else for(var d=c.length,l=MT(c,d),e=0;e<d;++e)dg(l[e],this,t);return!0};function bT(s,t,e,r){var i,a,o;if(Hl(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=RT(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,lO(c)}return s}ne.prototype.addListener=function(s,t){return bT(this,s,t,!1)};ne.prototype.on=ne.prototype.addListener;ne.prototype.prependListener=function(s,t){return bT(this,s,t,!0)};function uO(){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 kT(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=uO.bind(r);return i.listener=e,r.wrapFn=i,i}ne.prototype.once=function(s,t){return Hl(t),this.on(s,kT(this,s,t)),this};ne.prototype.prependOnceListener=function(s,t){return Hl(t),this.prependListener(s,kT(this,s,t)),this};ne.prototype.removeListener=function(s,t){var e,r,i,a,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,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():hO(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 IT(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?pO(i):MT(i,i.length)}ne.prototype.listeners=function(s){return IT(this,s,!0)};ne.prototype.rawListeners=function(s){return IT(this,s,!1)};ne.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):AT.call(s,t)};ne.prototype.listenerCount=AT;function AT(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?ud(this._events):[]};function MT(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function hO(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function pO(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function gO(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))}DT(s,t,a,{once:!0}),t!=="error"&&mO(s,i,{once:!0})})}function mO(s,t,e){typeof s.on=="function"&&DT(s,"error",t,e)}function DT(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 fO 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 ug=new fO;class OT{static encode(t){return ug.toBinary(t)}static decode(t){return ug.fromBinary(new Uint8Array(t))}}function TO(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Rr;class vO{constructor(t={}){cO(this,"opts"),ge(this,Rr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},se(this,Rr,0)}async wait(){se(this,Rr,A(this,Rr)+1);const t=TO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**A(this,Rr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return A(this,Rr)}reset(){se(this,Rr,0)}}Rr=new WeakMap;const _r={debug:0,info:1,warn:2,error:3};var oi,ci;class yO{constructor(t){ge(this,oi,void 0),ge(this,ci,void 0),se(this,oi,console),se(this,ci,t)}debug(...t){_r[A(this,ci)]>_r.debug||A(this,oi).debug("[Sockrates]:",...t)}info(...t){_r[A(this,ci)]>_r.info||A(this,oi).info("[Sockrates]:",...t)}warn(...t){_r[A(this,ci)]>_r.warn||A(this,oi).warn("[Sockrates]:",...t)}error(...t){_r[A(this,ci)]>_r.error||A(this,oi).error("[Sockrates]:",...t)}}oi=new WeakMap,ci=new WeakMap;var NT=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(NT||{});const SO="2",EO="3";var be,Sn,ye,Oe,br,Ge,ur,Yr,Ss,En,Hs,Yu,LT,go,hd,Qu,VT,Xu,hg,bd,Zu,eh,xT,To,pd,vo,kd,Id,th,Mn,yo,So,Ad;class PO{constructor(t,e){var f,T,E,P,C,_,N,U,D,$;ge(this,Yu),ge(this,go),ge(this,Qu),ge(this,Xu),ge(this,bd),ge(this,eh),ge(this,To),ge(this,vo),ge(this,Id),ge(this,Mn),ge(this,So),ge(this,be,void 0),ge(this,Sn,void 0),ge(this,ye,void 0),ge(this,Oe,void 0),ge(this,br,void 0),ge(this,Ge,void 0),ge(this,ur,void 0),ge(this,Yr,void 0),ge(this,Ss,void 0),ge(this,En,void 0),ge(this,Hs,void 0);var r,i,a,o,c,d,l,h,p;se(this,Sn,t),se(this,br,[]),se(this,Ge,new Rd),se(this,ur,!0),se(this,Ss,!1),se(this,ye,e!=null?e:{}),(f=(r=A(this,ye)).autoReconnect)!=null||(r.autoReconnect=!0),(T=(i=A(this,ye)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(E=(a=A(this,ye)).pingTimeout)!=null||(a.pingTimeout=3e4),(P=(o=A(this,ye)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(C=(c=A(this,ye)).debug)!=null||(c.debug=!0),(_=(d=A(this,ye)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(N=(l=A(this,ye)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(U=(h=A(this,ye)).queueOnDisconnect)!=null||(h.queueOnDisconnect=!1),(D=(p=A(this,ye)).flushOnReconnect)!=null||(p.flushOnReconnect=!1),se(this,Yr,{code:void 0,reason:void 0}),se(this,Oe,($=A(this,ye).logger)!=null?$:new yO(A(this,ye).debug?"debug":"info")),se(this,Hs,new vO)}get readyState(){var t;return(t=A(this,be))==null?void 0:t.readyState}get url(){return A(this,Sn)}updateURL(t){se(this,Sn,t),Se(this,eh,xT).call(this)}get config(){return A(this,ye)}get sendQueue(){return A(this,br)}flush(){if(!A(this,ye).queueOnDisconnect)return!1;const t=[];return A(this,br).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),se(this,br,t),A(this,br)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){A(this,Oe).debug("Websocket was already connecting or connected.");return}if(A(this,ur)!==!1)return new Promise((e,r)=>{Se(this,Mn,yo).call(this),Se(this,So,Ad).call(this);try{se(this,be,new WebSocket(Se(this,Yu,LT).call(this,A(this,Sn)))),A(this,be).binaryType="arraybuffer",A(this,Oe).debug("Connecting");const i=setTimeout(()=>{A(this,Oe).debug("Connection timeout. Closing socket"),se(this,ur,!0),Se(this,So,Ad).call(this),A(this,be).close(3001,"Connection Timeout"),A(this,ye).autoReconnect&&!A(this,Ss)&&(A(this,Ge).emit("reconnecting"),Se(this,To,pd).call(this)),r(new Error("Connection timed out!"))},A(this,ye).connectionTimeout);A(this,be).onopen=()=>{A(this,Oe).debug(`Ready State: ${NT[A(this,be).readyState]}`),i&&clearTimeout(i),Se(this,Id,th).call(this),se(this,Yr,{code:void 0,reason:void 0}),A(this,Ge).emit("connected"),A(this,ye).flushOnReconnect&&this.flush(),e()},A(this,be).onclose=a=>{try{i&&clearTimeout(i);const{code:o,reason:c}=a;r(c),A(this,Oe).debug("Socket closed. Close event:",{event:a}),A(this,Oe).debug(`Connection closed code: ${o}`),A(this,Oe).debug(`Connection closed reason: ${c}`),A(this,Ss)||Se(this,bd,Zu).call(this,o,c)}catch(o){Se(this,go,hd).call(this,o)}},A(this,be).onerror=a=>{Se(this,go,hd).call(this,a)},A(this,be).onmessage=a=>Se(this,Qu,VT).call(this,a)}catch(i){Se(this,go,hd).call(this,i,r)}})}send(t,e,r,i){const a={event:t,id:e,payload:r,metadata:i};if(A(this,ye).queueOnDisconnect&&(!A(this,be)||A(this,be).readyState!==1))return A(this,Oe).debug("Queuing message since socket is not connected!",a),A(this,br).push(a),!1;const o=OT.encode(a);return Se(this,vo,kd).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return Se(this,vo,kd).call(this,t)}receive(t,e){return A(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")){A(this,Ge).on(t,e);return}this.receive(t,e)}removeAllListeners(){A(this,Ge).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){A(this,Ge).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){A(this,Ge).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){se(this,ur,!1),Se(this,Mn,yo).call(this),this.removeAllListeners(),se(this,Yr,{code:1e3,reason:"Sockrates disconnect method called"}),A(this,be).close(1e3,"Sockrates disconnect method called.")}}be=new WeakMap,Sn=new WeakMap,ye=new WeakMap,Oe=new WeakMap,br=new WeakMap,Ge=new WeakMap,ur=new WeakMap,Yr=new WeakMap,Ss=new WeakMap,En=new WeakMap,Hs=new WeakMap,Yu=new WeakSet,LT=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)://.")},go=new WeakSet,hd=function(s,t){A(this,Oe).error("Error:",{error:s}),A(this,Ge).emit("errored",{error:s}),t==null||t(s)},Qu=new WeakSet,VT=function(s){if(Se(this,Id,th).call(this),s.data===SO){A(this,Oe).debug("Received ping from server"),Se(this,vo,kd).call(this,EO);return}const t=OT.decode(s.data),{id:e,payload:r}=t;A(this,Oe).debug("Received message",{event:t.event,messageID:e}),A(this,Ge).emit(t.event.toString(),{id:e,payload:r})},Xu=new WeakSet,hg=function(){return A(this,be).readyState===1},bd=new WeakSet,Zu=function(s,t){se(this,Yr,{reason:t,code:s}),A(this,Ge).emit("disconnected",{code:s,reason:t})},eh=new WeakSet,xT=function(){const{reason:s,code:t}=A(this,Yr);t&&t!==1e3&&A(this,ur)&&A(this,ye).autoReconnect&&!A(this,Ss)&&(A(this,Oe).debug(`Triggering reconnection due to ${s}.`),A(this,Ge).emit("reconnecting"),Se(this,To,pd).call(this))},To=new WeakSet,pd=async function(s=!0){if(s&&A(this,Ss)){A(this,Oe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(A(this,Ss)||A(this,Hs).reset(),A(this,ye).maxReconnectionAttempts!==null&&A(this,Hs).getAttempts()>=A(this,ye).maxReconnectionAttempts){A(this,Ge).emit("failed"),se(this,Ss,!1);return}se(this,Ss,!0),Se(this,So,Ad).call(this),Se(this,Mn,yo).call(this);try{if(await A(this,Hs).wait(),A(this,ur)===!1)return;if(A(this,Oe).debug(`Reconnection attempt ${A(this,Hs).getAttempts()}`),A(this,Ge).emit("reconnectAttempt",{attempt:A(this,Hs).getAttempts()}),await this.connect(),!Se(this,Xu,hg).call(this))throw Error("Reconnect Failed");se(this,Ss,!1),se(this,Yr,{code:void 0,reason:void 0}),A(this,Ge).emit("reconnected")}catch(t){A(this,Oe).debug("Failed to reconnect."),A(this,Ge).emit("reconnectFailure",{attempt:A(this,Hs).getAttempts()}),Se(this,To,pd).call(this,!1)}},vo=new WeakSet,kd=function(s){try{return A(this,be).send(s),!0}catch(t){return A(this,Oe).error(t.message),!1}},Id=new WeakSet,th=function(){this.config.disconnectOnPingTimeout&&(A(this,Oe).debug("Resetting ping timeout"),Se(this,Mn,yo).call(this),se(this,En,setTimeout(()=>{var s;A(this,Oe).debug("Disconnecting the socket due to ping timeout"),se(this,ur,!0);const t=3002,e="Ping timeout";(s=A(this,be))==null||s.close(t,e),Se(this,bd,Zu).call(this,t,e)},A(this,ye).pingTimeout)))},Mn=new WeakSet,yo=function(){A(this,En)&&(clearTimeout(A(this,En)),se(this,En,void 0))},So=new WeakSet,Ad=function(){A(this,be)&&(A(this,be).onopen=void 0,A(this,be).onerror=void 0,A(this,be).onmessage=void 0,A(this,be).onclose=void 0)};var _O=Object.defineProperty,CO=Object.getOwnPropertyDescriptor,ql=(s,t,e,r)=>{for(var i=r>1?void 0:r?CO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&_O(t,e,i),i};const pg=65535,wO=3e3;var Jr,Ee,Pe,ke,ss,Qe,Ic,sh,Ac,rh,Og;const UT=(Og=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,Pe);g(this,Ic);g(this,Ac);g(this,Jr,void 0);g(this,Ee,void 0);u(this,"roomName");u(this,"authToken");u(this,"capabilities");g(this,ss,void 0);g(this,Qe,void 0);var a;if(!t||!e||!r)throw new R("peerId, meetingId, or authToken can not be empty","0404");m(this,ss,void 0),m(this,Qe,s),this.capabilities=i,this.roomName=e,this.authToken=r,m(this,Jr,V(this,Ic,sh).call(this,t)),m(this,Ee,new PO(n(this,Jr),{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,Qe).getValue("telemetry")}get logger(){return n(this,Qe).getValue("logger")}get peerId(){return n(this,Qe).getValue("peerId")}updateURL(s){s!==this.peerId&&(m(this,Jr,V(this,Ic,sh).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),n(this,Ee).updateURL(n(this,Jr))}static getSocketEdgeDomain(s){return tn({servicePrefix:"socket-edge",baseURI:s})}get url(){return n(this,Jr)}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,Qe).getValue("telemetry").injectContext(r),n(this,Ee).send(s,e!=null?e:V(this,Ac,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,P)=>{n(this,Ee).removeListener(a,E),n(this,Ee).removeListener(pg,P),n(this,Ee).removeListener(kr.errorResponse,P),n(this,Ee).removeListener(Es.errorResponse,P)},l=r!=null?r:V(this,Ac,rh).call(this),h={};n(this,Qe).getValue("telemetry").injectContext(h);const f=({id:E,payload:P})=>{if(l===E){let C;try{const _=RR.fromBinary(P);C=new Error(_.errorMessage)}catch(_){C=new Error("failed to parse error message",{cause:_});try{const N=bb.fromBinary(P);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:P})=>{l===E&&(o({id:E,payload:P}),d(T,f))};n(this,Ee).on(a,T),n(this,Ee).on(pg,f),n(this,Ee).on(kr.errorResponse,f),n(this,Ee).on(Es.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,ss)&&(clearTimeout(n(this,ss)),m(this,ss,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:S.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)!==In.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==In.CONNECTED?n(this,Qe).getValue("peerSessionStore").emit(b.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,Pe,ke).joinAttempted}):m(this,ss,setTimeout(()=>{n(this,Qe).getValue("peerSessionStore").emit(b.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,Pe,ke).joinAttempted}),m(this,ss,void 0)},wO)),n(this,Pe,ke).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge",{country:S.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,ss)&&(clearTimeout(n(this,ss)),m(this,ss,void 0)),n(this,Qe).getValue("peerSessionStore").emit(b.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:S.location.country}),n(this,Qe).getValue("peerSessionStore").emit(b.SOCKET_SERVICE_FAILED),n(this,Pe,ke).updateSocketConnectionState("failed")})}},Jr=new WeakMap,Ee=new WeakMap,Pe=new WeakSet,ke=function(){return n(this,Qe).getValue("connectionHandler")},ss=new WeakMap,Qe=new WeakMap,Ic=new WeakSet,sh=function(s){let t=UT.getSocketEdgeDomain(n(this,Qe).getValue("baseURI"));typeof Na(n(this,Qe),"socket_server_base")=="string"&&(t=Na(n(this,Qe),"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=>Sd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(a).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},Ac=new WeakSet,rh=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Og);let Bc=UT;ql([S.trace("SocketService.connect")],Bc.prototype,"connect",1);ql([S.trace("SocketService.disconnect")],Bc.prototype,"disconnect",1);ql([S.trace("SocketService.sendMessagePromise")],Bc.prototype,"sendMessagePromise",1);ql([S.trace("SocketService.sendMessagePromiseWithTimeout")],Bc.prototype,"sendMessagePromiseWithTimeout",1);class RO{constructor(t){u(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var a;const e=ek.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=Rk.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=lf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return Bp.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return fk.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(x.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(x.createConnectedRooms,ik.toBinary({payloads:t}));return Bp.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(x.deleteConnectedRooms,gk.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(x.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 bO=Object.defineProperty,kO=Object.getOwnPropertyDescriptor,IO=(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},ys;class $T extends Bt{constructor(e){const r=e.getValue("logger");super(r);u(this,"meetings",[]);u(this,"parentMeeting",null);g(this,ys,void 0);m(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.
|
|
13
13
|
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,ys).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,ys).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,ys).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,ys).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,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}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,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{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}ys=new WeakMap;IO([kt({maxInvocations:60,period:60})],$T.prototype,"getConnectedMeetings",1);var AO=Object.defineProperty,MO=Object.getOwnPropertyDescriptor,Fh=(s,t,e,r)=>{for(var i=r>1?void 0:r?MO(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&&AO(t,e,i),i},ue,Ng;const FT=(Ng=class{constructor(s){u(this,"connectedMeetings");g(this,ue,void 0);m(this,ue,s),this.connectedMeetings=new $T(s)}get telemetry(){return n(this,ue).getValue("telemetry")}get logger(){return n(this,ue).getValue("logger")}static init(s){const t=new FT(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(x.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(x.transferPeer,this.handleTransferPeer.bind(this)),n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(x.movedPeer,this.handleMovedPeer.bind(this)),n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(x.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(x.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=n(this,ue).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.
|
|
14
14
|
Please connect with our support team to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:n(this,ue).getValue("self").videoEnabled,audio:n(this,ue).getValue("self").audioEnabled};try{n(this,ue).getValue("self").cleanupEvents(),await n(this,ue).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(a=(i=n(this,ue).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 HT.init({...n(this,ue).getValue("options"),cachedUserDetails:null,defaults:{...n(this,ue).getValue("options").defaults,...e,mediaHandler:n(this,ue).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,ue).getValue("self");r.self.setName(n(this,ue).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,ue).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,ue).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=n(this,ue).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,ue).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})}},ue=new WeakMap,Ng);let jl=FT;Fh([S.trace("ConnectedMeetingsController.getConnectedMeetings")],jl.prototype,"getConnectedMeetings",1);Fh([S.trace("ConnectedMeetingsController.setupEvents")],jl.prototype,"setupEvents",1);Fh([S.trace("ConnectedMeetingsController.switchMeeting")],jl.prototype,"switchMeeting",1);var DO=Object.defineProperty,OO=Object.getOwnPropertyDescriptor,Gl=(s,t,e,r)=>{for(var i=r>1?void 0:r?OO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&DO(t,e,i),i};const Pn=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),Te.isSupported()===!1)throw new R("Browser not supported","0010",c,!0);const d=UM(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 S0(s);s.setValue("connectionHandler",l);const h=Pn.createSocketService(s),p=h.connect(),f=d.getUserDetails(),T=d.getPlugins();let E,P="";try{await Pn.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:P}=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=Nu.init(E.preset,!s.getValue("modules").theme),_=Uu.init(s,C.viewType,E.preset.permissions),N=Pn.setupControllers(h,s,E,T,P,C,_);d0(C)&&((D=Pn.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})})),S.location.country=($=d.ipInfo)==null?void 0:$.country;const{controllers:U}=await N;return ow(),new Pn(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=aw(i),d={entity:fu.PEER,clientId:a,isAnonUser:!a,sdkVersion:s.getValue("sdkVersion"),presetName:s.getValue("presetName"),meetingHash:c,roomName:i,...Te.getDeviceInfo(),isReactNative:navigator.isReactNative};try{const h=(l=r==null?void 0:r.whitelabelled_flags_endpoint)==null||l?tn({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";await s.getValue("flagsmith").identify(`${fu.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 k,Le,Pr;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:(k=f.enableHighBitrate)!=null?k:!1,enableStereo:(Le=f.enableStereo)!=null?Le:!1}},...l}),t.setValue("maxPreferredStreams",Te.isMobile()?a.maxVideoStreams.mobile:a.maxVideoStreams.desktop);let T,E,P,C,_,N,U,D,$;const G=new XD(t,s),ee=new RO(s);t.setValue("connectedMeetingsSocketHandler",ee);const Xe=new Bl(t,s),as=new is(t,s),si=new iO(s),os=new CT(t,s),I=new nO(t,s),y=new QD(s),w=new an(t,s),L=await ti.init(t,os,d,o,a);t.setValue("selfController",L);const pe=await wf.init(t,L.self,os,G,i);if(c.participant&&(D=new Er(t,L.self,os)),(Pr=c.e2ee)!=null&&Pr.enabled&&c.e2ee.manager.init(h,t.getValue("peerSessionStore")),c.chat&&(E=await Ps.init(t,as,w,L.self,D.participants)),c.internals&&(_=await kh.init(t)),c.livestream&&a.viewType===bt.Livestream&&t.getValue("flagsmith").hasFeature(Q.LIVESTREAM)&&(U=new Nf(t,L.self,y)),a.viewType!==bt.Chat){if(c.poll&&(T=await Ef.init(t,L.self,Xe)),c.recording&&(N=new If(t,L.self,os)),c.stage&&(P=new Rf(t,si,os,L.self,D.participants)),c.plugin){if(!D)throw new R("The plugin module cannot be initialized without the `participant` module","0102");const Fs=await r;C=await xc.init(t,Fs,I,as,E==null?void 0:E.chat,L.self,D.participants,i)}if(c.connectedMeetings&&($=await jl.init(t)),c.pip){const Fs=await Tu._init(t,L.self);t.setValue("pip",Fs)}}const O={storesManager:new uD(t,I),pollController:T,selfController:L,metaController:pe,chatController:E,stageController:P,pluginController:C,recordingController:N,internalsController:_,livestreamController:U,participantController:D,connectedMeetingsController:$};return{theme:a,permissions:o,controllers:O}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return ET(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=["PING"];return new Bc(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Hc=Pn;Gl([S.trace("Controller.init")],Hc,"init",1);Gl([S.trace("setupFlagsmith")],Hc,"setupFlagsmith",1);Gl([S.trace("Controller.createRoomNodeClient")],Hc,"createRoomNodeClient",1);Gl([S.trace("Controller.createSocketService")],Hc,"createSocketService",1);class NO{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 gg=new NO;function LO(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=hi.baseURI.prod;t&&(a=t);const o=`https://${tn({servicePrefix:"api",baseURI:a})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:a,apiBase:o}}catch(e){throw new R("Invalid auth token","0004")}}var Kr,Qi,Xi,Mc,Pl,BT;class VO{constructor(){g(this,Pl);g(this,Kr,new Audio);g(this,Qi,new MediaStream);g(this,Xi,new Map);g(this,Mc,void 0);n(this,Kr).srcObject=n(this,Qi),n(this,Kr).autoplay=!0}async playTracks(t){return t.forEach(e=>{n(this,Xi).has(e.id)||(n(this,Qi).addTrack(e),n(this,Xi).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&n(this,Kr).setSinkId(t)}removeTrack(t){const e=n(this,Xi).get(t);e&&(n(this,Qi).removeTrack(e),n(this,Xi).delete(t))}async play(){return n(this,Kr).srcObject=n(this,Qi),n(this,Kr).play().catch(t=>{V(this,Pl,BT).call(this,t)})}onError(t){m(this,Mc,t)}}Kr=new WeakMap,Qi=new WeakMap,Xi=new WeakMap,Mc=new WeakMap,Pl=new WeakSet,BT=function(t){var e;(e=n(this,Mc))==null||e.call(this,t)};var Zi;class xO extends VO{constructor(){super();g(this,Zi,void 0);m(this,Zi,new Map)}addParticipantTrack(e,r){n(this,Zi).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=n(this,Zi).get(e);r&&this.removeTrack(r),n(this,Zi).delete(e)}}Zi=new WeakMap;var UO=Object.defineProperty,$O=Object.getOwnPropertyDescriptor,Wl=(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&&UO(t,e,i),i},He,en,Lg;let Zr=(Lg=class{constructor(t,e){g(this,He,void 0);g(this,en,void 0);m(this,en,t),m(this,He,e)}get peerId(){return n(this,en).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:gr.v4(),a=hr.createContext(i,{peerId:i}),o=a.getValue("logger");o.init(a);const c=new Hf(a,o);return await c.init(t,e,a),a.setValue("defaults",{mediaHandler:c}),c}static async init(t){var T,E,P,C,_,N,U;Te.init();const{mediaHandler:e}=(T=t.defaults)!=null?T:{},r=(e==null?void 0:e.peerId)||((P=(E=t==null?void 0:t.cachedUserDetails)==null?void 0:E.peerId)!=null?P:gr.v4()),{authToken:i,baseURI:a}=t,{meetingId:o,...c}=LO(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");zT(h),gg.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)}...
|
|
15
|
-
${(U=t.authToken)==null?void 0:U.slice(-10)}`}});const p=await Hc.init(d),f=new Zr(d,p);return d.setValue("meeting",f),f}static setupContext(t,e,r,i){var d,l;const a=hr.createContext(t,e),o={...YC,...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",QC({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",_s(e.cachedUserDetails)),a.setValue("sdkVersion","1.2.3
|
|
15
|
+
${(U=t.authToken)==null?void 0:U.slice(-10)}`}});const p=await Hc.init(d),f=new Zr(d,p);return d.setValue("meeting",f),f}static setupContext(t,e,r,i){var d,l;const a=hr.createContext(t,e),o={...YC,...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",QC({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",_s(e.cachedUserDetails)),a.setValue("sdkVersion","1.2.3"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new xO),a}async join(){const{selfController:t}=n(this,He);return t.self.roomJoined?null:t.joinRoom()}async leave(t){gg.cleanup(),n(this,en).getValue("peerSessionStore").reset();const{selfController:e}=n(this,He);return e.leaveRoom(t)}get participants(){var t;return(t=n(this,He).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,He).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,He).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,He).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,He).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,He).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,He).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,He).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,He).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,He).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,He).stageController)==null?void 0:t.stage}get stores(){return n(this,He).storesManager}get audio(){return n(this,en).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,He).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},He=new WeakMap,en=new WeakMap,Lg);Wl([ct("0002"),Sr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Zr.prototype,"join",1);Wl([ct("0003")],Zr.prototype,"leave",1);Wl([ct("0001"),Sr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Zr,"init",1);Zr=Wl([ct("0000")],Zr);const HT=Zr;module.exports=HT;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cloudflare/realtimekit",
|
|
3
|
-
"version": "1.2.3
|
|
3
|
+
"version": "1.2.3",
|
|
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,7 +86,8 @@
|
|
|
86
86
|
"worker-timers": "7.0.60"
|
|
87
87
|
},
|
|
88
88
|
"publishConfig": {
|
|
89
|
-
"
|
|
89
|
+
"access": "public",
|
|
90
|
+
"tag": "latest"
|
|
90
91
|
},
|
|
91
92
|
"devDependencies": {
|
|
92
93
|
"@types/events": "^3.0.0",
|