@cloudflare/realtimekit 1.1.0-staging.4 → 1.1.0-staging.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,Vr)},
19
19
  maxEnergy: ${a(this,Dn)}`),n===-1/0||i<1e-6?{energy:0,isVoice:!1}:((!a(this,Vr)||n<a(this,Vr))&&v(this,Vr,n),(!a(this,Dn)||n>a(this,Dn))&&v(this,Dn,n),{energy:(n-a(this,Vr))/(a(this,Dn)-a(this,Vr))*10||0,isVoice:r})},el=new WeakSet,Wh=function(t){return t<5},jh=new WeakSet,Hv=function(t=a(this,Ns)){var e;if(!a(this,ji)||!t){z.hasFeature(ie.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&l.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,ji)}`);return}const i={producerId:a(this,ji),energy:Math.round(t),silent:F(e=tl,el,Wh).call(e,t)};v(this,Ro,i.silent),this.reportRequest(i)},Hh=new WeakSet,qv=function(t){const e=Math.log10(t);return Math.round(e)},f(qh,el),f(qh,Hh);const YD=(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 h=()=>u(void 0,null,function*(){try{const g=new Float32Array(s*o),y=new window.AudioData({format:"f32",sampleRate:n,numberOfFrames:s,numberOfChannels:o,timestamp:c,data:g});c+=s/n*1e6,yield r.ready,yield r.write(y)}catch(g){d&&clearInterval(d),r.releaseLock(),i.writable.abort()}});d=window.setInterval(h,100);const p=new MediaStream([i]).getAudioTracks()[0];return p.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),i.writable.abort()}),Object.assign(p,{fakeTracks:"fakeTracks:fakeAudioTrack"}),p.enabled=t,p}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}},QD=(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 XD=Object.defineProperty,ZD=Object.getOwnPropertyDescriptor,me=(t,e,i,r)=>{for(var n=r>1?void 0:r?ZD(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&&XD(e,i,n),n};const Qt=["video/VP9","video/VP8"];var il,rl,Ct,Y,Mo,ar,xt,Ls,Vs,xs,nl,Ci,xr,Ao,Us,Fs,Ut,Xt,On,Bs,Gh,Gv,$h,$v,Jh,Jv,sl,Kh,zh,Yh,Kv,Qh,zv,Xh,Yv,Zh,Qv,gt,Pt,Ws,Do,ep,Xv,tp,Zv,ip,ey;const ty=(Yh=class{constructor(t,e,i){f(this,On),f(this,Gh),f(this,$h),f(this,Jh),f(this,sl),f(this,Qh),f(this,Xh),f(this,Zh),f(this,gt),f(this,Ws),f(this,ep),f(this,tp),f(this,ip),m(this,"context"),m(this,"authToken"),m(this,"e2ee"),f(this,il,void 0),f(this,rl,void 0),f(this,Ct,void 0),f(this,Y,void 0),f(this,Mo,void 0),f(this,ar,void 0),f(this,xt,void 0),f(this,Ls,void 0),f(this,Vs,void 0),f(this,xs,void 0),f(this,nl,void 0),f(this,Ci,null),f(this,xr,void 0),f(this,Ao,void 0),f(this,Us,void 0),f(this,Fs,void 0),f(this,Ut,void 0),f(this,Xt,void 0);var r,n;this.context=t;const{socket:s}=i;this.mediaJoined=!1,v(this,Us,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,Fs,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,ar,e),v(this,Ct,s),v(this,Ls,!1),v(this,Y,new JD(t,s,e)),v(this,xt,a(this,Y).events),v(this,xr,new Set),v(this,Ut,new Map),v(this,Vs,!1),v(this,xs,new ch),e===Ne.CF&&!navigator.isReactNative&&v(this,Xt,new qh(a(this,Y).socketHandler.audioActivity.bind(a(this,Y).socketHandler))),this.e2ee=(n=(r=t.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),v(this,nl,su(()=>u(this,null,function*(){if(!a(this,On,Bs).mediaJoinAttempted)return;const{roomJoined:o}=yield this.joinRoom(a(this,rl),a(this,il),!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 mediaJoined(){return a(this,On,Bs).mediaJoined}set mediaJoined(t){a(this,On,Bs).mediaJoined=t}reset(){a(this,Y).closeAllProducers(),a(this,Y).closeAllConsumers(),a(this,Ut).clear(),a(this,xr).clear(),v(this,Ci,null),a(this,xs).stop(),a(this,Y).stopAllTransports(),a(this,Y).reset(),v(this,xs,new ch)}joinRoom(t,e){return u(this,arguments,function*(i,r,n=!1,s=!1,o={}){a(this,On,Bs).mediaJoinAttempted=!0,v(this,Ls,!0),n&&this.reset();try{return yield a(this,xs).push(()=>F(this,Gh,Gv).call(this,i,r,s,o),"joinRoom")}catch(c){return l.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):(v(this,Ci,(()=>u(this,null,function*(){try{yield F(this,sl,Kh).call(this,i,r,n,s)}catch(o){throw v(this,Ci,null),o}}))()),a(this,Ci))})}getConsumers(){return a(this,Y).consumers}leaveRoom(){return u(this,null,function*(){var t;a(this,Y).stopAllTransports(),v(this,Vs,!1),a(this,On,Bs).mediaJoinAttempted=!1;const e={closeRoom:!1};try{const i=yield a(this,Ct).sendMessagePromise(a(this,xt).leaveRoom,Yw.toBinary(e));(t=UI.fromBinary(i.payload))!=null&&t.closed||l.warn("weird state on peer closed and should not happen")}catch(i){l.error("error on sending leave room request",{error:i})}J.callEnded(),S.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,Y).createConsumers(t)})}closeConsumers(t){return u(this,null,function*(){if(!t.length)return;const e=t.reduce((i,r)=>{const n=a(this,Y).producerIdToConsumerIdMap.get(r.producerId);return n?(i.push(n),i):(l.warn(`consumer not found in close consumers: ${r.producerId}`),i)},[]);yield a(this,Y).closeConsumers(e)})}_shareWebcam(t,e){return u(this,null,function*(){const i=e==="video/VP9"?be.WEBCAM:be.WEBCAM_BACKUP,r=F(this,gt,Pt).call(this,i);if(r){const p=yield r;if(a(this,Y).producers.has(p)){const g=a(this,Y).producers.get(p);if(!g.closed)return yield g.replaceTrack({track:t}),yield this.resumeWebcam(i),t;yield this.disableWebcam(e)}return this._shareWebcam(t,e)}const n=[e].concat(Qt.filter(p=>p!==e)),s=F(this,ip,ey).call(this,t,n),o=Kn(this.context,"disableSimulcast"),c=a(this,ar)===Ne.CF?ie.ENABLE_CF_SIMULCAST:ie.ENABLE_HIVE_SIMULCAST;!o&&z.hasFeature(c)?(l.info(`Simulcast enabled for SFU: ${a(this,ar)}`),s.encodings=L1(t)):l.info(`Simulcast disabled for webcam producer, SFU: ${a(this,ar)}`),z.hasFeature(ie.TRACK_HINT)&&(s.track.contentHint=z.getValue(ie.TRACK_HINT));const d=()=>{l.info("Disabling video due to the producer closure"),a(this,Ut).delete(i)},h=a(this,Y).createProducer(s,d);return F(this,Ws,Do).call(this,i,h.then(p=>p.id)),h.then(p=>p.track)})}shareWebcam(t){return u(this,null,function*(){var e;if(t===void 0)return null;const i=(e=z.getValue(ie.FORCE_VIDEO_CODEC))==null?void 0:e.toString();if(i)return l.debug(`Calling _shareWebcam with forced video codec: ${i}`),this._shareWebcam(t,i);const r=Qt.filter(n=>{var s,o;return((o=(s=a(this,Mo).sender)==null?void 0:s.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===n))>=0&&a(this,Fs).get(n).size>0});return r.length===0&&r.push(Qt[0]),yield Promise.all(r.map(n=>(l.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=()=>{l.info("Disabling screenShare due to the producer closure"),a(this,Ut).delete(be.SCREENSHARE_VIDEO),a(this,Ut).delete(be.SCREENSHARE_AUDIO)},s=a(this,Y).createProducer(r,n);F(this,Ws,Do).call(this,be.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,ar)!==Ne.CF},d=()=>{};o=a(this,Y).createProducer(c,d),F(this,Ws,Do).call(this,be.SCREENSHARE_AUDIO,o.then(h=>h.id))}yield Promise.all([s,o||Promise.resolve()]),J.screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new Vt("track undefined");const e=F(this,gt,Pt).call(this,be.MIC);if(e){const s=yield e;if(a(this,Y).producers.has(s)){const o=a(this,Y).producers.get(s);if(!o.closed){yield o.replaceTrack({track:t}),yield this.resumeMic(),a(this,Xt)&&(a(this,Xt).audioTrack=t,a(this,Xt).producerId=s,a(this,Xt).start());return}yield a(this,Y).closeProducer(s,{stopTrack:!1})}yield this.shareMic(t);return}const i=F(this,tp,Zv).call(this,t),r=()=>{a(this,Ut).delete(be.MIC)},n=a(this,Y).createProducer(i,r);F(this,Ws,Do).call(this,be.MIC,n.then(s=>s.id)),yield n.then(s=>{a(this,Xt)&&(a(this,Xt).audioTrack=s.track,a(this,Xt).producerId=s.id,a(this,Xt).start())})}catch(e){throw new w(e)}})}pauseMic(){return u(this,null,function*(){var t;const e=yield F(this,gt,Pt).call(this,be.MIC),i=a(this,Y).producers.get(e);if(!i){l.error("pauseMic::could_not_find_mic_producer");return}if(i.paused){l.info("pauseMic::mic_producer_already_paused");return}i.pause(),(t=a(this,Xt))==null||t.stop();const r={producerId:i.id,pause:!0};a(this,Ct).sendMessage(a(this,xt).toggleProducer,Wc.toBinary(r))})}pauseWebcam(){return u(this,null,function*(){const t=yield F(this,gt,Pt).call(this,be.WEBCAM),e=yield F(this,gt,Pt).call(this,be.WEBCAM_BACKUP),i=a(this,Y).producers.get(t),r=a(this,Y).producers.get(e);if(!i&&!r){l.error("pauseWebcam::could_not_find_webcam_producer");return}const n=s=>{const o={producerId:s.id,pause:!0};a(this,Ct).sendMessage(a(this,xt).toggleProducer,Wc.toBinary(o))};i&&(i.pause(),n(i)),r&&(r.pause(),n(r))})}resumeMic(){return u(this,null,function*(){const t=yield F(this,gt,Pt).call(this,be.MIC),e=a(this,Y).producers.get(t);if(!e){l.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){l.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,Ct).sendMessage(a(this,xt).toggleProducer,Wc.toBinary(i))})}resumeWebcam(){return u(this,arguments,function*(t=be.WEBCAM){const e=yield F(this,gt,Pt).call(this,t),i=a(this,Y).producers.get(e);if(!i){l.error("resumeWebcam::could_not_find_webcam_producer");return}if(!i.paused){l.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,Ct).sendMessage(a(this,xt).toggleProducer,Wc.toBinary(r))})}disableWebcam(t){return u(this,null,function*(){const e=t==="video/VP9"?be.WEBCAM:be.WEBCAM_BACKUP,i=yield F(this,gt,Pt).call(this,e);F(this,ep,Xv).call(this,e),i&&(yield a(this,Y).closeProducer(i))})}disableMic(){return u(this,null,function*(){var t;const e=yield F(this,gt,Pt).call(this,be.MIC);e&&(yield a(this,Y).closeProducer(e)),(t=a(this,Xt))==null||t.stop(),a(this,Ut).delete(be.MIC)})}disableScreenShare(){return u(this,null,function*(){l.info("screen_sharing_stopped"),J.screenShareStop();const t=yield F(this,gt,Pt).call(this,be.SCREENSHARE_VIDEO),e=yield F(this,gt,Pt).call(this,be.SCREENSHARE_AUDIO);t&&(yield a(this,Y).closeProducer(t)),e&&(yield a(this,Y).closeProducer(e)),a(this,xr).clear(),a(this,Ut).delete(be.SCREENSHARE_VIDEO),a(this,Ut).delete(be.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 F(this,gt,Pt).call(this,be.WEBCAM),r=yield F(this,gt,Pt).call(this,be.WEBCAM_BACKUP);yield a(this,Y).closeProducer(i,{stopTrack:!1}),yield a(this,Y).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const i=yield F(this,gt,Pt).call(this,be.SCREENSHARE_VIDEO);yield a(this,Y).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,Y).socketHandler.changeDisplayName(i)))throw new Error("failed to change display name!")})}kick(t){const e={peerIds:[t]};a(this,Y).socketHandler.kickPeer(e)}kickAll(){a(this,Y).socketHandler.kickAll()}muteAll(t){return u(this,null,function*(){if(!(yield a(this,Y).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield a(this,Y).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield a(this,Y).socketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield a(this,Y).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,Ct).sendMessagePromise(a(this,xt).globalPinPeer,lI.toBinary(e))}catch(i){l.error("Error in pinning peer:",{error:i})}})}validateScreenShare(t){return this.peerId===t.peerId&&a(this,Y).producers.get(t.producerId)&&a(this,xr).add(t.consumerPeerId),a(this,xr).size}switchConsumersToLayer(t,e){return u(this,null,function*(){const i=t.map(r=>this.getConsumers().get(r));a(this,Y).switchConsumersToLayer(i,e)})}handleSocketEvents(){return u(this,null,function*(){a(this,Ct).on(a(this,xt).peerProducerCreateBroadcast,({payload:t})=>{var e,i;if(this.mediaJoined)try{const{participantId:r,producerState:n}=mC.fromBinary(t);if(r===this.peerId)return;if(n!=null&&n.mimeType||(n.mimeType=n.kind===Li.AUDIO?"audio/opus":"video/VP8"),n.kind===Li.VIDEO&&!n.screenShare&&((i=(e=a(this,Mo).receiver)==null?void 0:e.video)==null?void 0:i.codecs.findIndex(s=>s.mimeType===Qt[0]))>=0&&a(this,Us).get(Qt[0]).has(r)&&n.mimeType!==Qt[0]){l.warn(`Ignoring producer: ${n.producerId}`);return}l.info(`producer created broadcast: ${r}, producer state: ${n}`),this.context.getValue("peerSessionStore").emit(P.NEW_PRODUCER,{peerId:r,producer:j(L({},n),{kind:n.kind===Li.AUDIO?"audio":"video",producingPeerId:r})})}catch(r){l.error("error in peer-producer-create-broadcast",{error:r})}}),a(this,Ct).on(a(this,xt).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:i,producerState:{kind:r,pause:n,producerId:s}}=tf.fromBinary(t),o=r===Li.AUDIO?"audio":"video";if(l.info(`producer toggle broadcast: ${e}, producerId: ${s}, kind:${o}, paused:${n} payload: ${JSON.stringify(tf.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&&(l.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){l.error("error in producer toggle broadcast handler",{error:e})}}),a(this,Ct).on(a(this,xt).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=hu.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),a(this,xr).delete(e),a(this,Y).consumers.forEach(i=>{i.peerId===e&&i.close()}),this.context.getValue("peerSessionStore").emit(P.PEER_CLOSED,{id:e})}catch(e){l.error("error in peer left broadcast",{error:e})}}),a(this,Ct).on(a(this,xt).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:i}}=vC.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(P.PRODUCER_CLOSED,{peerId:e,producerId:i});const r=a(this,Y).producerIdToConsumerIdMap.get(i);if(!r){l.warn(`no consumer found for producer:${i}`);return}l.info(`closing consumer ${r}, producer id: ${i}`),a(this,Y).closeConsumer(r).then(()=>{l.info(`closed consumer: ${r}`),a(this,Y).producerIdToConsumerIdMap.delete(i),this.context.getValue("peerSessionStore").emit(P.CONSUMER_CLOSED,{id:r})}).catch(n=>{l.error("error closing consumer",{error:n})})}catch(e){l.error("error on producer close broadcast",{error:e})}}),a(this,Ct).on(a(this,xt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,Ls)&&!a(this,Vs)||(l.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_DISCONNECTED),a(this,nl).call(this))})})}handleCallstatsEvents(){J.onConsumerScore(t=>{t.forEach((e,i)=>{const r=a(this,Y).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})})}),J.onProducerScore(t=>{t.forEach((e,i)=>{const r=Array.from(a(this,Y).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<=Qt.length;o+=1){const c=Qt[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===Qt.length-1){a(this,Fs).get(c).add(t);break}}for(let o=0;o<=Qt.length;o+=1){const c=Qt[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===Qt.length-1){a(this,Us).get(c).add(t);break}}}handlePeerLeaving(t){z.hasFeature(ie.FORCE_VIDEO_CODEC)||(a(this,Us).forEach(e=>e.delete(t)),a(this,Fs).forEach((e,i)=>{e.delete(t),!(e.size!==0||i===Qt[0])&&this.disableWebcam(i)}))}},il=new WeakMap,rl=new WeakMap,Ct=new WeakMap,Y=new WeakMap,Mo=new WeakMap,ar=new WeakMap,xt=new WeakMap,Ls=new WeakMap,Vs=new WeakMap,xs=new WeakMap,nl=new WeakMap,Ci=new WeakMap,xr=new WeakMap,Ao=new WeakMap,Us=new WeakMap,Fs=new WeakMap,Ut=new WeakMap,Xt=new WeakMap,On=new WeakSet,Bs=function(){return this.context.getValue("connectionHandler")},Gh=new WeakSet,Gv=function(t,e,i,r){return u(this,null,function*(){v(this,rl,t);try{return a(this,Ci)?yield a(this,Ci):yield F(this,sl,Kh).call(this,t,e,i,r),F(this,Jh,Jv).call(this,e),{roomJoined:yield F(this,$h,$v).call(this)}}catch(n){return l.error("Failed to complete room join",{error:n}),{roomJoined:!1}}finally{v(this,Ci,null)}})},$h=new WeakSet,$v=function(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:t}=yield a(this,Y).socketHandler.notifySelfJoinComplete();return v(this,il,t.roomUuid),v(this,Vs,!0),v(this,Ls,!1),!0}catch(t){return l.error("Error completing room join",{error:t}),this.mediaJoined=!1,!1}})},Jh=new WeakSet,Jv=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:j(L({},Ie.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};J.roomJoined(e)}catch(e){l.error("Error reporting room joined analytics",{error:e})}},0)},sl=new WeakSet,Kh=function(t,e,i,r){return u(this,null,function*(){var n,s;try{(s=a(this,Ao))!=null||v(this,Ao,F(n=ty,zh,Kv).call(n));const o=F(this,Qh,zv).call(this);yield F(this,Xh,Yv).call(this,t,e,i,o),yield a(this,Y).setupTransports({send:!0,recv:!0}),yield F(this,Zh,Qv).call(this,r)}catch(o){throw l.error("Failed to initialize connection",{error:o}),o}})},zh=new WeakSet,Kv=function(){const{ipInfo:t}=ht();if(!(t!=null&&t.loc))return;const[e,i]=t.loc.split(",").map(parseFloat);return{latitude:e,longitude:i}},Qh=new WeakSet,zv=function(){var t;const e=(t=z.getValue(ie.FORCE_VIDEO_CODEC))==null?void 0:t.toString(),i=ND(e);return v(this,Mo,i),i},Xh=new WeakSet,Yv=function(t,e,i,r){return u(this,null,function*(){yield Tv((n,s)=>u(this,null,function*(){if(!a(this,Ct).isConnected){s(new Error("Socket is not connected"));return}n>0&&l.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${n}`});try{yield a(this,Y).socketHandler.joinRoom(e,t,r,i,a(this,Ao))}catch(o){throw l.error("Failed to send joinRoom message after retries",{error:o}),o}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:z.hasFeature(ie.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3})})},Zh=new WeakSet,Qv=function(t){return u(this,null,function*(){if(!(a(this,ar)===Ne.HIVE||!z.hasFeature(ie.PRECREATE_PRODUCERS)||!t))try{const e=[];if(t.canProduceVideo===H.Allowed&&e.push(this.shareWebcam(QD(!0))),t.canProduceAudio===H.Allowed){const i=YD(!0);i&&e.push(this.shareMic(i))}e.length>0&&(yield Promise.all(e))}catch(e){l.warn("Failed to precreate producers",{error:e})}})},gt=new WeakSet,Pt=function(t){return a(this,Ut).get(t)},Ws=new WeakSet,Do=function(t,e){return a(this,Ut).set(t,e)},ep=new WeakSet,Xv=function(t){return a(this,Ut).delete(t)},tp=new WeakSet,Zv=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:a(this,ar)!==Ne.CF}},ip=new WeakSet,ey=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}},f(Yh,zh),Yh);let ue=ty;me([S.trace("MediaNodeClient.reset",{country:S.location.country})],ue.prototype,"reset",1),me([S.trace("MediaNodeClient.joinRoom")],ue.prototype,"joinRoom",1),me([S.trace("MediaNodeClient.leaveRoom")],ue.prototype,"leaveRoom",1),me([S.trace("MediaNodeClient.activatePeers")],ue.prototype,"activatePeers",1),me([S.trace("MediaNodeClient.createConsumers")],ue.prototype,"createConsumers",1),me([S.trace("MediaNodeClient.closeConsumers")],ue.prototype,"closeConsumers",1),me([S.trace("MediaNodeClient._shareWebcam")],ue.prototype,"_shareWebcam",1),me([S.trace("MediaNodeClient.shareWebcam")],ue.prototype,"shareWebcam",1),me([S.trace("MediaNodeClient.shareScreen")],ue.prototype,"shareScreen",1),me([S.trace("MediaNodeClient.shareMic")],ue.prototype,"shareMic",1),me([S.trace("MediaNodeClient.pauseMic")],ue.prototype,"pauseMic",1),me([S.trace("MediaNodeClient.pauseWebcam")],ue.prototype,"pauseWebcam",1),me([S.trace("MediaNodeClient.resumeMic")],ue.prototype,"resumeMic",1),me([S.trace("MediaNodeClient.resumeWebcam")],ue.prototype,"resumeWebcam",1),me([S.trace("MediaNodeClient.disableWebcam")],ue.prototype,"disableWebcam",1),me([S.trace("HiveClient.disableMic")],ue.prototype,"disableMic",1),me([S.trace("HiveClient.disableScreenShare")],ue.prototype,"disableScreenShare",1),me([S.trace("MediaNodeClient.muteSelf")],ue.prototype,"muteSelf",1),me([S.trace("MediaNodeClient.resetVideoProducers")],ue.prototype,"resetVideoProducers",1),me([S.trace("MediaNodeClient.changeDisplayName")],ue.prototype,"changeDisplayName",1),me([S.trace("MediaNodeClient.kickPeer")],ue.prototype,"kick",1),me([S.trace("MediaNodeClient.kickAllPeers")],ue.prototype,"kickAll",1),me([S.trace("MediaNodeClient.muteAll")],ue.prototype,"muteAll",1),me([S.trace("MediaNodeClient.muteAllVideo")],ue.prototype,"muteAllVideo",1),me([S.trace("MediaNodeClient.disableAudio")],ue.prototype,"disableAudio",1),me([S.trace("MediaNodeClient.disableVideo")],ue.prototype,"disableVideo",1),me([S.trace("MediaNodeClient.pinPeer")],ue.prototype,"pinPeer",1),me([S.trace("MediaNodeClient.validateScreenShare")],ue.prototype,"validateScreenShare",1);function iy(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 ue(t,e,i);return t.setValue("roomNodeClient",n),n}function ry(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch(i){l.error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var eO=Object.defineProperty,tO=Object.getOwnPropertyDescriptor,Nn=(t,e,i,r)=>{for(var n=r>1?void 0:r?tO(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&&eO(e,i,n),n},Ln,Hi,de,Ft,Zt,ny;const sy=(ny=class{constructor(t,e,i,r){f(this,Ft),m(this,"self"),m(this,"authToken"),f(this,Ln,void 0),m(this,"viewType"),f(this,Hi,void 0),f(this,de,void 0);const{socket:n}=i,s=t.getValue("authToken");this.self=e,v(this,de,t),this.viewType=r,this.authToken=s,v(this,Ln,n),v(this,Hi,i),e.config.viewType!==Rt.Chat&&this.setupEvents()}get peerId(){return a(this,de).getValue("peerId")}get mediaJoined(){return a(this,de).getValue("connectionHandler").mediaJoined}static init(t,e,i,r,n){return u(this,null,function*(){const s=ht(),o=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield tt.__init__(t,i,r,n,n.name,c);if(navigator.product!=="ReactNative"){const h=!z.hasFeature(ie.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const p=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(p)}),J.devices("AUDIO",p==null?void 0:p.filter(g=>g.kind==="audioinput")),J.devices("VIDEO",p==null?void 0:p.filter(g=>g.kind==="videoinput")),J.devices("SPEAKER",p==null?void 0:p.filter(g=>g.kind==="audiooutput")),l.info("Callstats:: initializing");try{yield J.initialize({peerId:o,engineName:Ie.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:z.getAllFlags(),logger:l,apiHostnames:xg(t),skipConnectivityChecks:h}),l.info("Callstats:: initialized")}catch(g){l.error("Callstats:: initialization failed",{error:g})}}),0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new sy(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===H.Allowed&&n)try{yield a(this,Ft,Zt).shareMic(e),this.self.audioEnabled||a(this,Ft,Zt).pauseMic()}catch(d){this.self.disableAudio()}if(r.canProduceVideo===H.Allowed&&s)try{const d=yield a(this,Ft,Zt).shareWebcam(i);d&&d.id!==i.id&&z.hasFeature(ie.EXP_RESHARE)&&(yield a(this,Ft,Zt).shareWebcam(d)),this.self.videoEnabled||a(this,Ft,Zt).pauseWebcam()}catch(d){this.self.disableVideo()}if(r.canProduceScreenshare===H.Allowed&&o)try{yield(t=a(this,Ft,Zt))==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(){l.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(l.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){l.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(l.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){l.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(t){return u(this,null,function*(){J.callEnded(),a(this,Ft,Zt).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){a(this,de).getValue("peerSessionStore").on(P.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),a(this,de).getValue("peerSessionStore").on(P.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,de).getValue("peerSessionStore").on(P.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,de).getValue("peerSessionStore").on(P.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,de).getValue("peerSessionStore").on(P.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),a(this,de).getValue("peerSessionStore").on(P.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&z.hasFeature(ie.REFRESH_ID_ON_DISCONNECTION)&&(e=jn()),a(this,Ln).updateURL(e),S.resetPeerId(e),ht().setHeader("dyte-tracing-id",e),en.remapContext(e,a(this,de)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,de).getValue("peerSessionStore").on(P.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Hi).on(B.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Hi).on(Jc.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&a(this,de).getValue("peerSessionStore").emit(P.UPDATE_PERMISSIONS,e.patch)})}),a(this,Hi).on(B.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Hi).on(B.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Hi).on(B.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,de).getValue("peerSessionStore").onAsync(P.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,de).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,de).getValue("peerSessionStore").on(P.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),J.audioOff())})),a(this,de).getValue("peerSessionStore").on(P.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),J.videoOff())})),a(this,de).getValue("peerSessionStore").onAsync(P.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,de).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,Hi).joinRoom(this.self);a(this,Hi).socket.flush();const i=Fu(e.stageType);if(a(this,de).setValue("stageStatus",i,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),a(this,de).notify("stageStatus")}catch(e){throw l.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,Ln))==null||e.disconnect()}catch(r){l.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),a(this,de).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),a(this,de).notify("stageStatus");try{(i=a(this,Ln))==null||i.disconnect()}catch(r){l.error("SelfController::leaveRoom::socketDisconnect")}ry(a(this,de)),yield a(this,de).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,de).getAllValues(),{sfu:d}=c;try{if(n===Rt.Livestream){if(o!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}iy(a(this,de),d,{socket:a(this,Ln),peerId:r})}const{canProduceAudio:h,canProduceVideo:p,canProduceScreenshare:g}=this.self.permissions,{roomJoined:y}=(i=yield(e=a(this,Ft,Zt))==null?void 0:e.joinRoom(this.self.name,s,t,t,{canProduceAudio:h,canProduceVideo:p,canProduceScreenshare:g}))!=null?i:{};if(!y)return;o==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(h){throw l.error("Error:SelfController.mediaRoomJoin",{error:h}),new w("Error: could not join media room","0002")}})}leaveMediaRoom(t){return u(this,null,function*(){const e=a(this,de).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===Rt.Webinar)&&a(this,Ft,Zt)&&(a(this,Ft,Zt).mediaJoined&&t!=="disconnected"&&(yield a(this,Ft,Zt).leaveRoom()),!(t==="stageLeft"&&e===Rt.Livestream)&&(a(this,Ft,Zt).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()})}},Ln=new WeakMap,Hi=new WeakMap,de=new WeakMap,Ft=new WeakSet,Zt=function(){return a(this,de).getValue("roomNodeClient")},ny);let Ur=sy;Nn([S.trace("SelfController.resetSelf")],Ur.prototype,"resetSelf",1),Nn([S.trace("SelfController.setupEvents")],Ur.prototype,"setupEvents",1),Nn([S.trace("SelfController.joinRoom")],Ur.prototype,"joinRoom",1),Nn([S.trace("SelfController.leaveRoom")],Ur.prototype,"leaveRoom",1),Nn([S.trace("SelfController.joinMediaRoom")],Ur.prototype,"joinMediaRoom",1),Nn([S.trace("SelfController.leaveMediaRoom")],Ur.prototype,"leaveMediaRoom",1),Nn([S.trace("SelfController.init")],Ur,"init",1);var al;class iO{constructor(e){f(this,al,void 0),v(this,al,e)}on(e,i){let r;e===B.roomPeerCount?r=sf.fromBinary.bind(sf):r=kf.fromBinary.bind(kf),a(this,al).on(e,({payload:n})=>{const s=r(n);return i(s)})}}al=new WeakMap;var ol;class rO{constructor(e){f(this,ol,void 0),v(this,ol,e)}on(e,i){let r,n;switch(e){case B.transcript:{r=pu.fromBinary.bind(pu),n=pu.create();break}default:{l.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,ol).on(e,({payload:s})=>{let o=n;try{o=r(s)}catch(c){l.error("chatSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}}ol=new WeakMap;var nO=Object.defineProperty,sO=Object.getOwnPropertyDescriptor,rp=(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&&nO(e,i,n),n},Fr;class cl{constructor(e){f(this,Fr,void 0),v(this,Fr,e)}getPolls(){return a(this,Fr).sendMessagePromise(Xi.getPolls)}createPoll(e,i,r=!1,n=!1){const s={anonymous:r,hideVotes:n,question:e,options:i};return a(this,Fr).sendMessage(Xi.createPoll,sA.toBinary(s))}votePoll(e,i){const r={index:i,pollId:e};return a(this,Fr).sendMessage(Xi.votePoll,oA.toBinary(r))}on(e,i){let r,n;switch(e){case Xi.updatePoll:case Xi.createPoll:case Xi.votePoll:{r=Iu.fromBinary.bind(Iu),n=Iu.create();break}}a(this,Fr).on(e,({payload:s})=>{let o=n;try{o=r(s)}catch(c){l.error("pollSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}removeListeners(e){a(this,Fr).removeListeners(e)}}Fr=new WeakMap,rp([S.trace("PollSocketHandler.getPolls")],cl.prototype,"getPolls",1),rp([S.trace("PollSocketHandler.createPoll")],cl.prototype,"createPoll",1),rp([S.trace("PollSocketHandler.votePoll")],cl.prototype,"votePoll",1);var aO=Object.defineProperty,oO=Object.getOwnPropertyDescriptor,cO=(t,e,i,r)=>{for(var n=r>1?void 0:r?oO(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&&aO(e,i,n),n},qi;class ay{constructor(e,i){m(this,"socket"),f(this,qi,void 0),v(this,qi,e),this.socket=i,this.handleSocketEvents(),a(this,qi).setValue("roomSocketHandler",this)}cleanup(){return u(this,null,function*(){var e;try{(e=this.socket)==null||e.disconnect()}catch(i){l.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(B.joinRoom,$C.toBinary(r));try{const{peer:s}=Xn.fromBinary((yield n).payload);a(this,qi).getValue("connectionHandler").socketJoined=!0,a(this,qi).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_ROOM_JOINED,{peer:s});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:h}]=yield Promise.all([o,c]);return a(this,qi).getValue("peerSessionStore").emit(P.ROOM_STATE,d),a(this,qi).getValue("peerSessionStore").emit(P.SOCKET_PEERS,h),{peer:s}}catch(s){throw l.error("RoomSocketHandler.joinRoom.failed",{error:s}),new w("Error: RoomSocketHandler.joinRoom failed.","0002",s)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return MP.fromBinary((yield this.socket.sendMessagePromise(B.getAllAddedParticipants)).payload).participants.map(e=>{var i=e,{id:r}=i,n=vc(i,["id"]);return j(L({},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(B.getRoomPeersInfo,VC.toBinary(s));n=fu.fromBinary(o.payload)}catch(s){l.error("getRoomPeers::binary_decode_error",{error:s})}return n})}getRoomPeersNonPaginated(){return u(this,null,function*(){let e;try{const i=yield this.socket.sendMessagePromise(B.getRoomPeersInfo);e=fu.fromBinary(i.payload)}catch(i){l.error("getRoomJoinedPeers::binary_decode_error",{error:i})}return e})}getStagePeers(){return u(this,null,function*(){let e;try{const i=yield this.socket.sendMessagePromise(B.getRoomPeersInfo);e=fu.fromBinary(i.payload)}catch(i){l.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(B.getPeerInfo,cf.toBinary({peerId:e}));i=Xn.fromBinary(r.payload)}catch(r){l.error("getPeerInfo::binary_decode_error",{error:r})}return i})}getRoomState(){return u(this,null,function*(){let e=of.create();try{const i=yield this.socket.sendMessagePromise(B.getRoomInfo);e=of.fromBinary(i.payload)}catch(i){l.error("getRoomState::binary_decode_error",{error:i})}return e})}getRoomStageState(){return u(this,null,function*(){let e=mf.create();try{const i=yield this.socket.sendMessagePromise(B.getRoomStageState);e=mf.fromBinary(i.payload)}catch(i){l.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(B.broadcastMessage,pa.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(B.broadcastToEntity,pa.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(B.broadcastToEntity,pa.toBinary(n))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(B.leaveRoom,KC.toBinary({}))})}kick(e){return u(this,null,function*(){const i={peerIds:[e]};this.socket.sendMessage(B.kick,hf.toBinary(i))})}kickAll(e=!1){return u(this,null,function*(){const i={propagateKickAcrossRooms:e};this.socket.sendMessage(B.kickAll,Yg.toBinary(i))})}getWaitingRoomRequests(){this.socket.sendMessage(B.getWaitingRoomRequests)}acceptWaitingRoomRequest(e){const i={userIds:e};this.socket.sendMessage(B.acceptWaitingRoomRequests,VP.toBinary(i))}rejectWaitingRoomRequest(e){const i={userIds:e};this.socket.sendMessage(B.denyWaitingRoomRequests,UP.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(Jc.updateUserPreset,pR.toBinary(r))})}handleSocketEvents(){this.socket.on(B.broadcastMessage,({payload:e})=>{try{const i=pa.fromBinary(e);a(this,qi).getValue("peerSessionStore").emit(P.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(i.payload)),type:i.type,timestamp:i.timestamp})}catch(i){l.error("failed to decode broadcast message:",i)}}),this.socket.on(B.broadcastToEntity,({payload:e})=>{try{const i=pa.fromBinary(e);a(this,qi).getValue("peerSessionStore").emit(P.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(i.payload)),type:i.type,timestamp:i.timestamp})}catch(i){l.error("failed to decode peer broadcast message:",i)}})}on(e,i){let r,n;switch(e){case B.joinRoom:case B.leaveRoom:case B.kick:case B.kickAll:{r=Xn.fromBinary.bind(Xn),n=Xn.create();break}case B.getWaitingRoomRequests:{r=(s,o)=>s?pf.fromBinary(s,o):{requests:[]},n=pf.create();break}case B.recordingPaused:case B.recordingStarted:case B.recordingStopped:{r=If.fromBinary.bind(If);break}case Jc.updateUserPreset:{r=ff.fromBinary.bind(ff);break}case gi.peerJoinedBroadcast:case ii.peerJoinedBroadcast:{r=Zg.fromBinary.bind(Zg);break}case gi.selfJoinComplete:case ii.selfJoinComplete:{r=uu.fromBinary.bind(uu);break}case gi.globalPeerPinBroadcast:case ii.globalPeerPinBroadcast:{r=rf.fromBinary.bind(rf);break}case gi.selectedPeer:case ii.selectedPeer:{r=lu.fromBinary.bind(lu);break}case gi.selectedPeerDiff:case ii.selectedPeerDiff:{r=Xg.fromBinary.bind(Xg);break}case gi.leaveRoom:case ii.leaveRoom:{r=hu.fromBinary.bind(hu);break}}this.socket.on(e,({payload:s})=>{let o=n;if(!r)return i(void 0);try{o=r(s)}catch(c){l.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(Jc.getUserPresets,aR.toBinary(i)),n=lR.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 l.error("Error in getting user preset",{error:r}),r}})}}qi=new WeakMap,cO([S.trace("RoomSocketHandler.joinRoom")],ay.prototype,"joinRoom",1);var ei;class dO{constructor(e){f(this,ei,void 0),v(this,ei,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield a(this,ei).sendMessagePromise(B.getStageRequests);return e?wu.fromBinary(e):{stageRequests:[]}})}requestAccess(){a(this,ei).sendMessage(B.requestStageAccess)}cancelRequestAccess(){a(this,ei).sendMessage(B.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,ei).sendMessage(B.grantStageAccess,zM.toBinary(i))})}denyAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,ei).sendMessage(B.denyStageAccess,QM.toBinary(i))})}joinStage(){return a(this,ei).sendMessagePromise(B.joinStage,void 0,void 0,B.peerStageStatusUpdate)}leaveStage(e){const i={userIds:[e]};return a(this,ei).sendMessagePromise(B.leaveStage,_f.toBinary(i),void 0,B.peerStageStatusUpdate)}kick(e){const i={userIds:e};return a(this,ei).sendMessagePromise(B.leaveStage,_f.toBinary(i))}on(e,i){let r;switch(e){case B.grantStageAccess:case B.denyStageAccess:{r=void 0;break}case B.getStagePeers:{r=bf.fromBinary.bind(bf);break}case B.getStageRequests:case B.requestStageAccess:case B.cancelStageRequest:{r=wu.fromBinary.bind(wu);break}case B.peerStageStatusUpdate:{r=nf.fromBinary.bind(nf);break}}a(this,ei).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,ei).sendMessagePromise(B.getPeerInfo,cf.toBinary({peerId:e}));return Xn.fromBinary(i.payload)})}}ei=new WeakMap;var it;class lO{constructor(e){f(this,it,void 0),v(this,it,e)}addPlugin(e,i){a(this,it).sendMessage(K.addPlugin,hM.toBinary({pluginId:e,staggered:i}))}removePlugin(e){a(this,it).sendMessage(K.removePlugin,mM.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield a(this,it).sendMessagePromise(K.getPlugins);return e?xM.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,i,r){const n={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(i))};a(this,it).sendMessage(K.customPluginEventToRoom,_M.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(K.customPluginEventToPeers,IM.toBinary(s),n)}enablePluginForRoom(e,i){a(this,it).sendMessage(K.enablePluginForRoom,fM.toBinary({pluginId:e}),i)}enablePluginForPeers(e,i,r){a(this,it).sendMessage(K.enablePluginForPeers,EM.toBinary({pluginId:e,peerIds:i}),r)}disablePluginForRoom(e,i){a(this,it).sendMessage(K.disablePluginForRoom,yM.toBinary({pluginId:e}),i)}disablePluginForPeers(e,i,r){a(this,it).sendMessage(K.disablePluginForPeers,kM.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(K.storeInsertKeys,yf.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(K.storeGetKeys,MM.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(K.storeDeleteKeys,DM.toBinary(s),n)}storeDelete(e,i,r){a(this,it).sendMessage(K.storeDelete,NM.toBinary({pluginId:e,storeName:i}),r)}getPluginDataOld(e,i){l.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(K.storeInsertKeys,yf.toBinary(n))}on(e,i){let r;switch(e){case K.addPlugin:case K.enablePluginForPeers:case K.enablePluginForRoom:{r=_u.fromBinary.bind(_u);break}case K.removePlugin:case K.disablePluginForPeers:case K.disablePluginForRoom:{r=Sf.fromBinary.bind(Sf);break}case K.customPluginEventToPeers:case K.customPluginEventToRoom:{r=Tf.fromBinary.bind(Tf);break}case K.storeInsertKeys:case K.storeGetKeys:case K.storeDeleteKeys:case K.storeDelete:{r=Ef.fromBinary.bind(Ef);break}}a(this,it).on(e,({payload:n,id:s})=>{const o=r(n);return i(o,s)})}}it=new WeakMap;var uO=Object.defineProperty,hO=(t,e,i)=>e in t?uO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,pO=(t,e,i)=>(hO(t,typeof e!="symbol"?e+"":e,i),i),np=(t,e,i)=>{if(!e.has(t))throw TypeError("Cannot "+i)},N=(t,e,i)=>(np(t,e,"read from private field"),i?i.call(t):e.get(t)),Pe=(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)},he=(t,e,i,r)=>(np(t,e,"write to private field"),r?r.call(t,i):e.set(t,i),i),Ae=(t,e,i)=>(np(t,e,"access private method"),i),dl={},mO={get exports(){return dl},set exports(t){dl=t}},js=typeof Reflect=="object"?Reflect:null,oy=js&&typeof js.apply=="function"?js.apply:function(t,e,i){return Function.prototype.apply.call(t,e,i)},ll;js&&typeof js.ownKeys=="function"?ll=js.ownKeys:Object.getOwnPropertySymbols?ll=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:ll=function(t){return Object.getOwnPropertyNames(t)};function gO(t){console&&console.warn&&console.warn(t)}var cy=Number.isNaN||function(t){return t!==t};function ge(){ge.init.call(this)}mO.exports=ge,dl.once=SO,ge.EventEmitter=ge,ge.prototype._events=void 0,ge.prototype._eventsCount=0,ge.prototype._maxListeners=void 0;var dy=10;function ul(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(ge,"defaultMaxListeners",{enumerable:!0,get:function(){return dy},set:function(t){if(typeof t!="number"||t<0||cy(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");dy=t}}),ge.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},ge.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||cy(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 ly(t){return t._maxListeners===void 0?ge.defaultMaxListeners:t._maxListeners}ge.prototype.getMaxListeners=function(){return ly(this)},ge.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")oy(c,this,e);else for(var d=c.length,h=gy(c,d),i=0;i<d;++i)oy(h[i],this,e);return!0};function uy(t,e,i,r){var n,s,o;if(ul(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=ly(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,gO(c)}return t}ge.prototype.addListener=function(t,e){return uy(this,t,e,!1)},ge.prototype.on=ge.prototype.addListener,ge.prototype.prependListener=function(t,e){return uy(this,t,e,!0)};function fO(){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 hy(t,e,i){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:i},n=fO.bind(r);return n.listener=i,r.wrapFn=n,n}ge.prototype.once=function(t,e){return ul(e),this.on(t,hy(this,t,e)),this},ge.prototype.prependOnceListener=function(t,e){return ul(e),this.prependListener(t,hy(this,t,e)),this},ge.prototype.removeListener=function(t,e){var i,r,n,s,o;if(ul(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},ge.prototype.off=ge.prototype.removeListener,ge.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 py(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?yO(n):gy(n,n.length)}ge.prototype.listeners=function(t){return py(this,t,!0)},ge.prototype.rawListeners=function(t){return py(this,t,!1)},ge.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):my.call(t,e)},ge.prototype.listenerCount=my;function my(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}ge.prototype.eventNames=function(){return this._eventsCount>0?ll(this._events):[]};function gy(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 yO(t){for(var e=new Array(t.length),i=0;i<e.length;++i)e[i]=t[i].listener||t[i];return e}function SO(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))}fy(t,e,s,{once:!0}),e!=="error"&&EO(t,n,{once:!0})})}function EO(t,e,i){typeof t.on=="function"&&fy(t,"error",e,i)}function fy(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 TO extends E{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 TO;class yy{static encode(e){return vy.toBinary(e)}static decode(e){return vy.fromBinary(new Uint8Array(e))}}function kO(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var Br;class bO{constructor(e={}){pO(this,"opts"),Pe(this,Br,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},he(this,Br,0)}wait(){return u(this,null,function*(){he(this,Br,N(this,Br)+1);const e=kO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*OS(2,N(this,Br))));yield new Promise(i=>{setTimeout(i,e)})})}getAttempts(){return N(this,Br)}reset(){he(this,Br,0)}}Br=new WeakMap;const Wr={debug:0,info:1,warn:2,error:3};var Vn,xn;class _O{constructor(e){Pe(this,Vn,void 0),Pe(this,xn,void 0),he(this,Vn,console),he(this,xn,e)}debug(...e){Wr[N(this,xn)]>Wr.debug||N(this,Vn).debug("[Sockrates]:",...e)}info(...e){Wr[N(this,xn)]>Wr.info||N(this,Vn).info("[Sockrates]:",...e)}warn(...e){Wr[N(this,xn)]>Wr.warn||N(this,Vn).warn("[Sockrates]:",...e)}error(...e){Wr[N(this,xn)]>Wr.error||N(this,Vn).error("[Sockrates]:",...e)}}Vn=new WeakMap,xn=new WeakMap;var Sy=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(Sy||{});const wO="2",IO="3";var xe,Hs,De,He,jr,rt,or,Hr,Pi,qs,cr,sp,Ey,Oo,hl,ap,Ty,op,ky,pl,cp,dp,by,No,ml,Lo,gl,fl,lp,Gs,Vo,xo,vl;class CO{constructor(e,i){var r;Pe(this,sp),Pe(this,Oo),Pe(this,ap),Pe(this,op),Pe(this,pl),Pe(this,dp),Pe(this,No),Pe(this,Lo),Pe(this,fl),Pe(this,Gs),Pe(this,xo),Pe(this,xe,void 0),Pe(this,Hs,void 0),Pe(this,De,void 0),Pe(this,He,void 0),Pe(this,jr,void 0),Pe(this,rt,void 0),Pe(this,or,void 0),Pe(this,Hr,void 0),Pe(this,Pi,void 0),Pe(this,qs,void 0),Pe(this,cr,void 0);var n,s,o,c,d,h,p,g,y;he(this,Hs,e),he(this,jr,[]),he(this,rt,new dl),he(this,or,!0),he(this,Pi,!1),he(this,De,i!=null?i:{}),(n=N(this,De)).autoReconnect!=null||(n.autoReconnect=!0),(s=N(this,De)).retryConnectionInterval!=null||(s.retryConnectionInterval=1e3),(o=N(this,De)).pingTimeout!=null||(o.pingTimeout=3e4),(c=N(this,De)).connectionTimeout!=null||(c.connectionTimeout=5e3),(d=N(this,De)).debug!=null||(d.debug=!0),(h=N(this,De)).maxReconnectionAttempts!=null||(h.maxReconnectionAttempts=10),(p=N(this,De)).disconnectOnPingTimeout!=null||(p.disconnectOnPingTimeout=!0),(g=N(this,De)).queueOnDisconnect!=null||(g.queueOnDisconnect=!1),(y=N(this,De)).flushOnReconnect!=null||(y.flushOnReconnect=!1),he(this,Hr,{code:void 0,reason:void 0}),he(this,He,(r=N(this,De).logger)!=null?r:new _O(N(this,De).debug?"debug":"info")),he(this,cr,new bO)}get readyState(){var e;return(e=N(this,xe))==null?void 0:e.readyState}get url(){return N(this,Hs)}updateURL(e){he(this,Hs,e),Ae(this,dp,by).call(this)}get config(){return N(this,De)}get sendQueue(){return N(this,jr)}flush(){if(!N(this,De).queueOnDisconnect)return!1;const e=[];return N(this,jr).forEach(i=>{this.send(i.event,i.id,i.payload,i.metadata)||e.push(i)}),he(this,jr,e),N(this,jr)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){N(this,He).debug("Websocket was already connecting or connected.");return}if(N(this,or)!==!1)return new Promise((i,r)=>{Ae(this,Gs,Vo).call(this),Ae(this,xo,vl).call(this);try{he(this,xe,new WebSocket(Ae(this,sp,Ey).call(this,N(this,Hs)))),N(this,xe).binaryType="arraybuffer",N(this,He).debug("Connecting");const n=setTimeout(()=>{N(this,He).debug("Connection timeout. Closing socket"),he(this,or,!0),Ae(this,xo,vl).call(this),N(this,xe).close(3001,"Connection Timeout"),N(this,De).autoReconnect&&!N(this,Pi)&&(N(this,rt).emit("reconnecting"),Ae(this,No,ml).call(this)),r(new Error("Connection timed out!"))},N(this,De).connectionTimeout);N(this,xe).onopen=()=>{N(this,He).debug(`Ready State: ${Sy[N(this,xe).readyState]}`),n&&clearTimeout(n),Ae(this,fl,lp).call(this),he(this,Hr,{code:void 0,reason:void 0}),N(this,rt).emit("connected"),N(this,De).flushOnReconnect&&this.flush(),i()},N(this,xe).onclose=s=>{try{n&&clearTimeout(n);const{code:o,reason:c}=s;r(c),N(this,He).debug("Socket closed. Close event:",{event:s}),N(this,He).debug(`Connection closed code: ${o}`),N(this,He).debug(`Connection closed reason: ${c}`),N(this,Pi)||Ae(this,pl,cp).call(this,o,c)}catch(o){Ae(this,Oo,hl).call(this,o)}},N(this,xe).onerror=s=>{Ae(this,Oo,hl).call(this,s)},N(this,xe).onmessage=s=>Ae(this,ap,Ty).call(this,s)}catch(n){Ae(this,Oo,hl).call(this,n,r)}})})}send(e,i,r,n){const s={event:e,id:i,payload:r,metadata:n};if(N(this,De).queueOnDisconnect&&(!N(this,xe)||N(this,xe).readyState!==1))return N(this,He).debug("Queuing message since socket is not connected!",s),N(this,jr).push(s),!1;const o=yy.encode(s);return Ae(this,Lo,gl).call(this,o)}emit(e,i,r,n){return this.send(e,i,r,n)}sendRaw(e){return Ae(this,Lo,gl).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(){he(this,or,!1),Ae(this,Gs,Vo).call(this),this.removeAllListeners(),he(this,Hr,{code:1e3,reason:"Sockrates disconnect method called"}),N(this,xe).close(1e3,"Sockrates disconnect method called.")}}xe=new WeakMap,Hs=new WeakMap,De=new WeakMap,He=new WeakMap,jr=new WeakMap,rt=new WeakMap,or=new WeakMap,Hr=new WeakMap,Pi=new WeakMap,qs=new WeakMap,cr=new WeakMap,sp=new WeakSet,Ey=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)://.")},Oo=new WeakSet,hl=function(t,e){N(this,He).error("Error:",{error:t}),N(this,rt).emit("errored",{error:t}),e==null||e(t)},ap=new WeakSet,Ty=function(t){if(Ae(this,fl,lp).call(this),t.data===wO){N(this,He).debug("Received ping from server"),Ae(this,Lo,gl).call(this,IO);return}const e=yy.decode(t.data),{id:i,payload:r}=e;N(this,He).debug("Received message",{event:e.event,messageID:i}),N(this,rt).emit(e.event.toString(),{id:i,payload:r})},op=new WeakSet,ky=function(){return N(this,xe).readyState===1},pl=new WeakSet,cp=function(t,e){he(this,Hr,{reason:e,code:t}),N(this,rt).emit("disconnected",{code:t,reason:e})},dp=new WeakSet,by=function(){const{reason:t,code:e}=N(this,Hr);e&&e!==1e3&&N(this,or)&&N(this,De).autoReconnect&&!N(this,Pi)&&(N(this,He).debug(`Triggering reconnection due to ${t}.`),N(this,rt).emit("reconnecting"),Ae(this,No,ml).call(this))},No=new WeakSet,ml=function(t=!0){return u(this,null,function*(){if(t&&N(this,Pi)){N(this,He).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(N(this,Pi)||N(this,cr).reset(),N(this,De).maxReconnectionAttempts!==null&&N(this,cr).getAttempts()>=N(this,De).maxReconnectionAttempts){N(this,rt).emit("failed"),he(this,Pi,!1);return}he(this,Pi,!0),Ae(this,xo,vl).call(this),Ae(this,Gs,Vo).call(this);try{if(yield N(this,cr).wait(),N(this,or)===!1)return;if(N(this,He).debug(`Reconnection attempt ${N(this,cr).getAttempts()}`),N(this,rt).emit("reconnectAttempt",{attempt:N(this,cr).getAttempts()}),yield this.connect(),!Ae(this,op,ky).call(this))throw Error("Reconnect Failed");he(this,Pi,!1),he(this,Hr,{code:void 0,reason:void 0}),N(this,rt).emit("reconnected")}catch(e){N(this,He).debug("Failed to reconnect."),N(this,rt).emit("reconnectFailure",{attempt:N(this,cr).getAttempts()}),Ae(this,No,ml).call(this,!1)}})},Lo=new WeakSet,gl=function(t){try{return N(this,xe).send(t),!0}catch(e){return N(this,He).error(e.message),!1}},fl=new WeakSet,lp=function(){this.config.disconnectOnPingTimeout&&(N(this,He).debug("Resetting ping timeout"),Ae(this,Gs,Vo).call(this),he(this,qs,setTimeout(()=>{var t;N(this,He).debug("Disconnecting the socket due to ping timeout"),he(this,or,!0);const e=3002,i="Ping timeout";(t=N(this,xe))==null||t.close(e,i),Ae(this,pl,cp).call(this,e,i)},N(this,De).pingTimeout)))},Gs=new WeakSet,Vo=function(){N(this,qs)&&(clearTimeout(N(this,qs)),he(this,qs,void 0))},xo=new WeakSet,vl=function(){N(this,xe)&&(N(this,xe).onopen=void 0,N(this,xe).onerror=void 0,N(this,xe).onmessage=void 0,N(this,xe).onclose=void 0)};var PO=Object.defineProperty,RO=Object.getOwnPropertyDescriptor,yl=(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};const _y=65535,MO=3e3;var Un,Ue,Fe,qe,Ri,ci,Sl,up,El,hp,wy;const Iy=(wy=class{constructor(t,{peerId:e,meetingId:i,authToken:r,capabilities:n}){f(this,Fe),f(this,Sl),f(this,El),f(this,Un,void 0),f(this,Ue,void 0),m(this,"roomName"),m(this,"authToken"),m(this,"capabilities"),f(this,Ri,void 0),f(this,ci,void 0);var s;if(!e||!i||!r)throw new w("peerId, meetingId, or authToken can not be empty","0404");v(this,Ri,void 0),v(this,ci,t),this.capabilities=n,this.roomName=i,this.authToken=r,v(this,Un,F(this,Sl,up).call(this,e)),v(this,Ue,new CO(a(this,Un),{autoReconnect:!0,disconnectOnPingTimeout:(s=n.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:l})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Fe,qe).socketJoinAttempted}set joinAttempted(t){a(this,Fe,qe).socketJoinAttempted=t}get peerId(){return a(this,ci).getValue("peerId")}updateURL(t){t!==this.peerId&&(v(this,Un,F(this,Sl,up).call(this,t)),l.debug("SocketService:: Connection URL updated.")),a(this,Ue).updateURL(a(this,Un))}static getSocketEdgeDomain(t){return zn({servicePrefix:"socket-edge",baseURI:t})}get url(){return a(this,Un)}connect(){return u(this,null,function*(){a(this,Fe,qe).socketJoinAttempted=!0,yield a(this,Ue).connect(),a(this,Fe,qe).socketJoinAttempted=!0,a(this,Fe,qe).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return u(this,null,function*(){a(this,Fe,qe).socketJoinAttempted=!1,a(this,Ue).disconnect(),a(this,Fe,qe).socketJoinAttempted=!0,a(this,Fe,qe).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return a(this,Ue).readyState===1}catch(t){return!1}}sendMessage(t,e,i){const r={};return S.injectContext(r),a(this,Ue).send(t,i!=null?i:F(this,El,hp).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=(T,b)=>{a(this,Ue).removeListener(s,T),a(this,Ue).removeListener(_y,b),a(this,Ue).removeListener(ii.errorResponse,b),a(this,Ue).removeListener(gi.errorResponse,b)},h=r!=null?r:F(this,El,hp).call(this),p={};S.injectContext(p);const g=({id:T,payload:b})=>{if(h===T){let O;try{const R=PI.fromBinary(b);O=new Error(R.errorMessage)}catch(R){O=new Error("failed to parse error message",{cause:R});try{const x=RC.fromBinary(b);O=new Error(x.message)}catch(x){O=new Error("failed to parse error message",{cause:x})}}c(O),d(y,g)}},y=({id:T,payload:b})=>{h===T&&(o({id:T,payload:b}),d(y,g))};a(this,Ue).on(s,y),a(this,Ue).on(_y,g),a(this,Ue).on(ii.errorResponse,g),a(this,Ue).on(gi.errorResponse,g),setTimeout(()=>{d(y,g),c(new Error(`request timeout for callback eventId:${t}`))},e),a(this,Ue).send(t,h,i,new TextEncoder().encode(JSON.stringify(p)))})}on(t,e){a(this,Ue).on(t,e)}onStateEvent(t,e){a(this,Ue).on(t,e)}removeListener(t,e){a(this,Ue).removeListener(t,e)}removeListeners(t){a(this,Ue).removeListeners(t)}flush(){return a(this,Ue).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){l.info("SocketService::Connected to socket-edge"),a(this,Ri)&&(clearTimeout(a(this,Ri)),v(this,Ri,void 0)),a(this,Fe,qe).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var i;l.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:S.location.country});const{recv:r,send:n}=(i=a(this,Fe,qe).mediaState)!=null?i:{};r!=null&&r.state&&(r==null?void 0:r.state)!==ws.CONNECTED||n!=null&&n.state&&(n==null?void 0:n.state)!==ws.CONNECTED?a(this,ci).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Fe,qe).joinAttempted}):v(this,Ri,setTimeout(()=>{a(this,ci).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Fe,qe).joinAttempted}),v(this,Ri,void 0)},MO)),a(this,Fe,qe).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){l.info("SocketService::Reconnecting to socket-edge",{country:S.location.country}),a(this,Fe,qe).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){l.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),a(this,Fe,qe).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{l.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),a(this,Fe,qe).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){l.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Fe,qe).mediaJoinAttempted}}),a(this,Ri)&&(clearTimeout(a(this,Ri)),v(this,Ri,void 0)),a(this,ci).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Fe,qe).mediaJoinAttempted}),a(this,Fe,qe).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){l.info("SocketService::Failed to connect to socket-edge",{country:S.location.country}),a(this,ci).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_FAILED),a(this,Fe,qe).updateSocketConnectionState("failed")}))}},Un=new WeakMap,Ue=new WeakMap,Fe=new WeakSet,qe=function(){return a(this,ci).getValue("connectionHandler")},Ri=new WeakMap,ci=new WeakMap,Sl=new WeakSet,up=function(t){let e=Iy.getSocketEdgeDomain(a(this,ci).getValue("baseURI"));typeof Kn(a(this,ci),"socket_server_base")=="string"&&(e=Kn(a(this,ci),"socket_server_base"));const i=`wss://${e}`,r=new URL(`${i}/ws`),n=this.peerId,s=j(L({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},El=new WeakSet,hp=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},wy);let Uo=Iy;yl([S.trace("SocketService.connect")],Uo.prototype,"connect",1),yl([S.trace("SocketService.disconnect")],Uo.prototype,"disconnect",1),yl([S.trace("SocketService.sendMessagePromise")],Uo.prototype,"sendMessagePromise",1),yl([S.trace("SocketService.sendMessagePromiseWithTimeout")],Uo.prototype,"sendMessagePromiseWithTimeout",1);const Fn=class{static handleConnectedRoomsDumpRaw({payload:t}){var e;const i=iP.fromBinary(t),r=i.meetings.map(n=>{var s;return{id:n.id,title:n.title,participants:(s=n.participants)!=null?s:[]}});return{parentMeeting:{id:i.parentMeeting.id,title:i.parentMeeting.title,participants:(e=i.parentMeeting.participants)!=null?e:[]},meetings:r}}static handleTransferPeerRaw({payload:t}){const e=PP.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=uf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return lf.fromBinary(t).payloads.map(e=>({id:e.id,title:e.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return yP.fromBinary(t).payloads}static getConnectedRoomsDump(){return u(this,null,function*(){const t=yield Fn.socketService.sendMessagePromise(B.getConnectedRoomsDump);return Fn.handleConnectedRoomsDumpRaw(t)})}static createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield Fn.socketService.sendMessagePromise(B.createConnectedRooms,aP.toBinary({payloads:t}));return lf.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))})}static updateConnectedRooms(t){return u(this,null,function*(){})}static disableConnectedRooms(t){return u(this,null,function*(){const e=t.map(r=>({id:r})),i=yield Fn.socketService.sendMessagePromise(B.deleteConnectedRooms,fP.toBinary({payloads:e}));return Fn.handleConnectedRoomsDeletedRaw(i)})}static movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield Fn.socketService.sendMessagePromise(B.movePeers,_P.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}})}};let Le=Fn;m(Le,"socketService"),m(Le,"currentMeetingId");var AO=Object.defineProperty,DO=Object.getOwnPropertyDescriptor,Tl=(t,e,i,r)=>{for(var n=r>1?void 0:r?DO(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&&AO(e,i,n),n};const $s=class{constructor(t,e){m(this,"apiBase"),m(this,"selfController"),m(this,"pollController"),m(this,"chatController"),m(this,"metaController"),m(this,"storesManager"),m(this,"stageController"),m(this,"pluginController"),m(this,"internalsController"),m(this,"recordingController"),m(this,"livestreamController"),m(this,"participantController"),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}static init(t){return u(this,null,function*(){var e,i;const{peerId:r,apiBase:n,authToken:s,meetingId:o,organizationId:c,cachedUserDetails:d}=t.getAllValues();if(ry(t),Ie.isSupported()===!1)throw new w("Browser not supported","0010",!0);const h=BA(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 p=new k1(t);t.setValue("connectionHandler",p);const g=$s.createSocketService(t),y=g.connect(),T=h.getUserDetails(),b=h.getPlugins();let O=Ne.HIVE,R,x="";try{yield $s.setupFlagsmith(t)}catch(ne){l.error("Failed to setup flagsmith",{error:ne})}try{yield y}catch(ne){l.error("[Controller]: Failed to connect to socket server:",{error:ne})}try{({sfu:O,meetingTitle:x}=yield h.getRoomNodeData()),R=yield T,l.info(`SFU ${O} is being used.`),t.setValue("presetName",R.preset.name),t.setValue("roomNodeOptions",{sfu:O})}catch(ne){l.error("Failed to get room metadata",{error:ne})}const G=aD.init(R.preset,!t.getValue("modules").theme),$=CD.init(t,G.viewType,R.preset.permissions),I=$s.setupControllers(g,t,R,b,x,G,$);u1(G)&&((e=$s.createRoomNodeClient(t,g).initializeConnection(R.participant.name,o,!1,$))==null||e.catch(ne=>{l.error("[Controller]: Failed to queue partial media room promise:",{error:ne})})),S.location.country=(i=h.ipInfo)==null?void 0:i.country;const{controllers:se}=yield I;return cw(),new $s(n,se)})}static setupFlagsmith(t){return u(this,null,function*(){var e;const{peerId:i,baseURI:r,overrides:n,meetingId:s,organizationId:o}=t.getAllValues(),c=ow(s),d=j(L({entity:cu.PEER,clientId:o,isAnonUser:!o,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:c,roomName:s},Ie.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const h=(e=n==null?void 0:n.whitelabelled_flags_endpoint)==null||e?zn({servicePrefix:"flags",baseURI:r}):"edge.api.flagsmith.com";yield z.identify(`${cu.PEER}_${i}`,JSON.parse(JSON.stringify(d)),!1,5e3,h,l),l.info("flagsmith::allFlags",{flags:JSON.stringify(z.getAllFlags())},!0)}catch(h){l.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,i,r,n,s,o){return u(this,null,function*(){var c,d,h;const p=e.getValue("modules"),{participant:g}=i,y=e.getValue("defaults"),{sfu:T}=e.getValue("roomNodeOptions"),{viewType:b,mediaConstraints:{audio:O}}=s;e.setValue("viewType",b),e.setValue("defaults",L({mediaConfiguration:{audio:{enableHighBitrate:(c=O.enableHighBitrate)!=null?c:!1,enableStereo:(d=O.enableStereo)!=null?d:!1}}},y)),e.setValue("maxPreferredStreams",Ie.isMobile()?s.maxVideoStreams.mobile:s.maxVideoStreams.desktop);let R,x,G,$,I,se,ne,Se;const nt=new rO(t);Le.socketService=t;const ft=new cl(t),Bt=new ri(t),M=new dO(t),k=new ay(e,t),_=new lO(t),W=new iO(t),Re=new an(t),fe=yield Ur.init(e,k,g,o,s),U=yield Gf.init(e,fe.self,k,nt,n);if(p.participant&&(Se=new ir(e,fe.self,k,T)),(h=p.e2ee)!=null&&h.enabled&&p.e2ee.manager.init(l,e.getValue("peerSessionStore")),p.chat&&(x=yield Zi.init(e,Bt,Re,fe.self,Se.participants)),p.internals&&(I=yield ju.init()),p.livestream&&s.viewType===Rt.Livestream&&z.hasFeature(ie.LIVESTREAM)&&(ne=new dv(e,fe.self,W)),s.viewType!==Rt.Chat){if(p.poll&&(R=yield Ff.init(e,fe.self,ft)),p.recording&&(se=new Zf(e,fe.self,k)),p.stage&&(G=new $f(e,M,k,fe.self,Se.participants)),p.plugin){if(!Se)throw new w("The plugin module cannot be initialized without the `participant` module","0102");const Ge=yield r;$=yield Ca.init(e,Ge,_,Bt,x==null?void 0:x.chat,fe.self,Se.participants,n)}if(p.pip){const Ge=yield uw._init(e,fe.self);e.setValue("pip",Ge)}}const C={storesManager:new mD(e,_),pollController:R,selfController:fe,metaController:U,chatController:x,stageController:G,pluginController:$,recordingController:se,internalsController:I,livestreamController:ne,participantController:Se};return{theme:s,permissions:o,controllers:C}})}static createRoomNodeClient(t,e){const{peerId:i,roomNodeOptions:r}=t.getAllValues(),{sfu:n}=r;return iy(t,n,{socket:e,peerId:i})}static createSocketService(t){const{peerId:e,meetingId:i,authToken:r}=t.getAllValues(),n=["PING"];return new Uo(t,{peerId:e,meetingId:i,authToken:r,capabilities:n})}};let Fo=$s;Tl([S.trace("Controller.init")],Fo,"init",1),Tl([S.trace("setupFlagsmith")],Fo,"setupFlagsmith",1),Tl([S.trace("Controller.createRoomNodeClient")],Fo,"createRoomNodeClient",1),Tl([S.trace("Controller.createSocketService")],Fo,"createSocketService",1);var OO=Object.defineProperty,NO=Object.getOwnPropertyDescriptor,LO=(t,e,i,r)=>{for(var n=r>1?void 0:r?NO(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&&OO(e,i,n),n},kl,pp;class Cy extends Wt{constructor(e,i){super(),f(this,kl,void 0),m(this,"meetings",[]),m(this,"parentMeeting",null),f(this,pp,void 0),v(this,pp,e),v(this,kl,i.self)}get supportsConnectedMeetings(){return a(this,kl).id!==""}get isActive(){return this.meetings.length!==0}get currentMeetingId(){return Le.currentMeetingId}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 Le.getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield Le.createConnectedRooms(e)).map(i=>({id:i.id,title:i.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield Le.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 Le.disableConnectedRooms(e)})}moveParticipants(e,i,r){return u(this,null,function*(){this.validateConnectedMeetingsAction();const n=yield Le.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 Le.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 j(L({},s),{participants:o})}if(e===s.id){const o=s.participants.filter(c=>!r.includes(c.id));return j(L({},s),{participants:o})}return s})}}kl=new WeakMap,pp=new WeakMap,LO([At({maxInvocations:60,period:60})],Cy.prototype,"getConnectedMeetings",1);var VO=Object.defineProperty,xO=Object.getOwnPropertyDescriptor,mp=(t,e,i,r)=>{for(var n=r>1?void 0:r?xO(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&&VO(e,i,n),n},Bo,Mi,gp,fp;const qr=(gp=class{constructor(t,e,i){m(this,"connectedMeetings"),f(this,Bo,void 0),f(this,Mi,void 0),f(this,fp,void 0),v(this,fp,t),v(this,Bo,i),this.connectedMeetings=new Cy(t,e),this.setCurrentMeeting(e)}static init(t,e,i){return qr.instance||(qr.instance=new qr(t,e,i)),qr.instance.connectedMeetings.supportsConnectedMeetings&&(qr.instance.setupEvents(),e.self.once("roomJoined",()=>qr.instance.getConnectedMeetings())),qr.instance}setCurrentMeeting(t){v(this,Mi,t),Le.currentMeetingId=t.meta.meetingId}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){Le.socketService&&(Le.socketService.on(B.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),Le.socketService.on(B.transferPeer,this.handleTransferPeer.bind(this)),Le.socketService.on(B.movedPeer,this.handleMovedPeer.bind(this)),Le.socketService.on(B.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),Le.socketService.on(B.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this)))}handleTransferPeer(t){const e=Le.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.`);l.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",i);const c={video:a(this,Mi).self.videoEnabled,audio:a(this,Mi).self.audioEnabled};try{a(this,Mi).self.cleanupEvents(),yield a(this,Mi).leave("connected-meeting")}catch(h){l.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(r=a(this,Mi))==null?void 0:r.meta)==null?void 0:n.meetingId}`,{error:h})}Le.socketService=void 0,l.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${i}`);const d=yield Dy.init(j(L({},a(this,Bo)),{cachedUserDetails:null,defaults:j(L(L({},a(this,Bo).defaults),c),{mediaHandler:a(this,Mi).self}),authToken:e}));l.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(s=d==null?void 0:d.meta)==null?void 0:s.meetingId}`);try{const{hidden:h}=a(this,Mi).self;d.self.setName(a(this,Mi).self.name),yield d.join(),h&&d.self.hide()}catch(h){l.error("ConnectedMeetingsController.joinRoom",{error:h})}return l.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),this.setCurrentMeeting(d),d})}handleConnectedRoomsDump(t){const e=Le.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 Le.handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=Le.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,j(L({},r),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(i.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=Le.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})}},Bo=new WeakMap,Mi=new WeakMap,fp=new WeakMap,m(gp,"instance"),gp);let bl=qr;mp([S.trace("ConnectedMeetingsController.getConnectedMeetings")],bl.prototype,"getConnectedMeetings",1),mp([S.trace("ConnectedMeetingsController.setupEvents")],bl.prototype,"setupEvents",1),mp([S.trace("ConnectedMeetingsController.switchMeeting")],bl.prototype,"switchMeeting",1);class UO{constructor(){m(this,"battery"),m(this,"init",()=>u(this,null,function*(){try{"getBattery"in navigator&&(this.battery=yield navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){l.error("Error getting battery",e)}})),m(this,"updateChargeInfo",()=>{var e;l.log(`Battery charging? ${(e=this.battery)!=null&&e.charging?"Yes":"No"}`)}),m(this,"updateLevelInfo",()=>{if(!this.battery){l.log("Battery level: Not known");return}l.log(`Battery level: ${this.battery.level*100}%`)}),m(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 Py=new UO;function FO(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://api.${s}`;return{meetingId:i,orgId:r,participantId:n,baseURI:s,apiBase:o}}catch(i){throw l.error("constants::decodeAuthToken",{error:i,debuggingHint:`Unable to decode auth token: ${t}`},!0),new w("Invalid auth token","0004")}}var Bn,Js,Ks,_l,vp,Ry;class BO{constructor(){f(this,vp),f(this,Bn,new Audio),f(this,Js,new MediaStream),f(this,Ks,new Map),f(this,_l,void 0),a(this,Bn).srcObject=a(this,Js),a(this,Bn).autoplay=!0}playTracks(e){return u(this,null,function*(){return e.forEach(i=>{a(this,Ks).has(i.id)||(a(this,Js).addTrack(i),a(this,Ks).set(i.id,i))}),this.play()})}setSpeakerDevice(e){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,Bn).setSinkId(e)}removeTrack(e){const i=a(this,Ks).get(e);i&&(a(this,Js).removeTrack(i),a(this,Ks).delete(e))}play(){return u(this,null,function*(){return a(this,Bn).srcObject=a(this,Js),a(this,Bn).play().catch(e=>{F(this,vp,Ry).call(this,e)})})}onError(e){v(this,_l,e)}}Bn=new WeakMap,Js=new WeakMap,Ks=new WeakMap,_l=new WeakMap,vp=new WeakSet,Ry=function(t){var e;(e=a(this,_l))==null||e.call(this,t)};var zs;class WO extends BO{constructor(){super(),f(this,zs,void 0),v(this,zs,new Map)}addParticipantTrack(e,i){a(this,zs).set(e,i.id),this.playTracks([i])}removeParticipantTrack(e){const i=a(this,zs).get(e);i&&this.removeTrack(i),a(this,zs).delete(e)}}zs=new WeakMap;var jO=Object.defineProperty,HO=Object.getOwnPropertyDescriptor,wl=(t,e,i,r)=>{for(var n=r>1?void 0:r?HO(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&&jO(e,i,n),n},ct,Il,Wn,yp,My,Ay;let Gr=(Ay=class{constructor(t,e){f(this,yp),f(this,ct,void 0),f(this,Il,void 0),f(this,Wn,void 0),v(this,Wn,t),v(this,ct,e)}static init(t){return u(this,null,function*(){var e,i,r,n,s,o,c;nw(),Ie.init();const d=(i=(e=t==null?void 0:t.cachedUserDetails)==null?void 0:e.peerId)!=null?i:jn();Py.init();const{authToken:h,baseURI:p}=t,g=FO(h,p),{meetingId:y}=g,T=vc(g,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const b=Gr.setupContext(d,t,y,T);S.meetingMetadata.roomName=y,S.meetingMetadata.userId=T.participantId,S.meetingMetadata.organizationId=T.orgId,S.init(b,(n=(r=t.modules)==null?void 0:r.tracing)!=null?n:!0),l.info("DyteClient::init::options",{dyteClientInitOptions:j(L({},t),{authToken:`${(s=t.authToken)==null?void 0:s.slice(0,10)}...
22
- ${(o=t.authToken)==null?void 0:o.slice(-10)}`})});const O=yield Fo.init(b),R=new Gr(b,O);return F(c=R,yp,My).call(c,t),R})}static setupContext(t,e,i,r){var n,s;const o=en.createContext(t,e),c=L(L({},Q_),e==null?void 0:e.modules);return 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",X_({baseURI:r.baseURI})),o.setValue("defaults",e.defaults||{audio:!0,video:!0}),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",vi(e.cachedUserDetails)),o.setValue("sdkVersion","3.1.0-staging.4"),(s=e.modules)!=null&&s.experimental_audio_playback&&o.setValue("audioPlayback",new WO),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,ct);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){var e;Py.cleanup(),a(this,Wn).getValue("peerSessionStore").reset(),(e=a(this,Wn).getValue("roomSocketHandler"))==null||e.cleanup();const{selfController:i}=a(this,ct);return i.leaveRoom(t)})}get participants(){var t;return(t=a(this,ct).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,ct).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,ct).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,ct).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,ct).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,ct).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,ct).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Il))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,ct).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,ct).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,ct).stageController)==null?void 0:t.stage}get stores(){return a(this,ct).storesManager}get audio(){return a(this,Wn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,ct).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)})}},ct=new WeakMap,Il=new WeakMap,Wn=new WeakMap,yp=new WeakSet,My=function(t){v(this,Il,bl.init(a(this,Wn),this,t))},Ay);wl([ut("0002"),Pr.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Gr.prototype,"join",1),wl([ut("0003")],Gr.prototype,"leave",1),wl([ut("0001"),Pr.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Gr,"init",1),Gr=wl([ut("0000")],Gr);const Dy=Gr;return Dy}();
22
+ ${(o=t.authToken)==null?void 0:o.slice(-10)}`})});const O=yield Fo.init(b),R=new Gr(b,O);return F(c=R,yp,My).call(c,t),R})}static setupContext(t,e,i,r){var n,s;const o=en.createContext(t,e),c=L(L({},Q_),e==null?void 0:e.modules);return 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",X_({baseURI:r.baseURI})),o.setValue("defaults",e.defaults||{audio:!0,video:!0}),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",vi(e.cachedUserDetails)),o.setValue("sdkVersion","3.1.0-staging.5"),(s=e.modules)!=null&&s.experimentalAudioPlayback&&o.setValue("audioPlayback",new WO),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,ct);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){var e;Py.cleanup(),a(this,Wn).getValue("peerSessionStore").reset(),(e=a(this,Wn).getValue("roomSocketHandler"))==null||e.cleanup();const{selfController:i}=a(this,ct);return i.leaveRoom(t)})}get participants(){var t;return(t=a(this,ct).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,ct).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,ct).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,ct).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,ct).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,ct).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,ct).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Il))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,ct).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,ct).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,ct).stageController)==null?void 0:t.stage}get stores(){return a(this,ct).storesManager}get audio(){return a(this,Wn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,ct).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)})}},ct=new WeakMap,Il=new WeakMap,Wn=new WeakMap,yp=new WeakSet,My=function(t){v(this,Il,bl.init(a(this,Wn),this,t))},Ay);wl([ut("0002"),Pr.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Gr.prototype,"join",1),wl([ut("0003")],Gr.prototype,"leave",1),wl([ut("0001"),Pr.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Gr,"init",1),Gr=wl([ut("0000")],Gr);const Dy=Gr;return Dy}();
package/dist/index.cjs.js CHANGED
@@ -20,4 +20,4 @@ ${t}`}const Js={maxInvocations:5,period:1};function Ft(t,e){return function(i,n,
20
20
  maxEnergy: ${a(this,mr)}`),r===-1/0||i<1e-6?{energy:0,isVoice:!1}:((!a(this,Pn)||r<a(this,Pn))&&v(this,Pn,r),(!a(this,mr)||r>a(this,mr))&&v(this,mr,r),{energy:(r-a(this,Pn))/(a(this,mr)-a(this,Pn))*10||0,isVoice:n})},Sd=new WeakSet,Ih=function(t){return t<5},Ch=new WeakSet,uy=function(t=a(this,Ls)){var e;if(!a(this,Bi)||!t){Y.hasFeature(ie.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&l.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,Bi)}`);return}const i={producerId:a(this,Bi),energy:Math.round(t),silent:F(e=Qd,Sd,Ih).call(e,t)};v(this,xo,i.silent),this.reportRequest(i)},au=new WeakSet,bg=function(t){const e=Math.log10(t);return Math.round(e)},f(Ph,Sd),f(Ph,au);const tO=(t=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const i=new window.MediaStreamTrackGenerator({kind:"audio"}),n=i.writable.getWriter(),r=48e3,s=128,o=1;let c=0,d=null;const h=()=>u(void 0,null,function*(){try{const g=new Float32Array(s*o),y=new window.AudioData({format:"f32",sampleRate:r,numberOfFrames:s,numberOfChannels:o,timestamp:c,data:g});c+=s/r*1e6,yield n.ready,yield n.write(y)}catch{d&&clearInterval(d),n.releaseLock(),i.writable.abort()}});d=window.setInterval(h,100);const p=new MediaStream([i]).getAudioTracks()[0];return p.addEventListener("ended",()=>{d&&clearInterval(d),n.releaseLock(),i.writable.abort()}),Object.assign(p,{fakeTracks:"fakeTracks:fakeAudioTrack"}),p.enabled=t,p}catch{}const e=window.AudioContext||window.webkitAudioContext;if(e)try{const i=new e;if(!i||i.state!=="running"||!i.destination)return;const n=i.createOscillator();n.frequency.value=0,n.type="sine";const r=i.createGain();r.gain.value=0,n.connect(r);const s=i.createMediaStreamDestination();r.connect(s),n.start();const o=s.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=t,o):void 0}catch{return}},iO=(t=!1)=>{var e,i;const n=new MediaStream().getVideoTracks()[0],r=document.createElement("canvas");r.height=(e=n==null?void 0:n.getSettings().height)!=null?e:720,r.width=(i=n==null?void 0:n.getSettings().width)!=null?i:1280;const s=r.getContext("2d");s.fillStyle="black",s.fillRect(0,0,r.width,r.height),setInterval(()=>{s.fillStyle="black",s.fillRect(0,0,r.width,r.height)},1e3);const o=r.captureStream().getVideoTracks()[0];return Object.assign(o,{fakeTracks:"fakeTracks:fakeVideoTrack"}),o.enabled=t,o};var nO=Object.defineProperty,rO=Object.getOwnPropertyDescriptor,fe=(t,e,i,n)=>{for(var r=n>1?void 0:n?rO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&nO(e,i,r),r};const jt=["video/VP9","video/VP8"];var Mc,Ac,yt,z,Ja,Gi,At,is,ns,rs,Dc,pi,fn,Ka,ss,as,Dt,Ht,Xn,os,ou,_g,cu,wg,du,Ig,Oc,lu,uu,hu,Cg,pu,Pg,mu,Rg,gu,Mg,lt,St,cs,za,fu,Ag,vu,Dg,yu,Og;const hy=(hu=class{constructor(t,e,i){f(this,Xn),f(this,ou),f(this,cu),f(this,du),f(this,Oc),f(this,pu),f(this,mu),f(this,gu),f(this,lt),f(this,cs),f(this,fu),f(this,vu),f(this,yu),m(this,"context"),m(this,"authToken"),m(this,"e2ee"),f(this,Mc,void 0),f(this,Ac,void 0),f(this,yt,void 0),f(this,z,void 0),f(this,Ja,void 0),f(this,Gi,void 0),f(this,At,void 0),f(this,is,void 0),f(this,ns,void 0),f(this,rs,void 0),f(this,Dc,void 0),f(this,pi,null),f(this,fn,void 0),f(this,Ka,void 0),f(this,ss,void 0),f(this,as,void 0),f(this,Dt,void 0),f(this,Ht,void 0);var n,r;this.context=t;const{socket:s}=i;this.mediaJoined=!1,v(this,ss,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,as,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,Gi,e),v(this,yt,s),v(this,is,!1),v(this,z,new XD(t,s,e)),v(this,At,a(this,z).events),v(this,fn,new Set),v(this,Dt,new Map),v(this,ns,!1),v(this,rs,new eh),e===Le.CF&&!navigator.isReactNative&&v(this,Ht,new Ph(a(this,z).socketHandler.audioActivity.bind(a(this,z).socketHandler))),this.e2ee=(r=(n=t.getValue("modules").e2ee)==null?void 0:n.enabled)!=null?r:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),v(this,Dc,Zh(()=>u(this,null,function*(){if(!a(this,Xn,os).mediaJoinAttempted)return;const{roomJoined:o}=yield this.joinRoom(a(this,Ac),a(this,Mc),!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 mediaJoined(){return a(this,Xn,os).mediaJoined}set mediaJoined(t){a(this,Xn,os).mediaJoined=t}reset(){a(this,z).closeAllProducers(),a(this,z).closeAllConsumers(),a(this,Dt).clear(),a(this,fn).clear(),v(this,pi,null),a(this,rs).stop(),a(this,z).stopAllTransports(),a(this,z).reset(),v(this,rs,new eh)}joinRoom(t,e){return u(this,arguments,function*(i,n,r=!1,s=!1,o={}){a(this,Xn,os).mediaJoinAttempted=!0,v(this,is,!0),r&&this.reset();try{return yield a(this,rs).push(()=>F(this,ou,_g).call(this,i,n,s,o),"joinRoom")}catch(c){return l.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,n,r=!1,s={}){return a(this,pi)?a(this,pi):(v(this,pi,(()=>u(this,null,function*(){try{yield F(this,Oc,lu).call(this,i,n,r,s)}catch(o){throw v(this,pi,null),o}}))()),a(this,pi))})}getConsumers(){return a(this,z).consumers}leaveRoom(){return u(this,null,function*(){var t;a(this,z).stopAllTransports(),v(this,ns,!1),a(this,Xn,os).mediaJoinAttempted=!1;const e={closeRoom:!1};try{const i=yield a(this,yt).sendMessagePromise(a(this,At).leaveRoom,iI.toBinary(e));(t=qI.fromBinary(i.payload))!=null&&t.closed||l.warn("weird state on peer closed and should not happen")}catch(i){l.error("error on sending leave room request",{error:i})}J.callEnded(),S.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,z).createConsumers(t)})}closeConsumers(t){return u(this,null,function*(){if(!t.length)return;const e=t.reduce((i,n)=>{const r=a(this,z).producerIdToConsumerIdMap.get(n.producerId);return r?(i.push(r),i):(l.warn(`consumer not found in close consumers: ${n.producerId}`),i)},[]);yield a(this,z).closeConsumers(e)})}_shareWebcam(t,e){return u(this,null,function*(){const i=e==="video/VP9"?ke.WEBCAM:ke.WEBCAM_BACKUP,n=F(this,lt,St).call(this,i);if(n){const p=yield n;if(a(this,z).producers.has(p)){const g=a(this,z).producers.get(p);if(!g.closed)return yield g.replaceTrack({track:t}),yield this.resumeWebcam(i),t;yield this.disableWebcam(e)}return this._shareWebcam(t,e)}const r=[e].concat(jt.filter(p=>p!==e)),s=F(this,yu,Og).call(this,t,r),o=Ws(this.context,"disableSimulcast"),c=a(this,Gi)===Le.CF?ie.ENABLE_CF_SIMULCAST:ie.ENABLE_HIVE_SIMULCAST;!o&&Y.hasFeature(c)?(l.info(`Simulcast enabled for SFU: ${a(this,Gi)}`),s.encodings=W1(t)):l.info(`Simulcast disabled for webcam producer, SFU: ${a(this,Gi)}`),Y.hasFeature(ie.TRACK_HINT)&&(s.track.contentHint=Y.getValue(ie.TRACK_HINT));const d=()=>{l.info("Disabling video due to the producer closure"),a(this,Dt).delete(i)},h=a(this,z).createProducer(s,d);return F(this,cs,za).call(this,i,h.then(p=>p.id)),h.then(p=>p.track)})}shareWebcam(t){return u(this,null,function*(){var e;if(t===void 0)return null;const i=(e=Y.getValue(ie.FORCE_VIDEO_CODEC))==null?void 0:e.toString();if(i)return l.debug(`Calling _shareWebcam with forced video codec: ${i}`),this._shareWebcam(t,i);const n=jt.filter(r=>{var s,o;return((o=(s=a(this,Ja).sender)==null?void 0:s.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===r))>=0&&a(this,as).get(r).size>0});return n.length===0&&n.push(jt[0]),yield Promise.all(n.map(r=>(l.debug(`Calling _shareWebcam with video codec: ${r}`),this._shareWebcam(t,r)))),t})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:i}=t;if(e===void 0)return;const n={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Re.isElectron()},stopTracks:!1},r=()=>{l.info("Disabling screenShare due to the producer closure"),a(this,Dt).delete(ke.SCREENSHARE_VIDEO),a(this,Dt).delete(ke.SCREENSHARE_AUDIO)},s=a(this,z).createProducer(n,r);F(this,cs,za).call(this,ke.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:Re.isElectron()},stopTracks:!1,zeroRtpOnPause:a(this,Gi)!==Le.CF},d=()=>{};o=a(this,z).createProducer(c,d),F(this,cs,za).call(this,ke.SCREENSHARE_AUDIO,o.then(h=>h.id))}yield Promise.all([s,o||Promise.resolve()]),J.screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new xt("track undefined");const e=F(this,lt,St).call(this,ke.MIC);if(e){const s=yield e;if(a(this,z).producers.has(s)){const o=a(this,z).producers.get(s);if(!o.closed){yield o.replaceTrack({track:t}),yield this.resumeMic(),a(this,Ht)&&(a(this,Ht).audioTrack=t,a(this,Ht).producerId=s,a(this,Ht).start());return}yield a(this,z).closeProducer(s,{stopTrack:!1})}yield this.shareMic(t);return}const i=F(this,vu,Dg).call(this,t),n=()=>{a(this,Dt).delete(ke.MIC)},r=a(this,z).createProducer(i,n);F(this,cs,za).call(this,ke.MIC,r.then(s=>s.id)),yield r.then(s=>{a(this,Ht)&&(a(this,Ht).audioTrack=s.track,a(this,Ht).producerId=s.id,a(this,Ht).start())})}catch(e){throw new w(e)}})}pauseMic(){return u(this,null,function*(){var t;const e=yield F(this,lt,St).call(this,ke.MIC),i=a(this,z).producers.get(e);if(!i){l.error("pauseMic::could_not_find_mic_producer");return}if(i.paused){l.info("pauseMic::mic_producer_already_paused");return}i.pause(),(t=a(this,Ht))==null||t.stop();const n={producerId:i.id,pause:!0};a(this,yt).sendMessage(a(this,At).toggleProducer,lc.toBinary(n))})}pauseWebcam(){return u(this,null,function*(){const t=yield F(this,lt,St).call(this,ke.WEBCAM),e=yield F(this,lt,St).call(this,ke.WEBCAM_BACKUP),i=a(this,z).producers.get(t),n=a(this,z).producers.get(e);if(!i&&!n){l.error("pauseWebcam::could_not_find_webcam_producer");return}const r=s=>{const o={producerId:s.id,pause:!0};a(this,yt).sendMessage(a(this,At).toggleProducer,lc.toBinary(o))};i&&(i.pause(),r(i)),n&&(n.pause(),r(n))})}resumeMic(){return u(this,null,function*(){const t=yield F(this,lt,St).call(this,ke.MIC),e=a(this,z).producers.get(t);if(!e){l.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){l.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,yt).sendMessage(a(this,At).toggleProducer,lc.toBinary(i))})}resumeWebcam(){return u(this,arguments,function*(t=ke.WEBCAM){const e=yield F(this,lt,St).call(this,t),i=a(this,z).producers.get(e);if(!i){l.error("resumeWebcam::could_not_find_webcam_producer");return}if(!i.paused){l.info("resumeWebcam::webcam_producer_already_resumed");return}i.resume(),i.appData.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,i);const n={producerId:i.id,pause:!1};a(this,yt).sendMessage(a(this,At).toggleProducer,lc.toBinary(n))})}disableWebcam(t){return u(this,null,function*(){const e=t==="video/VP9"?ke.WEBCAM:ke.WEBCAM_BACKUP,i=yield F(this,lt,St).call(this,e);F(this,fu,Ag).call(this,e),i&&(yield a(this,z).closeProducer(i))})}disableMic(){return u(this,null,function*(){var t;const e=yield F(this,lt,St).call(this,ke.MIC);e&&(yield a(this,z).closeProducer(e)),(t=a(this,Ht))==null||t.stop(),a(this,Dt).delete(ke.MIC)})}disableScreenShare(){return u(this,null,function*(){l.info("screen_sharing_stopped"),J.screenShareStop();const t=yield F(this,lt,St).call(this,ke.SCREENSHARE_VIDEO),e=yield F(this,lt,St).call(this,ke.SCREENSHARE_AUDIO);t&&(yield a(this,z).closeProducer(t)),e&&(yield a(this,z).closeProducer(e)),a(this,fn).clear(),a(this,Dt).delete(ke.SCREENSHARE_VIDEO),a(this,Dt).delete(ke.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 F(this,lt,St).call(this,ke.WEBCAM),n=yield F(this,lt,St).call(this,ke.WEBCAM_BACKUP);yield a(this,z).closeProducer(i,{stopTrack:!1}),yield a(this,z).closeProducer(n,{stopTrack:!1}),this.shareWebcam(t)}if(e){const i=yield F(this,lt,St).call(this,ke.SCREENSHARE_VIDEO);yield a(this,z).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,z).socketHandler.changeDisplayName(i)))throw new Error("failed to change display name!")})}kick(t){const e={peerIds:[t]};a(this,z).socketHandler.kickPeer(e)}kickAll(){a(this,z).socketHandler.kickAll()}muteAll(t){return u(this,null,function*(){if(!(yield a(this,z).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield a(this,z).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield a(this,z).socketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield a(this,z).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,yt).sendMessagePromise(a(this,At).globalPinPeer,fI.toBinary(e))}catch(i){l.error("Error in pinning peer:",{error:i})}})}validateScreenShare(t){return this.peerId===t.peerId&&a(this,z).producers.get(t.producerId)&&a(this,fn).add(t.consumerPeerId),a(this,fn).size}switchConsumersToLayer(t,e){return u(this,null,function*(){const i=t.map(n=>this.getConsumers().get(n));a(this,z).switchConsumersToLayer(i,e)})}handleSocketEvents(){return u(this,null,function*(){a(this,yt).on(a(this,At).peerProducerCreateBroadcast,({payload:t})=>{var e,i;if(this.mediaJoined)try{const{participantId:n,producerState:r}=EC.fromBinary(t);if(n===this.peerId)return;if(r!=null&&r.mimeType||(r.mimeType=r.kind===Wi.AUDIO?"audio/opus":"video/VP8"),r.kind===Wi.VIDEO&&!r.screenShare&&((i=(e=a(this,Ja).receiver)==null?void 0:e.video)==null?void 0:i.codecs.findIndex(s=>s.mimeType===jt[0]))>=0&&a(this,ss).get(jt[0]).has(n)&&r.mimeType!==jt[0]){l.warn(`Ignoring producer: ${r.producerId}`);return}l.info(`producer created broadcast: ${n}, producer state: ${r}`),this.context.getValue("peerSessionStore").emit(P.NEW_PRODUCER,{peerId:n,producer:G(L({},r),{kind:r.kind===Wi.AUDIO?"audio":"video",producingPeerId:n})})}catch(n){l.error("error in peer-producer-create-broadcast",{error:n})}}),a(this,yt).on(a(this,At).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:i,producerState:{kind:n,pause:r,producerId:s}}=bm.fromBinary(t),o=n===Wi.AUDIO?"audio":"video";if(l.info(`producer toggle broadcast: ${e}, producerId: ${s}, kind:${o}, paused:${r} payload: ${JSON.stringify(bm.fromBinary(t))}`),e===this.peerId&&i!==this.peerId&&r&&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:r,kind:o}),Array.from(this.getConsumers().values()).filter(c=>c.producerId===s).forEach(c=>{c.paused!==r&&(l.debug(`consumer state mismatched for ${c.id}. updating consumer pause state ${c.paused} to ${r}`),r?(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){l.error("error in producer toggle broadcast handler",{error:e})}}),a(this,yt).on(a(this,At).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=xu.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),a(this,fn).delete(e),a(this,z).consumers.forEach(i=>{i.peerId===e&&i.close()}),this.context.getValue("peerSessionStore").emit(P.PEER_CLOSED,{id:e})}catch(e){l.error("error in peer left broadcast",{error:e})}}),a(this,yt).on(a(this,At).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:i}}=bC.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(P.PRODUCER_CLOSED,{peerId:e,producerId:i});const n=a(this,z).producerIdToConsumerIdMap.get(i);if(!n){l.warn(`no consumer found for producer:${i}`);return}l.info(`closing consumer ${n}, producer id: ${i}`),a(this,z).closeConsumer(n).then(()=>{l.info(`closed consumer: ${n}`),a(this,z).producerIdToConsumerIdMap.delete(i),this.context.getValue("peerSessionStore").emit(P.CONSUMER_CLOSED,{id:n})}).catch(r=>{l.error("error closing consumer",{error:r})})}catch(e){l.error("error on producer close broadcast",{error:e})}}),a(this,yt).on(a(this,At).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,is)&&!a(this,ns)||(l.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_DISCONNECTED),a(this,Dc).call(this))})})}handleCallstatsEvents(){J.onConsumerScore(t=>{t.forEach((e,i)=>{const n=a(this,z).consumers.get(i);n&&this.context.getValue("peerSessionStore").emit(P.CONSUMER_SCORE_UPDATE,{id:i,kind:n.kind,peerId:n.peerId,score:e.score,scoreStats:e})})}),J.onProducerScore(t=>{t.forEach((e,i)=>{const n=Array.from(a(this,z).producers.values()).find(r=>r.id===i);n&&this.context.getValue("peerSessionStore").emit(P.PRODUCER_SCORE_UPDATE,{id:i,kind:n.kind,appData:n.appData,score:e.score,scoreStats:e})})})}handlePeerCapabilities(t,e){var i,n,r,s;for(let o=0;o<=jt.length;o+=1){const c=jt[o];if(((n=(i=e==null?void 0:e.receiver)==null?void 0:i.video)==null?void 0:n.codecs.findIndex(d=>d.mimeType===c))>=0||o===jt.length-1){a(this,as).get(c).add(t);break}}for(let o=0;o<=jt.length;o+=1){const c=jt[o];if(((s=(r=e==null?void 0:e.sender)==null?void 0:r.video)==null?void 0:s.codecs.findIndex(d=>d.mimeType===c))>=0||o===jt.length-1){a(this,ss).get(c).add(t);break}}}handlePeerLeaving(t){Y.hasFeature(ie.FORCE_VIDEO_CODEC)||(a(this,ss).forEach(e=>e.delete(t)),a(this,as).forEach((e,i)=>{e.delete(t),!(e.size!==0||i===jt[0])&&this.disableWebcam(i)}))}},Mc=new WeakMap,Ac=new WeakMap,yt=new WeakMap,z=new WeakMap,Ja=new WeakMap,Gi=new WeakMap,At=new WeakMap,is=new WeakMap,ns=new WeakMap,rs=new WeakMap,Dc=new WeakMap,pi=new WeakMap,fn=new WeakMap,Ka=new WeakMap,ss=new WeakMap,as=new WeakMap,Dt=new WeakMap,Ht=new WeakMap,Xn=new WeakSet,os=function(){return this.context.getValue("connectionHandler")},ou=new WeakSet,_g=function(t,e,i,n){return u(this,null,function*(){v(this,Ac,t);try{return a(this,pi)?yield a(this,pi):yield F(this,Oc,lu).call(this,t,e,i,n),F(this,du,Ig).call(this,e),{roomJoined:yield F(this,cu,wg).call(this)}}catch(r){return l.error("Failed to complete room join",{error:r}),{roomJoined:!1}}finally{v(this,pi,null)}})},cu=new WeakSet,wg=function(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:t}=yield a(this,z).socketHandler.notifySelfJoinComplete();return v(this,Mc,t.roomUuid),v(this,ns,!0),v(this,is,!1),!0}catch(t){return l.error("Error completing room join",{error:t}),this.mediaJoined=!1,!1}})},du=new WeakSet,Ig=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:G(L({},Re.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};J.roomJoined(e)}catch(e){l.error("Error reporting room joined analytics",{error:e})}},0)},Oc=new WeakSet,lu=function(t,e,i,n){return u(this,null,function*(){var r,s;try{(s=a(this,Ka))!=null||v(this,Ka,F(r=hy,uu,Cg).call(r));const o=F(this,pu,Pg).call(this);yield F(this,mu,Rg).call(this,t,e,i,o),yield a(this,z).setupTransports({send:!0,recv:!0}),yield F(this,gu,Mg).call(this,n)}catch(o){throw l.error("Failed to initialize connection",{error:o}),o}})},uu=new WeakSet,Cg=function(){const{ipInfo:t}=ht();if(!(t!=null&&t.loc))return;const[e,i]=t.loc.split(",").map(parseFloat);return{latitude:e,longitude:i}},pu=new WeakSet,Pg=function(){var t;const e=(t=Y.getValue(ie.FORCE_VIDEO_CODEC))==null?void 0:t.toString(),i=FD(e);return v(this,Ja,i),i},mu=new WeakSet,Rg=function(t,e,i,n){return u(this,null,function*(){yield Qv((r,s)=>u(this,null,function*(){if(!a(this,yt).isConnected){s(new Error("Socket is not connected"));return}r>0&&l.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${r}`});try{yield a(this,z).socketHandler.joinRoom(e,t,n,i,a(this,Ka))}catch(o){throw l.error("Failed to send joinRoom message after retries",{error:o}),o}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:Y.hasFeature(ie.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3})})},gu=new WeakSet,Mg=function(t){return u(this,null,function*(){if(!(a(this,Gi)===Le.HIVE||!Y.hasFeature(ie.PRECREATE_PRODUCERS)||!t))try{const e=[];if(t.canProduceVideo===q.Allowed&&e.push(this.shareWebcam(iO(!0))),t.canProduceAudio===q.Allowed){const i=tO(!0);i&&e.push(this.shareMic(i))}e.length>0&&(yield Promise.all(e))}catch(e){l.warn("Failed to precreate producers",{error:e})}})},lt=new WeakSet,St=function(t){return a(this,Dt).get(t)},cs=new WeakSet,za=function(t,e){return a(this,Dt).set(t,e)},fu=new WeakSet,Ag=function(t){return a(this,Dt).delete(t)},vu=new WeakSet,Dg=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:a(this,Gi)!==Le.CF}},yu=new WeakSet,Og=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}},f(hu,uu),hu);let he=hy;fe([S.trace("MediaNodeClient.reset",{country:S.location.country})],he.prototype,"reset",1);fe([S.trace("MediaNodeClient.joinRoom")],he.prototype,"joinRoom",1);fe([S.trace("MediaNodeClient.leaveRoom")],he.prototype,"leaveRoom",1);fe([S.trace("MediaNodeClient.activatePeers")],he.prototype,"activatePeers",1);fe([S.trace("MediaNodeClient.createConsumers")],he.prototype,"createConsumers",1);fe([S.trace("MediaNodeClient.closeConsumers")],he.prototype,"closeConsumers",1);fe([S.trace("MediaNodeClient._shareWebcam")],he.prototype,"_shareWebcam",1);fe([S.trace("MediaNodeClient.shareWebcam")],he.prototype,"shareWebcam",1);fe([S.trace("MediaNodeClient.shareScreen")],he.prototype,"shareScreen",1);fe([S.trace("MediaNodeClient.shareMic")],he.prototype,"shareMic",1);fe([S.trace("MediaNodeClient.pauseMic")],he.prototype,"pauseMic",1);fe([S.trace("MediaNodeClient.pauseWebcam")],he.prototype,"pauseWebcam",1);fe([S.trace("MediaNodeClient.resumeMic")],he.prototype,"resumeMic",1);fe([S.trace("MediaNodeClient.resumeWebcam")],he.prototype,"resumeWebcam",1);fe([S.trace("MediaNodeClient.disableWebcam")],he.prototype,"disableWebcam",1);fe([S.trace("HiveClient.disableMic")],he.prototype,"disableMic",1);fe([S.trace("HiveClient.disableScreenShare")],he.prototype,"disableScreenShare",1);fe([S.trace("MediaNodeClient.muteSelf")],he.prototype,"muteSelf",1);fe([S.trace("MediaNodeClient.resetVideoProducers")],he.prototype,"resetVideoProducers",1);fe([S.trace("MediaNodeClient.changeDisplayName")],he.prototype,"changeDisplayName",1);fe([S.trace("MediaNodeClient.kickPeer")],he.prototype,"kick",1);fe([S.trace("MediaNodeClient.kickAllPeers")],he.prototype,"kickAll",1);fe([S.trace("MediaNodeClient.muteAll")],he.prototype,"muteAll",1);fe([S.trace("MediaNodeClient.muteAllVideo")],he.prototype,"muteAllVideo",1);fe([S.trace("MediaNodeClient.disableAudio")],he.prototype,"disableAudio",1);fe([S.trace("MediaNodeClient.disableVideo")],he.prototype,"disableVideo",1);fe([S.trace("MediaNodeClient.pinPeer")],he.prototype,"pinPeer",1);fe([S.trace("MediaNodeClient.validateScreenShare")],he.prototype,"validateScreenShare",1);function py(t,e,i){const n=t.getValue("roomNodeClient");if(n){if(n)return n;throw new Error("Room node client already set up.")}const r=new he(t,e,i);return t.setValue("roomNodeClient",r),r}function my(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch{l.error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var sO=Object.defineProperty,aO=Object.getOwnPropertyDescriptor,Wr=(t,e,i,n)=>{for(var r=n>1?void 0:n?aO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&sO(e,i,r),r},Zn,Oi,de,Ot,qt,Ng;const gy=(Ng=class{constructor(t,e,i,n){f(this,Ot),m(this,"self"),m(this,"authToken"),f(this,Zn,void 0),m(this,"viewType"),f(this,Oi,void 0),f(this,de,void 0);const{socket:r}=i,s=t.getValue("authToken");this.self=e,v(this,de,t),this.viewType=n,this.authToken=s,v(this,Zn,r),v(this,Oi,i),e.config.viewType!==Ut.Chat&&this.setupEvents()}get peerId(){return a(this,de).getValue("peerId")}get mediaJoined(){return a(this,de).getValue("connectionHandler").mediaJoined}static init(t,e,i,n,r){return u(this,null,function*(){const s=ht(),o=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield rt.__init__(t,i,n,r,r.name,c);if(navigator.product!=="ReactNative"){const h=!Y.hasFeature(ie.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const p=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(p)}),J.devices("AUDIO",p==null?void 0:p.filter(g=>g.kind==="audioinput")),J.devices("VIDEO",p==null?void 0:p.filter(g=>g.kind==="videoinput")),J.devices("SPEAKER",p==null?void 0:p.filter(g=>g.kind==="audiooutput")),l.info("Callstats:: initializing");try{yield J.initialize({peerId:o,engineName:Re.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:Y.getAllFlags(),logger:l,apiHostnames:pv(t),skipConnectivityChecks:h}),l.info("Callstats:: initialized")}catch(g){l.error("Callstats:: initialization failed",{error:g})}}),0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new gy(t,d,e,r.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:i,permissions:n,audioEnabled:r,videoEnabled:s,screenShareEnabled:o,screenShareTracks:c}=this.self;if(n.canProduceAudio===q.Allowed&&r)try{yield a(this,Ot,qt).shareMic(e),this.self.audioEnabled||a(this,Ot,qt).pauseMic()}catch{this.self.disableAudio()}if(n.canProduceVideo===q.Allowed&&s)try{const d=yield a(this,Ot,qt).shareWebcam(i);d&&d.id!==i.id&&Y.hasFeature(ie.EXP_RESHARE)&&(yield a(this,Ot,qt).shareWebcam(d)),this.self.videoEnabled||a(this,Ot,qt).pauseWebcam()}catch{this.self.disableVideo()}if(n.canProduceScreenshare===q.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(){l.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(l.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){l.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(l.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){l.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(t){return u(this,null,function*(){J.callEnded(),a(this,Ot,qt).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){a(this,de).getValue("peerSessionStore").on(P.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),a(this,de).getValue("peerSessionStore").on(P.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,de).getValue("peerSessionStore").on(P.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,de).getValue("peerSessionStore").on(P.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,de).getValue("peerSessionStore").on(P.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),a(this,de).getValue("peerSessionStore").on(P.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&Y.hasFeature(ie.REFRESH_ID_ON_DISCONNECTION)&&(e=qs()),a(this,Zn).updateURL(e),S.resetPeerId(e),ht().setHeader("dyte-tracing-id",e),Pr.remapContext(e,a(this,de)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,de).getValue("peerSessionStore").on(P.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Oi).on(B.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Oi).on(Hc.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&a(this,de).getValue("peerSessionStore").emit(P.UPDATE_PERMISSIONS,e.patch)})}),a(this,Oi).on(B.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Oi).on(B.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Oi).on(B.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,de).getValue("peerSessionStore").onAsync(P.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,de).getValue("peerSessionStore").on(P.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:i,scoreStats:n})=>{var r;const s=(r=i==null?void 0:i.screenShare)!=null?r:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:s,score:t,participantId:this.self.id,scoreStats:n})}),a(this,de).getValue("peerSessionStore").on(P.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),J.audioOff())})),a(this,de).getValue("peerSessionStore").on(P.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),J.videoOff())})),a(this,de).getValue("peerSessionStore").onAsync(P.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,de).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,Oi).joinRoom(this.self);a(this,Oi).socket.flush();const i=sp(e.stageType);if(a(this,de).setValue("stageStatus",i,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),a(this,de).notify("stageStatus")}catch(e){throw l.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,Zn))==null||e.disconnect()}catch{l.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),a(this,de).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),a(this,de).notify("stageStatus");try{(i=a(this,Zn))==null||i.disconnect()}catch{l.error("SelfController::leaveRoom::socketDisconnect")}my(a(this,de)),yield a(this,de).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:n,viewType:r,meetingId:s,stageStatus:o,roomNodeOptions:c}=a(this,de).getAllValues(),{sfu:d}=c;try{if(r===Ut.Livestream){if(o!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}py(a(this,de),d,{socket:a(this,Zn),peerId:n})}const{canProduceAudio:h,canProduceVideo:p,canProduceScreenshare:g}=this.self.permissions,{roomJoined:y}=(i=yield(e=a(this,Ot,qt))==null?void 0:e.joinRoom(this.self.name,s,t,t,{canProduceAudio:h,canProduceVideo:p,canProduceScreenshare:g}))!=null?i:{};if(!y)return;o==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(h){throw l.error("Error:SelfController.mediaRoomJoin",{error:h}),new w("Error: could not join media room","0002")}})}leaveMediaRoom(t){return u(this,null,function*(){const e=a(this,de).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()})}},Zn=new WeakMap,Oi=new WeakMap,de=new WeakMap,Ot=new WeakSet,qt=function(){return a(this,de).getValue("roomNodeClient")},Ng);let $n=gy;Wr([S.trace("SelfController.resetSelf")],$n.prototype,"resetSelf",1);Wr([S.trace("SelfController.setupEvents")],$n.prototype,"setupEvents",1);Wr([S.trace("SelfController.joinRoom")],$n.prototype,"joinRoom",1);Wr([S.trace("SelfController.leaveRoom")],$n.prototype,"leaveRoom",1);Wr([S.trace("SelfController.joinMediaRoom")],$n.prototype,"joinMediaRoom",1);Wr([S.trace("SelfController.leaveMediaRoom")],$n.prototype,"leaveMediaRoom",1);Wr([S.trace("SelfController.init")],$n,"init",1);var Ed;class oO{constructor(e){f(this,Ed,void 0),v(this,Ed,e)}on(e,i){let n;e===B.roomPeerCount?n=Im.fromBinary.bind(Im):n=xm.fromBinary.bind(xm),a(this,Ed).on(e,({payload:r})=>{const s=n(r);return i(s)})}}Ed=new WeakMap;var Td;class cO{constructor(e){f(this,Td,void 0),v(this,Td,e)}on(e,i){let n,r;switch(e){case B.transcript:{n=Vl.fromBinary.bind(Vl),r=Vl.create();break}default:{l.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Td).on(e,({payload:s})=>{let o=r;try{o=n(s)}catch(c){l.error("chatSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}}Td=new WeakMap;var dO=Object.defineProperty,lO=Object.getOwnPropertyDescriptor,vp=(t,e,i,n)=>{for(var r=n>1?void 0:n?lO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&dO(e,i,r),r},Rn;class Tl{constructor(e){f(this,Rn,void 0),v(this,Rn,e)}getPolls(){return a(this,Rn).sendMessagePromise(Yi.getPolls)}createPoll(e,i,n=!1,r=!1){const s={anonymous:n,hideVotes:r,question:e,options:i};return a(this,Rn).sendMessage(Yi.createPoll,uA.toBinary(s))}votePoll(e,i){const n={index:i,pollId:e};return a(this,Rn).sendMessage(Yi.votePoll,pA.toBinary(n))}on(e,i){let n,r;switch(e){case Yi.updatePoll:case Yi.createPoll:case Yi.votePoll:{n=jl.fromBinary.bind(jl),r=jl.create();break}}a(this,Rn).on(e,({payload:s})=>{let o=r;try{o=n(s)}catch(c){l.error("pollSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}removeListeners(e){a(this,Rn).removeListeners(e)}}Rn=new WeakMap;vp([S.trace("PollSocketHandler.getPolls")],Tl.prototype,"getPolls",1);vp([S.trace("PollSocketHandler.createPoll")],Tl.prototype,"createPoll",1);vp([S.trace("PollSocketHandler.votePoll")],Tl.prototype,"votePoll",1);var uO=Object.defineProperty,hO=Object.getOwnPropertyDescriptor,pO=(t,e,i,n)=>{for(var r=n>1?void 0:n?hO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&uO(e,i,r),r},Vi;class fy{constructor(e,i){m(this,"socket"),f(this,Vi,void 0),v(this,Vi,e),this.socket=i,this.handleSocketEvents(),a(this,Vi).setValue("roomSocketHandler",this)}cleanup(){return u(this,null,function*(){var e;try{(e=this.socket)==null||e.disconnect()}catch{l.error("roomSocketHandler::cleanup")}})}joinRoom(e){return u(this,null,function*(){var i;this.socket.joinAttempted=!0;const n={capabilities:[],peer:{displayName:(i=e.name)!=null?i:"Participant",customParticipantId:e.customParticipantId,peerId:e.id,userId:e.userId,displayPictureUrl:e.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(B.joinRoom,XC.toBinary(n));try{const{peer:s}=ls.fromBinary((yield r).payload);a(this,Vi).getValue("connectionHandler").socketJoined=!0,a(this,Vi).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_ROOM_JOINED,{peer:s});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:h}]=yield Promise.all([o,c]);return a(this,Vi).getValue("peerSessionStore").emit(P.ROOM_STATE,d),a(this,Vi).getValue("peerSessionStore").emit(P.SOCKET_PEERS,h),{peer:s}}catch(s){throw l.error("RoomSocketHandler.joinRoom.failed",{error:s}),new w("Error: RoomSocketHandler.joinRoom failed.","0002",s)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return VP.fromBinary((yield this.socket.sendMessagePromise(B.getAllAddedParticipants)).payload).participants.map(e=>{var i=e,{id:n}=i,r=al(i,["id"]);return G(L({},r),{userId:n})})}catch{return[]}})}getRoomPeers(e,i,n){return u(this,null,function*(){let r;try{const s={seachQuery:e,limit:i,offset:n},o=yield this.socket.sendMessagePromise(B.getRoomPeersInfo,jC.toBinary(s));r=xl.fromBinary(o.payload)}catch(s){l.error("getRoomPeers::binary_decode_error",{error:s})}return r})}getRoomPeersNonPaginated(){return u(this,null,function*(){let e;try{const i=yield this.socket.sendMessagePromise(B.getRoomPeersInfo);e=xl.fromBinary(i.payload)}catch(i){l.error("getRoomJoinedPeers::binary_decode_error",{error:i})}return e})}getStagePeers(){return u(this,null,function*(){let e;try{const i=yield this.socket.sendMessagePromise(B.getRoomPeersInfo);e=xl.fromBinary(i.payload)}catch(i){l.error("getRoomJoinedPeers::binary_decode_error",{error:i})}return e})}getPeerInfo(e){return u(this,null,function*(){let i;try{const n=yield this.socket.sendMessagePromise(B.getPeerInfo,_v.toBinary({peerId:e}));i=ls.fromBinary(n.payload)}catch(n){l.error("getPeerInfo::binary_decode_error",{error:n})}return i})}getRoomState(){return u(this,null,function*(){let e=Cm.create();try{const i=yield this.socket.sendMessagePromise(B.getRoomInfo);e=Cm.fromBinary(i.payload)}catch(i){l.error("getRoomState::binary_decode_error",{error:i})}return e})}getRoomStageState(){return u(this,null,function*(){let e=Am.create();try{const i=yield this.socket.sendMessagePromise(B.getRoomStageState);e=Am.fromBinary(i.payload)}catch(i){l.error("getRoomStageState::binary_decode_error",{error:i})}return e})}broadcastMessage(e,i){return u(this,null,function*(){const n={type:e,payload:new TextEncoder().encode(JSON.stringify(i)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(B.broadcastMessage,ga.toBinary(n))})}broadcastToMeetings(e,i,n){return u(this,null,function*(){const r={type:e,payload:new TextEncoder().encode(JSON.stringify(n)),timestamp:Date.now(),ids:i,broadcastType:1};return this.socket.sendMessagePromise(B.broadcastToEntity,ga.toBinary(r))})}broadcastToPeers(e,i,n){return u(this,null,function*(){const r={type:e,payload:new TextEncoder().encode(JSON.stringify(n)),timestamp:Date.now(),ids:i,broadcastType:0};return this.socket.sendMessage(B.broadcastToEntity,ga.toBinary(r))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(B.leaveRoom,eP.toBinary({}))})}kick(e){return u(this,null,function*(){const i={peerIds:[e]};this.socket.sendMessage(B.kick,Iv.toBinary(i))})}kickAll(e=!1){return u(this,null,function*(){const i={propagateKickAcrossRooms:e};this.socket.sendMessage(B.kickAll,Tv.toBinary(i))})}getWaitingRoomRequests(){this.socket.sendMessage(B.getWaitingRoomRequests)}acceptWaitingRoomRequest(e){const i={userIds:e};this.socket.sendMessage(B.acceptWaitingRoomRequests,jP.toBinary(i))}rejectWaitingRoomRequest(e){const i={userIds:e};this.socket.sendMessage(B.denyWaitingRoomRequests,qP.toBinary(i))}updatePermissions(e,i){return u(this,null,function*(){const n={updatePeersPresets:[]};return e.forEach(r=>{n.updatePeersPresets.push({userIds:r,patch:i})}),this.socket.sendMessagePromise(Hc.updateUserPreset,SR.toBinary(n))})}handleSocketEvents(){this.socket.on(B.broadcastMessage,({payload:e})=>{try{const i=ga.fromBinary(e);a(this,Vi).getValue("peerSessionStore").emit(P.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(i.payload)),type:i.type,timestamp:i.timestamp})}catch(i){l.error("failed to decode broadcast message:",i)}}),this.socket.on(B.broadcastToEntity,({payload:e})=>{try{const i=ga.fromBinary(e);a(this,Vi).getValue("peerSessionStore").emit(P.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(i.payload)),type:i.type,timestamp:i.timestamp})}catch(i){l.error("failed to decode peer broadcast message:",i)}})}on(e,i){let n,r;switch(e){case B.joinRoom:case B.leaveRoom:case B.kick:case B.kickAll:{n=ls.fromBinary.bind(ls),r=ls.create();break}case B.getWaitingRoomRequests:{n=(s,o)=>s?Mm.fromBinary(s,o):{requests:[]},r=Mm.create();break}case B.recordingPaused:case B.recordingStarted:case B.recordingStopped:{n=Bm.fromBinary.bind(Bm);break}case Hc.updateUserPreset:{n=Dm.fromBinary.bind(Dm);break}case bi.peerJoinedBroadcast:case ai.peerJoinedBroadcast:{n=Tm.fromBinary.bind(Tm);break}case bi.selfJoinComplete:case ai.selfJoinComplete:{n=Vu.fromBinary.bind(Vu);break}case bi.globalPeerPinBroadcast:case ai.globalPeerPinBroadcast:{n=_m.fromBinary.bind(_m);break}case bi.selectedPeer:case ai.selectedPeer:{n=Lu.fromBinary.bind(Lu);break}case bi.selectedPeerDiff:case ai.selectedPeerDiff:{n=Em.fromBinary.bind(Em);break}case bi.leaveRoom:case ai.leaveRoom:{n=xu.fromBinary.bind(xu);break}}this.socket.on(e,({payload:s})=>{let o=r;if(!n)return i(void 0);try{o=n(s)}catch(c){l.error("roomSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}getUserPermissions(e){return u(this,null,function*(){const i={userIds:[e]};try{const n=yield this.socket.sendMessagePromise(Hc.getUserPresets,hR.toBinary(i)),r=fR.fromBinary(n.payload).peerPresets[0],s=new TextDecoder().decode(r.preset),o=JSON.parse(s).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(n){throw l.error("Error in getting user preset",{error:n}),n}})}}Vi=new WeakMap;pO([S.trace("RoomSocketHandler.joinRoom")],fy.prototype,"joinRoom",1);var Jt;class mO{constructor(e){f(this,Jt,void 0),v(this,Jt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield a(this,Jt).sendMessagePromise(B.getStageRequests);return e?Wl.fromBinary(e):{stageRequests:[]}})}requestAccess(){a(this,Jt).sendMessage(B.requestStageAccess)}cancelRequestAccess(){a(this,Jt).sendMessage(B.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,Jt).sendMessage(B.grantStageAccess,tA.toBinary(i))})}denyAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,Jt).sendMessage(B.denyStageAccess,nA.toBinary(i))})}joinStage(){return a(this,Jt).sendMessagePromise(B.joinStage,void 0,void 0,B.peerStageStatusUpdate)}leaveStage(e){const i={userIds:[e]};return a(this,Jt).sendMessagePromise(B.leaveStage,Fm.toBinary(i),void 0,B.peerStageStatusUpdate)}kick(e){const i={userIds:e};return a(this,Jt).sendMessagePromise(B.leaveStage,Fm.toBinary(i))}on(e,i){let n;switch(e){case B.grantStageAccess:case B.denyStageAccess:{n=void 0;break}case B.getStagePeers:{n=Um.fromBinary.bind(Um);break}case B.getStageRequests:case B.requestStageAccess:case B.cancelStageRequest:{n=Wl.fromBinary.bind(Wl);break}case B.peerStageStatusUpdate:{n=wm.fromBinary.bind(wm);break}}a(this,Jt).on(e,({payload:r,id:s})=>{if(!r||!n)return i(void 0,s);const o=n(r);return i(o,s)})}getPeerInfo(e){return u(this,null,function*(){const i=yield a(this,Jt).sendMessagePromise(B.getPeerInfo,_v.toBinary({peerId:e}));return ls.fromBinary(i.payload)})}}Jt=new WeakMap;var tt;class gO{constructor(e){f(this,tt,void 0),v(this,tt,e)}addPlugin(e,i){a(this,tt).sendMessage(K.addPlugin,yM.toBinary({pluginId:e,staggered:i}))}removePlugin(e){a(this,tt).sendMessage(K.removePlugin,EM.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield a(this,tt).sendMessagePromise(K.getPlugins);return e?HM.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,i,n){const r={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(i))};a(this,tt).sendMessage(K.customPluginEventToRoom,MM.toBinary(r),n)}customPluginEventToPeers(e,i,n,r){const s={pluginId:e,peerIds:i,pluginData:new TextEncoder().encode(JSON.stringify(n))};a(this,tt).sendMessage(K.customPluginEventToPeers,DM.toBinary(s),r)}enablePluginForRoom(e,i){a(this,tt).sendMessage(K.enablePluginForRoom,kM.toBinary({pluginId:e}),i)}enablePluginForPeers(e,i,n){a(this,tt).sendMessage(K.enablePluginForPeers,IM.toBinary({pluginId:e,peerIds:i}),n)}disablePluginForRoom(e,i){a(this,tt).sendMessage(K.disablePluginForRoom,_M.toBinary({pluginId:e}),i)}disablePluginForPeers(e,i,n){a(this,tt).sendMessage(K.disablePluginForPeers,PM.toBinary({pluginId:e,peerIds:i}),n)}storeInsertKeys(e,i,n,r){const s={pluginId:e,storeName:i,insertKeys:n.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,tt).sendMessage(K.storeInsertKeys,Om.toBinary(s),r)}storeGetKeys(e,i,n,r){const s={pluginId:e,storeName:i,getKeys:n.map(o=>({storeKey:o.key}))};a(this,tt).sendMessage(K.storeGetKeys,VM.toBinary(s),r)}storeDeleteKeys(e,i,n,r){const s={pluginId:e,storeName:i,deleteKeys:n.map(o=>({storeKey:o.key}))};a(this,tt).sendMessage(K.storeDeleteKeys,UM.toBinary(s),r)}storeDelete(e,i,n){a(this,tt).sendMessage(K.storeDelete,BM.toBinary({pluginId:e,storeName:i}),n)}getPluginDataOld(e,i){l.info("getPluginDataOld",{plugin:{id:e,storeName:i}})}storePluginDataOld(e,i,n){const r={pluginId:e,storeName:i,insertKeys:[{storeKey:n.key,payload:new TextEncoder().encode(JSON.stringify(n))}]};a(this,tt).sendMessage(K.storeInsertKeys,Om.toBinary(r))}on(e,i){let n;switch(e){case K.addPlugin:case K.enablePluginForPeers:case K.enablePluginForRoom:{n=Wu.fromBinary.bind(Wu);break}case K.removePlugin:case K.disablePluginForPeers:case K.disablePluginForRoom:{n=Nm.fromBinary.bind(Nm);break}case K.customPluginEventToPeers:case K.customPluginEventToRoom:{n=Vm.fromBinary.bind(Vm);break}case K.storeInsertKeys:case K.storeGetKeys:case K.storeDeleteKeys:case K.storeDelete:{n=Lm.fromBinary.bind(Lm);break}}a(this,tt).on(e,({payload:r,id:s})=>{const o=n(r);return i(o,s)})}}tt=new WeakMap;var fO=Object.defineProperty,vO=(t,e,i)=>e in t?fO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,yO=(t,e,i)=>(vO(t,typeof e!="symbol"?e+"":e,i),i),yp=(t,e,i)=>{if(!e.has(t))throw TypeError("Cannot "+i)},N=(t,e,i)=>(yp(t,e,"read from private field"),i?i.call(t):e.get(t)),Ce=(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)},ue=(t,e,i,n)=>(yp(t,e,"write to private field"),n?n.call(t,i):e.set(t,i),i),De=(t,e,i)=>(yp(t,e,"access private method"),i),Xd={},SO={get exports(){return Xd},set exports(t){Xd=t}},Vs=typeof Reflect=="object"?Reflect:null,Lg=Vs&&typeof Vs.apply=="function"?Vs.apply:function(t,e,i){return Function.prototype.apply.call(t,e,i)},kd;Vs&&typeof Vs.ownKeys=="function"?kd=Vs.ownKeys:Object.getOwnPropertySymbols?kd=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:kd=function(t){return Object.getOwnPropertyNames(t)};function EO(t){console&&console.warn&&console.warn(t)}var vy=Number.isNaN||function(t){return t!==t};function ge(){ge.init.call(this)}SO.exports=ge;Xd.once=_O;ge.EventEmitter=ge;ge.prototype._events=void 0;ge.prototype._eventsCount=0;ge.prototype._maxListeners=void 0;var Vg=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(ge,"defaultMaxListeners",{enumerable:!0,get:function(){return Vg},set:function(t){if(typeof t!="number"||t<0||vy(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Vg=t}});ge.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};ge.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||vy(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 yy(t){return t._maxListeners===void 0?ge.defaultMaxListeners:t._maxListeners}ge.prototype.getMaxListeners=function(){return yy(this)};ge.prototype.emit=function(t){for(var e=[],i=1;i<arguments.length;i++)e.push(arguments[i]);var n=t==="error",r=this._events;if(r!==void 0)n=n&&r.error===void 0;else if(!n)return!1;if(n){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=r[t];if(c===void 0)return!1;if(typeof c=="function")Lg(c,this,e);else for(var d=c.length,h=by(c,d),i=0;i<d;++i)Lg(h[i],this,e);return!0};function Sy(t,e,i,n){var r,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]=n?[i,o]:[o,i]:n?o.unshift(i):o.push(i),r=yy(t),r>0&&o.length>r&&!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,EO(c)}return t}ge.prototype.addListener=function(t,e){return Sy(this,t,e,!1)};ge.prototype.on=ge.prototype.addListener;ge.prototype.prependListener=function(t,e){return Sy(this,t,e,!0)};function TO(){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 Ey(t,e,i){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:i},r=TO.bind(n);return r.listener=i,n.wrapFn=r,r}ge.prototype.once=function(t,e){return kl(e),this.on(t,Ey(this,t,e)),this};ge.prototype.prependOnceListener=function(t,e){return kl(e),this.prependListener(t,Ey(this,t,e)),this};ge.prototype.removeListener=function(t,e){var i,n,r,s,o;if(kl(e),n=this._events,n===void 0)return this;if(i=n[t],i===void 0)return this;if(i===e||i.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,i.listener||e));else if(typeof i!="function"){for(r=-1,s=i.length-1;s>=0;s--)if(i[s]===e||i[s].listener===e){o=i[s].listener,r=s;break}if(r<0)return this;r===0?i.shift():kO(i,r),i.length===1&&(n[t]=i[0]),n.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this};ge.prototype.off=ge.prototype.removeListener;ge.prototype.removeAllListeners=function(t){var e,i,n;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 r=Object.keys(i),s;for(n=0;n<r.length;++n)s=r[n],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(n=e.length-1;n>=0;n--)this.removeListener(t,e[n]);return this};function Ty(t,e,i){var n=t._events;if(n===void 0)return[];var r=n[e];return r===void 0?[]:typeof r=="function"?i?[r.listener||r]:[r]:i?bO(r):by(r,r.length)}ge.prototype.listeners=function(t){return Ty(this,t,!0)};ge.prototype.rawListeners=function(t){return Ty(this,t,!1)};ge.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):ky.call(t,e)};ge.prototype.listenerCount=ky;function ky(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}ge.prototype.eventNames=function(){return this._eventsCount>0?kd(this._events):[]};function by(t,e){for(var i=new Array(e),n=0;n<e;++n)i[n]=t[n];return i}function kO(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function bO(t){for(var e=new Array(t.length),i=0;i<e.length;++i)e[i]=t[i].listener||t[i];return e}function _O(t,e){return new Promise(function(i,n){function r(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",r),i([].slice.call(arguments))}_y(t,e,s,{once:!0}),e!=="error"&&wO(t,r,{once:!0})})}function wO(t,e,i){typeof t.on=="function"&&_y(t,"error",e,i)}function _y(t,e,i,n){if(typeof t.on=="function")n.once?t.once(e,i):t.on(e,i);else if(typeof t.addEventListener=="function")t.addEventListener(e,function r(s){n.once&&t.removeEventListener(e,r),i(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}class IO extends E{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 xg=new IO;class wy{static encode(e){return xg.toBinary(e)}static decode(e){return xg.fromBinary(new Uint8Array(e))}}function CO(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var Mn;class PO{constructor(e={}){yO(this,"opts"),Ce(this,Mn,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},ue(this,Mn,0)}wait(){return u(this,null,function*(){ue(this,Mn,N(this,Mn)+1);const e=CO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*US(2,N(this,Mn))));yield new Promise(i=>{setTimeout(i,e)})})}getAttempts(){return N(this,Mn)}reset(){ue(this,Mn,0)}}Mn=new WeakMap;const vn={debug:0,info:1,warn:2,error:3};var gr,fr;class RO{constructor(e){Ce(this,gr,void 0),Ce(this,fr,void 0),ue(this,gr,console),ue(this,fr,e)}debug(...e){vn[N(this,fr)]>vn.debug||N(this,gr).debug("[Sockrates]:",...e)}info(...e){vn[N(this,fr)]>vn.info||N(this,gr).info("[Sockrates]:",...e)}warn(...e){vn[N(this,fr)]>vn.warn||N(this,gr).warn("[Sockrates]:",...e)}error(...e){vn[N(this,fr)]>vn.error||N(this,gr).error("[Sockrates]:",...e)}}gr=new WeakMap,fr=new WeakMap;var Iy=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(Iy||{});const MO="2",AO="3";var Fe,Ts,Ae,Ge,An,it,tn,Un,ki,ks,zi,Rh,Cy,_o,bd,Mh,Py,Ah,Ug,Zd,Dh,Oh,Ry,Uo,_d,Fo,el,tl,Nh,xs,Bo,Wo,il;class DO{constructor(e,i){var n;Ce(this,Rh),Ce(this,_o),Ce(this,Mh),Ce(this,Ah),Ce(this,Zd),Ce(this,Oh),Ce(this,Uo),Ce(this,Fo),Ce(this,tl),Ce(this,xs),Ce(this,Wo),Ce(this,Fe,void 0),Ce(this,Ts,void 0),Ce(this,Ae,void 0),Ce(this,Ge,void 0),Ce(this,An,void 0),Ce(this,it,void 0),Ce(this,tn,void 0),Ce(this,Un,void 0),Ce(this,ki,void 0),Ce(this,ks,void 0),Ce(this,zi,void 0);var r,s,o,c,d,h,p,g,y;ue(this,Ts,e),ue(this,An,[]),ue(this,it,new Xd),ue(this,tn,!0),ue(this,ki,!1),ue(this,Ae,i!=null?i:{}),(r=N(this,Ae)).autoReconnect!=null||(r.autoReconnect=!0),(s=N(this,Ae)).retryConnectionInterval!=null||(s.retryConnectionInterval=1e3),(o=N(this,Ae)).pingTimeout!=null||(o.pingTimeout=3e4),(c=N(this,Ae)).connectionTimeout!=null||(c.connectionTimeout=5e3),(d=N(this,Ae)).debug!=null||(d.debug=!0),(h=N(this,Ae)).maxReconnectionAttempts!=null||(h.maxReconnectionAttempts=10),(p=N(this,Ae)).disconnectOnPingTimeout!=null||(p.disconnectOnPingTimeout=!0),(g=N(this,Ae)).queueOnDisconnect!=null||(g.queueOnDisconnect=!1),(y=N(this,Ae)).flushOnReconnect!=null||(y.flushOnReconnect=!1),ue(this,Un,{code:void 0,reason:void 0}),ue(this,Ge,(n=N(this,Ae).logger)!=null?n:new RO(N(this,Ae).debug?"debug":"info")),ue(this,zi,new PO)}get readyState(){var e;return(e=N(this,Fe))==null?void 0:e.readyState}get url(){return N(this,Ts)}updateURL(e){ue(this,Ts,e),De(this,Oh,Ry).call(this)}get config(){return N(this,Ae)}get sendQueue(){return N(this,An)}flush(){if(!N(this,Ae).queueOnDisconnect)return!1;const e=[];return N(this,An).forEach(i=>{this.send(i.event,i.id,i.payload,i.metadata)||e.push(i)}),ue(this,An,e),N(this,An)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){N(this,Ge).debug("Websocket was already connecting or connected.");return}if(N(this,tn)!==!1)return new Promise((i,n)=>{De(this,xs,Bo).call(this),De(this,Wo,il).call(this);try{ue(this,Fe,new WebSocket(De(this,Rh,Cy).call(this,N(this,Ts)))),N(this,Fe).binaryType="arraybuffer",N(this,Ge).debug("Connecting");const r=setTimeout(()=>{N(this,Ge).debug("Connection timeout. Closing socket"),ue(this,tn,!0),De(this,Wo,il).call(this),N(this,Fe).close(3001,"Connection Timeout"),N(this,Ae).autoReconnect&&!N(this,ki)&&(N(this,it).emit("reconnecting"),De(this,Uo,_d).call(this)),n(new Error("Connection timed out!"))},N(this,Ae).connectionTimeout);N(this,Fe).onopen=()=>{N(this,Ge).debug(`Ready State: ${Iy[N(this,Fe).readyState]}`),r&&clearTimeout(r),De(this,tl,Nh).call(this),ue(this,Un,{code:void 0,reason:void 0}),N(this,it).emit("connected"),N(this,Ae).flushOnReconnect&&this.flush(),i()},N(this,Fe).onclose=s=>{try{r&&clearTimeout(r);const{code:o,reason:c}=s;n(c),N(this,Ge).debug("Socket closed. Close event:",{event:s}),N(this,Ge).debug(`Connection closed code: ${o}`),N(this,Ge).debug(`Connection closed reason: ${c}`),N(this,ki)||De(this,Zd,Dh).call(this,o,c)}catch(o){De(this,_o,bd).call(this,o)}},N(this,Fe).onerror=s=>{De(this,_o,bd).call(this,s)},N(this,Fe).onmessage=s=>De(this,Mh,Py).call(this,s)}catch(r){De(this,_o,bd).call(this,r,n)}})})}send(e,i,n,r){const s={event:e,id:i,payload:n,metadata:r};if(N(this,Ae).queueOnDisconnect&&(!N(this,Fe)||N(this,Fe).readyState!==1))return N(this,Ge).debug("Queuing message since socket is not connected!",s),N(this,An).push(s),!1;const o=wy.encode(s);return De(this,Fo,el).call(this,o)}emit(e,i,n,r){return this.send(e,i,n,r)}sendRaw(e){return De(this,Fo,el).call(this,e)}receive(e,i){return N(this,it).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,it).on(e,i);return}this.receive(e,i)}removeAllListeners(){N(this,it).removeAllListeners()}removeReceiver(e,i){this.removeListener(e,i)}removeListener(e,i){N(this,it).removeListener(e.toString(),i)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){N(this,it).listeners(e.toString()).map(i=>this.removeListener(e,i))}disconnect(){ue(this,tn,!1),De(this,xs,Bo).call(this),this.removeAllListeners(),ue(this,Un,{code:1e3,reason:"Sockrates disconnect method called"}),N(this,Fe).close(1e3,"Sockrates disconnect method called.")}}Fe=new WeakMap,Ts=new WeakMap,Ae=new WeakMap,Ge=new WeakMap,An=new WeakMap,it=new WeakMap,tn=new WeakMap,Un=new WeakMap,ki=new WeakMap,ks=new WeakMap,zi=new WeakMap,Rh=new WeakSet,Cy=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)://.")},_o=new WeakSet,bd=function(t,e){N(this,Ge).error("Error:",{error:t}),N(this,it).emit("errored",{error:t}),e==null||e(t)},Mh=new WeakSet,Py=function(t){if(De(this,tl,Nh).call(this),t.data===MO){N(this,Ge).debug("Received ping from server"),De(this,Fo,el).call(this,AO);return}const e=wy.decode(t.data),{id:i,payload:n}=e;N(this,Ge).debug("Received message",{event:e.event,messageID:i}),N(this,it).emit(e.event.toString(),{id:i,payload:n})},Ah=new WeakSet,Ug=function(){return N(this,Fe).readyState===1},Zd=new WeakSet,Dh=function(t,e){ue(this,Un,{reason:e,code:t}),N(this,it).emit("disconnected",{code:t,reason:e})},Oh=new WeakSet,Ry=function(){const{reason:t,code:e}=N(this,Un);e&&e!==1e3&&N(this,tn)&&N(this,Ae).autoReconnect&&!N(this,ki)&&(N(this,Ge).debug(`Triggering reconnection due to ${t}.`),N(this,it).emit("reconnecting"),De(this,Uo,_d).call(this))},Uo=new WeakSet,_d=function(t=!0){return u(this,null,function*(){if(t&&N(this,ki)){N(this,Ge).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(N(this,ki)||N(this,zi).reset(),N(this,Ae).maxReconnectionAttempts!==null&&N(this,zi).getAttempts()>=N(this,Ae).maxReconnectionAttempts){N(this,it).emit("failed"),ue(this,ki,!1);return}ue(this,ki,!0),De(this,Wo,il).call(this),De(this,xs,Bo).call(this);try{if(yield N(this,zi).wait(),N(this,tn)===!1)return;if(N(this,Ge).debug(`Reconnection attempt ${N(this,zi).getAttempts()}`),N(this,it).emit("reconnectAttempt",{attempt:N(this,zi).getAttempts()}),yield this.connect(),!De(this,Ah,Ug).call(this))throw Error("Reconnect Failed");ue(this,ki,!1),ue(this,Un,{code:void 0,reason:void 0}),N(this,it).emit("reconnected")}catch{N(this,Ge).debug("Failed to reconnect."),N(this,it).emit("reconnectFailure",{attempt:N(this,zi).getAttempts()}),De(this,Uo,_d).call(this,!1)}})},Fo=new WeakSet,el=function(t){try{return N(this,Fe).send(t),!0}catch(e){return N(this,Ge).error(e.message),!1}},tl=new WeakSet,Nh=function(){this.config.disconnectOnPingTimeout&&(N(this,Ge).debug("Resetting ping timeout"),De(this,xs,Bo).call(this),ue(this,ks,setTimeout(()=>{var t;N(this,Ge).debug("Disconnecting the socket due to ping timeout"),ue(this,tn,!0);const e=3002,i="Ping timeout";(t=N(this,Fe))==null||t.close(e,i),De(this,Zd,Dh).call(this,e,i)},N(this,Ae).pingTimeout)))},xs=new WeakSet,Bo=function(){N(this,ks)&&(clearTimeout(N(this,ks)),ue(this,ks,void 0))},Wo=new WeakSet,il=function(){N(this,Fe)&&(N(this,Fe).onopen=void 0,N(this,Fe).onerror=void 0,N(this,Fe).onmessage=void 0,N(this,Fe).onclose=void 0)};var OO=Object.defineProperty,NO=Object.getOwnPropertyDescriptor,bl=(t,e,i,n)=>{for(var r=n>1?void 0:n?NO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&OO(e,i,r),r};const Fg=65535,LO=3e3;var er,Ve,xe,We,mi,ii,Nc,Su,Lc,Eu,Bg;const My=(Bg=class{constructor(t,{peerId:e,meetingId:i,authToken:n,capabilities:r}){f(this,xe),f(this,Nc),f(this,Lc),f(this,er,void 0),f(this,Ve,void 0),m(this,"roomName"),m(this,"authToken"),m(this,"capabilities"),f(this,mi,void 0),f(this,ii,void 0);var s;if(!e||!i||!n)throw new w("peerId, meetingId, or authToken can not be empty","0404");v(this,mi,void 0),v(this,ii,t),this.capabilities=r,this.roomName=i,this.authToken=n,v(this,er,F(this,Nc,Su).call(this,e)),v(this,Ve,new DO(a(this,er),{autoReconnect:!0,disconnectOnPingTimeout:(s=r.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:l})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,xe,We).socketJoinAttempted}set joinAttempted(t){a(this,xe,We).socketJoinAttempted=t}get peerId(){return a(this,ii).getValue("peerId")}updateURL(t){t!==this.peerId&&(v(this,er,F(this,Nc,Su).call(this,t)),l.debug("SocketService:: Connection URL updated.")),a(this,Ve).updateURL(a(this,er))}static getSocketEdgeDomain(t){return Os({servicePrefix:"socket-edge",baseURI:t})}get url(){return a(this,er)}connect(){return u(this,null,function*(){a(this,xe,We).socketJoinAttempted=!0,yield a(this,Ve).connect(),a(this,xe,We).socketJoinAttempted=!0,a(this,xe,We).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return u(this,null,function*(){a(this,xe,We).socketJoinAttempted=!1,a(this,Ve).disconnect(),a(this,xe,We).socketJoinAttempted=!0,a(this,xe,We).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return a(this,Ve).readyState===1}catch{return!1}}sendMessage(t,e,i){const n={};return S.injectContext(n),a(this,Ve).send(t,i!=null?i:F(this,Lc,Eu).call(this),e,new TextEncoder().encode(JSON.stringify(n)))}sendMessagePromise(t,e,i,n){const r=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:r,protobuf:e,messageId:i,resp:n})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:i,messageId:n,resp:r}){const s=r!=null?r:t;return new Promise((o,c)=>{const d=(T,b)=>{a(this,Ve).removeListener(s,T),a(this,Ve).removeListener(Fg,b),a(this,Ve).removeListener(ai.errorResponse,b),a(this,Ve).removeListener(bi.errorResponse,b)},h=n!=null?n:F(this,Lc,Eu).call(this),p={};S.injectContext(p);const g=({id:T,payload:b})=>{if(h===T){let D;try{const R=NI.fromBinary(b);D=new Error(R.errorMessage)}catch(R){D=new Error("failed to parse error message",{cause:R});try{const V=LC.fromBinary(b);D=new Error(V.message)}catch(V){D=new Error("failed to parse error message",{cause:V})}}c(D),d(y,g)}},y=({id:T,payload:b})=>{h===T&&(o({id:T,payload:b}),d(y,g))};a(this,Ve).on(s,y),a(this,Ve).on(Fg,g),a(this,Ve).on(ai.errorResponse,g),a(this,Ve).on(bi.errorResponse,g),setTimeout(()=>{d(y,g),c(new Error(`request timeout for callback eventId:${t}`))},e),a(this,Ve).send(t,h,i,new TextEncoder().encode(JSON.stringify(p)))})}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*(){l.info("SocketService::Connected to socket-edge"),a(this,mi)&&(clearTimeout(a(this,mi)),v(this,mi,void 0)),a(this,xe,We).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var i;l.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:S.location.country});const{recv:n,send:r}=(i=a(this,xe,We).mediaState)!=null?i:{};n!=null&&n.state&&(n==null?void 0:n.state)!==Hs.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Hs.CONNECTED?a(this,ii).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,xe,We).joinAttempted}):v(this,mi,setTimeout(()=>{a(this,ii).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,xe,We).joinAttempted}),v(this,mi,void 0)},LO)),a(this,xe,We).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){l.info("SocketService::Reconnecting to socket-edge",{country:S.location.country}),a(this,xe,We).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){l.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),a(this,xe,We).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{l.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),a(this,xe,We).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){l.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,xe,We).mediaJoinAttempted}}),a(this,mi)&&(clearTimeout(a(this,mi)),v(this,mi,void 0)),a(this,ii).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,xe,We).mediaJoinAttempted}),a(this,xe,We).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){l.info("SocketService::Failed to connect to socket-edge",{country:S.location.country}),a(this,ii).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_FAILED),a(this,xe,We).updateSocketConnectionState("failed")}))}},er=new WeakMap,Ve=new WeakMap,xe=new WeakSet,We=function(){return a(this,ii).getValue("connectionHandler")},mi=new WeakMap,ii=new WeakMap,Nc=new WeakSet,Su=function(t){let e=My.getSocketEdgeDomain(a(this,ii).getValue("baseURI"));typeof Ws(a(this,ii),"socket_server_base")=="string"&&(e=Ws(a(this,ii),"socket_server_base"));const i=`wss://${e}`,n=new URL(`${i}/ws`),r=this.peerId,s=G(L({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},r!==t&&{oldPeerID:r}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>Bd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0});return Object.entries(s).forEach(([o,c])=>{n.searchParams.append(o,c.toString())}),n.href},Lc=new WeakSet,Eu=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Bg);let tc=My;bl([S.trace("SocketService.connect")],tc.prototype,"connect",1);bl([S.trace("SocketService.disconnect")],tc.prototype,"disconnect",1);bl([S.trace("SocketService.sendMessagePromise")],tc.prototype,"sendMessagePromise",1);bl([S.trace("SocketService.sendMessagePromiseWithTimeout")],tc.prototype,"sendMessagePromiseWithTimeout",1);const vr=class{static handleConnectedRoomsDumpRaw({payload:t}){var e;const i=cP.fromBinary(t),n=i.meetings.map(r=>{var s;return{id:r.id,title:r.title,participants:(s=r.participants)!=null?s:[]}});return{parentMeeting:{id:i.parentMeeting.id,title:i.parentMeeting.title,participants:(e=i.parentMeeting.participants)!=null?e:[]},meetings:n}}static handleTransferPeerRaw({payload:t}){const e=NP.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=wv.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return Rm.fromBinary(t).payloads.map(e=>({id:e.id,title:e.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return _P.fromBinary(t).payloads}static getConnectedRoomsDump(){return u(this,null,function*(){const t=yield vr.socketService.sendMessagePromise(B.getConnectedRoomsDump);return vr.handleConnectedRoomsDumpRaw(t)})}static createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield vr.socketService.sendMessagePromise(B.createConnectedRooms,hP.toBinary({payloads:t}));return Rm.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))})}static updateConnectedRooms(t){return u(this,null,function*(){})}static disableConnectedRooms(t){return u(this,null,function*(){const e=t.map(n=>({id:n})),i=yield vr.socketService.sendMessagePromise(B.deleteConnectedRooms,kP.toBinary({payloads:e}));return vr.handleConnectedRoomsDeletedRaw(i)})}static movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield vr.socketService.sendMessagePromise(B.movePeers,MP.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}})}};let Ne=vr;m(Ne,"socketService"),m(Ne,"currentMeetingId");var VO=Object.defineProperty,xO=Object.getOwnPropertyDescriptor,_l=(t,e,i,n)=>{for(var r=n>1?void 0:n?xO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&VO(e,i,r),r};const bs=class{constructor(t,e){m(this,"apiBase"),m(this,"selfController"),m(this,"pollController"),m(this,"chatController"),m(this,"metaController"),m(this,"storesManager"),m(this,"stageController"),m(this,"pluginController"),m(this,"internalsController"),m(this,"recordingController"),m(this,"livestreamController"),m(this,"participantController"),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}static init(t){return u(this,null,function*(){var e,i;const{peerId:n,apiBase:r,authToken:s,meetingId:o,organizationId:c,cachedUserDetails:d}=t.getAllValues();if(my(t),Re.isSupported()===!1)throw new w("Browser not supported","0010",!0);const h=$A(t,{authToken:s,baseURL:r,cachedUserDetails:d});h.setRoomName(o),h.setRoomUUID(o),h.setOrganizationId(c),h.setHeader("dyte-tracing-id",n),t.setValue("apiClient",h);const p=new P1(t);t.setValue("connectionHandler",p);const g=bs.createSocketService(t),y=g.connect(),T=h.getUserDetails(),b=h.getPlugins();let D=Le.HIVE,R,V="";try{yield bs.setupFlagsmith(t)}catch(ne){l.error("Failed to setup flagsmith",{error:ne})}try{yield y}catch(ne){l.error("[Controller]: Failed to connect to socket server:",{error:ne})}try{({sfu:D,meetingTitle:V}=yield h.getRoomNodeData()),R=yield T,l.info(`SFU ${D} is being used.`),t.setValue("presetName",R.preset.name),t.setValue("roomNodeOptions",{sfu:D})}catch(ne){l.error("Failed to get room metadata",{error:ne})}const j=hD.init(R.preset,!t.getValue("modules").theme),$=OD.init(t,j.viewType,R.preset.permissions),I=bs.setupControllers(g,t,R,b,V,j,$);v1(j)&&((e=bs.createRoomNodeClient(t,g).initializeConnection(R.participant.name,o,!1,$))==null||e.catch(ne=>{l.error("[Controller]: Failed to queue partial media room promise:",{error:ne})})),S.location.country=(i=h.ipInfo)==null?void 0:i.country;const{controllers:se}=yield I;return mw(),new bs(r,se)})}static setupFlagsmith(t){return u(this,null,function*(){var e;const{peerId:i,baseURI:n,overrides:r,meetingId:s,organizationId:o}=t.getAllValues(),c=pw(s),d=G(L({entity:Nu.PEER,clientId:o,isAnonUser:!o,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:c,roomName:s},Re.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const h=(e=r==null?void 0:r.whitelabelled_flags_endpoint)==null||e?Os({servicePrefix:"flags",baseURI:n}):"edge.api.flagsmith.com";yield Y.identify(`${Nu.PEER}_${i}`,JSON.parse(JSON.stringify(d)),!1,5e3,h,l),l.info("flagsmith::allFlags",{flags:JSON.stringify(Y.getAllFlags())},!0)}catch{l.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,i,n,r,s,o){return u(this,null,function*(){var c,d,h;const p=e.getValue("modules"),{participant:g}=i,y=e.getValue("defaults"),{sfu:T}=e.getValue("roomNodeOptions"),{viewType:b,mediaConstraints:{audio:D}}=s;e.setValue("viewType",b),e.setValue("defaults",L({mediaConfiguration:{audio:{enableHighBitrate:(c=D.enableHighBitrate)!=null?c:!1,enableStereo:(d=D.enableStereo)!=null?d:!1}}},y)),e.setValue("maxPreferredStreams",Re.isMobile()?s.maxVideoStreams.mobile:s.maxVideoStreams.desktop);let R,V,j,$,I,se,ne,ve;const Qe=new cO(t);Ne.socketService=t;const dt=new Tl(t),Rt=new oi(t),M=new mO(t),k=new fy(e,t),_=new gO(t),W=new oO(t),we=new Ar(t),pe=yield $n.init(e,k,g,o,s),U=yield xv.init(e,pe.self,k,Qe,r);if(p.participant&&(ve=new dn(e,pe.self,k,T)),(h=p.e2ee)!=null&&h.enabled&&p.e2ee.manager.init(l,e.getValue("peerSessionStore")),p.chat&&(V=yield nn.init(e,Rt,we,pe.self,ve.participants)),p.internals&&(I=yield op.init()),p.livestream&&s.viewType===Ut.Livestream&&Y.hasFeature(ie.LIVESTREAM)&&(ne=new $v(e,pe.self,W)),s.viewType!==Ut.Chat){if(p.poll&&(R=yield Ov.init(e,pe.self,dt)),p.recording&&(se=new Wv(e,pe.self,k)),p.stage&&(j=new Uv(e,M,k,pe.self,ve.participants)),p.plugin){if(!ve)throw new w("The plugin module cannot be initialized without the `participant` module","0102");const Be=yield n;$=yield Qo.init(e,Be,_,Rt,V==null?void 0:V.chat,pe.self,ve.participants,r)}if(p.pip){const Be=yield vw._init(e,pe.self);e.setValue("pip",Be)}}const C={storesManager:new ED(e,_),pollController:R,selfController:pe,metaController:U,chatController:V,stageController:j,pluginController:$,recordingController:se,internalsController:I,livestreamController:ne,participantController:ve};return{theme:s,permissions:o,controllers:C}})}static createRoomNodeClient(t,e){const{peerId:i,roomNodeOptions:n}=t.getAllValues(),{sfu:r}=n;return py(t,r,{socket:e,peerId:i})}static createSocketService(t){const{peerId:e,meetingId:i,authToken:n}=t.getAllValues(),r=["PING"];return new tc(t,{peerId:e,meetingId:i,authToken:n,capabilities:r})}};let ic=bs;_l([S.trace("Controller.init")],ic,"init",1);_l([S.trace("setupFlagsmith")],ic,"setupFlagsmith",1);_l([S.trace("Controller.createRoomNodeClient")],ic,"createRoomNodeClient",1);_l([S.trace("Controller.createSocketService")],ic,"createSocketService",1);var UO=Object.defineProperty,FO=Object.getOwnPropertyDescriptor,BO=(t,e,i,n)=>{for(var r=n>1?void 0:n?FO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&UO(e,i,r),r},wd,Lh;class Ay extends Qt{constructor(e,i){super(),f(this,wd,void 0),m(this,"meetings",[]),m(this,"parentMeeting",null),f(this,Lh,void 0),v(this,Lh,e),v(this,wd,i.self)}get supportsConnectedMeetings(){return a(this,wd).id!==""}get isActive(){return this.meetings.length!==0}get currentMeetingId(){return Ne.currentMeetingId}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 Ne.getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield Ne.createConnectedRooms(e)).map(i=>({id:i.id,title:i.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield Ne.updateConnectedRooms(e.map(i=>({meetingId:i.id,title:i.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(r=>r.id)):Promise.resolve());return yield Promise.all(i),yield Ne.disableConnectedRooms(e)})}moveParticipants(e,i,n){return u(this,null,function*(){this.validateConnectedMeetingsAction();const r=yield Ne.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:n.map(s=>({id:s}))});return r.success&&this.moveSuccessHandler(e,i,n),r})}moveParticipantsWithCustomPreset(e,i,n){return u(this,null,function*(){this.validateConnectedMeetingsAction();const r=yield Ne.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:n});return r.success&&this.moveSuccessHandler(e,i,n.map(s=>s.id)),r})}moveSuccessHandler(e,i,n){const r=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(s=>s.participants)].forEach(s=>r.set(s.id,s)),i===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(n.map(s=>r.get(s)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(s=>!n.includes(s.id))),this.meetings=this.meetings.map(s=>{if(i===s.id){const o=s.participants.concat(n.map(c=>r.get(c)));return G(L({},s),{participants:o})}if(e===s.id){const o=s.participants.filter(c=>!n.includes(c.id));return G(L({},s),{participants:o})}return s})}}wd=new WeakMap,Lh=new WeakMap;BO([Ft({maxInvocations:60,period:60})],Ay.prototype,"getConnectedMeetings",1);var WO=Object.defineProperty,jO=Object.getOwnPropertyDescriptor,Sp=(t,e,i,n)=>{for(var r=n>1?void 0:n?jO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&WO(e,i,r),r},Ya,gi,Tu,ku;const Dn=(Tu=class{constructor(t,e,i){m(this,"connectedMeetings"),f(this,Ya,void 0),f(this,gi,void 0),f(this,ku,void 0),v(this,ku,t),v(this,Ya,i),this.connectedMeetings=new Ay(t,e),this.setCurrentMeeting(e)}static init(t,e,i){return Dn.instance||(Dn.instance=new Dn(t,e,i)),Dn.instance.connectedMeetings.supportsConnectedMeetings&&(Dn.instance.setupEvents(),e.self.once("roomJoined",()=>Dn.instance.getConnectedMeetings())),Dn.instance}setCurrentMeeting(t){v(this,gi,t),Ne.currentMeetingId=t.meta.meetingId}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){Ne.socketService&&(Ne.socketService.on(B.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),Ne.socketService.on(B.transferPeer,this.handleTransferPeer.bind(this)),Ne.socketService.on(B.movedPeer,this.handleMovedPeer.bind(this)),Ne.socketService.on(B.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),Ne.socketService.on(B.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this)))}handleTransferPeer(t){const e=Ne.handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:i}){var n,r,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.`);l.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",i);const c={video:a(this,gi).self.videoEnabled,audio:a(this,gi).self.audioEnabled};try{a(this,gi).self.cleanupEvents(),yield a(this,gi).leave("connected-meeting")}catch(h){l.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(r=(n=a(this,gi))==null?void 0:n.meta)==null?void 0:r.meetingId}`,{error:h})}Ne.socketService=void 0,l.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${i}`);const d=yield Oy.init(G(L({},a(this,Ya)),{cachedUserDetails:null,defaults:G(L(L({},a(this,Ya).defaults),c),{mediaHandler:a(this,gi).self}),authToken:e}));l.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(s=d==null?void 0:d.meta)==null?void 0:s.meetingId}`);try{const{hidden:h}=a(this,gi).self;d.self.setName(a(this,gi).self.name),yield d.join(),h&&d.self.hide()}catch(h){l.error("ConnectedMeetingsController.joinRoom",{error:h})}return l.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),this.setCurrentMeeting(d),d})}handleConnectedRoomsDump(t){const e=Ne.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 Ne.handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=Ne.handleConnectedRoomsUpdatedRaw(t),i=new Map;this.connectedMeetings.meetings.forEach(n=>{i.set(n.id,n)}),e.forEach(n=>{i.has(n.id)?i.get(n.id).title=n.title:i.set(n.id,G(L({},n),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(i.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=Ne.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})}},Ya=new WeakMap,gi=new WeakMap,ku=new WeakMap,m(Tu,"instance"),Tu);let wl=Dn;Sp([S.trace("ConnectedMeetingsController.getConnectedMeetings")],wl.prototype,"getConnectedMeetings",1);Sp([S.trace("ConnectedMeetingsController.setupEvents")],wl.prototype,"setupEvents",1);Sp([S.trace("ConnectedMeetingsController.switchMeeting")],wl.prototype,"switchMeeting",1);class HO{constructor(){m(this,"battery"),m(this,"init",()=>u(this,null,function*(){try{"getBattery"in navigator&&(this.battery=yield navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){l.error("Error getting battery",e)}})),m(this,"updateChargeInfo",()=>{var e;l.log(`Battery charging? ${(e=this.battery)!=null&&e.charging?"Yes":"No"}`)}),m(this,"updateLevelInfo",()=>{if(!this.battery){l.log("Battery level: Not known");return}l.log(`Battery level: ${this.battery.level*100}%`)}),m(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 Wg=new HO;function qO(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:n,participantId:r}=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://api.${s}`;return{meetingId:i,orgId:n,participantId:r,baseURI:s,apiBase:o}}catch(i){throw l.error("constants::decodeAuthToken",{error:i,debuggingHint:`Unable to decode auth token: ${t}`},!0),new w("Invalid auth token","0004")}}var yr,_s,ws,nl,Vh,Dy;class GO{constructor(){f(this,Vh),f(this,yr,new Audio),f(this,_s,new MediaStream),f(this,ws,new Map),f(this,nl,void 0),a(this,yr).srcObject=a(this,_s),a(this,yr).autoplay=!0}playTracks(e){return u(this,null,function*(){return e.forEach(i=>{a(this,ws).has(i.id)||(a(this,_s).addTrack(i),a(this,ws).set(i.id,i))}),this.play()})}setSpeakerDevice(e){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,yr).setSinkId(e)}removeTrack(e){const i=a(this,ws).get(e);i&&(a(this,_s).removeTrack(i),a(this,ws).delete(e))}play(){return u(this,null,function*(){return a(this,yr).srcObject=a(this,_s),a(this,yr).play().catch(e=>{F(this,Vh,Dy).call(this,e)})})}onError(e){v(this,nl,e)}}yr=new WeakMap,_s=new WeakMap,ws=new WeakMap,nl=new WeakMap,Vh=new WeakSet,Dy=function(t){var e;(e=a(this,nl))==null||e.call(this,t)};var Is;class $O extends GO{constructor(){super(),f(this,Is,void 0),v(this,Is,new Map)}addParticipantTrack(e,i){a(this,Is).set(e,i.id),this.playTracks([i])}removeParticipantTrack(e){const i=a(this,Is).get(e);i&&this.removeTrack(i),a(this,Is).delete(e)}}Is=new WeakMap;var JO=Object.defineProperty,KO=Object.getOwnPropertyDescriptor,Il=(t,e,i,n)=>{for(var r=n>1?void 0:n?KO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&JO(e,i,r),r},at,Vc,tr,bu,jg,Hg;let Hn=(Hg=class{constructor(t,e){f(this,bu),f(this,at,void 0),f(this,Vc,void 0),f(this,tr,void 0),v(this,tr,t),v(this,at,e)}static init(t){return u(this,null,function*(){var e,i,n,r,s,o,c;lw(),Re.init();const d=(i=(e=t==null?void 0:t.cachedUserDetails)==null?void 0:e.peerId)!=null?i:qs();Wg.init();const{authToken:h,baseURI:p}=t,g=qO(h,p),{meetingId:y}=g,T=al(g,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const b=Hn.setupContext(d,t,y,T);S.meetingMetadata.roomName=y,S.meetingMetadata.userId=T.participantId,S.meetingMetadata.organizationId=T.orgId,S.init(b,(r=(n=t.modules)==null?void 0:n.tracing)!=null?r:!0),l.info("DyteClient::init::options",{dyteClientInitOptions:G(L({},t),{authToken:`${(s=t.authToken)==null?void 0:s.slice(0,10)}...
23
- ${(o=t.authToken)==null?void 0:o.slice(-10)}`})});const D=yield ic.init(b),R=new Hn(b,D);return F(c=R,bu,jg).call(c,t),R})}static setupContext(t,e,i,n){var r,s;const o=Pr.createContext(t,e),c=L(L({},nw),e==null?void 0:e.modules);return o.setValue("peerId",t),o.setValue("modules",c),o.setValue("sdkName","web-core"),o.setValue("meetingId",i),o.setValue("apiBase",n.apiBase),o.setValue("baseURI",n.baseURI),o.setValue("userId",n.participantId),o.setValue("organizationId",n.orgId),o.setValue("authToken",e.authToken),o.setValue("overrides",(r=e.overrides)!=null?r:{}),o.setValue("env",rw({baseURI:n.baseURI})),o.setValue("defaults",e.defaults||{audio:!0,video:!0}),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",wi(e.cachedUserDetails)),o.setValue("sdkVersion","3.1.0-staging.4"),(s=e.modules)!=null&&s.experimental_audio_playback&&o.setValue("audioPlayback",new $O),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,at);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){var e;Wg.cleanup(),a(this,tr).getValue("peerSessionStore").reset(),(e=a(this,tr).getValue("roomSocketHandler"))==null||e.cleanup();const{selfController:i}=a(this,at);return i.leaveRoom(t)})}get participants(){var t;return(t=a(this,at).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,at).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,at).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,at).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,at).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,at).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,at).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Vc))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,at).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,at).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,at).stageController)==null?void 0:t.stage}get stores(){return a(this,at).storesManager}get audio(){return a(this,tr).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,at).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)})}},at=new WeakMap,Vc=new WeakMap,tr=new WeakMap,bu=new WeakSet,jg=function(t){v(this,Vc,wl.init(a(this,tr),this,t))},Hg);Il([gt("0002"),Gn.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Hn.prototype,"join",1);Il([gt("0003")],Hn.prototype,"leave",1);Il([gt("0001"),Gn.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Hn,"init",1);Hn=Il([gt("0000")],Hn);const Oy=Hn;exports.RTKSelfMedia=Yv;exports.default=Oy;
23
+ ${(o=t.authToken)==null?void 0:o.slice(-10)}`})});const D=yield ic.init(b),R=new Hn(b,D);return F(c=R,bu,jg).call(c,t),R})}static setupContext(t,e,i,n){var r,s;const o=Pr.createContext(t,e),c=L(L({},nw),e==null?void 0:e.modules);return o.setValue("peerId",t),o.setValue("modules",c),o.setValue("sdkName","web-core"),o.setValue("meetingId",i),o.setValue("apiBase",n.apiBase),o.setValue("baseURI",n.baseURI),o.setValue("userId",n.participantId),o.setValue("organizationId",n.orgId),o.setValue("authToken",e.authToken),o.setValue("overrides",(r=e.overrides)!=null?r:{}),o.setValue("env",rw({baseURI:n.baseURI})),o.setValue("defaults",e.defaults||{audio:!0,video:!0}),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",wi(e.cachedUserDetails)),o.setValue("sdkVersion","3.1.0-staging.5"),(s=e.modules)!=null&&s.experimentalAudioPlayback&&o.setValue("audioPlayback",new $O),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,at);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){var e;Wg.cleanup(),a(this,tr).getValue("peerSessionStore").reset(),(e=a(this,tr).getValue("roomSocketHandler"))==null||e.cleanup();const{selfController:i}=a(this,at);return i.leaveRoom(t)})}get participants(){var t;return(t=a(this,at).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,at).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,at).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,at).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,at).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,at).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,at).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Vc))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,at).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,at).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,at).stageController)==null?void 0:t.stage}get stores(){return a(this,at).storesManager}get audio(){return a(this,tr).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,at).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)})}},at=new WeakMap,Vc=new WeakMap,tr=new WeakMap,bu=new WeakSet,jg=function(t){v(this,Vc,wl.init(a(this,tr),this,t))},Hg);Il([gt("0002"),Gn.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Hn.prototype,"join",1);Il([gt("0003")],Hn.prototype,"leave",1);Il([gt("0001"),Gn.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Hn,"init",1);Hn=Il([gt("0000")],Hn);const Oy=Hn;exports.RTKSelfMedia=Yv;exports.default=Oy;
package/dist/index.d.ts CHANGED
@@ -4057,7 +4057,7 @@ interface Modules {
4057
4057
  staggered?: boolean;
4058
4058
  }[];
4059
4059
  };
