@cloudflare/realtimekit 1.1.5-staging.3 → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.js CHANGED
@@ -19,4 +19,4 @@ slogScale: ${n}, isVoice: ${r}, minEnergy: ${a(this,Fr)},
19
19
  maxEnergy: ${a(this,xn)}`),n===-1/0||i<1e-6?{energy:0,isVoice:!1}:((!a(this,Fr)||n<a(this,Fr))&&f(this,Fr,n),(!a(this,xn)||n>a(this,xn))&&f(this,xn,n),{energy:(n-a(this,Fr))/(a(this,xn)-a(this,Fr))*10||0,isVoice:r})},cl=new WeakSet,Xh=function(t){return t<5},Zh=new WeakSet,oy=function(t=a(this,Gs)){var e;if(!a(this,Wi)||!t){a(this,Br).getValue("flagsmith").hasFeature(Z.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,Wi)}`);return}const i={producerId:a(this,Wi),energy:Math.round(t),silent:U(e=dl,cl,Xh).call(e,t)};f(this,xo,i.silent),this.reportRequest(i)},ep=new WeakSet,cy=function(t){const e=Math.log10(t);return Math.round(e)},g(tp,cl),g(tp,ep);const mO=(t=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const i=new window.MediaStreamTrackGenerator({kind:"audio"}),r=i.writable.getWriter(),n=48e3,s=128,o=1;let c=0,d=null;const l=()=>u(void 0,null,function*(){try{const m=new Float32Array(s*o),v=new window.AudioData({format:"f32",sampleRate:n,numberOfFrames:s,numberOfChannels:o,timestamp:c,data:m});c+=s/n*1e6,yield r.ready,yield r.write(v)}catch(m){d&&clearInterval(d),r.releaseLock(),i.writable.abort()}});d=window.setInterval(l,100);const h=new MediaStream([i]).getAudioTracks()[0];return h.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),i.writable.abort()}),Object.assign(h,{fakeTracks:"fakeTracks:fakeAudioTrack"}),h.enabled=t,h}catch(i){}const e=window.AudioContext||window.webkitAudioContext;if(e)try{const i=new e;if(!i||i.state!=="running"||!i.destination)return;const r=i.createOscillator();r.frequency.value=0,r.type="sine";const n=i.createGain();n.gain.value=0,r.connect(n);const s=i.createMediaStreamDestination();n.connect(s),r.start();const o=s.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=t,o):void 0}catch(i){return}},gO=(t=!1)=>{var e,i;const r=new MediaStream().getVideoTracks()[0],n=document.createElement("canvas");n.height=(e=r==null?void 0:r.getSettings().height)!=null?e:720,n.width=(i=r==null?void 0:r.getSettings().width)!=null?i:1280;const s=n.getContext("2d");s.fillStyle="black",s.fillRect(0,0,n.width,n.height),setInterval(()=>{s.fillStyle="black",s.fillRect(0,0,n.width,n.height)},1e3);const o=n.captureStream().getVideoTracks()[0];return Object.assign(o,{fakeTracks:"fakeTracks:fakeVideoTrack"}),o.enabled=t,o};var fO=Object.defineProperty,vO=Object.getOwnPropertyDescriptor,pe=(t,e,i,r)=>{for(var n=r>1?void 0:r?vO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&fO(e,i,n),n};const Yt=["video/VP9","video/VP8"];var ll,ul,Pt,J,Uo,lr,Ut,qs,$s,Js,hl,Ci,jr,Fo,Ks,zs,Ft,Qt,Un,Ys,ip,dy,rp,ly,np,uy,pl,sp,ap,op,hy,cp,py,dp,my,lp,gy,ft,Rt,Qs,Bo,up,fy,hp,vy,pp,yy;const Sy=(op=class{constructor(t,e,i){g(this,Un),g(this,ip),g(this,rp),g(this,np),g(this,pl),g(this,cp),g(this,dp),g(this,lp),g(this,ft),g(this,Qs),g(this,up),g(this,hp),g(this,pp),p(this,"context"),p(this,"authToken"),p(this,"e2ee"),g(this,ll,void 0),g(this,ul,void 0),g(this,Pt,void 0),g(this,J,void 0),g(this,Uo,void 0),g(this,lr,void 0),g(this,Ut,void 0),g(this,qs,void 0),g(this,$s,void 0),g(this,Js,void 0),g(this,hl,void 0),g(this,Ci,null),g(this,jr,void 0),g(this,Fo,void 0),g(this,Ks,void 0),g(this,zs,void 0),g(this,Ft,void 0),g(this,Qt,void 0);var r,n;this.context=t;const{socket:s}=i;this.mediaJoined=!1,f(this,Ks,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,zs,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,lr,e),f(this,Pt,s),f(this,qs,!1),f(this,J,new lO(t,s,e)),f(this,Ut,a(this,J).events),f(this,jr,new Set),f(this,Ft,new Map),f(this,$s,!1),f(this,Js,new fh(t.getValue("logger"))),e===Ae.CF&&f(this,Qt,new tp(this.context,a(this,J).socketHandler.audioActivity.bind(a(this,J).socketHandler))),this.e2ee=(n=(r=t.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,hl,mu(()=>u(this,null,function*(){if(!a(this,Un,Ys).mediaJoinAttempted)return;const{roomJoined:o}=yield this.joinRoom(a(this,ul),a(this,ll),!0,!0);o&&(this.context.getValue("peerSessionStore").emit(P.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(P.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,Un,Ys).mediaJoined}set mediaJoined(t){a(this,Un,Ys).mediaJoined=t}reset(){a(this,J).closeAllProducers(),a(this,J).closeAllConsumers(),a(this,Ft).clear(),a(this,jr).clear(),f(this,Ci,null),a(this,Js).stop(),a(this,J).stopAllTransports(),a(this,J).reset(),f(this,Js,new fh)}joinRoom(t,e){return u(this,arguments,function*(i,r,n=!1,s=!1,o={}){a(this,Un,Ys).mediaJoinAttempted=!0,f(this,qs,!0),n&&this.reset();try{return yield a(this,Js).push(()=>U(this,ip,dy).call(this,i,r,s,o),"joinRoom")}catch(c){return this.logger.error("Error in room joining process",{error:c}),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_FAILED),{roomJoined:!1}}})}initializeConnection(t,e){return u(this,arguments,function*(i,r,n=!1,s={}){return a(this,Ci)?a(this,Ci):(f(this,Ci,(()=>u(this,null,function*(){try{yield U(this,pl,sp).call(this,i,r,n,s)}catch(o){throw f(this,Ci,null),o}}))()),a(this,Ci))})}getConsumers(){return a(this,J).consumers}leaveRoom(){return u(this,null,function*(){a(this,J).stopAllTransports(),f(this,$s,!1),a(this,Un,Ys).mediaJoinAttempted=!1;const t={closeRoom:!1};a(this,Pt).sendMessagePromise(a(this,Ut).leaveRoom,mI.toBinary(t)).then(e=>{var i;(i=iC.fromBinary(e.payload))!=null&&i.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(t){return u(this,null,function*(){return this.createConsumers(t)})}createConsumers(t){return u(this,null,function*(){return t.length===0?Promise.resolve():a(this,J).createConsumers(t)})}closeConsumers(t){return u(this,null,function*(){if(!t.length)return;const e=t.reduce((i,r)=>{const n=a(this,J).producerIdToConsumerIdMap.get(r.producerId);return n?(i.push(n),i):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),i)},[]);yield a(this,J).closeConsumers(e)})}_shareWebcam(t,e){return u(this,null,function*(){const i=e==="video/VP9"?Ee.WEBCAM:Ee.WEBCAM_BACKUP,r=U(this,ft,Rt).call(this,i);if(r){const h=yield r;if(a(this,J).producers.has(h)){const m=a(this,J).producers.get(h);if(!m.closed)return yield m.replaceTrack({track:t}),yield this.resumeWebcam(i),t;yield this.disableWebcam(e)}return this._shareWebcam(t,e)}const n=[e].concat(Yt.filter(h=>h!==e)),s=U(this,pp,yy).call(this,t,n),o=Xn(this.context,"disableSimulcast"),c=a(this,lr)===Ae.CF?Z.ENABLE_CF_SIMULCAST:Z.ENABLE_HIVE_SIMULCAST;!o&&this.context.getValue("flagsmith").hasFeature(c)?(this.logger.info(`Simulcast enabled for SFU: ${a(this,lr)}`),s.encodings=Z1(this.context,t)):this.logger.info(`Simulcast disabled for webcam producer, SFU: ${a(this,lr)}`),this.context.getValue("flagsmith").hasFeature(Z.TRACK_HINT)&&(s.track.contentHint=this.context.getValue("flagsmith").getValue(Z.TRACK_HINT));const d=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,Ft).delete(i)},l=a(this,J).createProducer(s,d);return U(this,Qs,Bo).call(this,i,l.then(h=>h.id)),l.then(h=>h.track)})}shareWebcam(t){return u(this,null,function*(){var e;if(t===void 0)return null;const i=(e=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:e.toString();if(i)return this.logger.debug(`Calling _shareWebcam with forced video codec: ${i}`),this._shareWebcam(t,i);const r=Yt.filter(n=>{var s,o;return((o=(s=a(this,Uo).sender)==null?void 0:s.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===n))>=0&&a(this,zs).get(n).size>0});return r.length===0&&r.push(Yt[0]),yield Promise.all(r.map(n=>(this.logger.debug(`Calling _shareWebcam with video codec: ${n}`),this._shareWebcam(t,n)))),t})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:i}=t;if(e===void 0)return;const r={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1},n=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Ft).delete(Ee.SCREENSHARE_VIDEO),a(this,Ft).delete(Ee.SCREENSHARE_AUDIO)},s=a(this,J).createProducer(r,n);U(this,Qs,Bo).call(this,Ee.SCREENSHARE_VIDEO,s.then(c=>c.id));let o;if(i){const c={track:i,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1,zeroRtpOnPause:a(this,lr)!==Ae.CF},d=()=>{};o=a(this,J).createProducer(c,d),U(this,Qs,Bo).call(this,Ee.SCREENSHARE_AUDIO,o.then(l=>l.id))}yield Promise.all([s,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new xt("track undefined");const e=U(this,ft,Rt).call(this,Ee.MIC);if(e){const s=yield e;if(a(this,J).producers.has(s)){const o=a(this,J).producers.get(s);if(!o.closed){yield o.replaceTrack({track:t}),yield this.resumeMic(),a(this,Qt)&&(a(this,Qt).audioTrack=t,a(this,Qt).producerId=s,a(this,Qt).start());return}yield a(this,J).closeProducer(s,{stopTrack:!1})}yield this.shareMic(t);return}const i=U(this,hp,vy).call(this,t),r=()=>{a(this,Ft).delete(Ee.MIC)},n=a(this,J).createProducer(i,r);U(this,Qs,Bo).call(this,Ee.MIC,n.then(s=>s.id)),yield n.then(s=>{a(this,Qt)&&(a(this,Qt).audioTrack=s.track,a(this,Qt).producerId=s.id,a(this,Qt).start())})}catch(e){throw new _(e)}})}pauseMic(){return u(this,null,function*(){var t;const e=yield U(this,ft,Rt).call(this,Ee.MIC),i=a(this,J).producers.get(e);if(!i){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(i.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}i.pause(),(t=a(this,Qt))==null||t.stop();const r={producerId:i.id,pause:!0};a(this,Pt).sendMessage(a(this,Ut).toggleProducer,$c.toBinary(r))})}pauseWebcam(){return u(this,null,function*(){const t=yield U(this,ft,Rt).call(this,Ee.WEBCAM),e=yield U(this,ft,Rt).call(this,Ee.WEBCAM_BACKUP),i=a(this,J).producers.get(t),r=a(this,J).producers.get(e);if(!i&&!r){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const n=s=>{const o={producerId:s.id,pause:!0};a(this,Pt).sendMessage(a(this,Ut).toggleProducer,$c.toBinary(o))};i&&(i.pause(),n(i)),r&&(r.pause(),n(r))})}resumeMic(){return u(this,null,function*(){const t=yield U(this,ft,Rt).call(this,Ee.MIC),e=a(this,J).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,e);const i={producerId:e.id,pause:!1};a(this,Pt).sendMessage(a(this,Ut).toggleProducer,$c.toBinary(i))})}resumeWebcam(){return u(this,arguments,function*(t=Ee.WEBCAM){const e=yield U(this,ft,Rt).call(this,t),i=a(this,J).producers.get(e);if(!i){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!i.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}i.resume(),i.appData.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,i);const r={producerId:i.id,pause:!1};a(this,Pt).sendMessage(a(this,Ut).toggleProducer,$c.toBinary(r))})}disableWebcam(t){return u(this,null,function*(){const e=t==="video/VP9"?Ee.WEBCAM:Ee.WEBCAM_BACKUP,i=yield U(this,ft,Rt).call(this,e);U(this,up,fy).call(this,e),i&&(yield a(this,J).closeProducer(i))})}disableMic(){return u(this,null,function*(){var t;const e=yield U(this,ft,Rt).call(this,Ee.MIC);e&&(yield a(this,J).closeProducer(e)),(t=a(this,Qt))==null||t.stop(),a(this,Ft).delete(Ee.MIC)})}disableScreenShare(){return u(this,null,function*(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=yield U(this,ft,Rt).call(this,Ee.SCREENSHARE_VIDEO),e=yield U(this,ft,Rt).call(this,Ee.SCREENSHARE_AUDIO);t&&(yield a(this,J).closeProducer(t)),e&&(yield a(this,J).closeProducer(e)),a(this,jr).clear(),a(this,Ft).delete(Ee.SCREENSHARE_VIDEO),a(this,Ft).delete(Ee.SCREENSHARE_AUDIO)})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(t,e){return u(this,null,function*(){if(t){const i=yield U(this,ft,Rt).call(this,Ee.WEBCAM),r=yield U(this,ft,Rt).call(this,Ee.WEBCAM_BACKUP);yield a(this,J).closeProducer(i,{stopTrack:!1}),yield a(this,J).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const i=yield U(this,ft,Rt).call(this,Ee.SCREENSHARE_VIDEO);yield a(this,J).closeProducer(i,{stopTrack:!1}),this.shareScreen({video:e})}})}changeDisplayName(t,e){return u(this,null,function*(){const i={displayName:t,participantId:e!=null?e:this.peerId};if(!(yield a(this,J).socketHandler.changeDisplayName(i)))throw new Error("failed to change display name!")})}kick(t){const e={peerIds:[t]};a(this,J).socketHandler.kickPeer(e)}kickAll(){a(this,J).socketHandler.kickAll()}muteAll(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForPeer(t,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(t){return u(this,null,function*(){const e={participantId:t!=null?t:""};try{yield a(this,Pt).sendMessagePromise(a(this,Ut).globalPinPeer,PI.toBinary(e))}catch(i){this.logger.error("Error in pinning peer:",{error:i})}})}validateScreenShare(t){return this.peerId===t.peerId&&a(this,J).producers.get(t.producerId)&&a(this,jr).add(t.consumerPeerId),a(this,jr).size}switchConsumersToLayer(t,e){return u(this,null,function*(){const i=t.map(r=>this.getConsumers().get(r));a(this,J).switchConsumersToLayer(i,e)})}handleSocketEvents(){return u(this,null,function*(){a(this,Pt).on(a(this,Ut).peerProducerCreateBroadcast,({payload:t})=>{var e,i;if(this.mediaJoined)try{const{participantId:r,producerState:n}=DC.fromBinary(t);if(r===this.peerId)return;if(n!=null&&n.mimeType||(n.mimeType=n.kind===Ni.AUDIO?"audio/opus":"video/VP8"),n.kind===Ni.VIDEO&&!n.screenShare&&((i=(e=a(this,Uo).receiver)==null?void 0:e.video)==null?void 0:i.codecs.findIndex(s=>s.mimeType===Yt[0]))>=0&&a(this,Ks).get(Yt[0]).has(r)&&n.mimeType!==Yt[0]){this.logger.warn(`Ignoring producer: ${n.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${n}`),this.context.getValue("peerSessionStore").emit(P.NEW_PRODUCER,{peerId:r,producer:H(V({},n),{kind:n.kind===Ni.AUDIO?"audio":"video",producingPeerId:r})})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),a(this,Pt).on(a(this,Ut).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:i,producerState:{kind:r,pause:n,producerId:s}}=ff.fromBinary(t),o=r===Ni.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${s}, kind:${o}, paused:${n} payload: ${JSON.stringify(ff.fromBinary(t))}`),e===this.peerId&&i!==this.peerId&&n&&this.context.getValue("peerSessionStore").emit(o==="audio"?P.MUTE_SELF:P.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(P.PRODUCER_TOGGLE,{peerId:e,producerId:s,paused:n,kind:o}),Array.from(this.getConsumers().values()).filter(c=>c.producerId===s).forEach(c=>{c.paused!==n&&(this.logger.debug(`consumer state mismatched for ${c.id}. updating consumer pause state ${c.paused} to ${n}`),n?(c.pause(),this.context.getValue("peerSessionStore").emit(P.CONSUMER_PAUSED,{id:c.id})):(c.resume(),this.context.getValue("peerSessionStore").emit(P.CONSUMER_RESUMED,{id:c.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,Pt).on(a(this,Ut).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=Eu.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,jr).delete(e),a(this,J).consumers.forEach(i=>{i.peerId===e&&i.close()}),this.context.getValue("peerSessionStore").emit(P.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),a(this,Pt).on(a(this,Ut).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:i}}=VC.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(P.PRODUCER_CLOSED,{peerId:e,producerId:i});const r=a(this,J).producerIdToConsumerIdMap.get(i);if(!r){this.logger.warn(`no consumer found for producer:${i}`);return}this.logger.info(`closing consumer ${r}, producer id: ${i}`),a(this,J).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),a(this,J).producerIdToConsumerIdMap.delete(i),this.context.getValue("peerSessionStore").emit(P.CONSUMER_CLOSED,{id:r})}).catch(n=>{this.logger.error("error closing consumer",{error:n})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,Pt).on(a(this,Ut).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,qs)&&!a(this,$s)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_DISCONNECTED),a(this,hl).call(this))})})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,i)=>{const r=a(this,J).consumers.get(i);r&&this.context.getValue("peerSessionStore").emit(P.CONSUMER_SCORE_UPDATE,{id:i,kind:r.kind,peerId:r.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,i)=>{const r=Array.from(a(this,J).producers.values()).find(n=>n.id===i);r&&this.context.getValue("peerSessionStore").emit(P.PRODUCER_SCORE_UPDATE,{id:i,kind:r.kind,appData:r.appData,score:e.score,scoreStats:e})})})}handlePeerCapabilities(t,e){var i,r,n,s;for(let o=0;o<=Yt.length;o+=1){const c=Yt[o];if(((r=(i=e==null?void 0:e.receiver)==null?void 0:i.video)==null?void 0:r.codecs.findIndex(d=>d.mimeType===c))>=0||o===Yt.length-1){a(this,zs).get(c).add(t);break}}for(let o=0;o<=Yt.length;o+=1){const c=Yt[o];if(((s=(n=e==null?void 0:e.sender)==null?void 0:n.video)==null?void 0:s.codecs.findIndex(d=>d.mimeType===c))>=0||o===Yt.length-1){a(this,Ks).get(c).add(t);break}}}handlePeerLeaving(t){this.context.getValue("flagsmith").hasFeature(Z.FORCE_VIDEO_CODEC)||(a(this,Ks).forEach(e=>e.delete(t)),a(this,zs).forEach((e,i)=>{e.delete(t),!(e.size!==0||i===Yt[0])&&this.disableWebcam(i)}))}},ll=new WeakMap,ul=new WeakMap,Pt=new WeakMap,J=new WeakMap,Uo=new WeakMap,lr=new WeakMap,Ut=new WeakMap,qs=new WeakMap,$s=new WeakMap,Js=new WeakMap,hl=new WeakMap,Ci=new WeakMap,jr=new WeakMap,Fo=new WeakMap,Ks=new WeakMap,zs=new WeakMap,Ft=new WeakMap,Qt=new WeakMap,Un=new WeakSet,Ys=function(){return this.context.getValue("connectionHandler")},ip=new WeakSet,dy=function(t,e,i,r){return u(this,null,function*(){f(this,ul,t);try{return a(this,Ci)?yield a(this,Ci):yield U(this,pl,sp).call(this,t,e,i,r),U(this,np,uy).call(this,e),{roomJoined:yield U(this,rp,ly).call(this)}}catch(n){return this.logger.error("Failed to complete room join",{error:n}),{roomJoined:!1}}finally{f(this,Ci,null)}})},rp=new WeakSet,ly=function(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:t}=yield a(this,J).socketHandler.notifySelfJoinComplete();return f(this,ll,t.roomUuid),f(this,$s,!0),f(this,qs,!1),!0}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,!1}})},np=new WeakSet,uy=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:H(V({},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(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},pl=new WeakSet,sp=function(t,e,i,r){return u(this,null,function*(){var n,s;try{(s=a(this,Fo))!=null||f(this,Fo,U(n=Sy,ap,hy).call(n));const o=U(this,cp,py).call(this);yield U(this,dp,my).call(this,t,e,i,o),yield a(this,J).setupTransports({send:!0,recv:!0}),yield U(this,lp,gy).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}})},ap=new WeakSet,hy=function(){const{ipInfo:t}=pt();if(!(t!=null&&t.loc))return;const[e,i]=t.loc.split(",").map(parseFloat);return{latitude:e,longitude:i}},cp=new WeakSet,py=function(){var t;const e=(t=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:t.toString(),i=QD(e);return f(this,Uo,i),i},dp=new WeakSet,my=function(t,e,i,r){return u(this,null,function*(){yield xv((n,s)=>u(this,null,function*(){if(!a(this,Pt).isConnected){s(new Error("Socket is not connected"));return}n>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${n}`});try{yield a(this,J).socketHandler.joinRoom(e,t,r,i,a(this,Fo))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:this.context.getValue("flagsmith").hasFeature(Z.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3})})},lp=new WeakSet,gy=function(t){return u(this,null,function*(){if(!(a(this,lr)===Ae.HIVE||!this.context.getValue("flagsmith").hasFeature(Z.PRECREATE_PRODUCERS)||!t))try{const e=[];if(t.canProduceVideo===G.Allowed&&e.push(this.shareWebcam(gO(!1))),t.canProduceAudio===G.Allowed){const i=mO(!1);i&&e.push(this.shareMic(i))}e.length>0&&(yield Promise.all(e))}catch(e){this.logger.warn("Failed to precreate producers",{error:e})}})},ft=new WeakSet,Rt=function(t){return a(this,Ft).get(t)},Qs=new WeakSet,Bo=function(t,e){return a(this,Ft).set(t,e)},up=new WeakSet,fy=function(t){return a(this,Ft).delete(t)},hp=new WeakSet,vy=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:a(this,lr)!==Ae.CF}},pp=new WeakSet,yy=function(t,e){return{track:t,codecOptions:e?e.map(i=>({name:i.split("/")[1]})):[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},g(op,ap),op);let oe=Sy;pe([k.trace("MediaNodeClient.reset",{country:k.location.country})],oe.prototype,"reset",1),pe([k.trace("MediaNodeClient.joinRoom")],oe.prototype,"joinRoom",1),pe([k.trace("MediaNodeClient.leaveRoom")],oe.prototype,"leaveRoom",1),pe([k.trace("MediaNodeClient.activatePeers")],oe.prototype,"activatePeers",1),pe([k.trace("MediaNodeClient.createConsumers")],oe.prototype,"createConsumers",1),pe([k.trace("MediaNodeClient.closeConsumers")],oe.prototype,"closeConsumers",1),pe([k.trace("MediaNodeClient._shareWebcam")],oe.prototype,"_shareWebcam",1),pe([k.trace("MediaNodeClient.shareWebcam")],oe.prototype,"shareWebcam",1),pe([k.trace("MediaNodeClient.shareScreen")],oe.prototype,"shareScreen",1),pe([k.trace("MediaNodeClient.shareMic")],oe.prototype,"shareMic",1),pe([k.trace("MediaNodeClient.pauseMic")],oe.prototype,"pauseMic",1),pe([k.trace("MediaNodeClient.pauseWebcam")],oe.prototype,"pauseWebcam",1),pe([k.trace("MediaNodeClient.resumeMic")],oe.prototype,"resumeMic",1),pe([k.trace("MediaNodeClient.resumeWebcam")],oe.prototype,"resumeWebcam",1),pe([k.trace("MediaNodeClient.disableWebcam")],oe.prototype,"disableWebcam",1),pe([k.trace("HiveClient.disableMic")],oe.prototype,"disableMic",1),pe([k.trace("HiveClient.disableScreenShare")],oe.prototype,"disableScreenShare",1),pe([k.trace("MediaNodeClient.muteSelf")],oe.prototype,"muteSelf",1),pe([k.trace("MediaNodeClient.resetVideoProducers")],oe.prototype,"resetVideoProducers",1),pe([k.trace("MediaNodeClient.changeDisplayName")],oe.prototype,"changeDisplayName",1),pe([k.trace("MediaNodeClient.kickPeer")],oe.prototype,"kick",1),pe([k.trace("MediaNodeClient.kickAllPeers")],oe.prototype,"kickAll",1),pe([k.trace("MediaNodeClient.muteAll")],oe.prototype,"muteAll",1),pe([k.trace("MediaNodeClient.muteAllVideo")],oe.prototype,"muteAllVideo",1),pe([k.trace("MediaNodeClient.disableAudio")],oe.prototype,"disableAudio",1),pe([k.trace("MediaNodeClient.disableVideo")],oe.prototype,"disableVideo",1),pe([k.trace("MediaNodeClient.pinPeer")],oe.prototype,"pinPeer",1),pe([k.trace("MediaNodeClient.validateScreenShare")],oe.prototype,"validateScreenShare",1);function Ey(t,e,i){const r=t.getValue("roomNodeClient");if(r){if(r)return r;throw new Error("Room node client already set up.")}const n=new oe(t,e,i);return t.setValue("roomNodeClient",n),n}function ky(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch(i){t.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var yO=Object.defineProperty,SO=Object.getOwnPropertyDescriptor,Fn=(t,e,i,r)=>{for(var n=r>1?void 0:r?SO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&yO(e,i,n),n},Bn,ji,re,Bt,Xt,Ty;const by=(Ty=class{constructor(t,e,i,r){g(this,Bt),p(this,"self"),p(this,"authToken"),g(this,Bn,void 0),p(this,"viewType"),g(this,ji,void 0),g(this,re,void 0);const{socket:n}=i,s=t.getValue("authToken");this.self=e,f(this,re,t),this.viewType=r,this.authToken=s,f(this,Bn,n),f(this,ji,i),e.config.viewType!==Mt.Chat&&this.setupEvents()}get peerId(){return a(this,re).getValue("peerId")}get telemetry(){return a(this,re).getValue("telemetry")}get logger(){return a(this,re).getValue("logger")}get mediaJoined(){return a(this,re).getValue("connectionHandler").mediaJoined}static init(t,e,i,r,n){return u(this,null,function*(){const s=pt(),o=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield tt.__init__(t,i,r,n,n.name,c);t.setValue("self",d);const l=t.getValue("logger");if(navigator.product!=="ReactNative"){const h=!t.getValue("flagsmith").hasFeature(Z.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const m=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(m)}),t.getValue("callstats").devices("AUDIO",m==null?void 0:m.filter(v=>v.kind==="audioinput")),t.getValue("callstats").devices("VIDEO",m==null?void 0:m.filter(v=>v.kind==="videoinput")),t.getValue("callstats").devices("SPEAKER",m==null?void 0:m.filter(v=>v.kind==="audiooutput")),l.info("Callstats:: initializing");try{yield t.getValue("callstats").initialize({peerId:o,engineName:Te.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:t.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:Qg(t),skipConnectivityChecks:h}),l.info("Callstats:: initialized")}catch(v){l.error("Callstats:: initialization failed",{error:v})}}),0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new by(t,d,e,n.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:i,permissions:r,audioEnabled:n,videoEnabled:s,screenShareEnabled:o,screenShareTracks:c}=this.self;if(r.canProduceAudio===G.Allowed&&n)try{yield a(this,Bt,Xt).shareMic(e),this.self.audioEnabled||a(this,Bt,Xt).pauseMic()}catch(d){this.self.disableAudio()}if(r.canProduceVideo===G.Allowed&&s)try{const d=yield a(this,Bt,Xt).shareWebcam(i);d&&d.id!==i.id&&a(this,re).getValue("flagsmith").hasFeature(Z.EXP_RESHARE)&&(yield a(this,Bt,Xt).shareWebcam(d)),this.self.videoEnabled||a(this,Bt,Xt).pauseWebcam()}catch(d){this.self.disableVideo()}if(r.canProduceScreenshare===G.Allowed&&o)try{yield(t=a(this,Bt,Xt))==null?void 0:t.shareScreen({video:c.video,audio:c.audio})}catch(d){this.self.disableScreenShare()}})}kickHandler(t){return u(this,null,function*(){let e="kicked";(t==null?void 0:t.kickType)==="kickAll"&&(e="ended"),this.leaveRoom(e)})}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(t){return u(this,null,function*(){a(this,re).getValue("callstats").callEnded(),a(this,Bt,Xt).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){a(this,re).getValue("peerSessionStore").on(P.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),a(this,re).getValue("peerSessionStore").on(P.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,re).getValue("peerSessionStore").on(P.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,re).getValue("peerSessionStore").on(P.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,re).getValue("peerSessionStore").on(P.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),a(this,re).getValue("peerSessionStore").on(P.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&a(this,re).getValue("flagsmith").hasFeature(Z.REFRESH_ID_ON_DISCONNECTION)&&(e=Yr()),a(this,Bn).updateURL(e),a(this,re).getValue("telemetry").resetPeerId(e),pt().setHeader("dyte-tracing-id",e),Ki.remapContext(e,a(this,re)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,re).getValue("peerSessionStore").on(P.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,ji).on(F.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,ji).on(Xc.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&a(this,re).getValue("peerSessionStore").emit(P.UPDATE_PERMISSIONS,e.patch)})}),a(this,ji).on(F.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,ji).on(F.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,ji).on(F.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,re).getValue("peerSessionStore").onAsync(P.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,re).getValue("peerSessionStore").on(P.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:i,scoreStats:r})=>{var n;const s=(n=i==null?void 0:i.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:s,score:t,participantId:this.self.id,scoreStats:r})}),a(this,re).getValue("peerSessionStore").on(P.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),a(this,re).getValue("callstats").audioOff())})),a(this,re).getValue("peerSessionStore").on(P.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),a(this,re).getValue("callstats").videoOff())})),a(this,re).getValue("peerSessionStore").onAsync(P.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,re).getValue("peerSessionStore").on(P.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield a(this,ji).joinRoom(this.self);a(this,ji).socket.flush();const i=Ku(e.stageType);if(a(this,re).setValue("stageStatus",i,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),a(this,re).notify("stageStatus")}catch(e){throw this.logger.error("Error in joinRoom",{error:e}),e}})}leaveRoom(t="left"){return u(this,null,function*(){var e,i;if(t==="rejected"){try{(e=a(this,Bn))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),a(this,re).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),a(this,re).notify("stageStatus");try{(i=a(this,Bn))==null||i.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}ky(a(this,re)),yield a(this,re).getValue("roomSocketHandler").cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}joinMediaRoom(t=!1){return u(this,null,function*(){var e,i;const{peerId:r,viewType:n,meetingId:s,stageStatus:o,roomNodeOptions:c}=a(this,re).getAllValues(),{sfu:d}=c;try{if(n===Mt.Livestream){if(o!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}Ey(a(this,re),d,{socket:a(this,Bn),peerId:r})}const{canProduceAudio:l,canProduceVideo:h,canProduceScreenshare:m}=this.self.permissions,{roomJoined:v}=(i=yield(e=a(this,Bt,Xt))==null?void 0:e.joinRoom(this.self.name,s,t,t,{canProduceAudio:l,canProduceVideo:h,canProduceScreenshare:m}))!=null?i:{};if(!v)return;o==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(l){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:l}),new _("Error: could not join media room","0002")}})}leaveMediaRoom(t){return u(this,null,function*(){const e=a(this,re).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===Mt.Webinar)&&a(this,Bt,Xt)&&(a(this,Bt,Xt).mediaJoined&&t!=="disconnected"&&(yield a(this,Bt,Xt).leaveRoom()),!(t==="stageLeft"&&e===Mt.Livestream)&&(a(this,Bt,Xt).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()})}},Bn=new WeakMap,ji=new WeakMap,re=new WeakMap,Bt=new WeakSet,Xt=function(){return a(this,re).getValue("roomNodeClient")},Ty);let Hr=by;Fn([k.trace("SelfController.resetSelf")],Hr.prototype,"resetSelf",1),Fn([k.trace("SelfController.setupEvents")],Hr.prototype,"setupEvents",1),Fn([k.trace("SelfController.joinRoom")],Hr.prototype,"joinRoom",1),Fn([k.trace("SelfController.leaveRoom")],Hr.prototype,"leaveRoom",1),Fn([k.trace("SelfController.joinMediaRoom")],Hr.prototype,"joinMediaRoom",1),Fn([k.trace("SelfController.leaveMediaRoom")],Hr.prototype,"leaveMediaRoom",1),Fn([k.trace("SelfController.init")],Hr,"init",1);var ml;class EO{constructor(e){g(this,ml,void 0),f(this,ml,e)}on(e,i){let r;e===F.roomPeerCount?r=Sf.fromBinary.bind(Sf):r=Lf.fromBinary.bind(Lf),a(this,ml).on(e,({payload:n})=>{if(e===F.roomPeerCount&&!n)return;const s=r(n);i(s)})}}ml=new WeakMap;var gl,fl;class kO{constructor(e,i){g(this,gl,void 0),g(this,fl,void 0),f(this,gl,i),f(this,fl,e)}get logger(){return a(this,fl).getValue("logger")}on(e,i){let r,n;switch(e){case F.transcript:{r=ku.fromBinary.bind(ku),n=ku.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,gl).on(e,({payload:s})=>{let o=n;try{o=r(s)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}}gl=new WeakMap,fl=new WeakMap;var TO=Object.defineProperty,bO=Object.getOwnPropertyDescriptor,mp=(t,e,i,r)=>{for(var n=r>1?void 0:r?bO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&TO(e,i,n),n},Gr,Wo;class vl{constructor(e,i){g(this,Gr,void 0),g(this,Wo,void 0),f(this,Gr,i),f(this,Wo,e)}get logger(){return a(this,Wo).getValue("logger")}get telemetry(){return a(this,Wo).getValue("telemetry")}getPolls(){return a(this,Gr).sendMessagePromise(Xi.getPolls)}createPoll(e,i,r=!1,n=!1){const s={anonymous:r,hideVotes:n,question:e,options:i};return a(this,Gr).sendMessage(Xi.createPoll,bA.toBinary(s))}votePoll(e,i){const r={index:i,pollId:e};return a(this,Gr).sendMessage(Xi.votePoll,_A.toBinary(r))}on(e,i){let r,n;switch(e){case Xi.updatePoll:case Xi.createPoll:case Xi.votePoll:{r=Nu.fromBinary.bind(Nu),n=Nu.create();break}}a(this,Gr).on(e,({payload:s})=>{let o=n;try{o=r(s)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}removeListeners(e){a(this,Gr).removeListeners(e)}}Gr=new WeakMap,Wo=new WeakMap,mp([k.trace("PollSocketHandler.getPolls")],vl.prototype,"getPolls",1),mp([k.trace("PollSocketHandler.createPoll")],vl.prototype,"createPoll",1),mp([k.trace("PollSocketHandler.votePoll")],vl.prototype,"votePoll",1);var wO=Object.defineProperty,_O=Object.getOwnPropertyDescriptor,IO=(t,e,i,r)=>{for(var n=r>1?void 0:r?_O(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&wO(e,i,n),n},di;class wy{constructor(e,i){p(this,"socket"),g(this,di,void 0),f(this,di,e),this.socket=i,this.handleSocketEvents(),a(this,di).setValue("roomSocketHandler",this)}get telemetry(){return a(this,di).getValue("telemetry")}get logger(){return a(this,di).getValue("logger")}cleanup(){return u(this,null,function*(){var e;try{(e=this.socket)==null||e.disconnect()}catch(i){this.logger.error("roomSocketHandler::cleanup")}})}joinRoom(e){return u(this,null,function*(){var i;this.socket.joinAttempted=!0;const r={capabilities:[],peer:{displayName:(i=e.name)!=null?i:"Participant",customParticipantId:e.customParticipantId,peerId:e.id,userId:e.userId,displayPictureUrl:e.picture,waitlisted:!1},roomUuid:""},n=this.socket.sendMessagePromise(F.joinRoom,lP.toBinary(r));try{const{peer:s}=ts.fromBinary((yield n).payload);a(this,di).getValue("connectionHandler").socketJoined=!0,a(this,di).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_ROOM_JOINED,{peer:s});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=yield Promise.all([o,c]);return a(this,di).getValue("peerSessionStore").emit(P.ROOM_STATE,d),a(this,di).getValue("peerSessionStore").emit(P.SOCKET_PEERS,l),{peer:s}}catch(s){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:s}),new _("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,s)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return KP.fromBinary((yield this.socket.sendMessagePromise(F.getAllAddedParticipants)).payload).participants.map(e=>{var i=e,{id:r}=i,n=kc(i,["id"]);return H(V({},n),{userId:r})})}catch(e){return[]}})}getRoomPeers(e,i,r){return u(this,null,function*(){let n;try{const s={seachQuery:e,limit:i,offset:r},o=yield this.socket.sendMessagePromise(F.getRoomPeersInfo,eP.toBinary(s));n=wu.fromBinary(o.payload)}catch(s){this.logger.error("getRoomPeers::binary_decode_error",{error:s})}return n})}getRoomPeersNonPaginated(){return u(this,null,function*(){let e;try{const i=yield this.socket.sendMessagePromise(F.getRoomPeersInfo);e=wu.fromBinary(i.payload)}catch(i){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:i})}return e})}getStagePeers(){return u(this,null,function*(){let e;try{const i=yield this.socket.sendMessagePromise(F.getRoomPeersInfo);e=wu.fromBinary(i.payload)}catch(i){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:i})}return e})}getPeerInfo(e){return u(this,null,function*(){let i;try{const r=yield this.socket.sendMessagePromise(F.getPeerInfo,Tf.toBinary({peerId:e}));i=ts.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return i})}getRoomState(){return u(this,null,function*(){let e=kf.create();try{const i=yield this.socket.sendMessagePromise(F.getRoomInfo);e=kf.fromBinary(i.payload)}catch(i){this.logger.error("getRoomState::binary_decode_error",{error:i})}return e})}getRoomStageState(){return u(this,null,function*(){let e=Pf.create();try{const i=yield this.socket.sendMessagePromise(F.getRoomStageState);e=Pf.fromBinary(i.payload)}catch(i){this.logger.error("getRoomStageState::binary_decode_error",{error:i})}return e})}broadcastMessage(e,i){return u(this,null,function*(){const r={type:e,payload:new TextEncoder().encode(JSON.stringify(i)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(F.broadcastMessage,ba.toBinary(r))})}broadcastToMeetings(e,i,r){return u(this,null,function*(){const n={type:e,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:i,broadcastType:1};return this.socket.sendMessagePromise(F.broadcastToEntity,ba.toBinary(n))})}broadcastToPeers(e,i,r){return u(this,null,function*(){const n={type:e,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:i,broadcastType:0};return this.socket.sendMessage(F.broadcastToEntity,ba.toBinary(n))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(F.leaveRoom,hP.toBinary({}))})}kick(e){return u(this,null,function*(){const i={peerIds:[e]};this.socket.sendMessage(F.kick,If.toBinary(i))})}kickAll(e=!1){return u(this,null,function*(){const i={propagateKickAcrossRooms:e};this.socket.sendMessage(F.kickAll,uf.toBinary(i))})}getWaitingRoomRequests(){this.socket.sendMessage(F.getWaitingRoomRequests)}acceptWaitingRoomRequest(e){const i={userIds:e};this.socket.sendMessage(F.acceptWaitingRoomRequests,eR.toBinary(i))}rejectWaitingRoomRequest(e){const i={userIds:e};this.socket.sendMessage(F.denyWaitingRoomRequests,iR.toBinary(i))}updatePermissions(e,i){return u(this,null,function*(){const r={updatePeersPresets:[]};return e.forEach(n=>{r.updatePeersPresets.push({userIds:n,patch:i})}),this.socket.sendMessagePromise(Xc.updateUserPreset,AR.toBinary(r))})}handleSocketEvents(){this.socket.on(F.broadcastMessage,({payload:e})=>{try{const i=ba.fromBinary(e);a(this,di).getValue("peerSessionStore").emit(P.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(i.payload)),type:i.type,timestamp:i.timestamp})}catch(i){this.logger.error("failed to decode broadcast message:",i)}}),this.socket.on(F.broadcastToEntity,({payload:e})=>{try{const i=ba.fromBinary(e);a(this,di).getValue("peerSessionStore").emit(P.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(i.payload)),type:i.type,timestamp:i.timestamp})}catch(i){this.logger.error("failed to decode peer broadcast message:",i)}})}on(e,i){let r,n;switch(e){case F.joinRoom:case F.leaveRoom:case F.kick:case F.kickAll:{r=ts.fromBinary.bind(ts),n=ts.create();break}case F.getWaitingRoomRequests:{r=(s,o)=>s?Cf.fromBinary(s,o):{requests:[]},n=Cf.create();break}case F.recordingPaused:case F.recordingStarted:case F.recordingStopped:{r=Bf.fromBinary.bind(Bf);break}case Xc.updateUserPreset:{r=Mf.fromBinary.bind(Mf);break}case fi.peerJoinedBroadcast:case ii.peerJoinedBroadcast:{r=mf.fromBinary.bind(mf);break}case fi.selfJoinComplete:case ii.selfJoinComplete:{r=Su.fromBinary.bind(Su);break}case fi.globalPeerPinBroadcast:case ii.globalPeerPinBroadcast:{r=vf.fromBinary.bind(vf);break}case fi.selectedPeer:case ii.selectedPeer:{r=yu.fromBinary.bind(yu);break}case fi.selectedPeerDiff:case ii.selectedPeerDiff:{r=pf.fromBinary.bind(pf);break}case fi.leaveRoom:case ii.leaveRoom:{r=Eu.fromBinary.bind(Eu);break}}this.socket.on(e,({payload:s})=>{let o=n;if(!r)return i(void 0);try{o=r(s)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}getUserPermissions(e){return u(this,null,function*(){const i={userIds:[e]};try{const r=yield this.socket.sendMessagePromise(Xc.getUserPresets,wR.toBinary(i)),n=PR.fromBinary(r.payload).peerPresets[0],s=new TextDecoder().decode(n.preset),o=JSON.parse(s).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}})}}di=new WeakMap,IO([k.trace("RoomSocketHandler.joinRoom")],wy.prototype,"joinRoom",1);var Zt;class CO{constructor(e){g(this,Zt,void 0),f(this,Zt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield a(this,Zt).sendMessagePromise(F.getStageRequests);return e?Ou.fromBinary(e):{stageRequests:[]}})}requestAccess(){a(this,Zt).sendMessage(F.requestStageAccess)}cancelRequestAccess(){a(this,Zt).sendMessage(F.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,Zt).sendMessage(F.grantStageAccess,pA.toBinary(i))})}denyAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,Zt).sendMessage(F.denyStageAccess,gA.toBinary(i))})}joinStage(){return a(this,Zt).sendMessagePromise(F.joinStage,void 0,void 0,F.peerStageStatusUpdate)}leaveStage(e){const i={userIds:[e]};return a(this,Zt).sendMessagePromise(F.leaveStage,Uf.toBinary(i),void 0,F.peerStageStatusUpdate)}kick(e){const i={userIds:e};return a(this,Zt).sendMessagePromise(F.leaveStage,Uf.toBinary(i))}on(e,i){let r;switch(e){case F.grantStageAccess:case F.denyStageAccess:{r=void 0;break}case F.getStagePeers:{r=xf.fromBinary.bind(xf);break}case F.getStageRequests:case F.requestStageAccess:case F.cancelStageRequest:{r=Ou.fromBinary.bind(Ou);break}case F.peerStageStatusUpdate:{r=yf.fromBinary.bind(yf);break}}a(this,Zt).on(e,({payload:n,id:s})=>{if(!n||!r)return i(void 0,s);const o=r(n);return i(o,s)})}getPeerInfo(e){return u(this,null,function*(){const i=yield a(this,Zt).sendMessagePromise(F.getPeerInfo,Tf.toBinary({peerId:e}));return ts.fromBinary(i.payload)})}}Zt=new WeakMap;var it,yl;class PO{constructor(e,i){g(this,it,void 0),g(this,yl,void 0),f(this,it,i),f(this,yl,e)}get logger(){return a(this,yl).getValue("logger")}addPlugin(e,i){a(this,it).sendMessage($.addPlugin,MM.toBinary({pluginId:e,staggered:i}))}removePlugin(e){a(this,it).sendMessage($.removePlugin,DM.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield a(this,it).sendMessagePromise($.getPlugins);return e?tA.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,i,r){const n={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(i))};a(this,it).sendMessage($.customPluginEventToRoom,jM.toBinary(n),r)}customPluginEventToPeers(e,i,r,n){const s={pluginId:e,peerIds:i,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,it).sendMessage($.customPluginEventToPeers,GM.toBinary(s),n)}enablePluginForRoom(e,i){a(this,it).sendMessage($.enablePluginForRoom,NM.toBinary({pluginId:e}),i)}enablePluginForPeers(e,i,r){a(this,it).sendMessage($.enablePluginForPeers,UM.toBinary({pluginId:e,peerIds:i}),r)}disablePluginForRoom(e,i){a(this,it).sendMessage($.disablePluginForRoom,LM.toBinary({pluginId:e}),i)}disablePluginForPeers(e,i,r){a(this,it).sendMessage($.disablePluginForPeers,BM.toBinary({pluginId:e,peerIds:i}),r)}storeInsertKeys(e,i,r,n){const s={pluginId:e,storeName:i,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,it).sendMessage($.storeInsertKeys,Df.toBinary(s),n)}storeGetKeys(e,i,r,n){const s={pluginId:e,storeName:i,getKeys:r.map(o=>({storeKey:o.key}))};a(this,it).sendMessage($.storeGetKeys,KM.toBinary(s),n)}storeDeleteKeys(e,i,r,n){const s={pluginId:e,storeName:i,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,it).sendMessage($.storeDeleteKeys,YM.toBinary(s),n)}storeDelete(e,i,r){a(this,it).sendMessage($.storeDelete,XM.toBinary({pluginId:e,storeName:i}),r)}getPluginDataOld(e,i){this.logger.info("getPluginDataOld",{plugin:{id:e,storeName:i}})}storePluginDataOld(e,i,r){const n={pluginId:e,storeName:i,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};a(this,it).sendMessage($.storeInsertKeys,Df.toBinary(n))}on(e,i){let r;switch(e){case $.addPlugin:case $.enablePluginForPeers:case $.enablePluginForRoom:{r=Du.fromBinary.bind(Du);break}case $.removePlugin:case $.disablePluginForPeers:case $.disablePluginForRoom:{r=Of.fromBinary.bind(Of);break}case $.customPluginEventToPeers:case $.customPluginEventToRoom:{r=Vf.fromBinary.bind(Vf);break}case $.storeInsertKeys:case $.storeGetKeys:case $.storeDeleteKeys:case $.storeDelete:{r=Nf.fromBinary.bind(Nf);break}}a(this,it).on(e,({payload:n,id:s})=>{const o=r(n);return i(o,s)})}}it=new WeakMap,yl=new WeakMap;var RO=Object.defineProperty,MO=(t,e,i)=>e in t?RO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,AO=(t,e,i)=>(MO(t,typeof e!="symbol"?e+"":e,i),i),gp=(t,e,i)=>{if(!e.has(t))throw TypeError("Cannot "+i)},N=(t,e,i)=>(gp(t,e,"read from private field"),i?i.call(t):e.get(t)),_e=(t,e,i)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,i)},ce=(t,e,i,r)=>(gp(t,e,"write to private field"),r?r.call(t,i):e.set(t,i),i),Pe=(t,e,i)=>(gp(t,e,"access private method"),i),Sl={},DO={get exports(){return Sl},set exports(t){Sl=t}},Xs=typeof Reflect=="object"?Reflect:null,_y=Xs&&typeof Xs.apply=="function"?Xs.apply:function(t,e,i){return Function.prototype.apply.call(t,e,i)},El;Xs&&typeof Xs.ownKeys=="function"?El=Xs.ownKeys:Object.getOwnPropertySymbols?El=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:El=function(t){return Object.getOwnPropertyNames(t)};function OO(t){console&&console.warn&&console.warn(t)}var Iy=Number.isNaN||function(t){return t!==t};function me(){me.init.call(this)}DO.exports=me,Sl.once=xO,me.EventEmitter=me,me.prototype._events=void 0,me.prototype._eventsCount=0,me.prototype._maxListeners=void 0;var Cy=10;function kl(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(me,"defaultMaxListeners",{enumerable:!0,get:function(){return Cy},set:function(t){if(typeof t!="number"||t<0||Iy(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Cy=t}}),me.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},me.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Iy(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function Py(t){return t._maxListeners===void 0?me.defaultMaxListeners:t._maxListeners}me.prototype.getMaxListeners=function(){return Py(this)},me.prototype.emit=function(t){for(var e=[],i=1;i<arguments.length;i++)e.push(arguments[i]);var r=t==="error",n=this._events;if(n!==void 0)r=r&&n.error===void 0;else if(!r)return!1;if(r){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var c=n[t];if(c===void 0)return!1;if(typeof c=="function")_y(c,this,e);else for(var d=c.length,l=Oy(c,d),i=0;i<d;++i)_y(l[i],this,e);return!0};function Ry(t,e,i,r){var n,s,o;if(kl(i),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,i.listener?i.listener:i),s=t._events),o=s[e]),o===void 0)o=s[e]=i,++t._eventsCount;else if(typeof o=="function"?o=s[e]=r?[i,o]:[o,i]:r?o.unshift(i):o.push(i),n=Py(t),n>0&&o.length>n&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=o.length,OO(c)}return t}me.prototype.addListener=function(t,e){return Ry(this,t,e,!1)},me.prototype.on=me.prototype.addListener,me.prototype.prependListener=function(t,e){return Ry(this,t,e,!0)};function NO(){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 My(t,e,i){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:i},n=NO.bind(r);return n.listener=i,r.wrapFn=n,n}me.prototype.once=function(t,e){return kl(e),this.on(t,My(this,t,e)),this},me.prototype.prependOnceListener=function(t,e){return kl(e),this.prependListener(t,My(this,t,e)),this},me.prototype.removeListener=function(t,e){var i,r,n,s,o;if(kl(e),r=this._events,r===void 0)return this;if(i=r[t],i===void 0)return this;if(i===e||i.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete r[t],r.removeListener&&this.emit("removeListener",t,i.listener||e));else if(typeof i!="function"){for(n=-1,s=i.length-1;s>=0;s--)if(i[s]===e||i[s].listener===e){o=i[s].listener,n=s;break}if(n<0)return this;n===0?i.shift():VO(i,n),i.length===1&&(r[t]=i[0]),r.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this},me.prototype.off=me.prototype.removeListener,me.prototype.removeAllListeners=function(t){var e,i,r;if(i=this._events,i===void 0)return this;if(i.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):i[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete i[t]),this;if(arguments.length===0){var n=Object.keys(i),s;for(r=0;r<n.length;++r)s=n[r],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=i[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(r=e.length-1;r>=0;r--)this.removeListener(t,e[r]);return this};function Ay(t,e,i){var r=t._events;if(r===void 0)return[];var n=r[e];return n===void 0?[]:typeof n=="function"?i?[n.listener||n]:[n]:i?LO(n):Oy(n,n.length)}me.prototype.listeners=function(t){return Ay(this,t,!0)},me.prototype.rawListeners=function(t){return Ay(this,t,!1)},me.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Dy.call(t,e)},me.prototype.listenerCount=Dy;function Dy(t){var e=this._events;if(e!==void 0){var i=e[t];if(typeof i=="function")return 1;if(i!==void 0)return i.length}return 0}me.prototype.eventNames=function(){return this._eventsCount>0?El(this._events):[]};function Oy(t,e){for(var i=new Array(e),r=0;r<e;++r)i[r]=t[r];return i}function VO(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function LO(t){for(var e=new Array(t.length),i=0;i<e.length;++i)e[i]=t[i].listener||t[i];return e}function xO(t,e){return new Promise(function(i,r){function n(o){t.removeListener(e,s),r(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",n),i([].slice.call(arguments))}Ny(t,e,s,{once:!0}),e!=="error"&&UO(t,n,{once:!0})})}function UO(t,e,i){typeof t.on=="function"&&Ny(t,"error",e,i)}function Ny(t,e,i,r){if(typeof t.on=="function")r.once?t.once(e,i):t.on(e,i);else if(typeof t.addEventListener=="function")t.addEventListener(e,function n(s){r.once&&t.removeEventListener(e,n),i(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}class FO extends y{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 Vy=new FO;class Ly{static encode(e){return Vy.toBinary(e)}static decode(e){return Vy.fromBinary(new Uint8Array(e))}}function BO(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var qr;class WO{constructor(e={}){AO(this,"opts"),_e(this,qr,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},ce(this,qr,0)}wait(){return u(this,null,function*(){ce(this,qr,N(this,qr)+1);const e=BO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*QS(2,N(this,qr))));yield new Promise(i=>{setTimeout(i,e)})})}getAttempts(){return N(this,qr)}reset(){ce(this,qr,0)}}qr=new WeakMap;const $r={debug:0,info:1,warn:2,error:3};var Wn,jn;class jO{constructor(e){_e(this,Wn,void 0),_e(this,jn,void 0),ce(this,Wn,console),ce(this,jn,e)}debug(...e){$r[N(this,jn)]>$r.debug||N(this,Wn).debug("[Sockrates]:",...e)}info(...e){$r[N(this,jn)]>$r.info||N(this,Wn).info("[Sockrates]:",...e)}warn(...e){$r[N(this,jn)]>$r.warn||N(this,Wn).warn("[Sockrates]:",...e)}error(...e){$r[N(this,jn)]>$r.error||N(this,Wn).error("[Sockrates]:",...e)}}Wn=new WeakMap,jn=new WeakMap;var xy=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(xy||{});const HO="2",GO="3";var Ne,Zs,Re,We,Jr,rt,ur,Kr,Pi,ea,hr,fp,Uy,jo,Tl,vp,Fy,yp,By,bl,Sp,Ep,Wy,Ho,wl,Go,_l,Il,kp,ta,qo,$o,Cl;class qO{constructor(e,i){var r;_e(this,fp),_e(this,jo),_e(this,vp),_e(this,yp),_e(this,bl),_e(this,Ep),_e(this,Ho),_e(this,Go),_e(this,Il),_e(this,ta),_e(this,$o),_e(this,Ne,void 0),_e(this,Zs,void 0),_e(this,Re,void 0),_e(this,We,void 0),_e(this,Jr,void 0),_e(this,rt,void 0),_e(this,ur,void 0),_e(this,Kr,void 0),_e(this,Pi,void 0),_e(this,ea,void 0),_e(this,hr,void 0);var n,s,o,c,d,l,h,m,v;ce(this,Zs,e),ce(this,Jr,[]),ce(this,rt,new Sl),ce(this,ur,!0),ce(this,Pi,!1),ce(this,Re,i!=null?i:{}),(n=N(this,Re)).autoReconnect!=null||(n.autoReconnect=!0),(s=N(this,Re)).retryConnectionInterval!=null||(s.retryConnectionInterval=1e3),(o=N(this,Re)).pingTimeout!=null||(o.pingTimeout=3e4),(c=N(this,Re)).connectionTimeout!=null||(c.connectionTimeout=5e3),(d=N(this,Re)).debug!=null||(d.debug=!0),(l=N(this,Re)).maxReconnectionAttempts!=null||(l.maxReconnectionAttempts=10),(h=N(this,Re)).disconnectOnPingTimeout!=null||(h.disconnectOnPingTimeout=!0),(m=N(this,Re)).queueOnDisconnect!=null||(m.queueOnDisconnect=!1),(v=N(this,Re)).flushOnReconnect!=null||(v.flushOnReconnect=!1),ce(this,Kr,{code:void 0,reason:void 0}),ce(this,We,(r=N(this,Re).logger)!=null?r:new jO(N(this,Re).debug?"debug":"info")),ce(this,hr,new WO)}get readyState(){var e;return(e=N(this,Ne))==null?void 0:e.readyState}get url(){return N(this,Zs)}updateURL(e){ce(this,Zs,e),Pe(this,Ep,Wy).call(this)}get config(){return N(this,Re)}get sendQueue(){return N(this,Jr)}flush(){if(!N(this,Re).queueOnDisconnect)return!1;const e=[];return N(this,Jr).forEach(i=>{this.send(i.event,i.id,i.payload,i.metadata)||e.push(i)}),ce(this,Jr,e),N(this,Jr)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){N(this,We).debug("Websocket was already connecting or connected.");return}if(N(this,ur)!==!1)return new Promise((i,r)=>{Pe(this,ta,qo).call(this),Pe(this,$o,Cl).call(this);try{ce(this,Ne,new WebSocket(Pe(this,fp,Uy).call(this,N(this,Zs)))),N(this,Ne).binaryType="arraybuffer",N(this,We).debug("Connecting");const n=setTimeout(()=>{N(this,We).debug("Connection timeout. Closing socket"),ce(this,ur,!0),Pe(this,$o,Cl).call(this),N(this,Ne).close(3001,"Connection Timeout"),N(this,Re).autoReconnect&&!N(this,Pi)&&(N(this,rt).emit("reconnecting"),Pe(this,Ho,wl).call(this)),r(new Error("Connection timed out!"))},N(this,Re).connectionTimeout);N(this,Ne).onopen=()=>{N(this,We).debug(`Ready State: ${xy[N(this,Ne).readyState]}`),n&&clearTimeout(n),Pe(this,Il,kp).call(this),ce(this,Kr,{code:void 0,reason:void 0}),N(this,rt).emit("connected"),N(this,Re).flushOnReconnect&&this.flush(),i()},N(this,Ne).onclose=s=>{try{n&&clearTimeout(n);const{code:o,reason:c}=s;r(c),N(this,We).debug("Socket closed. Close event:",{event:s}),N(this,We).debug(`Connection closed code: ${o}`),N(this,We).debug(`Connection closed reason: ${c}`),N(this,Pi)||Pe(this,bl,Sp).call(this,o,c)}catch(o){Pe(this,jo,Tl).call(this,o)}},N(this,Ne).onerror=s=>{Pe(this,jo,Tl).call(this,s)},N(this,Ne).onmessage=s=>Pe(this,vp,Fy).call(this,s)}catch(n){Pe(this,jo,Tl).call(this,n,r)}})})}send(e,i,r,n){const s={event:e,id:i,payload:r,metadata:n};if(N(this,Re).queueOnDisconnect&&(!N(this,Ne)||N(this,Ne).readyState!==1))return N(this,We).debug("Queuing message since socket is not connected!",s),N(this,Jr).push(s),!1;const o=Ly.encode(s);return Pe(this,Go,_l).call(this,o)}emit(e,i,r,n){return this.send(e,i,r,n)}sendRaw(e){return Pe(this,Go,_l).call(this,e)}receive(e,i){return N(this,rt).on(e.toString(),i)}on(e,i){if(typeof e=="string"&&(e==="connected"||e==="disconnected"||e==="errored"||e==="reconnected"||e==="reconnecting"||e==="reconnectAttempt"||e==="reconnectFailure"||e==="failed")){N(this,rt).on(e,i);return}this.receive(e,i)}removeAllListeners(){N(this,rt).removeAllListeners()}removeReceiver(e,i){this.removeListener(e,i)}removeListener(e,i){N(this,rt).removeListener(e.toString(),i)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){N(this,rt).listeners(e.toString()).map(i=>this.removeListener(e,i))}disconnect(){ce(this,ur,!1),Pe(this,ta,qo).call(this),this.removeAllListeners(),ce(this,Kr,{code:1e3,reason:"Sockrates disconnect method called"}),N(this,Ne).close(1e3,"Sockrates disconnect method called.")}}Ne=new WeakMap,Zs=new WeakMap,Re=new WeakMap,We=new WeakMap,Jr=new WeakMap,rt=new WeakMap,ur=new WeakMap,Kr=new WeakMap,Pi=new WeakMap,ea=new WeakMap,hr=new WeakMap,fp=new WeakSet,Uy=function(t){if(t.startsWith("ws://")||t.startsWith("wss://"))return t;if(t.startsWith("https://"))return`wss://${t.substring(8)}`;if(t.startsWith("http://"))return`ws://${t.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},jo=new WeakSet,Tl=function(t,e){N(this,We).error("Error:",{error:t}),N(this,rt).emit("errored",{error:t}),e==null||e(t)},vp=new WeakSet,Fy=function(t){if(Pe(this,Il,kp).call(this),t.data===HO){N(this,We).debug("Received ping from server"),Pe(this,Go,_l).call(this,GO);return}const e=Ly.decode(t.data),{id:i,payload:r}=e;N(this,We).debug("Received message",{event:e.event,messageID:i}),N(this,rt).emit(e.event.toString(),{id:i,payload:r})},yp=new WeakSet,By=function(){return N(this,Ne).readyState===1},bl=new WeakSet,Sp=function(t,e){ce(this,Kr,{reason:e,code:t}),N(this,rt).emit("disconnected",{code:t,reason:e})},Ep=new WeakSet,Wy=function(){const{reason:t,code:e}=N(this,Kr);e&&e!==1e3&&N(this,ur)&&N(this,Re).autoReconnect&&!N(this,Pi)&&(N(this,We).debug(`Triggering reconnection due to ${t}.`),N(this,rt).emit("reconnecting"),Pe(this,Ho,wl).call(this))},Ho=new WeakSet,wl=function(t=!0){return u(this,null,function*(){if(t&&N(this,Pi)){N(this,We).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(N(this,Pi)||N(this,hr).reset(),N(this,Re).maxReconnectionAttempts!==null&&N(this,hr).getAttempts()>=N(this,Re).maxReconnectionAttempts){N(this,rt).emit("failed"),ce(this,Pi,!1);return}ce(this,Pi,!0),Pe(this,$o,Cl).call(this),Pe(this,ta,qo).call(this);try{if(yield N(this,hr).wait(),N(this,ur)===!1)return;if(N(this,We).debug(`Reconnection attempt ${N(this,hr).getAttempts()}`),N(this,rt).emit("reconnectAttempt",{attempt:N(this,hr).getAttempts()}),yield this.connect(),!Pe(this,yp,By).call(this))throw Error("Reconnect Failed");ce(this,Pi,!1),ce(this,Kr,{code:void 0,reason:void 0}),N(this,rt).emit("reconnected")}catch(e){N(this,We).debug("Failed to reconnect."),N(this,rt).emit("reconnectFailure",{attempt:N(this,hr).getAttempts()}),Pe(this,Ho,wl).call(this,!1)}})},Go=new WeakSet,_l=function(t){try{return N(this,Ne).send(t),!0}catch(e){return N(this,We).error(e.message),!1}},Il=new WeakSet,kp=function(){this.config.disconnectOnPingTimeout&&(N(this,We).debug("Resetting ping timeout"),Pe(this,ta,qo).call(this),ce(this,ea,setTimeout(()=>{var t;N(this,We).debug("Disconnecting the socket due to ping timeout"),ce(this,ur,!0);const e=3002,i="Ping timeout";(t=N(this,Ne))==null||t.close(e,i),Pe(this,bl,Sp).call(this,e,i)},N(this,Re).pingTimeout)))},ta=new WeakSet,qo=function(){N(this,ea)&&(clearTimeout(N(this,ea)),ce(this,ea,void 0))},$o=new WeakSet,Cl=function(){N(this,Ne)&&(N(this,Ne).onopen=void 0,N(this,Ne).onerror=void 0,N(this,Ne).onmessage=void 0,N(this,Ne).onclose=void 0)};var $O=Object.defineProperty,JO=Object.getOwnPropertyDescriptor,Pl=(t,e,i,r)=>{for(var n=r>1?void 0:r?JO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&$O(e,i,n),n};const jy=65535,KO=3e3;var Hn,Ve,Le,je,Ri,vt,Rl,Tp,Ml,bp,Hy;const Gy=(Hy=class{constructor(t,{peerId:e,meetingId:i,authToken:r,capabilities:n}){g(this,Le),g(this,Rl),g(this,Ml),g(this,Hn,void 0),g(this,Ve,void 0),p(this,"roomName"),p(this,"authToken"),p(this,"capabilities"),g(this,Ri,void 0),g(this,vt,void 0);var s;if(!e||!i||!r)throw new _("peerId, meetingId, or authToken can not be empty","0404");f(this,Ri,void 0),f(this,vt,t),this.capabilities=n,this.roomName=i,this.authToken=r,f(this,Hn,U(this,Rl,Tp).call(this,e)),f(this,Ve,new qO(a(this,Hn),{autoReconnect:!0,disconnectOnPingTimeout:(s=n.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Le,je).socketJoinAttempted}set joinAttempted(t){a(this,Le,je).socketJoinAttempted=t}get telemetry(){return a(this,vt).getValue("telemetry")}get logger(){return a(this,vt).getValue("logger")}get peerId(){return a(this,vt).getValue("peerId")}updateURL(t){t!==this.peerId&&(f(this,Hn,U(this,Rl,Tp).call(this,t)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Ve).updateURL(a(this,Hn))}static getSocketEdgeDomain(t){return an({servicePrefix:"socket-edge",baseURI:t})}get url(){return a(this,Hn)}connect(){return u(this,null,function*(){a(this,Le,je).socketJoinAttempted=!0,yield a(this,Ve).connect(),a(this,Le,je).socketJoinAttempted=!0,a(this,Le,je).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return u(this,null,function*(){a(this,Le,je).socketJoinAttempted=!1,a(this,Ve).disconnect(),a(this,Le,je).socketJoinAttempted=!0,a(this,Le,je).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return a(this,Ve).readyState===1}catch(t){return!1}}sendMessage(t,e,i){const r={};return a(this,vt).getValue("telemetry").injectContext(r),a(this,Ve).send(t,i!=null?i:U(this,Ml,bp).call(this),e,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(t,e,i,r){const n=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:n,protobuf:e,messageId:i,resp:r})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:i,messageId:r,resp:n}){const s=n!=null?n:t;return new Promise((o,c)=>{const d=(S,T)=>{a(this,Ve).removeListener(s,S),a(this,Ve).removeListener(jy,T),a(this,Ve).removeListener(ii.errorResponse,T),a(this,Ve).removeListener(fi.errorResponse,T)},l=r!=null?r:U(this,Ml,bp).call(this),h={};a(this,vt).getValue("telemetry").injectContext(h);const m=({id:S,payload:T})=>{if(l===S){let M;try{const I=$I.fromBinary(T);M=new Error(I.errorMessage)}catch(I){M=new Error("failed to parse error message",{cause:I});try{const R=JC.fromBinary(T);M=new Error(R.message)}catch(R){M=new Error("failed to parse error message",{cause:R})}}c(M),d(v,m)}},v=({id:S,payload:T})=>{l===S&&(o({id:S,payload:T}),d(v,m))};a(this,Ve).on(s,v),a(this,Ve).on(jy,m),a(this,Ve).on(ii.errorResponse,m),a(this,Ve).on(fi.errorResponse,m),setTimeout(()=>{d(v,m),c(new Error(`request timeout for callback eventId:${t}`))},e),a(this,Ve).send(t,l,i,new TextEncoder().encode(JSON.stringify(h)))})}on(t,e){a(this,Ve).on(t,e)}onStateEvent(t,e){a(this,Ve).on(t,e)}removeListener(t,e){a(this,Ve).removeListener(t,e)}removeListeners(t){a(this,Ve).removeListeners(t)}flush(){return a(this,Ve).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){this.logger.info("SocketService::Connected to socket-edge"),a(this,Ri)&&(clearTimeout(a(this,Ri)),f(this,Ri,void 0)),a(this,Le,je).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:k.location.country});const{recv:r,send:n}=(i=a(this,Le,je).mediaState)!=null?i:{};r!=null&&r.state&&(r==null?void 0:r.state)!==Ms.CONNECTED||n!=null&&n.state&&(n==null?void 0:n.state)!==Ms.CONNECTED?a(this,vt).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Le,je).joinAttempted}):f(this,Ri,setTimeout(()=>{a(this,vt).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Le,je).joinAttempted}),f(this,Ri,void 0)},KO)),a(this,Le,je).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnecting to socket-edge",{country:k.location.country}),a(this,Le,je).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),a(this,Le,je).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),a(this,Le,je).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Le,je).mediaJoinAttempted}}),a(this,Ri)&&(clearTimeout(a(this,Ri)),f(this,Ri,void 0)),a(this,vt).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Le,je).mediaJoinAttempted}),a(this,Le,je).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){this.logger.info("SocketService::Failed to connect to socket-edge",{country:k.location.country}),a(this,vt).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_FAILED),a(this,Le,je).updateSocketConnectionState("failed")}))}},Hn=new WeakMap,Ve=new WeakMap,Le=new WeakSet,je=function(){return a(this,vt).getValue("connectionHandler")},Ri=new WeakMap,vt=new WeakMap,Rl=new WeakSet,Tp=function(t){let e=Gy.getSocketEdgeDomain(a(this,vt).getValue("baseURI"));typeof Xn(a(this,vt),"socket_server_base")=="string"&&(e=Xn(a(this,vt),"socket_server_base"));const i=`wss://${e}`,r=new URL(`${i}/ws`),n=this.peerId,s=H(V({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},n!==t&&{oldPeerID:n}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>Jc[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0});return Object.entries(s).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},Ml=new WeakSet,bp=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Hy);let Jo=Gy;Pl([k.trace("SocketService.connect")],Jo.prototype,"connect",1),Pl([k.trace("SocketService.disconnect")],Jo.prototype,"disconnect",1),Pl([k.trace("SocketService.sendMessagePromise")],Jo.prototype,"sendMessagePromise",1),Pl([k.trace("SocketService.sendMessagePromiseWithTimeout")],Jo.prototype,"sendMessagePromiseWithTimeout",1);class zO{constructor(e){p(this,"socketService"),this.socketService=e}handleConnectedRoomsDumpRaw({payload:e}){var i;const r=EP.fromBinary(e),n=r.meetings.map(s=>{var o;return{id:s.id,title:s.title,participants:(o=s.participants)!=null?o:[]}});return{parentMeeting:{id:r.parentMeeting.id,title:r.parentMeeting.title,participants:(i=r.parentMeeting.participants)!=null?i:[]},meetings:n}}handleTransferPeerRaw({payload:e}){const i=$P.fromBinary(e);return{authToken:i.authToken,meetingId:i.meetingId}}handleMovedPeerRaw({payload:e}){const i=_f.fromBinary(e);return{meetingId:i.meetingId,customParticipantId:i.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:e}){return wf.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}handleConnectedRoomsDeletedRaw({payload:e}){return LP.fromBinary(e).payloads}getConnectedRoomsDump(){return u(this,null,function*(){const e=yield this.socketService.sendMessagePromise(F.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(e)})}createConnectedRooms(e){return u(this,null,function*(){const{payload:i}=yield this.socketService.sendMessagePromise(F.createConnectedRooms,wP.toBinary({payloads:e}));return wf.fromBinary(i).payloads.map(r=>({id:r.id,title:r.title}))})}updateConnectedRooms(e){return u(this,null,function*(){})}disableConnectedRooms(e){return u(this,null,function*(){const i=e.map(n=>({id:n})),r=yield this.socketService.sendMessagePromise(F.deleteConnectedRooms,NP.toBinary({payloads:i}));return this.handleConnectedRoomsDeletedRaw(r)})}movePeersBetweenRooms(e){return u(this,null,function*(){try{const i=yield this.socketService.sendMessagePromise(F.movePeers,jP.toBinary({sourceMeetingId:e.sourceMeetingId,destinationMeetingId:e.destinationMeetingId,participants:e.participants}));return new TextDecoder().decode(i.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(i){return{success:!1,error:i}}})}}var YO=Object.defineProperty,QO=Object.getOwnPropertyDescriptor,XO=(t,e,i,r)=>{for(var n=r>1?void 0:r?QO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&YO(e,i,n),n},Hi;class qy extends Wt{constructor(e){const i=e.getValue("logger");super(i),p(this,"meetings",[]),p(this,"parentMeeting",null),g(this,Hi,void 0),f(this,Hi,e)}get supportsConnectedMeetings(){return a(this,Hi).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.
20
20
  Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`)}getConnectedMeetings(){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),yield a(this,Hi).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield a(this,Hi).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e)).map(i=>({id:i.id,title:i.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield a(this,Hi).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(i=>({meetingId:i.id,title:i.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=this.meetings.map(r=>e.includes(r.id)&&r.participants.length!==0?this.moveParticipants(r.id,this.parentMeeting.id,r.participants.map(n=>n.id)):Promise.resolve());return yield Promise.all(i),yield a(this,Hi).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e)})}moveParticipants(e,i,r){return u(this,null,function*(){this.validateConnectedMeetingsAction();const n=yield a(this,Hi).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:r.map(s=>({id:s}))});return n.success&&this.moveSuccessHandler(e,i,r),n})}moveParticipantsWithCustomPreset(e,i,r){return u(this,null,function*(){this.validateConnectedMeetingsAction();const n=yield a(this,Hi).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:r});return n.success&&this.moveSuccessHandler(e,i,r.map(s=>s.id)),n})}moveSuccessHandler(e,i,r){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(s=>s.participants)].forEach(s=>n.set(s.id,s)),i===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(r.map(s=>n.get(s)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(s=>!r.includes(s.id))),this.meetings=this.meetings.map(s=>{if(i===s.id){const o=s.participants.concat(r.map(c=>n.get(c)));return H(V({},s),{participants:o})}if(e===s.id){const o=s.participants.filter(c=>!r.includes(c.id));return H(V({},s),{participants:o})}return s})}}Hi=new WeakMap,XO([Dt({maxInvocations:60,period:60})],qy.prototype,"getConnectedMeetings",1);var ZO=Object.defineProperty,eN=Object.getOwnPropertyDescriptor,wp=(t,e,i,r)=>{for(var n=r>1?void 0:r?eN(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&ZO(e,i,n),n},Ie,$y;const Jy=($y=class{constructor(t){p(this,"connectedMeetings"),g(this,Ie,void 0),f(this,Ie,t),this.connectedMeetings=new qy(t)}get telemetry(){return a(this,Ie).getValue("telemetry")}get logger(){return a(this,Ie).getValue("logger")}static init(t){const e=new Jy(t);return e.connectedMeetings.supportsConnectedMeetings&&(e.setupEvents(),t.getValue("self").once("roomJoined",()=>e.getConnectedMeetings())),e}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,Ie).getValue("connectedMeetingsSocketHandler").socketService.on(F.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,Ie).getValue("connectedMeetingsSocketHandler").socketService.on(F.transferPeer,this.handleTransferPeer.bind(this)),a(this,Ie).getValue("connectedMeetingsSocketHandler").socketService.on(F.movedPeer,this.handleMovedPeer.bind(this)),a(this,Ie).getValue("connectedMeetingsSocketHandler").socketService.on(F.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,Ie).getValue("connectedMeetingsSocketHandler").socketService.on(F.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(t){const e=a(this,Ie).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:i}){var r,n,s,o;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
21
21
  Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",i);const c={video:a(this,Ie).getValue("self").videoEnabled,audio:a(this,Ie).getValue("self").audioEnabled};try{a(this,Ie).getValue("self").cleanupEvents(),yield a(this,Ie).getValue("meeting").leave("connected-meeting")}catch(l){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(r=a(this,Ie).getValue("meeting"))==null?void 0:r.meta)==null?void 0:n.meetingId}`,{error:l})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${i}`);const d=yield Qy.init(H(V({},a(this,Ie).getValue("options")),{cachedUserDetails:null,defaults:H(V(V({},a(this,Ie).getValue("options").defaults),c),{mediaHandler:a(this,Ie).getValue("self")}),authToken:e}));this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(s=d==null?void 0:d.meta)==null?void 0:s.meetingId}`);try{const{hidden:l}=a(this,Ie).getValue("self");d.self.setName(a(this,Ie).getValue("self").name),yield d.join(),l&&d.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: ${(o=d==null?void 0:d.meta)==null?void 0:o.meetingId}`),this.connectedMeetings.emit("meetingChanged",d),d})}handleConnectedRoomsDump(t){const e=a(this,Ie).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(t);this.connectedMeetings.meetings=e.meetings.map(i=>({id:i.id,title:i.title,participants:i.participants||[]})),this.connectedMeetings.parentMeeting={id:e.parentMeeting.id,title:e.parentMeeting.title,participants:e.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(t){return a(this,Ie).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=a(this,Ie).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(t),i=new Map;this.connectedMeetings.meetings.forEach(r=>{i.set(r.id,r)}),e.forEach(r=>{i.has(r.id)?i.get(r.id).title=r.title:i.set(r.id,H(V({},r),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(i.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=a(this,Ie).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(t).map(i=>i.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(i=>!e.includes(i.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Ie=new WeakMap,$y);let Al=Jy;wp([k.trace("ConnectedMeetingsController.getConnectedMeetings")],Al.prototype,"getConnectedMeetings",1),wp([k.trace("ConnectedMeetingsController.setupEvents")],Al.prototype,"setupEvents",1),wp([k.trace("ConnectedMeetingsController.switchMeeting")],Al.prototype,"switchMeeting",1);var tN=Object.defineProperty,iN=Object.getOwnPropertyDescriptor,Dl=(t,e,i,r)=>{for(var n=r>1?void 0:r?iN(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&tN(e,i,n),n};const ia=class{constructor(t,e,i){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=t,this.storesManager=e.storesManager,this.metaController=e.metaController,this.selfController=e.selfController,this.chatController=e.chatController,this.pollController=e.pollController,this.stageController=e.stageController,this.pluginController=e.pluginController,this.recordingController=e.recordingController,this.internalsController=e.internalsController,this.participantController=e.participantController,this.livestreamController=e.livestreamController,this.connectedMeetingsController=e.connectedMeetingsController,this.telemetry=i.getValue("telemetry"),this.logger=i.getValue("logger")}static init(t){return u(this,null,function*(){var e,i;const{peerId:r,apiBase:n,authToken:s,meetingId:o,organizationId:c,cachedUserDetails:d,logger:l}=t.getAllValues();if(ky(t),Te.isSupported()===!1)throw new _("Browser not supported","0010",l,!0);const h=n1(t,{authToken:s,baseURL:n,cachedUserDetails:d});h.setRoomName(o),h.setRoomUUID(o),h.setOrganizationId(c),h.setHeader("dyte-tracing-id",r),t.setValue("apiClient",h);const m=new B1(t);t.setValue("connectionHandler",m);const v=ia.createSocketService(t),S=v.connect(),T=h.getUserDetails(),M=h.getPlugins();let I=Ae.HIVE,R,j="";try{yield ia.setupFlagsmith(t)}catch(ae){l.error("Failed to setup flagsmith",{error:ae})}try{yield S}catch(ae){l.error("[Controller]: Failed to connect to socket server:",{error:ae})}try{({sfu:I,meetingTitle:j}=yield h.getRoomNodeData()),R=yield T,l.info(`SFU ${I} is being used.`),t.setValue("presetName",R.preset.name),t.setValue("roomNodeOptions",{sfu:I})}catch(ae){l.error("Failed to get room metadata",{error:ae})}const W=wD.init(R.preset,!t.getValue("modules").theme),b=qD.init(t,W.viewType,R.preset.permissions),te=ia.setupControllers(v,t,R,M,j,W,b);R1(W)&&((e=ia.createRoomNodeClient(t,v).initializeConnection(R.participant.name,o,!1,b))==null||e.catch(ae=>{l.error("[Controller]: Failed to queue partial media room promise:",{error:ae})})),k.location.country=(i=h.ipInfo)==null?void 0:i.country;const{controllers:ie}=yield te;return I_(),new ia(n,ie,t)})}static setupFlagsmith(t){return u(this,null,function*(){var e;const{peerId:i,baseURI:r,overrides:n,meetingId:s,organizationId:o,logger:c}=t.getAllValues(),d=__(s),l=H(V({entity:vu.PEER,clientId:o,isAnonUser:!o,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:d,roomName:s},Te.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const h=(e=n==null?void 0:n.whitelabelled_flags_endpoint)==null||e?an({servicePrefix:"flags",baseURI:r}):"edge.api.flagsmith.com";yield t.getValue("flagsmith").identify(`${vu.PEER}_${i}`,JSON.parse(JSON.stringify(l)),!1,5e3,h,c),c.info("flagsmith::allFlags",{flags:JSON.stringify(t.getValue("flagsmith").getAllFlags())},!0)}catch(h){c.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,i,r,n,s,o){return u(this,null,function*(){var c,d,l;const h=e.getValue("modules"),{participant:m}=i,v=e.getValue("defaults"),S=e.getValue("logger"),{sfu:T}=e.getValue("roomNodeOptions"),{viewType:M,mediaConstraints:{audio:I}}=s;e.setValue("viewType",M),e.setValue("defaults",V({mediaConfiguration:{audio:{enableHighBitrate:(c=I.enableHighBitrate)!=null?c:!1,enableStereo:(d=I.enableStereo)!=null?d:!1}}},v)),e.setValue("maxPreferredStreams",Te.isMobile()?s.maxVideoStreams.mobile:s.maxVideoStreams.desktop);let R,j,W,b,te,ie,ae,De,st;const ei=new kO(e,t),A=new zO(t);e.setValue("connectedMeetingsSocketHandler",A);const E=new vl(e,t),w=new ri(e,t),B=new CO(t),de=new wy(e,t),Ke=new PO(e,t),x=new EO(t),C=new un(e,t),le=yield Hr.init(e,de,m,o,s);e.setValue("selfController",le);const $n=yield av.init(e,le.self,de,ei,n);if(h.participant&&(De=new sr(e,le.self,de,T)),(l=h.e2ee)!=null&&l.enabled&&h.e2ee.manager.init(S,e.getValue("peerSessionStore")),h.chat&&(j=yield Zi.init(e,w,C,le.self,De.participants)),h.internals&&(te=yield Qu.init(e)),h.livestream&&s.viewType===Mt.Livestream&&e.getValue("flagsmith").hasFeature(Z.LIVESTREAM)&&(ae=new wv(e,le.self,x)),s.viewType!==Mt.Chat){if(h.poll&&(R=yield Zf.init(e,le.self,E)),h.recording&&(ie=new mv(e,le.self,de)),h.stage&&(W=new ov(e,B,de,le.self,De.participants)),h.plugin){if(!De)throw new _("The plugin module cannot be initialized without the `participant` module","0102");const pr=yield r;b=yield Ua.init(e,pr,Ke,w,j==null?void 0:j.chat,le.self,De.participants,n)}if(h.connectedMeetings&&(st=yield Al.init(e)),h.pip){const pr=yield R_._init(e,le.self);e.setValue("pip",pr)}}const Jn={storesManager:new DD(e,Ke),pollController:R,selfController:le,metaController:$n,chatController:j,stageController:W,pluginController:b,recordingController:ie,internalsController:te,livestreamController:ae,participantController:De,connectedMeetingsController:st};return{theme:s,permissions:o,controllers:Jn}})}static createRoomNodeClient(t,e){const{peerId:i,roomNodeOptions:r}=t.getAllValues(),{sfu:n}=r;return Ey(t,n,{socket:e,peerId:i})}static createSocketService(t){const{peerId:e,meetingId:i,authToken:r}=t.getAllValues(),n=["PING"];return new Jo(t,{peerId:e,meetingId:i,authToken:r,capabilities:n})}};let Ko=ia;Dl([k.trace("Controller.init")],Ko,"init",1),Dl([k.trace("setupFlagsmith")],Ko,"setupFlagsmith",1),Dl([k.trace("Controller.createRoomNodeClient")],Ko,"createRoomNodeClient",1),Dl([k.trace("Controller.createSocketService")],Ko,"createSocketService",1);class rN{constructor(){p(this,"battery"),p(this,"logger"),p(this,"init",e=>u(this,null,function*(){this.logger=e;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(i){e.error("Error getting battery",i)}})),p(this,"updateChargeInfo",()=>{var e;this.logger.log(`Battery charging? ${(e=this.battery)!=null&&e.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 e,i;"getBattery"in navigator&&((e=this.battery)==null||e.removeEventListener("chargingchange",this.updateChargeInfo),(i=this.battery)==null||i.removeEventListener("levelchange",this.updateLevelInfo))})}}const Ky=new rN;function nN(t,e){t.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c \u2014 not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.dyte.io/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:i,orgId:r,participantId:n}=JSON.parse(atob(t.split(".")[1]));if(!i)throw Error(`Received V1 auth token ${t}`);let s="dyte.io";e&&(s=e);const o=`https://${an({servicePrefix:"api",baseURI:s})}`;return{meetingId:i,orgId:r,participantId:n,baseURI:s,apiBase:o}}catch(i){throw new _("Invalid auth token","0004")}}var Gn,ra,na,Ol,_p,zy;class sN{constructor(){g(this,_p),g(this,Gn,new Audio),g(this,ra,new MediaStream),g(this,na,new Map),g(this,Ol,void 0),a(this,Gn).srcObject=a(this,ra),a(this,Gn).autoplay=!0}playTracks(e){return u(this,null,function*(){return e.forEach(i=>{a(this,na).has(i.id)||(a(this,ra).addTrack(i),a(this,na).set(i.id,i))}),this.play()})}setSpeakerDevice(e){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,Gn).setSinkId(e)}removeTrack(e){const i=a(this,na).get(e);i&&(a(this,ra).removeTrack(i),a(this,na).delete(e))}play(){return u(this,null,function*(){return a(this,Gn).srcObject=a(this,ra),a(this,Gn).play().catch(e=>{U(this,_p,zy).call(this,e)})})}onError(e){f(this,Ol,e)}}Gn=new WeakMap,ra=new WeakMap,na=new WeakMap,Ol=new WeakMap,_p=new WeakSet,zy=function(t){var e;(e=a(this,Ol))==null||e.call(this,t)};var sa;class aN extends sN{constructor(){super(),g(this,sa,void 0),f(this,sa,new Map)}addParticipantTrack(e,i){a(this,sa).set(e,i.id),this.playTracks([i])}removeParticipantTrack(e){const i=a(this,sa).get(e);i&&this.removeTrack(i),a(this,sa).delete(e)}}sa=new WeakMap;var oN=Object.defineProperty,cN=Object.getOwnPropertyDescriptor,Nl=(t,e,i,r)=>{for(var n=r>1?void 0:r?cN(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&oN(e,i,n),n},nt,qn,Yy;let zr=(Yy=class{constructor(t,e){g(this,nt,void 0),g(this,qn,void 0),f(this,qn,t),f(this,nt,e)}get peerId(){return a(this,qn).getValue("peerId")}static initMedia(t={},e=!1,i=void 0){var r;const n=(r=i==null?void 0:i.peerId)!=null?r:Yr(),s=Ki.createContext(n,{peerId:n}),o=s.getValue("logger");o.init(s);const c=new Nv(o);return c.init(t,e,s),s.setValue("defaults",{mediaHandler:c}),c}static init(t){return u(this,null,function*(){var e,i,r,n,s,o,c;Te.init();const{mediaHandler:d}=(e=t.defaults)!=null?e:{},l=(d==null?void 0:d.peerId)||((r=(i=t==null?void 0:t.cachedUserDetails)==null?void 0:i.peerId)!=null?r:Yr()),{authToken:h,baseURI:m}=t,v=nN(h,m),{meetingId:S}=v,T=kc(v,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const M=zr.setupContext(l,t,S,T),I=M.getValue("telemetry"),R=M.getValue("logger");tE(R),Ky.init(R),I.init(M,{roomName:S,userId:T.participantId,organizationId:T.orgId,peerId:l},(s=(n=t.modules)==null?void 0:n.tracing)!=null?s:!0),R.init(M),R.info("DyteClient::init::options",{dyteClientInitOptions:H(V({},t),{authToken:`${(o=t.authToken)==null?void 0:o.slice(0,10)}...
22
- ${(c=t.authToken)==null?void 0:c.slice(-10)}`})});const j=yield Ko.init(M),W=new zr(M,j);return M.setValue("meeting",W),W})}static setupContext(t,e,i,r){var n,s;const o=Ki.createContext(t,e),c=V(V({},v_),e==null?void 0:e.modules),d=e.defaults||{audio:!0,video:!0};return o.setValue("options",e),o.setValue("peerId",t),o.setValue("modules",c),o.setValue("sdkName","web-core"),o.setValue("meetingId",i),o.setValue("apiBase",r.apiBase),o.setValue("baseURI",r.baseURI),o.setValue("userId",r.participantId),o.setValue("organizationId",r.orgId),o.setValue("authToken",e.authToken),o.setValue("overrides",(n=e.overrides)!=null?n:{}),o.setValue("env",y_({baseURI:r.baseURI})),o.setValue("defaults",d),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",yi(e.cachedUserDetails)),o.setValue("sdkVersion","3.1.5-staging.3"),(s=e.modules)!=null&&s.experimentalAudioPlayback&&o.setValue("audioPlayback",new aN),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,nt);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){var e;Ky.cleanup(),a(this,qn).getValue("peerSessionStore").reset(),(e=a(this,qn).getValue("roomSocketHandler"))==null||e.cleanup();const{selfController:i}=a(this,nt);return i.leaveRoom(t)})}get participants(){var t;return(t=a(this,nt).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,nt).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,nt).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,nt).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,nt).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,nt).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,nt).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,nt).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,nt).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,nt).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,nt).stageController)==null?void 0:t.stage}get stores(){return a(this,nt).storesManager}get audio(){return a(this,qn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,nt).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)})}},nt=new WeakMap,qn=new WeakMap,Yy);Nl([ht("0002"),er.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],zr.prototype,"join",1),Nl([ht("0003")],zr.prototype,"leave",1),Nl([ht("0001"),er.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],zr,"init",1),zr=Nl([ht("0000")],zr);const Qy=zr;return Qy}();
22
+ ${(c=t.authToken)==null?void 0:c.slice(-10)}`})});const j=yield Ko.init(M),W=new zr(M,j);return M.setValue("meeting",W),W})}static setupContext(t,e,i,r){var n,s;const o=Ki.createContext(t,e),c=V(V({},v_),e==null?void 0:e.modules),d=e.defaults||{audio:!0,video:!0};return o.setValue("options",e),o.setValue("peerId",t),o.setValue("modules",c),o.setValue("sdkName","web-core"),o.setValue("meetingId",i),o.setValue("apiBase",r.apiBase),o.setValue("baseURI",r.baseURI),o.setValue("userId",r.participantId),o.setValue("organizationId",r.orgId),o.setValue("authToken",e.authToken),o.setValue("overrides",(n=e.overrides)!=null?n:{}),o.setValue("env",y_({baseURI:r.baseURI})),o.setValue("defaults",d),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",yi(e.cachedUserDetails)),o.setValue("sdkVersion","3.1.5"),(s=e.modules)!=null&&s.experimentalAudioPlayback&&o.setValue("audioPlayback",new aN),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,nt);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){var e;Ky.cleanup(),a(this,qn).getValue("peerSessionStore").reset(),(e=a(this,qn).getValue("roomSocketHandler"))==null||e.cleanup();const{selfController:i}=a(this,nt);return i.leaveRoom(t)})}get participants(){var t;return(t=a(this,nt).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,nt).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,nt).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,nt).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,nt).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,nt).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,nt).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,nt).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,nt).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,nt).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,nt).stageController)==null?void 0:t.stage}get stores(){return a(this,nt).storesManager}get audio(){return a(this,qn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,nt).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)})}},nt=new WeakMap,qn=new WeakMap,Yy);Nl([ht("0002"),er.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],zr.prototype,"join",1),Nl([ht("0003")],zr.prototype,"leave",1),Nl([ht("0001"),er.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],zr,"init",1),zr=Nl([ht("0000")],zr);const Qy=zr;return Qy}();
package/dist/index.cjs.js CHANGED
@@ -20,4 +20,4 @@ ${t}`}const ra={maxInvocations:5,period:1};function Ft(t,e){return function(i,r,
20
20
  maxEnergy: ${a(this,Tn)}`),n===-1/0||i<1e-6?{energy:0,isVoice:!1}:((!a(this,Dr)||n<a(this,Dr))&&f(this,Dr,n),(!a(this,Tn)||n>a(this,Tn))&&f(this,Tn,n),{energy:(n-a(this,Dr))/(a(this,Tn)-a(this,Dr))*10||0,isVoice:r})},Cd=new WeakSet,Nh=function(t){return t<5},Vh=new WeakSet,Py=function(t=a(this,$s)){var e;if(!a(this,Fi)||!t){a(this,Br).getValue("flagsmith").hasFeature(Z.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,Fi)}`);return}const i={producerId:a(this,Fi),energy:Math.round(t),silent:U(e=sl,Cd,Nh).call(e,t)};f(this,jo,i.silent),this.reportRequest(i)},mu=new WeakSet,Og=function(t){const e=Math.log10(t);return Math.round(e)},g(Lh,Cd),g(Lh,mu);const EO=(t=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const i=new window.MediaStreamTrackGenerator({kind:"audio"}),r=i.writable.getWriter(),n=48e3,s=128,o=1;let c=0,d=null;const l=()=>u(void 0,null,function*(){try{const m=new Float32Array(s*o),v=new window.AudioData({format:"f32",sampleRate:n,numberOfFrames:s,numberOfChannels:o,timestamp:c,data:m});c+=s/n*1e6,yield r.ready,yield r.write(v)}catch{d&&clearInterval(d),r.releaseLock(),i.writable.abort()}});d=window.setInterval(l,100);const h=new MediaStream([i]).getAudioTracks()[0];return h.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),i.writable.abort()}),Object.assign(h,{fakeTracks:"fakeTracks:fakeAudioTrack"}),h.enabled=t,h}catch{}const e=window.AudioContext||window.webkitAudioContext;if(e)try{const i=new e;if(!i||i.state!=="running"||!i.destination)return;const r=i.createOscillator();r.frequency.value=0,r.type="sine";const n=i.createGain();n.gain.value=0,r.connect(n);const s=i.createMediaStreamDestination();n.connect(s),r.start();const o=s.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=t,o):void 0}catch{return}},kO=(t=!1)=>{var e,i;const r=new MediaStream().getVideoTracks()[0],n=document.createElement("canvas");n.height=(e=r==null?void 0:r.getSettings().height)!=null?e:720,n.width=(i=r==null?void 0:r.getSettings().width)!=null?i:1280;const s=n.getContext("2d");s.fillStyle="black",s.fillRect(0,0,n.width,n.height),setInterval(()=>{s.fillStyle="black",s.fillRect(0,0,n.width,n.height)},1e3);const o=n.captureStream().getVideoTracks()[0];return Object.assign(o,{fakeTracks:"fakeTracks:fakeVideoTrack"}),o.enabled=t,o};var TO=Object.defineProperty,bO=Object.getOwnPropertyDescriptor,me=(t,e,i,r)=>{for(var n=r>1?void 0:r?bO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&TO(e,i,n),n};const Ht=["video/VP9","video/VP8"];var Oc,Nc,St,J,Za,qi,At,ls,us,hs,Vc,hi,Sr,eo,ps,ms,Dt,Gt,on,gs,gu,Ng,fu,Vg,vu,Lg,Lc,yu,Su,Eu,xg,ku,Ug,Tu,Fg,bu,Bg,lt,Et,fs,to,wu,Wg,_u,jg,Iu,Hg;const Ry=(Eu=class{constructor(t,e,i){g(this,on),g(this,gu),g(this,fu),g(this,vu),g(this,Lc),g(this,ku),g(this,Tu),g(this,bu),g(this,lt),g(this,fs),g(this,wu),g(this,_u),g(this,Iu),p(this,"context"),p(this,"authToken"),p(this,"e2ee"),g(this,Oc,void 0),g(this,Nc,void 0),g(this,St,void 0),g(this,J,void 0),g(this,Za,void 0),g(this,qi,void 0),g(this,At,void 0),g(this,ls,void 0),g(this,us,void 0),g(this,hs,void 0),g(this,Vc,void 0),g(this,hi,null),g(this,Sr,void 0),g(this,eo,void 0),g(this,ps,void 0),g(this,ms,void 0),g(this,Dt,void 0),g(this,Gt,void 0);var r,n;this.context=t;const{socket:s}=i;this.mediaJoined=!1,f(this,ps,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,ms,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,qi,e),f(this,St,s),f(this,ls,!1),f(this,J,new fO(t,s,e)),f(this,At,a(this,J).events),f(this,Sr,new Set),f(this,Dt,new Map),f(this,us,!1),f(this,hs,new sh(t.getValue("logger"))),e===De.CF&&f(this,Gt,new Lh(this.context,a(this,J).socketHandler.audioActivity.bind(a(this,J).socketHandler))),this.e2ee=(n=(r=t.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,Vc,op(()=>u(this,null,function*(){if(!a(this,on,gs).mediaJoinAttempted)return;const{roomJoined:o}=yield this.joinRoom(a(this,Nc),a(this,Oc),!0,!0);o&&(this.context.getValue("peerSessionStore").emit(P.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(P.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,on,gs).mediaJoined}set mediaJoined(t){a(this,on,gs).mediaJoined=t}reset(){a(this,J).closeAllProducers(),a(this,J).closeAllConsumers(),a(this,Dt).clear(),a(this,Sr).clear(),f(this,hi,null),a(this,hs).stop(),a(this,J).stopAllTransports(),a(this,J).reset(),f(this,hs,new sh)}joinRoom(t,e){return u(this,arguments,function*(i,r,n=!1,s=!1,o={}){a(this,on,gs).mediaJoinAttempted=!0,f(this,ls,!0),n&&this.reset();try{return yield a(this,hs).push(()=>U(this,gu,Ng).call(this,i,r,s,o),"joinRoom")}catch(c){return this.logger.error("Error in room joining process",{error:c}),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_FAILED),{roomJoined:!1}}})}initializeConnection(t,e){return u(this,arguments,function*(i,r,n=!1,s={}){return a(this,hi)?a(this,hi):(f(this,hi,(()=>u(this,null,function*(){try{yield U(this,Lc,yu).call(this,i,r,n,s)}catch(o){throw f(this,hi,null),o}}))()),a(this,hi))})}getConsumers(){return a(this,J).consumers}leaveRoom(){return u(this,null,function*(){a(this,J).stopAllTransports(),f(this,us,!1),a(this,on,gs).mediaJoinAttempted=!1;const t={closeRoom:!1};a(this,St).sendMessagePromise(a(this,At).leaveRoom,EI.toBinary(t)).then(e=>{var i;(i=cC.fromBinary(e.payload))!=null&&i.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(t){return u(this,null,function*(){return this.createConsumers(t)})}createConsumers(t){return u(this,null,function*(){return t.length===0?Promise.resolve():a(this,J).createConsumers(t)})}closeConsumers(t){return u(this,null,function*(){if(!t.length)return;const e=t.reduce((i,r)=>{const n=a(this,J).producerIdToConsumerIdMap.get(r.producerId);return n?(i.push(n),i):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),i)},[]);yield a(this,J).closeConsumers(e)})}_shareWebcam(t,e){return u(this,null,function*(){const i=e==="video/VP9"?Se.WEBCAM:Se.WEBCAM_BACKUP,r=U(this,lt,Et).call(this,i);if(r){const h=yield r;if(a(this,J).producers.has(h)){const m=a(this,J).producers.get(h);if(!m.closed)return yield m.replaceTrack({track:t}),yield this.resumeWebcam(i),t;yield this.disableWebcam(e)}return this._shareWebcam(t,e)}const n=[e].concat(Ht.filter(h=>h!==e)),s=U(this,Iu,Hg).call(this,t,n),o=Xs(this.context,"disableSimulcast"),c=a(this,qi)===De.CF?Z.ENABLE_CF_SIMULCAST:Z.ENABLE_HIVE_SIMULCAST;!o&&this.context.getValue("flagsmith").hasFeature(c)?(this.logger.info(`Simulcast enabled for SFU: ${a(this,qi)}`),s.encodings=sD(this.context,t)):this.logger.info(`Simulcast disabled for webcam producer, SFU: ${a(this,qi)}`),this.context.getValue("flagsmith").hasFeature(Z.TRACK_HINT)&&(s.track.contentHint=this.context.getValue("flagsmith").getValue(Z.TRACK_HINT));const d=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,Dt).delete(i)},l=a(this,J).createProducer(s,d);return U(this,fs,to).call(this,i,l.then(h=>h.id)),l.then(h=>h.track)})}shareWebcam(t){return u(this,null,function*(){var e;if(t===void 0)return null;const i=(e=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:e.toString();if(i)return this.logger.debug(`Calling _shareWebcam with forced video codec: ${i}`),this._shareWebcam(t,i);const r=Ht.filter(n=>{var s,o;return((o=(s=a(this,Za).sender)==null?void 0:s.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===n))>=0&&a(this,ms).get(n).size>0});return r.length===0&&r.push(Ht[0]),yield Promise.all(r.map(n=>(this.logger.debug(`Calling _shareWebcam with video codec: ${n}`),this._shareWebcam(t,n)))),t})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:i}=t;if(e===void 0)return;const r={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ie.isElectron()},stopTracks:!1},n=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Dt).delete(Se.SCREENSHARE_VIDEO),a(this,Dt).delete(Se.SCREENSHARE_AUDIO)},s=a(this,J).createProducer(r,n);U(this,fs,to).call(this,Se.SCREENSHARE_VIDEO,s.then(c=>c.id));let o;if(i){const c={track:i,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ie.isElectron()},stopTracks:!1,zeroRtpOnPause:a(this,qi)!==De.CF},d=()=>{};o=a(this,J).createProducer(c,d),U(this,fs,to).call(this,Se.SCREENSHARE_AUDIO,o.then(l=>l.id))}yield Promise.all([s,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new xt("track undefined");const e=U(this,lt,Et).call(this,Se.MIC);if(e){const s=yield e;if(a(this,J).producers.has(s)){const o=a(this,J).producers.get(s);if(!o.closed){yield o.replaceTrack({track:t}),yield this.resumeMic(),a(this,Gt)&&(a(this,Gt).audioTrack=t,a(this,Gt).producerId=s,a(this,Gt).start());return}yield a(this,J).closeProducer(s,{stopTrack:!1})}yield this.shareMic(t);return}const i=U(this,_u,jg).call(this,t),r=()=>{a(this,Dt).delete(Se.MIC)},n=a(this,J).createProducer(i,r);U(this,fs,to).call(this,Se.MIC,n.then(s=>s.id)),yield n.then(s=>{a(this,Gt)&&(a(this,Gt).audioTrack=s.track,a(this,Gt).producerId=s.id,a(this,Gt).start())})}catch(e){throw new _(e)}})}pauseMic(){return u(this,null,function*(){var t;const e=yield U(this,lt,Et).call(this,Se.MIC),i=a(this,J).producers.get(e);if(!i){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(i.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}i.pause(),(t=a(this,Gt))==null||t.stop();const r={producerId:i.id,pause:!0};a(this,St).sendMessage(a(this,At).toggleProducer,gc.toBinary(r))})}pauseWebcam(){return u(this,null,function*(){const t=yield U(this,lt,Et).call(this,Se.WEBCAM),e=yield U(this,lt,Et).call(this,Se.WEBCAM_BACKUP),i=a(this,J).producers.get(t),r=a(this,J).producers.get(e);if(!i&&!r){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const n=s=>{const o={producerId:s.id,pause:!0};a(this,St).sendMessage(a(this,At).toggleProducer,gc.toBinary(o))};i&&(i.pause(),n(i)),r&&(r.pause(),n(r))})}resumeMic(){return u(this,null,function*(){const t=yield U(this,lt,Et).call(this,Se.MIC),e=a(this,J).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,e);const i={producerId:e.id,pause:!1};a(this,St).sendMessage(a(this,At).toggleProducer,gc.toBinary(i))})}resumeWebcam(){return u(this,arguments,function*(t=Se.WEBCAM){const e=yield U(this,lt,Et).call(this,t),i=a(this,J).producers.get(e);if(!i){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!i.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}i.resume(),i.appData.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,i);const r={producerId:i.id,pause:!1};a(this,St).sendMessage(a(this,At).toggleProducer,gc.toBinary(r))})}disableWebcam(t){return u(this,null,function*(){const e=t==="video/VP9"?Se.WEBCAM:Se.WEBCAM_BACKUP,i=yield U(this,lt,Et).call(this,e);U(this,wu,Wg).call(this,e),i&&(yield a(this,J).closeProducer(i))})}disableMic(){return u(this,null,function*(){var t;const e=yield U(this,lt,Et).call(this,Se.MIC);e&&(yield a(this,J).closeProducer(e)),(t=a(this,Gt))==null||t.stop(),a(this,Dt).delete(Se.MIC)})}disableScreenShare(){return u(this,null,function*(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=yield U(this,lt,Et).call(this,Se.SCREENSHARE_VIDEO),e=yield U(this,lt,Et).call(this,Se.SCREENSHARE_AUDIO);t&&(yield a(this,J).closeProducer(t)),e&&(yield a(this,J).closeProducer(e)),a(this,Sr).clear(),a(this,Dt).delete(Se.SCREENSHARE_VIDEO),a(this,Dt).delete(Se.SCREENSHARE_AUDIO)})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(t,e){return u(this,null,function*(){if(t){const i=yield U(this,lt,Et).call(this,Se.WEBCAM),r=yield U(this,lt,Et).call(this,Se.WEBCAM_BACKUP);yield a(this,J).closeProducer(i,{stopTrack:!1}),yield a(this,J).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const i=yield U(this,lt,Et).call(this,Se.SCREENSHARE_VIDEO);yield a(this,J).closeProducer(i,{stopTrack:!1}),this.shareScreen({video:e})}})}changeDisplayName(t,e){return u(this,null,function*(){const i={displayName:t,participantId:e!=null?e:this.peerId};if(!(yield a(this,J).socketHandler.changeDisplayName(i)))throw new Error("failed to change display name!")})}kick(t){const e={peerIds:[t]};a(this,J).socketHandler.kickPeer(e)}kickAll(){a(this,J).socketHandler.kickAll()}muteAll(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForPeer(t,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(t){return u(this,null,function*(){const e={participantId:t!=null?t:""};try{yield a(this,St).sendMessagePromise(a(this,At).globalPinPeer,NI.toBinary(e))}catch(i){this.logger.error("Error in pinning peer:",{error:i})}})}validateScreenShare(t){return this.peerId===t.peerId&&a(this,J).producers.get(t.producerId)&&a(this,Sr).add(t.consumerPeerId),a(this,Sr).size}switchConsumersToLayer(t,e){return u(this,null,function*(){const i=t.map(r=>this.getConsumers().get(r));a(this,J).switchConsumersToLayer(i,e)})}handleSocketEvents(){return u(this,null,function*(){a(this,St).on(a(this,At).peerProducerCreateBroadcast,({payload:t})=>{var e,i;if(this.mediaJoined)try{const{participantId:r,producerState:n}=UC.fromBinary(t);if(r===this.peerId)return;if(n!=null&&n.mimeType||(n.mimeType=n.kind===Bi.AUDIO?"audio/opus":"video/VP8"),n.kind===Bi.VIDEO&&!n.screenShare&&((i=(e=a(this,Za).receiver)==null?void 0:e.video)==null?void 0:i.codecs.findIndex(s=>s.mimeType===Ht[0]))>=0&&a(this,ps).get(Ht[0]).has(r)&&n.mimeType!==Ht[0]){this.logger.warn(`Ignoring producer: ${n.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${n}`),this.context.getValue("peerSessionStore").emit(P.NEW_PRODUCER,{peerId:r,producer:q(V({},n),{kind:n.kind===Bi.AUDIO?"audio":"video",producingPeerId:r})})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),a(this,St).on(a(this,At).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:i,producerState:{kind:r,pause:n,producerId:s}}=Mm.fromBinary(t),o=r===Bi.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${s}, kind:${o}, paused:${n} payload: ${JSON.stringify(Mm.fromBinary(t))}`),e===this.peerId&&i!==this.peerId&&n&&this.context.getValue("peerSessionStore").emit(o==="audio"?P.MUTE_SELF:P.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(P.PRODUCER_TOGGLE,{peerId:e,producerId:s,paused:n,kind:o}),Array.from(this.getConsumers().values()).filter(c=>c.producerId===s).forEach(c=>{c.paused!==n&&(this.logger.debug(`consumer state mismatched for ${c.id}. updating consumer pause state ${c.paused} to ${n}`),n?(c.pause(),this.context.getValue("peerSessionStore").emit(P.CONSUMER_PAUSED,{id:c.id})):(c.resume(),this.context.getValue("peerSessionStore").emit(P.CONSUMER_RESUMED,{id:c.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,St).on(a(this,At).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=ju.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,Sr).delete(e),a(this,J).consumers.forEach(i=>{i.peerId===e&&i.close()}),this.context.getValue("peerSessionStore").emit(P.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),a(this,St).on(a(this,At).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:i}}=WC.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(P.PRODUCER_CLOSED,{peerId:e,producerId:i});const r=a(this,J).producerIdToConsumerIdMap.get(i);if(!r){this.logger.warn(`no consumer found for producer:${i}`);return}this.logger.info(`closing consumer ${r}, producer id: ${i}`),a(this,J).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),a(this,J).producerIdToConsumerIdMap.delete(i),this.context.getValue("peerSessionStore").emit(P.CONSUMER_CLOSED,{id:r})}).catch(n=>{this.logger.error("error closing consumer",{error:n})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,St).on(a(this,At).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,ls)&&!a(this,us)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_DISCONNECTED),a(this,Vc).call(this))})})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,i)=>{const r=a(this,J).consumers.get(i);r&&this.context.getValue("peerSessionStore").emit(P.CONSUMER_SCORE_UPDATE,{id:i,kind:r.kind,peerId:r.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,i)=>{const r=Array.from(a(this,J).producers.values()).find(n=>n.id===i);r&&this.context.getValue("peerSessionStore").emit(P.PRODUCER_SCORE_UPDATE,{id:i,kind:r.kind,appData:r.appData,score:e.score,scoreStats:e})})})}handlePeerCapabilities(t,e){var i,r,n,s;for(let o=0;o<=Ht.length;o+=1){const c=Ht[o];if(((r=(i=e==null?void 0:e.receiver)==null?void 0:i.video)==null?void 0:r.codecs.findIndex(d=>d.mimeType===c))>=0||o===Ht.length-1){a(this,ms).get(c).add(t);break}}for(let o=0;o<=Ht.length;o+=1){const c=Ht[o];if(((s=(n=e==null?void 0:e.sender)==null?void 0:n.video)==null?void 0:s.codecs.findIndex(d=>d.mimeType===c))>=0||o===Ht.length-1){a(this,ps).get(c).add(t);break}}}handlePeerLeaving(t){this.context.getValue("flagsmith").hasFeature(Z.FORCE_VIDEO_CODEC)||(a(this,ps).forEach(e=>e.delete(t)),a(this,ms).forEach((e,i)=>{e.delete(t),!(e.size!==0||i===Ht[0])&&this.disableWebcam(i)}))}},Oc=new WeakMap,Nc=new WeakMap,St=new WeakMap,J=new WeakMap,Za=new WeakMap,qi=new WeakMap,At=new WeakMap,ls=new WeakMap,us=new WeakMap,hs=new WeakMap,Vc=new WeakMap,hi=new WeakMap,Sr=new WeakMap,eo=new WeakMap,ps=new WeakMap,ms=new WeakMap,Dt=new WeakMap,Gt=new WeakMap,on=new WeakSet,gs=function(){return this.context.getValue("connectionHandler")},gu=new WeakSet,Ng=function(t,e,i,r){return u(this,null,function*(){f(this,Nc,t);try{return a(this,hi)?yield a(this,hi):yield U(this,Lc,yu).call(this,t,e,i,r),U(this,vu,Lg).call(this,e),{roomJoined:yield U(this,fu,Vg).call(this)}}catch(n){return this.logger.error("Failed to complete room join",{error:n}),{roomJoined:!1}}finally{f(this,hi,null)}})},fu=new WeakSet,Vg=function(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:t}=yield a(this,J).socketHandler.notifySelfJoinComplete();return f(this,Oc,t.roomUuid),f(this,us,!0),f(this,ls,!1),!0}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,!1}})},vu=new WeakSet,Lg=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:q(V({},Ie.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(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},Lc=new WeakSet,yu=function(t,e,i,r){return u(this,null,function*(){var n,s;try{(s=a(this,eo))!=null||f(this,eo,U(n=Ry,Su,xg).call(n));const o=U(this,ku,Ug).call(this);yield U(this,Tu,Fg).call(this,t,e,i,o),yield a(this,J).setupTransports({send:!0,recv:!0}),yield U(this,bu,Bg).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}})},Su=new WeakSet,xg=function(){const{ipInfo:t}=pt();if(!(t!=null&&t.loc))return;const[e,i]=t.loc.split(",").map(parseFloat);return{latitude:e,longitude:i}},ku=new WeakSet,Ug=function(){var t;const e=(t=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:t.toString(),i=rO(e);return f(this,Za,i),i},Tu=new WeakSet,Fg=function(t,e,i,r){return u(this,null,function*(){yield my((n,s)=>u(this,null,function*(){if(!a(this,St).isConnected){s(new Error("Socket is not connected"));return}n>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${n}`});try{yield a(this,J).socketHandler.joinRoom(e,t,r,i,a(this,eo))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:this.context.getValue("flagsmith").hasFeature(Z.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3})})},bu=new WeakSet,Bg=function(t){return u(this,null,function*(){if(!(a(this,qi)===De.HIVE||!this.context.getValue("flagsmith").hasFeature(Z.PRECREATE_PRODUCERS)||!t))try{const e=[];if(t.canProduceVideo===G.Allowed&&e.push(this.shareWebcam(kO(!1))),t.canProduceAudio===G.Allowed){const i=EO(!1);i&&e.push(this.shareMic(i))}e.length>0&&(yield Promise.all(e))}catch(e){this.logger.warn("Failed to precreate producers",{error:e})}})},lt=new WeakSet,Et=function(t){return a(this,Dt).get(t)},fs=new WeakSet,to=function(t,e){return a(this,Dt).set(t,e)},wu=new WeakSet,Wg=function(t){return a(this,Dt).delete(t)},_u=new WeakSet,jg=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:a(this,qi)!==De.CF}},Iu=new WeakSet,Hg=function(t,e){return{track:t,codecOptions:e?e.map(i=>({name:i.split("/")[1]})):[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},g(Eu,Su),Eu);let le=Ry;me([k.trace("MediaNodeClient.reset",{country:k.location.country})],le.prototype,"reset",1);me([k.trace("MediaNodeClient.joinRoom")],le.prototype,"joinRoom",1);me([k.trace("MediaNodeClient.leaveRoom")],le.prototype,"leaveRoom",1);me([k.trace("MediaNodeClient.activatePeers")],le.prototype,"activatePeers",1);me([k.trace("MediaNodeClient.createConsumers")],le.prototype,"createConsumers",1);me([k.trace("MediaNodeClient.closeConsumers")],le.prototype,"closeConsumers",1);me([k.trace("MediaNodeClient._shareWebcam")],le.prototype,"_shareWebcam",1);me([k.trace("MediaNodeClient.shareWebcam")],le.prototype,"shareWebcam",1);me([k.trace("MediaNodeClient.shareScreen")],le.prototype,"shareScreen",1);me([k.trace("MediaNodeClient.shareMic")],le.prototype,"shareMic",1);me([k.trace("MediaNodeClient.pauseMic")],le.prototype,"pauseMic",1);me([k.trace("MediaNodeClient.pauseWebcam")],le.prototype,"pauseWebcam",1);me([k.trace("MediaNodeClient.resumeMic")],le.prototype,"resumeMic",1);me([k.trace("MediaNodeClient.resumeWebcam")],le.prototype,"resumeWebcam",1);me([k.trace("MediaNodeClient.disableWebcam")],le.prototype,"disableWebcam",1);me([k.trace("HiveClient.disableMic")],le.prototype,"disableMic",1);me([k.trace("HiveClient.disableScreenShare")],le.prototype,"disableScreenShare",1);me([k.trace("MediaNodeClient.muteSelf")],le.prototype,"muteSelf",1);me([k.trace("MediaNodeClient.resetVideoProducers")],le.prototype,"resetVideoProducers",1);me([k.trace("MediaNodeClient.changeDisplayName")],le.prototype,"changeDisplayName",1);me([k.trace("MediaNodeClient.kickPeer")],le.prototype,"kick",1);me([k.trace("MediaNodeClient.kickAllPeers")],le.prototype,"kickAll",1);me([k.trace("MediaNodeClient.muteAll")],le.prototype,"muteAll",1);me([k.trace("MediaNodeClient.muteAllVideo")],le.prototype,"muteAllVideo",1);me([k.trace("MediaNodeClient.disableAudio")],le.prototype,"disableAudio",1);me([k.trace("MediaNodeClient.disableVideo")],le.prototype,"disableVideo",1);me([k.trace("MediaNodeClient.pinPeer")],le.prototype,"pinPeer",1);me([k.trace("MediaNodeClient.validateScreenShare")],le.prototype,"validateScreenShare",1);function My(t,e,i){const r=t.getValue("roomNodeClient");if(r){if(r)return r;throw new Error("Room node client already set up.")}const n=new le(t,e,i);return t.setValue("roomNodeClient",n),n}function Ay(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch{t.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var wO=Object.defineProperty,_O=Object.getOwnPropertyDescriptor,Jn=(t,e,i,r)=>{for(var n=r>1?void 0:r?_O(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&wO(e,i,n),n},cn,Ai,re,Ot,qt,Gg;const Dy=(Gg=class{constructor(t,e,i,r){g(this,Ot),p(this,"self"),p(this,"authToken"),g(this,cn,void 0),p(this,"viewType"),g(this,Ai,void 0),g(this,re,void 0);const{socket:n}=i,s=t.getValue("authToken");this.self=e,f(this,re,t),this.viewType=r,this.authToken=s,f(this,cn,n),f(this,Ai,i),e.config.viewType!==Ut.Chat&&this.setupEvents()}get peerId(){return a(this,re).getValue("peerId")}get telemetry(){return a(this,re).getValue("telemetry")}get logger(){return a(this,re).getValue("logger")}get mediaJoined(){return a(this,re).getValue("connectionHandler").mediaJoined}static init(t,e,i,r,n){return u(this,null,function*(){const s=pt(),o=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield st.__init__(t,i,r,n,n.name,c);t.setValue("self",d);const l=t.getValue("logger");if(navigator.product!=="ReactNative"){const h=!t.getValue("flagsmith").hasFeature(Z.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const m=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(m)}),t.getValue("callstats").devices("AUDIO",m==null?void 0:m.filter(v=>v.kind==="audioinput")),t.getValue("callstats").devices("VIDEO",m==null?void 0:m.filter(v=>v.kind==="videoinput")),t.getValue("callstats").devices("SPEAKER",m==null?void 0:m.filter(v=>v.kind==="audiooutput")),l.info("Callstats:: initializing");try{yield t.getValue("callstats").initialize({peerId:o,engineName:Ie.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:t.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:Mv(t),skipConnectivityChecks:h}),l.info("Callstats:: initialized")}catch(v){l.error("Callstats:: initialization failed",{error:v})}}),0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new Dy(t,d,e,n.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:i,permissions:r,audioEnabled:n,videoEnabled:s,screenShareEnabled:o,screenShareTracks:c}=this.self;if(r.canProduceAudio===G.Allowed&&n)try{yield a(this,Ot,qt).shareMic(e),this.self.audioEnabled||a(this,Ot,qt).pauseMic()}catch{this.self.disableAudio()}if(r.canProduceVideo===G.Allowed&&s)try{const d=yield a(this,Ot,qt).shareWebcam(i);d&&d.id!==i.id&&a(this,re).getValue("flagsmith").hasFeature(Z.EXP_RESHARE)&&(yield a(this,Ot,qt).shareWebcam(d)),this.self.videoEnabled||a(this,Ot,qt).pauseWebcam()}catch{this.self.disableVideo()}if(r.canProduceScreenshare===G.Allowed&&o)try{yield(t=a(this,Ot,qt))==null?void 0:t.shareScreen({video:c.video,audio:c.audio})}catch{this.self.disableScreenShare()}})}kickHandler(t){return u(this,null,function*(){let e="kicked";(t==null?void 0:t.kickType)==="kickAll"&&(e="ended"),this.leaveRoom(e)})}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(t){return u(this,null,function*(){a(this,re).getValue("callstats").callEnded(),a(this,Ot,qt).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){a(this,re).getValue("peerSessionStore").on(P.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),a(this,re).getValue("peerSessionStore").on(P.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,re).getValue("peerSessionStore").on(P.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,re).getValue("peerSessionStore").on(P.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,re).getValue("peerSessionStore").on(P.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),a(this,re).getValue("peerSessionStore").on(P.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&a(this,re).getValue("flagsmith").hasFeature(Z.REFRESH_ID_ON_DISCONNECTION)&&(e=Vn()),a(this,cn).updateURL(e),a(this,re).getValue("telemetry").resetPeerId(e),pt().setHeader("dyte-tracing-id",e),sr.remapContext(e,a(this,re)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,re).getValue("peerSessionStore").on(P.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Ai).on(F.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Ai).on($c.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&a(this,re).getValue("peerSessionStore").emit(P.UPDATE_PERMISSIONS,e.patch)})}),a(this,Ai).on(F.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Ai).on(F.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Ai).on(F.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,re).getValue("peerSessionStore").onAsync(P.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,re).getValue("peerSessionStore").on(P.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:i,scoreStats:r})=>{var n;const s=(n=i==null?void 0:i.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:s,score:t,participantId:this.self.id,scoreStats:r})}),a(this,re).getValue("peerSessionStore").on(P.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),a(this,re).getValue("callstats").audioOff())})),a(this,re).getValue("peerSessionStore").on(P.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),a(this,re).getValue("callstats").videoOff())})),a(this,re).getValue("peerSessionStore").onAsync(P.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,re).getValue("peerSessionStore").on(P.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield a(this,Ai).joinRoom(this.self);a(this,Ai).socket.flush();const i=hp(e.stageType);if(a(this,re).setValue("stageStatus",i,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),a(this,re).notify("stageStatus")}catch(e){throw this.logger.error("Error in joinRoom",{error:e}),e}})}leaveRoom(t="left"){return u(this,null,function*(){var e,i;if(t==="rejected"){try{(e=a(this,cn))==null||e.disconnect()}catch{this.logger.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),a(this,re).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),a(this,re).notify("stageStatus");try{(i=a(this,cn))==null||i.disconnect()}catch{this.logger.error("SelfController::leaveRoom::socketDisconnect")}Ay(a(this,re)),yield a(this,re).getValue("roomSocketHandler").cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}joinMediaRoom(t=!1){return u(this,null,function*(){var e,i;const{peerId:r,viewType:n,meetingId:s,stageStatus:o,roomNodeOptions:c}=a(this,re).getAllValues(),{sfu:d}=c;try{if(n===Ut.Livestream){if(o!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}My(a(this,re),d,{socket:a(this,cn),peerId:r})}const{canProduceAudio:l,canProduceVideo:h,canProduceScreenshare:m}=this.self.permissions,{roomJoined:v}=(i=yield(e=a(this,Ot,qt))==null?void 0:e.joinRoom(this.self.name,s,t,t,{canProduceAudio:l,canProduceVideo:h,canProduceScreenshare:m}))!=null?i:{};if(!v)return;o==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(l){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:l}),new _("Error: could not join media room","0002")}})}leaveMediaRoom(t){return u(this,null,function*(){const e=a(this,re).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===Ut.Webinar)&&a(this,Ot,qt)&&(a(this,Ot,qt).mediaJoined&&t!=="disconnected"&&(yield a(this,Ot,qt).leaveRoom()),!(t==="stageLeft"&&e===Ut.Livestream)&&(a(this,Ot,qt).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()})}},cn=new WeakMap,Ai=new WeakMap,re=new WeakMap,Ot=new WeakSet,qt=function(){return a(this,re).getValue("roomNodeClient")},Gg);let zr=Dy;Jn([k.trace("SelfController.resetSelf")],zr.prototype,"resetSelf",1);Jn([k.trace("SelfController.setupEvents")],zr.prototype,"setupEvents",1);Jn([k.trace("SelfController.joinRoom")],zr.prototype,"joinRoom",1);Jn([k.trace("SelfController.leaveRoom")],zr.prototype,"leaveRoom",1);Jn([k.trace("SelfController.joinMediaRoom")],zr.prototype,"joinMediaRoom",1);Jn([k.trace("SelfController.leaveMediaRoom")],zr.prototype,"leaveMediaRoom",1);Jn([k.trace("SelfController.init")],zr,"init",1);var Pd;class IO{constructor(e){g(this,Pd,void 0),f(this,Pd,e)}on(e,i){let r;e===F.roomPeerCount?r=Om.fromBinary.bind(Om):r=Gm.fromBinary.bind(Gm),a(this,Pd).on(e,({payload:n})=>{if(e===F.roomPeerCount&&!n)return;const s=r(n);i(s)})}}Pd=new WeakMap;var Rd,Md;class CO{constructor(e,i){g(this,Rd,void 0),g(this,Md,void 0),f(this,Rd,i),f(this,Md,e)}get logger(){return a(this,Md).getValue("logger")}on(e,i){let r,n;switch(e){case F.transcript:{r=Gl.fromBinary.bind(Gl),n=Gl.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Rd).on(e,({payload:s})=>{let o=n;try{o=r(s)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}}Rd=new WeakMap,Md=new WeakMap;var PO=Object.defineProperty,RO=Object.getOwnPropertyDescriptor,wp=(t,e,i,r)=>{for(var n=r>1?void 0:r?RO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&PO(e,i,n),n},Or,Po;class Rl{constructor(e,i){g(this,Or,void 0),g(this,Po,void 0),f(this,Or,i),f(this,Po,e)}get logger(){return a(this,Po).getValue("logger")}get telemetry(){return a(this,Po).getValue("telemetry")}getPolls(){return a(this,Or).sendMessagePromise(Zi.getPolls)}createPoll(e,i,r=!1,n=!1){const s={anonymous:r,hideVotes:n,question:e,options:i};return a(this,Or).sendMessage(Zi.createPoll,RA.toBinary(s))}votePoll(e,i){const r={index:i,pollId:e};return a(this,Or).sendMessage(Zi.votePoll,AA.toBinary(r))}on(e,i){let r,n;switch(e){case Zi.updatePoll:case Zi.createPoll:case Zi.votePoll:{r=Yl.fromBinary.bind(Yl),n=Yl.create();break}}a(this,Or).on(e,({payload:s})=>{let o=n;try{o=r(s)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}removeListeners(e){a(this,Or).removeListeners(e)}}Or=new WeakMap,Po=new WeakMap;wp([k.trace("PollSocketHandler.getPolls")],Rl.prototype,"getPolls",1);wp([k.trace("PollSocketHandler.createPoll")],Rl.prototype,"createPoll",1);wp([k.trace("PollSocketHandler.votePoll")],Rl.prototype,"votePoll",1);var MO=Object.defineProperty,AO=Object.getOwnPropertyDescriptor,DO=(t,e,i,r)=>{for(var n=r>1?void 0:r?AO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&MO(e,i,n),n},si;class Oy{constructor(e,i){p(this,"socket"),g(this,si,void 0),f(this,si,e),this.socket=i,this.handleSocketEvents(),a(this,si).setValue("roomSocketHandler",this)}get telemetry(){return a(this,si).getValue("telemetry")}get logger(){return a(this,si).getValue("logger")}cleanup(){return u(this,null,function*(){var e;try{(e=this.socket)==null||e.disconnect()}catch{this.logger.error("roomSocketHandler::cleanup")}})}joinRoom(e){return u(this,null,function*(){var i;this.socket.joinAttempted=!0;const r={capabilities:[],peer:{displayName:(i=e.name)!=null?i:"Participant",customParticipantId:e.customParticipantId,peerId:e.id,userId:e.userId,displayPictureUrl:e.picture,waitlisted:!1},roomUuid:""},n=this.socket.sendMessagePromise(F.joinRoom,fP.toBinary(r));try{const{peer:s}=ys.fromBinary((yield n).payload);a(this,si).getValue("connectionHandler").socketJoined=!0,a(this,si).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_ROOM_JOINED,{peer:s});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=yield Promise.all([o,c]);return a(this,si).getValue("peerSessionStore").emit(P.ROOM_STATE,d),a(this,si).getValue("peerSessionStore").emit(P.SOCKET_PEERS,l),{peer:s}}catch(s){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:s}),new _("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,s)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return eR.fromBinary((yield this.socket.sendMessagePromise(F.getAllAddedParticipants)).payload).participants.map(e=>{var i=e,{id:r}=i,n=ml(i,["id"]);return q(V({},n),{userId:r})})}catch{return[]}})}getRoomPeers(e,i,r){return u(this,null,function*(){let n;try{const s={seachQuery:e,limit:i,offset:r},o=yield this.socket.sendMessagePromise(F.getRoomPeersInfo,aP.toBinary(s));n=ql.fromBinary(o.payload)}catch(s){this.logger.error("getRoomPeers::binary_decode_error",{error:s})}return n})}getRoomPeersNonPaginated(){return u(this,null,function*(){let e;try{const i=yield this.socket.sendMessagePromise(F.getRoomPeersInfo);e=ql.fromBinary(i.payload)}catch(i){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:i})}return e})}getStagePeers(){return u(this,null,function*(){let e;try{const i=yield this.socket.sendMessagePromise(F.getRoomPeersInfo);e=ql.fromBinary(i.payload)}catch(i){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:i})}return e})}getPeerInfo(e){return u(this,null,function*(){let i;try{const r=yield this.socket.sendMessagePromise(F.getPeerInfo,Wv.toBinary({peerId:e}));i=ys.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return i})}getRoomState(){return u(this,null,function*(){let e=Nm.create();try{const i=yield this.socket.sendMessagePromise(F.getRoomInfo);e=Nm.fromBinary(i.payload)}catch(i){this.logger.error("getRoomState::binary_decode_error",{error:i})}return e})}getRoomStageState(){return u(this,null,function*(){let e=Um.create();try{const i=yield this.socket.sendMessagePromise(F.getRoomStageState);e=Um.fromBinary(i.payload)}catch(i){this.logger.error("getRoomStageState::binary_decode_error",{error:i})}return e})}broadcastMessage(e,i){return u(this,null,function*(){const r={type:e,payload:new TextEncoder().encode(JSON.stringify(i)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(F.broadcastMessage,Ta.toBinary(r))})}broadcastToMeetings(e,i,r){return u(this,null,function*(){const n={type:e,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:i,broadcastType:1};return this.socket.sendMessagePromise(F.broadcastToEntity,Ta.toBinary(n))})}broadcastToPeers(e,i,r){return u(this,null,function*(){const n={type:e,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:i,broadcastType:0};return this.socket.sendMessage(F.broadcastToEntity,Ta.toBinary(n))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(F.leaveRoom,yP.toBinary({}))})}kick(e){return u(this,null,function*(){const i={peerIds:[e]};this.socket.sendMessage(F.kick,Hv.toBinary(i))})}kickAll(e=!1){return u(this,null,function*(){const i={propagateKickAcrossRooms:e};this.socket.sendMessage(F.kickAll,Uv.toBinary(i))})}getWaitingRoomRequests(){this.socket.sendMessage(F.getWaitingRoomRequests)}acceptWaitingRoomRequest(e){const i={userIds:e};this.socket.sendMessage(F.acceptWaitingRoomRequests,aR.toBinary(i))}rejectWaitingRoomRequest(e){const i={userIds:e};this.socket.sendMessage(F.denyWaitingRoomRequests,cR.toBinary(i))}updatePermissions(e,i){return u(this,null,function*(){const r={updatePeersPresets:[]};return e.forEach(n=>{r.updatePeersPresets.push({userIds:n,patch:i})}),this.socket.sendMessagePromise($c.updateUserPreset,xR.toBinary(r))})}handleSocketEvents(){this.socket.on(F.broadcastMessage,({payload:e})=>{try{const i=Ta.fromBinary(e);a(this,si).getValue("peerSessionStore").emit(P.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(i.payload)),type:i.type,timestamp:i.timestamp})}catch(i){this.logger.error("failed to decode broadcast message:",i)}}),this.socket.on(F.broadcastToEntity,({payload:e})=>{try{const i=Ta.fromBinary(e);a(this,si).getValue("peerSessionStore").emit(P.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(i.payload)),type:i.type,timestamp:i.timestamp})}catch(i){this.logger.error("failed to decode peer broadcast message:",i)}})}on(e,i){let r,n;switch(e){case F.joinRoom:case F.leaveRoom:case F.kick:case F.kickAll:{r=ys.fromBinary.bind(ys),n=ys.create();break}case F.getWaitingRoomRequests:{r=(s,o)=>s?xm.fromBinary(s,o):{requests:[]},n=xm.create();break}case F.recordingPaused:case F.recordingStarted:case F.recordingStopped:{r=Jm.fromBinary.bind(Jm);break}case $c.updateUserPreset:{r=Fm.fromBinary.bind(Fm);break}case Ti.peerJoinedBroadcast:case oi.peerJoinedBroadcast:{r=Pm.fromBinary.bind(Pm);break}case Ti.selfJoinComplete:case oi.selfJoinComplete:{r=Wu.fromBinary.bind(Wu);break}case Ti.globalPeerPinBroadcast:case oi.globalPeerPinBroadcast:{r=Am.fromBinary.bind(Am);break}case Ti.selectedPeer:case oi.selectedPeer:{r=Bu.fromBinary.bind(Bu);break}case Ti.selectedPeerDiff:case oi.selectedPeerDiff:{r=Cm.fromBinary.bind(Cm);break}case Ti.leaveRoom:case oi.leaveRoom:{r=ju.fromBinary.bind(ju);break}}this.socket.on(e,({payload:s})=>{let o=n;if(!r)return i(void 0);try{o=r(s)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}getUserPermissions(e){return u(this,null,function*(){const i={userIds:[e]};try{const r=yield this.socket.sendMessagePromise($c.getUserPresets,MR.toBinary(i)),n=NR.fromBinary(r.payload).peerPresets[0],s=new TextDecoder().decode(n.preset),o=JSON.parse(s).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}})}}si=new WeakMap;DO([k.trace("RoomSocketHandler.joinRoom")],Oy.prototype,"joinRoom",1);var Kt;class OO{constructor(e){g(this,Kt,void 0),f(this,Kt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield a(this,Kt).sendMessagePromise(F.getStageRequests);return e?zl.fromBinary(e):{stageRequests:[]}})}requestAccess(){a(this,Kt).sendMessage(F.requestStageAccess)}cancelRequestAccess(){a(this,Kt).sendMessage(F.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,Kt).sendMessage(F.grantStageAccess,SA.toBinary(i))})}denyAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,Kt).sendMessage(F.denyStageAccess,kA.toBinary(i))})}joinStage(){return a(this,Kt).sendMessagePromise(F.joinStage,void 0,void 0,F.peerStageStatusUpdate)}leaveStage(e){const i={userIds:[e]};return a(this,Kt).sendMessagePromise(F.leaveStage,$m.toBinary(i),void 0,F.peerStageStatusUpdate)}kick(e){const i={userIds:e};return a(this,Kt).sendMessagePromise(F.leaveStage,$m.toBinary(i))}on(e,i){let r;switch(e){case F.grantStageAccess:case F.denyStageAccess:{r=void 0;break}case F.getStagePeers:{r=qm.fromBinary.bind(qm);break}case F.getStageRequests:case F.requestStageAccess:case F.cancelStageRequest:{r=zl.fromBinary.bind(zl);break}case F.peerStageStatusUpdate:{r=Dm.fromBinary.bind(Dm);break}}a(this,Kt).on(e,({payload:n,id:s})=>{if(!n||!r)return i(void 0,s);const o=r(n);return i(o,s)})}getPeerInfo(e){return u(this,null,function*(){const i=yield a(this,Kt).sendMessagePromise(F.getPeerInfo,Wv.toBinary({peerId:e}));return ys.fromBinary(i.payload)})}}Kt=new WeakMap;var it,Ad;class NO{constructor(e,i){g(this,it,void 0),g(this,Ad,void 0),f(this,it,i),f(this,Ad,e)}get logger(){return a(this,Ad).getValue("logger")}addPlugin(e,i){a(this,it).sendMessage($.addPlugin,LM.toBinary({pluginId:e,staggered:i}))}removePlugin(e){a(this,it).sendMessage($.removePlugin,UM.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield a(this,it).sendMessagePromise($.getPlugins);return e?oA.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,i,r){const n={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(i))};a(this,it).sendMessage($.customPluginEventToRoom,KM.toBinary(n),r)}customPluginEventToPeers(e,i,r,n){const s={pluginId:e,peerIds:i,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,it).sendMessage($.customPluginEventToPeers,YM.toBinary(s),n)}enablePluginForRoom(e,i){a(this,it).sendMessage($.enablePluginForRoom,BM.toBinary({pluginId:e}),i)}enablePluginForPeers(e,i,r){a(this,it).sendMessage($.enablePluginForPeers,GM.toBinary({pluginId:e,peerIds:i}),r)}disablePluginForRoom(e,i){a(this,it).sendMessage($.disablePluginForRoom,jM.toBinary({pluginId:e}),i)}disablePluginForPeers(e,i,r){a(this,it).sendMessage($.disablePluginForPeers,$M.toBinary({pluginId:e,peerIds:i}),r)}storeInsertKeys(e,i,r,n){const s={pluginId:e,storeName:i,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,it).sendMessage($.storeInsertKeys,Bm.toBinary(s),n)}storeGetKeys(e,i,r,n){const s={pluginId:e,storeName:i,getKeys:r.map(o=>({storeKey:o.key}))};a(this,it).sendMessage($.storeGetKeys,eA.toBinary(s),n)}storeDeleteKeys(e,i,r,n){const s={pluginId:e,storeName:i,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,it).sendMessage($.storeDeleteKeys,iA.toBinary(s),n)}storeDelete(e,i,r){a(this,it).sendMessage($.storeDelete,nA.toBinary({pluginId:e,storeName:i}),r)}getPluginDataOld(e,i){this.logger.info("getPluginDataOld",{plugin:{id:e,storeName:i}})}storePluginDataOld(e,i,r){const n={pluginId:e,storeName:i,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};a(this,it).sendMessage($.storeInsertKeys,Bm.toBinary(n))}on(e,i){let r;switch(e){case $.addPlugin:case $.enablePluginForPeers:case $.enablePluginForRoom:{r=$u.fromBinary.bind($u);break}case $.removePlugin:case $.disablePluginForPeers:case $.disablePluginForRoom:{r=Wm.fromBinary.bind(Wm);break}case $.customPluginEventToPeers:case $.customPluginEventToRoom:{r=Hm.fromBinary.bind(Hm);break}case $.storeInsertKeys:case $.storeGetKeys:case $.storeDeleteKeys:case $.storeDelete:{r=jm.fromBinary.bind(jm);break}}a(this,it).on(e,({payload:n,id:s})=>{const o=r(n);return i(o,s)})}}it=new WeakMap,Ad=new WeakMap;var VO=Object.defineProperty,LO=(t,e,i)=>e in t?VO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,xO=(t,e,i)=>(LO(t,typeof e!="symbol"?e+"":e,i),i),_p=(t,e,i)=>{if(!e.has(t))throw TypeError("Cannot "+i)},N=(t,e,i)=>(_p(t,e,"read from private field"),i?i.call(t):e.get(t)),we=(t,e,i)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,i)},de=(t,e,i,r)=>(_p(t,e,"write to private field"),r?r.call(t,i):e.set(t,i),i),Re=(t,e,i)=>(_p(t,e,"access private method"),i),al={},UO={get exports(){return al},set exports(t){al=t}},Js=typeof Reflect=="object"?Reflect:null,qg=Js&&typeof Js.apply=="function"?Js.apply:function(t,e,i){return Function.prototype.apply.call(t,e,i)},Dd;Js&&typeof Js.ownKeys=="function"?Dd=Js.ownKeys:Object.getOwnPropertySymbols?Dd=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Dd=function(t){return Object.getOwnPropertyNames(t)};function FO(t){console&&console.warn&&console.warn(t)}var Ny=Number.isNaN||function(t){return t!==t};function pe(){pe.init.call(this)}UO.exports=pe;al.once=HO;pe.EventEmitter=pe;pe.prototype._events=void 0;pe.prototype._eventsCount=0;pe.prototype._maxListeners=void 0;var $g=10;function Ml(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(pe,"defaultMaxListeners",{enumerable:!0,get:function(){return $g},set:function(t){if(typeof t!="number"||t<0||Ny(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");$g=t}});pe.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};pe.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Ny(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function Vy(t){return t._maxListeners===void 0?pe.defaultMaxListeners:t._maxListeners}pe.prototype.getMaxListeners=function(){return Vy(this)};pe.prototype.emit=function(t){for(var e=[],i=1;i<arguments.length;i++)e.push(arguments[i]);var r=t==="error",n=this._events;if(n!==void 0)r=r&&n.error===void 0;else if(!r)return!1;if(r){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var c=n[t];if(c===void 0)return!1;if(typeof c=="function")qg(c,this,e);else for(var d=c.length,l=By(c,d),i=0;i<d;++i)qg(l[i],this,e);return!0};function Ly(t,e,i,r){var n,s,o;if(Ml(i),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,i.listener?i.listener:i),s=t._events),o=s[e]),o===void 0)o=s[e]=i,++t._eventsCount;else if(typeof o=="function"?o=s[e]=r?[i,o]:[o,i]:r?o.unshift(i):o.push(i),n=Vy(t),n>0&&o.length>n&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=o.length,FO(c)}return t}pe.prototype.addListener=function(t,e){return Ly(this,t,e,!1)};pe.prototype.on=pe.prototype.addListener;pe.prototype.prependListener=function(t,e){return Ly(this,t,e,!0)};function BO(){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 xy(t,e,i){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:i},n=BO.bind(r);return n.listener=i,r.wrapFn=n,n}pe.prototype.once=function(t,e){return Ml(e),this.on(t,xy(this,t,e)),this};pe.prototype.prependOnceListener=function(t,e){return Ml(e),this.prependListener(t,xy(this,t,e)),this};pe.prototype.removeListener=function(t,e){var i,r,n,s,o;if(Ml(e),r=this._events,r===void 0)return this;if(i=r[t],i===void 0)return this;if(i===e||i.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete r[t],r.removeListener&&this.emit("removeListener",t,i.listener||e));else if(typeof i!="function"){for(n=-1,s=i.length-1;s>=0;s--)if(i[s]===e||i[s].listener===e){o=i[s].listener,n=s;break}if(n<0)return this;n===0?i.shift():WO(i,n),i.length===1&&(r[t]=i[0]),r.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this};pe.prototype.off=pe.prototype.removeListener;pe.prototype.removeAllListeners=function(t){var e,i,r;if(i=this._events,i===void 0)return this;if(i.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):i[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete i[t]),this;if(arguments.length===0){var n=Object.keys(i),s;for(r=0;r<n.length;++r)s=n[r],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=i[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(r=e.length-1;r>=0;r--)this.removeListener(t,e[r]);return this};function Uy(t,e,i){var r=t._events;if(r===void 0)return[];var n=r[e];return n===void 0?[]:typeof n=="function"?i?[n.listener||n]:[n]:i?jO(n):By(n,n.length)}pe.prototype.listeners=function(t){return Uy(this,t,!0)};pe.prototype.rawListeners=function(t){return Uy(this,t,!1)};pe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Fy.call(t,e)};pe.prototype.listenerCount=Fy;function Fy(t){var e=this._events;if(e!==void 0){var i=e[t];if(typeof i=="function")return 1;if(i!==void 0)return i.length}return 0}pe.prototype.eventNames=function(){return this._eventsCount>0?Dd(this._events):[]};function By(t,e){for(var i=new Array(e),r=0;r<e;++r)i[r]=t[r];return i}function WO(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function jO(t){for(var e=new Array(t.length),i=0;i<e.length;++i)e[i]=t[i].listener||t[i];return e}function HO(t,e){return new Promise(function(i,r){function n(o){t.removeListener(e,s),r(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",n),i([].slice.call(arguments))}Wy(t,e,s,{once:!0}),e!=="error"&&GO(t,n,{once:!0})})}function GO(t,e,i){typeof t.on=="function"&&Wy(t,"error",e,i)}function Wy(t,e,i,r){if(typeof t.on=="function")r.once?t.once(e,i):t.on(e,i);else if(typeof t.addEventListener=="function")t.addEventListener(e,function n(s){r.once&&t.removeEventListener(e,n),i(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}class qO extends y{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 Jg=new qO;class jy{static encode(e){return Jg.toBinary(e)}static decode(e){return Jg.fromBinary(new Uint8Array(e))}}function $O(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var Nr;class JO{constructor(e={}){xO(this,"opts"),we(this,Nr,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},de(this,Nr,0)}wait(){return u(this,null,function*(){de(this,Nr,N(this,Nr)+1);const e=$O(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*tE(2,N(this,Nr))));yield new Promise(i=>{setTimeout(i,e)})})}getAttempts(){return N(this,Nr)}reset(){de(this,Nr,0)}}Nr=new WeakMap;const Er={debug:0,info:1,warn:2,error:3};var bn,wn;class KO{constructor(e){we(this,bn,void 0),we(this,wn,void 0),de(this,bn,console),de(this,wn,e)}debug(...e){Er[N(this,wn)]>Er.debug||N(this,bn).debug("[Sockrates]:",...e)}info(...e){Er[N(this,wn)]>Er.info||N(this,bn).info("[Sockrates]:",...e)}warn(...e){Er[N(this,wn)]>Er.warn||N(this,bn).warn("[Sockrates]:",...e)}error(...e){Er[N(this,wn)]>Er.error||N(this,bn).error("[Sockrates]:",...e)}}bn=new WeakMap,wn=new WeakMap;var Hy=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(Hy||{});const zO="2",YO="3";var Le,Ns,Pe,je,Vr,rt,nr,jr,ki,Vs,Xi,xh,Gy,Ro,Od,Uh,qy,Fh,Kg,ol,Bh,Wh,$y,Ho,Nd,Go,cl,dl,jh,Ks,qo,$o,ll;class QO{constructor(e,i){var r;we(this,xh),we(this,Ro),we(this,Uh),we(this,Fh),we(this,ol),we(this,Wh),we(this,Ho),we(this,Go),we(this,dl),we(this,Ks),we(this,$o),we(this,Le,void 0),we(this,Ns,void 0),we(this,Pe,void 0),we(this,je,void 0),we(this,Vr,void 0),we(this,rt,void 0),we(this,nr,void 0),we(this,jr,void 0),we(this,ki,void 0),we(this,Vs,void 0),we(this,Xi,void 0);var n,s,o,c,d,l,h,m,v;de(this,Ns,e),de(this,Vr,[]),de(this,rt,new al),de(this,nr,!0),de(this,ki,!1),de(this,Pe,i!=null?i:{}),(n=N(this,Pe)).autoReconnect!=null||(n.autoReconnect=!0),(s=N(this,Pe)).retryConnectionInterval!=null||(s.retryConnectionInterval=1e3),(o=N(this,Pe)).pingTimeout!=null||(o.pingTimeout=3e4),(c=N(this,Pe)).connectionTimeout!=null||(c.connectionTimeout=5e3),(d=N(this,Pe)).debug!=null||(d.debug=!0),(l=N(this,Pe)).maxReconnectionAttempts!=null||(l.maxReconnectionAttempts=10),(h=N(this,Pe)).disconnectOnPingTimeout!=null||(h.disconnectOnPingTimeout=!0),(m=N(this,Pe)).queueOnDisconnect!=null||(m.queueOnDisconnect=!1),(v=N(this,Pe)).flushOnReconnect!=null||(v.flushOnReconnect=!1),de(this,jr,{code:void 0,reason:void 0}),de(this,je,(r=N(this,Pe).logger)!=null?r:new KO(N(this,Pe).debug?"debug":"info")),de(this,Xi,new JO)}get readyState(){var e;return(e=N(this,Le))==null?void 0:e.readyState}get url(){return N(this,Ns)}updateURL(e){de(this,Ns,e),Re(this,Wh,$y).call(this)}get config(){return N(this,Pe)}get sendQueue(){return N(this,Vr)}flush(){if(!N(this,Pe).queueOnDisconnect)return!1;const e=[];return N(this,Vr).forEach(i=>{this.send(i.event,i.id,i.payload,i.metadata)||e.push(i)}),de(this,Vr,e),N(this,Vr)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){N(this,je).debug("Websocket was already connecting or connected.");return}if(N(this,nr)!==!1)return new Promise((i,r)=>{Re(this,Ks,qo).call(this),Re(this,$o,ll).call(this);try{de(this,Le,new WebSocket(Re(this,xh,Gy).call(this,N(this,Ns)))),N(this,Le).binaryType="arraybuffer",N(this,je).debug("Connecting");const n=setTimeout(()=>{N(this,je).debug("Connection timeout. Closing socket"),de(this,nr,!0),Re(this,$o,ll).call(this),N(this,Le).close(3001,"Connection Timeout"),N(this,Pe).autoReconnect&&!N(this,ki)&&(N(this,rt).emit("reconnecting"),Re(this,Ho,Nd).call(this)),r(new Error("Connection timed out!"))},N(this,Pe).connectionTimeout);N(this,Le).onopen=()=>{N(this,je).debug(`Ready State: ${Hy[N(this,Le).readyState]}`),n&&clearTimeout(n),Re(this,dl,jh).call(this),de(this,jr,{code:void 0,reason:void 0}),N(this,rt).emit("connected"),N(this,Pe).flushOnReconnect&&this.flush(),i()},N(this,Le).onclose=s=>{try{n&&clearTimeout(n);const{code:o,reason:c}=s;r(c),N(this,je).debug("Socket closed. Close event:",{event:s}),N(this,je).debug(`Connection closed code: ${o}`),N(this,je).debug(`Connection closed reason: ${c}`),N(this,ki)||Re(this,ol,Bh).call(this,o,c)}catch(o){Re(this,Ro,Od).call(this,o)}},N(this,Le).onerror=s=>{Re(this,Ro,Od).call(this,s)},N(this,Le).onmessage=s=>Re(this,Uh,qy).call(this,s)}catch(n){Re(this,Ro,Od).call(this,n,r)}})})}send(e,i,r,n){const s={event:e,id:i,payload:r,metadata:n};if(N(this,Pe).queueOnDisconnect&&(!N(this,Le)||N(this,Le).readyState!==1))return N(this,je).debug("Queuing message since socket is not connected!",s),N(this,Vr).push(s),!1;const o=jy.encode(s);return Re(this,Go,cl).call(this,o)}emit(e,i,r,n){return this.send(e,i,r,n)}sendRaw(e){return Re(this,Go,cl).call(this,e)}receive(e,i){return N(this,rt).on(e.toString(),i)}on(e,i){if(typeof e=="string"&&(e==="connected"||e==="disconnected"||e==="errored"||e==="reconnected"||e==="reconnecting"||e==="reconnectAttempt"||e==="reconnectFailure"||e==="failed")){N(this,rt).on(e,i);return}this.receive(e,i)}removeAllListeners(){N(this,rt).removeAllListeners()}removeReceiver(e,i){this.removeListener(e,i)}removeListener(e,i){N(this,rt).removeListener(e.toString(),i)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){N(this,rt).listeners(e.toString()).map(i=>this.removeListener(e,i))}disconnect(){de(this,nr,!1),Re(this,Ks,qo).call(this),this.removeAllListeners(),de(this,jr,{code:1e3,reason:"Sockrates disconnect method called"}),N(this,Le).close(1e3,"Sockrates disconnect method called.")}}Le=new WeakMap,Ns=new WeakMap,Pe=new WeakMap,je=new WeakMap,Vr=new WeakMap,rt=new WeakMap,nr=new WeakMap,jr=new WeakMap,ki=new WeakMap,Vs=new WeakMap,Xi=new WeakMap,xh=new WeakSet,Gy=function(t){if(t.startsWith("ws://")||t.startsWith("wss://"))return t;if(t.startsWith("https://"))return`wss://${t.substring(8)}`;if(t.startsWith("http://"))return`ws://${t.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},Ro=new WeakSet,Od=function(t,e){N(this,je).error("Error:",{error:t}),N(this,rt).emit("errored",{error:t}),e==null||e(t)},Uh=new WeakSet,qy=function(t){if(Re(this,dl,jh).call(this),t.data===zO){N(this,je).debug("Received ping from server"),Re(this,Go,cl).call(this,YO);return}const e=jy.decode(t.data),{id:i,payload:r}=e;N(this,je).debug("Received message",{event:e.event,messageID:i}),N(this,rt).emit(e.event.toString(),{id:i,payload:r})},Fh=new WeakSet,Kg=function(){return N(this,Le).readyState===1},ol=new WeakSet,Bh=function(t,e){de(this,jr,{reason:e,code:t}),N(this,rt).emit("disconnected",{code:t,reason:e})},Wh=new WeakSet,$y=function(){const{reason:t,code:e}=N(this,jr);e&&e!==1e3&&N(this,nr)&&N(this,Pe).autoReconnect&&!N(this,ki)&&(N(this,je).debug(`Triggering reconnection due to ${t}.`),N(this,rt).emit("reconnecting"),Re(this,Ho,Nd).call(this))},Ho=new WeakSet,Nd=function(t=!0){return u(this,null,function*(){if(t&&N(this,ki)){N(this,je).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(N(this,ki)||N(this,Xi).reset(),N(this,Pe).maxReconnectionAttempts!==null&&N(this,Xi).getAttempts()>=N(this,Pe).maxReconnectionAttempts){N(this,rt).emit("failed"),de(this,ki,!1);return}de(this,ki,!0),Re(this,$o,ll).call(this),Re(this,Ks,qo).call(this);try{if(yield N(this,Xi).wait(),N(this,nr)===!1)return;if(N(this,je).debug(`Reconnection attempt ${N(this,Xi).getAttempts()}`),N(this,rt).emit("reconnectAttempt",{attempt:N(this,Xi).getAttempts()}),yield this.connect(),!Re(this,Fh,Kg).call(this))throw Error("Reconnect Failed");de(this,ki,!1),de(this,jr,{code:void 0,reason:void 0}),N(this,rt).emit("reconnected")}catch{N(this,je).debug("Failed to reconnect."),N(this,rt).emit("reconnectFailure",{attempt:N(this,Xi).getAttempts()}),Re(this,Ho,Nd).call(this,!1)}})},Go=new WeakSet,cl=function(t){try{return N(this,Le).send(t),!0}catch(e){return N(this,je).error(e.message),!1}},dl=new WeakSet,jh=function(){this.config.disconnectOnPingTimeout&&(N(this,je).debug("Resetting ping timeout"),Re(this,Ks,qo).call(this),de(this,Vs,setTimeout(()=>{var t;N(this,je).debug("Disconnecting the socket due to ping timeout"),de(this,nr,!0);const e=3002,i="Ping timeout";(t=N(this,Le))==null||t.close(e,i),Re(this,ol,Bh).call(this,e,i)},N(this,Pe).pingTimeout)))},Ks=new WeakSet,qo=function(){N(this,Vs)&&(clearTimeout(N(this,Vs)),de(this,Vs,void 0))},$o=new WeakSet,ll=function(){N(this,Le)&&(N(this,Le).onopen=void 0,N(this,Le).onerror=void 0,N(this,Le).onmessage=void 0,N(this,Le).onclose=void 0)};var XO=Object.defineProperty,ZO=Object.getOwnPropertyDescriptor,Al=(t,e,i,r)=>{for(var n=r>1?void 0:r?ZO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&XO(e,i,n),n};const zg=65535,eN=3e3;var dn,Oe,Ne,xe,pi,ut,xc,Cu,Uc,Pu,Yg;const Jy=(Yg=class{constructor(t,{peerId:e,meetingId:i,authToken:r,capabilities:n}){g(this,Ne),g(this,xc),g(this,Uc),g(this,dn,void 0),g(this,Oe,void 0),p(this,"roomName"),p(this,"authToken"),p(this,"capabilities"),g(this,pi,void 0),g(this,ut,void 0);var s;if(!e||!i||!r)throw new _("peerId, meetingId, or authToken can not be empty","0404");f(this,pi,void 0),f(this,ut,t),this.capabilities=n,this.roomName=i,this.authToken=r,f(this,dn,U(this,xc,Cu).call(this,e)),f(this,Oe,new QO(a(this,dn),{autoReconnect:!0,disconnectOnPingTimeout:(s=n.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Ne,xe).socketJoinAttempted}set joinAttempted(t){a(this,Ne,xe).socketJoinAttempted=t}get telemetry(){return a(this,ut).getValue("telemetry")}get logger(){return a(this,ut).getValue("logger")}get peerId(){return a(this,ut).getValue("peerId")}updateURL(t){t!==this.peerId&&(f(this,dn,U(this,xc,Cu).call(this,t)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Oe).updateURL(a(this,dn))}static getSocketEdgeDomain(t){return On({servicePrefix:"socket-edge",baseURI:t})}get url(){return a(this,dn)}connect(){return u(this,null,function*(){a(this,Ne,xe).socketJoinAttempted=!0,yield a(this,Oe).connect(),a(this,Ne,xe).socketJoinAttempted=!0,a(this,Ne,xe).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return u(this,null,function*(){a(this,Ne,xe).socketJoinAttempted=!1,a(this,Oe).disconnect(),a(this,Ne,xe).socketJoinAttempted=!0,a(this,Ne,xe).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return a(this,Oe).readyState===1}catch{return!1}}sendMessage(t,e,i){const r={};return a(this,ut).getValue("telemetry").injectContext(r),a(this,Oe).send(t,i!=null?i:U(this,Uc,Pu).call(this),e,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(t,e,i,r){const n=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:n,protobuf:e,messageId:i,resp:r})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:i,messageId:r,resp:n}){const s=n!=null?n:t;return new Promise((o,c)=>{const d=(S,T)=>{a(this,Oe).removeListener(s,S),a(this,Oe).removeListener(zg,T),a(this,Oe).removeListener(oi.errorResponse,T),a(this,Oe).removeListener(Ti.errorResponse,T)},l=r!=null?r:U(this,Uc,Pu).call(this),h={};a(this,ut).getValue("telemetry").injectContext(h);const m=({id:S,payload:T})=>{if(l===S){let M;try{const I=XI.fromBinary(T);M=new Error(I.errorMessage)}catch(I){M=new Error("failed to parse error message",{cause:I});try{const R=ZC.fromBinary(T);M=new Error(R.message)}catch(R){M=new Error("failed to parse error message",{cause:R})}}c(M),d(v,m)}},v=({id:S,payload:T})=>{l===S&&(o({id:S,payload:T}),d(v,m))};a(this,Oe).on(s,v),a(this,Oe).on(zg,m),a(this,Oe).on(oi.errorResponse,m),a(this,Oe).on(Ti.errorResponse,m),setTimeout(()=>{d(v,m),c(new Error(`request timeout for callback eventId:${t}`))},e),a(this,Oe).send(t,l,i,new TextEncoder().encode(JSON.stringify(h)))})}on(t,e){a(this,Oe).on(t,e)}onStateEvent(t,e){a(this,Oe).on(t,e)}removeListener(t,e){a(this,Oe).removeListener(t,e)}removeListeners(t){a(this,Oe).removeListeners(t)}flush(){return a(this,Oe).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){this.logger.info("SocketService::Connected to socket-edge"),a(this,pi)&&(clearTimeout(a(this,pi)),f(this,pi,void 0)),a(this,Ne,xe).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:k.location.country});const{recv:r,send:n}=(i=a(this,Ne,xe).mediaState)!=null?i:{};r!=null&&r.state&&(r==null?void 0:r.state)!==ea.CONNECTED||n!=null&&n.state&&(n==null?void 0:n.state)!==ea.CONNECTED?a(this,ut).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ne,xe).joinAttempted}):f(this,pi,setTimeout(()=>{a(this,ut).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ne,xe).joinAttempted}),f(this,pi,void 0)},eN)),a(this,Ne,xe).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnecting to socket-edge",{country:k.location.country}),a(this,Ne,xe).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),a(this,Ne,xe).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),a(this,Ne,xe).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Ne,xe).mediaJoinAttempted}}),a(this,pi)&&(clearTimeout(a(this,pi)),f(this,pi,void 0)),a(this,ut).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Ne,xe).mediaJoinAttempted}),a(this,Ne,xe).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){this.logger.info("SocketService::Failed to connect to socket-edge",{country:k.location.country}),a(this,ut).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_FAILED),a(this,Ne,xe).updateSocketConnectionState("failed")}))}},dn=new WeakMap,Oe=new WeakMap,Ne=new WeakSet,xe=function(){return a(this,ut).getValue("connectionHandler")},pi=new WeakMap,ut=new WeakMap,xc=new WeakSet,Cu=function(t){let e=Jy.getSocketEdgeDomain(a(this,ut).getValue("baseURI"));typeof Xs(a(this,ut),"socket_server_base")=="string"&&(e=Xs(a(this,ut),"socket_server_base"));const i=`wss://${e}`,r=new URL(`${i}/ws`),n=this.peerId,s=q(V({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},n!==t&&{oldPeerID:n}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>Kd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0});return Object.entries(s).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},Uc=new WeakSet,Pu=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Yg);let ac=Jy;Al([k.trace("SocketService.connect")],ac.prototype,"connect",1);Al([k.trace("SocketService.disconnect")],ac.prototype,"disconnect",1);Al([k.trace("SocketService.sendMessagePromise")],ac.prototype,"sendMessagePromise",1);Al([k.trace("SocketService.sendMessagePromiseWithTimeout")],ac.prototype,"sendMessagePromiseWithTimeout",1);class tN{constructor(e){p(this,"socketService"),this.socketService=e}handleConnectedRoomsDumpRaw({payload:e}){var i;const r=IP.fromBinary(e),n=r.meetings.map(s=>{var o;return{id:s.id,title:s.title,participants:(o=s.participants)!=null?o:[]}});return{parentMeeting:{id:r.parentMeeting.id,title:r.parentMeeting.title,participants:(i=r.parentMeeting.participants)!=null?i:[]},meetings:n}}handleTransferPeerRaw({payload:e}){const i=XP.fromBinary(e);return{authToken:i.authToken,meetingId:i.meetingId}}handleMovedPeerRaw({payload:e}){const i=jv.fromBinary(e);return{meetingId:i.meetingId,customParticipantId:i.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:e}){return Lm.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}handleConnectedRoomsDeletedRaw({payload:e}){return jP.fromBinary(e).payloads}getConnectedRoomsDump(){return u(this,null,function*(){const e=yield this.socketService.sendMessagePromise(F.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(e)})}createConnectedRooms(e){return u(this,null,function*(){const{payload:i}=yield this.socketService.sendMessagePromise(F.createConnectedRooms,MP.toBinary({payloads:e}));return Lm.fromBinary(i).payloads.map(r=>({id:r.id,title:r.title}))})}updateConnectedRooms(e){return u(this,null,function*(){})}disableConnectedRooms(e){return u(this,null,function*(){const i=e.map(n=>({id:n})),r=yield this.socketService.sendMessagePromise(F.deleteConnectedRooms,BP.toBinary({payloads:i}));return this.handleConnectedRoomsDeletedRaw(r)})}movePeersBetweenRooms(e){return u(this,null,function*(){try{const i=yield this.socketService.sendMessagePromise(F.movePeers,KP.toBinary({sourceMeetingId:e.sourceMeetingId,destinationMeetingId:e.destinationMeetingId,participants:e.participants}));return new TextDecoder().decode(i.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(i){return{success:!1,error:i}}})}}var iN=Object.defineProperty,rN=Object.getOwnPropertyDescriptor,nN=(t,e,i,r)=>{for(var n=r>1?void 0:r?rN(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&iN(e,i,n),n},Vi;class Ky extends Qt{constructor(e){const i=e.getValue("logger");super(i),p(this,"meetings",[]),p(this,"parentMeeting",null),g(this,Vi,void 0),f(this,Vi,e)}get supportsConnectedMeetings(){return a(this,Vi).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 Dyte team to move you to V2 APIs & to enable connected meetings.`)}getConnectedMeetings(){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),yield a(this,Vi).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield a(this,Vi).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e)).map(i=>({id:i.id,title:i.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield a(this,Vi).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(i=>({meetingId:i.id,title:i.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=this.meetings.map(r=>e.includes(r.id)&&r.participants.length!==0?this.moveParticipants(r.id,this.parentMeeting.id,r.participants.map(n=>n.id)):Promise.resolve());return yield Promise.all(i),yield a(this,Vi).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e)})}moveParticipants(e,i,r){return u(this,null,function*(){this.validateConnectedMeetingsAction();const n=yield a(this,Vi).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:r.map(s=>({id:s}))});return n.success&&this.moveSuccessHandler(e,i,r),n})}moveParticipantsWithCustomPreset(e,i,r){return u(this,null,function*(){this.validateConnectedMeetingsAction();const n=yield a(this,Vi).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:r});return n.success&&this.moveSuccessHandler(e,i,r.map(s=>s.id)),n})}moveSuccessHandler(e,i,r){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(s=>s.participants)].forEach(s=>n.set(s.id,s)),i===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(r.map(s=>n.get(s)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(s=>!r.includes(s.id))),this.meetings=this.meetings.map(s=>{if(i===s.id){const o=s.participants.concat(r.map(c=>n.get(c)));return q(V({},s),{participants:o})}if(e===s.id){const o=s.participants.filter(c=>!r.includes(c.id));return q(V({},s),{participants:o})}return s})}}Vi=new WeakMap;nN([Ft({maxInvocations:60,period:60})],Ky.prototype,"getConnectedMeetings",1);var sN=Object.defineProperty,aN=Object.getOwnPropertyDescriptor,Ip=(t,e,i,r)=>{for(var n=r>1?void 0:r?aN(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&sN(e,i,n),n},Te,Qg;const zy=(Qg=class{constructor(t){p(this,"connectedMeetings"),g(this,Te,void 0),f(this,Te,t),this.connectedMeetings=new Ky(t)}get telemetry(){return a(this,Te).getValue("telemetry")}get logger(){return a(this,Te).getValue("logger")}static init(t){const e=new zy(t);return e.connectedMeetings.supportsConnectedMeetings&&(e.setupEvents(),t.getValue("self").once("roomJoined",()=>e.getConnectedMeetings())),e}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,Te).getValue("connectedMeetingsSocketHandler").socketService.on(F.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,Te).getValue("connectedMeetingsSocketHandler").socketService.on(F.transferPeer,this.handleTransferPeer.bind(this)),a(this,Te).getValue("connectedMeetingsSocketHandler").socketService.on(F.movedPeer,this.handleMovedPeer.bind(this)),a(this,Te).getValue("connectedMeetingsSocketHandler").socketService.on(F.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,Te).getValue("connectedMeetingsSocketHandler").socketService.on(F.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(t){const e=a(this,Te).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:i}){var r,n,s,o;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
22
22
  Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",i);const c={video:a(this,Te).getValue("self").videoEnabled,audio:a(this,Te).getValue("self").audioEnabled};try{a(this,Te).getValue("self").cleanupEvents(),yield a(this,Te).getValue("meeting").leave("connected-meeting")}catch(l){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(r=a(this,Te).getValue("meeting"))==null?void 0:r.meta)==null?void 0:n.meetingId}`,{error:l})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${i}`);const d=yield Qy.init(q(V({},a(this,Te).getValue("options")),{cachedUserDetails:null,defaults:q(V(V({},a(this,Te).getValue("options").defaults),c),{mediaHandler:a(this,Te).getValue("self")}),authToken:e}));this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(s=d==null?void 0:d.meta)==null?void 0:s.meetingId}`);try{const{hidden:l}=a(this,Te).getValue("self");d.self.setName(a(this,Te).getValue("self").name),yield d.join(),l&&d.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: ${(o=d==null?void 0:d.meta)==null?void 0:o.meetingId}`),this.connectedMeetings.emit("meetingChanged",d),d})}handleConnectedRoomsDump(t){const e=a(this,Te).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(t);this.connectedMeetings.meetings=e.meetings.map(i=>({id:i.id,title:i.title,participants:i.participants||[]})),this.connectedMeetings.parentMeeting={id:e.parentMeeting.id,title:e.parentMeeting.title,participants:e.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(t){return a(this,Te).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=a(this,Te).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(t),i=new Map;this.connectedMeetings.meetings.forEach(r=>{i.set(r.id,r)}),e.forEach(r=>{i.has(r.id)?i.get(r.id).title=r.title:i.set(r.id,q(V({},r),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(i.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=a(this,Te).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(t).map(i=>i.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(i=>!e.includes(i.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Te=new WeakMap,Qg);let Dl=zy;Ip([k.trace("ConnectedMeetingsController.getConnectedMeetings")],Dl.prototype,"getConnectedMeetings",1);Ip([k.trace("ConnectedMeetingsController.setupEvents")],Dl.prototype,"setupEvents",1);Ip([k.trace("ConnectedMeetingsController.switchMeeting")],Dl.prototype,"switchMeeting",1);var oN=Object.defineProperty,cN=Object.getOwnPropertyDescriptor,Ol=(t,e,i,r)=>{for(var n=r>1?void 0:r?cN(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&oN(e,i,n),n};const Ls=class{constructor(t,e,i){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=t,this.storesManager=e.storesManager,this.metaController=e.metaController,this.selfController=e.selfController,this.chatController=e.chatController,this.pollController=e.pollController,this.stageController=e.stageController,this.pluginController=e.pluginController,this.recordingController=e.recordingController,this.internalsController=e.internalsController,this.participantController=e.participantController,this.livestreamController=e.livestreamController,this.connectedMeetingsController=e.connectedMeetingsController,this.telemetry=i.getValue("telemetry"),this.logger=i.getValue("logger")}static init(t){return u(this,null,function*(){var e,i;const{peerId:r,apiBase:n,authToken:s,meetingId:o,organizationId:c,cachedUserDetails:d,logger:l}=t.getAllValues();if(Ay(t),Ie.isSupported()===!1)throw new _("Browser not supported","0010",l,!0);const h=l1(t,{authToken:s,baseURL:n,cachedUserDetails:d});h.setRoomName(o),h.setRoomUUID(o),h.setOrganizationId(c),h.setHeader("dyte-tracing-id",r),t.setValue("apiClient",h);const m=new $1(t);t.setValue("connectionHandler",m);const v=Ls.createSocketService(t),S=v.connect(),T=h.getUserDetails(),M=h.getPlugins();let I=De.HIVE,R,j="";try{yield Ls.setupFlagsmith(t)}catch(ae){l.error("Failed to setup flagsmith",{error:ae})}try{yield S}catch(ae){l.error("[Controller]: Failed to connect to socket server:",{error:ae})}try{({sfu:I,meetingTitle:j}=yield h.getRoomNodeData()),R=yield T,l.info(`SFU ${I} is being used.`),t.setValue("presetName",R.preset.name),t.setValue("roomNodeOptions",{sfu:I})}catch(ae){l.error("Failed to get room metadata",{error:ae})}const W=MD.init(R.preset,!t.getValue("modules").theme),b=QD.init(t,W.viewType,R.preset.permissions),te=Ls.setupControllers(v,t,R,M,j,W,b);V1(W)&&((e=Ls.createRoomNodeClient(t,v).initializeConnection(R.participant.name,o,!1,b))==null||e.catch(ae=>{l.error("[Controller]: Failed to queue partial media room promise:",{error:ae})})),k.location.country=(i=h.ipInfo)==null?void 0:i.country;const{controllers:ie}=yield te;return D_(),new Ls(n,ie,t)})}static setupFlagsmith(t){return u(this,null,function*(){var e;const{peerId:i,baseURI:r,overrides:n,meetingId:s,organizationId:o,logger:c}=t.getAllValues(),d=A_(s),l=q(V({entity:Fu.PEER,clientId:o,isAnonUser:!o,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:d,roomName:s},Ie.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const h=(e=n==null?void 0:n.whitelabelled_flags_endpoint)==null||e?On({servicePrefix:"flags",baseURI:r}):"edge.api.flagsmith.com";yield t.getValue("flagsmith").identify(`${Fu.PEER}_${i}`,JSON.parse(JSON.stringify(l)),!1,5e3,h,c),c.info("flagsmith::allFlags",{flags:JSON.stringify(t.getValue("flagsmith").getAllFlags())},!0)}catch{c.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,i,r,n,s,o){return u(this,null,function*(){var c,d,l;const h=e.getValue("modules"),{participant:m}=i,v=e.getValue("defaults"),S=e.getValue("logger"),{sfu:T}=e.getValue("roomNodeOptions"),{viewType:M,mediaConstraints:{audio:I}}=s;e.setValue("viewType",M),e.setValue("defaults",V({mediaConfiguration:{audio:{enableHighBitrate:(c=I.enableHighBitrate)!=null?c:!1,enableStereo:(d=I.enableStereo)!=null?d:!1}}},v)),e.setValue("maxPreferredStreams",Ie.isMobile()?s.maxVideoStreams.mobile:s.maxVideoStreams.desktop);let R,j,W,b,te,ie,ae,Me,Xe;const Wt=new CO(e,t),A=new tN(t);e.setValue("connectedMeetingsSocketHandler",A);const E=new Rl(e,t),w=new ci(e,t),B=new OO(t),oe=new Oy(e,t),He=new NO(e,t),x=new IO(t),C=new xn(e,t),ce=yield zr.init(e,oe,m,o,s);e.setValue("selfController",ce);const Yr=yield ey.init(e,ce.self,oe,Wt,n);if(h.participant&&(Me=new pr(e,ce.self,oe,T)),(l=h.e2ee)!=null&&l.enabled&&h.e2ee.manager.init(S,e.getValue("peerSessionStore")),h.chat&&(j=yield ar.init(e,w,C,ce.self,Me.participants)),h.internals&&(te=yield mp.init(e)),h.livestream&&s.viewType===Ut.Livestream&&e.getValue("flagsmith").hasFeature(Z.LIVESTREAM)&&(ae=new dy(e,ce.self,x)),s.viewType!==Ut.Chat){if(h.poll&&(R=yield Yv.init(e,ce.self,E)),h.recording&&(ie=new ny(e,ce.self,oe)),h.stage&&(W=new ty(e,B,oe,ce.self,Me.participants)),h.plugin){if(!Me)throw new _("The plugin module cannot be initialized without the `participant` module","0102");const Gi=yield r;b=yield ic.init(e,Gi,He,w,j==null?void 0:j.chat,ce.self,Me.participants,n)}if(h.connectedMeetings&&(Xe=yield Dl.init(e)),h.pip){const Gi=yield V_._init(e,ce.self);e.setValue("pip",Gi)}}const Qr={storesManager:new UD(e,He),pollController:R,selfController:ce,metaController:Yr,chatController:j,stageController:W,pluginController:b,recordingController:ie,internalsController:te,livestreamController:ae,participantController:Me,connectedMeetingsController:Xe};return{theme:s,permissions:o,controllers:Qr}})}static createRoomNodeClient(t,e){const{peerId:i,roomNodeOptions:r}=t.getAllValues(),{sfu:n}=r;return My(t,n,{socket:e,peerId:i})}static createSocketService(t){const{peerId:e,meetingId:i,authToken:r}=t.getAllValues(),n=["PING"];return new ac(t,{peerId:e,meetingId:i,authToken:r,capabilities:n})}};let oc=Ls;Ol([k.trace("Controller.init")],oc,"init",1);Ol([k.trace("setupFlagsmith")],oc,"setupFlagsmith",1);Ol([k.trace("Controller.createRoomNodeClient")],oc,"createRoomNodeClient",1);Ol([k.trace("Controller.createSocketService")],oc,"createSocketService",1);class dN{constructor(){p(this,"battery"),p(this,"logger"),p(this,"init",e=>u(this,null,function*(){this.logger=e;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(i){e.error("Error getting battery",i)}})),p(this,"updateChargeInfo",()=>{var e;this.logger.log(`Battery charging? ${(e=this.battery)!=null&&e.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 e,i;"getBattery"in navigator&&((e=this.battery)==null||e.removeEventListener("chargingchange",this.updateChargeInfo),(i=this.battery)==null||i.removeEventListener("levelchange",this.updateLevelInfo))})}}const Xg=new dN;function lN(t,e){t.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c \u2014 not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.dyte.io/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:i,orgId:r,participantId:n}=JSON.parse(atob(t.split(".")[1]));if(!i)throw Error(`Received V1 auth token ${t}`);let s="dyte.io";e&&(s=e);const o=`https://${On({servicePrefix:"api",baseURI:s})}`;return{meetingId:i,orgId:r,participantId:n,baseURI:s,apiBase:o}}catch{throw new _("Invalid auth token","0004")}}var _n,xs,Us,ul,Hh,Yy;class uN{constructor(){g(this,Hh),g(this,_n,new Audio),g(this,xs,new MediaStream),g(this,Us,new Map),g(this,ul,void 0),a(this,_n).srcObject=a(this,xs),a(this,_n).autoplay=!0}playTracks(e){return u(this,null,function*(){return e.forEach(i=>{a(this,Us).has(i.id)||(a(this,xs).addTrack(i),a(this,Us).set(i.id,i))}),this.play()})}setSpeakerDevice(e){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,_n).setSinkId(e)}removeTrack(e){const i=a(this,Us).get(e);i&&(a(this,xs).removeTrack(i),a(this,Us).delete(e))}play(){return u(this,null,function*(){return a(this,_n).srcObject=a(this,xs),a(this,_n).play().catch(e=>{U(this,Hh,Yy).call(this,e)})})}onError(e){f(this,ul,e)}}_n=new WeakMap,xs=new WeakMap,Us=new WeakMap,ul=new WeakMap,Hh=new WeakSet,Yy=function(t){var e;(e=a(this,ul))==null||e.call(this,t)};var Fs;class hN extends uN{constructor(){super(),g(this,Fs,void 0),f(this,Fs,new Map)}addParticipantTrack(e,i){a(this,Fs).set(e,i.id),this.playTracks([i])}removeParticipantTrack(e){const i=a(this,Fs).get(e);i&&this.removeTrack(i),a(this,Fs).delete(e)}}Fs=new WeakMap;var pN=Object.defineProperty,mN=Object.getOwnPropertyDescriptor,Nl=(t,e,i,r)=>{for(var n=r>1?void 0:r?mN(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&pN(e,i,n),n},et,ln,Zg;let Jr=(Zg=class{constructor(t,e){g(this,et,void 0),g(this,ln,void 0),f(this,ln,t),f(this,et,e)}get peerId(){return a(this,ln).getValue("peerId")}static initMedia(t={},e=!1,i=void 0){var r;const n=(r=i==null?void 0:i.peerId)!=null?r:Vn(),s=sr.createContext(n,{peerId:n}),o=s.getValue("logger");o.init(s);const c=new py(o);return c.init(t,e,s),s.setValue("defaults",{mediaHandler:c}),c}static init(t){return u(this,null,function*(){var e,i,r,n,s,o,c;Ie.init();const{mediaHandler:d}=(e=t.defaults)!=null?e:{},l=(d==null?void 0:d.peerId)||((r=(i=t==null?void 0:t.cachedUserDetails)==null?void 0:i.peerId)!=null?r:Vn()),{authToken:h,baseURI:m}=t,v=lN(h,m),{meetingId:S}=v,T=ml(v,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const M=Jr.setupContext(l,t,S,T),I=M.getValue("telemetry"),R=M.getValue("logger");sE(R),Xg.init(R),I.init(M,{roomName:S,userId:T.participantId,organizationId:T.orgId,peerId:l},(s=(n=t.modules)==null?void 0:n.tracing)!=null?s:!0),R.init(M),R.info("DyteClient::init::options",{dyteClientInitOptions:q(V({},t),{authToken:`${(o=t.authToken)==null?void 0:o.slice(0,10)}...
23
- ${(c=t.authToken)==null?void 0:c.slice(-10)}`})});const j=yield oc.init(M),W=new Jr(M,j);return M.setValue("meeting",W),W})}static setupContext(t,e,i,r){var n,s;const o=sr.createContext(t,e),c=V(V({},b_),e==null?void 0:e.modules),d=e.defaults||{audio:!0,video:!0};return o.setValue("options",e),o.setValue("peerId",t),o.setValue("modules",c),o.setValue("sdkName","web-core"),o.setValue("meetingId",i),o.setValue("apiBase",r.apiBase),o.setValue("baseURI",r.baseURI),o.setValue("userId",r.participantId),o.setValue("organizationId",r.orgId),o.setValue("authToken",e.authToken),o.setValue("overrides",(n=e.overrides)!=null?n:{}),o.setValue("env",w_({baseURI:r.baseURI})),o.setValue("defaults",d),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",wi(e.cachedUserDetails)),o.setValue("sdkVersion","3.1.5-staging.3"),(s=e.modules)!=null&&s.experimentalAudioPlayback&&o.setValue("audioPlayback",new hN),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,et);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){var e;Xg.cleanup(),a(this,ln).getValue("peerSessionStore").reset(),(e=a(this,ln).getValue("roomSocketHandler"))==null||e.cleanup();const{selfController:i}=a(this,et);return i.leaveRoom(t)})}get participants(){var t;return(t=a(this,et).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,et).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,et).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,et).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,et).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,et).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,et).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,et).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,et).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,et).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,et).stageController)==null?void 0:t.stage}get stores(){return a(this,et).storesManager}get audio(){return a(this,ln).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,et).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)})}},et=new WeakMap,ln=new WeakMap,Zg);Nl([ft("0002"),hr.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Jr.prototype,"join",1);Nl([ft("0003")],Jr.prototype,"leave",1);Nl([ft("0001"),hr.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Jr,"init",1);Jr=Nl([ft("0000")],Jr);const Qy=Jr;module.exports=Qy;
23
+ ${(c=t.authToken)==null?void 0:c.slice(-10)}`})});const j=yield oc.init(M),W=new Jr(M,j);return M.setValue("meeting",W),W})}static setupContext(t,e,i,r){var n,s;const o=sr.createContext(t,e),c=V(V({},b_),e==null?void 0:e.modules),d=e.defaults||{audio:!0,video:!0};return o.setValue("options",e),o.setValue("peerId",t),o.setValue("modules",c),o.setValue("sdkName","web-core"),o.setValue("meetingId",i),o.setValue("apiBase",r.apiBase),o.setValue("baseURI",r.baseURI),o.setValue("userId",r.participantId),o.setValue("organizationId",r.orgId),o.setValue("authToken",e.authToken),o.setValue("overrides",(n=e.overrides)!=null?n:{}),o.setValue("env",w_({baseURI:r.baseURI})),o.setValue("defaults",d),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",wi(e.cachedUserDetails)),o.setValue("sdkVersion","3.1.5"),(s=e.modules)!=null&&s.experimentalAudioPlayback&&o.setValue("audioPlayback",new hN),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,et);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){var e;Xg.cleanup(),a(this,ln).getValue("peerSessionStore").reset(),(e=a(this,ln).getValue("roomSocketHandler"))==null||e.cleanup();const{selfController:i}=a(this,et);return i.leaveRoom(t)})}get participants(){var t;return(t=a(this,et).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,et).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,et).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,et).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,et).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,et).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,et).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,et).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,et).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,et).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,et).stageController)==null?void 0:t.stage}get stores(){return a(this,et).storesManager}get audio(){return a(this,ln).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,et).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)})}},et=new WeakMap,ln=new WeakMap,Zg);Nl([ft("0002"),hr.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Jr.prototype,"join",1);Nl([ft("0003")],Jr.prototype,"leave",1);Nl([ft("0001"),hr.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Jr,"init",1);Jr=Nl([ft("0000")],Jr);const Qy=Jr;module.exports=Qy;
package/dist/index.es.js CHANGED
@@ -30440,7 +30440,7 @@ let ri = (Wg = class {
30440
30440
  video: true
30441
30441
  };
30442
30442
  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", PC({ baseURI: i.baseURI })), n.setValue("defaults", c), n.setValue("onError", e.onError || (() => {
30443
- })), n.setValue("cachedUserDetails", _s(e.cachedUserDetails)), n.setValue("sdkVersion", "3.1.5-staging.3"), (u = e.modules) != null && u.experimentalAudioPlayback && n.setValue("audioPlayback", new oO()), n;
30443
+ })), n.setValue("cachedUserDetails", _s(e.cachedUserDetails)), n.setValue("sdkVersion", "3.1.5"), (u = e.modules) != null && u.experimentalAudioPlayback && n.setValue("audioPlayback", new oO()), n;
30444
30444
  }
30445
30445
  join() {
30446
30446
  return l(this, null, function* () {
package/dist/index.rn.js CHANGED
@@ -19,4 +19,4 @@ slogScale: ${n}, isVoice: ${r}, minEnergy: ${a(this,Dr)},
19
19
  maxEnergy: ${a(this,Tn)}`),n===-1/0||i<1e-6?{energy:0,isVoice:!1}:((!a(this,Dr)||n<a(this,Dr))&&f(this,Dr,n),(!a(this,Tn)||n>a(this,Tn))&&f(this,Tn,n),{energy:(n-a(this,Dr))/(a(this,Tn)-a(this,Dr))*10||0,isVoice:r})},Cd=new WeakSet,Nh=function(t){return t<5},Vh=new WeakSet,Py=function(t=a(this,$s)){var e;if(!a(this,Fi)||!t){a(this,Br).getValue("flagsmith").hasFeature(Z.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,Fi)}`);return}const i={producerId:a(this,Fi),energy:Math.round(t),silent:U(e=sl,Cd,Nh).call(e,t)};f(this,jo,i.silent),this.reportRequest(i)},mu=new WeakSet,Og=function(t){const e=Math.log10(t);return Math.round(e)},g(Lh,Cd),g(Lh,mu);const EO=(t=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const i=new window.MediaStreamTrackGenerator({kind:"audio"}),r=i.writable.getWriter(),n=48e3,s=128,o=1;let c=0,d=null;const l=()=>u(void 0,null,function*(){try{const m=new Float32Array(s*o),v=new window.AudioData({format:"f32",sampleRate:n,numberOfFrames:s,numberOfChannels:o,timestamp:c,data:m});c+=s/n*1e6,yield r.ready,yield r.write(v)}catch(m){d&&clearInterval(d),r.releaseLock(),i.writable.abort()}});d=window.setInterval(l,100);const h=new MediaStream([i]).getAudioTracks()[0];return h.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),i.writable.abort()}),Object.assign(h,{fakeTracks:"fakeTracks:fakeAudioTrack"}),h.enabled=t,h}catch(i){}const e=window.AudioContext||window.webkitAudioContext;if(e)try{const i=new e;if(!i||i.state!=="running"||!i.destination)return;const r=i.createOscillator();r.frequency.value=0,r.type="sine";const n=i.createGain();n.gain.value=0,r.connect(n);const s=i.createMediaStreamDestination();n.connect(s),r.start();const o=s.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=t,o):void 0}catch(i){return}},kO=(t=!1)=>{var e,i;const r=new MediaStream().getVideoTracks()[0],n=document.createElement("canvas");n.height=(e=r==null?void 0:r.getSettings().height)!=null?e:720,n.width=(i=r==null?void 0:r.getSettings().width)!=null?i:1280;const s=n.getContext("2d");s.fillStyle="black",s.fillRect(0,0,n.width,n.height),setInterval(()=>{s.fillStyle="black",s.fillRect(0,0,n.width,n.height)},1e3);const o=n.captureStream().getVideoTracks()[0];return Object.assign(o,{fakeTracks:"fakeTracks:fakeVideoTrack"}),o.enabled=t,o};var TO=Object.defineProperty,bO=Object.getOwnPropertyDescriptor,me=(t,e,i,r)=>{for(var n=r>1?void 0:r?bO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&TO(e,i,n),n};const Ht=["video/VP9","video/VP8"];var Oc,Nc,St,J,Za,qi,At,ls,us,hs,Vc,hi,Sr,eo,ps,ms,Dt,Gt,on,gs,gu,Ng,fu,Vg,vu,Lg,Lc,yu,Su,Eu,xg,ku,Ug,Tu,Fg,bu,Bg,lt,Et,fs,to,wu,Wg,_u,jg,Iu,Hg;const Ry=(Eu=class{constructor(t,e,i){g(this,on),g(this,gu),g(this,fu),g(this,vu),g(this,Lc),g(this,ku),g(this,Tu),g(this,bu),g(this,lt),g(this,fs),g(this,wu),g(this,_u),g(this,Iu),p(this,"context"),p(this,"authToken"),p(this,"e2ee"),g(this,Oc,void 0),g(this,Nc,void 0),g(this,St,void 0),g(this,J,void 0),g(this,Za,void 0),g(this,qi,void 0),g(this,At,void 0),g(this,ls,void 0),g(this,us,void 0),g(this,hs,void 0),g(this,Vc,void 0),g(this,hi,null),g(this,Sr,void 0),g(this,eo,void 0),g(this,ps,void 0),g(this,ms,void 0),g(this,Dt,void 0),g(this,Gt,void 0);var r,n;this.context=t;const{socket:s}=i;this.mediaJoined=!1,f(this,ps,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,ms,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,qi,e),f(this,St,s),f(this,ls,!1),f(this,J,new fO(t,s,e)),f(this,At,a(this,J).events),f(this,Sr,new Set),f(this,Dt,new Map),f(this,us,!1),f(this,hs,new sh(t.getValue("logger"))),e===De.CF&&f(this,Gt,new Lh(this.context,a(this,J).socketHandler.audioActivity.bind(a(this,J).socketHandler))),this.e2ee=(n=(r=t.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,Vc,op(()=>u(this,null,function*(){if(!a(this,on,gs).mediaJoinAttempted)return;const{roomJoined:o}=yield this.joinRoom(a(this,Nc),a(this,Oc),!0,!0);o&&(this.context.getValue("peerSessionStore").emit(P.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(P.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,on,gs).mediaJoined}set mediaJoined(t){a(this,on,gs).mediaJoined=t}reset(){a(this,J).closeAllProducers(),a(this,J).closeAllConsumers(),a(this,Dt).clear(),a(this,Sr).clear(),f(this,hi,null),a(this,hs).stop(),a(this,J).stopAllTransports(),a(this,J).reset(),f(this,hs,new sh)}joinRoom(t,e){return u(this,arguments,function*(i,r,n=!1,s=!1,o={}){a(this,on,gs).mediaJoinAttempted=!0,f(this,ls,!0),n&&this.reset();try{return yield a(this,hs).push(()=>U(this,gu,Ng).call(this,i,r,s,o),"joinRoom")}catch(c){return this.logger.error("Error in room joining process",{error:c}),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_FAILED),{roomJoined:!1}}})}initializeConnection(t,e){return u(this,arguments,function*(i,r,n=!1,s={}){return a(this,hi)?a(this,hi):(f(this,hi,(()=>u(this,null,function*(){try{yield U(this,Lc,yu).call(this,i,r,n,s)}catch(o){throw f(this,hi,null),o}}))()),a(this,hi))})}getConsumers(){return a(this,J).consumers}leaveRoom(){return u(this,null,function*(){a(this,J).stopAllTransports(),f(this,us,!1),a(this,on,gs).mediaJoinAttempted=!1;const t={closeRoom:!1};a(this,St).sendMessagePromise(a(this,At).leaveRoom,EI.toBinary(t)).then(e=>{var i;(i=cC.fromBinary(e.payload))!=null&&i.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(t){return u(this,null,function*(){return this.createConsumers(t)})}createConsumers(t){return u(this,null,function*(){return t.length===0?Promise.resolve():a(this,J).createConsumers(t)})}closeConsumers(t){return u(this,null,function*(){if(!t.length)return;const e=t.reduce((i,r)=>{const n=a(this,J).producerIdToConsumerIdMap.get(r.producerId);return n?(i.push(n),i):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),i)},[]);yield a(this,J).closeConsumers(e)})}_shareWebcam(t,e){return u(this,null,function*(){const i=e==="video/VP9"?Se.WEBCAM:Se.WEBCAM_BACKUP,r=U(this,lt,Et).call(this,i);if(r){const h=yield r;if(a(this,J).producers.has(h)){const m=a(this,J).producers.get(h);if(!m.closed)return yield m.replaceTrack({track:t}),yield this.resumeWebcam(i),t;yield this.disableWebcam(e)}return this._shareWebcam(t,e)}const n=[e].concat(Ht.filter(h=>h!==e)),s=U(this,Iu,Hg).call(this,t,n),o=Xs(this.context,"disableSimulcast"),c=a(this,qi)===De.CF?Z.ENABLE_CF_SIMULCAST:Z.ENABLE_HIVE_SIMULCAST;!o&&this.context.getValue("flagsmith").hasFeature(c)?(this.logger.info(`Simulcast enabled for SFU: ${a(this,qi)}`),s.encodings=sD(this.context,t)):this.logger.info(`Simulcast disabled for webcam producer, SFU: ${a(this,qi)}`),this.context.getValue("flagsmith").hasFeature(Z.TRACK_HINT)&&(s.track.contentHint=this.context.getValue("flagsmith").getValue(Z.TRACK_HINT));const d=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,Dt).delete(i)},l=a(this,J).createProducer(s,d);return U(this,fs,to).call(this,i,l.then(h=>h.id)),l.then(h=>h.track)})}shareWebcam(t){return u(this,null,function*(){var e;if(t===void 0)return null;const i=(e=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:e.toString();if(i)return this.logger.debug(`Calling _shareWebcam with forced video codec: ${i}`),this._shareWebcam(t,i);const r=Ht.filter(n=>{var s,o;return((o=(s=a(this,Za).sender)==null?void 0:s.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===n))>=0&&a(this,ms).get(n).size>0});return r.length===0&&r.push(Ht[0]),yield Promise.all(r.map(n=>(this.logger.debug(`Calling _shareWebcam with video codec: ${n}`),this._shareWebcam(t,n)))),t})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:i}=t;if(e===void 0)return;const r={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ie.isElectron()},stopTracks:!1},n=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Dt).delete(Se.SCREENSHARE_VIDEO),a(this,Dt).delete(Se.SCREENSHARE_AUDIO)},s=a(this,J).createProducer(r,n);U(this,fs,to).call(this,Se.SCREENSHARE_VIDEO,s.then(c=>c.id));let o;if(i){const c={track:i,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ie.isElectron()},stopTracks:!1,zeroRtpOnPause:a(this,qi)!==De.CF},d=()=>{};o=a(this,J).createProducer(c,d),U(this,fs,to).call(this,Se.SCREENSHARE_AUDIO,o.then(l=>l.id))}yield Promise.all([s,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new xt("track undefined");const e=U(this,lt,Et).call(this,Se.MIC);if(e){const s=yield e;if(a(this,J).producers.has(s)){const o=a(this,J).producers.get(s);if(!o.closed){yield o.replaceTrack({track:t}),yield this.resumeMic(),a(this,Gt)&&(a(this,Gt).audioTrack=t,a(this,Gt).producerId=s,a(this,Gt).start());return}yield a(this,J).closeProducer(s,{stopTrack:!1})}yield this.shareMic(t);return}const i=U(this,_u,jg).call(this,t),r=()=>{a(this,Dt).delete(Se.MIC)},n=a(this,J).createProducer(i,r);U(this,fs,to).call(this,Se.MIC,n.then(s=>s.id)),yield n.then(s=>{a(this,Gt)&&(a(this,Gt).audioTrack=s.track,a(this,Gt).producerId=s.id,a(this,Gt).start())})}catch(e){throw new _(e)}})}pauseMic(){return u(this,null,function*(){var t;const e=yield U(this,lt,Et).call(this,Se.MIC),i=a(this,J).producers.get(e);if(!i){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(i.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}i.pause(),(t=a(this,Gt))==null||t.stop();const r={producerId:i.id,pause:!0};a(this,St).sendMessage(a(this,At).toggleProducer,gc.toBinary(r))})}pauseWebcam(){return u(this,null,function*(){const t=yield U(this,lt,Et).call(this,Se.WEBCAM),e=yield U(this,lt,Et).call(this,Se.WEBCAM_BACKUP),i=a(this,J).producers.get(t),r=a(this,J).producers.get(e);if(!i&&!r){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const n=s=>{const o={producerId:s.id,pause:!0};a(this,St).sendMessage(a(this,At).toggleProducer,gc.toBinary(o))};i&&(i.pause(),n(i)),r&&(r.pause(),n(r))})}resumeMic(){return u(this,null,function*(){const t=yield U(this,lt,Et).call(this,Se.MIC),e=a(this,J).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,e);const i={producerId:e.id,pause:!1};a(this,St).sendMessage(a(this,At).toggleProducer,gc.toBinary(i))})}resumeWebcam(){return u(this,arguments,function*(t=Se.WEBCAM){const e=yield U(this,lt,Et).call(this,t),i=a(this,J).producers.get(e);if(!i){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!i.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}i.resume(),i.appData.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,i);const r={producerId:i.id,pause:!1};a(this,St).sendMessage(a(this,At).toggleProducer,gc.toBinary(r))})}disableWebcam(t){return u(this,null,function*(){const e=t==="video/VP9"?Se.WEBCAM:Se.WEBCAM_BACKUP,i=yield U(this,lt,Et).call(this,e);U(this,wu,Wg).call(this,e),i&&(yield a(this,J).closeProducer(i))})}disableMic(){return u(this,null,function*(){var t;const e=yield U(this,lt,Et).call(this,Se.MIC);e&&(yield a(this,J).closeProducer(e)),(t=a(this,Gt))==null||t.stop(),a(this,Dt).delete(Se.MIC)})}disableScreenShare(){return u(this,null,function*(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=yield U(this,lt,Et).call(this,Se.SCREENSHARE_VIDEO),e=yield U(this,lt,Et).call(this,Se.SCREENSHARE_AUDIO);t&&(yield a(this,J).closeProducer(t)),e&&(yield a(this,J).closeProducer(e)),a(this,Sr).clear(),a(this,Dt).delete(Se.SCREENSHARE_VIDEO),a(this,Dt).delete(Se.SCREENSHARE_AUDIO)})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(t,e){return u(this,null,function*(){if(t){const i=yield U(this,lt,Et).call(this,Se.WEBCAM),r=yield U(this,lt,Et).call(this,Se.WEBCAM_BACKUP);yield a(this,J).closeProducer(i,{stopTrack:!1}),yield a(this,J).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const i=yield U(this,lt,Et).call(this,Se.SCREENSHARE_VIDEO);yield a(this,J).closeProducer(i,{stopTrack:!1}),this.shareScreen({video:e})}})}changeDisplayName(t,e){return u(this,null,function*(){const i={displayName:t,participantId:e!=null?e:this.peerId};if(!(yield a(this,J).socketHandler.changeDisplayName(i)))throw new Error("failed to change display name!")})}kick(t){const e={peerIds:[t]};a(this,J).socketHandler.kickPeer(e)}kickAll(){a(this,J).socketHandler.kickAll()}muteAll(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForPeer(t,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(t){return u(this,null,function*(){const e={participantId:t!=null?t:""};try{yield a(this,St).sendMessagePromise(a(this,At).globalPinPeer,NI.toBinary(e))}catch(i){this.logger.error("Error in pinning peer:",{error:i})}})}validateScreenShare(t){return this.peerId===t.peerId&&a(this,J).producers.get(t.producerId)&&a(this,Sr).add(t.consumerPeerId),a(this,Sr).size}switchConsumersToLayer(t,e){return u(this,null,function*(){const i=t.map(r=>this.getConsumers().get(r));a(this,J).switchConsumersToLayer(i,e)})}handleSocketEvents(){return u(this,null,function*(){a(this,St).on(a(this,At).peerProducerCreateBroadcast,({payload:t})=>{var e,i;if(this.mediaJoined)try{const{participantId:r,producerState:n}=UC.fromBinary(t);if(r===this.peerId)return;if(n!=null&&n.mimeType||(n.mimeType=n.kind===Bi.AUDIO?"audio/opus":"video/VP8"),n.kind===Bi.VIDEO&&!n.screenShare&&((i=(e=a(this,Za).receiver)==null?void 0:e.video)==null?void 0:i.codecs.findIndex(s=>s.mimeType===Ht[0]))>=0&&a(this,ps).get(Ht[0]).has(r)&&n.mimeType!==Ht[0]){this.logger.warn(`Ignoring producer: ${n.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${n}`),this.context.getValue("peerSessionStore").emit(P.NEW_PRODUCER,{peerId:r,producer:q(V({},n),{kind:n.kind===Bi.AUDIO?"audio":"video",producingPeerId:r})})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),a(this,St).on(a(this,At).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:i,producerState:{kind:r,pause:n,producerId:s}}=Mm.fromBinary(t),o=r===Bi.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${s}, kind:${o}, paused:${n} payload: ${JSON.stringify(Mm.fromBinary(t))}`),e===this.peerId&&i!==this.peerId&&n&&this.context.getValue("peerSessionStore").emit(o==="audio"?P.MUTE_SELF:P.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(P.PRODUCER_TOGGLE,{peerId:e,producerId:s,paused:n,kind:o}),Array.from(this.getConsumers().values()).filter(c=>c.producerId===s).forEach(c=>{c.paused!==n&&(this.logger.debug(`consumer state mismatched for ${c.id}. updating consumer pause state ${c.paused} to ${n}`),n?(c.pause(),this.context.getValue("peerSessionStore").emit(P.CONSUMER_PAUSED,{id:c.id})):(c.resume(),this.context.getValue("peerSessionStore").emit(P.CONSUMER_RESUMED,{id:c.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,St).on(a(this,At).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=ju.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,Sr).delete(e),a(this,J).consumers.forEach(i=>{i.peerId===e&&i.close()}),this.context.getValue("peerSessionStore").emit(P.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),a(this,St).on(a(this,At).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:i}}=WC.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(P.PRODUCER_CLOSED,{peerId:e,producerId:i});const r=a(this,J).producerIdToConsumerIdMap.get(i);if(!r){this.logger.warn(`no consumer found for producer:${i}`);return}this.logger.info(`closing consumer ${r}, producer id: ${i}`),a(this,J).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),a(this,J).producerIdToConsumerIdMap.delete(i),this.context.getValue("peerSessionStore").emit(P.CONSUMER_CLOSED,{id:r})}).catch(n=>{this.logger.error("error closing consumer",{error:n})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,St).on(a(this,At).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,ls)&&!a(this,us)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_DISCONNECTED),a(this,Vc).call(this))})})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,i)=>{const r=a(this,J).consumers.get(i);r&&this.context.getValue("peerSessionStore").emit(P.CONSUMER_SCORE_UPDATE,{id:i,kind:r.kind,peerId:r.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,i)=>{const r=Array.from(a(this,J).producers.values()).find(n=>n.id===i);r&&this.context.getValue("peerSessionStore").emit(P.PRODUCER_SCORE_UPDATE,{id:i,kind:r.kind,appData:r.appData,score:e.score,scoreStats:e})})})}handlePeerCapabilities(t,e){var i,r,n,s;for(let o=0;o<=Ht.length;o+=1){const c=Ht[o];if(((r=(i=e==null?void 0:e.receiver)==null?void 0:i.video)==null?void 0:r.codecs.findIndex(d=>d.mimeType===c))>=0||o===Ht.length-1){a(this,ms).get(c).add(t);break}}for(let o=0;o<=Ht.length;o+=1){const c=Ht[o];if(((s=(n=e==null?void 0:e.sender)==null?void 0:n.video)==null?void 0:s.codecs.findIndex(d=>d.mimeType===c))>=0||o===Ht.length-1){a(this,ps).get(c).add(t);break}}}handlePeerLeaving(t){this.context.getValue("flagsmith").hasFeature(Z.FORCE_VIDEO_CODEC)||(a(this,ps).forEach(e=>e.delete(t)),a(this,ms).forEach((e,i)=>{e.delete(t),!(e.size!==0||i===Ht[0])&&this.disableWebcam(i)}))}},Oc=new WeakMap,Nc=new WeakMap,St=new WeakMap,J=new WeakMap,Za=new WeakMap,qi=new WeakMap,At=new WeakMap,ls=new WeakMap,us=new WeakMap,hs=new WeakMap,Vc=new WeakMap,hi=new WeakMap,Sr=new WeakMap,eo=new WeakMap,ps=new WeakMap,ms=new WeakMap,Dt=new WeakMap,Gt=new WeakMap,on=new WeakSet,gs=function(){return this.context.getValue("connectionHandler")},gu=new WeakSet,Ng=function(t,e,i,r){return u(this,null,function*(){f(this,Nc,t);try{return a(this,hi)?yield a(this,hi):yield U(this,Lc,yu).call(this,t,e,i,r),U(this,vu,Lg).call(this,e),{roomJoined:yield U(this,fu,Vg).call(this)}}catch(n){return this.logger.error("Failed to complete room join",{error:n}),{roomJoined:!1}}finally{f(this,hi,null)}})},fu=new WeakSet,Vg=function(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:t}=yield a(this,J).socketHandler.notifySelfJoinComplete();return f(this,Oc,t.roomUuid),f(this,us,!0),f(this,ls,!1),!0}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,!1}})},vu=new WeakSet,Lg=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:q(V({},Ie.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(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},Lc=new WeakSet,yu=function(t,e,i,r){return u(this,null,function*(){var n,s;try{(s=a(this,eo))!=null||f(this,eo,U(n=Ry,Su,xg).call(n));const o=U(this,ku,Ug).call(this);yield U(this,Tu,Fg).call(this,t,e,i,o),yield a(this,J).setupTransports({send:!0,recv:!0}),yield U(this,bu,Bg).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}})},Su=new WeakSet,xg=function(){const{ipInfo:t}=pt();if(!(t!=null&&t.loc))return;const[e,i]=t.loc.split(",").map(parseFloat);return{latitude:e,longitude:i}},ku=new WeakSet,Ug=function(){var t;const e=(t=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:t.toString(),i=rO(e);return f(this,Za,i),i},Tu=new WeakSet,Fg=function(t,e,i,r){return u(this,null,function*(){yield my((n,s)=>u(this,null,function*(){if(!a(this,St).isConnected){s(new Error("Socket is not connected"));return}n>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${n}`});try{yield a(this,J).socketHandler.joinRoom(e,t,r,i,a(this,eo))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:this.context.getValue("flagsmith").hasFeature(Z.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3})})},bu=new WeakSet,Bg=function(t){return u(this,null,function*(){if(!(a(this,qi)===De.HIVE||!this.context.getValue("flagsmith").hasFeature(Z.PRECREATE_PRODUCERS)||!t))try{const e=[];if(t.canProduceVideo===G.Allowed&&e.push(this.shareWebcam(kO(!1))),t.canProduceAudio===G.Allowed){const i=EO(!1);i&&e.push(this.shareMic(i))}e.length>0&&(yield Promise.all(e))}catch(e){this.logger.warn("Failed to precreate producers",{error:e})}})},lt=new WeakSet,Et=function(t){return a(this,Dt).get(t)},fs=new WeakSet,to=function(t,e){return a(this,Dt).set(t,e)},wu=new WeakSet,Wg=function(t){return a(this,Dt).delete(t)},_u=new WeakSet,jg=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:a(this,qi)!==De.CF}},Iu=new WeakSet,Hg=function(t,e){return{track:t,codecOptions:e?e.map(i=>({name:i.split("/")[1]})):[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},g(Eu,Su),Eu);let le=Ry;me([k.trace("MediaNodeClient.reset",{country:k.location.country})],le.prototype,"reset",1);me([k.trace("MediaNodeClient.joinRoom")],le.prototype,"joinRoom",1);me([k.trace("MediaNodeClient.leaveRoom")],le.prototype,"leaveRoom",1);me([k.trace("MediaNodeClient.activatePeers")],le.prototype,"activatePeers",1);me([k.trace("MediaNodeClient.createConsumers")],le.prototype,"createConsumers",1);me([k.trace("MediaNodeClient.closeConsumers")],le.prototype,"closeConsumers",1);me([k.trace("MediaNodeClient._shareWebcam")],le.prototype,"_shareWebcam",1);me([k.trace("MediaNodeClient.shareWebcam")],le.prototype,"shareWebcam",1);me([k.trace("MediaNodeClient.shareScreen")],le.prototype,"shareScreen",1);me([k.trace("MediaNodeClient.shareMic")],le.prototype,"shareMic",1);me([k.trace("MediaNodeClient.pauseMic")],le.prototype,"pauseMic",1);me([k.trace("MediaNodeClient.pauseWebcam")],le.prototype,"pauseWebcam",1);me([k.trace("MediaNodeClient.resumeMic")],le.prototype,"resumeMic",1);me([k.trace("MediaNodeClient.resumeWebcam")],le.prototype,"resumeWebcam",1);me([k.trace("MediaNodeClient.disableWebcam")],le.prototype,"disableWebcam",1);me([k.trace("HiveClient.disableMic")],le.prototype,"disableMic",1);me([k.trace("HiveClient.disableScreenShare")],le.prototype,"disableScreenShare",1);me([k.trace("MediaNodeClient.muteSelf")],le.prototype,"muteSelf",1);me([k.trace("MediaNodeClient.resetVideoProducers")],le.prototype,"resetVideoProducers",1);me([k.trace("MediaNodeClient.changeDisplayName")],le.prototype,"changeDisplayName",1);me([k.trace("MediaNodeClient.kickPeer")],le.prototype,"kick",1);me([k.trace("MediaNodeClient.kickAllPeers")],le.prototype,"kickAll",1);me([k.trace("MediaNodeClient.muteAll")],le.prototype,"muteAll",1);me([k.trace("MediaNodeClient.muteAllVideo")],le.prototype,"muteAllVideo",1);me([k.trace("MediaNodeClient.disableAudio")],le.prototype,"disableAudio",1);me([k.trace("MediaNodeClient.disableVideo")],le.prototype,"disableVideo",1);me([k.trace("MediaNodeClient.pinPeer")],le.prototype,"pinPeer",1);me([k.trace("MediaNodeClient.validateScreenShare")],le.prototype,"validateScreenShare",1);function My(t,e,i){const r=t.getValue("roomNodeClient");if(r){if(r)return r;throw new Error("Room node client already set up.")}const n=new le(t,e,i);return t.setValue("roomNodeClient",n),n}function Ay(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch(i){t.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var wO=Object.defineProperty,_O=Object.getOwnPropertyDescriptor,Jn=(t,e,i,r)=>{for(var n=r>1?void 0:r?_O(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&wO(e,i,n),n},cn,Ai,re,Ot,qt,Gg;const Dy=(Gg=class{constructor(t,e,i,r){g(this,Ot),p(this,"self"),p(this,"authToken"),g(this,cn,void 0),p(this,"viewType"),g(this,Ai,void 0),g(this,re,void 0);const{socket:n}=i,s=t.getValue("authToken");this.self=e,f(this,re,t),this.viewType=r,this.authToken=s,f(this,cn,n),f(this,Ai,i),e.config.viewType!==Ut.Chat&&this.setupEvents()}get peerId(){return a(this,re).getValue("peerId")}get telemetry(){return a(this,re).getValue("telemetry")}get logger(){return a(this,re).getValue("logger")}get mediaJoined(){return a(this,re).getValue("connectionHandler").mediaJoined}static init(t,e,i,r,n){return u(this,null,function*(){const s=pt(),o=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield st.__init__(t,i,r,n,n.name,c);t.setValue("self",d);const l=t.getValue("logger");if(navigator.product!=="ReactNative"){const h=!t.getValue("flagsmith").hasFeature(Z.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const m=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(m)}),t.getValue("callstats").devices("AUDIO",m==null?void 0:m.filter(v=>v.kind==="audioinput")),t.getValue("callstats").devices("VIDEO",m==null?void 0:m.filter(v=>v.kind==="videoinput")),t.getValue("callstats").devices("SPEAKER",m==null?void 0:m.filter(v=>v.kind==="audiooutput")),l.info("Callstats:: initializing");try{yield t.getValue("callstats").initialize({peerId:o,engineName:Ie.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:t.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:Mv(t),skipConnectivityChecks:h}),l.info("Callstats:: initialized")}catch(v){l.error("Callstats:: initialization failed",{error:v})}}),0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new Dy(t,d,e,n.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:i,permissions:r,audioEnabled:n,videoEnabled:s,screenShareEnabled:o,screenShareTracks:c}=this.self;if(r.canProduceAudio===G.Allowed&&n)try{yield a(this,Ot,qt).shareMic(e),this.self.audioEnabled||a(this,Ot,qt).pauseMic()}catch(d){this.self.disableAudio()}if(r.canProduceVideo===G.Allowed&&s)try{const d=yield a(this,Ot,qt).shareWebcam(i);d&&d.id!==i.id&&a(this,re).getValue("flagsmith").hasFeature(Z.EXP_RESHARE)&&(yield a(this,Ot,qt).shareWebcam(d)),this.self.videoEnabled||a(this,Ot,qt).pauseWebcam()}catch(d){this.self.disableVideo()}if(r.canProduceScreenshare===G.Allowed&&o)try{yield(t=a(this,Ot,qt))==null?void 0:t.shareScreen({video:c.video,audio:c.audio})}catch(d){this.self.disableScreenShare()}})}kickHandler(t){return u(this,null,function*(){let e="kicked";(t==null?void 0:t.kickType)==="kickAll"&&(e="ended"),this.leaveRoom(e)})}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(t){return u(this,null,function*(){a(this,re).getValue("callstats").callEnded(),a(this,Ot,qt).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){a(this,re).getValue("peerSessionStore").on(P.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),a(this,re).getValue("peerSessionStore").on(P.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,re).getValue("peerSessionStore").on(P.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,re).getValue("peerSessionStore").on(P.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,re).getValue("peerSessionStore").on(P.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),a(this,re).getValue("peerSessionStore").on(P.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&a(this,re).getValue("flagsmith").hasFeature(Z.REFRESH_ID_ON_DISCONNECTION)&&(e=Vn()),a(this,cn).updateURL(e),a(this,re).getValue("telemetry").resetPeerId(e),pt().setHeader("dyte-tracing-id",e),sr.remapContext(e,a(this,re)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,re).getValue("peerSessionStore").on(P.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Ai).on(F.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Ai).on($c.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&a(this,re).getValue("peerSessionStore").emit(P.UPDATE_PERMISSIONS,e.patch)})}),a(this,Ai).on(F.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Ai).on(F.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Ai).on(F.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,re).getValue("peerSessionStore").onAsync(P.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,re).getValue("peerSessionStore").on(P.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:i,scoreStats:r})=>{var n;const s=(n=i==null?void 0:i.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:s,score:t,participantId:this.self.id,scoreStats:r})}),a(this,re).getValue("peerSessionStore").on(P.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),a(this,re).getValue("callstats").audioOff())})),a(this,re).getValue("peerSessionStore").on(P.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),a(this,re).getValue("callstats").videoOff())})),a(this,re).getValue("peerSessionStore").onAsync(P.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,re).getValue("peerSessionStore").on(P.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield a(this,Ai).joinRoom(this.self);a(this,Ai).socket.flush();const i=hp(e.stageType);if(a(this,re).setValue("stageStatus",i,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),a(this,re).notify("stageStatus")}catch(e){throw this.logger.error("Error in joinRoom",{error:e}),e}})}leaveRoom(t="left"){return u(this,null,function*(){var e,i;if(t==="rejected"){try{(e=a(this,cn))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),a(this,re).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),a(this,re).notify("stageStatus");try{(i=a(this,cn))==null||i.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}Ay(a(this,re)),yield a(this,re).getValue("roomSocketHandler").cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}joinMediaRoom(t=!1){return u(this,null,function*(){var e,i;const{peerId:r,viewType:n,meetingId:s,stageStatus:o,roomNodeOptions:c}=a(this,re).getAllValues(),{sfu:d}=c;try{if(n===Ut.Livestream){if(o!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}My(a(this,re),d,{socket:a(this,cn),peerId:r})}const{canProduceAudio:l,canProduceVideo:h,canProduceScreenshare:m}=this.self.permissions,{roomJoined:v}=(i=yield(e=a(this,Ot,qt))==null?void 0:e.joinRoom(this.self.name,s,t,t,{canProduceAudio:l,canProduceVideo:h,canProduceScreenshare:m}))!=null?i:{};if(!v)return;o==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(l){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:l}),new _("Error: could not join media room","0002")}})}leaveMediaRoom(t){return u(this,null,function*(){const e=a(this,re).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===Ut.Webinar)&&a(this,Ot,qt)&&(a(this,Ot,qt).mediaJoined&&t!=="disconnected"&&(yield a(this,Ot,qt).leaveRoom()),!(t==="stageLeft"&&e===Ut.Livestream)&&(a(this,Ot,qt).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()})}},cn=new WeakMap,Ai=new WeakMap,re=new WeakMap,Ot=new WeakSet,qt=function(){return a(this,re).getValue("roomNodeClient")},Gg);let zr=Dy;Jn([k.trace("SelfController.resetSelf")],zr.prototype,"resetSelf",1);Jn([k.trace("SelfController.setupEvents")],zr.prototype,"setupEvents",1);Jn([k.trace("SelfController.joinRoom")],zr.prototype,"joinRoom",1);Jn([k.trace("SelfController.leaveRoom")],zr.prototype,"leaveRoom",1);Jn([k.trace("SelfController.joinMediaRoom")],zr.prototype,"joinMediaRoom",1);Jn([k.trace("SelfController.leaveMediaRoom")],zr.prototype,"leaveMediaRoom",1);Jn([k.trace("SelfController.init")],zr,"init",1);var Pd;class IO{constructor(e){g(this,Pd,void 0),f(this,Pd,e)}on(e,i){let r;e===F.roomPeerCount?r=Om.fromBinary.bind(Om):r=Gm.fromBinary.bind(Gm),a(this,Pd).on(e,({payload:n})=>{if(e===F.roomPeerCount&&!n)return;const s=r(n);i(s)})}}Pd=new WeakMap;var Rd,Md;class CO{constructor(e,i){g(this,Rd,void 0),g(this,Md,void 0),f(this,Rd,i),f(this,Md,e)}get logger(){return a(this,Md).getValue("logger")}on(e,i){let r,n;switch(e){case F.transcript:{r=Gl.fromBinary.bind(Gl),n=Gl.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Rd).on(e,({payload:s})=>{let o=n;try{o=r(s)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}}Rd=new WeakMap,Md=new WeakMap;var PO=Object.defineProperty,RO=Object.getOwnPropertyDescriptor,wp=(t,e,i,r)=>{for(var n=r>1?void 0:r?RO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&PO(e,i,n),n},Or,Po;class Rl{constructor(e,i){g(this,Or,void 0),g(this,Po,void 0),f(this,Or,i),f(this,Po,e)}get logger(){return a(this,Po).getValue("logger")}get telemetry(){return a(this,Po).getValue("telemetry")}getPolls(){return a(this,Or).sendMessagePromise(Zi.getPolls)}createPoll(e,i,r=!1,n=!1){const s={anonymous:r,hideVotes:n,question:e,options:i};return a(this,Or).sendMessage(Zi.createPoll,RA.toBinary(s))}votePoll(e,i){const r={index:i,pollId:e};return a(this,Or).sendMessage(Zi.votePoll,AA.toBinary(r))}on(e,i){let r,n;switch(e){case Zi.updatePoll:case Zi.createPoll:case Zi.votePoll:{r=Yl.fromBinary.bind(Yl),n=Yl.create();break}}a(this,Or).on(e,({payload:s})=>{let o=n;try{o=r(s)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}removeListeners(e){a(this,Or).removeListeners(e)}}Or=new WeakMap,Po=new WeakMap;wp([k.trace("PollSocketHandler.getPolls")],Rl.prototype,"getPolls",1);wp([k.trace("PollSocketHandler.createPoll")],Rl.prototype,"createPoll",1);wp([k.trace("PollSocketHandler.votePoll")],Rl.prototype,"votePoll",1);var MO=Object.defineProperty,AO=Object.getOwnPropertyDescriptor,DO=(t,e,i,r)=>{for(var n=r>1?void 0:r?AO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&MO(e,i,n),n},si;class Oy{constructor(e,i){p(this,"socket"),g(this,si,void 0),f(this,si,e),this.socket=i,this.handleSocketEvents(),a(this,si).setValue("roomSocketHandler",this)}get telemetry(){return a(this,si).getValue("telemetry")}get logger(){return a(this,si).getValue("logger")}cleanup(){return u(this,null,function*(){var e;try{(e=this.socket)==null||e.disconnect()}catch(i){this.logger.error("roomSocketHandler::cleanup")}})}joinRoom(e){return u(this,null,function*(){var i;this.socket.joinAttempted=!0;const r={capabilities:[],peer:{displayName:(i=e.name)!=null?i:"Participant",customParticipantId:e.customParticipantId,peerId:e.id,userId:e.userId,displayPictureUrl:e.picture,waitlisted:!1},roomUuid:""},n=this.socket.sendMessagePromise(F.joinRoom,fP.toBinary(r));try{const{peer:s}=ys.fromBinary((yield n).payload);a(this,si).getValue("connectionHandler").socketJoined=!0,a(this,si).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_ROOM_JOINED,{peer:s});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=yield Promise.all([o,c]);return a(this,si).getValue("peerSessionStore").emit(P.ROOM_STATE,d),a(this,si).getValue("peerSessionStore").emit(P.SOCKET_PEERS,l),{peer:s}}catch(s){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:s}),new _("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,s)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return eR.fromBinary((yield this.socket.sendMessagePromise(F.getAllAddedParticipants)).payload).participants.map(e=>{var i=e,{id:r}=i,n=ml(i,["id"]);return q(V({},n),{userId:r})})}catch(e){return[]}})}getRoomPeers(e,i,r){return u(this,null,function*(){let n;try{const s={seachQuery:e,limit:i,offset:r},o=yield this.socket.sendMessagePromise(F.getRoomPeersInfo,aP.toBinary(s));n=ql.fromBinary(o.payload)}catch(s){this.logger.error("getRoomPeers::binary_decode_error",{error:s})}return n})}getRoomPeersNonPaginated(){return u(this,null,function*(){let e;try{const i=yield this.socket.sendMessagePromise(F.getRoomPeersInfo);e=ql.fromBinary(i.payload)}catch(i){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:i})}return e})}getStagePeers(){return u(this,null,function*(){let e;try{const i=yield this.socket.sendMessagePromise(F.getRoomPeersInfo);e=ql.fromBinary(i.payload)}catch(i){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:i})}return e})}getPeerInfo(e){return u(this,null,function*(){let i;try{const r=yield this.socket.sendMessagePromise(F.getPeerInfo,Wv.toBinary({peerId:e}));i=ys.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return i})}getRoomState(){return u(this,null,function*(){let e=Nm.create();try{const i=yield this.socket.sendMessagePromise(F.getRoomInfo);e=Nm.fromBinary(i.payload)}catch(i){this.logger.error("getRoomState::binary_decode_error",{error:i})}return e})}getRoomStageState(){return u(this,null,function*(){let e=Um.create();try{const i=yield this.socket.sendMessagePromise(F.getRoomStageState);e=Um.fromBinary(i.payload)}catch(i){this.logger.error("getRoomStageState::binary_decode_error",{error:i})}return e})}broadcastMessage(e,i){return u(this,null,function*(){const r={type:e,payload:new TextEncoder().encode(JSON.stringify(i)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(F.broadcastMessage,Ta.toBinary(r))})}broadcastToMeetings(e,i,r){return u(this,null,function*(){const n={type:e,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:i,broadcastType:1};return this.socket.sendMessagePromise(F.broadcastToEntity,Ta.toBinary(n))})}broadcastToPeers(e,i,r){return u(this,null,function*(){const n={type:e,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:i,broadcastType:0};return this.socket.sendMessage(F.broadcastToEntity,Ta.toBinary(n))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(F.leaveRoom,yP.toBinary({}))})}kick(e){return u(this,null,function*(){const i={peerIds:[e]};this.socket.sendMessage(F.kick,Hv.toBinary(i))})}kickAll(e=!1){return u(this,null,function*(){const i={propagateKickAcrossRooms:e};this.socket.sendMessage(F.kickAll,Uv.toBinary(i))})}getWaitingRoomRequests(){this.socket.sendMessage(F.getWaitingRoomRequests)}acceptWaitingRoomRequest(e){const i={userIds:e};this.socket.sendMessage(F.acceptWaitingRoomRequests,aR.toBinary(i))}rejectWaitingRoomRequest(e){const i={userIds:e};this.socket.sendMessage(F.denyWaitingRoomRequests,cR.toBinary(i))}updatePermissions(e,i){return u(this,null,function*(){const r={updatePeersPresets:[]};return e.forEach(n=>{r.updatePeersPresets.push({userIds:n,patch:i})}),this.socket.sendMessagePromise($c.updateUserPreset,xR.toBinary(r))})}handleSocketEvents(){this.socket.on(F.broadcastMessage,({payload:e})=>{try{const i=Ta.fromBinary(e);a(this,si).getValue("peerSessionStore").emit(P.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(i.payload)),type:i.type,timestamp:i.timestamp})}catch(i){this.logger.error("failed to decode broadcast message:",i)}}),this.socket.on(F.broadcastToEntity,({payload:e})=>{try{const i=Ta.fromBinary(e);a(this,si).getValue("peerSessionStore").emit(P.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(i.payload)),type:i.type,timestamp:i.timestamp})}catch(i){this.logger.error("failed to decode peer broadcast message:",i)}})}on(e,i){let r,n;switch(e){case F.joinRoom:case F.leaveRoom:case F.kick:case F.kickAll:{r=ys.fromBinary.bind(ys),n=ys.create();break}case F.getWaitingRoomRequests:{r=(s,o)=>s?xm.fromBinary(s,o):{requests:[]},n=xm.create();break}case F.recordingPaused:case F.recordingStarted:case F.recordingStopped:{r=Jm.fromBinary.bind(Jm);break}case $c.updateUserPreset:{r=Fm.fromBinary.bind(Fm);break}case Ti.peerJoinedBroadcast:case oi.peerJoinedBroadcast:{r=Pm.fromBinary.bind(Pm);break}case Ti.selfJoinComplete:case oi.selfJoinComplete:{r=Wu.fromBinary.bind(Wu);break}case Ti.globalPeerPinBroadcast:case oi.globalPeerPinBroadcast:{r=Am.fromBinary.bind(Am);break}case Ti.selectedPeer:case oi.selectedPeer:{r=Bu.fromBinary.bind(Bu);break}case Ti.selectedPeerDiff:case oi.selectedPeerDiff:{r=Cm.fromBinary.bind(Cm);break}case Ti.leaveRoom:case oi.leaveRoom:{r=ju.fromBinary.bind(ju);break}}this.socket.on(e,({payload:s})=>{let o=n;if(!r)return i(void 0);try{o=r(s)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}getUserPermissions(e){return u(this,null,function*(){const i={userIds:[e]};try{const r=yield this.socket.sendMessagePromise($c.getUserPresets,MR.toBinary(i)),n=NR.fromBinary(r.payload).peerPresets[0],s=new TextDecoder().decode(n.preset),o=JSON.parse(s).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}})}}si=new WeakMap;DO([k.trace("RoomSocketHandler.joinRoom")],Oy.prototype,"joinRoom",1);var Kt;class OO{constructor(e){g(this,Kt,void 0),f(this,Kt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield a(this,Kt).sendMessagePromise(F.getStageRequests);return e?zl.fromBinary(e):{stageRequests:[]}})}requestAccess(){a(this,Kt).sendMessage(F.requestStageAccess)}cancelRequestAccess(){a(this,Kt).sendMessage(F.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,Kt).sendMessage(F.grantStageAccess,SA.toBinary(i))})}denyAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,Kt).sendMessage(F.denyStageAccess,kA.toBinary(i))})}joinStage(){return a(this,Kt).sendMessagePromise(F.joinStage,void 0,void 0,F.peerStageStatusUpdate)}leaveStage(e){const i={userIds:[e]};return a(this,Kt).sendMessagePromise(F.leaveStage,$m.toBinary(i),void 0,F.peerStageStatusUpdate)}kick(e){const i={userIds:e};return a(this,Kt).sendMessagePromise(F.leaveStage,$m.toBinary(i))}on(e,i){let r;switch(e){case F.grantStageAccess:case F.denyStageAccess:{r=void 0;break}case F.getStagePeers:{r=qm.fromBinary.bind(qm);break}case F.getStageRequests:case F.requestStageAccess:case F.cancelStageRequest:{r=zl.fromBinary.bind(zl);break}case F.peerStageStatusUpdate:{r=Dm.fromBinary.bind(Dm);break}}a(this,Kt).on(e,({payload:n,id:s})=>{if(!n||!r)return i(void 0,s);const o=r(n);return i(o,s)})}getPeerInfo(e){return u(this,null,function*(){const i=yield a(this,Kt).sendMessagePromise(F.getPeerInfo,Wv.toBinary({peerId:e}));return ys.fromBinary(i.payload)})}}Kt=new WeakMap;var it,Ad;class NO{constructor(e,i){g(this,it,void 0),g(this,Ad,void 0),f(this,it,i),f(this,Ad,e)}get logger(){return a(this,Ad).getValue("logger")}addPlugin(e,i){a(this,it).sendMessage($.addPlugin,LM.toBinary({pluginId:e,staggered:i}))}removePlugin(e){a(this,it).sendMessage($.removePlugin,UM.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield a(this,it).sendMessagePromise($.getPlugins);return e?oA.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,i,r){const n={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(i))};a(this,it).sendMessage($.customPluginEventToRoom,KM.toBinary(n),r)}customPluginEventToPeers(e,i,r,n){const s={pluginId:e,peerIds:i,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,it).sendMessage($.customPluginEventToPeers,YM.toBinary(s),n)}enablePluginForRoom(e,i){a(this,it).sendMessage($.enablePluginForRoom,BM.toBinary({pluginId:e}),i)}enablePluginForPeers(e,i,r){a(this,it).sendMessage($.enablePluginForPeers,GM.toBinary({pluginId:e,peerIds:i}),r)}disablePluginForRoom(e,i){a(this,it).sendMessage($.disablePluginForRoom,jM.toBinary({pluginId:e}),i)}disablePluginForPeers(e,i,r){a(this,it).sendMessage($.disablePluginForPeers,$M.toBinary({pluginId:e,peerIds:i}),r)}storeInsertKeys(e,i,r,n){const s={pluginId:e,storeName:i,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,it).sendMessage($.storeInsertKeys,Bm.toBinary(s),n)}storeGetKeys(e,i,r,n){const s={pluginId:e,storeName:i,getKeys:r.map(o=>({storeKey:o.key}))};a(this,it).sendMessage($.storeGetKeys,eA.toBinary(s),n)}storeDeleteKeys(e,i,r,n){const s={pluginId:e,storeName:i,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,it).sendMessage($.storeDeleteKeys,iA.toBinary(s),n)}storeDelete(e,i,r){a(this,it).sendMessage($.storeDelete,nA.toBinary({pluginId:e,storeName:i}),r)}getPluginDataOld(e,i){this.logger.info("getPluginDataOld",{plugin:{id:e,storeName:i}})}storePluginDataOld(e,i,r){const n={pluginId:e,storeName:i,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};a(this,it).sendMessage($.storeInsertKeys,Bm.toBinary(n))}on(e,i){let r;switch(e){case $.addPlugin:case $.enablePluginForPeers:case $.enablePluginForRoom:{r=$u.fromBinary.bind($u);break}case $.removePlugin:case $.disablePluginForPeers:case $.disablePluginForRoom:{r=Wm.fromBinary.bind(Wm);break}case $.customPluginEventToPeers:case $.customPluginEventToRoom:{r=Hm.fromBinary.bind(Hm);break}case $.storeInsertKeys:case $.storeGetKeys:case $.storeDeleteKeys:case $.storeDelete:{r=jm.fromBinary.bind(jm);break}}a(this,it).on(e,({payload:n,id:s})=>{const o=r(n);return i(o,s)})}}it=new WeakMap,Ad=new WeakMap;var VO=Object.defineProperty,LO=(t,e,i)=>e in t?VO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,xO=(t,e,i)=>(LO(t,typeof e!="symbol"?e+"":e,i),i),_p=(t,e,i)=>{if(!e.has(t))throw TypeError("Cannot "+i)},N=(t,e,i)=>(_p(t,e,"read from private field"),i?i.call(t):e.get(t)),we=(t,e,i)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,i)},de=(t,e,i,r)=>(_p(t,e,"write to private field"),r?r.call(t,i):e.set(t,i),i),Re=(t,e,i)=>(_p(t,e,"access private method"),i),al={},UO={get exports(){return al},set exports(t){al=t}},Js=typeof Reflect=="object"?Reflect:null,qg=Js&&typeof Js.apply=="function"?Js.apply:function(t,e,i){return Function.prototype.apply.call(t,e,i)},Dd;Js&&typeof Js.ownKeys=="function"?Dd=Js.ownKeys:Object.getOwnPropertySymbols?Dd=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Dd=function(t){return Object.getOwnPropertyNames(t)};function FO(t){console&&console.warn&&console.warn(t)}var Ny=Number.isNaN||function(t){return t!==t};function pe(){pe.init.call(this)}UO.exports=pe;al.once=HO;pe.EventEmitter=pe;pe.prototype._events=void 0;pe.prototype._eventsCount=0;pe.prototype._maxListeners=void 0;var $g=10;function Ml(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(pe,"defaultMaxListeners",{enumerable:!0,get:function(){return $g},set:function(t){if(typeof t!="number"||t<0||Ny(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");$g=t}});pe.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};pe.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Ny(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function Vy(t){return t._maxListeners===void 0?pe.defaultMaxListeners:t._maxListeners}pe.prototype.getMaxListeners=function(){return Vy(this)};pe.prototype.emit=function(t){for(var e=[],i=1;i<arguments.length;i++)e.push(arguments[i]);var r=t==="error",n=this._events;if(n!==void 0)r=r&&n.error===void 0;else if(!r)return!1;if(r){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var c=n[t];if(c===void 0)return!1;if(typeof c=="function")qg(c,this,e);else for(var d=c.length,l=By(c,d),i=0;i<d;++i)qg(l[i],this,e);return!0};function Ly(t,e,i,r){var n,s,o;if(Ml(i),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,i.listener?i.listener:i),s=t._events),o=s[e]),o===void 0)o=s[e]=i,++t._eventsCount;else if(typeof o=="function"?o=s[e]=r?[i,o]:[o,i]:r?o.unshift(i):o.push(i),n=Vy(t),n>0&&o.length>n&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=o.length,FO(c)}return t}pe.prototype.addListener=function(t,e){return Ly(this,t,e,!1)};pe.prototype.on=pe.prototype.addListener;pe.prototype.prependListener=function(t,e){return Ly(this,t,e,!0)};function BO(){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 xy(t,e,i){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:i},n=BO.bind(r);return n.listener=i,r.wrapFn=n,n}pe.prototype.once=function(t,e){return Ml(e),this.on(t,xy(this,t,e)),this};pe.prototype.prependOnceListener=function(t,e){return Ml(e),this.prependListener(t,xy(this,t,e)),this};pe.prototype.removeListener=function(t,e){var i,r,n,s,o;if(Ml(e),r=this._events,r===void 0)return this;if(i=r[t],i===void 0)return this;if(i===e||i.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete r[t],r.removeListener&&this.emit("removeListener",t,i.listener||e));else if(typeof i!="function"){for(n=-1,s=i.length-1;s>=0;s--)if(i[s]===e||i[s].listener===e){o=i[s].listener,n=s;break}if(n<0)return this;n===0?i.shift():WO(i,n),i.length===1&&(r[t]=i[0]),r.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this};pe.prototype.off=pe.prototype.removeListener;pe.prototype.removeAllListeners=function(t){var e,i,r;if(i=this._events,i===void 0)return this;if(i.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):i[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete i[t]),this;if(arguments.length===0){var n=Object.keys(i),s;for(r=0;r<n.length;++r)s=n[r],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=i[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(r=e.length-1;r>=0;r--)this.removeListener(t,e[r]);return this};function Uy(t,e,i){var r=t._events;if(r===void 0)return[];var n=r[e];return n===void 0?[]:typeof n=="function"?i?[n.listener||n]:[n]:i?jO(n):By(n,n.length)}pe.prototype.listeners=function(t){return Uy(this,t,!0)};pe.prototype.rawListeners=function(t){return Uy(this,t,!1)};pe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Fy.call(t,e)};pe.prototype.listenerCount=Fy;function Fy(t){var e=this._events;if(e!==void 0){var i=e[t];if(typeof i=="function")return 1;if(i!==void 0)return i.length}return 0}pe.prototype.eventNames=function(){return this._eventsCount>0?Dd(this._events):[]};function By(t,e){for(var i=new Array(e),r=0;r<e;++r)i[r]=t[r];return i}function WO(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function jO(t){for(var e=new Array(t.length),i=0;i<e.length;++i)e[i]=t[i].listener||t[i];return e}function HO(t,e){return new Promise(function(i,r){function n(o){t.removeListener(e,s),r(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",n),i([].slice.call(arguments))}Wy(t,e,s,{once:!0}),e!=="error"&&GO(t,n,{once:!0})})}function GO(t,e,i){typeof t.on=="function"&&Wy(t,"error",e,i)}function Wy(t,e,i,r){if(typeof t.on=="function")r.once?t.once(e,i):t.on(e,i);else if(typeof t.addEventListener=="function")t.addEventListener(e,function n(s){r.once&&t.removeEventListener(e,n),i(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}class qO extends y{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 Jg=new qO;class jy{static encode(e){return Jg.toBinary(e)}static decode(e){return Jg.fromBinary(new Uint8Array(e))}}function $O(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var Nr;class JO{constructor(e={}){xO(this,"opts"),we(this,Nr,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},de(this,Nr,0)}wait(){return u(this,null,function*(){de(this,Nr,N(this,Nr)+1);const e=$O(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*tE(2,N(this,Nr))));yield new Promise(i=>{setTimeout(i,e)})})}getAttempts(){return N(this,Nr)}reset(){de(this,Nr,0)}}Nr=new WeakMap;const Er={debug:0,info:1,warn:2,error:3};var bn,wn;class KO{constructor(e){we(this,bn,void 0),we(this,wn,void 0),de(this,bn,console),de(this,wn,e)}debug(...e){Er[N(this,wn)]>Er.debug||N(this,bn).debug("[Sockrates]:",...e)}info(...e){Er[N(this,wn)]>Er.info||N(this,bn).info("[Sockrates]:",...e)}warn(...e){Er[N(this,wn)]>Er.warn||N(this,bn).warn("[Sockrates]:",...e)}error(...e){Er[N(this,wn)]>Er.error||N(this,bn).error("[Sockrates]:",...e)}}bn=new WeakMap,wn=new WeakMap;var Hy=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(Hy||{});const zO="2",YO="3";var Le,Ns,Pe,je,Vr,rt,nr,jr,ki,Vs,Xi,xh,Gy,Ro,Od,Uh,qy,Fh,Kg,ol,Bh,Wh,$y,Ho,Nd,Go,cl,dl,jh,Ks,qo,$o,ll;class QO{constructor(e,i){var r;we(this,xh),we(this,Ro),we(this,Uh),we(this,Fh),we(this,ol),we(this,Wh),we(this,Ho),we(this,Go),we(this,dl),we(this,Ks),we(this,$o),we(this,Le,void 0),we(this,Ns,void 0),we(this,Pe,void 0),we(this,je,void 0),we(this,Vr,void 0),we(this,rt,void 0),we(this,nr,void 0),we(this,jr,void 0),we(this,ki,void 0),we(this,Vs,void 0),we(this,Xi,void 0);var n,s,o,c,d,l,h,m,v;de(this,Ns,e),de(this,Vr,[]),de(this,rt,new al),de(this,nr,!0),de(this,ki,!1),de(this,Pe,i!=null?i:{}),(n=N(this,Pe)).autoReconnect!=null||(n.autoReconnect=!0),(s=N(this,Pe)).retryConnectionInterval!=null||(s.retryConnectionInterval=1e3),(o=N(this,Pe)).pingTimeout!=null||(o.pingTimeout=3e4),(c=N(this,Pe)).connectionTimeout!=null||(c.connectionTimeout=5e3),(d=N(this,Pe)).debug!=null||(d.debug=!0),(l=N(this,Pe)).maxReconnectionAttempts!=null||(l.maxReconnectionAttempts=10),(h=N(this,Pe)).disconnectOnPingTimeout!=null||(h.disconnectOnPingTimeout=!0),(m=N(this,Pe)).queueOnDisconnect!=null||(m.queueOnDisconnect=!1),(v=N(this,Pe)).flushOnReconnect!=null||(v.flushOnReconnect=!1),de(this,jr,{code:void 0,reason:void 0}),de(this,je,(r=N(this,Pe).logger)!=null?r:new KO(N(this,Pe).debug?"debug":"info")),de(this,Xi,new JO)}get readyState(){var e;return(e=N(this,Le))==null?void 0:e.readyState}get url(){return N(this,Ns)}updateURL(e){de(this,Ns,e),Re(this,Wh,$y).call(this)}get config(){return N(this,Pe)}get sendQueue(){return N(this,Vr)}flush(){if(!N(this,Pe).queueOnDisconnect)return!1;const e=[];return N(this,Vr).forEach(i=>{this.send(i.event,i.id,i.payload,i.metadata)||e.push(i)}),de(this,Vr,e),N(this,Vr)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){N(this,je).debug("Websocket was already connecting or connected.");return}if(N(this,nr)!==!1)return new Promise((i,r)=>{Re(this,Ks,qo).call(this),Re(this,$o,ll).call(this);try{de(this,Le,new WebSocket(Re(this,xh,Gy).call(this,N(this,Ns)))),N(this,Le).binaryType="arraybuffer",N(this,je).debug("Connecting");const n=setTimeout(()=>{N(this,je).debug("Connection timeout. Closing socket"),de(this,nr,!0),Re(this,$o,ll).call(this),N(this,Le).close(3001,"Connection Timeout"),N(this,Pe).autoReconnect&&!N(this,ki)&&(N(this,rt).emit("reconnecting"),Re(this,Ho,Nd).call(this)),r(new Error("Connection timed out!"))},N(this,Pe).connectionTimeout);N(this,Le).onopen=()=>{N(this,je).debug(`Ready State: ${Hy[N(this,Le).readyState]}`),n&&clearTimeout(n),Re(this,dl,jh).call(this),de(this,jr,{code:void 0,reason:void 0}),N(this,rt).emit("connected"),N(this,Pe).flushOnReconnect&&this.flush(),i()},N(this,Le).onclose=s=>{try{n&&clearTimeout(n);const{code:o,reason:c}=s;r(c),N(this,je).debug("Socket closed. Close event:",{event:s}),N(this,je).debug(`Connection closed code: ${o}`),N(this,je).debug(`Connection closed reason: ${c}`),N(this,ki)||Re(this,ol,Bh).call(this,o,c)}catch(o){Re(this,Ro,Od).call(this,o)}},N(this,Le).onerror=s=>{Re(this,Ro,Od).call(this,s)},N(this,Le).onmessage=s=>Re(this,Uh,qy).call(this,s)}catch(n){Re(this,Ro,Od).call(this,n,r)}})})}send(e,i,r,n){const s={event:e,id:i,payload:r,metadata:n};if(N(this,Pe).queueOnDisconnect&&(!N(this,Le)||N(this,Le).readyState!==1))return N(this,je).debug("Queuing message since socket is not connected!",s),N(this,Vr).push(s),!1;const o=jy.encode(s);return Re(this,Go,cl).call(this,o)}emit(e,i,r,n){return this.send(e,i,r,n)}sendRaw(e){return Re(this,Go,cl).call(this,e)}receive(e,i){return N(this,rt).on(e.toString(),i)}on(e,i){if(typeof e=="string"&&(e==="connected"||e==="disconnected"||e==="errored"||e==="reconnected"||e==="reconnecting"||e==="reconnectAttempt"||e==="reconnectFailure"||e==="failed")){N(this,rt).on(e,i);return}this.receive(e,i)}removeAllListeners(){N(this,rt).removeAllListeners()}removeReceiver(e,i){this.removeListener(e,i)}removeListener(e,i){N(this,rt).removeListener(e.toString(),i)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){N(this,rt).listeners(e.toString()).map(i=>this.removeListener(e,i))}disconnect(){de(this,nr,!1),Re(this,Ks,qo).call(this),this.removeAllListeners(),de(this,jr,{code:1e3,reason:"Sockrates disconnect method called"}),N(this,Le).close(1e3,"Sockrates disconnect method called.")}}Le=new WeakMap,Ns=new WeakMap,Pe=new WeakMap,je=new WeakMap,Vr=new WeakMap,rt=new WeakMap,nr=new WeakMap,jr=new WeakMap,ki=new WeakMap,Vs=new WeakMap,Xi=new WeakMap,xh=new WeakSet,Gy=function(t){if(t.startsWith("ws://")||t.startsWith("wss://"))return t;if(t.startsWith("https://"))return`wss://${t.substring(8)}`;if(t.startsWith("http://"))return`ws://${t.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},Ro=new WeakSet,Od=function(t,e){N(this,je).error("Error:",{error:t}),N(this,rt).emit("errored",{error:t}),e==null||e(t)},Uh=new WeakSet,qy=function(t){if(Re(this,dl,jh).call(this),t.data===zO){N(this,je).debug("Received ping from server"),Re(this,Go,cl).call(this,YO);return}const e=jy.decode(t.data),{id:i,payload:r}=e;N(this,je).debug("Received message",{event:e.event,messageID:i}),N(this,rt).emit(e.event.toString(),{id:i,payload:r})},Fh=new WeakSet,Kg=function(){return N(this,Le).readyState===1},ol=new WeakSet,Bh=function(t,e){de(this,jr,{reason:e,code:t}),N(this,rt).emit("disconnected",{code:t,reason:e})},Wh=new WeakSet,$y=function(){const{reason:t,code:e}=N(this,jr);e&&e!==1e3&&N(this,nr)&&N(this,Pe).autoReconnect&&!N(this,ki)&&(N(this,je).debug(`Triggering reconnection due to ${t}.`),N(this,rt).emit("reconnecting"),Re(this,Ho,Nd).call(this))},Ho=new WeakSet,Nd=function(t=!0){return u(this,null,function*(){if(t&&N(this,ki)){N(this,je).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(N(this,ki)||N(this,Xi).reset(),N(this,Pe).maxReconnectionAttempts!==null&&N(this,Xi).getAttempts()>=N(this,Pe).maxReconnectionAttempts){N(this,rt).emit("failed"),de(this,ki,!1);return}de(this,ki,!0),Re(this,$o,ll).call(this),Re(this,Ks,qo).call(this);try{if(yield N(this,Xi).wait(),N(this,nr)===!1)return;if(N(this,je).debug(`Reconnection attempt ${N(this,Xi).getAttempts()}`),N(this,rt).emit("reconnectAttempt",{attempt:N(this,Xi).getAttempts()}),yield this.connect(),!Re(this,Fh,Kg).call(this))throw Error("Reconnect Failed");de(this,ki,!1),de(this,jr,{code:void 0,reason:void 0}),N(this,rt).emit("reconnected")}catch(e){N(this,je).debug("Failed to reconnect."),N(this,rt).emit("reconnectFailure",{attempt:N(this,Xi).getAttempts()}),Re(this,Ho,Nd).call(this,!1)}})},Go=new WeakSet,cl=function(t){try{return N(this,Le).send(t),!0}catch(e){return N(this,je).error(e.message),!1}},dl=new WeakSet,jh=function(){this.config.disconnectOnPingTimeout&&(N(this,je).debug("Resetting ping timeout"),Re(this,Ks,qo).call(this),de(this,Vs,setTimeout(()=>{var t;N(this,je).debug("Disconnecting the socket due to ping timeout"),de(this,nr,!0);const e=3002,i="Ping timeout";(t=N(this,Le))==null||t.close(e,i),Re(this,ol,Bh).call(this,e,i)},N(this,Pe).pingTimeout)))},Ks=new WeakSet,qo=function(){N(this,Vs)&&(clearTimeout(N(this,Vs)),de(this,Vs,void 0))},$o=new WeakSet,ll=function(){N(this,Le)&&(N(this,Le).onopen=void 0,N(this,Le).onerror=void 0,N(this,Le).onmessage=void 0,N(this,Le).onclose=void 0)};var XO=Object.defineProperty,ZO=Object.getOwnPropertyDescriptor,Al=(t,e,i,r)=>{for(var n=r>1?void 0:r?ZO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&XO(e,i,n),n};const zg=65535,eN=3e3;var dn,Oe,Ne,xe,pi,ut,xc,Cu,Uc,Pu,Yg;const Jy=(Yg=class{constructor(t,{peerId:e,meetingId:i,authToken:r,capabilities:n}){g(this,Ne),g(this,xc),g(this,Uc),g(this,dn,void 0),g(this,Oe,void 0),p(this,"roomName"),p(this,"authToken"),p(this,"capabilities"),g(this,pi,void 0),g(this,ut,void 0);var s;if(!e||!i||!r)throw new _("peerId, meetingId, or authToken can not be empty","0404");f(this,pi,void 0),f(this,ut,t),this.capabilities=n,this.roomName=i,this.authToken=r,f(this,dn,U(this,xc,Cu).call(this,e)),f(this,Oe,new QO(a(this,dn),{autoReconnect:!0,disconnectOnPingTimeout:(s=n.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Ne,xe).socketJoinAttempted}set joinAttempted(t){a(this,Ne,xe).socketJoinAttempted=t}get telemetry(){return a(this,ut).getValue("telemetry")}get logger(){return a(this,ut).getValue("logger")}get peerId(){return a(this,ut).getValue("peerId")}updateURL(t){t!==this.peerId&&(f(this,dn,U(this,xc,Cu).call(this,t)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Oe).updateURL(a(this,dn))}static getSocketEdgeDomain(t){return On({servicePrefix:"socket-edge",baseURI:t})}get url(){return a(this,dn)}connect(){return u(this,null,function*(){a(this,Ne,xe).socketJoinAttempted=!0,yield a(this,Oe).connect(),a(this,Ne,xe).socketJoinAttempted=!0,a(this,Ne,xe).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return u(this,null,function*(){a(this,Ne,xe).socketJoinAttempted=!1,a(this,Oe).disconnect(),a(this,Ne,xe).socketJoinAttempted=!0,a(this,Ne,xe).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return a(this,Oe).readyState===1}catch(t){return!1}}sendMessage(t,e,i){const r={};return a(this,ut).getValue("telemetry").injectContext(r),a(this,Oe).send(t,i!=null?i:U(this,Uc,Pu).call(this),e,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(t,e,i,r){const n=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:n,protobuf:e,messageId:i,resp:r})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:i,messageId:r,resp:n}){const s=n!=null?n:t;return new Promise((o,c)=>{const d=(S,T)=>{a(this,Oe).removeListener(s,S),a(this,Oe).removeListener(zg,T),a(this,Oe).removeListener(oi.errorResponse,T),a(this,Oe).removeListener(Ti.errorResponse,T)},l=r!=null?r:U(this,Uc,Pu).call(this),h={};a(this,ut).getValue("telemetry").injectContext(h);const m=({id:S,payload:T})=>{if(l===S){let M;try{const I=XI.fromBinary(T);M=new Error(I.errorMessage)}catch(I){M=new Error("failed to parse error message",{cause:I});try{const R=ZC.fromBinary(T);M=new Error(R.message)}catch(R){M=new Error("failed to parse error message",{cause:R})}}c(M),d(v,m)}},v=({id:S,payload:T})=>{l===S&&(o({id:S,payload:T}),d(v,m))};a(this,Oe).on(s,v),a(this,Oe).on(zg,m),a(this,Oe).on(oi.errorResponse,m),a(this,Oe).on(Ti.errorResponse,m),setTimeout(()=>{d(v,m),c(new Error(`request timeout for callback eventId:${t}`))},e),a(this,Oe).send(t,l,i,new TextEncoder().encode(JSON.stringify(h)))})}on(t,e){a(this,Oe).on(t,e)}onStateEvent(t,e){a(this,Oe).on(t,e)}removeListener(t,e){a(this,Oe).removeListener(t,e)}removeListeners(t){a(this,Oe).removeListeners(t)}flush(){return a(this,Oe).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){this.logger.info("SocketService::Connected to socket-edge"),a(this,pi)&&(clearTimeout(a(this,pi)),f(this,pi,void 0)),a(this,Ne,xe).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:k.location.country});const{recv:r,send:n}=(i=a(this,Ne,xe).mediaState)!=null?i:{};r!=null&&r.state&&(r==null?void 0:r.state)!==ea.CONNECTED||n!=null&&n.state&&(n==null?void 0:n.state)!==ea.CONNECTED?a(this,ut).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ne,xe).joinAttempted}):f(this,pi,setTimeout(()=>{a(this,ut).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ne,xe).joinAttempted}),f(this,pi,void 0)},eN)),a(this,Ne,xe).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnecting to socket-edge",{country:k.location.country}),a(this,Ne,xe).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),a(this,Ne,xe).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),a(this,Ne,xe).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Ne,xe).mediaJoinAttempted}}),a(this,pi)&&(clearTimeout(a(this,pi)),f(this,pi,void 0)),a(this,ut).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Ne,xe).mediaJoinAttempted}),a(this,Ne,xe).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){this.logger.info("SocketService::Failed to connect to socket-edge",{country:k.location.country}),a(this,ut).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_FAILED),a(this,Ne,xe).updateSocketConnectionState("failed")}))}},dn=new WeakMap,Oe=new WeakMap,Ne=new WeakSet,xe=function(){return a(this,ut).getValue("connectionHandler")},pi=new WeakMap,ut=new WeakMap,xc=new WeakSet,Cu=function(t){let e=Jy.getSocketEdgeDomain(a(this,ut).getValue("baseURI"));typeof Xs(a(this,ut),"socket_server_base")=="string"&&(e=Xs(a(this,ut),"socket_server_base"));const i=`wss://${e}`,r=new URL(`${i}/ws`),n=this.peerId,s=q(V({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},n!==t&&{oldPeerID:n}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>Kd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0});return Object.entries(s).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},Uc=new WeakSet,Pu=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Yg);let ac=Jy;Al([k.trace("SocketService.connect")],ac.prototype,"connect",1);Al([k.trace("SocketService.disconnect")],ac.prototype,"disconnect",1);Al([k.trace("SocketService.sendMessagePromise")],ac.prototype,"sendMessagePromise",1);Al([k.trace("SocketService.sendMessagePromiseWithTimeout")],ac.prototype,"sendMessagePromiseWithTimeout",1);class tN{constructor(e){p(this,"socketService"),this.socketService=e}handleConnectedRoomsDumpRaw({payload:e}){var i;const r=IP.fromBinary(e),n=r.meetings.map(s=>{var o;return{id:s.id,title:s.title,participants:(o=s.participants)!=null?o:[]}});return{parentMeeting:{id:r.parentMeeting.id,title:r.parentMeeting.title,participants:(i=r.parentMeeting.participants)!=null?i:[]},meetings:n}}handleTransferPeerRaw({payload:e}){const i=XP.fromBinary(e);return{authToken:i.authToken,meetingId:i.meetingId}}handleMovedPeerRaw({payload:e}){const i=jv.fromBinary(e);return{meetingId:i.meetingId,customParticipantId:i.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:e}){return Lm.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}handleConnectedRoomsDeletedRaw({payload:e}){return jP.fromBinary(e).payloads}getConnectedRoomsDump(){return u(this,null,function*(){const e=yield this.socketService.sendMessagePromise(F.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(e)})}createConnectedRooms(e){return u(this,null,function*(){const{payload:i}=yield this.socketService.sendMessagePromise(F.createConnectedRooms,MP.toBinary({payloads:e}));return Lm.fromBinary(i).payloads.map(r=>({id:r.id,title:r.title}))})}updateConnectedRooms(e){return u(this,null,function*(){})}disableConnectedRooms(e){return u(this,null,function*(){const i=e.map(n=>({id:n})),r=yield this.socketService.sendMessagePromise(F.deleteConnectedRooms,BP.toBinary({payloads:i}));return this.handleConnectedRoomsDeletedRaw(r)})}movePeersBetweenRooms(e){return u(this,null,function*(){try{const i=yield this.socketService.sendMessagePromise(F.movePeers,KP.toBinary({sourceMeetingId:e.sourceMeetingId,destinationMeetingId:e.destinationMeetingId,participants:e.participants}));return new TextDecoder().decode(i.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(i){return{success:!1,error:i}}})}}var iN=Object.defineProperty,rN=Object.getOwnPropertyDescriptor,nN=(t,e,i,r)=>{for(var n=r>1?void 0:r?rN(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&iN(e,i,n),n},Vi;class Ky extends Qt{constructor(e){const i=e.getValue("logger");super(i),p(this,"meetings",[]),p(this,"parentMeeting",null),g(this,Vi,void 0),f(this,Vi,e)}get supportsConnectedMeetings(){return a(this,Vi).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.
20
20
  Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`)}getConnectedMeetings(){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),yield a(this,Vi).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield a(this,Vi).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e)).map(i=>({id:i.id,title:i.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield a(this,Vi).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(i=>({meetingId:i.id,title:i.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=this.meetings.map(r=>e.includes(r.id)&&r.participants.length!==0?this.moveParticipants(r.id,this.parentMeeting.id,r.participants.map(n=>n.id)):Promise.resolve());return yield Promise.all(i),yield a(this,Vi).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e)})}moveParticipants(e,i,r){return u(this,null,function*(){this.validateConnectedMeetingsAction();const n=yield a(this,Vi).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:r.map(s=>({id:s}))});return n.success&&this.moveSuccessHandler(e,i,r),n})}moveParticipantsWithCustomPreset(e,i,r){return u(this,null,function*(){this.validateConnectedMeetingsAction();const n=yield a(this,Vi).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:r});return n.success&&this.moveSuccessHandler(e,i,r.map(s=>s.id)),n})}moveSuccessHandler(e,i,r){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(s=>s.participants)].forEach(s=>n.set(s.id,s)),i===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(r.map(s=>n.get(s)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(s=>!r.includes(s.id))),this.meetings=this.meetings.map(s=>{if(i===s.id){const o=s.participants.concat(r.map(c=>n.get(c)));return q(V({},s),{participants:o})}if(e===s.id){const o=s.participants.filter(c=>!r.includes(c.id));return q(V({},s),{participants:o})}return s})}}Vi=new WeakMap;nN([Ft({maxInvocations:60,period:60})],Ky.prototype,"getConnectedMeetings",1);var sN=Object.defineProperty,aN=Object.getOwnPropertyDescriptor,Ip=(t,e,i,r)=>{for(var n=r>1?void 0:r?aN(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&sN(e,i,n),n},Te,Qg;const zy=(Qg=class{constructor(t){p(this,"connectedMeetings"),g(this,Te,void 0),f(this,Te,t),this.connectedMeetings=new Ky(t)}get telemetry(){return a(this,Te).getValue("telemetry")}get logger(){return a(this,Te).getValue("logger")}static init(t){const e=new zy(t);return e.connectedMeetings.supportsConnectedMeetings&&(e.setupEvents(),t.getValue("self").once("roomJoined",()=>e.getConnectedMeetings())),e}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,Te).getValue("connectedMeetingsSocketHandler").socketService.on(F.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,Te).getValue("connectedMeetingsSocketHandler").socketService.on(F.transferPeer,this.handleTransferPeer.bind(this)),a(this,Te).getValue("connectedMeetingsSocketHandler").socketService.on(F.movedPeer,this.handleMovedPeer.bind(this)),a(this,Te).getValue("connectedMeetingsSocketHandler").socketService.on(F.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,Te).getValue("connectedMeetingsSocketHandler").socketService.on(F.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(t){const e=a(this,Te).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:i}){var r,n,s,o;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
21
21
  Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",i);const c={video:a(this,Te).getValue("self").videoEnabled,audio:a(this,Te).getValue("self").audioEnabled};try{a(this,Te).getValue("self").cleanupEvents(),yield a(this,Te).getValue("meeting").leave("connected-meeting")}catch(l){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(r=a(this,Te).getValue("meeting"))==null?void 0:r.meta)==null?void 0:n.meetingId}`,{error:l})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${i}`);const d=yield Qy.init(q(V({},a(this,Te).getValue("options")),{cachedUserDetails:null,defaults:q(V(V({},a(this,Te).getValue("options").defaults),c),{mediaHandler:a(this,Te).getValue("self")}),authToken:e}));this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(s=d==null?void 0:d.meta)==null?void 0:s.meetingId}`);try{const{hidden:l}=a(this,Te).getValue("self");d.self.setName(a(this,Te).getValue("self").name),yield d.join(),l&&d.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: ${(o=d==null?void 0:d.meta)==null?void 0:o.meetingId}`),this.connectedMeetings.emit("meetingChanged",d),d})}handleConnectedRoomsDump(t){const e=a(this,Te).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(t);this.connectedMeetings.meetings=e.meetings.map(i=>({id:i.id,title:i.title,participants:i.participants||[]})),this.connectedMeetings.parentMeeting={id:e.parentMeeting.id,title:e.parentMeeting.title,participants:e.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(t){return a(this,Te).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=a(this,Te).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(t),i=new Map;this.connectedMeetings.meetings.forEach(r=>{i.set(r.id,r)}),e.forEach(r=>{i.has(r.id)?i.get(r.id).title=r.title:i.set(r.id,q(V({},r),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(i.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=a(this,Te).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(t).map(i=>i.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(i=>!e.includes(i.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Te=new WeakMap,Qg);let Dl=zy;Ip([k.trace("ConnectedMeetingsController.getConnectedMeetings")],Dl.prototype,"getConnectedMeetings",1);Ip([k.trace("ConnectedMeetingsController.setupEvents")],Dl.prototype,"setupEvents",1);Ip([k.trace("ConnectedMeetingsController.switchMeeting")],Dl.prototype,"switchMeeting",1);var oN=Object.defineProperty,cN=Object.getOwnPropertyDescriptor,Ol=(t,e,i,r)=>{for(var n=r>1?void 0:r?cN(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&oN(e,i,n),n};const Ls=class{constructor(t,e,i){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=t,this.storesManager=e.storesManager,this.metaController=e.metaController,this.selfController=e.selfController,this.chatController=e.chatController,this.pollController=e.pollController,this.stageController=e.stageController,this.pluginController=e.pluginController,this.recordingController=e.recordingController,this.internalsController=e.internalsController,this.participantController=e.participantController,this.livestreamController=e.livestreamController,this.connectedMeetingsController=e.connectedMeetingsController,this.telemetry=i.getValue("telemetry"),this.logger=i.getValue("logger")}static init(t){return u(this,null,function*(){var e,i;const{peerId:r,apiBase:n,authToken:s,meetingId:o,organizationId:c,cachedUserDetails:d,logger:l}=t.getAllValues();if(Ay(t),Ie.isSupported()===!1)throw new _("Browser not supported","0010",l,!0);const h=l1(t,{authToken:s,baseURL:n,cachedUserDetails:d});h.setRoomName(o),h.setRoomUUID(o),h.setOrganizationId(c),h.setHeader("dyte-tracing-id",r),t.setValue("apiClient",h);const m=new $1(t);t.setValue("connectionHandler",m);const v=Ls.createSocketService(t),S=v.connect(),T=h.getUserDetails(),M=h.getPlugins();let I=De.HIVE,R,j="";try{yield Ls.setupFlagsmith(t)}catch(ae){l.error("Failed to setup flagsmith",{error:ae})}try{yield S}catch(ae){l.error("[Controller]: Failed to connect to socket server:",{error:ae})}try{({sfu:I,meetingTitle:j}=yield h.getRoomNodeData()),R=yield T,l.info(`SFU ${I} is being used.`),t.setValue("presetName",R.preset.name),t.setValue("roomNodeOptions",{sfu:I})}catch(ae){l.error("Failed to get room metadata",{error:ae})}const W=MD.init(R.preset,!t.getValue("modules").theme),b=QD.init(t,W.viewType,R.preset.permissions),te=Ls.setupControllers(v,t,R,M,j,W,b);V1(W)&&((e=Ls.createRoomNodeClient(t,v).initializeConnection(R.participant.name,o,!1,b))==null||e.catch(ae=>{l.error("[Controller]: Failed to queue partial media room promise:",{error:ae})})),k.location.country=(i=h.ipInfo)==null?void 0:i.country;const{controllers:ie}=yield te;return D_(),new Ls(n,ie,t)})}static setupFlagsmith(t){return u(this,null,function*(){var e;const{peerId:i,baseURI:r,overrides:n,meetingId:s,organizationId:o,logger:c}=t.getAllValues(),d=A_(s),l=q(V({entity:Fu.PEER,clientId:o,isAnonUser:!o,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:d,roomName:s},Ie.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const h=(e=n==null?void 0:n.whitelabelled_flags_endpoint)==null||e?On({servicePrefix:"flags",baseURI:r}):"edge.api.flagsmith.com";yield t.getValue("flagsmith").identify(`${Fu.PEER}_${i}`,JSON.parse(JSON.stringify(l)),!1,5e3,h,c),c.info("flagsmith::allFlags",{flags:JSON.stringify(t.getValue("flagsmith").getAllFlags())},!0)}catch(h){c.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,i,r,n,s,o){return u(this,null,function*(){var c,d,l;const h=e.getValue("modules"),{participant:m}=i,v=e.getValue("defaults"),S=e.getValue("logger"),{sfu:T}=e.getValue("roomNodeOptions"),{viewType:M,mediaConstraints:{audio:I}}=s;e.setValue("viewType",M),e.setValue("defaults",V({mediaConfiguration:{audio:{enableHighBitrate:(c=I.enableHighBitrate)!=null?c:!1,enableStereo:(d=I.enableStereo)!=null?d:!1}}},v)),e.setValue("maxPreferredStreams",Ie.isMobile()?s.maxVideoStreams.mobile:s.maxVideoStreams.desktop);let R,j,W,b,te,ie,ae,Me,Xe;const Wt=new CO(e,t),A=new tN(t);e.setValue("connectedMeetingsSocketHandler",A);const E=new Rl(e,t),w=new ci(e,t),B=new OO(t),oe=new Oy(e,t),He=new NO(e,t),x=new IO(t),C=new xn(e,t),ce=yield zr.init(e,oe,m,o,s);e.setValue("selfController",ce);const Yr=yield ey.init(e,ce.self,oe,Wt,n);if(h.participant&&(Me=new pr(e,ce.self,oe,T)),(l=h.e2ee)!=null&&l.enabled&&h.e2ee.manager.init(S,e.getValue("peerSessionStore")),h.chat&&(j=yield ar.init(e,w,C,ce.self,Me.participants)),h.internals&&(te=yield mp.init(e)),h.livestream&&s.viewType===Ut.Livestream&&e.getValue("flagsmith").hasFeature(Z.LIVESTREAM)&&(ae=new dy(e,ce.self,x)),s.viewType!==Ut.Chat){if(h.poll&&(R=yield Yv.init(e,ce.self,E)),h.recording&&(ie=new ny(e,ce.self,oe)),h.stage&&(W=new ty(e,B,oe,ce.self,Me.participants)),h.plugin){if(!Me)throw new _("The plugin module cannot be initialized without the `participant` module","0102");const Gi=yield r;b=yield ic.init(e,Gi,He,w,j==null?void 0:j.chat,ce.self,Me.participants,n)}if(h.connectedMeetings&&(Xe=yield Dl.init(e)),h.pip){const Gi=yield V_._init(e,ce.self);e.setValue("pip",Gi)}}const Qr={storesManager:new UD(e,He),pollController:R,selfController:ce,metaController:Yr,chatController:j,stageController:W,pluginController:b,recordingController:ie,internalsController:te,livestreamController:ae,participantController:Me,connectedMeetingsController:Xe};return{theme:s,permissions:o,controllers:Qr}})}static createRoomNodeClient(t,e){const{peerId:i,roomNodeOptions:r}=t.getAllValues(),{sfu:n}=r;return My(t,n,{socket:e,peerId:i})}static createSocketService(t){const{peerId:e,meetingId:i,authToken:r}=t.getAllValues(),n=["PING"];return new ac(t,{peerId:e,meetingId:i,authToken:r,capabilities:n})}};let oc=Ls;Ol([k.trace("Controller.init")],oc,"init",1);Ol([k.trace("setupFlagsmith")],oc,"setupFlagsmith",1);Ol([k.trace("Controller.createRoomNodeClient")],oc,"createRoomNodeClient",1);Ol([k.trace("Controller.createSocketService")],oc,"createSocketService",1);class dN{constructor(){p(this,"battery"),p(this,"logger"),p(this,"init",e=>u(this,null,function*(){this.logger=e;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(i){e.error("Error getting battery",i)}})),p(this,"updateChargeInfo",()=>{var e;this.logger.log(`Battery charging? ${(e=this.battery)!=null&&e.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 e,i;"getBattery"in navigator&&((e=this.battery)==null||e.removeEventListener("chargingchange",this.updateChargeInfo),(i=this.battery)==null||i.removeEventListener("levelchange",this.updateLevelInfo))})}}const Xg=new dN;function lN(t,e){t.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c \u2014 not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.dyte.io/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:i,orgId:r,participantId:n}=JSON.parse(atob(t.split(".")[1]));if(!i)throw Error(`Received V1 auth token ${t}`);let s="dyte.io";e&&(s=e);const o=`https://${On({servicePrefix:"api",baseURI:s})}`;return{meetingId:i,orgId:r,participantId:n,baseURI:s,apiBase:o}}catch(i){throw new _("Invalid auth token","0004")}}var _n,xs,Us,ul,Hh,Yy;class uN{constructor(){g(this,Hh),g(this,_n,new Audio),g(this,xs,new MediaStream),g(this,Us,new Map),g(this,ul,void 0),a(this,_n).srcObject=a(this,xs),a(this,_n).autoplay=!0}playTracks(e){return u(this,null,function*(){return e.forEach(i=>{a(this,Us).has(i.id)||(a(this,xs).addTrack(i),a(this,Us).set(i.id,i))}),this.play()})}setSpeakerDevice(e){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,_n).setSinkId(e)}removeTrack(e){const i=a(this,Us).get(e);i&&(a(this,xs).removeTrack(i),a(this,Us).delete(e))}play(){return u(this,null,function*(){return a(this,_n).srcObject=a(this,xs),a(this,_n).play().catch(e=>{U(this,Hh,Yy).call(this,e)})})}onError(e){f(this,ul,e)}}_n=new WeakMap,xs=new WeakMap,Us=new WeakMap,ul=new WeakMap,Hh=new WeakSet,Yy=function(t){var e;(e=a(this,ul))==null||e.call(this,t)};var Fs;class hN extends uN{constructor(){super(),g(this,Fs,void 0),f(this,Fs,new Map)}addParticipantTrack(e,i){a(this,Fs).set(e,i.id),this.playTracks([i])}removeParticipantTrack(e){const i=a(this,Fs).get(e);i&&this.removeTrack(i),a(this,Fs).delete(e)}}Fs=new WeakMap;var pN=Object.defineProperty,mN=Object.getOwnPropertyDescriptor,Nl=(t,e,i,r)=>{for(var n=r>1?void 0:r?mN(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&pN(e,i,n),n},et,ln,Zg;let Jr=(Zg=class{constructor(t,e){g(this,et,void 0),g(this,ln,void 0),f(this,ln,t),f(this,et,e)}get peerId(){return a(this,ln).getValue("peerId")}static initMedia(t={},e=!1,i=void 0){var r;const n=(r=i==null?void 0:i.peerId)!=null?r:Vn(),s=sr.createContext(n,{peerId:n}),o=s.getValue("logger");o.init(s);const c=new py(o);return c.init(t,e,s),s.setValue("defaults",{mediaHandler:c}),c}static init(t){return u(this,null,function*(){var e,i,r,n,s,o,c;Ie.init();const{mediaHandler:d}=(e=t.defaults)!=null?e:{},l=(d==null?void 0:d.peerId)||((r=(i=t==null?void 0:t.cachedUserDetails)==null?void 0:i.peerId)!=null?r:Vn()),{authToken:h,baseURI:m}=t,v=lN(h,m),{meetingId:S}=v,T=ml(v,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const M=Jr.setupContext(l,t,S,T),I=M.getValue("telemetry"),R=M.getValue("logger");sE(R),Xg.init(R),I.init(M,{roomName:S,userId:T.participantId,organizationId:T.orgId,peerId:l},(s=(n=t.modules)==null?void 0:n.tracing)!=null?s:!0),R.init(M),R.info("DyteClient::init::options",{dyteClientInitOptions:q(V({},t),{authToken:`${(o=t.authToken)==null?void 0:o.slice(0,10)}...
22
- ${(c=t.authToken)==null?void 0:c.slice(-10)}`})});const j=yield oc.init(M),W=new Jr(M,j);return M.setValue("meeting",W),W})}static setupContext(t,e,i,r){var n,s;const o=sr.createContext(t,e),c=V(V({},b_),e==null?void 0:e.modules),d=e.defaults||{audio:!0,video:!0};return o.setValue("options",e),o.setValue("peerId",t),o.setValue("modules",c),o.setValue("sdkName","web-core"),o.setValue("meetingId",i),o.setValue("apiBase",r.apiBase),o.setValue("baseURI",r.baseURI),o.setValue("userId",r.participantId),o.setValue("organizationId",r.orgId),o.setValue("authToken",e.authToken),o.setValue("overrides",(n=e.overrides)!=null?n:{}),o.setValue("env",w_({baseURI:r.baseURI})),o.setValue("defaults",d),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",wi(e.cachedUserDetails)),o.setValue("sdkVersion","3.1.5-staging.3"),(s=e.modules)!=null&&s.experimentalAudioPlayback&&o.setValue("audioPlayback",new hN),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,et);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){var e;Xg.cleanup(),a(this,ln).getValue("peerSessionStore").reset(),(e=a(this,ln).getValue("roomSocketHandler"))==null||e.cleanup();const{selfController:i}=a(this,et);return i.leaveRoom(t)})}get participants(){var t;return(t=a(this,et).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,et).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,et).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,et).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,et).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,et).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,et).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,et).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,et).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,et).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,et).stageController)==null?void 0:t.stage}get stores(){return a(this,et).storesManager}get audio(){return a(this,ln).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,et).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)})}},et=new WeakMap,ln=new WeakMap,Zg);Nl([ft("0002"),hr.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Jr.prototype,"join",1);Nl([ft("0003")],Jr.prototype,"leave",1);Nl([ft("0001"),hr.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Jr,"init",1);Jr=Nl([ft("0000")],Jr);const Qy=Jr;module.exports=Qy;
22
+ ${(c=t.authToken)==null?void 0:c.slice(-10)}`})});const j=yield oc.init(M),W=new Jr(M,j);return M.setValue("meeting",W),W})}static setupContext(t,e,i,r){var n,s;const o=sr.createContext(t,e),c=V(V({},b_),e==null?void 0:e.modules),d=e.defaults||{audio:!0,video:!0};return o.setValue("options",e),o.setValue("peerId",t),o.setValue("modules",c),o.setValue("sdkName","web-core"),o.setValue("meetingId",i),o.setValue("apiBase",r.apiBase),o.setValue("baseURI",r.baseURI),o.setValue("userId",r.participantId),o.setValue("organizationId",r.orgId),o.setValue("authToken",e.authToken),o.setValue("overrides",(n=e.overrides)!=null?n:{}),o.setValue("env",w_({baseURI:r.baseURI})),o.setValue("defaults",d),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",wi(e.cachedUserDetails)),o.setValue("sdkVersion","3.1.5"),(s=e.modules)!=null&&s.experimentalAudioPlayback&&o.setValue("audioPlayback",new hN),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,et);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){var e;Xg.cleanup(),a(this,ln).getValue("peerSessionStore").reset(),(e=a(this,ln).getValue("roomSocketHandler"))==null||e.cleanup();const{selfController:i}=a(this,et);return i.leaveRoom(t)})}get participants(){var t;return(t=a(this,et).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,et).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,et).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,et).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,et).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,et).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,et).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,et).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,et).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,et).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,et).stageController)==null?void 0:t.stage}get stores(){return a(this,et).storesManager}get audio(){return a(this,ln).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,et).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)})}},et=new WeakMap,ln=new WeakMap,Zg);Nl([ft("0002"),hr.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Jr.prototype,"join",1);Nl([ft("0003")],Jr.prototype,"leave",1);Nl([ft("0001"),hr.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Jr,"init",1);Jr=Nl([ft("0000")],Jr);const Qy=Jr;module.exports=Qy;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/realtimekit",
3
- "version": "1.1.5-staging.3",
3
+ "version": "1.1.5",
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",
@@ -63,7 +63,8 @@
63
63
  "worker-timers": "7.0.60"
64
64
  },
65
65
  "publishConfig": {
66
- "tag": "staging"
66
+ "access": "public",
67
+ "tag": "latest"
67
68
  },
68
69
  "devDependencies": {},
69
70
  "scripts": {