4060
- experimental_audio_playback?: boolean;
4060
+ experimentalAudioPlayback?: boolean;
4061
4061
  }
4062
4062
  interface DefaultOptions {
4063
4063
  video?: boolean;
package/dist/index.es.js CHANGED
@@ -30030,7 +30030,7 @@ let Xr = (Dm = class {
30030
30030
  var c, d;
30031
30031
  const a = Xi.createContext(t, e), o = D(D({}, sC), e == null ? void 0 : e.modules);
30032
30032
  return a.setValue("peerId", t), a.setValue("modules", o), a.setValue("sdkName", "web-core"), a.setValue("meetingId", r), a.setValue("apiBase", i.apiBase), a.setValue("baseURI", i.baseURI), a.setValue("userId", i.participantId), a.setValue("organizationId", i.orgId), a.setValue("authToken", e.authToken), a.setValue("overrides", (c = e.overrides) != null ? c : {}), a.setValue("env", rC({ baseURI: i.baseURI })), a.setValue("defaults", e.defaults || { audio: true, video: true }), a.setValue("onError", e.onError || (() => {
30033
- })), a.setValue("cachedUserDetails", Cs(e.cachedUserDetails)), a.setValue("sdkVersion", "3.1.0-staging.4"), (d = e.modules) != null && d.experimental_audio_playback && a.setValue("audioPlayback", new BD()), a;
30033
+ })), a.setValue("cachedUserDetails", Cs(e.cachedUserDetails)), a.setValue("sdkVersion", "3.1.0-staging.5"), (d = e.modules) != null && d.experimentalAudioPlayback && a.setValue("audioPlayback", new BD()), a;
30034
30034
  }
30035
30035
  join() {
30036
30036
  return l(this, null, function* () {
package/dist/index.rn.js CHANGED
@@ -19,4 +19,4 @@ slogScale: ${r}, isVoice: ${n}, minEnergy: ${a(this,Pn)},
19
19
  maxEnergy: ${a(this,mr)}`),r===-1/0||i<1e-6?{energy:0,isVoice:!1}:((!a(this,Pn)||r<a(this,Pn))&&v(this,Pn,r),(!a(this,mr)||r>a(this,mr))&&v(this,mr,r),{energy:(r-a(this,Pn))/(a(this,mr)-a(this,Pn))*10||0,isVoice:n})},Sd=new WeakSet,Ih=function(t){return t<5},Ch=new WeakSet,ly=function(t=a(this,Ls)){var e;if(!a(this,Bi)||!t){Y.hasFeature(ie.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&l.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,Bi)}`);return}const i={producerId:a(this,Bi),energy:Math.round(t),silent:F(e=Qd,Sd,Ih).call(e,t)};v(this,xo,i.silent),this.reportRequest(i)},au=new WeakSet,bg=function(t){const e=Math.log10(t);return Math.round(e)},f(Ph,Sd),f(Ph,au);const tO=(t=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const i=new window.MediaStreamTrackGenerator({kind:"audio"}),n=i.writable.getWriter(),r=48e3,s=128,o=1;let c=0,d=null;const h=()=>u(void 0,null,function*(){try{const g=new Float32Array(s*o),y=new window.AudioData({format:"f32",sampleRate:r,numberOfFrames:s,numberOfChannels:o,timestamp:c,data:g});c+=s/r*1e6,yield n.ready,yield n.write(y)}catch(g){d&&clearInterval(d),n.releaseLock(),i.writable.abort()}});d=window.setInterval(h,100);const p=new MediaStream([i]).getAudioTracks()[0];return p.addEventListener("ended",()=>{d&&clearInterval(d),n.releaseLock(),i.writable.abort()}),Object.assign(p,{fakeTracks:"fakeTracks:fakeAudioTrack"}),p.enabled=t,p}catch(i){}const e=window.AudioContext||window.webkitAudioContext;if(e)try{const i=new e;if(!i||i.state!=="running"||!i.destination)return;const n=i.createOscillator();n.frequency.value=0,n.type="sine";const r=i.createGain();r.gain.value=0,n.connect(r);const s=i.createMediaStreamDestination();r.connect(s),n.start();const o=s.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=t,o):void 0}catch(i){return}},iO=(t=!1)=>{var e,i;const n=new MediaStream().getVideoTracks()[0],r=document.createElement("canvas");r.height=(e=n==null?void 0:n.getSettings().height)!=null?e:720,r.width=(i=n==null?void 0:n.getSettings().width)!=null?i:1280;const s=r.getContext("2d");s.fillStyle="black",s.fillRect(0,0,r.width,r.height),setInterval(()=>{s.fillStyle="black",s.fillRect(0,0,r.width,r.height)},1e3);const o=r.captureStream().getVideoTracks()[0];return Object.assign(o,{fakeTracks:"fakeTracks:fakeVideoTrack"}),o.enabled=t,o};var nO=Object.defineProperty,rO=Object.getOwnPropertyDescriptor,fe=(t,e,i,n)=>{for(var r=n>1?void 0:n?rO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&nO(e,i,r),r};const jt=["video/VP9","video/VP8"];var Mc,Ac,yt,z,Ja,Gi,At,is,ns,rs,Dc,pi,fn,Ka,ss,as,Dt,Ht,Xn,os,ou,_g,cu,wg,du,Ig,Oc,lu,uu,hu,Cg,pu,Pg,mu,Rg,gu,Mg,lt,St,cs,za,fu,Ag,vu,Dg,yu,Og;const uy=(hu=class{constructor(t,e,i){f(this,Xn),f(this,ou),f(this,cu),f(this,du),f(this,Oc),f(this,pu),f(this,mu),f(this,gu),f(this,lt),f(this,cs),f(this,fu),f(this,vu),f(this,yu),m(this,"context"),m(this,"authToken"),m(this,"e2ee"),f(this,Mc,void 0),f(this,Ac,void 0),f(this,yt,void 0),f(this,z,void 0),f(this,Ja,void 0),f(this,Gi,void 0),f(this,At,void 0),f(this,is,void 0),f(this,ns,void 0),f(this,rs,void 0),f(this,Dc,void 0),f(this,pi,null),f(this,fn,void 0),f(this,Ka,void 0),f(this,ss,void 0),f(this,as,void 0),f(this,Dt,void 0),f(this,Ht,void 0);var n,r;this.context=t;const{socket:s}=i;this.mediaJoined=!1,v(this,ss,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,as,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,Gi,e),v(this,yt,s),v(this,is,!1),v(this,z,new XD(t,s,e)),v(this,At,a(this,z).events),v(this,fn,new Set),v(this,Dt,new Map),v(this,ns,!1),v(this,rs,new eh),e===Le.CF&&!navigator.isReactNative&&v(this,Ht,new Ph(a(this,z).socketHandler.audioActivity.bind(a(this,z).socketHandler))),this.e2ee=(r=(n=t.getValue("modules").e2ee)==null?void 0:n.enabled)!=null?r:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),v(this,Dc,Zh(()=>u(this,null,function*(){if(!a(this,Xn,os).mediaJoinAttempted)return;const{roomJoined:o}=yield this.joinRoom(a(this,Ac),a(this,Mc),!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 mediaJoined(){return a(this,Xn,os).mediaJoined}set mediaJoined(t){a(this,Xn,os).mediaJoined=t}reset(){a(this,z).closeAllProducers(),a(this,z).closeAllConsumers(),a(this,Dt).clear(),a(this,fn).clear(),v(this,pi,null),a(this,rs).stop(),a(this,z).stopAllTransports(),a(this,z).reset(),v(this,rs,new eh)}joinRoom(t,e){return u(this,arguments,function*(i,n,r=!1,s=!1,o={}){a(this,Xn,os).mediaJoinAttempted=!0,v(this,is,!0),r&&this.reset();try{return yield a(this,rs).push(()=>F(this,ou,_g).call(this,i,n,s,o),"joinRoom")}catch(c){return l.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,n,r=!1,s={}){return a(this,pi)?a(this,pi):(v(this,pi,(()=>u(this,null,function*(){try{yield F(this,Oc,lu).call(this,i,n,r,s)}catch(o){throw v(this,pi,null),o}}))()),a(this,pi))})}getConsumers(){return a(this,z).consumers}leaveRoom(){return u(this,null,function*(){var t;a(this,z).stopAllTransports(),v(this,ns,!1),a(this,Xn,os).mediaJoinAttempted=!1;const e={closeRoom:!1};try{const i=yield a(this,yt).sendMessagePromise(a(this,At).leaveRoom,tI.toBinary(e));(t=HI.fromBinary(i.payload))!=null&&t.closed||l.warn("weird state on peer closed and should not happen")}catch(i){l.error("error on sending leave room request",{error:i})}J.callEnded(),S.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,z).createConsumers(t)})}closeConsumers(t){return u(this,null,function*(){if(!t.length)return;const e=t.reduce((i,n)=>{const r=a(this,z).producerIdToConsumerIdMap.get(n.producerId);return r?(i.push(r),i):(l.warn(`consumer not found in close consumers: ${n.producerId}`),i)},[]);yield a(this,z).closeConsumers(e)})}_shareWebcam(t,e){return u(this,null,function*(){const i=e==="video/VP9"?ke.WEBCAM:ke.WEBCAM_BACKUP,n=F(this,lt,St).call(this,i);if(n){const p=yield n;if(a(this,z).producers.has(p)){const g=a(this,z).producers.get(p);if(!g.closed)return yield g.replaceTrack({track:t}),yield this.resumeWebcam(i),t;yield this.disableWebcam(e)}return this._shareWebcam(t,e)}const r=[e].concat(jt.filter(p=>p!==e)),s=F(this,yu,Og).call(this,t,r),o=Ws(this.context,"disableSimulcast"),c=a(this,Gi)===Le.CF?ie.ENABLE_CF_SIMULCAST:ie.ENABLE_HIVE_SIMULCAST;!o&&Y.hasFeature(c)?(l.info(`Simulcast enabled for SFU: ${a(this,Gi)}`),s.encodings=B1(t)):l.info(`Simulcast disabled for webcam producer, SFU: ${a(this,Gi)}`),Y.hasFeature(ie.TRACK_HINT)&&(s.track.contentHint=Y.getValue(ie.TRACK_HINT));const d=()=>{l.info("Disabling video due to the producer closure"),a(this,Dt).delete(i)},h=a(this,z).createProducer(s,d);return F(this,cs,za).call(this,i,h.then(p=>p.id)),h.then(p=>p.track)})}shareWebcam(t){return u(this,null,function*(){var e;if(t===void 0)return null;const i=(e=Y.getValue(ie.FORCE_VIDEO_CODEC))==null?void 0:e.toString();if(i)return l.debug(`Calling _shareWebcam with forced video codec: ${i}`),this._shareWebcam(t,i);const n=jt.filter(r=>{var s,o;return((o=(s=a(this,Ja).sender)==null?void 0:s.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===r))>=0&&a(this,as).get(r).size>0});return n.length===0&&n.push(jt[0]),yield Promise.all(n.map(r=>(l.debug(`Calling _shareWebcam with video codec: ${r}`),this._shareWebcam(t,r)))),t})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:i}=t;if(e===void 0)return;const n={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Re.isElectron()},stopTracks:!1},r=()=>{l.info("Disabling screenShare due to the producer closure"),a(this,Dt).delete(ke.SCREENSHARE_VIDEO),a(this,Dt).delete(ke.SCREENSHARE_AUDIO)},s=a(this,z).createProducer(n,r);F(this,cs,za).call(this,ke.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:Re.isElectron()},stopTracks:!1,zeroRtpOnPause:a(this,Gi)!==Le.CF},d=()=>{};o=a(this,z).createProducer(c,d),F(this,cs,za).call(this,ke.SCREENSHARE_AUDIO,o.then(h=>h.id))}yield Promise.all([s,o||Promise.resolve()]),J.screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new xt("track undefined");const e=F(this,lt,St).call(this,ke.MIC);if(e){const s=yield e;if(a(this,z).producers.has(s)){const o=a(this,z).producers.get(s);if(!o.closed){yield o.replaceTrack({track:t}),yield this.resumeMic(),a(this,Ht)&&(a(this,Ht).audioTrack=t,a(this,Ht).producerId=s,a(this,Ht).start());return}yield a(this,z).closeProducer(s,{stopTrack:!1})}yield this.shareMic(t);return}const i=F(this,vu,Dg).call(this,t),n=()=>{a(this,Dt).delete(ke.MIC)},r=a(this,z).createProducer(i,n);F(this,cs,za).call(this,ke.MIC,r.then(s=>s.id)),yield r.then(s=>{a(this,Ht)&&(a(this,Ht).audioTrack=s.track,a(this,Ht).producerId=s.id,a(this,Ht).start())})}catch(e){throw new w(e)}})}pauseMic(){return u(this,null,function*(){var t;const e=yield F(this,lt,St).call(this,ke.MIC),i=a(this,z).producers.get(e);if(!i){l.error("pauseMic::could_not_find_mic_producer");return}if(i.paused){l.info("pauseMic::mic_producer_already_paused");return}i.pause(),(t=a(this,Ht))==null||t.stop();const n={producerId:i.id,pause:!0};a(this,yt).sendMessage(a(this,At).toggleProducer,lc.toBinary(n))})}pauseWebcam(){return u(this,null,function*(){const t=yield F(this,lt,St).call(this,ke.WEBCAM),e=yield F(this,lt,St).call(this,ke.WEBCAM_BACKUP),i=a(this,z).producers.get(t),n=a(this,z).producers.get(e);if(!i&&!n){l.error("pauseWebcam::could_not_find_webcam_producer");return}const r=s=>{const o={producerId:s.id,pause:!0};a(this,yt).sendMessage(a(this,At).toggleProducer,lc.toBinary(o))};i&&(i.pause(),r(i)),n&&(n.pause(),r(n))})}resumeMic(){return u(this,null,function*(){const t=yield F(this,lt,St).call(this,ke.MIC),e=a(this,z).producers.get(t);if(!e){l.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){l.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,yt).sendMessage(a(this,At).toggleProducer,lc.toBinary(i))})}resumeWebcam(){return u(this,arguments,function*(t=ke.WEBCAM){const e=yield F(this,lt,St).call(this,t),i=a(this,z).producers.get(e);if(!i){l.error("resumeWebcam::could_not_find_webcam_producer");return}if(!i.paused){l.info("resumeWebcam::webcam_producer_already_resumed");return}i.resume(),i.appData.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,i);const n={producerId:i.id,pause:!1};a(this,yt).sendMessage(a(this,At).toggleProducer,lc.toBinary(n))})}disableWebcam(t){return u(this,null,function*(){const e=t==="video/VP9"?ke.WEBCAM:ke.WEBCAM_BACKUP,i=yield F(this,lt,St).call(this,e);F(this,fu,Ag).call(this,e),i&&(yield a(this,z).closeProducer(i))})}disableMic(){return u(this,null,function*(){var t;const e=yield F(this,lt,St).call(this,ke.MIC);e&&(yield a(this,z).closeProducer(e)),(t=a(this,Ht))==null||t.stop(),a(this,Dt).delete(ke.MIC)})}disableScreenShare(){return u(this,null,function*(){l.info("screen_sharing_stopped"),J.screenShareStop();const t=yield F(this,lt,St).call(this,ke.SCREENSHARE_VIDEO),e=yield F(this,lt,St).call(this,ke.SCREENSHARE_AUDIO);t&&(yield a(this,z).closeProducer(t)),e&&(yield a(this,z).closeProducer(e)),a(this,fn).clear(),a(this,Dt).delete(ke.SCREENSHARE_VIDEO),a(this,Dt).delete(ke.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 F(this,lt,St).call(this,ke.WEBCAM),n=yield F(this,lt,St).call(this,ke.WEBCAM_BACKUP);yield a(this,z).closeProducer(i,{stopTrack:!1}),yield a(this,z).closeProducer(n,{stopTrack:!1}),this.shareWebcam(t)}if(e){const i=yield F(this,lt,St).call(this,ke.SCREENSHARE_VIDEO);yield a(this,z).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,z).socketHandler.changeDisplayName(i)))throw new Error("failed to change display name!")})}kick(t){const e={peerIds:[t]};a(this,z).socketHandler.kickPeer(e)}kickAll(){a(this,z).socketHandler.kickAll()}muteAll(t){return u(this,null,function*(){if(!(yield a(this,z).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield a(this,z).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield a(this,z).socketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield a(this,z).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,yt).sendMessagePromise(a(this,At).globalPinPeer,gI.toBinary(e))}catch(i){l.error("Error in pinning peer:",{error:i})}})}validateScreenShare(t){return this.peerId===t.peerId&&a(this,z).producers.get(t.producerId)&&a(this,fn).add(t.consumerPeerId),a(this,fn).size}switchConsumersToLayer(t,e){return u(this,null,function*(){const i=t.map(n=>this.getConsumers().get(n));a(this,z).switchConsumersToLayer(i,e)})}handleSocketEvents(){return u(this,null,function*(){a(this,yt).on(a(this,At).peerProducerCreateBroadcast,({payload:t})=>{var e,i;if(this.mediaJoined)try{const{participantId:n,producerState:r}=SC.fromBinary(t);if(n===this.peerId)return;if(r!=null&&r.mimeType||(r.mimeType=r.kind===Wi.AUDIO?"audio/opus":"video/VP8"),r.kind===Wi.VIDEO&&!r.screenShare&&((i=(e=a(this,Ja).receiver)==null?void 0:e.video)==null?void 0:i.codecs.findIndex(s=>s.mimeType===jt[0]))>=0&&a(this,ss).get(jt[0]).has(n)&&r.mimeType!==jt[0]){l.warn(`Ignoring producer: ${r.producerId}`);return}l.info(`producer created broadcast: ${n}, producer state: ${r}`),this.context.getValue("peerSessionStore").emit(P.NEW_PRODUCER,{peerId:n,producer:G(L({},r),{kind:r.kind===Wi.AUDIO?"audio":"video",producingPeerId:n})})}catch(n){l.error("error in peer-producer-create-broadcast",{error:n})}}),a(this,yt).on(a(this,At).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:i,producerState:{kind:n,pause:r,producerId:s}}=bm.fromBinary(t),o=n===Wi.AUDIO?"audio":"video";if(l.info(`producer toggle broadcast: ${e}, producerId: ${s}, kind:${o}, paused:${r} payload: ${JSON.stringify(bm.fromBinary(t))}`),e===this.peerId&&i!==this.peerId&&r&&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:r,kind:o}),Array.from(this.getConsumers().values()).filter(c=>c.producerId===s).forEach(c=>{c.paused!==r&&(l.debug(`consumer state mismatched for ${c.id}. updating consumer pause state ${c.paused} to ${r}`),r?(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){l.error("error in producer toggle broadcast handler",{error:e})}}),a(this,yt).on(a(this,At).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=xu.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),a(this,fn).delete(e),a(this,z).consumers.forEach(i=>{i.peerId===e&&i.close()}),this.context.getValue("peerSessionStore").emit(P.PEER_CLOSED,{id:e})}catch(e){l.error("error in peer left broadcast",{error:e})}}),a(this,yt).on(a(this,At).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:i}}=kC.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(P.PRODUCER_CLOSED,{peerId:e,producerId:i});const n=a(this,z).producerIdToConsumerIdMap.get(i);if(!n){l.warn(`no consumer found for producer:${i}`);return}l.info(`closing consumer ${n}, producer id: ${i}`),a(this,z).closeConsumer(n).then(()=>{l.info(`closed consumer: ${n}`),a(this,z).producerIdToConsumerIdMap.delete(i),this.context.getValue("peerSessionStore").emit(P.CONSUMER_CLOSED,{id:n})}).catch(r=>{l.error("error closing consumer",{error:r})})}catch(e){l.error("error on producer close broadcast",{error:e})}}),a(this,yt).on(a(this,At).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,is)&&!a(this,ns)||(l.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_DISCONNECTED),a(this,Dc).call(this))})})}handleCallstatsEvents(){J.onConsumerScore(t=>{t.forEach((e,i)=>{const n=a(this,z).consumers.get(i);n&&this.context.getValue("peerSessionStore").emit(P.CONSUMER_SCORE_UPDATE,{id:i,kind:n.kind,peerId:n.peerId,score:e.score,scoreStats:e})})}),J.onProducerScore(t=>{t.forEach((e,i)=>{const n=Array.from(a(this,z).producers.values()).find(r=>r.id===i);n&&this.context.getValue("peerSessionStore").emit(P.PRODUCER_SCORE_UPDATE,{id:i,kind:n.kind,appData:n.appData,score:e.score,scoreStats:e})})})}handlePeerCapabilities(t,e){var i,n,r,s;for(let o=0;o<=jt.length;o+=1){const c=jt[o];if(((n=(i=e==null?void 0:e.receiver)==null?void 0:i.video)==null?void 0:n.codecs.findIndex(d=>d.mimeType===c))>=0||o===jt.length-1){a(this,as).get(c).add(t);break}}for(let o=0;o<=jt.length;o+=1){const c=jt[o];if(((s=(r=e==null?void 0:e.sender)==null?void 0:r.video)==null?void 0:s.codecs.findIndex(d=>d.mimeType===c))>=0||o===jt.length-1){a(this,ss).get(c).add(t);break}}}handlePeerLeaving(t){Y.hasFeature(ie.FORCE_VIDEO_CODEC)||(a(this,ss).forEach(e=>e.delete(t)),a(this,as).forEach((e,i)=>{e.delete(t),!(e.size!==0||i===jt[0])&&this.disableWebcam(i)}))}},Mc=new WeakMap,Ac=new WeakMap,yt=new WeakMap,z=new WeakMap,Ja=new WeakMap,Gi=new WeakMap,At=new WeakMap,is=new WeakMap,ns=new WeakMap,rs=new WeakMap,Dc=new WeakMap,pi=new WeakMap,fn=new WeakMap,Ka=new WeakMap,ss=new WeakMap,as=new WeakMap,Dt=new WeakMap,Ht=new WeakMap,Xn=new WeakSet,os=function(){return this.context.getValue("connectionHandler")},ou=new WeakSet,_g=function(t,e,i,n){return u(this,null,function*(){v(this,Ac,t);try{return a(this,pi)?yield a(this,pi):yield F(this,Oc,lu).call(this,t,e,i,n),F(this,du,Ig).call(this,e),{roomJoined:yield F(this,cu,wg).call(this)}}catch(r){return l.error("Failed to complete room join",{error:r}),{roomJoined:!1}}finally{v(this,pi,null)}})},cu=new WeakSet,wg=function(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:t}=yield a(this,z).socketHandler.notifySelfJoinComplete();return v(this,Mc,t.roomUuid),v(this,ns,!0),v(this,is,!1),!0}catch(t){return l.error("Error completing room join",{error:t}),this.mediaJoined=!1,!1}})},du=new WeakSet,Ig=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:G(L({},Re.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};J.roomJoined(e)}catch(e){l.error("Error reporting room joined analytics",{error:e})}},0)},Oc=new WeakSet,lu=function(t,e,i,n){return u(this,null,function*(){var r,s;try{(s=a(this,Ka))!=null||v(this,Ka,F(r=uy,uu,Cg).call(r));const o=F(this,pu,Pg).call(this);yield F(this,mu,Rg).call(this,t,e,i,o),yield a(this,z).setupTransports({send:!0,recv:!0}),yield F(this,gu,Mg).call(this,n)}catch(o){throw l.error("Failed to initialize connection",{error:o}),o}})},uu=new WeakSet,Cg=function(){const{ipInfo:t}=ht();if(!(t!=null&&t.loc))return;const[e,i]=t.loc.split(",").map(parseFloat);return{latitude:e,longitude:i}},pu=new WeakSet,Pg=function(){var t;const e=(t=Y.getValue(ie.FORCE_VIDEO_CODEC))==null?void 0:t.toString(),i=FD(e);return v(this,Ja,i),i},mu=new WeakSet,Rg=function(t,e,i,n){return u(this,null,function*(){yield Yv((r,s)=>u(this,null,function*(){if(!a(this,yt).isConnected){s(new Error("Socket is not connected"));return}r>0&&l.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${r}`});try{yield a(this,z).socketHandler.joinRoom(e,t,n,i,a(this,Ka))}catch(o){throw l.error("Failed to send joinRoom message after retries",{error:o}),o}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:Y.hasFeature(ie.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3})})},gu=new WeakSet,Mg=function(t){return u(this,null,function*(){if(!(a(this,Gi)===Le.HIVE||!Y.hasFeature(ie.PRECREATE_PRODUCERS)||!t))try{const e=[];if(t.canProduceVideo===q.Allowed&&e.push(this.shareWebcam(iO(!0))),t.canProduceAudio===q.Allowed){const i=tO(!0);i&&e.push(this.shareMic(i))}e.length>0&&(yield Promise.all(e))}catch(e){l.warn("Failed to precreate producers",{error:e})}})},lt=new WeakSet,St=function(t){return a(this,Dt).get(t)},cs=new WeakSet,za=function(t,e){return a(this,Dt).set(t,e)},fu=new WeakSet,Ag=function(t){return a(this,Dt).delete(t)},vu=new WeakSet,Dg=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:a(this,Gi)!==Le.CF}},yu=new WeakSet,Og=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}},f(hu,uu),hu);let he=uy;fe([S.trace("MediaNodeClient.reset",{country:S.location.country})],he.prototype,"reset",1);fe([S.trace("MediaNodeClient.joinRoom")],he.prototype,"joinRoom",1);fe([S.trace("MediaNodeClient.leaveRoom")],he.prototype,"leaveRoom",1);fe([S.trace("MediaNodeClient.activatePeers")],he.prototype,"activatePeers",1);fe([S.trace("MediaNodeClient.createConsumers")],he.prototype,"createConsumers",1);fe([S.trace("MediaNodeClient.closeConsumers")],he.prototype,"closeConsumers",1);fe([S.trace("MediaNodeClient._shareWebcam")],he.prototype,"_shareWebcam",1);fe([S.trace("MediaNodeClient.shareWebcam")],he.prototype,"shareWebcam",1);fe([S.trace("MediaNodeClient.shareScreen")],he.prototype,"shareScreen",1);fe([S.trace("MediaNodeClient.shareMic")],he.prototype,"shareMic",1);fe([S.trace("MediaNodeClient.pauseMic")],he.prototype,"pauseMic",1);fe([S.trace("MediaNodeClient.pauseWebcam")],he.prototype,"pauseWebcam",1);fe([S.trace("MediaNodeClient.resumeMic")],he.prototype,"resumeMic",1);fe([S.trace("MediaNodeClient.resumeWebcam")],he.prototype,"resumeWebcam",1);fe([S.trace("MediaNodeClient.disableWebcam")],he.prototype,"disableWebcam",1);fe([S.trace("HiveClient.disableMic")],he.prototype,"disableMic",1);fe([S.trace("HiveClient.disableScreenShare")],he.prototype,"disableScreenShare",1);fe([S.trace("MediaNodeClient.muteSelf")],he.prototype,"muteSelf",1);fe([S.trace("MediaNodeClient.resetVideoProducers")],he.prototype,"resetVideoProducers",1);fe([S.trace("MediaNodeClient.changeDisplayName")],he.prototype,"changeDisplayName",1);fe([S.trace("MediaNodeClient.kickPeer")],he.prototype,"kick",1);fe([S.trace("MediaNodeClient.kickAllPeers")],he.prototype,"kickAll",1);fe([S.trace("MediaNodeClient.muteAll")],he.prototype,"muteAll",1);fe([S.trace("MediaNodeClient.muteAllVideo")],he.prototype,"muteAllVideo",1);fe([S.trace("MediaNodeClient.disableAudio")],he.prototype,"disableAudio",1);fe([S.trace("MediaNodeClient.disableVideo")],he.prototype,"disableVideo",1);fe([S.trace("MediaNodeClient.pinPeer")],he.prototype,"pinPeer",1);fe([S.trace("MediaNodeClient.validateScreenShare")],he.prototype,"validateScreenShare",1);function hy(t,e,i){const n=t.getValue("roomNodeClient");if(n){if(n)return n;throw new Error("Room node client already set up.")}const r=new he(t,e,i);return t.setValue("roomNodeClient",r),r}function py(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch(i){l.error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var sO=Object.defineProperty,aO=Object.getOwnPropertyDescriptor,Wr=(t,e,i,n)=>{for(var r=n>1?void 0:n?aO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&sO(e,i,r),r},Zn,Oi,de,Ot,qt,Ng;const my=(Ng=class{constructor(t,e,i,n){f(this,Ot),m(this,"self"),m(this,"authToken"),f(this,Zn,void 0),m(this,"viewType"),f(this,Oi,void 0),f(this,de,void 0);const{socket:r}=i,s=t.getValue("authToken");this.self=e,v(this,de,t),this.viewType=n,this.authToken=s,v(this,Zn,r),v(this,Oi,i),e.config.viewType!==Ut.Chat&&this.setupEvents()}get peerId(){return a(this,de).getValue("peerId")}get mediaJoined(){return a(this,de).getValue("connectionHandler").mediaJoined}static init(t,e,i,n,r){return u(this,null,function*(){const s=ht(),o=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield rt.__init__(t,i,n,r,r.name,c);if(navigator.product!=="ReactNative"){const h=!Y.hasFeature(ie.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const p=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(p)}),J.devices("AUDIO",p==null?void 0:p.filter(g=>g.kind==="audioinput")),J.devices("VIDEO",p==null?void 0:p.filter(g=>g.kind==="videoinput")),J.devices("SPEAKER",p==null?void 0:p.filter(g=>g.kind==="audiooutput")),l.info("Callstats:: initializing");try{yield J.initialize({peerId:o,engineName:Re.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:Y.getAllFlags(),logger:l,apiHostnames:pv(t),skipConnectivityChecks:h}),l.info("Callstats:: initialized")}catch(g){l.error("Callstats:: initialization failed",{error:g})}}),0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new my(t,d,e,r.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:i,permissions:n,audioEnabled:r,videoEnabled:s,screenShareEnabled:o,screenShareTracks:c}=this.self;if(n.canProduceAudio===q.Allowed&&r)try{yield a(this,Ot,qt).shareMic(e),this.self.audioEnabled||a(this,Ot,qt).pauseMic()}catch(d){this.self.disableAudio()}if(n.canProduceVideo===q.Allowed&&s)try{const d=yield a(this,Ot,qt).shareWebcam(i);d&&d.id!==i.id&&Y.hasFeature(ie.EXP_RESHARE)&&(yield a(this,Ot,qt).shareWebcam(d)),this.self.videoEnabled||a(this,Ot,qt).pauseWebcam()}catch(d){this.self.disableVideo()}if(n.canProduceScreenshare===q.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(){l.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(l.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){l.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(l.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){l.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(t){return u(this,null,function*(){J.callEnded(),a(this,Ot,qt).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){a(this,de).getValue("peerSessionStore").on(P.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),a(this,de).getValue("peerSessionStore").on(P.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,de).getValue("peerSessionStore").on(P.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,de).getValue("peerSessionStore").on(P.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,de).getValue("peerSessionStore").on(P.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),a(this,de).getValue("peerSessionStore").on(P.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&Y.hasFeature(ie.REFRESH_ID_ON_DISCONNECTION)&&(e=qs()),a(this,Zn).updateURL(e),S.resetPeerId(e),ht().setHeader("dyte-tracing-id",e),Pr.remapContext(e,a(this,de)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,de).getValue("peerSessionStore").on(P.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Oi).on(B.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Oi).on(Hc.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&a(this,de).getValue("peerSessionStore").emit(P.UPDATE_PERMISSIONS,e.patch)})}),a(this,Oi).on(B.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Oi).on(B.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Oi).on(B.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,de).getValue("peerSessionStore").onAsync(P.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,de).getValue("peerSessionStore").on(P.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:i,scoreStats:n})=>{var r;const s=(r=i==null?void 0:i.screenShare)!=null?r:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:s,score:t,participantId:this.self.id,scoreStats:n})}),a(this,de).getValue("peerSessionStore").on(P.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),J.audioOff())})),a(this,de).getValue("peerSessionStore").on(P.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),J.videoOff())})),a(this,de).getValue("peerSessionStore").onAsync(P.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,de).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,Oi).joinRoom(this.self);a(this,Oi).socket.flush();const i=sp(e.stageType);if(a(this,de).setValue("stageStatus",i,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),a(this,de).notify("stageStatus")}catch(e){throw l.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,Zn))==null||e.disconnect()}catch(n){l.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),a(this,de).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),a(this,de).notify("stageStatus");try{(i=a(this,Zn))==null||i.disconnect()}catch(n){l.error("SelfController::leaveRoom::socketDisconnect")}py(a(this,de)),yield a(this,de).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:n,viewType:r,meetingId:s,stageStatus:o,roomNodeOptions:c}=a(this,de).getAllValues(),{sfu:d}=c;try{if(r===Ut.Livestream){if(o!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}hy(a(this,de),d,{socket:a(this,Zn),peerId:n})}const{canProduceAudio:h,canProduceVideo:p,canProduceScreenshare:g}=this.self.permissions,{roomJoined:y}=(i=yield(e=a(this,Ot,qt))==null?void 0:e.joinRoom(this.self.name,s,t,t,{canProduceAudio:h,canProduceVideo:p,canProduceScreenshare:g}))!=null?i:{};if(!y)return;o==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(h){throw l.error("Error:SelfController.mediaRoomJoin",{error:h}),new w("Error: could not join media room","0002")}})}leaveMediaRoom(t){return u(this,null,function*(){const e=a(this,de).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()})}},Zn=new WeakMap,Oi=new WeakMap,de=new WeakMap,Ot=new WeakSet,qt=function(){return a(this,de).getValue("roomNodeClient")},Ng);let $n=my;Wr([S.trace("SelfController.resetSelf")],$n.prototype,"resetSelf",1);Wr([S.trace("SelfController.setupEvents")],$n.prototype,"setupEvents",1);Wr([S.trace("SelfController.joinRoom")],$n.prototype,"joinRoom",1);Wr([S.trace("SelfController.leaveRoom")],$n.prototype,"leaveRoom",1);Wr([S.trace("SelfController.joinMediaRoom")],$n.prototype,"joinMediaRoom",1);Wr([S.trace("SelfController.leaveMediaRoom")],$n.prototype,"leaveMediaRoom",1);Wr([S.trace("SelfController.init")],$n,"init",1);var Ed;class oO{constructor(e){f(this,Ed,void 0),v(this,Ed,e)}on(e,i){let n;e===B.roomPeerCount?n=Im.fromBinary.bind(Im):n=xm.fromBinary.bind(xm),a(this,Ed).on(e,({payload:r})=>{const s=n(r);return i(s)})}}Ed=new WeakMap;var Td;class cO{constructor(e){f(this,Td,void 0),v(this,Td,e)}on(e,i){let n,r;switch(e){case B.transcript:{n=Vl.fromBinary.bind(Vl),r=Vl.create();break}default:{l.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Td).on(e,({payload:s})=>{let o=r;try{o=n(s)}catch(c){l.error("chatSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}}Td=new WeakMap;var dO=Object.defineProperty,lO=Object.getOwnPropertyDescriptor,vp=(t,e,i,n)=>{for(var r=n>1?void 0:n?lO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&dO(e,i,r),r},Rn;class Tl{constructor(e){f(this,Rn,void 0),v(this,Rn,e)}getPolls(){return a(this,Rn).sendMessagePromise(Yi.getPolls)}createPoll(e,i,n=!1,r=!1){const s={anonymous:n,hideVotes:r,question:e,options:i};return a(this,Rn).sendMessage(Yi.createPoll,lA.toBinary(s))}votePoll(e,i){const n={index:i,pollId:e};return a(this,Rn).sendMessage(Yi.votePoll,hA.toBinary(n))}on(e,i){let n,r;switch(e){case Yi.updatePoll:case Yi.createPoll:case Yi.votePoll:{n=jl.fromBinary.bind(jl),r=jl.create();break}}a(this,Rn).on(e,({payload:s})=>{let o=r;try{o=n(s)}catch(c){l.error("pollSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}removeListeners(e){a(this,Rn).removeListeners(e)}}Rn=new WeakMap;vp([S.trace("PollSocketHandler.getPolls")],Tl.prototype,"getPolls",1);vp([S.trace("PollSocketHandler.createPoll")],Tl.prototype,"createPoll",1);vp([S.trace("PollSocketHandler.votePoll")],Tl.prototype,"votePoll",1);var uO=Object.defineProperty,hO=Object.getOwnPropertyDescriptor,pO=(t,e,i,n)=>{for(var r=n>1?void 0:n?hO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&uO(e,i,r),r},Vi;class gy{constructor(e,i){m(this,"socket"),f(this,Vi,void 0),v(this,Vi,e),this.socket=i,this.handleSocketEvents(),a(this,Vi).setValue("roomSocketHandler",this)}cleanup(){return u(this,null,function*(){var e;try{(e=this.socket)==null||e.disconnect()}catch(i){l.error("roomSocketHandler::cleanup")}})}joinRoom(e){return u(this,null,function*(){var i;this.socket.joinAttempted=!0;const n={capabilities:[],peer:{displayName:(i=e.name)!=null?i:"Participant",customParticipantId:e.customParticipantId,peerId:e.id,userId:e.userId,displayPictureUrl:e.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(B.joinRoom,QC.toBinary(n));try{const{peer:s}=ls.fromBinary((yield r).payload);a(this,Vi).getValue("connectionHandler").socketJoined=!0,a(this,Vi).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_ROOM_JOINED,{peer:s});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:h}]=yield Promise.all([o,c]);return a(this,Vi).getValue("peerSessionStore").emit(P.ROOM_STATE,d),a(this,Vi).getValue("peerSessionStore").emit(P.SOCKET_PEERS,h),{peer:s}}catch(s){throw l.error("RoomSocketHandler.joinRoom.failed",{error:s}),new w("Error: RoomSocketHandler.joinRoom failed.","0002",s)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return LP.fromBinary((yield this.socket.sendMessagePromise(B.getAllAddedParticipants)).payload).participants.map(e=>{var i=e,{id:n}=i,r=al(i,["id"]);return G(L({},r),{userId:n})})}catch(e){return[]}})}getRoomPeers(e,i,n){return u(this,null,function*(){let r;try{const s={seachQuery:e,limit:i,offset:n},o=yield this.socket.sendMessagePromise(B.getRoomPeersInfo,WC.toBinary(s));r=xl.fromBinary(o.payload)}catch(s){l.error("getRoomPeers::binary_decode_error",{error:s})}return r})}getRoomPeersNonPaginated(){return u(this,null,function*(){let e;try{const i=yield this.socket.sendMessagePromise(B.getRoomPeersInfo);e=xl.fromBinary(i.payload)}catch(i){l.error("getRoomJoinedPeers::binary_decode_error",{error:i})}return e})}getStagePeers(){return u(this,null,function*(){let e;try{const i=yield this.socket.sendMessagePromise(B.getRoomPeersInfo);e=xl.fromBinary(i.payload)}catch(i){l.error("getRoomJoinedPeers::binary_decode_error",{error:i})}return e})}getPeerInfo(e){return u(this,null,function*(){let i;try{const n=yield this.socket.sendMessagePromise(B.getPeerInfo,_v.toBinary({peerId:e}));i=ls.fromBinary(n.payload)}catch(n){l.error("getPeerInfo::binary_decode_error",{error:n})}return i})}getRoomState(){return u(this,null,function*(){let e=Cm.create();try{const i=yield this.socket.sendMessagePromise(B.getRoomInfo);e=Cm.fromBinary(i.payload)}catch(i){l.error("getRoomState::binary_decode_error",{error:i})}return e})}getRoomStageState(){return u(this,null,function*(){let e=Am.create();try{const i=yield this.socket.sendMessagePromise(B.getRoomStageState);e=Am.fromBinary(i.payload)}catch(i){l.error("getRoomStageState::binary_decode_error",{error:i})}return e})}broadcastMessage(e,i){return u(this,null,function*(){const n={type:e,payload:new TextEncoder().encode(JSON.stringify(i)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(B.broadcastMessage,ga.toBinary(n))})}broadcastToMeetings(e,i,n){return u(this,null,function*(){const r={type:e,payload:new TextEncoder().encode(JSON.stringify(n)),timestamp:Date.now(),ids:i,broadcastType:1};return this.socket.sendMessagePromise(B.broadcastToEntity,ga.toBinary(r))})}broadcastToPeers(e,i,n){return u(this,null,function*(){const r={type:e,payload:new TextEncoder().encode(JSON.stringify(n)),timestamp:Date.now(),ids:i,broadcastType:0};return this.socket.sendMessage(B.broadcastToEntity,ga.toBinary(r))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(B.leaveRoom,ZC.toBinary({}))})}kick(e){return u(this,null,function*(){const i={peerIds:[e]};this.socket.sendMessage(B.kick,Iv.toBinary(i))})}kickAll(e=!1){return u(this,null,function*(){const i={propagateKickAcrossRooms:e};this.socket.sendMessage(B.kickAll,Tv.toBinary(i))})}getWaitingRoomRequests(){this.socket.sendMessage(B.getWaitingRoomRequests)}acceptWaitingRoomRequest(e){const i={userIds:e};this.socket.sendMessage(B.acceptWaitingRoomRequests,WP.toBinary(i))}rejectWaitingRoomRequest(e){const i={userIds:e};this.socket.sendMessage(B.denyWaitingRoomRequests,HP.toBinary(i))}updatePermissions(e,i){return u(this,null,function*(){const n={updatePeersPresets:[]};return e.forEach(r=>{n.updatePeersPresets.push({userIds:r,patch:i})}),this.socket.sendMessagePromise(Hc.updateUserPreset,yR.toBinary(n))})}handleSocketEvents(){this.socket.on(B.broadcastMessage,({payload:e})=>{try{const i=ga.fromBinary(e);a(this,Vi).getValue("peerSessionStore").emit(P.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(i.payload)),type:i.type,timestamp:i.timestamp})}catch(i){l.error("failed to decode broadcast message:",i)}}),this.socket.on(B.broadcastToEntity,({payload:e})=>{try{const i=ga.fromBinary(e);a(this,Vi).getValue("peerSessionStore").emit(P.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(i.payload)),type:i.type,timestamp:i.timestamp})}catch(i){l.error("failed to decode peer broadcast message:",i)}})}on(e,i){let n,r;switch(e){case B.joinRoom:case B.leaveRoom:case B.kick:case B.kickAll:{n=ls.fromBinary.bind(ls),r=ls.create();break}case B.getWaitingRoomRequests:{n=(s,o)=>s?Mm.fromBinary(s,o):{requests:[]},r=Mm.create();break}case B.recordingPaused:case B.recordingStarted:case B.recordingStopped:{n=Bm.fromBinary.bind(Bm);break}case Hc.updateUserPreset:{n=Dm.fromBinary.bind(Dm);break}case bi.peerJoinedBroadcast:case ai.peerJoinedBroadcast:{n=Tm.fromBinary.bind(Tm);break}case bi.selfJoinComplete:case ai.selfJoinComplete:{n=Vu.fromBinary.bind(Vu);break}case bi.globalPeerPinBroadcast:case ai.globalPeerPinBroadcast:{n=_m.fromBinary.bind(_m);break}case bi.selectedPeer:case ai.selectedPeer:{n=Lu.fromBinary.bind(Lu);break}case bi.selectedPeerDiff:case ai.selectedPeerDiff:{n=Em.fromBinary.bind(Em);break}case bi.leaveRoom:case ai.leaveRoom:{n=xu.fromBinary.bind(xu);break}}this.socket.on(e,({payload:s})=>{let o=r;if(!n)return i(void 0);try{o=n(s)}catch(c){l.error("roomSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}getUserPermissions(e){return u(this,null,function*(){const i={userIds:[e]};try{const n=yield this.socket.sendMessagePromise(Hc.getUserPresets,uR.toBinary(i)),r=gR.fromBinary(n.payload).peerPresets[0],s=new TextDecoder().decode(r.preset),o=JSON.parse(s).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(n){throw l.error("Error in getting user preset",{error:n}),n}})}}Vi=new WeakMap;pO([S.trace("RoomSocketHandler.joinRoom")],gy.prototype,"joinRoom",1);var Jt;class mO{constructor(e){f(this,Jt,void 0),v(this,Jt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield a(this,Jt).sendMessagePromise(B.getStageRequests);return e?Wl.fromBinary(e):{stageRequests:[]}})}requestAccess(){a(this,Jt).sendMessage(B.requestStageAccess)}cancelRequestAccess(){a(this,Jt).sendMessage(B.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,Jt).sendMessage(B.grantStageAccess,eA.toBinary(i))})}denyAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,Jt).sendMessage(B.denyStageAccess,iA.toBinary(i))})}joinStage(){return a(this,Jt).sendMessagePromise(B.joinStage,void 0,void 0,B.peerStageStatusUpdate)}leaveStage(e){const i={userIds:[e]};return a(this,Jt).sendMessagePromise(B.leaveStage,Fm.toBinary(i),void 0,B.peerStageStatusUpdate)}kick(e){const i={userIds:e};return a(this,Jt).sendMessagePromise(B.leaveStage,Fm.toBinary(i))}on(e,i){let n;switch(e){case B.grantStageAccess:case B.denyStageAccess:{n=void 0;break}case B.getStagePeers:{n=Um.fromBinary.bind(Um);break}case B.getStageRequests:case B.requestStageAccess:case B.cancelStageRequest:{n=Wl.fromBinary.bind(Wl);break}case B.peerStageStatusUpdate:{n=wm.fromBinary.bind(wm);break}}a(this,Jt).on(e,({payload:r,id:s})=>{if(!r||!n)return i(void 0,s);const o=n(r);return i(o,s)})}getPeerInfo(e){return u(this,null,function*(){const i=yield a(this,Jt).sendMessagePromise(B.getPeerInfo,_v.toBinary({peerId:e}));return ls.fromBinary(i.payload)})}}Jt=new WeakMap;var tt;class gO{constructor(e){f(this,tt,void 0),v(this,tt,e)}addPlugin(e,i){a(this,tt).sendMessage(K.addPlugin,vM.toBinary({pluginId:e,staggered:i}))}removePlugin(e){a(this,tt).sendMessage(K.removePlugin,SM.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield a(this,tt).sendMessagePromise(K.getPlugins);return e?jM.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,i,n){const r={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(i))};a(this,tt).sendMessage(K.customPluginEventToRoom,RM.toBinary(r),n)}customPluginEventToPeers(e,i,n,r){const s={pluginId:e,peerIds:i,pluginData:new TextEncoder().encode(JSON.stringify(n))};a(this,tt).sendMessage(K.customPluginEventToPeers,AM.toBinary(s),r)}enablePluginForRoom(e,i){a(this,tt).sendMessage(K.enablePluginForRoom,TM.toBinary({pluginId:e}),i)}enablePluginForPeers(e,i,n){a(this,tt).sendMessage(K.enablePluginForPeers,wM.toBinary({pluginId:e,peerIds:i}),n)}disablePluginForRoom(e,i){a(this,tt).sendMessage(K.disablePluginForRoom,bM.toBinary({pluginId:e}),i)}disablePluginForPeers(e,i,n){a(this,tt).sendMessage(K.disablePluginForPeers,CM.toBinary({pluginId:e,peerIds:i}),n)}storeInsertKeys(e,i,n,r){const s={pluginId:e,storeName:i,insertKeys:n.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,tt).sendMessage(K.storeInsertKeys,Om.toBinary(s),r)}storeGetKeys(e,i,n,r){const s={pluginId:e,storeName:i,getKeys:n.map(o=>({storeKey:o.key}))};a(this,tt).sendMessage(K.storeGetKeys,LM.toBinary(s),r)}storeDeleteKeys(e,i,n,r){const s={pluginId:e,storeName:i,deleteKeys:n.map(o=>({storeKey:o.key}))};a(this,tt).sendMessage(K.storeDeleteKeys,xM.toBinary(s),r)}storeDelete(e,i,n){a(this,tt).sendMessage(K.storeDelete,FM.toBinary({pluginId:e,storeName:i}),n)}getPluginDataOld(e,i){l.info("getPluginDataOld",{plugin:{id:e,storeName:i}})}storePluginDataOld(e,i,n){const r={pluginId:e,storeName:i,insertKeys:[{storeKey:n.key,payload:new TextEncoder().encode(JSON.stringify(n))}]};a(this,tt).sendMessage(K.storeInsertKeys,Om.toBinary(r))}on(e,i){let n;switch(e){case K.addPlugin:case K.enablePluginForPeers:case K.enablePluginForRoom:{n=Wu.fromBinary.bind(Wu);break}case K.removePlugin:case K.disablePluginForPeers:case K.disablePluginForRoom:{n=Nm.fromBinary.bind(Nm);break}case K.customPluginEventToPeers:case K.customPluginEventToRoom:{n=Vm.fromBinary.bind(Vm);break}case K.storeInsertKeys:case K.storeGetKeys:case K.storeDeleteKeys:case K.storeDelete:{n=Lm.fromBinary.bind(Lm);break}}a(this,tt).on(e,({payload:r,id:s})=>{const o=n(r);return i(o,s)})}}tt=new WeakMap;var fO=Object.defineProperty,vO=(t,e,i)=>e in t?fO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,yO=(t,e,i)=>(vO(t,typeof e!="symbol"?e+"":e,i),i),yp=(t,e,i)=>{if(!e.has(t))throw TypeError("Cannot "+i)},N=(t,e,i)=>(yp(t,e,"read from private field"),i?i.call(t):e.get(t)),Ce=(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)},ue=(t,e,i,n)=>(yp(t,e,"write to private field"),n?n.call(t,i):e.set(t,i),i),De=(t,e,i)=>(yp(t,e,"access private method"),i),Xd={},SO={get exports(){return Xd},set exports(t){Xd=t}},Vs=typeof Reflect=="object"?Reflect:null,Lg=Vs&&typeof Vs.apply=="function"?Vs.apply:function(t,e,i){return Function.prototype.apply.call(t,e,i)},kd;Vs&&typeof Vs.ownKeys=="function"?kd=Vs.ownKeys:Object.getOwnPropertySymbols?kd=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:kd=function(t){return Object.getOwnPropertyNames(t)};function EO(t){console&&console.warn&&console.warn(t)}var fy=Number.isNaN||function(t){return t!==t};function ge(){ge.init.call(this)}SO.exports=ge;Xd.once=_O;ge.EventEmitter=ge;ge.prototype._events=void 0;ge.prototype._eventsCount=0;ge.prototype._maxListeners=void 0;var Vg=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(ge,"defaultMaxListeners",{enumerable:!0,get:function(){return Vg},set:function(t){if(typeof t!="number"||t<0||fy(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Vg=t}});ge.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};ge.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||fy(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?ge.defaultMaxListeners:t._maxListeners}ge.prototype.getMaxListeners=function(){return vy(this)};ge.prototype.emit=function(t){for(var e=[],i=1;i<arguments.length;i++)e.push(arguments[i]);var n=t==="error",r=this._events;if(r!==void 0)n=n&&r.error===void 0;else if(!n)return!1;if(n){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=r[t];if(c===void 0)return!1;if(typeof c=="function")Lg(c,this,e);else for(var d=c.length,h=ky(c,d),i=0;i<d;++i)Lg(h[i],this,e);return!0};function yy(t,e,i,n){var r,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]=n?[i,o]:[o,i]:n?o.unshift(i):o.push(i),r=vy(t),r>0&&o.length>r&&!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,EO(c)}return t}ge.prototype.addListener=function(t,e){return yy(this,t,e,!1)};ge.prototype.on=ge.prototype.addListener;ge.prototype.prependListener=function(t,e){return yy(this,t,e,!0)};function TO(){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 Sy(t,e,i){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:i},r=TO.bind(n);return r.listener=i,n.wrapFn=r,r}ge.prototype.once=function(t,e){return kl(e),this.on(t,Sy(this,t,e)),this};ge.prototype.prependOnceListener=function(t,e){return kl(e),this.prependListener(t,Sy(this,t,e)),this};ge.prototype.removeListener=function(t,e){var i,n,r,s,o;if(kl(e),n=this._events,n===void 0)return this;if(i=n[t],i===void 0)return this;if(i===e||i.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,i.listener||e));else if(typeof i!="function"){for(r=-1,s=i.length-1;s>=0;s--)if(i[s]===e||i[s].listener===e){o=i[s].listener,r=s;break}if(r<0)return this;r===0?i.shift():kO(i,r),i.length===1&&(n[t]=i[0]),n.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this};ge.prototype.off=ge.prototype.removeListener;ge.prototype.removeAllListeners=function(t){var e,i,n;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 r=Object.keys(i),s;for(n=0;n<r.length;++n)s=r[n],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(n=e.length-1;n>=0;n--)this.removeListener(t,e[n]);return this};function Ey(t,e,i){var n=t._events;if(n===void 0)return[];var r=n[e];return r===void 0?[]:typeof r=="function"?i?[r.listener||r]:[r]:i?bO(r):ky(r,r.length)}ge.prototype.listeners=function(t){return Ey(this,t,!0)};ge.prototype.rawListeners=function(t){return Ey(this,t,!1)};ge.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Ty.call(t,e)};ge.prototype.listenerCount=Ty;function Ty(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}ge.prototype.eventNames=function(){return this._eventsCount>0?kd(this._events):[]};function ky(t,e){for(var i=new Array(e),n=0;n<e;++n)i[n]=t[n];return i}function kO(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function bO(t){for(var e=new Array(t.length),i=0;i<e.length;++i)e[i]=t[i].listener||t[i];return e}function _O(t,e){return new Promise(function(i,n){function r(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",r),i([].slice.call(arguments))}by(t,e,s,{once:!0}),e!=="error"&&wO(t,r,{once:!0})})}function wO(t,e,i){typeof t.on=="function"&&by(t,"error",e,i)}function by(t,e,i,n){if(typeof t.on=="function")n.once?t.once(e,i):t.on(e,i);else if(typeof t.addEventListener=="function")t.addEventListener(e,function r(s){n.once&&t.removeEventListener(e,r),i(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}class IO extends E{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 xg=new IO;class _y{static encode(e){return xg.toBinary(e)}static decode(e){return xg.fromBinary(new Uint8Array(e))}}function CO(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var Mn;class PO{constructor(e={}){yO(this,"opts"),Ce(this,Mn,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},ue(this,Mn,0)}wait(){return u(this,null,function*(){ue(this,Mn,N(this,Mn)+1);const e=CO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*xS(2,N(this,Mn))));yield new Promise(i=>{setTimeout(i,e)})})}getAttempts(){return N(this,Mn)}reset(){ue(this,Mn,0)}}Mn=new WeakMap;const vn={debug:0,info:1,warn:2,error:3};var gr,fr;class RO{constructor(e){Ce(this,gr,void 0),Ce(this,fr,void 0),ue(this,gr,console),ue(this,fr,e)}debug(...e){vn[N(this,fr)]>vn.debug||N(this,gr).debug("[Sockrates]:",...e)}info(...e){vn[N(this,fr)]>vn.info||N(this,gr).info("[Sockrates]:",...e)}warn(...e){vn[N(this,fr)]>vn.warn||N(this,gr).warn("[Sockrates]:",...e)}error(...e){vn[N(this,fr)]>vn.error||N(this,gr).error("[Sockrates]:",...e)}}gr=new WeakMap,fr=new WeakMap;var wy=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(wy||{});const MO="2",AO="3";var Fe,Ts,Ae,Ge,An,it,tn,Un,ki,ks,zi,Rh,Iy,_o,bd,Mh,Cy,Ah,Ug,Zd,Dh,Oh,Py,Uo,_d,Fo,el,tl,Nh,xs,Bo,Wo,il;class DO{constructor(e,i){var n;Ce(this,Rh),Ce(this,_o),Ce(this,Mh),Ce(this,Ah),Ce(this,Zd),Ce(this,Oh),Ce(this,Uo),Ce(this,Fo),Ce(this,tl),Ce(this,xs),Ce(this,Wo),Ce(this,Fe,void 0),Ce(this,Ts,void 0),Ce(this,Ae,void 0),Ce(this,Ge,void 0),Ce(this,An,void 0),Ce(this,it,void 0),Ce(this,tn,void 0),Ce(this,Un,void 0),Ce(this,ki,void 0),Ce(this,ks,void 0),Ce(this,zi,void 0);var r,s,o,c,d,h,p,g,y;ue(this,Ts,e),ue(this,An,[]),ue(this,it,new Xd),ue(this,tn,!0),ue(this,ki,!1),ue(this,Ae,i!=null?i:{}),(r=N(this,Ae)).autoReconnect!=null||(r.autoReconnect=!0),(s=N(this,Ae)).retryConnectionInterval!=null||(s.retryConnectionInterval=1e3),(o=N(this,Ae)).pingTimeout!=null||(o.pingTimeout=3e4),(c=N(this,Ae)).connectionTimeout!=null||(c.connectionTimeout=5e3),(d=N(this,Ae)).debug!=null||(d.debug=!0),(h=N(this,Ae)).maxReconnectionAttempts!=null||(h.maxReconnectionAttempts=10),(p=N(this,Ae)).disconnectOnPingTimeout!=null||(p.disconnectOnPingTimeout=!0),(g=N(this,Ae)).queueOnDisconnect!=null||(g.queueOnDisconnect=!1),(y=N(this,Ae)).flushOnReconnect!=null||(y.flushOnReconnect=!1),ue(this,Un,{code:void 0,reason:void 0}),ue(this,Ge,(n=N(this,Ae).logger)!=null?n:new RO(N(this,Ae).debug?"debug":"info")),ue(this,zi,new PO)}get readyState(){var e;return(e=N(this,Fe))==null?void 0:e.readyState}get url(){return N(this,Ts)}updateURL(e){ue(this,Ts,e),De(this,Oh,Py).call(this)}get config(){return N(this,Ae)}get sendQueue(){return N(this,An)}flush(){if(!N(this,Ae).queueOnDisconnect)return!1;const e=[];return N(this,An).forEach(i=>{this.send(i.event,i.id,i.payload,i.metadata)||e.push(i)}),ue(this,An,e),N(this,An)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){N(this,Ge).debug("Websocket was already connecting or connected.");return}if(N(this,tn)!==!1)return new Promise((i,n)=>{De(this,xs,Bo).call(this),De(this,Wo,il).call(this);try{ue(this,Fe,new WebSocket(De(this,Rh,Iy).call(this,N(this,Ts)))),N(this,Fe).binaryType="arraybuffer",N(this,Ge).debug("Connecting");const r=setTimeout(()=>{N(this,Ge).debug("Connection timeout. Closing socket"),ue(this,tn,!0),De(this,Wo,il).call(this),N(this,Fe).close(3001,"Connection Timeout"),N(this,Ae).autoReconnect&&!N(this,ki)&&(N(this,it).emit("reconnecting"),De(this,Uo,_d).call(this)),n(new Error("Connection timed out!"))},N(this,Ae).connectionTimeout);N(this,Fe).onopen=()=>{N(this,Ge).debug(`Ready State: ${wy[N(this,Fe).readyState]}`),r&&clearTimeout(r),De(this,tl,Nh).call(this),ue(this,Un,{code:void 0,reason:void 0}),N(this,it).emit("connected"),N(this,Ae).flushOnReconnect&&this.flush(),i()},N(this,Fe).onclose=s=>{try{r&&clearTimeout(r);const{code:o,reason:c}=s;n(c),N(this,Ge).debug("Socket closed. Close event:",{event:s}),N(this,Ge).debug(`Connection closed code: ${o}`),N(this,Ge).debug(`Connection closed reason: ${c}`),N(this,ki)||De(this,Zd,Dh).call(this,o,c)}catch(o){De(this,_o,bd).call(this,o)}},N(this,Fe).onerror=s=>{De(this,_o,bd).call(this,s)},N(this,Fe).onmessage=s=>De(this,Mh,Cy).call(this,s)}catch(r){De(this,_o,bd).call(this,r,n)}})})}send(e,i,n,r){const s={event:e,id:i,payload:n,metadata:r};if(N(this,Ae).queueOnDisconnect&&(!N(this,Fe)||N(this,Fe).readyState!==1))return N(this,Ge).debug("Queuing message since socket is not connected!",s),N(this,An).push(s),!1;const o=_y.encode(s);return De(this,Fo,el).call(this,o)}emit(e,i,n,r){return this.send(e,i,n,r)}sendRaw(e){return De(this,Fo,el).call(this,e)}receive(e,i){return N(this,it).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,it).on(e,i);return}this.receive(e,i)}removeAllListeners(){N(this,it).removeAllListeners()}removeReceiver(e,i){this.removeListener(e,i)}removeListener(e,i){N(this,it).removeListener(e.toString(),i)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){N(this,it).listeners(e.toString()).map(i=>this.removeListener(e,i))}disconnect(){ue(this,tn,!1),De(this,xs,Bo).call(this),this.removeAllListeners(),ue(this,Un,{code:1e3,reason:"Sockrates disconnect method called"}),N(this,Fe).close(1e3,"Sockrates disconnect method called.")}}Fe=new WeakMap,Ts=new WeakMap,Ae=new WeakMap,Ge=new WeakMap,An=new WeakMap,it=new WeakMap,tn=new WeakMap,Un=new WeakMap,ki=new WeakMap,ks=new WeakMap,zi=new WeakMap,Rh=new WeakSet,Iy=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)://.")},_o=new WeakSet,bd=function(t,e){N(this,Ge).error("Error:",{error:t}),N(this,it).emit("errored",{error:t}),e==null||e(t)},Mh=new WeakSet,Cy=function(t){if(De(this,tl,Nh).call(this),t.data===MO){N(this,Ge).debug("Received ping from server"),De(this,Fo,el).call(this,AO);return}const e=_y.decode(t.data),{id:i,payload:n}=e;N(this,Ge).debug("Received message",{event:e.event,messageID:i}),N(this,it).emit(e.event.toString(),{id:i,payload:n})},Ah=new WeakSet,Ug=function(){return N(this,Fe).readyState===1},Zd=new WeakSet,Dh=function(t,e){ue(this,Un,{reason:e,code:t}),N(this,it).emit("disconnected",{code:t,reason:e})},Oh=new WeakSet,Py=function(){const{reason:t,code:e}=N(this,Un);e&&e!==1e3&&N(this,tn)&&N(this,Ae).autoReconnect&&!N(this,ki)&&(N(this,Ge).debug(`Triggering reconnection due to ${t}.`),N(this,it).emit("reconnecting"),De(this,Uo,_d).call(this))},Uo=new WeakSet,_d=function(t=!0){return u(this,null,function*(){if(t&&N(this,ki)){N(this,Ge).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(N(this,ki)||N(this,zi).reset(),N(this,Ae).maxReconnectionAttempts!==null&&N(this,zi).getAttempts()>=N(this,Ae).maxReconnectionAttempts){N(this,it).emit("failed"),ue(this,ki,!1);return}ue(this,ki,!0),De(this,Wo,il).call(this),De(this,xs,Bo).call(this);try{if(yield N(this,zi).wait(),N(this,tn)===!1)return;if(N(this,Ge).debug(`Reconnection attempt ${N(this,zi).getAttempts()}`),N(this,it).emit("reconnectAttempt",{attempt:N(this,zi).getAttempts()}),yield this.connect(),!De(this,Ah,Ug).call(this))throw Error("Reconnect Failed");ue(this,ki,!1),ue(this,Un,{code:void 0,reason:void 0}),N(this,it).emit("reconnected")}catch(e){N(this,Ge).debug("Failed to reconnect."),N(this,it).emit("reconnectFailure",{attempt:N(this,zi).getAttempts()}),De(this,Uo,_d).call(this,!1)}})},Fo=new WeakSet,el=function(t){try{return N(this,Fe).send(t),!0}catch(e){return N(this,Ge).error(e.message),!1}},tl=new WeakSet,Nh=function(){this.config.disconnectOnPingTimeout&&(N(this,Ge).debug("Resetting ping timeout"),De(this,xs,Bo).call(this),ue(this,ks,setTimeout(()=>{var t;N(this,Ge).debug("Disconnecting the socket due to ping timeout"),ue(this,tn,!0);const e=3002,i="Ping timeout";(t=N(this,Fe))==null||t.close(e,i),De(this,Zd,Dh).call(this,e,i)},N(this,Ae).pingTimeout)))},xs=new WeakSet,Bo=function(){N(this,ks)&&(clearTimeout(N(this,ks)),ue(this,ks,void 0))},Wo=new WeakSet,il=function(){N(this,Fe)&&(N(this,Fe).onopen=void 0,N(this,Fe).onerror=void 0,N(this,Fe).onmessage=void 0,N(this,Fe).onclose=void 0)};var OO=Object.defineProperty,NO=Object.getOwnPropertyDescriptor,bl=(t,e,i,n)=>{for(var r=n>1?void 0:n?NO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&OO(e,i,r),r};const Fg=65535,LO=3e3;var er,Ve,xe,We,mi,ii,Nc,Su,Lc,Eu,Bg;const Ry=(Bg=class{constructor(t,{peerId:e,meetingId:i,authToken:n,capabilities:r}){f(this,xe),f(this,Nc),f(this,Lc),f(this,er,void 0),f(this,Ve,void 0),m(this,"roomName"),m(this,"authToken"),m(this,"capabilities"),f(this,mi,void 0),f(this,ii,void 0);var s;if(!e||!i||!n)throw new w("peerId, meetingId, or authToken can not be empty","0404");v(this,mi,void 0),v(this,ii,t),this.capabilities=r,this.roomName=i,this.authToken=n,v(this,er,F(this,Nc,Su).call(this,e)),v(this,Ve,new DO(a(this,er),{autoReconnect:!0,disconnectOnPingTimeout:(s=r.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:l})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,xe,We).socketJoinAttempted}set joinAttempted(t){a(this,xe,We).socketJoinAttempted=t}get peerId(){return a(this,ii).getValue("peerId")}updateURL(t){t!==this.peerId&&(v(this,er,F(this,Nc,Su).call(this,t)),l.debug("SocketService:: Connection URL updated.")),a(this,Ve).updateURL(a(this,er))}static getSocketEdgeDomain(t){return Os({servicePrefix:"socket-edge",baseURI:t})}get url(){return a(this,er)}connect(){return u(this,null,function*(){a(this,xe,We).socketJoinAttempted=!0,yield a(this,Ve).connect(),a(this,xe,We).socketJoinAttempted=!0,a(this,xe,We).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return u(this,null,function*(){a(this,xe,We).socketJoinAttempted=!1,a(this,Ve).disconnect(),a(this,xe,We).socketJoinAttempted=!0,a(this,xe,We).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 n={};return S.injectContext(n),a(this,Ve).send(t,i!=null?i:F(this,Lc,Eu).call(this),e,new TextEncoder().encode(JSON.stringify(n)))}sendMessagePromise(t,e,i,n){const r=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:r,protobuf:e,messageId:i,resp:n})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:i,messageId:n,resp:r}){const s=r!=null?r:t;return new Promise((o,c)=>{const d=(T,b)=>{a(this,Ve).removeListener(s,T),a(this,Ve).removeListener(Fg,b),a(this,Ve).removeListener(ai.errorResponse,b),a(this,Ve).removeListener(bi.errorResponse,b)},h=n!=null?n:F(this,Lc,Eu).call(this),p={};S.injectContext(p);const g=({id:T,payload:b})=>{if(h===T){let D;try{const R=OI.fromBinary(b);D=new Error(R.errorMessage)}catch(R){D=new Error("failed to parse error message",{cause:R});try{const V=NC.fromBinary(b);D=new Error(V.message)}catch(V){D=new Error("failed to parse error message",{cause:V})}}c(D),d(y,g)}},y=({id:T,payload:b})=>{h===T&&(o({id:T,payload:b}),d(y,g))};a(this,Ve).on(s,y),a(this,Ve).on(Fg,g),a(this,Ve).on(ai.errorResponse,g),a(this,Ve).on(bi.errorResponse,g),setTimeout(()=>{d(y,g),c(new Error(`request timeout for callback eventId:${t}`))},e),a(this,Ve).send(t,h,i,new TextEncoder().encode(JSON.stringify(p)))})}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*(){l.info("SocketService::Connected to socket-edge"),a(this,mi)&&(clearTimeout(a(this,mi)),v(this,mi,void 0)),a(this,xe,We).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var i;l.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:S.location.country});const{recv:n,send:r}=(i=a(this,xe,We).mediaState)!=null?i:{};n!=null&&n.state&&(n==null?void 0:n.state)!==Hs.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Hs.CONNECTED?a(this,ii).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,xe,We).joinAttempted}):v(this,mi,setTimeout(()=>{a(this,ii).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,xe,We).joinAttempted}),v(this,mi,void 0)},LO)),a(this,xe,We).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){l.info("SocketService::Reconnecting to socket-edge",{country:S.location.country}),a(this,xe,We).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){l.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),a(this,xe,We).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{l.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),a(this,xe,We).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){l.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,xe,We).mediaJoinAttempted}}),a(this,mi)&&(clearTimeout(a(this,mi)),v(this,mi,void 0)),a(this,ii).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,xe,We).mediaJoinAttempted}),a(this,xe,We).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){l.info("SocketService::Failed to connect to socket-edge",{country:S.location.country}),a(this,ii).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_FAILED),a(this,xe,We).updateSocketConnectionState("failed")}))}},er=new WeakMap,Ve=new WeakMap,xe=new WeakSet,We=function(){return a(this,ii).getValue("connectionHandler")},mi=new WeakMap,ii=new WeakMap,Nc=new WeakSet,Su=function(t){let e=Ry.getSocketEdgeDomain(a(this,ii).getValue("baseURI"));typeof Ws(a(this,ii),"socket_server_base")=="string"&&(e=Ws(a(this,ii),"socket_server_base"));const i=`wss://${e}`,n=new URL(`${i}/ws`),r=this.peerId,s=G(L({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},r!==t&&{oldPeerID:r}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>Bd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0});return Object.entries(s).forEach(([o,c])=>{n.searchParams.append(o,c.toString())}),n.href},Lc=new WeakSet,Eu=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Bg);let tc=Ry;bl([S.trace("SocketService.connect")],tc.prototype,"connect",1);bl([S.trace("SocketService.disconnect")],tc.prototype,"disconnect",1);bl([S.trace("SocketService.sendMessagePromise")],tc.prototype,"sendMessagePromise",1);bl([S.trace("SocketService.sendMessagePromiseWithTimeout")],tc.prototype,"sendMessagePromiseWithTimeout",1);const vr=class{static handleConnectedRoomsDumpRaw({payload:t}){var e;const i=oP.fromBinary(t),n=i.meetings.map(r=>{var s;return{id:r.id,title:r.title,participants:(s=r.participants)!=null?s:[]}});return{parentMeeting:{id:i.parentMeeting.id,title:i.parentMeeting.title,participants:(e=i.parentMeeting.participants)!=null?e:[]},meetings:n}}static handleTransferPeerRaw({payload:t}){const e=OP.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=wv.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return Rm.fromBinary(t).payloads.map(e=>({id:e.id,title:e.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return bP.fromBinary(t).payloads}static getConnectedRoomsDump(){return u(this,null,function*(){const t=yield vr.socketService.sendMessagePromise(B.getConnectedRoomsDump);return vr.handleConnectedRoomsDumpRaw(t)})}static createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield vr.socketService.sendMessagePromise(B.createConnectedRooms,uP.toBinary({payloads:t}));return Rm.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))})}static updateConnectedRooms(t){return u(this,null,function*(){})}static disableConnectedRooms(t){return u(this,null,function*(){const e=t.map(n=>({id:n})),i=yield vr.socketService.sendMessagePromise(B.deleteConnectedRooms,TP.toBinary({payloads:e}));return vr.handleConnectedRoomsDeletedRaw(i)})}static movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield vr.socketService.sendMessagePromise(B.movePeers,RP.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}})}};let Ne=vr;m(Ne,"socketService"),m(Ne,"currentMeetingId");var VO=Object.defineProperty,xO=Object.getOwnPropertyDescriptor,_l=(t,e,i,n)=>{for(var r=n>1?void 0:n?xO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&VO(e,i,r),r};const bs=class{constructor(t,e){m(this,"apiBase"),m(this,"selfController"),m(this,"pollController"),m(this,"chatController"),m(this,"metaController"),m(this,"storesManager"),m(this,"stageController"),m(this,"pluginController"),m(this,"internalsController"),m(this,"recordingController"),m(this,"livestreamController"),m(this,"participantController"),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}static init(t){return u(this,null,function*(){var e,i;const{peerId:n,apiBase:r,authToken:s,meetingId:o,organizationId:c,cachedUserDetails:d}=t.getAllValues();if(py(t),Re.isSupported()===!1)throw new w("Browser not supported","0010",!0);const h=GA(t,{authToken:s,baseURL:r,cachedUserDetails:d});h.setRoomName(o),h.setRoomUUID(o),h.setOrganizationId(c),h.setHeader("dyte-tracing-id",n),t.setValue("apiClient",h);const p=new C1(t);t.setValue("connectionHandler",p);const g=bs.createSocketService(t),y=g.connect(),T=h.getUserDetails(),b=h.getPlugins();let D=Le.HIVE,R,V="";try{yield bs.setupFlagsmith(t)}catch(ne){l.error("Failed to setup flagsmith",{error:ne})}try{yield y}catch(ne){l.error("[Controller]: Failed to connect to socket server:",{error:ne})}try{({sfu:D,meetingTitle:V}=yield h.getRoomNodeData()),R=yield T,l.info(`SFU ${D} is being used.`),t.setValue("presetName",R.preset.name),t.setValue("roomNodeOptions",{sfu:D})}catch(ne){l.error("Failed to get room metadata",{error:ne})}const j=uD.init(R.preset,!t.getValue("modules").theme),$=DD.init(t,j.viewType,R.preset.permissions),I=bs.setupControllers(g,t,R,b,V,j,$);f1(j)&&((e=bs.createRoomNodeClient(t,g).initializeConnection(R.participant.name,o,!1,$))==null||e.catch(ne=>{l.error("[Controller]: Failed to queue partial media room promise:",{error:ne})})),S.location.country=(i=h.ipInfo)==null?void 0:i.country;const{controllers:se}=yield I;return pw(),new bs(r,se)})}static setupFlagsmith(t){return u(this,null,function*(){var e;const{peerId:i,baseURI:n,overrides:r,meetingId:s,organizationId:o}=t.getAllValues(),c=hw(s),d=G(L({entity:Nu.PEER,clientId:o,isAnonUser:!o,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:c,roomName:s},Re.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const h=(e=r==null?void 0:r.whitelabelled_flags_endpoint)==null||e?Os({servicePrefix:"flags",baseURI:n}):"edge.api.flagsmith.com";yield Y.identify(`${Nu.PEER}_${i}`,JSON.parse(JSON.stringify(d)),!1,5e3,h,l),l.info("flagsmith::allFlags",{flags:JSON.stringify(Y.getAllFlags())},!0)}catch(h){l.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,i,n,r,s,o){return u(this,null,function*(){var c,d,h;const p=e.getValue("modules"),{participant:g}=i,y=e.getValue("defaults"),{sfu:T}=e.getValue("roomNodeOptions"),{viewType:b,mediaConstraints:{audio:D}}=s;e.setValue("viewType",b),e.setValue("defaults",L({mediaConfiguration:{audio:{enableHighBitrate:(c=D.enableHighBitrate)!=null?c:!1,enableStereo:(d=D.enableStereo)!=null?d:!1}}},y)),e.setValue("maxPreferredStreams",Re.isMobile()?s.maxVideoStreams.mobile:s.maxVideoStreams.desktop);let R,V,j,$,I,se,ne,ve;const Qe=new cO(t);Ne.socketService=t;const dt=new Tl(t),Rt=new oi(t),M=new mO(t),k=new gy(e,t),_=new gO(t),W=new oO(t),we=new Ar(t),pe=yield $n.init(e,k,g,o,s),U=yield xv.init(e,pe.self,k,Qe,r);if(p.participant&&(ve=new dn(e,pe.self,k,T)),(h=p.e2ee)!=null&&h.enabled&&p.e2ee.manager.init(l,e.getValue("peerSessionStore")),p.chat&&(V=yield nn.init(e,Rt,we,pe.self,ve.participants)),p.internals&&(I=yield op.init()),p.livestream&&s.viewType===Ut.Livestream&&Y.hasFeature(ie.LIVESTREAM)&&(ne=new $v(e,pe.self,W)),s.viewType!==Ut.Chat){if(p.poll&&(R=yield Ov.init(e,pe.self,dt)),p.recording&&(se=new Wv(e,pe.self,k)),p.stage&&(j=new Uv(e,M,k,pe.self,ve.participants)),p.plugin){if(!ve)throw new w("The plugin module cannot be initialized without the `participant` module","0102");const Be=yield n;$=yield Qo.init(e,Be,_,Rt,V==null?void 0:V.chat,pe.self,ve.participants,r)}if(p.pip){const Be=yield fw._init(e,pe.self);e.setValue("pip",Be)}}const C={storesManager:new SD(e,_),pollController:R,selfController:pe,metaController:U,chatController:V,stageController:j,pluginController:$,recordingController:se,internalsController:I,livestreamController:ne,participantController:ve};return{theme:s,permissions:o,controllers:C}})}static createRoomNodeClient(t,e){const{peerId:i,roomNodeOptions:n}=t.getAllValues(),{sfu:r}=n;return hy(t,r,{socket:e,peerId:i})}static createSocketService(t){const{peerId:e,meetingId:i,authToken:n}=t.getAllValues(),r=["PING"];return new tc(t,{peerId:e,meetingId:i,authToken:n,capabilities:r})}};let ic=bs;_l([S.trace("Controller.init")],ic,"init",1);_l([S.trace("setupFlagsmith")],ic,"setupFlagsmith",1);_l([S.trace("Controller.createRoomNodeClient")],ic,"createRoomNodeClient",1);_l([S.trace("Controller.createSocketService")],ic,"createSocketService",1);var UO=Object.defineProperty,FO=Object.getOwnPropertyDescriptor,BO=(t,e,i,n)=>{for(var r=n>1?void 0:n?FO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&UO(e,i,r),r},wd,Lh;class My extends Qt{constructor(e,i){super(),f(this,wd,void 0),m(this,"meetings",[]),m(this,"parentMeeting",null),f(this,Lh,void 0),v(this,Lh,e),v(this,wd,i.self)}get supportsConnectedMeetings(){return a(this,wd).id!==""}get isActive(){return this.meetings.length!==0}get currentMeetingId(){return Ne.currentMeetingId}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 Ne.getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield Ne.createConnectedRooms(e)).map(i=>({id:i.id,title:i.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield Ne.updateConnectedRooms(e.map(i=>({meetingId:i.id,title:i.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(r=>r.id)):Promise.resolve());return yield Promise.all(i),yield Ne.disableConnectedRooms(e)})}moveParticipants(e,i,n){return u(this,null,function*(){this.validateConnectedMeetingsAction();const r=yield Ne.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:n.map(s=>({id:s}))});return r.success&&this.moveSuccessHandler(e,i,n),r})}moveParticipantsWithCustomPreset(e,i,n){return u(this,null,function*(){this.validateConnectedMeetingsAction();const r=yield Ne.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:n});return r.success&&this.moveSuccessHandler(e,i,n.map(s=>s.id)),r})}moveSuccessHandler(e,i,n){const r=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(s=>s.participants)].forEach(s=>r.set(s.id,s)),i===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(n.map(s=>r.get(s)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(s=>!n.includes(s.id))),this.meetings=this.meetings.map(s=>{if(i===s.id){const o=s.participants.concat(n.map(c=>r.get(c)));return G(L({},s),{participants:o})}if(e===s.id){const o=s.participants.filter(c=>!n.includes(c.id));return G(L({},s),{participants:o})}return s})}}wd=new WeakMap,Lh=new WeakMap;BO([Ft({maxInvocations:60,period:60})],My.prototype,"getConnectedMeetings",1);var WO=Object.defineProperty,jO=Object.getOwnPropertyDescriptor,Sp=(t,e,i,n)=>{for(var r=n>1?void 0:n?jO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&WO(e,i,r),r},Ya,gi,Tu,ku;const Dn=(Tu=class{constructor(t,e,i){m(this,"connectedMeetings"),f(this,Ya,void 0),f(this,gi,void 0),f(this,ku,void 0),v(this,ku,t),v(this,Ya,i),this.connectedMeetings=new My(t,e),this.setCurrentMeeting(e)}static init(t,e,i){return Dn.instance||(Dn.instance=new Dn(t,e,i)),Dn.instance.connectedMeetings.supportsConnectedMeetings&&(Dn.instance.setupEvents(),e.self.once("roomJoined",()=>Dn.instance.getConnectedMeetings())),Dn.instance}setCurrentMeeting(t){v(this,gi,t),Ne.currentMeetingId=t.meta.meetingId}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){Ne.socketService&&(Ne.socketService.on(B.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),Ne.socketService.on(B.transferPeer,this.handleTransferPeer.bind(this)),Ne.socketService.on(B.movedPeer,this.handleMovedPeer.bind(this)),Ne.socketService.on(B.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),Ne.socketService.on(B.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this)))}handleTransferPeer(t){const e=Ne.handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:i}){var n,r,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.`);l.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",i);const c={video:a(this,gi).self.videoEnabled,audio:a(this,gi).self.audioEnabled};try{a(this,gi).self.cleanupEvents(),yield a(this,gi).leave("connected-meeting")}catch(h){l.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(r=(n=a(this,gi))==null?void 0:n.meta)==null?void 0:r.meetingId}`,{error:h})}Ne.socketService=void 0,l.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${i}`);const d=yield Dy.init(G(L({},a(this,Ya)),{cachedUserDetails:null,defaults:G(L(L({},a(this,Ya).defaults),c),{mediaHandler:a(this,gi).self}),authToken:e}));l.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(s=d==null?void 0:d.meta)==null?void 0:s.meetingId}`);try{const{hidden:h}=a(this,gi).self;d.self.setName(a(this,gi).self.name),yield d.join(),h&&d.self.hide()}catch(h){l.error("ConnectedMeetingsController.joinRoom",{error:h})}return l.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),this.setCurrentMeeting(d),d})}handleConnectedRoomsDump(t){const e=Ne.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 Ne.handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=Ne.handleConnectedRoomsUpdatedRaw(t),i=new Map;this.connectedMeetings.meetings.forEach(n=>{i.set(n.id,n)}),e.forEach(n=>{i.has(n.id)?i.get(n.id).title=n.title:i.set(n.id,G(L({},n),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(i.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=Ne.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})}},Ya=new WeakMap,gi=new WeakMap,ku=new WeakMap,m(Tu,"instance"),Tu);let wl=Dn;Sp([S.trace("ConnectedMeetingsController.getConnectedMeetings")],wl.prototype,"getConnectedMeetings",1);Sp([S.trace("ConnectedMeetingsController.setupEvents")],wl.prototype,"setupEvents",1);Sp([S.trace("ConnectedMeetingsController.switchMeeting")],wl.prototype,"switchMeeting",1);class HO{constructor(){m(this,"battery"),m(this,"init",()=>u(this,null,function*(){try{"getBattery"in navigator&&(this.battery=yield navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){l.error("Error getting battery",e)}})),m(this,"updateChargeInfo",()=>{var e;l.log(`Battery charging? ${(e=this.battery)!=null&&e.charging?"Yes":"No"}`)}),m(this,"updateLevelInfo",()=>{if(!this.battery){l.log("Battery level: Not known");return}l.log(`Battery level: ${this.battery.level*100}%`)}),m(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 Wg=new HO;function qO(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:n,participantId:r}=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://api.${s}`;return{meetingId:i,orgId:n,participantId:r,baseURI:s,apiBase:o}}catch(i){throw l.error("constants::decodeAuthToken",{error:i,debuggingHint:`Unable to decode auth token: ${t}`},!0),new w("Invalid auth token","0004")}}var yr,_s,ws,nl,Vh,Ay;class GO{constructor(){f(this,Vh),f(this,yr,new Audio),f(this,_s,new MediaStream),f(this,ws,new Map),f(this,nl,void 0),a(this,yr).srcObject=a(this,_s),a(this,yr).autoplay=!0}playTracks(e){return u(this,null,function*(){return e.forEach(i=>{a(this,ws).has(i.id)||(a(this,_s).addTrack(i),a(this,ws).set(i.id,i))}),this.play()})}setSpeakerDevice(e){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,yr).setSinkId(e)}removeTrack(e){const i=a(this,ws).get(e);i&&(a(this,_s).removeTrack(i),a(this,ws).delete(e))}play(){return u(this,null,function*(){return a(this,yr).srcObject=a(this,_s),a(this,yr).play().catch(e=>{F(this,Vh,Ay).call(this,e)})})}onError(e){v(this,nl,e)}}yr=new WeakMap,_s=new WeakMap,ws=new WeakMap,nl=new WeakMap,Vh=new WeakSet,Ay=function(t){var e;(e=a(this,nl))==null||e.call(this,t)};var Is;class $O extends GO{constructor(){super(),f(this,Is,void 0),v(this,Is,new Map)}addParticipantTrack(e,i){a(this,Is).set(e,i.id),this.playTracks([i])}removeParticipantTrack(e){const i=a(this,Is).get(e);i&&this.removeTrack(i),a(this,Is).delete(e)}}Is=new WeakMap;var JO=Object.defineProperty,KO=Object.getOwnPropertyDescriptor,Il=(t,e,i,n)=>{for(var r=n>1?void 0:n?KO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&JO(e,i,r),r},at,Vc,tr,bu,jg,Hg;let Hn=(Hg=class{constructor(t,e){f(this,bu),f(this,at,void 0),f(this,Vc,void 0),f(this,tr,void 0),v(this,tr,t),v(this,at,e)}static init(t){return u(this,null,function*(){var e,i,n,r,s,o,c;dw(),Re.init();const d=(i=(e=t==null?void 0:t.cachedUserDetails)==null?void 0:e.peerId)!=null?i:qs();Wg.init();const{authToken:h,baseURI:p}=t,g=qO(h,p),{meetingId:y}=g,T=al(g,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const b=Hn.setupContext(d,t,y,T);S.meetingMetadata.roomName=y,S.meetingMetadata.userId=T.participantId,S.meetingMetadata.organizationId=T.orgId,S.init(b,(r=(n=t.modules)==null?void 0:n.tracing)!=null?r:!0),l.info("DyteClient::init::options",{dyteClientInitOptions:G(L({},t),{authToken:`${(s=t.authToken)==null?void 0:s.slice(0,10)}...
22
- ${(o=t.authToken)==null?void 0:o.slice(-10)}`})});const D=yield ic.init(b),R=new Hn(b,D);return F(c=R,bu,jg).call(c,t),R})}static setupContext(t,e,i,n){var r,s;const o=Pr.createContext(t,e),c=L(L({},iw),e==null?void 0:e.modules);return o.setValue("peerId",t),o.setValue("modules",c),o.setValue("sdkName","web-core"),o.setValue("meetingId",i),o.setValue("apiBase",n.apiBase),o.setValue("baseURI",n.baseURI),o.setValue("userId",n.participantId),o.setValue("organizationId",n.orgId),o.setValue("authToken",e.authToken),o.setValue("overrides",(r=e.overrides)!=null?r:{}),o.setValue("env",nw({baseURI:n.baseURI})),o.setValue("defaults",e.defaults||{audio:!0,video:!0}),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",wi(e.cachedUserDetails)),o.setValue("sdkVersion","VERSION_PLACEHOLDER"),(s=e.modules)!=null&&s.experimental_audio_playback&&o.setValue("audioPlayback",new $O),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,at);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){var e;Wg.cleanup(),a(this,tr).getValue("peerSessionStore").reset(),(e=a(this,tr).getValue("roomSocketHandler"))==null||e.cleanup();const{selfController:i}=a(this,at);return i.leaveRoom(t)})}get participants(){var t;return(t=a(this,at).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,at).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,at).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,at).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,at).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,at).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,at).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Vc))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,at).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,at).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,at).stageController)==null?void 0:t.stage}get stores(){return a(this,at).storesManager}get audio(){return a(this,tr).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,at).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)})}},at=new WeakMap,Vc=new WeakMap,tr=new WeakMap,bu=new WeakSet,jg=function(t){v(this,Vc,wl.init(a(this,tr),this,t))},Hg);Il([gt("0002"),Gn.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Hn.prototype,"join",1);Il([gt("0003")],Hn.prototype,"leave",1);Il([gt("0001"),Gn.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Hn,"init",1);Hn=Il([gt("0000")],Hn);const Dy=Hn;module.exports=Dy;
22
+ ${(o=t.authToken)==null?void 0:o.slice(-10)}`})});const D=yield ic.init(b),R=new Hn(b,D);return F(c=R,bu,jg).call(c,t),R})}static setupContext(t,e,i,n){var r,s;const o=Pr.createContext(t,e),c=L(L({},iw),e==null?void 0:e.modules);return o.setValue("peerId",t),o.setValue("modules",c),o.setValue("sdkName","web-core"),o.setValue("meetingId",i),o.setValue("apiBase",n.apiBase),o.setValue("baseURI",n.baseURI),o.setValue("userId",n.participantId),o.setValue("organizationId",n.orgId),o.setValue("authToken",e.authToken),o.setValue("overrides",(r=e.overrides)!=null?r:{}),o.setValue("env",nw({baseURI:n.baseURI})),o.setValue("defaults",e.defaults||{audio:!0,video:!0}),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",wi(e.cachedUserDetails)),o.setValue("sdkVersion","VERSION_PLACEHOLDER"),(s=e.modules)!=null&&s.experimentalAudioPlayback&&o.setValue("audioPlayback",new $O),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,at);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){var e;Wg.cleanup(),a(this,tr).getValue("peerSessionStore").reset(),(e=a(this,tr).getValue("roomSocketHandler"))==null||e.cleanup();const{selfController:i}=a(this,at);return i.leaveRoom(t)})}get participants(){var t;return(t=a(this,at).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,at).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,at).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,at).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,at).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,at).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,at).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Vc))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,at).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,at).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,at).stageController)==null?void 0:t.stage}get stores(){return a(this,at).storesManager}get audio(){return a(this,tr).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,at).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)})}},at=new WeakMap,Vc=new WeakMap,tr=new WeakMap,bu=new WeakSet,jg=function(t){v(this,Vc,wl.init(a(this,tr),this,t))},Hg);Il([gt("0002"),Gn.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Hn.prototype,"join",1);Il([gt("0003")],Hn.prototype,"leave",1);Il([gt("0001"),Gn.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Hn,"init",1);Hn=Il([gt("0000")],Hn);const Dy=Hn;module.exports=Dy;
@@ -4021,7 +4021,7 @@ interface Modules {
4021
4021
  staggered?: boolean;
4022
4022
  }[];
4023
4023
  };
4024
- experimental_audio_playback?: boolean;
4024
+ experimentalAudioPlayback?: boolean;
4025
4025
  }
4026
4026
  interface DefaultOptions {
4027
4027
  video?: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/realtimekit",
3
- "version": "1.1.0-staging.4",
3
+ "version": "1.1.0-staging.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",