@cloudflare/realtimekit 2.0.4-staging.5 → 2.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.js +1 -1
- package/dist/dependencies.txt +1 -1
- package/dist/index.cjs.js +1 -1
- package/dist/index.es.js +1 -1
- package/dist/index.es5.js +1 -1
- package/dist/index.rn.js +1 -1
- package/package.json +3 -2
package/dist/browser.js
CHANGED
|
@@ -14,4 +14,4 @@ ${this.message}`;try{let d=n&&!!i;r&&r.endsWith("00")&&i&&(d=!0),d&&i.error("Cli
|
|
|
14
14
|
`).map(e=>Ni.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=Ht(),{transcript:e}=await t.getActiveTranscript();this.transcripts=Ni.parseTranscripts(e)}catch(t){}}async onTranscript(t){var r;const e=this.transcripts.filter(({peerId:i})=>i===t.peerId);if((r=e==null?void 0:e.at(-1))!=null&&r.isPartialTranscript){const i=e.at(-1);i.transcript=t.transcript,i.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",i);return}this.transcripts=[...this.transcripts,t],this.emit("transcript",t)}},jo=new WeakMap,Vv);PS([y.trace("Ai.getActiveTranscript")],Ni.prototype,"getActiveTranscript",1),Ni=PS([pt("0000")],Ni);var dD=Object.defineProperty,lD=Object.getOwnPropertyDescriptor,uD=(s,t,e,r)=>{for(var i=r>1?void 0:r?lD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&dD(t,e,i),i};const sp=(xv=class{constructor(s,t,e,r,i,n){p(this,"meta");p(this,"ai");m(this,si,void 0);m(this,da,void 0);p(this,"aiSocketHandler");m(this,Jt,void 0);g(this,Jt,s),this.meta=new tp(s,t,t.config.viewType,e,n),this.ai=r,g(this,si,t),g(this,da,e),this.aiSocketHandler=i,this.setupEvents()}get telemetry(){return a(this,Jt).getValue("telemetry")}get logger(){return a(this,Jt).getValue("logger")}static async init(s,t,e,r,i){const n=await Ni.init(s,t.permissions.transcriptionEnabled);return new sp(s,t,e,n,r,i)}conditionallySetActiveTab(s){var t;s!=null&&s.currentTab&&((t=this.meta.selfActiveTab)==null?void 0:t.id)!==s.currentTab.id&&(this.meta.setSelfActiveTab(s.currentTab,wS.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){a(this,Jt).getValue("peerSessionStore").on(P.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),a(this,Jt).getValue("peerSessionStore").on(P.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),a(this,Jt).getValue("peerSessionStore").on(P.ROOM_STATE,({createdAt:s,roomUuid:t})=>{const e=this.meta.meetingStartedTimestamp;if(t&&(this.meta.sessionId=t),s&&!e){const r=new Date(s*1e3);this.meta.meetingStartedTimestamp=r,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),a(this,Jt).getValue("peerSessionStore").on(P.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),a(this,si).permissions.canSpotlight&&this.meta.selfActiveTab&&(this.logger.info("Asserting Spotlight status to other peers."),a(this,da).broadcastMessage("spotlight",{userId:a(this,si).userId,currentTab:this.meta.selfActiveTab})),a(this,Jt).getValue("peerSessionStore").on(P.PEER_JOINED_INTERNAL,async s=>{a(this,si).permissions.canSpotlight&&this.meta.selfActiveTab&&a(this,da).broadcastToPeers("spotlight",[s.id],{userId:a(this,si).userId,currentTab:this.meta.selfActiveTab})}),a(this,Jt).getValue("peerSessionStore").on(P.ROOM_MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),a(this,Jt).getValue("peerSessionStore").on(P.MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),this.aiSocketHandler.on($.transcript,s=>{let t;try{t=sp.extractSocketTranscript(s)}catch(e){this.logger.error("Failed to parse transcript socket message.",{error:e});return}if(!t){this.logger.warn("Received empty transcript data");return}this.ai.onTranscript(t)})}static extractSocketTranscript(s){return s?{id:ki(),name:s.speaker.displayName,peerId:s.speaker.peerId,userId:s.speaker.participantId,customParticipantId:s.speaker.customParticipantId,transcript:s.sentence,isPartialTranscript:s.isPartial||!1,date:new Date(s.startedAt*1e3)}:void 0}},si=new WeakMap,da=new WeakMap,Jt=new WeakMap,xv);let _S=sp;uD([y.trace("MetaController.setupEvents")],_S.prototype,"setupEvents",1);const To={},ur={executeWithLock({methodName:s,lockName:t,timeout:e}){return(r,i,n)=>{const o=n.value;return n.value=function(...d){var E,k;const l=(k=(this==null?void 0:this.peerId)||((E=d[0])==null?void 0:E.authToken))!=null?k:"",u=`${t}-${l}`,h=this==null?void 0:this.logger;if(To[u]){const R=new Error(`Unsupported concurrent calls on method: ${s}.`);throw R.name="UnsupportedConcurrentMethodExecution",h==null||h.error("Locker::UnsupportedConcurrentMethodExecution",{error:{stack:R.stack},locker:{methodName:s,lockName:u}}),R}To[u]=!0;const f=setTimeout(()=>delete To[u],e),S=o.apply(this,d);return Promise.resolve(S).then(()=>{delete To[u],clearTimeout(f)}).catch(()=>{delete To[u],clearTimeout(f)}),S},n}}};var hD=Object.defineProperty,pD=Object.getOwnPropertyDescriptor,Li=(s,t,e,r)=>{for(var i=r>1?void 0:r?pD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&hD(t,e,i),i};class Wr extends Ft{constructor(e,r,i,n,o){const c=e.getValue("logger");super(c);m(this,Wo);m(this,la);m(this,ds,void 0);m(this,Wl,void 0);m(this,le,void 0);m(this,Go,void 0);m(this,Us,void 0);m(this,Qe,void 0);g(this,Qe,e),g(this,ds,n),g(this,Wl,o),g(this,le,r),g(this,Go,i),g(this,Us,[]),this.setupEvents()}get telemetry(){return a(this,Qe).getValue("telemetry")}get status(){return a(this,Qe).getValue("stageStatus")}setupEvents(){const e={[P.GET_STAGE_REQUESTS]:async n=>{g(this,Us,n)},[P.UPDATE_STAGE_REQUESTS]:async({add:n})=>{const o=a(this,Us).length,{stageRequests:c}=this.getAccessRequests();(n||c.length>o)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)}},r=()=>{Object.entries(e).forEach(([n,o])=>{a(this,Qe).getValue("peerSessionStore").onAsync(n,o)})},i=()=>{Object.entries(e).forEach(([n,o])=>{a(this,Qe).getValue("peerSessionStore").removeListener(n,o)})};a(this,le).permissions.on("permissionsUpdate",n=>{const{canAcceptProductionRequests:o}=n;o!==void 0&&(a(this,le).permissions.acceptStageRequests?(r(),a(this,ds).getStageRequests()):(i(),g(this,Us,[]),this.emit("stageAccessRequestUpdate",a(this,Us))))}),a(this,le).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,le).permissions.acceptStageRequests)throw this.logger.error("Stage::get_access_request::permission_denied"),new C("You do not have permission to perform this action","2001");const e=a(this,Go).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return g(this,Us,e),{stageRequests:a(this,Us)}}async requestAccess(){if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new C(`Unable to request access you are currently ${this.status}`,"2006");if(a(this,le).permissions.stageAccess===G.Allowed){I(this,la,Ku).call(this,"ACCEPTED_TO_JOIN_STAGE");return}a(this,ds).requestAccess(),I(this,la,Ku).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");a(this,ds).cancelRequestAccess(),I(this,la,Ku).call(this,"OFF_STAGE")}grantAccess(e){if(!a(this,le).roomJoined)throw new C("Can`t grant for participant without joining room");if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,le).permissions.acceptStageRequests)throw this.logger.error("Stage::grant_access::permission_denied"),new C("You do not have permission to perform this action","2001");return a(this,ds).grantAccess(e)}denyAccess(e){if(!a(this,le).roomJoined)throw new C("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,le).permissions.acceptStageRequests)throw this.logger.error("Stage::deny_access::permission_denied"),new C("You do not have permission to perform this action","2001");return a(this,ds).denyAccess(e)}get peerId(){return a(this,Qe).getValue("peerId")}async join(){const e=a(this,Qe).getValue("viewType");if(this.status==="ON_STAGE")throw new C("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||a(this,le).permissions.stageAccess===G.NotAllowed)throw new C(`Unable to join stage you are currently ${this.status}`,"2006");if(a(this,Qe).setValue("stageStatus","ON_STAGE",!1),await a(this,ds).joinStage(),e===vs.Livestream){await a(this,Qe).getValue("selfController").joinRoom();return}a(this,Qe).notify("stageStatus"),a(this,le).audioEnabled&&a(this,Wo,Hp).shareMic(a(this,le).audioTrack),a(this,le).videoEnabled&&a(this,Wo,Hp).shareWebcam(a(this,le).videoTrack)}async leave(){if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new C(`Unable to leave stage you are currently ${this.status}`,"2006");a(this,le).setIsPinned(!1),a(this,Qe).setValue("stageStatus","OFF_STAGE",!1),await a(this,ds).leaveStage(a(this,le).userId);try{await a(this,Qe).getValue("peerSessionStore").emitAsync(P.LEAVE_MEDIA_ROOM,"stageLeft")}catch(e){this.logger.error("Stage::leave::emitAsync::failed",{error:e})}a(this,Qe).notify("stageStatus")}async kick(e){if(!a(this,le).roomJoined)throw new C("Can`t kick participant without joining room","2005");if(!a(this,le).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,le).permissions.acceptStageRequests)throw this.logger.error("Stage::kick::permission_denied"),new C("You do not have permissions for kick","2001");return a(this,ds).kick(e)}}ds=new WeakMap,Wl=new WeakMap,le=new WeakMap,Go=new WeakMap,Us=new WeakMap,Qe=new WeakMap,Wo=new WeakSet,Hp=function(){return a(this,Qe).getValue("roomNodeClient")},la=new WeakSet,Ku=async function(e){this.status!==e&&a(this,Qe).setValue("stageStatus",e)},Li([y.trace("Stage.getStageRequests")],Wr.prototype,"getAccessRequests",1),Li([y.trace("Stage.requestAccess")],Wr.prototype,"requestAccess",1),Li([y.trace("Stage.cancelRequestAccess")],Wr.prototype,"cancelRequestAccess",1),Li([y.trace("Stage.grantAccess")],Wr.prototype,"grantAccess",1),Li([y.trace("Stage.denyAccess")],Wr.prototype,"denyAccess",1),Li([ur.executeWithLock({methodName:"joinStage",lockName:"Stage.join",timeout:5e3}),y.trace("Stage.joinStage")],Wr.prototype,"join",1),Li([y.trace("Stage.leaveStage")],Wr.prototype,"leave",1);function mD(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function rp(s){switch(s){case ar.UNSPECIFIED:return"OFF_STAGE";case ar.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case ar.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case ar.OFF_STAGE:return"OFF_STAGE";case ar.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var gD=Object.defineProperty,fD=Object.getOwnPropertyDescriptor,SD=(s,t,e,r)=>{for(var i=r>1?void 0:r?fD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&gD(t,e,i),i};class kS{constructor(t,e,r,i,n){p(this,"stage");m(this,ri,void 0);m(this,Ps,void 0);m(this,ii,void 0);m(this,Jo,0);m(this,Et,void 0);g(this,Et,t),this.stage=new Wr(t,i,n,e,r),g(this,ii,e),g(this,ri,i),g(this,Ps,n),this.setupEvents()}get telemetry(){return a(this,Et).getValue("telemetry")}get logger(){return a(this,Et).getValue("logger")}setupEvents(){a(this,Et).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),a(this,ii).on($.grantStageAccess,()=>{a(this,ri).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),a(this,ii).on($.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===a(this,ri).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),a(this,ii).on($.denyStageAccess,()=>{a(this,ri).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),a(this,ii).on($.getStageRequests,async t=>{var r;if(a(this,ri).permissions.stageAccess!==G.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await a(this,Et).getValue("peerSessionStore").emitAsync(P.GET_STAGE_REQUESTS,e),a(this,Jo)<e.length&&e.length>0&&this.stage.emit("newStageRequest",{count:e.length}),g(this,Jo,e.length),this.stage.emit("stageAccessRequestUpdate",e)})}getCurrentStageRequests(){return a(this,Ps).joined.toArray().filter(e=>e.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(e=>({displayName:e.name,userId:e.userId,peerId:e.id}))}async setStageStatus(t){this.stage.status!==t&&a(this,Et).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=rp(t.stageType),r=a(this,Et).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:a(this,Et).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(r);break;case 0:case 4:default:a(this,Et).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}async peerStageStatusHandler(t){const e=a(this,Ps).joined.get(t.peerId),r=a(this,Ps).viewMode==="ACTIVE_GRID";if(!e){this.logger.warn("err::peerStageStatusUpdate: participant not found");return}switch(t.stageType){case 1:e.setStageStatus("ON_STAGE"),r&&a(this,Et).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:a(this,Ps).viewMode,page:a(this,Ps).currentPage});break;case 2:e.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:e.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:e.setStageStatus("OFF_STAGE"),r&&a(this,Et).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:a(this,Ps).viewMode,page:a(this,Ps).currentPage});break}a(this,Et).getValue("peerSessionStore").emit(P.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}ri=new WeakMap,Ps=new WeakMap,ii=new WeakMap,Jo=new WeakMap,Et=new WeakMap,SD([y.trace("Stage.setupEvents")],kS.prototype,"setupEvents",1);var vD=Object.defineProperty,TD=Object.getOwnPropertyDescriptor,ip=(s,t,e,r)=>{for(var i=r>1?void 0:r?TD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&vD(t,e,i),i};let yo=($v=class extends Vn{constructor(t,e,r,i){const n=t.getValue("logger");super(n);p(this,"name");p(this,"icon");p(this,"id");p(this,"permissions");m(this,zi,void 0);m(this,yr,void 0);m(this,Ko,void 0);m(this,zo,void 0);m(this,Yi,void 0);p(this,"active");p(this,"enabledBy");g(this,Ko,t);const o=t.getValue("meetingId");this.id=`${o}:${e.id}`,this.name=e.name,this.icon=e.icon,g(this,zo,e.component),this.permissions=e.permissions,g(this,zi,i),g(this,yr,r),this.active=!1,this.enabledBy=""}get component(){return a(this,zo)}get telemetry(){return a(this,Ko).getValue("telemetry")}set activePluginsStore(t){g(this,yr,t)}activateForSelf(){g(this,Yi,new Date),this.active=!0,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("enabled")}deactivateForSelf(){g(this,Yi,void 0),this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("closed")}async activate(){var t;if(!this.active&&(t=this.permissions)!=null&&t.canActivate){if(!a(this,yr))throw new C("Cannot activate plugin: active plugins store is not available yet.","0604");await a(this,yr).set(this.id,{name:this.name,icon:this.icon,id:this.id,enabledBy:a(this,zi).id}),this.enabledBy=a(this,zi).id,this.activateForSelf(),this.logger.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}})}}async deactivate(){var e;if(!this.active||!((e=this.permissions)!=null&&e.canDeactivate)&&this.enabledBy!==a(this,zi).id)return;if(!a(this,yr))throw new C("Cannot deactivate plugin: active plugins store is not available yet.","0604");const t=a(this,Yi)?new Date().getTime()-a(this,Yi).getTime():0;await a(this,yr).set(this.id,null),this.deactivateForSelf(),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:t}})}},zi=new WeakMap,yr=new WeakMap,Ko=new WeakMap,zo=new WeakMap,Yi=new WeakMap,$v);ip([y.trace("Plugin.activatePlugin")],yo.prototype,"activate",1),ip([y.trace("Plugin.deactivatePlugin")],yo.prototype,"deactivate",1),yo=ip([pt("0600")],yo);class CS extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:n,onClearEvent:o}=e;super();m(this,Fe,void 0);m(this,Qi,void 0);p(this,"onAddEvent");p(this,"onDeleteEvent");p(this,"onClearEvent");g(this,Fe,new Vn(r)),this.onAddEvent=i,this.onDeleteEvent=n,this.onClearEvent=o,g(this,Qi,new Map)}emit(e,...r){return a(this,Fe).emit(e,...r)}on(e,r){return a(this,Fe).on(e,r)}addListener(e,r){return a(this,Fe).addListener(e,r)}off(e,r){return a(this,Fe).off(e,r)}once(e,r){return a(this,Fe).once(e,r)}prependListener(e,r){return a(this,Fe).prependListener(e,r)}prependOnceListener(e,r){return a(this,Fe).prependOnceListener(e,r)}removeListener(e,r){return a(this,Fe).removeListener(e,r)}removeAllListeners(e){return a(this,Fe).removeAllListeners(e)}listeners(e){return a(this,Fe).listeners(e)}listenerCount(e){return a(this,Fe).listenerCount(e)}getMaxListeners(){return a(this,Fe).getMaxListeners()}setMaxListeners(e){return a(this,Fe).setMaxListeners(e)}eventNames(){return a(this,Fe).eventNames()}add(e,r=!0){return this.set(e.id,e,r)}set(e,r,i=!0){const n=super.set(e,r),o=(c,...d)=>{this.emit(c,r,...d)};return a(this,Qi).set(e,o),r.on("*",o),i&&a(this,Fe).emit(this.onAddEvent,r),n}delete(e,r=!0,i=!1){const n=this.get(e);if(!n)return!1;n.removeListener("*",a(this,Qi).get(e));const o=super.delete(e);return i&&n.removeAllListeners(),r&&a(this,Fe).emit(this.onDeleteEvent,n),o}clear(e=!0,r=!1){this.forEach(n=>{n.removeListener("*",a(this,Qi).get(n.id)),r&&n.removeAllListeners()});const i=super.clear();return e&&a(this,Fe).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}Fe=new WeakMap,Qi=new WeakMap;class RS extends CS{constructor(t){super({onAddEvent:"pluginAdded",onDeleteEvent:"pluginDeleted"},t)}add(t,e=!0){return super.add(t,e)}delete(t,e=!0,r=!1){return super.delete(t,e,r)}}var yD=Object.defineProperty,ED=Object.getOwnPropertyDescriptor,bD=(s,t,e,r)=>{for(var i=r>1?void 0:r?ED(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&yD(t,e,i),i};let np=class{constructor(s){p(this,"all");p(this,"active");this.all=new RS(s),this.active=new RS(s)}};np=bD([pt("0600")],np);var wD=Object.defineProperty,PD=Object.getOwnPropertyDescriptor,_D=(s,t,e,r)=>{for(var i=r>1?void 0:r?PD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&wD(t,e,i),i};const IS=(Uv=class{constructor(s,t,e,r){m(this,Jl);m(this,Yo);m(this,Qo);m(this,Xo);p(this,"plugins");m(this,_s,void 0);m(this,ua,void 0);m(this,ni,void 0);m(this,Xi,null);g(this,ni,s),this.plugins=t,g(this,ua,e),g(this,_s,r),this.setupEvents()}get telemetry(){return a(this,ni).getValue("telemetry")}get logger(){return a(this,ni).getValue("logger")}static async init(s,t,e,r){var l,u;const i=s.getValue("logger"),n=s.getValue("connectionHandler"),o=new np(i);let c;n.socketState.state==="connected"?(i.info("Creating active plugins store immediately. Socket is already connected."),c=await r.create(Ch,!0)):i.info("Deferring active plugins store creation until socket connects."),t.forEach(h=>{const f=new yo(s,h,c,e);o.all.add(f)});const d=new IS(s,o,r,c);return c?I(l=d,Xo,Gp).call(l):I(u=d,Jl,Xv).call(u),d}cleanup(){I(this,Yo,qp).call(this)}setupEvents(){this.plugins.all.on("stateUpdate",({active:s,id:t})=>{if(s){this.plugins.active.add(this.plugins.all.get(t));return}this.plugins.active.delete(t)}),a(this,ni).getValue("peerSessionStore").onAsync(P.SOCKET_SERVICE_ROOM_JOINED,async()=>{var t,e;if(((e=(t=this.plugins.active)==null?void 0:t.toArray())!=null?e:[]).forEach(r=>{r.deactivateForSelf()}),!a(this,_s)){this.logger.warn("Active plugins store not available yet on ROOM_JOINED. Sync will be performed when store is created.");return}await I(this,Qo,jp).call(this),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to sync active plugins.")})}},_s=new WeakMap,ua=new WeakMap,ni=new WeakMap,Xi=new WeakMap,Jl=new WeakSet,Xv=function(){const s=a(this,ni).getValue("peerSessionStore"),t=async e=>{if(e.state==="connected"&&!a(this,_s))try{g(this,_s,await a(this,ua).create(Ch,!0)),I(this,Yo,qp).call(this),this.plugins.all.toArray().forEach(r=>{r.activePluginsStore=a(this,_s)}),I(this,Xo,Gp).call(this),this.logger.info("Active plugins store created after socket connected"),await I(this,Qo,jp).call(this)}catch(r){this.logger.error("Failed to create active plugins store after socket connected, will retry on next reconnect",{error:r})}};s.on(P.SOCKET_STATE_UPDATE,t),g(this,Xi,()=>{s.off(P.SOCKET_STATE_UPDATE,t)})},Yo=new WeakSet,qp=function(){a(this,Xi)&&(a(this,Xi).call(this),g(this,Xi,null))},Qo=new WeakSet,jp=async function(){try{await a(this,ua).refresh(a(this,_s).name)}catch(t){this.logger.error("Failed to refresh active plugins store, syncing from stale data.",{error:t})}const s=a(this,_s).getAll();Object.entries(s).forEach(([t,e])=>{if(!e)return;const r=this.plugins.all.get(t);if(!r){this.logger.warn(`Plugin '${t}' not found in plugins.all, ignoring store entry.`);return}r.active||(r.enabledBy=e.enabledBy,r.activateForSelf())})},Xo=new WeakSet,Gp=function(){a(this,_s).subscribe("*",s=>{Object.entries(s).forEach(([t,e])=>{const r=this.plugins.all.get(t);if(!r){this.logger.warn(`Plugin '${t}' not found in plugins.all, ignoring store update.`);return}!e&&r.active&&r.deactivateForSelf(),e&&!r.active&&(r.enabledBy=e.enabledBy,r.activateForSelf())})})},Uv);let AS=IS;_D([y.trace("PluginController.setupEvents")],AS.prototype,"setupEvents",1);class kD{constructor(t){p(this,"mediaJoined");p(this,"socketJoined");p(this,"socketJoinAttempted");p(this,"mediaJoinAttempted");p(this,"socketState");p(this,"mediaState");m(this,Zo,void 0);this.mediaJoined=!1,this.socketJoined=!1,this.socketJoinAttempted=!1,this.mediaJoinAttempted=!1,this.socketState={state:void 0,reconnected:!1,reconnectionAttempt:void 0},this.mediaState={recv:void 0,send:void 0},g(this,Zo,t)}get joinAttempted(){return this.mediaJoinAttempted||this.socketJoinAttempted}get roomJoined(){return this.mediaJoined&&this.socketJoined}updateSocketConnectionState(t,e){let r;const{reconnected:i}=this.socketState;switch(t){case"connected":r={state:"connected",reconnected:i,reconnectionAttempt:void 0};break;case"disconnected":r={state:"disconnected",reconnected:!1,reconnectionAttempt:0},this.socketJoined=!1;break;case"reconnected":r={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":r={state:"reconnecting",reconnected:i,reconnectionAttempt:0};break;case"reconnectAttempt":r={state:"reconnecting",reconnected:i,reconnectionAttempt:e};break;case"failed":r={state:"failed",reconnected:i,reconnectionAttempt:void 0},this.socketJoined=!1;break}r&&(this.socketState=r,a(this,Zo).getValue("peerSessionStore").emit(P.SOCKET_STATE_UPDATE,r))}}Zo=new WeakMap;var CD=Object.defineProperty,RD=Object.getOwnPropertyDescriptor,Eo=(s,t,e,r)=>{for(var i=r>1?void 0:r?RD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&CD(t,e,i),i};const MS="Cannot start recording: another recording is already in progress.";let Vi=(Fv=class extends Ft{constructor(t,e){const r=t.getValue("logger");super(r);m(this,ma);m(this,ha,void 0);m(this,pa,void 0);p(this,"recordingPeerIds",[]);p(this,"recordings",[]);g(this,pa,t),g(this,ha,e)}get recordingState(){return this.recordings.some(t=>t.state==="RECORDING")?"RECORDING":this.recordings.some(t=>t.state==="PAUSED")?"PAUSED":this.recordings.some(t=>t.state==="STARTING")?"STARTING":this.recordings.some(t=>t.state==="STOPPING")?"STOPPING":"IDLE"}get telemetry(){return a(this,pa).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!a(this,ha).permissions.canRecord)throw this.logger.error("Recording::start::permission_denied"),new C("User does not have permission to start recording","1001");if((t==null?void 0:t.allowMultiple)!==!0&&(this.recordingState==="STARTING"||this.recordingState==="RECORDING"||this.recordingState==="STOPPING"))throw this.logger.error("Recording::start::recording_in_progress",{recording:{state:this.recordingState}}),new C(MS,"1005");try{const e=Ht(),{recording:r={}}=a(this,pa).getValue("defaults"),i=await e.startRecording(r,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:i,state:"STARTING",type:"BROWSER"}])}catch(e){throw this.logger.error("Recording::start::recording_failed_to_start",{error:e}),e instanceof ul&&e.status===409?new C(MS,"1005"):new C("Error while starting recording","1000",this.logger)}}async stop(t){await I(this,ma,zu).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await I(this,ma,zu).call(this,"pause",["RECORDING"],t)}async resume(t){await I(this,ma,zu).call(this,"resume",["PAUSED"],t)}},ha=new WeakMap,pa=new WeakMap,ma=new WeakSet,zu=async function(t,e,r){if(!a(this,ha).permissions.canRecord)throw this.logger.error("Recording::stop::permission_denied"),new C("User does not have permission to stop recording","1001");let i=[];if(r!==void 0){const n=this.recordings.find(o=>o.id===r);if(n===void 0)throw new C("Could not find the specified recording","1004");if(e.includes(n.state)){this.logger.error("Recording::stop::recording_not_in_expected_state",{recording:{state:n.state}});return}i.push(n)}else i=this.recordings.filter(n=>e.includes(n.state));i.forEach(async n=>{const o=n.state;t==="stop"&&(n.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{await Ht().updateRecording(n.id,t)}catch(c){throw this.logger.error("Recording::stop::recording_failed_to_stop",{error:c}),n.state!==o&&(n.state=o,this.emit("recordingUpdate",o)),new C("Error while stopping recording","1000",this.logger)}})},Fv);Eo([y.trace("Recording.start")],Vi.prototype,"start",1),Eo([y.trace("Recording.stop")],Vi.prototype,"stop",1),Eo([y.trace("Recording.stop")],Vi.prototype,"pause",1),Eo([y.trace("Recording.stop")],Vi.prototype,"resume",1),Vi=Eo([pt("1000")],Vi);var ID=Object.defineProperty,AD=Object.getOwnPropertyDescriptor,MD=(s,t,e,r)=>{for(var i=r>1?void 0:r?AD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ID(t,e,i),i};class OS{constructor(t,e,r){p(this,"recording");p(this,"room");m(this,Zi,void 0);g(this,Zi,t),this.recording=new Vi(t,e),this.room=r,this.setupEvents()}get telemetry(){return a(this,Zi).getValue("telemetry")}get logger(){return a(this,Zi).getValue("logger")}getRecordingTypeFromProtoType(t){let e;switch(t){case Di.BROWSER:e="BROWSER";break;case Di.COMPOSITE:e="COMPOSITE";break;case Di.TRACK:e="TRACK";break;default:e="BROWSER"}return e}setupEvents(){a(this,Zi).getValue("peerSessionStore").on(P.ROOM_STATE,t=>{t.activeRecordings.length!==0?this.recording.updateRecordings(t.activeRecordings.map(e=>{const r=this.getRecordingTypeFromProtoType(e.recordingType);return{id:e.recordingId,state:e.recordingStatus,type:r}})):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on($.recordingStarted,t=>{let e=!1;const r=[...this.recording.recordings];if(r.forEach(i=>{i.id===t.recordingId&&(e=!0,i.state="RECORDING")}),e===!1){const i=this.getRecordingTypeFromProtoType(t.recordingType);r.push({id:t.recordingId,state:"RECORDING",type:i})}this.recording.updateRecordings(r)}),this.room.on($.recordingPaused,t=>{const e=[...this.recording.recordings];e.forEach(r=>{r.id===t.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(e)}),this.room.on($.recordingStopped,t=>{const e=[...this.recording.recordings.filter(r=>r.id!==t.recordingId)];this.recording.updateRecordings(e)})}}Zi=new WeakMap,MD([y.trace("RecordingController.setupEvents")],OS.prototype,"setupEvents",1);class OD{constructor(t){m(this,en,void 0);g(this,en,t)}hasFeature(t){return a(this,en).getValue("logger").warn("Unimplemented method: meeting.__internals__.hasFeature called"),!1}getFeatureValue(t){return a(this,en).getValue("logger").warn("Unimplemented method: meeting.__internals__.getFeatureValue called"),null}getAllFeatures(){return a(this,en).getValue("logger").warn("Unimplemented method: meeting.__internals__.getAllFeatures called"),{}}}en=new WeakMap;class ap{constructor(t,e,r,i){p(this,"authToken");p(this,"logger");p(this,"features");p(this,"browserSpecs");p(this,"callStats");this.authToken=t,this.logger=e,this.features=r,this.browserSpecs=Pe,this.callStats=i}static init(t){return new ap(t.getValue("authToken"),t.getValue("logger"),new OD(t),t.getValue("callstats"))}}class op{constructor(t){p(this,"internals");this.internals=t}static async init(t){const e=ap.init(t);return new op(e)}}var DD=Object.defineProperty,ND=Object.getOwnPropertyDescriptor,jt=(s,t,e,r)=>{for(var i=r>1?void 0:r?ND(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&DD(t,e,i),i};class Dt extends Vn{constructor(e,r,i=ml,n=!0){const o=e.getValue("logger");super(o);m(this,Ge,void 0);m(this,ke,void 0);m(this,Ee,void 0);m(this,Er,void 0);m(this,ls,void 0);m(this,ec,void 0);m(this,Ve,void 0);p(this,"audioUpdateInProgress");p(this,"videoUpdateInProgress");g(this,Ve,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,g(this,Ge,new US(e,r)),g(this,ke,new d1(e,a(this,Ge),void 0,i)),g(this,Ee,new f1(e,a(this,Ge),void 0,i)),g(this,ls,new p1(a(this,Ve),a(this,Ge))),g(this,Er,new u1(e,a(this,Ge))),g(this,ec,n),a(this,ke).on("trackMuted",this.onAudioTrackMuted.bind(this)),a(this,ke).on("trackChanged",this.onAudioTrackChanged.bind(this)),a(this,Ee).on("trackChanged",this.onVideoTrackChanged.bind(this)),a(this,Ee).on("trackEnded",this.onVideoTrackEnded.bind(this)),a(this,ls).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return a(this,Ve).getValue("telemetry")}set context(e){g(this,Ve,e)}async onVisibilityChange(){a(this,Ve).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?a(this,Ve).getValue("callstats").browserBackgrounded():(a(this,Ve).getValue("callstats").browserForegrounded(),await this.setupSpeaker())}async repopulateAvailableDevices(){return!0}async setupStreams({audio:e,video:r}){var o;e?a(this,Ve).getValue("callstats").audioOn():a(this,Ve).getValue("callstats").audioOff(),r?a(this,Ve).getValue("callstats").videoOn():a(this,Ve).getValue("callstats").videoOff();let i,n;if(e&&r)try{const c=await a(this,Ge).getAudioAndVideoTrack(a(this,ke).userSelectedDevice,a(this,Ee).userSelectedDevice);i=c.audioTrack,n=c.videoTrack}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!i&&e)try{i=await a(this,Ge).getAudioTrack(!1,a(this,ke).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!n&&r)try{n=await a(this,Ge).getVideoTrack(a(this,Ee).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}e&&!i&&a(this,Ve).getValue("callstats").audioOff(),r&&!n&&a(this,Ve).getValue("callstats").videoOff(),await a(this,ke).setMediaTrack(i),await a(this,Ee).setMediaTrack(n);try{await this.setupSpeaker()}catch(c){}if(n){const c=await this.getDeviceById(n.getSettings().deviceId);a(this,Ve).getValue("callstats").selectedDevice("VIDEO",c)}if(i){const c=await this.getDeviceById(i.getSettings().deviceId);a(this,Ve).getValue("callstats").selectedDevice("AUDIO",c)}(o=a(this,Er).currentDevice)!=null&&o.deviceId&&a(this,Ve).getValue("callstats").selectedDevice("SPEAKER",a(this,Er).currentDevice),a(this,Ge).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})}getCurrentDevices(){return{audio:a(this,ke).currentDevice,video:a(this,Ee).currentDevice,speaker:a(this,Er).currentDevice}}get permissions(){return a(this,Ge).permissions}getAllDevices(){return a(this,Ge).getAvailableDevices()}getDeviceById(e,r){return a(this,Ge).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return a(this,ke).mediaTrack}get audioTrack(){return a(this,ke).transformedMediaTrack}get audioEnabled(){return a(this,ke).trackEnabled}async enableAudio(e){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?await a(this,ke).enableTrack(!1,e):await a(this,ke).unmuteTrack()}catch(r){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){a(this,ke).mediaTrack&&!a(this,ke).isCustomTrack?a(this,ke).muteTrack():a(this,ke).disableTrack()}getAudioDevices(e){return a(this,Ge).getAudioInputDevices(e)}async setAudioDevice(e,{saveDevicePreference:r}){await a(this,ke).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Ve).getValue("callstats").selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async setupSpeaker(){const{speaker:e}=this.getCurrentDevices();await a(this,Er).setPreferredSpeaker();const{speaker:r}=this.getCurrentDevices();(e==null?void 0:e.deviceId)!==(r==null?void 0:r.deviceId)&&r&&this.emit("DEVICE_CHANGE",{device:r})}async setSpeakerDevice(e,{saveDevicePreference:r}){await a(this,Er).setupSpeaker(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Ve).getValue("callstats").selectedDevice("SPEAKER",e),this.emit("DEVICE_CHANGE",{device:e})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return a(this,Ee).mediaTrack}get videoTrack(){return a(this,Ee).transformedMediaTrack}get videoEnabled(){return a(this,Ee).trackEnabled}async enableVideo(e){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?await a(this,Ee).enableTrack(!1,e):await a(this,Ee).unmuteTrack()}catch(r){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){a(this,Ee).disableTrack()}getVideoDevices(e){return a(this,Ge).getVideoInputDevices(e)}async setVideoDevice(e,{saveDevicePreference:r}){await a(this,Ee).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Ve).getValue("callstats").selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async updateVideoConstraints(e){await a(this,Ee).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:a(this,ls).audioMediaTrack,video:a(this,ls).videoMediaTrack}}get screenShareEnabled(){return a(this,ls).trackEnabled}async enableScreenShare(){await a(this,ls).enableScreenShare()}async disableScreenShare(){a(this,ls).disableScreenShare()}async updateScreenshareConstraints(e){await a(this,ls).updateConstraints(e)}getSpeakerDevices(e){return a(this,Ge).getAudioOutputDevices(e)}addAudioMiddleware(e){return a(this,ke).addMiddleware(e)}removeAudioMiddleware(e){return a(this,ke).removeMiddleware(e)}removeAllAudioMiddlewares(){return a(this,ke).removeAllMiddlewares()}addVideoMiddleware(e){return a(this,Ee).addMiddleware(e)}removeVideoMiddleware(e){return a(this,Ee).removeMiddleware(e)}removeAllVideoMiddlewares(){return a(this,Ee).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return a(this,Ee).setVideoMiddlewareGlobalConfig(e)}destruct(){a(this,ke).disableTrack(),a(this,Ee).disableTrack(),a(this,Ee).terminateMiddlewareWebWorker(),a(this,ls).disableScreenShare(),a(this,Ge).destruct()}async onDeviceChange(e,r){var n,o;if(this.emit("DEVICE_LIST_UPDATED",e),r||!a(this,ec))return;let i=!1;(n=e==null?void 0:e.added)==null||n.reverse().forEach(async c=>{var d;c&&!ml(c)&&(c.kind==="audioinput"&&((d=this.audioTrack)==null?void 0:d.enabled)===!0?await this.setAudioDevice(c,{saveDevicePreference:!1}):c.kind==="audiooutput"&&(i=!0,await this.setSpeakerDevice(c,{saveDevicePreference:!1})))}),i||(o=e==null?void 0:e.removed)==null||o.forEach(async c=>{var d;if(c.kind==="audiooutput"&&((d=this.getCurrentDevices().speaker)==null?void 0:d.deviceId)===c.deviceId){const l=await this.getSpeakerDevices();(l==null?void 0:l.length)>0&&await this.setSpeakerDevice(l[0],{saveDevicePreference:!1})}})}removeAllTracks(){this.destruct()}removeAudioTrack(){a(this,ke).disableTrack()}removeVideoTrack(){a(this,Ee).disableTrack(),a(this,Ee).terminateMiddlewareWebWorker()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}Ge=new WeakMap,ke=new WeakMap,Ee=new WeakMap,Er=new WeakMap,ls=new WeakMap,ec=new WeakMap,Ve=new WeakMap,jt([y.trace("MediaHandler.setupStreams")],Dt.prototype,"setupStreams",1),jt([y.trace("MediaHandler.enableAudio")],Dt.prototype,"enableAudio",1),jt([y.trace("MediaHandler.disableAudio")],Dt.prototype,"disableAudio",1),jt([y.trace("MediaHandler.setAudioDevice")],Dt.prototype,"setAudioDevice",1),jt([y.trace("MediaHandler.enableVideo")],Dt.prototype,"enableVideo",1),jt([y.trace("MediaHandler.disableVideo")],Dt.prototype,"disableVideo",1),jt([y.trace("MediaHandler.setVideoDevice")],Dt.prototype,"setVideoDevice",1),jt([y.trace("MediaHandler.updateVideoConstraints")],Dt.prototype,"updateVideoConstraints",1),jt([y.trace("MediaHandler.enableScreenShare")],Dt.prototype,"enableScreenShare",1),jt([y.trace("MediaHandler.disableScreenShare")],Dt.prototype,"disableScreenShare",1),jt([y.trace("MediaHandler.updateScreenshareConstraints")],Dt.prototype,"updateScreenshareConstraints",1),jt([y.trace("MediaHandler.destruct")],Dt.prototype,"destruct",1),jt([y.trace("MediaHandler.onDeviceChange")],Dt.prototype,"onDeviceChange",1);function pl(s,t,e){switch(!0){case Pe.isChromiumBased():switch(t){case"NotAllowedError":return e.includes("by system")?"SYSTEM_DENIED":s==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case Pe.isSafari():switch(t){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case Pe.isFirefox():switch(t){case"NotFoundError":case"NotReadableError":return"SYSTEM_DENIED";case"NotAllowedError":return"DENIED";case"AbortError":default:return"COULD_NOT_START"}default:return"COULD_NOT_START"}}const LD=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function ml(s){var e,r;const t=(e=s.label)==null?void 0:e.toLowerCase();return((r=Pe._bowser)==null?void 0:r.getOSName())==="macOS"&&t.includes("iphone")?!0:LD.some(i=>t==null?void 0:t.includes(i))}async function VD(s,t,e){if(!(t!=null&&t.length))return e;const r=s.getValue("logger"),i=new AudioContext,n=await Promise.all(t==null?void 0:t.map(d=>d(i))),o=i.createMediaStreamSource(new MediaStream([e])),c=i.createMediaStreamDestination();try{let d=o;for(let l=0;l<n.length;l+=1)d.connect(n[l]),d=n[l];d.connect(c)}catch(d){return r.error("getTransformedAudioTrack::middleware_execution_failed",{error:d}),e}return c.stream.getAudioTracks()[0]}const xD=s=>(t,e)=>(s.set(t,e),e),DS=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,NS=536870912,LS=NS*2,$D=(s,t)=>e=>{const r=t.get(e);let i=r===void 0?e.size:r<LS?r+1:0;if(!e.has(i))return s(e,i);if(e.size<NS){for(;e.has(i);)i=Math.floor(Math.random()*LS);return s(e,i)}if(e.size>DS)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;e.has(i);)i=Math.floor(Math.random()*DS);return s(e,i)},VS=new WeakMap,UD=xD(VS),gl=$D(UD,VS),FD=s=>s.method!==void 0&&s.method==="call",BD=s=>s.error===null&&typeof s.id=="number",fl=((s,t)=>{let e=null;return()=>{if(e!==null)return e;const r=new Blob([t],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(r);return e=s(i),setTimeout(()=>URL.revokeObjectURL(i)),e}})(s=>{const t=new Map([[0,()=>{}]]),e=new Map([[0,()=>{}]]),r=new Map,i=new Worker(s);return i.addEventListener("message",({data:l})=>{if(FD(l)){const{params:{timerId:u,timerType:h}}=l;if(h==="interval"){const f=t.get(u);if(typeof f=="number"){const S=r.get(f);if(S===void 0||S.timerId!==u||S.timerType!==h)throw new Error("The timer is in an undefined state.")}else if(typeof f!="undefined")f();else throw new Error("The timer is in an undefined state.")}else if(h==="timeout"){const f=e.get(u);if(typeof f=="number"){const S=r.get(f);if(S===void 0||S.timerId!==u||S.timerType!==h)throw new Error("The timer is in an undefined state.")}else if(typeof f!="undefined")f(),e.delete(u);else throw new Error("The timer is in an undefined state.")}}else if(BD(l)){const{id:u}=l,h=r.get(u);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:f,timerType:S}=h;r.delete(u),S==="interval"?t.delete(f):e.delete(f)}else{const{error:{message:u}}=l;throw new Error(u)}}),{clearInterval:l=>{const u=gl(r);r.set(u,{timerId:l,timerType:"interval"}),t.set(l,u),i.postMessage({id:u,method:"clear",params:{timerId:l,timerType:"interval"}})},clearTimeout:l=>{const u=gl(r);r.set(u,{timerId:l,timerType:"timeout"}),e.set(l,u),i.postMessage({id:u,method:"clear",params:{timerId:l,timerType:"timeout"}})},setInterval:(l,u=0)=>{const h=gl(t);return t.set(h,()=>{l(),typeof t.get(h)=="function"&&i.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:h,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:h,timerType:"interval"}}),h},setTimeout:(l,u=0)=>{const h=gl(e);return e.set(h,l),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:h,timerType:"timeout"}}),h}}},`(()=>{"use strict";const e=new Map,t=new Map,r=(e,t)=>{let r,o;const i=performance.now();r=i,o=e-Math.max(0,i-t);return{expected:r+o,remainingDelay:o}},o=(e,t,r,i)=>{const s=performance.now();s>r?postMessage({id:null,method:"call",params:{timerId:t,timerType:i}}):e.set(t,setTimeout(o,r-s,e,t,r,i))};addEventListener("message",(i=>{let{data:s}=i;try{if("clear"===s.method){const{id:r,params:{timerId:o,timerType:i}}=s;if("interval"===i)(t=>{const r=e.get(t);if(void 0===r)throw new Error('There is no interval scheduled with the given id "'.concat(t,'".'));clearTimeout(r),e.delete(t)})(o),postMessage({error:null,id:r});else{if("timeout"!==i)throw new Error('The given type "'.concat(i,'" is not supported'));(e=>{const r=t.get(e);if(void 0===r)throw new Error('There is no timeout scheduled with the given id "'.concat(e,'".'));clearTimeout(r),t.delete(e)})(o),postMessage({error:null,id:r})}}else{if("set"!==s.method)throw new Error('The given method "'.concat(s.method,'" is not supported'));{const{params:{delay:i,now:n,timerId:a,timerType:d}}=s;if("interval"===d)((t,i,s)=>{const{expected:n,remainingDelay:a}=r(t,s);e.set(i,setTimeout(o,a,e,i,n,"interval"))})(i,a,n);else{if("timeout"!==d)throw new Error('The given type "'.concat(d,'" is not supported'));((e,i,s)=>{const{expected:n,remainingDelay:a}=r(e,s);t.set(i,setTimeout(o,a,t,i,n,"timeout"))})(i,a,n)}}}}catch(e){postMessage({error:{message:e.message},id:s.id,result:null})}}))})();`),xS=s=>fl().clearInterval(s),HD=s=>fl().clearTimeout(s),$S=(s,t)=>fl().setInterval(s,t),cp=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:xS,clearTimeout:HD,setInterval:$S,setTimeout:(s,t)=>fl().setTimeout(s,t)},Symbol.toStringTag,{value:"Module"}));class qD{constructor(t){m(this,tn,void 0);m(this,tc,void 0);g(this,tc,t)}get logger(){return a(this,tc).getValue("logger")}terminateMiddlewareWebWorker(){if(a(this,tn))try{xS(a(this,tn)),g(this,tn,void 0)}catch(t){this.logger.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}async getTransformedVideoTrack(t,e,r){if(!(t!=null&&t.length))return e;const i=document.createElement("canvas"),n=await Promise.all(t==null?void 0:t.map(f=>f({canvas:i,WorkerTimers:cp})));if(r.disablePerFrameCanvasRendering){const S=i.captureStream().getVideoTracks()[0];return Object.defineProperty(S,"originalSettings",{value:e.getSettings()}),S}const o=document.createElement("video"),c=new MediaStream;c.addTrack(e);const d=i.getContext("2d");o.srcObject=c,o.autoplay=!0,this.terminateMiddlewareWebWorker();const l=async()=>{if(e.enabled===!1||e.readyState==="ended"){this.terminateMiddlewareWebWorker(),o.remove(),i.remove();return}try{d.drawImage(o,0,0);for(let f=0;f<n.length;f+=1)typeof n[f]=="function"&&await n[f](i,d)}catch(f){this.logger.error("getTransformedVideoTrack::middleware_execution_failed",{error:f})}};try{o.play()}catch(f){}o.addEventListener("play",()=>{i.width=o.width||e.getSettings().width,i.height=o.width||e.getSettings().height,g(this,tn,$S(l,50))},!1);const h=i.captureStream().getVideoTracks()[0];return Object.defineProperty(h,"originalSettings",{value:e.getSettings()}),h}}tn=new WeakMap,tc=new WeakMap;const jD={qvga:{width:{ideal:320},height:{ideal:240},frameRate:{ideal:30}},vga:{width:{ideal:640},height:{ideal:480},frameRate:{ideal:30}},hd:{width:{ideal:1280},height:{ideal:720},frameRate:{ideal:30}},fhd:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},uhd:{width:{ideal:3840},height:{ideal:2160},frameRate:{ideal:30}}},GD=[[320,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2}]],[640,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2}]],[1280,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]],[1920,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]],[3840,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]]],WD=(s,t)=>{var d,l,u;const e=(d=s==null?void 0:s.getValue("overrides"))==null?void 0:d.simulcastConfig;if((l=e==null?void 0:e.encodings)!=null&&l.length)return e.encodings;const r="getSettings"in t&&t.getSettings().width||"getConstraints"in t&&t.getConstraints().width||"originalSettings"in t&&((u=t.originalSettings)==null?void 0:u.width),i=GD,n=i.map(([h])=>h).sort((h,f)=>h-f);let o=Number.MAX_VALUE,c=0;return n.forEach((h,f)=>{Math.abs(h-r)<o&&(o=Math.abs(h-r),c=f)}),i[c][1]};var Re=(s=>(s.WEBCAM="webcam",s.WEBCAM_BACKUP="webcam_backup",s.MIC="mic",s.SCREENSHARE_VIDEO="screenshare_video",s.SCREENSHARE_AUDIO="screenshare_audio",s))(Re||{});const JD=eC(),jn=Ls(JD.config.media);function KD(s){var e,r;const t={};return s.audio&&(t.audio={enableStereo:(e=s.audio.enableStereo)!=null?e:!1,enableHighBitrate:(r=s.audio.enableHighBitrate)!=null?r:!1}),t.video=s.video.quality,t}class zD{constructor(t,e){m(this,sn,void 0);m(this,Kl,void 0);p(this,"getScreenShareConstraints",()=>{var l,u,h,f,S,E,k,R,D;const t=(l=a(this,sn))==null?void 0:l.screenshare,e=(h=(u=t==null?void 0:t.width)==null?void 0:u.max)!=null?h:1920,r=(S=(f=t==null?void 0:t.height)==null?void 0:f.max)!=null?S:1080,i=(k=(E=t==null?void 0:t.frameRate)==null?void 0:E.max)!=null?k:5,n=(D=(R=t==null?void 0:t.frameRate)==null?void 0:R.ideal)!=null?D:5,o=t==null?void 0:t.displaySurface,c=t==null?void 0:t.selfBrowserSurface;let d={width:{max:e},height:{max:r},frameRate:{ideal:n,max:i}};return o!==void 0&&["monitor","browser","window"].includes(o)&&(d={...d,displaySurface:o}),c!==void 0&&(d={...d,selfBrowserSurface:c}),{audio:!0,video:d}});p(this,"getAudioConstraints",t=>{var n,o,c,d,l,u,h;const e={},r=(n=a(this,sn))==null?void 0:n.audio,i=r!=null&&r.enableStereo?2:1;return Pe.isFirefox()||Pe.isWebKitBased()?(e.audio={deviceId:t,autoGainControl:(o=r==null?void 0:r.autoGainControl)!=null?o:!0,echoCancellation:(c=r==null?void 0:r.echoCancellation)!=null?c:!0,noiseSuppression:(d=r==null?void 0:r.noiseSupression)!=null?d:!0,channelCount:i},e):(e.audio={autoGainControl:(l=r==null?void 0:r.autoGainControl)!=null?l:!0,echoCancellation:(u=r==null?void 0:r.echoCancellation)!=null?u:!0,noiseSuppression:(h=r==null?void 0:r.noiseSupression)!=null?h:!0,channelCount:i},t&&(e.audio.deviceId={exact:t}),e)});p(this,"getVideoConstraints",t=>{var o,c,d;const e={},r=(o=a(this,sn))==null?void 0:o.video,i=f_(jD);let n=i.vga;if(typeof r=="string"){const l=i[r];l&&(n=l)}else r!==void 0&&(n.height.ideal=r.height.ideal,n.width.ideal=r.width.ideal,n.frameRate.ideal=(d=(c=r.frameRate)==null?void 0:c.ideal)!=null?d:30);return e.video=n,typeof e.video=="boolean"||(t?e.video.deviceId={exact:t}:e.video.facingMode="user"),e});g(this,Kl,t),g(this,sn,e)}getUpdatedVideoConstraints(t){return t}}sn=new WeakMap,Kl=new WeakMap;class dp extends Error{constructor(e,r,i){super(r);p(this,"constraints");p(this,"name");this.name=e,this.constraints=i}}class YD{constructor(){p(this,"permissions");this.permissions={audio:"NOT_REQUESTED",video:"NOT_REQUESTED",screenshare:"NOT_REQUESTED"}}async getAudioInputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="audioinput")}async getVideoInputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="videoinput")}async getAudioOutputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="audiooutput")}}var QD=Object.defineProperty,XD=Object.getOwnPropertyDescriptor,bs=(s,t,e,r)=>{for(var i=r>1?void 0:r?XD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&QD(t,e,i),i};let Gt=(Bv=class extends YD{constructor(t,e){super();m(this,ga,void 0);m(this,us,void 0);m(this,Xe,void 0);g(this,Xe,t),g(this,us,new zD(t,e)),g(this,ga,new AbortController)}get telemetry(){return a(this,Xe).getValue("telemetry")}get logger(){return a(this,Xe).getValue("logger")}get constraintsBuilder(){return a(this,us)}async destruct(){var t;(t=a(this,ga))==null||t.abort()}handlePermissionErrors(t,e){const r=pl(t,e.name,e.message);return this.permissions[t]=r,a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}async getAudioAndVideoTrack(t,e){var r,i,n,o;try{const c=await this.getAudioInputDevices(),d=await this.getVideoInputDevices(),l=!!(c!=null&&c.find(D=>D.deviceId===t));let u;t&&l?u=t:c&&((r=c[0])!=null&&r.deviceId)&&(u=(i=c[0])==null?void 0:i.deviceId);const h=!!(d!=null&&d.find(D=>D.deviceId===e));let f;e&&h?f=e:d&&((n=d[0])!=null&&n.deviceId)&&(f=(o=d[0])==null?void 0:o.deviceId);const S={audio:a(this,us).getAudioConstraints(u).audio,video:a(this,us).getVideoConstraints(f).video};this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(S)});const E=await navigator.mediaDevices.getUserMedia(S);this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(S)});const k=E.getAudioTracks()[0];let R=E.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",R.label.includes("OBS Virtual")){const N=(await this.getVideoInputDevices()).find(F=>F.label.includes("OBS Virtual"));R=await this.getVideoTrack(N.deviceId)}return a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:k,videoTrack:R}}catch(c){throw this.logger.error("WebMediaInterface.getAudioAndVideoTrack",{error:c}),new C("Couldnt fetch audio and video track","1605")}}async getAudioTrack(t,e){var c,d;let r=await this.getAudioInputDevices();if(!(r!=null&&r.length))throw this.permissions.audio="NO_DEVICES_AVAILABLE",a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new C("No audio devices available","1606");const i=!!(r!=null&&r.find(l=>l.deviceId===e));let n;e&&i?n=e:(c=r[0])!=null&&c.deviceId&&(n=(d=r[0])==null?void 0:d.deviceId);const o=async l=>{let u;try{r=r.filter(f=>f.deviceId!==l),u=a(this,us).getAudioConstraints(l),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(u)});const[h]=(await navigator.mediaDevices.getUserMedia(u)).getAudioTracks();return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(u)}),h}catch(h){const f=pl("audio",h.name,h.message),S=new dp(h.name,h.message,u);if(f==="COULD_NOT_START"){const E=r.shift();if(!E)throw S;this.logger.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(u),error:h});const k=a(this,us).getAudioConstraints(E.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(k)}),o(E.deviceId)}throw S}};try{const l=await o(n);return l.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),l}catch(l){throw l.constraints&&this.handlePermissionErrors("audio",l),new C(l.message,"1601")}}async getVideoTrack(t){var c,d,l;const e=(c=await this.getCurrentDeviceLabel(t))==null?void 0:c.includes("OBS Virtual"),r=await this.getVideoInputDevices();if(!(r!=null&&r.length))throw this.permissions.video="NO_DEVICES_AVAILABLE",a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new C("No video devices available","1607");const i=!!(r!=null&&r.find(u=>u.deviceId===t));let n;t&&i?n=t:(d=r[0])!=null&&d.deviceId&&(n=(l=r[0])==null?void 0:l.deviceId);const o=async u=>{try{let h=u;const{video:f}=h;e&&typeof f!="boolean"&&(h={video:{deviceId:f.deviceId}}),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(h)});const[S]=(await navigator.mediaDevices.getUserMedia(h)).getVideoTracks();if(e&&typeof f!="boolean"&&typeof f.width=="object"){const{width:E,height:k}=S.getSettings(),{ideal:R}=f.width;S.applyConstraints({width:{ideal:R},height:{ideal:Math.floor(k*R/E)},frameRate:f.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(h)}),S}catch(h){const f=pl("video",h.name,h.message),S=new dp(h.name,h.message,u);if(f==="COULD_NOT_START"){const E=r.shift();if(!E)throw S;this.logger.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(u),error:h});const k=a(this,us).getVideoConstraints(E.deviceId);return this.logger.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(k)}),o({video:k.video})}throw S}};try{const u=a(this,us).getVideoConstraints(n),h=await o(u);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),h}catch(u){throw u.constraints&&this.handlePermissionErrors("video",u),new C(u.message,"1602")}}async getScreenShareTracks(){const t=async e=>{try{this.logger.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),a(this,Xe).getValue("callstats").screenShareRequested();const r=await navigator.mediaDevices.getDisplayMedia(e);return this.logger.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(e)}),r}catch(r){const i=pl("video",r.name,r.message),n=new dp(r.name,r.message,e),o={video:!0};if(Pk(e,o))throw n;if(i==="COULD_NOT_START")return t(o);throw n}};try{const e=a(this,us).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",a(this,Xe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:r.getAudioTracks()[0],videoTrack:r.getVideoTracks()[0]}}catch(e){throw e.constraints&&this.handlePermissionErrors("screenshare",e),new C(e.message,"1612")}}async getCurrentDeviceLabel(t){const e=await this.getDevice(t||"default");return e==null?void 0:e.label}async enumerateDevicesWithExternalFirst(){const t=await navigator.mediaDevices.enumerateDevices(),e=i=>{var o;const n=((o=i.label)==null?void 0:o.toLowerCase())||"";return ml(i)?4:n.includes("airpods")||n.includes("airdopes")||n.includes("bluetooth")||n.includes("wireless")||n.includes("headphones")||n.includes("headset")&&!n.includes("earpiece")||n.includes("earbuds")||n.includes("usb")||n.includes("external")?0:i.deviceId==="default"||n.includes("default")?1:n.includes("built-in")||n.includes("internal")?2:3},r=i=>{var o;if(i.kind!=="videoinput")return!1;const n=((o=i.label)==null?void 0:o.toLowerCase())||"";return n.includes("front")||n.includes("user")||n.includes("selfie")?!0:!(n.includes("back")||n.includes("rear")||n.includes("environment"))};return t.sort((i,n)=>{var u,h;const o=e(i),c=e(n);if(o!==c)return o-c;const d=i.deviceId==="default"||((u=i.label)==null?void 0:u.toLowerCase().includes("default")),l=n.deviceId==="default"||((h=n.label)==null?void 0:h.toLowerCase().includes("default"));if(d&&!l)return-1;if(!d&&l)return 1;if(i.kind==="videoinput"&&n.kind==="videoinput"){const f=r(i),S=r(n);if(f&&!S)return-1;if(!f&&S)return 1}return 0})}async getAvailableDevices(){try{return await this.enumerateDevicesWithExternalFirst()||[]}catch(t){return this.logger.error("enumerate_devices_failed",{error:t}),[]}}async getAvailableDevicesByKind(t){try{return(await this.enumerateDevicesWithExternalFirst()).filter(({kind:e})=>t===e)}catch(e){throw this.logger.error("enumerate_devices_failed",{error:e}),new C("Failed to get available devices by kind","1609")}}async getDevice(t){try{return(await this.enumerateDevicesWithExternalFirst()).filter(r=>r.deviceId===t)[0]}catch(e){throw this.logger.error("enumerate_devices_failed",{error:e}),new C("Failed to get device","1609")}}async onDeviceChange(t){if(Pe.supportsDeviceChangeEvent()){let e=await this.getAvailableDevices();navigator.mediaDevices.addEventListener("devicechange",async r=>{var l,u;const i=h=>`${h.kind}-${h.label}-${h.deviceId}-${h.groupId}`,n=new Set(e.map(h=>i(h))),o=await this.getAvailableDevices(),c=new Set(o.map(h=>i(h))),d={added:o.filter(h=>!n.has(i(h))),removed:e.filter(h=>!c.has(i(h))),devices:o};if(e=o,(l=d.added)!=null&&l.length||(u=d.removed)!=null&&u.length){this.logger.info("repopulated_full_device_list",{devices:JSON.stringify(o)});const h=[...d.added,...d.removed];h.some(f=>f.kind==="audioinput")&&a(this,Xe).getValue("callstats").devices("AUDIO",o==null?void 0:o.filter(f=>f.kind==="audioinput")),h.some(f=>f.kind==="videoinput")&&a(this,Xe).getValue("callstats").devices("VIDEO",o==null?void 0:o.filter(f=>f.kind==="videoinput")),h.some(f=>f.kind==="audiooutput")&&a(this,Xe).getValue("callstats").devices("SPEAKER",o==null?void 0:o.filter(f=>f.kind==="audiooutput")),t(r,d,!1)}},{signal:a(this,ga).signal})}}},ga=new WeakMap,us=new WeakMap,Xe=new WeakMap,Bv);bs([y.trace("WebMediaInterface.destruct")],Gt.prototype,"destruct",1),bs([y.trace("WebMediaInterface.handlePermissionErrors")],Gt.prototype,"handlePermissionErrors",1),bs([y.trace("WebMediaInterface.getAudioAndVideoTrack")],Gt.prototype,"getAudioAndVideoTrack",1),bs([y.trace("WebMediaInterface.getAudioTrack")],Gt.prototype,"getAudioTrack",1),bs([y.trace("WebMediaInterface.getVideoTrack")],Gt.prototype,"getVideoTrack",1),bs([y.trace("WebMediaInterface.getScreenShareTracks")],Gt.prototype,"getScreenShareTracks",1),bs([y.trace("WebMediaInterface.getAvailableDevices")],Gt.prototype,"getAvailableDevices",1),bs([y.trace("WebMediaInterface.getAvailableDevicesByKind")],Gt.prototype,"getAvailableDevicesByKind",1),bs([y.trace("WebMediaInterface.getDevice")],Gt.prototype,"getDevice",1),bs([y.trace("WebMediaInterface.onDeviceChange")],Gt.prototype,"onDeviceChange",1),Gt=bs([pt("1600")],Gt);const US=Gt,xi={setItem:(s,t,e)=>{try{localStorage.setItem(s,t)}catch(r){e==null||e.error("LocalStorage::setItem::crashed",{error:r,localStorage:{key:s,value:t}})}},getItem:(s,t)=>{try{return localStorage.getItem(s)}catch(e){t==null||t.error("LocalStorage::getItem::crashed",{error:e,localStorage:{key:s}})}return null}},ZD=(s=0)=>new Promise(t=>setTimeout(t,s)),e1=(s,t,e)=>{const r=typeof e=="number"?e:250,i=s.createMediaStreamSource(t),n=s.createAnalyser();n.fftSize=2048,i.connect(n);const o=new Uint8Array(n.fftSize);let c=!1;setTimeout(()=>{c=!0},r);function d(){return c?Promise.resolve(!0):(n.getByteTimeDomainData(o),o.some(l=>l!==128&&l!==0)?Promise.resolve(!1):ZD().then(d))}return d().then(l=>(i.disconnect(),l),l=>{throw i.disconnect(),l})},t1=typeof AudioContext!="undefined"?AudioContext:null;class lp{constructor(t){p(this,"_AudioContext");p(this,"audioContext");p(this,"_audioContextRefContainers");const e={AudioContext:t1,...t};Object.defineProperties(this,{_AudioContext:{value:e.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:lp}})}getOrCreate(t){if(!this._audioContextRefContainers.has(t)&&(this._audioContextRefContainers.add(t),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch(e){}return this.audioContext}release(t){this._audioContextRefContainers.has(t)&&(this._audioContextRefContainers.delete(t),!this._audioContextRefContainers.size&&this.audioContext&&(this.audioContext.close(),this.audioContext=null))}}const FS=new lp,s1=3,r1=250;function i1(s){const t={},e=FS.getOrCreate(t);let r=s1;function i(){return r-=1,e1(e,s.srcObject,r1).then(n=>n?r>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{FS.release(t)})}async function BS(s,t){const e=new Audio,r=new MediaStream;r.addTrack(t),e.srcObject=r;let i=!1;try{const n=e.play();n&&await n,i=await i1(e),i&&s.info("checkIfAudioTrackIsSilent::silence_detected")}catch(n){s.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:n})}finally{e.pause(),e.remove()}return i}var n1=Object.defineProperty,a1=Object.getOwnPropertyDescriptor,HS=(s,t,e,r)=>{for(var i=r>1?void 0:r?a1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&n1(t,e,i),i};let Sl=class extends Vn{constructor(t,e,r,i){var o;const n=t.getValue("logger");super(n);p(this,"constructorName",this.constructor.name);p(this,"userSelectedDevice");p(this,"mediaInterface");p(this,"isNonPreferredDevice");p(this,"_mediaTrack");p(this,"transformedMediaTrack");p(this,"middlewares",[]);p(this,"currentDevice");p(this,"userPreferredDeviceKey",`Realtimekit::${this.constructorName}::UserDeviceID`);p(this,"setUserPreferredDevice",t=>xi.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>xi.getItem(this.userPreferredDeviceKey,this.logger));p(this,"isCustomTrack",!1);p(this,"context");this.context=t,this.mediaInterface=e,r&&this.setMediaTrack(r),this.userSelectedDevice=(o=this.getUserPreferredDevice())!=null?o:void 0,this.isNonPreferredDevice=i,this.onTrackEnded=this.onTrackEnded.bind(this),this.onTrackMuted=this.onTrackMuted.bind(this)}get telemetry(){return this.context.getValue("telemetry")}disableTrack(){var t,e;this.removeMediaTrackListeners(),this.isCustomTrack||(t=this._mediaTrack)==null||t.stop(),this._mediaTrack=void 0,(e=this.transformedMediaTrack)==null||e.stop(),this.transformedMediaTrack=void 0}get mediaTrack(){return this._mediaTrack}async setMediaTrack(t,e=!1){const r=i=>{this.logger.error(`${this.constructorName}.setMediaTrack.error`,{error:i})};try{this.disableTrack()}catch(i){r(i)}this._mediaTrack=await this.conditionallyChangeTrack(t,e),await this.setTransformedTrack();try{this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(i){r(i)}}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){this.logger.warn("BaseMediaHandler.muteTrack Tried muting with no track present");return}this.transformedMediaTrack&&(this.transformedMediaTrack.enabled=!1),this.mediaTrack.enabled=!1}async unmuteTrack(){try{this.mediaTrack?this.mediaTrack.enabled=!0:await this.enableTrack(!1)}catch(t){throw this.logger.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new C("Failed to unmute track","1611")}}getCurrentDeviceId(){var e;const{kind:t}=this.mediaTrack;switch(t){case"audio":{const{deviceId:r}=this.mediaTrack.getSettings();if(r)return r;const i=this.mediaTrack.getConstraints();return this.userSelectedDevice?(i&&typeof i.deviceId=="object"&&"exact"in i.deviceId?i.deviceId.exact:i.deviceId)||((e=i==null?void 0:i.advanced)==null?void 0:e[0].deviceId)||"default":this.mediaTrack.getSettings().deviceId}default:return this.mediaTrack.getSettings().deviceId}}async setCurrentDevice(){var e;if(!this.mediaTrack){this.currentDevice=void 0;return}const t=this.getCurrentDeviceId();((e=this.currentDevice)==null?void 0:e.deviceId)!==t&&(this.currentDevice=await this.mediaInterface.getDevice(t))}async setDevice(t,{saveDevicePreference:e}){if(!t)throw this.logger.warn(`${this.constructorName}.setDevice No device received`),new C("No device received!","1603");this.userSelectedDevice=t.deviceId,e&&this.setUserPreferredDevice(t.deviceId),await this.onSetDevice(t)}async addMiddleware(t){if(Pe.isWebKitBased()&&!(Pe.isSafari()&&$k.test(Pe.getVersion())))return{success:!1,message:"Middlewares are not supported in this WebKit engine based browser."};if(this.middlewares.includes(t))return{success:!1,message:"This middleware has been applied, already. Skipping."};try{return this.middlewares.push(t),this.trackEnabled&&await this.setTransformedTrack(),{success:!0,message:"Successfully added the middleware."}}catch(e){return this.logger.error("While adding middleware",{error:e}),this.removeMiddleware(t),{success:!1,message:e==null?void 0:e.message}}}async removeMiddleware(t){const e=this.middlewares.indexOf(t,0);if(e>-1)try{return this.middlewares.splice(e,1),await this.setTransformedTrack(!0),{success:!0,message:"Successfully removed the middleware."}}catch(r){return this.logger.error("While removing middleware",{error:r}),{success:!1,message:r==null?void 0:r.message}}return{success:!1,message:"No such middleware was found. Skipping."}}async removeAllMiddlewares(){var t;if((t=this.middlewares)!=null&&t.length)try{return this.middlewares=[],await this.setTransformedTrack(!0),{success:!0,message:"Successfully removed all the middlewares."}}catch(e){return this.logger.error("While removing all the middlewares",{error:e}),{success:!1,message:e==null?void 0:e.message}}return{success:!1,message:"No middlewares were found. Skipping."}}addMediaTrackListeners(){var t,e,r;this.mediaTrack&&(this.logger.info(`${this.constructorName}.addMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),this.mediaTrack.addEventListener("ended",this.onTrackEnded),this.mediaTrack.addEventListener("mute",this.onTrackMuted))}removeMediaTrackListeners(){var t,e,r;this.mediaTrack&&(this.logger.info(`${this.constructorName}.removeMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),this.logger.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};HS([y.trace("BaseMediaHandler.unmuteTrack")],Sl.prototype,"unmuteTrack",1),Sl=HS([pt("1600")],Sl);const qS=Sl;var o1=Object.defineProperty,c1=Object.getOwnPropertyDescriptor,up=(s,t,e,r)=>{for(var i=r>1?void 0:r?c1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&o1(t,e,i),i};const hp="[Realtimekit]nonSilentDeviceLabels";class vl extends qS{async onSetDevice(t){if(!t)throw this.logger.warn("AudioMediaHandler.setDevice No device received"),new C("No device received!","1603");if(t.kind!=="audioinput")throw this.logger.warn("AudioMediaHandler.setDevice Received non audio device"),new C("Non audio device received while setting device!","1603");try{const e=this.trackEnabled;this.disableTrack(),await this.setMediaTrack(await this.mediaInterface.getAudioTrack(!e,this.userSelectedDevice))}catch(e){throw this.logger.error("AudioMediaHandler.setDevice.error",{error:e}),this.disableTrack(),new C(e.message,"1604")}}async enableTrack(t,e){if(this.trackEnabled){this.logger.warn("AudioMediaHandler.enableTrack Track already enabled!");return}if(e){this.isCustomTrack=!0,await this.setMediaTrack(e,!0);return}this.isCustomTrack=!1;const r=await this.mediaInterface.getAudioTrack(t,this.userSelectedDevice);await this.setMediaTrack(r)}async setTransformedTrack(t){var e;if(!t&&!((e=this.middlewares)!=null&&e.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await VD(this.context,this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(r){this.logger.error("AudioMediaHandler.setTransformedTrack",{error:r}),this.transformedMediaTrack=this.mediaTrack}}async onTrackEnded(){this.logger.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const t=this.mediaTrack.enabled;this.disableTrack(),await this.enableTrack(!t),await this.setTransformedTrack(),this.emit("trackChanged")}onTrackMuted(){this.logger.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(t,e=!1){var d;if(!t||this.userSelectedDevice||e)return t;let r=t;const i=await this.mediaInterface.getAudioInputDevices(),n=this.isNonPreferredDevice?i.filter(l=>l&&!this.isNonPreferredDevice(l)):i;if(!(n!=null&&n.length))return r;n.find(l=>l.deviceId===t.getSettings().deviceId)||(r.stop(),this.logger.info("localmediahandler::setupstreams::found_audio_non_preferred"),r=await this.mediaInterface.getAudioTrack(!1,n[0].deviceId));const o=JSON.parse(xi.getItem(hp,this.logger));if(o!=null&&o.devices.some(l=>l.label===r.label))return r;if(!await BS(this.logger,r)){const l=(d=o==null?void 0:o.devices.concat({label:r.label}))!=null?d:[{label:r.label}];return xi.setItem(hp,JSON.stringify({devices:l}),this.logger),r}this.logger.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const c=r.getSettings().deviceId;return n.filter(l=>l.deviceId!==c).some(async l=>{var u;if(r=await this.mediaInterface.getAudioTrack(!1,l.deviceId),!await BS(this.logger,r)){const h=(u=o==null?void 0:o.devices.concat({label:r.label}))!=null?u:[{label:r.label}];return xi.setItem(hp,JSON.stringify({devices:h}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),r}}up([y.trace("AudioMediaHandler.setTransformedTrack")],vl.prototype,"setTransformedTrack",1),up([y.trace("AudioMediaHandler.onTrackEnded")],vl.prototype,"onTrackEnded",1),up([y.trace("AudioMediaHandler.conditionallyChangeTrack")],vl.prototype,"conditionallyChangeTrack",1);const d1=vl;class l1{constructor(t,e){m(this,rn,void 0);p(this,"currentDevice");p(this,"userPreferredDeviceKey","Realtimekit::speaker::UserDeviceID");p(this,"logger");p(this,"setUserPreferredDevice",t=>xi.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>xi.getItem(this.userPreferredDeviceKey,this.logger));g(this,rn,e),this.logger=t.getValue("logger")}async setPreferredSpeaker(){const t=this.getUserPreferredDevice(),e=await a(this,rn).getAudioOutputDevices(),r=e==null?void 0:e.find(i=>i.deviceId===t);await this.setupSpeaker(r,{saveDevicePreference:!1})}async setupSpeaker(t,{saveDevicePreference:e}){var n,o;if(!(a(this,rn)instanceof US))return;let r=t;if(t||([r]=(await a(this,rn).getAvailableDevicesByKind("audiooutput")).filter(d=>!ml(d))),!r)throw new C("No speaker found","1608");if(((n=this.currentDevice)==null?void 0:n.deviceId)===r.deviceId)return;e&&this.setUserPreferredDevice(r.deviceId),this.currentDevice=r;const i=document.querySelectorAll("audio");(o=i[0])!=null&&o.setSinkId&&i.forEach(async c=>{if(typeof c.sinkId!="undefined"&&this.currentDevice.deviceId&&c.sinkId!==this.currentDevice.deviceId)try{await c.setSinkId(this.currentDevice.deviceId)}catch(d){}})}}rn=new WeakMap;const u1=l1;class h1 extends Vn{constructor(e,r){const i=e.getValue("logger");super(i);p(this,"mediaInterface");p(this,"audioMediaTrack");p(this,"videoMediaTrack");m(this,sc,void 0);g(this,sc,e),this.mediaInterface=r}get trackEnabled(){return!!this.videoMediaTrack}async enableScreenShare(){var e,r;try{const{audioTrack:i,videoTrack:n}=await this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=i,this.videoMediaTrack=n,this.addMediaTrackListeners(),((r=(e=this.mediaInterface)==null?void 0:e.permissions)==null?void 0:r.screenshare)==="ACCEPTED")return;this.mediaInterface.permissions&&(this.mediaInterface.permissions.screenshare="ACCEPTED",a(this,sc).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch(i){}}disableScreenShare(){var e,r;this.removeMediaTrackListeners(),(e=this.audioMediaTrack)==null||e.stop(),(r=this.videoMediaTrack)==null||r.stop(),this.videoMediaTrack=void 0,this.audioMediaTrack=void 0}async updateConstraints(e){if(!this.videoMediaTrack)throw new C("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100",this.logger);try{this.videoMediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(i){this.logger.error("ScreenShareHandler.updateConstraints.error",{error:i})}}addMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this)),Pe.isWebKitBased()&&((r=this.videoMediaTrack)==null||r.addEventListener("mute",this.onTrackEnded.bind(this)))}removeMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(r=this.videoMediaTrack)==null||r.removeEventListener("mute",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}sc=new WeakMap;const p1=h1;var m1=Object.defineProperty,g1=Object.getOwnPropertyDescriptor,Tl=(s,t,e,r)=>{for(var i=r>1?void 0:r?g1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&m1(t,e,i),i};class bo extends qS{constructor(e,r,i,n){super(e,r,i,n);m(this,fa,void 0);m(this,rc,{disablePerFrameCanvasRendering:!1});g(this,fa,new qD(e))}async onSetDevice(e){if(!e)throw this.logger.warn("VideoMediaHandler.setDevice No device received"),new C("No device received!","1603");if(e.kind!=="videoinput")throw this.logger.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new C("Non video device received while setting video device!","1603");if(!(this.mediaTrack&&this.mediaTrack.enabled)){this.logger.warn("VideoMediaHandler.setDevice Tried switching device with video disabled",{devices:[e]}),this.currentDevice=e;return}try{this.disableTrack(),await this.setMediaTrack(await this.mediaInterface.getVideoTrack(this.userSelectedDevice))}catch(r){throw this.logger.error("VideoMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new C("Failed to change device","1600",this.logger)}}async enableTrack(e,r){if(this.trackEnabled){this.logger.warn("VideoMediaHandler.enableTrack Track already enabled!");return}if(r){this.isCustomTrack=!0,await this.setMediaTrack(r,!0);return}this.isCustomTrack=!1;const i=await this.mediaInterface.getVideoTrack(this.userSelectedDevice);await this.setMediaTrack(i)}async setTransformedTrack(e){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await a(this,fa).getTransformedVideoTrack(this.middlewares,this.mediaTrack,a(this,rc)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){g(this,rc,e)}async updateConstraints(e){if(!this._mediaTrack)throw new C("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100",this.logger);try{this._mediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),await this.setTransformedTrack(),this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(i){this.logger.error("VideoMediaHandler.updateConstraints.error",{error:i})}}terminateMiddlewareWebWorker(){a(this,fa).terminateMiddlewareWebWorker()}async onTrackEnded(){this.logger.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")}onTrackMuted(){this.logger.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(e,r=!1){if(!e||this.userSelectedDevice||r)return e;let i=e;const n=await this.mediaInterface.getVideoInputDevices(),o=this.isNonPreferredDevice?n.filter(c=>!this.isNonPreferredDevice(c)):n;return!(o!=null&&o.length)||window.FAST_RTK||o.find(c=>c.deviceId===e.getSettings().deviceId)||(i.stop(),this.logger.info("localmediahandler::setupstreams::found_video_non_preferred"),i=await this.mediaInterface.getVideoTrack(o[0].deviceId)),i}}fa=new WeakMap,rc=new WeakMap,Tl([y.trace("VideoMediaHandler.setTransformedTrack")],bo.prototype,"setTransformedTrack",1),Tl([y.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],bo.prototype,"setVideoMiddlewareGlobalConfig",1),Tl([y.trace("VideoMediaHandler.onTrackEnded")],bo.prototype,"onTrackEnded",1),Tl([y.trace("VideoMediaHandler.conditionallyChangeTrack")],bo.prototype,"conditionallyChangeTrack",1);const f1=bo,jS=Ls(Rh()),va=class{constructor(t){m(this,bt,void 0);m(this,nn,void 0);m(this,ic,void 0);m(this,Sa,void 0);if(!t)throw new C("Could not load preset.","0904");g(this,bt,t.config),g(this,ic,t.name),g(this,nn,t.ui||Ls(Rh().ui)),g(this,Sa,t.permissions.plugins.config)}static fromResponse(t){return new va(t)}static default(){return new va(jS)}static init(t,e=!0){return!t||e?new va(jS):new va(t)}get setupScreen(){return{isEnabled:!0}}get waitingRoom(){return{isEnabled:!0}}get controlBar(){return{isEnabled:!0,elements:{chat:!0,fullscreen:!0,invite:!1,layout:!1,participants:!0,plugins:!0,polls:!0,reactions:!1,screenshare:!0}}}get header(){return{isEnabled:!0,elements:{logo:a(this,nn).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return a(this,bt).viewType}get livestreamViewerQualities(){return a(this,bt).livestreamViewerQualities||[]}get maxVideoStreams(){return a(this,bt).maxVideoStreams}get maxScreenShareCount(){return a(this,bt).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(a(this,Sa)).filter(t=>a(this,Sa)[t].disabled)}get designTokens(){return a(this,nn).designTokens}get configDiff(){return a(this,nn).configDiff}get isSimulcastEnabled(){var t,e,r,i;return(i=(r=(e=(t=a(this,bt))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:r.simulcast)!=null?i:!1}get mediaConstraints(){var t,e,r,i,n,o,c,d,l,u,h,f,S,E,k,R,D,N,F,U,B,Z,ie,H;return{audio:{enableStereo:(i=(r=(e=(t=a(this,bt))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:jn.audio.enableStereo,enableHighBitrate:(d=(c=(o=(n=a(this,bt))==null?void 0:n.media)==null?void 0:o.audio)==null?void 0:c.enableHighBitrate)!=null?d:jn.audio.enableHighBitrate},video:{quality:(f=(h=(u=(l=a(this,bt))==null?void 0:l.media)==null?void 0:u.video)==null?void 0:h.quality)!=null?f:jn.video.quality,frameRate:(R=(k=(E=(S=a(this,bt))==null?void 0:S.media)==null?void 0:E.video)==null?void 0:k.frameRate)!=null?R:jn.video.frameRate},screenshare:{quality:(U=(F=(N=(D=a(this,bt))==null?void 0:D.media)==null?void 0:N.screenshare)==null?void 0:F.quality)!=null?U:jn.screenshare.quality,frameRate:(H=(ie=(Z=(B=a(this,bt))==null?void 0:B.media)==null?void 0:Z.screenshare)==null?void 0:ie.frameRate)!=null?H:jn.screenshare.frameRate}}}get name(){return a(this,ic)}};let pp=va;bt=new WeakMap,nn=new WeakMap,ic=new WeakMap,Sa=new WeakMap;var S1=Object.defineProperty,v1=Object.getOwnPropertyDescriptor,GS=(s,t,e,r)=>{for(var i=r>1?void 0:r?v1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&S1(t,e,i),i};class mp extends Ft{constructor(e,r){const i=e.getValue("logger");super(i);m(this,Ta,void 0);p(this,"state","IDLE");p(this,"playbackUrl");p(this,"ingestionCredentials");p(this,"viewerCount");m(this,nc,void 0);g(this,Ta,r),g(this,nc,e),this.viewerCount=0}get telemetry(){return a(this,nc).getValue("telemetry")}setLivestreamState(e){const r=this.state;this.state=e,r!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}async start(e={manualIngestion:!1}){if(!a(this,Ta).permissions.canLivestream)throw this.logger.error("Livestream::start::permission_denied"),new C("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const r=Ht(),{playbackUrl:i,ingestionCredentials:n}=await r.startLivestreaming(e);this.playbackUrl=i,this.ingestionCredentials=n,e!=null&&e.manualIngestion&&this.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}catch(r){throw this.logger.error("Recording::stop::livestream_failed_to_start",{error:r}),this.setLivestreamState("IDLE"),new C("Error while starting livestream","1900",this.logger)}}async stop(){if(!a(this,Ta).permissions.canLivestream)throw this.logger.error("Livestream::stop::permission_denied"),new C("User does not have permission to stop livestreaming","1901");if(this.state!=="LIVESTREAMING"&&this.state!=="WAITING_ON_MANUAL_INGESTION")throw this.logger.error("Livestream::stop::inconsistent_state"),new C("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),await Ht().stopLivestreaming()}catch(e){throw this.logger.error("Livestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new C("Error while stopping livestream","1900",this.logger)}}}Ta=new WeakMap,nc=new WeakMap,GS([y.trace("livestream.start")],mp.prototype,"start",1),GS([y.trace("livestream.stop")],mp.prototype,"stop",1);var T1=Object.defineProperty,y1=Object.getOwnPropertyDescriptor,E1=(s,t,e,r)=>{for(var i=r>1?void 0:r?y1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&T1(t,e,i),i};class WS{constructor(t,e,r){p(this,"livestream");m(this,ya,void 0);m(this,Ea,void 0);m(this,br,void 0);m(this,Fs,void 0);g(this,Fs,t),g(this,Ea,e),this.livestream=new mp(t,e),g(this,br,r),this.setupEvents()}get logger(){return a(this,Fs).getValue("logger")}get telemetry(){return a(this,Fs).getValue("telemetry")}async fetchInitialLivestreamingState(){const t=Ht(),{status:e,playbackUrl:r,manualIngest:i,ingestionCredentials:n}=await t.getActiveLivestream();this.livestream.playbackUrl=r,this.livestream.ingestionCredentials=n,e==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),e==="INVOKED"&&i&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}setupEvents(){a(this,br).on($.startedLivestream,async t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{a(this,Ea).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}}),a(this,br).on($.livestreamingInvoked,async t=>{if(t.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{a(this,Ea).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}}),a(this,br).on($.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),a(this,br).on($.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),a(this,br).on($.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),a(this,Fs).getValue("peerSessionStore").on(P.PEER_JOINED_INTERNAL,async t=>{var e;((e=t.flags)==null?void 0:e.hiddenParticipant)===!0&&t.recorderType==="LIVESTREAMER"&&(g(this,ya,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),a(this,Fs).getValue("peerSessionStore").on(P.PEER_CLOSED,t=>{t.id===a(this,ya)&&(g(this,ya,void 0),this.livestream.setLivestreamState("IDLE"))}),a(this,Fs).getValue("peerSessionStore").onAsync(P.LEAVE_MEDIA_ROOM,async()=>{if(!this.livestream.playbackUrl){this.logger.info("Fetching livestreaming state on leave stage");try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Failed to fetch livestreaming state on leave stage",{error:t})}}}),a(this,Fs).getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Error: LivestreamController.fetchLivestream")}})}}ya=new WeakMap,Ea=new WeakMap,br=new WeakMap,Fs=new WeakMap,E1([y.trace("LivestreamController.setupEvents")],WS.prototype,"setupEvents",1);var b1=Object.defineProperty,w1=Object.getOwnPropertyDescriptor,wo=(s,t,e,r)=>{for(var i=r>1?void 0:r?w1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&b1(t,e,i),i};class Gn{constructor({name:t,socketHandler:e,meetingId:r}){m(this,zl);p(this,"name","");m(this,ct,{});m(this,ai,"");m(this,oi,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"bulkRateLimitConfig",{maxInvocations:5,period:1});p(this,"listeners",{});this.name=t,g(this,oi,e),g(this,ai,r)}async set(t,e,r=!0,i=!1){a(this,ct)[t]=e,r&&this.remoteSet(t,e),i&&(this.listeners[t]&&this.listeners[t].forEach(n=>n({[t]:a(this,ct)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(n=>n({[t]:a(this,ct)[t]})))}remoteSet(t,e){a(this,oi).storeInsertKeys(a(this,ai),this.name,[{key:t,payload:e}])}async bulkSet(t){t.forEach(({key:e,payload:r})=>{a(this,ct)[e]=r}),a(this,oi).storeInsertKeys(a(this,ai),this.name,t)}async update(t,e,r=!0){I(this,zl,Zv).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(a(this,ct)[t]&&delete a(this,ct)[t],e)return a(this,oi).storeDeleteKeys(a(this,ai),this.name,[{key:t}]);r&&(this.listeners[t]&&(this.listeners[t].forEach(i=>i({[t]:void 0})),delete this.listeners[t]),this.listeners["*"]&&this.listeners["*"].forEach(i=>i({[t]:void 0})))}async bulkDelete(t){return t.forEach(({key:e})=>{a(this,ct)[e]&&delete a(this,ct)[e]}),a(this,oi).storeDeleteKeys(a(this,ai),this.name,t)}get(t){if(a(this,ct)[t])return a(this,ct)[t]}getAll(){return a(this,ct)}clear(){g(this,ct,{})}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(t,e){this.bulkRateLimitConfig.maxInvocations=t,this.bulkRateLimitConfig.period=e}subscribe(t,e){if(this.listeners[t]){this.listeners[t].push(e);return}this.listeners[t]=[e]}unsubscribe(t,e){var r;if(e){this.listeners[t]=((r=this.listeners[t])==null?void 0:r.filter(i=>i!==e))||[];return}this.listeners[t]&&delete this.listeners[t]}populate(t){g(this,ct,t)}}ct=new WeakMap,ai=new WeakMap,oi=new WeakMap,zl=new WeakSet,Zv=function(t,e,r=!0){let i;const n=a(this,ct)[t],o=Object.prototype.toString.call(e),c=Object.prototype.toString.call(n);if(o!==c){this.set(t,e);return}switch(c){case"[object Array]":i=[...n,...e];break;case"[object Object]":i={...n,...e};break;case"[object Map]":i=new Map([...n,...e]);break;case"[object Set]":i=new Set([...n,...e]);break;default:i=e;break}this.set(t,i,r)},wo([qt(Hn,"rateLimitConfig")],Gn.prototype,"remoteSet",1),wo([qt(Hn,"bulkRateLimitConfig")],Gn.prototype,"bulkSet",1),wo([qt(Hn,"rateLimitConfig")],Gn.prototype,"update",1),wo([qt(Hn,"rateLimitConfig")],Gn.prototype,"delete",1),wo([qt(Hn,"bulkRateLimitConfig")],Gn.prototype,"bulkDelete",1);class P1{constructor(t,e){m(this,ac);m(this,Yl);p(this,"stores",new Map);m(this,ci,void 0);m(this,di,"");m(this,oc,void 0);m(this,ks,new Map);g(this,ci,e),g(this,di,t.getValue("meetingId")),g(this,oc,t),I(this,Yl,eT).call(this)}create(t,e=!1){if(Uk.includes(t)&&!e)throw new C(`'${t}' is a reserved store name.`,"0601");const r=new Gn({name:t,socketHandler:a(this,ci),meetingId:a(this,di)});return a(this,ci).storeGetKeys(a(this,di),t,[]),new Promise((n,o)=>{const c=setTimeout(()=>{a(this,ks).delete(t),o(Error("Failed"))},3e3);a(this,ks).set(t,{rejectTimeout:c,resolve:n,store:r})})}refresh(t){const e=this.stores.get(t);return e?(e.clear(),a(this,ci).storeGetKeys(a(this,di),t,[]),new Promise((i,n)=>{const o=setTimeout(()=>{a(this,ks).delete(t),n(Error("Store refresh timed out"))},3e3);a(this,ks).set(t,{rejectTimeout:o,resolve:i,store:e})})):Promise.reject(Error(`Store '${t}' does not exist`))}}ci=new WeakMap,di=new WeakMap,ac=new WeakSet,Wp=function(){return a(this,oc).getValue("peerId")},oc=new WeakMap,ks=new WeakMap,Yl=new WeakSet,eT=function(){[or.storeInsertKeys,or.storeGetKeys,or.storeDeleteKeys].forEach(t=>{a(this,ci).on(t,async e=>{var n,o;if(e.pluginId!==a(this,di))return;const r=(n=e.storeItems)==null?void 0:n.map(c=>{var d;return{timestamp:c.timestamp,peerId:c.peerId,payload:JSON.parse((d=c.payload)!=null&&d.length?new TextDecoder().decode(c.payload):"{}"),key:c.storeKey}});if(t===or.storeGetKeys){const c=a(this,ks).get(e.storeName),d=this.stores.get(e.storeName)||(c==null?void 0:c.store);if(a(this,ks).get(e.storeName)&&(this.stores.set(e.storeName,c.store),c.resolve(d),clearTimeout(c.rejectTimeout),a(this,ks).delete(e.storeName)),!d)return;r.forEach(l=>{d.set(l.key,l.payload,!1,!1)});return}const i=this.stores.get(e.storeName)||((o=a(this,ks).get(e.storeName))==null?void 0:o.store);i!==void 0&&(t===or.storeInsertKeys&&r.forEach(({key:c,peerId:d,payload:l})=>{d!==a(this,ac,Wp)&&i.set(c,l,!1,!0)}),t===or.storeDeleteKeys&&r.forEach(({key:c,peerId:d})=>{d!==a(this,ac,Wp)&&i.delete(c,!1,!0)}))})})};function $i(s){var t,e,r,i,n,o,c,d,l,u,h,f,S;return s?{media:{audio:{enabled:s.audioEnabled,trackId:(t=s.audioTrack)==null?void 0:t.id,permission:"mediaPermissions"in s?(e=s.mediaPermissions)==null?void 0:e.audio:null},video:{enabled:s.videoEnabled,trackId:(r=s.videoTrack)==null?void 0:r.id,permission:"mediaPermissions"in s?(i=s.mediaPermissions)==null?void 0:i.video:null},screenshare:{enabled:s.screenShareEnabled,permission:"mediaPermissions"in s?(n=s.mediaPermissions)==null?void 0:n.screenshare:null,audio:{enabled:(c=(o=s.screenShareTracks)==null?void 0:o.audio)==null?void 0:c.enabled,trackId:(l=(d=s.screenShareTracks)==null?void 0:d.audio)==null?void 0:l.id},video:{enabled:(h=(u=s.screenShareTracks)==null?void 0:u.video)==null?void 0:h.enabled,trackId:(S=(f=s.screenShareTracks)==null?void 0:f.video)==null?void 0:S.id}}}}:{}}var _1=Object.defineProperty,k1=Object.getOwnPropertyDescriptor,Wn=(s,t,e,r)=>{for(var i=r>1?void 0:r?k1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&_1(t,e,i),i};const C1=.8,R1=1.2;let hr=(Hv=class extends Ft{constructor(t,e,r,i){const n=t.getValue("logger");super(n);m(this,an);m(this,li);m(this,on);m(this,Ql);m(this,cn);m(this,dc);m(this,Zl);m(this,eu);p(this,"id");p(this,"userId");p(this,"name");p(this,"picture");p(this,"isHost");p(this,"customParticipantId");p(this,"flags");p(this,"device");p(this,"videoTrack");p(this,"audioTrack");p(this,"screenShareTracks");p(this,"videoEnabled");p(this,"audioEnabled");p(this,"screenShareEnabled");p(this,"producers");p(this,"manualProducerConfig");m(this,ba,void 0);p(this,"supportsRemoteControl",!1);m(this,wa,void 0);p(this,"presetName");m(this,Kt,void 0);m(this,wt,void 0);m(this,cc,void 0);m(this,ui,new Map);m(this,wr,1);m(this,Xl,wh(t=>{if(!this.videoTrack)return;const{clientWidth:e,clientHeight:r}=t,{width:i,height:n}=this.videoTrack.getSettings();if(!i||!n)return;const o=n/r,c=i/e,d=Math.max(o,c);d>R1&&a(this,wr)===1?(g(this,wr,0),a(this,Kt).getValue("peerSessionStore").emit(P.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,wr)})):d<C1&&a(this,wr)===0&&(g(this,wr,1),a(this,Kt).getValue("peerSessionStore").emit(P.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,wr)}))},2e3));g(this,Kt,t);const{id:o,userId:c,displayName:d,device:l,picture:u,isHost:h,flags:f,stageStatus:S,customParticipantId:E,audioMuted:k,audioTrack:R,videoEnabled:D=!1,videoTrack:N,producers:F,metadata:U}=e;this.id=o,this.userId=c,this.name=d,this.device=l,this.picture=u,this.isHost=h,this.flags=f,this.manualProducerConfig=Ok,g(this,wa,S!=null?S:"ON_STAGE"),this.customParticipantId=E,this.audioEnabled=!k,this.audioTrack=R,this.videoEnabled=D,this.videoTrack=N,this.screenShareTracks={audio:void 0,video:void 0},this.producers=F!=null?F:[],this.presetName=U==null?void 0:U.preset_name,g(this,ba,!1),g(this,wt,r),g(this,cc,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),I(this,dc,Jp).call(this)}get stageStatus(){return a(this,wa)}get telemetry(){return a(this,Kt).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("Participant::setVideoEnabled::videoUpdate",{...$i(this)}),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(this.logger.info("Participant::setAudioEnabled::audioUpdate",{...$i(this)}),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}))}setScreenShareEnabled(t,e=!0){this.screenShareEnabled=t,e&&this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}setupEvents(){this.on("videoUpdate",I(this,dc,Jp)),a(this,li,Xa)&&(this.on("audioUpdate",I(this,Zl,sT)),this.on("screenShareUpdate",I(this,eu,rT)))}async pin(){if(!a(this,on,vd))throw new C("Can`t pin participant without joining room","1205");if(!a(this,wt).permissions.pinParticipant)throw new C("You do not have permission to pin participants.","1201");return a(this,an,Sd).pinPeer(this.id)}async unpin(){if(!a(this,on,vd))throw new C("Can`t unpin participant without joining room","1205");if(!a(this,wt).permissions.pinParticipant)throw new C("You do not have permission to unpin participants.","1201");return a(this,an,Sd).pinPeer(null)}setIsPinned(t,e=!0){var i;g(this,ba,t);const r=t?"pinned":"unpinned";(i=a(this,cn,Td))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}async disableAudio(){const t=this.id;if(this.logger.info(`Local peer ${a(this,wt).id} is disabling mic of a remote peer ${t}`),!a(this,on,vd))throw new C("Can`t disable participant audio without joining room","1205");if(a(this,wt).permissions.canDisableParticipantAudio)return a(this,an,Sd).disableAudio(t);throw this.logger.error(`Local peer ${a(this,wt).id} is not authorized to disable mic of a remote peer ${t}`),new C("Unauthorized: User does not have permission to disable participant audio.","1201")}async kick(){const t=this.id;if(this.logger.info(`Local peer ${a(this,wt).id} is kicking a remote peer ${t} out of the meeting.`),!a(this,Ql,tT))throw new C("Can`t kick participant without joining room","1205");if(a(this,wt).permissions.kickParticipant){await a(this,Kt).getValue("peerSessionStore").emitAsync(P.KICK_PEER,{peerId:t});return}throw this.logger.error(`Local peer ${a(this,wt).id} is not authorized to kick a remote peer ${t} out of the meeting.`),new C("Unauthorized: User does not have permission to kick participants.","1201")}async disableVideo(){const t=this.id;if(this.logger.info(`Local peer ${a(this,wt).id} is disabling webcam of a remote peer ${t}.`),!a(this,on,vd))throw new C("Can`t disable participant video without joining room","1205");if(a(this,wt).permissions.canDisableParticipantVideo)return a(this,an,Sd).disableVideo(t);throw this.logger.error(`Local peer ${a(this,wt).id} is not authorized to disable webcam of a remote peer ${t}.`),new C("Unauthorized: User does not have permission to disable participant video.","1201")}async getPermissions(){return a(this,cc).getUserPermissions(this.userId)}setStageStatus(t){g(this,wa,t),this.emit("stageStatusUpdate",this)}get isPinned(){return a(this,ba)}registerVideoElement(t){var r,i,n,o;if(!t)return;let e;(i=(r=a(this,ui).get(t))==null?void 0:r.observer)==null||i.disconnect(),"ResizeObserver"in window&&(e=new ResizeObserver(()=>a(this,Xl).call(this,t)),e.observe(t)),a(this,ui).set(t,{observer:e}),this.updateVideo(t),(o=a(this,cn,Td))==null||o.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(n=this.raised)!=null?n:!1)}deregisterVideoElement(t){var e,r,i,n;if(!t){(e=a(this,cn,Td))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=a(this,ui).get(t))==null?void 0:r.observer)==null||i.disconnect(),a(this,ui).delete(t),(n=a(this,cn,Td))==null||n.removeSource(this.id)}updateVideo(t){var e;if(this.videoEnabled){if(this.videoTrack==null)return;const r=(e=t.srcObject)==null?void 0:e.getTracks()[0];if((r==null?void 0:r.id)===this.videoTrack.id)return;const i=new MediaStream;i.addTrack(this.videoTrack),t.srcObject=i}else t.srcObject=void 0;t.style.display=this.videoEnabled?"block":"none"}},ba=new WeakMap,wa=new WeakMap,Kt=new WeakMap,an=new WeakSet,Sd=function(){return a(this,Kt).getValue("roomNodeClient")},li=new WeakSet,Xa=function(){return a(this,Kt).getValue("audioPlayback")},on=new WeakSet,vd=function(){return a(this,Kt).getValue("connectionHandler").mediaJoined},Ql=new WeakSet,tT=function(){return a(this,Kt).getValue("connectionHandler").socketJoined},wt=new WeakMap,cc=new WeakMap,ui=new WeakMap,cn=new WeakSet,Td=function(){return a(this,Kt).getValue("pip")},wr=new WeakMap,Xl=new WeakMap,dc=new WeakSet,Jp=function(){Array.from(a(this,ui).keys()).forEach(this.updateVideo)},Zl=new WeakSet,sT=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=a(this,li,Xa))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=a(this,li,Xa))==null||e.removeParticipantTrack(this.id)},eu=new WeakSet,rT=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=a(this,li,Xa))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=a(this,li,Xa))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},Hv);Wn([y.trace("Participant.disableAudio")],hr.prototype,"disableAudio",1),Wn([y.trace("Participant.kick")],hr.prototype,"kick",1),Wn([y.trace("Participant.disableVideo")],hr.prototype,"disableVideo",1),Wn([y.trace("Participant.getPermissions")],hr.prototype,"getPermissions",1),Wn([y.trace("Participant.setStageStatus")],hr.prototype,"setStageStatus",1),hr=Wn([pt("1200")],hr);class Po extends CS{constructor(t,e){const{onAddEvent:r="participantJoined",onDeleteEvent:i="participantLeft",onClearEvent:n="participantsCleared"}=e!=null?e:{};super({onAddEvent:r,onDeleteEvent:i,onClearEvent:n},t)}add(t,e=!0){return this.has(t.id)&&Object.is(this.get(t.id),t)===!1&&this.delete(t.id),super.add(t,e)}clear(t=!0,e=!1){return super.clear(t,e)}delete(t,e=!0,r=!1){return super.delete(t,e,r)}}class I1 extends Vn{constructor(e){super(e);m(this,hi,void 0);g(this,hi,new Map)}__set(e,r){return a(this,hi).set(e,r)}__clear(){return a(this,hi).clear()}get(e){return a(this,hi).get(e)}toArray(){return Array.from(a(this,hi).values())}}hi=new WeakMap;class A1{constructor(){p(this,"_orderedArray");p(this,"_map");this._map=new Map,this._orderedArray=[]}add(t,e){if(!this._map.has(t))return this._map.set(t,{peerId:t,priority:e}),this._orderedArray.splice(Math.max(e-1,0),0,t),this.index(t);const r=this.index(t);this.delete(t);const i=this.add(t,e);return r!==i?i:-1}delete(t){if(this._map.has(t)){const e=this.index(t);this._map.delete(t),this._orderedArray.splice(e,1)}}index(t){return this._map.has(t)?this._orderedArray.indexOf(t):-1}[Symbol.iterator](){return this._orderedArray[Symbol.iterator]()}}class M1{constructor(){p(this,"_activeSpeakerPeers");p(this,"_compulsoryPeers");this._activeSpeakerPeers=new A1,this._compulsoryPeers=new Set}add(t,e,r){if(!t)return-1;if(e<0)return this._compulsoryPeers.add(t),0;const i=r.getValue("logger");if(this.compulsoryPeers.includes(t)&&(e>0||e===246267631)){if(i.info("SelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),e===246267631)return-1}else if(e===229490415)return this.delete(t,r),-1;return this._activeSpeakerPeers.add(t,e)}delete(t,e){const r=e==null?void 0:e.getValue("logger");r==null||r.info("SelectedPeer::deleting_peer_from_selectedPeer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),this._activeSpeakerPeers.delete(t)}reassignPeer(t,e,r){const i=this._activeSpeakerPeers.index(t),n=this._compulsoryPeers.has(t);this.delete(t,r),n&&this.add(e,-1,r),i>=0&&this.add(e,i+1,r)}index(t){return this._activeSpeakerPeers.index(t)}get peers(){return Array.from(new Set(this.compulsoryPeers.concat(this.activeSpeakerPeers)))}get compulsoryPeers(){return Array.from(this._compulsoryPeers.values())}get activeSpeakerPeers(){return Array.from(this._activeSpeakerPeers)}_removeFromCompulsoryPeer(t){this._compulsoryPeers.delete(t)}}const JS=new M1;var O1=Object.defineProperty,D1=Object.getOwnPropertyDescriptor,$s=(s,t,e,r)=>{for(var i=r>1?void 0:r?D1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&O1(t,e,i),i};const N1=["ACTIVE_GRID","PAGINATED","MANUAL"];let ns=(qv=class extends Ft{constructor(t,e,r){const i=t.getValue("logger");super(i);m(this,lc);m(this,dn);m(this,Pa);p(this,"waitlisted");p(this,"joined");p(this,"active");p(this,"videoSubscribed");p(this,"audioSubscribed");p(this,"pinned");p(this,"all");m(this,xe,void 0);m(this,ln,void 0);m(this,Vt,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"viewMode");p(this,"currentPage");p(this,"lastActiveSpeaker");p(this,"selectedPeers",JS);g(this,xe,t),g(this,ln,e),g(this,Vt,r),this.waitlisted=new Po(i),this.joined=new Po(i),this.videoSubscribed=new Po(i),this.audioSubscribed=new Po(i),this.active=this.videoSubscribed,this.pinned=new Po(i),this.all=new I1(i),this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return a(this,xe).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return a(this,xe).getValue("telemetry")}setupEvents(){a(this,xe).getValue("peerSessionStore").on(P.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=a(this,xe).getValue("modules").e2ee)==null?void 0:r.enabled)!==!0&&this.emit("media_decode_error",{reason:`Got encrypted media for participantId ${e}, but encryption wasn't enabled in init.defaults`,code:"1702"})});const t=a(this,xe).getValue("audioPlayback");t&&this.audioSubscribed.on("participantLeft",e=>{t.removeParticipantTrack(e.id)})}get count(){return this.joined.size}get maxActiveParticipantsCount(){var t;return(t=a(this,xe))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new C("0 <= Max active participants count limit <= 24","1203");a(this,xe).setValue("maxPreferredStreams",t),a(this,Pa,Yu)&&a(this,xe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.selectedPeers.compulsoryPeers.length,e=this.joined.toArray().filter(r=>r.stageStatus==="ON_STAGE");return Math.ceil((e.length-t)/Math.max(this.maxActiveParticipantsCount-t,1))}return 0}acceptWaitingRoomRequest(t){var r,i;if(!a(this,dn,yd))throw new C("Can`t accept waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;return a(this,Vt).acceptWaitingRoomRequest([e])}async acceptAllWaitingRoomRequest(t){const e=t.map(r=>{var i,n;return(n=(i=this.waitlisted.get(r))==null?void 0:i.userId)!=null?n:r});return a(this,Vt).acceptWaitingRoomRequest(e)}async rejectWaitingRoomRequest(t){var r,i;if(!a(this,dn,yd))throw new C("Can`t reject waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;a(this,Vt).rejectWaitingRoomRequest([e])}async setViewMode(t){if(this.logger.info("Participants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(r=>N1.includes(r))(t))throw this.logger.error("Participants::setViewMode::invalid_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),new C(`Invalid view mode: ${t}. Try ACTIVE_GRID, PAGINATED or MANUAL.`,"1207");if(this.viewMode===t){this.logger.info("Participants::setViewMode::view_mode_same_as_previous");return}this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,a(this,xe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,a(this,xe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,a(this,xe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})}async subscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new C("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)))}),a(this,xe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}async unsubscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new C("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!1},i.manualProducerConfig.screenshareAudio||this.audioSubscribed.delete(i.id)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!1},i.manualProducerConfig.screenshareVideo||this.videoSubscribed.delete(i.id)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!1},i.manualProducerConfig.audio||this.audioSubscribed.delete(i.id)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!1},i.manualProducerConfig.video||this.videoSubscribed.delete(i.id)))}),a(this,xe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}getPeerIdsForCurrentPage(){this.logger.info("Participants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(c=>this.joined.has(c)),r=Array.from(this.pinned.keys()).filter(c=>!e.includes(c)),i=Array.from(this.joined.toArray().filter(c=>c.stageStatus==="ON_STAGE").map(c=>c.id)),n=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),o=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,i.slice(n,o))}async setPage(t){if(this.logger.info("Participants::set_page",{pageNavigation:{settingPage:t,viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),this.viewMode==="PAGINATED"){if(!Number.isInteger(t))throw this.logger.error("Participants::invalid_page_number"),new C(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`,"1202");this.currentPage=t,a(this,xe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.viewMode,page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}}async disableAllAudio(t){if(this.logger.info("Participants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!a(this,Pa,Yu))throw new C("Can`t disable all audio without joining room","1205");if(a(this,ln).permissions.canAllowParticipantAudio)return a(this,lc,Kp).muteAll(t);throw this.logger.error("Participants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new C("Unauthorized: User does not have permission to disable peer audio.","1201")}async disableAllVideo(){if(this.logger.info("Participants::disable_all_video"),!a(this,Pa,Yu))throw new C("Can`t disable all video without joining room","1205");if(a(this,ln).permissions.canAllowParticipantVideo)return a(this,lc,Kp).muteAllVideo();throw this.logger.error("Participants::unauthorized_disable_all_video"),new C("Unauthorized: User does not have permission to disable peer video.","1201")}async kickAll(){if(this.logger.info("Participants::kick_all"),a(this,xe).getValue("viewType")!=="LIVESTREAM"&&!a(this,dn,yd))throw new C("Can`t kick all without joining room","1205");if(!a(this,ln).permissions.kickParticipant)throw this.logger.error("Participants::unauthorized_kick_all"),new C("Unauthorized: User does not have permission to kick peers.","1201");const e=!0;a(this,Vt).kickAll(e)}async broadcastMessage(t,e,r){if(this.logger.info("Participants::broadcastMessage"),!a(this,dn,yd))throw new C("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new C("`type` must be a non-empty string.","1209");if(r)if("meetingIds"in r)await a(this,Vt).broadcastToMeetings(t,r.meetingIds,e);else{let i=[];"participantIds"in r?i=r.participantIds:i=this.joined.toArray().filter(n=>{var o;return(o=r.presetNames)==null?void 0:o.includes(n.presetName)}).map(n=>n.id),await a(this,Vt).broadcastToPeers(t,i,e)}else await a(this,Vt).broadcastMessage(t,e)}async getAllJoinedPeers(t,e,r){return(await a(this,Vt).getRoomPeers(t,e,r)).peers.map(pr.formatSocketPeerMessage)}async updatePermissions(t,e){const r=this.joined.toArray().filter(n=>t.includes(n.id)).map(n=>n.userId),i=[...new Set(r)];if(!i.length)throw new C("Cannot update permissions, no valid userIDs found","1204");a(this,Vt).updatePermissions(i,e)}async getParticipantsInMeetingPreJoin(){return a(this,Vt).getRoomPeersNonPaginated()}},xe=new WeakMap,lc=new WeakSet,Kp=function(){return a(this,xe).getValue("roomNodeClient")},dn=new WeakSet,yd=function(){var t;return((t=a(this,xe).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},Pa=new WeakSet,Yu=function(){var t;return((t=a(this,xe).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},ln=new WeakMap,Vt=new WeakMap,qv);$s([y.trace("Participants.setViewMode")],ns.prototype,"setViewMode",1),$s([y.trace("Participants.setPage")],ns.prototype,"setPage",1),$s([y.trace("Participants.disableAllAudio")],ns.prototype,"disableAllAudio",1),$s([y.trace("Participants.disableAllVideo")],ns.prototype,"disableAllVideo",1),$s([y.trace("Participants.kickAll")],ns.prototype,"kickAll",1),$s([y.trace("Participants.broadcastMessage"),qt(Hn,"rateLimitConfig")],ns.prototype,"broadcastMessage",1),$s([y.trace("Participants.getAllJoinedPeers"),qt({maxInvocations:10,period:60})],ns.prototype,"getAllJoinedPeers",1),$s([y.trace("Participant.updatePermissions"),qt({maxInvocations:1e3,period:60})],ns.prototype,"updatePermissions",1),$s([y.trace("Participants.getParticipantsInMeetingPreJoin")],ns.prototype,"getParticipantsInMeetingPreJoin",1),ns=$s([pt("1200")],ns);var L1=Object.defineProperty,V1=Object.getOwnPropertyDescriptor,Ui=(s,t,e,r)=>{for(var i=r>1?void 0:r?V1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&L1(t,e,i),i};const x1=5e3,$1=1e4,_o=(jv=class{constructor(s,t,e){m(this,hn);m(this,tu);m(this,su);m(this,uc);m(this,ru);m(this,iu);p(this,"participants");p(this,"self");p(this,"selectedPeers",JS);p(this,"maxSpatialLayerUpdates",new Map);p(this,"consumerPeerMap");p(this,"events");p(this,"roomSocketHandler");p(this,"context");p(this,"videoPeerConsumerMap",new Map);m(this,hs,{mode:"ACTIVE_GRID",page:0});m(this,Bs,!1);m(this,pi,!1);p(this,"isRebuildingReconnectSnapshot",!1);m(this,Ze,new Map);m(this,Pr,void 0);m(this,un,void 0);m(this,nu,({state:s})=>{s==="disconnected"||s==="stageLeft"||(this.isRebuildingReconnectSnapshot=!1,I(this,iu,oT).call(this),a(this,Ze).clear(),g(this,Pr,void 0))});p(this,"updateConsumerSpatialLayers",wh(()=>{const s={},t=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(t.entries()).forEach(([e,r])=>{s[r]===void 0&&(s[r]={layer:r,consumerIds:[]}),s[r].consumerIds.push(e)}),Object.keys(s).forEach(e=>{const r=s[e];this.logger.log(`Switching max spatial layer to ${r.layer}`,{consumerIds:r.consumerIds}),this.roomNodeClient.switchConsumersToLayer(r.consumerIds,r.layer)})},2e3));p(this,"updateConsumers",async(s,t)=>{this.logger.info(`updateConsumers: Starting serialized consumer updates: createProducerIds=[${s.map(({producerId:e})=>e).join(",")}], deleteConsumerIds=[${t.join(",")}], consumersSyncing=${a(this,Bs)}.`);try{s.length!==0&&(this.logger.info(`updateConsumers: Creating consumers for producerIds=[${s.map(({producerId:e})=>e).join(",")}].`),await this.roomNodeClient.createConsumers(s),this.logger.info("updateConsumers: Successfully created consumers."))}catch(e){this.logger.error("updateConsumers: Error creating consumers",{error:e})}try{t.length!==0&&(this.logger.info(`updateConsumers: Closing consumers after grace period: consumerIds=[${t.join(",")}].`),await this.roomNodeClient.closeConsumersById(t),this.logger.info("updateConsumers: Successfully closed consumers."))}catch(e){this.logger.error("updateConsumers: Error closing consumers",{error:e})}this.logger.info("updateConsumers: Completed consumer updates.")});this.context=s,this.roomSocketHandler=e,this.participants=new ns(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,this.events=Es,t.config.viewType!=="CHAT"&&(this.setupEventsGlobal(),I(this,ru,aT).call(this)),this.setupEvents(),this.self.on("roomLeft",a(this,nu))}get roomNodeClient(){return this.context.getValue("roomNodeClient")}get mediaJoined(){var s;return((s=this.roomNodeClient)==null?void 0:s.mediaJoined)===!0}get pip(){return this.context.getValue("pip")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}handleSocketPeers(s){var d;const t=new Set(this.roomSocketHandler.socket.supersededLocalPeerIds),e=(d=s==null?void 0:s.filter(l=>!l.waitlisted&&!t.has(l.peerId)))!=null?d:[],r=new Set(e.map(({peerId:l})=>l)),i=t.size>0||this.participants.joined.size>0,n=this.context.getValue("viewType"),o=this.context.getValue("stageStatus"),c=this.mediaJoined&&(n!==vs.Livestream||o==="ON_STAGE");this.isRebuildingReconnectSnapshot=i&&c,this.isRebuildingReconnectSnapshot||(this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear()),i||(this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID"),this.participants.joined.forEach(({id:l})=>{var u;r.has(l)||(u=this.pip)==null||u.removeSource(l)}),this.participants.joined.clear(),e.forEach(l=>{var h;const u=this.createParticipantObjFromSocketPeer(l);if(this.isRebuildingReconnectSnapshot){const f=(h=this.participants.videoSubscribed.get(l.peerId))!=null?h:this.participants.audioSubscribed.get(l.peerId);f&&(u.manualProducerConfig={...f.manualProducerConfig})}this.logger.debug(`Processing socket join for ${this.self.id===u.id?"local peer":"remote peer"} ${u.id} listed in socket peers.`),this.onParticipantSocketJoined(u),this.logger.debug(`Processed socket join for ${this.self.id===u.id?"local peer":"remote peer"} ${u.id} listed in socket peers.`)})}handlePeerMediaJoinedBroadcast({participant:s,producerHandoverFromPeerId:t}){var i;if(!s)return;const e=s.peerId===this.self.id,r=(i=s.producerStates)!=null?i:[];this.logger.info(`${e?"Local peer":"Remote peer"} ${s.peerId} has joined media room with producerStates: ${JSON.stringify(r)}`),t&&t!==s.peerId&&r.length>0&&(this.logger.info(`Producer handover detected from ${t} to ${s.peerId} for producer ids ${r.map(({producerId:n})=>n).join(",")}`),this.context.getValue("peerSessionStore").emit(P.PRODUCER_HANDOVER,{oldPeerId:t,newPeerId:s.peerId,producerIds:r.map(({producerId:n})=>n)})),this.logger.debug(`Processing media join for newly joined ${e?"local peer":"remote peer"} ${s.peerId}.`),this.onParticipantMediaJoined(s.peerId,r),this.logger.debug(`Processed media join for newly joined ${e?"local peer":"remote peer"} ${s.peerId}.`)}clearParticipantMediaState(s,t,e){const r=s;e?t==="audio"?(r.screenShareTracks.audio=void 0,r.setScreenShareEnabled(r.screenShareEnabled&&r.screenShareTracks.video!==void 0)):(r.setScreenShareEnabled(!1),r.screenShareTracks={audio:void 0,video:void 0}):t==="audio"?(r.setAudioEnabled(!1),r.audioTrack=void 0):(r.setVideoEnabled(!1),this.updatePipSource(r.id,!1),r.videoTrack=void 0)}setupEvents(){this.roomSocketHandler.on($.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),this.context.getValue("peerSessionStore").on(P.SOCKET_PEERS,this.handleSocketPeers.bind(this)),this.roomSocketHandler.on(this.events.peerJoinedBroadcast,this.handlePeerMediaJoinedBroadcast.bind(this)),this.roomSocketHandler.on(this.events.selfJoinComplete,async({participants:s,selectedPeers:t,roomState:e})=>{this.logger.info(`Local peer has joined media room. Processing media joins for existing ${s==null?void 0:s.length} peers.`),s.forEach(({peerId:n,producerStates:o})=>{this.logger.debug(`Processing media join for ${this.self.peerId===n?"local peer":"existing remote peer"} ${n}.`),this.onParticipantMediaJoined(n,o),this.logger.debug(`Processed media join for ${this.self.peerId===n?"local peer":"existing remote peer"} ${n}.`)}),this.isRebuildingReconnectSnapshot&&this.rewireConsumersOnLocalUserReconnect();const{audioPeers:r,compulsoryPeers:i}=t!=null?t:{};this.applyPinnedSnapshot(e.pinnedPeerIds),this.computeActivateParticipants(r!=null?r:[],i),this.participants.viewMode==="PAGINATED"&&(this.participants.currentPage<1||this.participants.currentPage>this.participants.pageCount)&&await this.participants.setViewMode("ACTIVE_GRID"),this.isRebuildingReconnectSnapshot=!1,this.logger.info("Participants reconciliation on local peer's media join is complete. Reconciling consumers."),this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}),this.context.getValue("peerSessionStore").on(P.MAX_SPATIAL_LAYER_CHANGE,({peerId:s,maxSpatialLayer:t})=>{const e=this.videoPeerConsumerMap.get(s);e&&(this.maxSpatialLayerUpdates.set(e,t),this.updateConsumerSpatialLayers())}),this.context.getValue("peerSessionStore").on(P.PRODUCER_HANDOVER,s=>this.handleProducerHandover(s)),this.context.getValue("peerSessionStore").on(P.NEW_PRODUCER,({peerId:s,producer:t})=>{if(!t){this.logger.error(`Received new remote producer for peer ${s}. producer is invalid/empty.`);return}const e=this.participants.joined.get(s);if(!e){this.logger.warn(`Received new ${t.screenShare?"screenshare":"participant"} ${t.kind} remote producer ${t.producerId} for a non-existent peer ${s}`);return}const r=e.producers.find(({producerId:n})=>n===t.producerId);let i="REPLACED";r?(Object.assign(r,t),i="REPLACED"):(e.producers.push(t),i="INSERTED"),this.logger.info(`Scheduling syncConsumer post upserting (${i}) new producer ${t.producerId} to peer ${s} for ${t.screenShare?"screenshare":"participant"} ${t.kind}`),this.scheduleSyncConsumers({source:"NEW_REMOTE_PRODUCER"})}),this.context.getValue("peerSessionStore").on(P.PRODUCER_CLOSED,({peerId:s,producerId:t})=>{const e=this.participants.joined.get(s);if(!e){this.logger.warn(`Received producer closed event for producer ${t} of a peer ${s} that might have already left the meeting.`);return}const r=e.producers.find(i=>i.producerId===t);r?(this.logger.info(`${r.screenShare?"Screenshare":"Participant"} ${r.kind} producer ${t} of peer ${s} has closed. Updating media state and scheduling syncConsumers for reconciliation.`),this.clearParticipantMediaState(e,r.kind,r.screenShare),r.kind==="video"&&!r.screenShare&&this.videoPeerConsumerMap.get(s)===t&&this.videoPeerConsumerMap.delete(s),e.producers=e.producers.filter(i=>i.producerId!==t),this.scheduleSyncConsumers({source:"PRODUCER_CLOSED"})):this.logger.warn(`Received producer closed event for producer ${t} of a peer ${s}. Peer doesn't have the producer associated with it. Ignoring the event.`)}),this.context.getValue("peerSessionStore").on(P.PRODUCER_TOGGLE,({peerId:s,producerId:t,paused:e,kind:r})=>{const i=this.participants.joined.get(s);if(i){const n=i.producers.find(o=>o.producerId===t);if(!n){this.logger.warn(`Processing participant ${r} producer ${e?"paused":"resumed"} broadcast for remote producer ${t} of peer ${s} however producer is not associated with the peer. Ignoring the event.`);return}if(this.logger.info(`Processing participant ${r} producer ${e?"paused":"resumed"} broadcast for remote producer ${t} of peer ${s}. Reconciling media states and consumers.`),n.pause=e,r==="audio"&&i.setAudioEnabled(!e),r==="video"){const o=this.roomNodeClient.getConsumers().get(t);e?(i.setVideoEnabled(!1),this.updatePipSource(i.id,!1)):o&&!o.closed&&(i.videoTrack=o.track,i.setVideoEnabled(!0),this.updatePipSource(i.id,!0)),this.context.getValue("callstats").consumerSharedMediaState(t,{video:!e}),this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}}else this.logger.warn(`Processing participant ${r} producer ${e?"paused":"resumed"} broadcast for remote producer ${t} of a missing peer ${s}. Ignoring the event.`)}),this.roomSocketHandler.on(this.events.globalPeerPinBroadcast,s=>{let t;if(s&&(t=s.participantId),!this.mediaJoined)return;const e=t;this.onParticipantPinned(e);const r=this.participants.joined.get(e);r&&(this.logger.info(`globalPeerPinBroadcast: Scheduling audio/video consumer sync for pinned participant ${e} - ProducerCount: ${r.producers.length}, ConsumersSyncing: ${a(this,Bs)}, ProducerIds: [${r.producers.map(i=>i.producerId).join(", ")}]`),this.scheduleSyncConsumers({source:"GLOBAL_PEER_PIN"}))}),this.roomSocketHandler.on(this.events.selectedPeer,({audioPeers:s,compulsoryPeers:t})=>{this.mediaJoined&&this.onSelectedPeers(t.concat(s))}),this.roomSocketHandler.on(this.events.selectedPeerDiff,({entries:s})=>{if(!this.mediaJoined)return;const t=s.map(e=>({peerId:e.peerId,priority:e.priority}));this.updateActiveParticipantsWithPriorities(t,!0)})}waitingRoomRequestHandler(s){var r,i;this.logger.info(`Received waitlisted peers: ${((i=(r=s==null?void 0:s.requests)==null?void 0:r.map(n=>n.peerId))==null?void 0:i.join(", "))||"none"}`);const t=s.requests.filter(n=>!this.participants.waitlisted.get(n.peerId)),e=this.participants.waitlisted.toArray().filter(n=>!s.requests.find(o=>o.peerId===n.id));t.forEach(n=>this.participants.waitlisted.add(new hr(this.context,{id:n.peerId,displayName:n.displayName,audioMuted:!0,videoEnabled:!1,audioTrack:void 0,videoTrack:void 0,stageStatus:"OFF_STAGE",userId:n.userId,flags:{},isHost:!1,customParticipantId:n.customParticipantId,picture:n.picture,metadata:{preset_name:n.presetName}},this.self,this.roomSocketHandler))),e.forEach(n=>this.participants.waitlisted.delete(n.id))}get maxPreferredStreams(){return this.participants.maxActiveParticipantsCount}selectPagePeers(s){const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(d=>this.participants.joined.has(d)),r=Array.from(this.participants.pinned.keys()).filter(d=>!e.includes(d)),i=Array.from(this.participants.joined.toArray().filter(d=>d.stageStatus==="ON_STAGE").map(d=>d.id)),n=Math.max((s-1)*(this.maxPreferredStreams-e.length-r.length)),o=s*(this.maxPreferredStreams-e.length-r.length);return e.concat(r,i.slice(n,o))}selectActivePeers(s){const t=new Map,e=Array.from(this.participants.joined.toArray().filter(u=>u.stageStatus==="ON_STAGE").map(u=>(t.set(u.id,!0),u.id))),r=this.selectedPeers.peers,i=this.participants.pinned.toArray().reduce((u,h)=>(h.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(h.id):u.push(h.id),u),[]),n=this.self.stageStatus==="ON_STAGE"?1:0,o=s-n,c=new Set(r.concat(i).filter(u=>u!==this.self.id&&t.has(u)));let d=Array.from(c);const l=o-c.size;if(l>=0){const u=e.filter(h=>!c.has(h)&&h!==this.self.id).slice(0,l);d=Array.from(c).concat(u)}else d=d.slice(0,o);return d}updateMediaSubscribedMaps(s,t){const{page:e}=t!=null?t:{};s&&a(this,hs).mode!==s&&(a(this,hs).mode=s),e&&a(this,hs).page!==e&&(a(this,hs).page=e);const{mode:r,page:i}=a(this,hs);switch(r){case"PAGINATED":{if(!i)return;const n=this.selectPagePeers(i),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMap(this.participants.videoSubscribed,n),this.updateParticipantsMap(this.participants.audioSubscribed,o),this.logger.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:n});break}case"ACTIVE_GRID":{const n=this.selectActivePeers(this.participants.maxActiveParticipantsCount),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMapMinReplacement(this.participants.videoSubscribed,n),this.updateParticipantsMap(this.participants.audioSubscribed,o);break}case"MANUAL":{this.reconcileManualSubscriptionMaps();break}default:throw new Error(`View mode ${s} not supported`)}}async scheduleSyncConsumers({source:s}){var e,r,i;const t=((e=a(this,hs))==null?void 0:e.mode)==="PAGINATED"&&!a(this,Bs)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${s}, ViewMode: ${(r=a(this,hs))==null?void 0:r.mode}, ConsumersSyncing: ${a(this,Bs)}, Delay: ${t}, Page: ${(i=a(this,hs))==null?void 0:i.page}`),setTimeout(()=>this.syncConsumers(),t)}async syncConsumers(){var R,D,N,F,U,B,Z,ie;const s=this.context.getValue("connectionHandler");if((R=s==null?void 0:s.socketState)!=null&&R.state&&s.socketState.state!=="connected"){I(this,hn,Ed).call(this,"socket not connected"),this.logger.info("syncConsumers: Socket not connected, deferring sync.");return}if(((N=(D=s==null?void 0:s.mediaState)==null?void 0:D.recv)==null?void 0:N.state)!=="connected"){I(this,hn,Ed).call(this,"Recv transport not connected"),this.logger.info("syncConsumers: Connection not ready, exiting.");return}if(I(this,tu,iT).call(this),a(this,Bs)){g(this,pi,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),g(this,Bs,!0),g(this,pi,!1);let t=[];this.participants.videoSubscribed.forEach(H=>{var St,A;const re=this.participants.joined.get(H.id),we=(A=(St=H.producers)==null?void 0:St.filter(v=>v.kind==="video"))!=null?A:[];re&&(we!=null&&we.length)&&we.forEach(v=>{var ce,fe,V,_;const w=((fe=(ce=re.manualProducerConfig)==null?void 0:ce.video)!=null?fe:!0)&&v.kind==="video"&&!v.screenShare,x=((_=(V=re.manualProducerConfig)==null?void 0:V.screenshareVideo)!=null?_:!0)&&v.kind==="video"&&v.screenShare;(w||x)&&(v.pause||t.push(v))})}),this.participants.audioSubscribed.forEach(H=>{var St,A;const re=this.participants.joined.get(H.id),we=(A=(St=H.producers)==null?void 0:St.filter(v=>v.kind==="audio"))!=null?A:[];re&&(we!=null&&we.length)&&we.forEach(v=>{var ce,fe,V,_;const w=((fe=(ce=re.manualProducerConfig)==null?void 0:ce.audio)!=null?fe:!0)&&v.kind==="audio"&&!v.screenShare,x=((_=(V=re.manualProducerConfig)==null?void 0:V.screenshareAudio)!=null?_:!0)&&v.kind==="audio"&&v.screenShare;(w||x)&&t.push(v)})}),t=Mk(t,H=>H.producerId);const e=new Map;t.forEach(H=>{e.set(H.producerId,H)});const r=(U=(F=this.roomNodeClient)==null?void 0:F.getConsumers())!=null?U:new Map,i=[];r.forEach(H=>{H.closed&&i.push(H.id)});const n=(Z=(B=this.roomNodeClient)==null?void 0:B.removeClosedConsumers(i))!=null?Z:[];n.forEach(H=>{a(this,Ze).delete(H),this.consumerPeerMap.has(H)&&this.processConsumerClosed(H)}),n.length>0&&this.logger.info(`syncConsumers: Removed closed consumers: consumerIds=[${n.join(",")}].`);let o=[];const c=new Set,d=[],l=[];e.forEach(H=>{const re=r.get(H.producerId);if(!re){o.push(H);return}c.add(re.id);const{needsRemap:we,wasMarkedForDeletion:St}=I(this,uc,zp).call(this,re,H);we&&l.push(re.id),St&&d.push(re.id)});const u=[];r.forEach(H=>{H.closed||c.has(H.id)||I(this,su,nT).call(this,H)&&u.push(H.id)});const h=Date.now(),f=[];let S=[];a(this,Ze).forEach((H,re)=>{const we=r.get(re);if(!we||we.closed){a(this,Ze).delete(re);return}if(c.has(re)){a(this,Ze).delete(re);return}h-H>=$1?S.push(re):f.push(re)}),e.size>0&&this.logger.debug(`syncConsumers: Desired producer IDs: [${Array.from(e.keys()).join(",")}].`),r.size>0&&this.logger.debug(`syncConsumers: Current consumer IDs: [${Array.from(r.keys()).join(",")}].`),o.length>0&&this.logger.info(`syncConsumers: Producer IDs requiring consumers: [${o.map(({producerId:H})=>H).join(",")}].`),c.size>0&&this.logger.debug(`syncConsumers: Consumer IDs to keep: [${Array.from(c).join(",")}].`),l.length>0&&this.logger.info(`syncConsumers: Consumer IDs with consumer rewiring: [${l.join(",")}].`),d.length>0&&this.logger.info(`syncConsumers: Consumer IDs revived before deletion: [${d.join(",")}].`),u.length>0&&this.logger.info(`syncConsumers: Newly marked consumer IDs: [${u.join(",")}].`),f.length>0&&this.logger.info(`syncConsumers: Consumer IDs in deletion grace period: [${f.join(",")}].`),S.length>0&&this.logger.info(`syncConsumers: Consumer IDs ready for deletion: [${S.join(",")}].`);const E=35,k=35;o.length>E&&(this.logger.warn(`syncConsumers: Too many remote producers to create consumers: ${o.length}. Only adding ${E} in this run.`),o=o.slice(0,E),this.scheduleSyncConsumers({source:"SOFT_CAPPED_CREATE_CONSUMERS"})),S.length>k&&(this.logger.warn(`syncConsumers: Too many remote consumers ready to close: ${S.length}. Only removing ${k} in this run.`),S=S.slice(0,k),this.scheduleSyncConsumers({source:"SOFT_CAPPED_REMOVE_CONSUMERS"}));try{o.length>0||S.length>0?(this.logger.info(`syncConsumers: Calling updateConsumers: createProducerIds=[${o.map(({producerId:H})=>H).join(",")}], deleteConsumerIds=[${S.join(",")}].`),await this.updateConsumers(o,S),this.logger.info("syncConsumers: updateConsumers completed successfully.")):this.logger.info("syncConsumers: No changes needed, skipping updateConsumers.")}catch(H){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:H})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),g(this,Bs,!1),(ie=s==null?void 0:s.socketState)!=null&&ie.state&&s.socketState.state!=="connected"&&g(this,pi,!0)}a(this,pi)&&(this.logger.info("syncConsumers: Resync required, calling syncConsumers again."),this.syncConsumers())}computeActivateParticipants(s,t){const e=s.map((i,n)=>({peerId:i,priority:n+1})),r=t==null?void 0:t.map((i,n)=>({peerId:i,priority:-(n+1)}));e.push(...r!=null?r:[]),e.length>0&&this.updateActiveParticipantsWithPriorities(e)}createParticipantObjFromSocketPeer(s){const t=_o.formatSocketPeerMessage(s);return new hr(this.context,{...t,isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0},this.self,this.roomSocketHandler)}updatePipSource(s,t){var e,r;t?(e=this.pip)==null||e.enableSource(s):(r=this.pip)==null||r.disableSource(s)}onParticipantMediaJoined(s,t){if(!this.mediaJoined||s===this.self.id)return;const e=this.participants.joined.get(s);if(!e){this.logger.warn(`Received media.peerJoinedBroadcast for non-existent peer ${s}`);return}this.logger.info(`processing media state of remote producers of peer ${s} with producerStates: ${JSON.stringify(t)}`),t.forEach(r=>{r.kind===Ns.AUDIO&&!r.screenShare?e.setAudioEnabled(!r.pause):r.kind===Ns.VIDEO&&!r.screenShare&&(e.setVideoEnabled(!r.pause),this.updatePipSource(e.id,!r.pause));const i={...r,producingTransportId:r.producingTransportId,kind:r.kind===Ns.AUDIO?"audio":"video",producingPeerId:s,mimeType:r.mimeType},n=e.producers.find(({producerId:o})=>o===i.producerId);n?Object.assign(n,i):e.producers.push(i)}),this.logger.info(`Reconciling consumers due to media join of peer ${s}. Media join is complete.`),this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}updateParticipantsMapMinReplacement(s,t){const e=Array.from(s.keys()),r=new Map(s),i=new Set(t),n=[];e.forEach((o,c)=>{(!i.has(o)||!this.participants.joined.get(o))&&n.push(c)}),t.forEach(o=>{if(s.get(o))return;if(e.length<t.length){e.push(o);return}const c=n.shift();e[c]=o}),n.forEach(o=>{e.splice(o,1)}),Array.from(s.keys()).forEach(o=>{s.delete(o,!i.has(o))}),e.forEach(o=>{const c=this.participants.joined.get(o);if(!c)return;const d=r.get(o),l=!d||d!==c;s.add(c,l)}),s.emit("participantsUpdate")}reconcileManualSubscriptionMaps(){const s=Array.from(this.participants.videoSubscribed.keys()),t=Array.from(this.participants.audioSubscribed.keys());this.updateParticipantsMap(this.participants.videoSubscribed,s.filter(e=>this.participants.joined.has(e))),this.updateParticipantsMap(this.participants.audioSubscribed,t.filter(e=>this.participants.joined.has(e)))}updateParticipantsMap(s,t){Array.from(s.keys()).forEach(r=>{t.includes(r)||s.delete(r,!0)}),t.forEach(r=>{const i=s.get(r),n=this.participants.joined.get(r);n&&i!==n&&(i&&s.delete(r,!1),s.add(n,!0))}),s.emit("participantsUpdate")}updatePinnedParticipants(){this.participants.pinned.forEach(s=>{s.setIsPinned(!1),this.participants.pinned.delete(s.id)})}applyPinnedSnapshot(s){const t=s[0];if(this.participants.pinned.forEach(i=>{i.id!==t&&(i.setIsPinned(!1),this.participants.pinned.delete(i.id))}),t===this.self.id){this.self.setIsPinned(!0),this.participants.pinned.emit("participantsUpdate");return}if(this.self.isPinned&&this.self.setIsPinned(!1),!t){this.participants.pinned.emit("participantsUpdate");return}const e=this.participants.joined.get(t),r=this.participants.pinned.get(t);if(!e){r&&this.participants.pinned.delete(t),this.participants.pinned.emit("participantsUpdate");return}r!==e&&(r&&(r.setIsPinned(!1),this.participants.pinned.delete(t,!1)),e.setIsPinned(!0),this.participants.pinned.add(e,!0)),this.participants.pinned.emit("participantsUpdate")}rewireConsumersOnLocalUserReconnect(){this.participants.joined.forEach(s=>{s.producers.forEach(t=>{const e=this.roomNodeClient.getConsumers().get(t.producerId);!e||e.closed||(I(this,uc,zp).call(this,e,t),t.pause&&!t.screenShare&&(t.kind==="audio"?s.setAudioEnabled(!1):(s.setVideoEnabled(!1),this.updatePipSource(s.id,!1))))})})}static replaceParticipantInMap(s,t,e,r){const i=s,n=i.get(t);if(!n)return;const o=new Set,c=Array.from(i.values()).reduce((d,l)=>{const u=l.id===t?e:l;return o.has(u.id)||(o.add(u.id),d.push(u)),d},[]);if(Array.from(i.keys()).forEach(d=>{i.delete(d,!1)}),c.forEach(d=>i.add(d,!1)),r){const d=i.emit.bind(i);d("participantLeft",n),d("participantJoined",e)}i.emit("participantsUpdate")}handleProducerHandover(s){const{oldPeerId:t,newPeerId:e,producerIds:r}=s;if(typeof t!="string"||typeof e!="string"||t===e||!Array.isArray(r)||r.length===0||r.some(u=>typeof u!="string")||e===this.self.id)return;const i=this.participants.joined.get(t),n=this.participants.joined.get(e);if(!i||!n||!i.userId||i.userId!==n.userId){this.logger.warn(`ParticipantController::producerHandover::participant validation failed from ${t} to ${e}`);return}this.selectedPeers.reassignPeer(t,e,this.context);const o=this.context.getValue("audioPlayback");o==null||o.reassignParticipantTrack(t,e),o==null||o.reassignParticipantTrack(`screenshare-${t}`,`screenshare-${e}`);const c=new Set(r),d=i.producers.filter(({producerId:u})=>c.has(u));if(d.length===0)return;d.some(u=>u.kind==="audio"&&!u.screenShare)&&(i.setAudioEnabled(!1),i.audioTrack=void 0),d.some(u=>u.screenShare)&&(i.setScreenShareEnabled(!1),i.screenShareTracks={audio:void 0,video:void 0}),n.manualProducerConfig={...i.manualProducerConfig},i.producers=i.producers.filter(({producerId:u})=>!c.has(u)),d.forEach(u=>{if(n.producers.some(({producerId:f})=>f===u.producerId))return;const h={...u};delete h.consumer,this.context.getValue("peerSessionStore").emit(P.NEW_PRODUCER,{peerId:e,producer:{...h,producingPeerId:e}})}),this.roomNodeClient.handoverPeerProducers(e,r).forEach(u=>{u.kind==="video"&&u.appData.screenShare!==!0&&this.videoPeerConsumerMap.get(t)===u.id&&(this.videoPeerConsumerMap.delete(t),this.updatePipSource(t,!1)),this.context.getValue("peerSessionStore").emit(P.NEW_CONSUMER_CREATED,{id:u.id,appData:u.appData,peerId:e})}),_o.replaceParticipantInMap(this.participants.videoSubscribed,t,n,!0),_o.replaceParticipantInMap(this.participants.audioSubscribed,t,n,!1),this.participants.pinned.has(t)&&(i.setIsPinned(!1),n.setIsPinned(!0),_o.replaceParticipantInMap(this.participants.pinned,t,n,!0)),this.logger.info(`Removing old peer ${t} locally after handover.`),this.onParticipantLeave(t).catch(u=>{this.logger.error("Failed to remove old peer locally after handover",{error:u})})}setupEventsGlobal(){this.roomSocketHandler.on($.joinRoom,({peer:s})=>{s.waitlisted||(this.logger.info(`Processing socket join for ${this.self.id===s.peerId?"local peer":"remote peer"} ${s.peerId}.`),this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(s)),this.logger.info(`Processed socket join for ${this.self.id===s.peerId?"local peer":"remote peer"} ${s.peerId}.`))}),this.roomSocketHandler.on($.leaveRoom,async s=>{const{peerId:t}=s.peer;this.logger.info(`peer ${t} left the meeting. Removing it from selected peers`),this.selectedPeers.delete(t,this.context),this.onParticipantLeave(t)}),this.context.getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,()=>{this.self.permissions.acceptWaitingRequests&&this.roomSocketHandler.getWaitingRoomRequests()}),this.self.permissions.on("permissionsUpdate",s=>{const{acceptWaitingRequests:t}=s;t!==void 0&&(t?this.roomSocketHandler.getWaitingRoomRequests():this.participants.waitlisted.clear())}),this.context.getValue("peerSessionStore").on(P.PEER_CLOSED,({id:s})=>{this.logger.info(`Remote peer ${s} has left media room. Scheduling delayed consumer cleanup.`),this.scheduleSyncConsumers({source:"REMOTE_PEER_CLOSED"})}),this.context.getValue("peerSessionStore").on(P.MEDIA_ROOM_JOIN_FAILED,()=>{this.isRebuildingReconnectSnapshot&&(this.isRebuildingReconnectSnapshot=!1)}),this.context.getValue("peerSessionStore").on(P.SOCKET_SERVICE_DISCONNECTED,()=>{this.isRebuildingReconnectSnapshot=!1,g(this,pi,!0),I(this,hn,Ed).call(this,"socket disconnected"),this.logger.info("Socket disconnected — keeping participants visible for seamless reconnection")}),this.context.getValue("peerSessionStore").on(P.TRANSPORT_STATE_UPDATE,({transport:s,state:t})=>{if(s==="recv"){if(t!=="connected"){I(this,hn,Ed).call(this,`Recv transport not yet connected. state: ${t}`);return}this.logger.info("Receive transport connected; scheduling consumer reconciliation"),this.scheduleSyncConsumers({source:"RECV_TRANSPORT_CONNECTED"})}}),this.context.getValue("peerSessionStore").on(P.CONSUMER_PAUSED,({id:s})=>{this.processConsumerPaused(s)}),this.context.getValue("peerSessionStore").on(P.CONSUMER_RESUMED,({id:s})=>{this.processConsumerResumed(s)}),this.context.getValue("peerSessionStore").on(P.NEW_CONSUMER_CREATED,({id:s})=>{this.processNewConsumer(s)}),this.context.getValue("peerSessionStore").on(P.CONSUMER_CLOSED,({id:s})=>{const t=a(this,Ze).delete(s);this.logger.info(`Consumer closed: consumerId=${s}, wasMarkedForDeletion=${t}.`),this.processConsumerClosed(s)}),this.context.getValue("peerSessionStore").on(P.ROOM_MESSAGE,async({payload:s,type:t,timestamp:e})=>{this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(P.MESSAGE,async({payload:s,type:t,timestamp:e})=>{t!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(P.LOW_CONSUMER_SCORE,({peerId:s,score:t,kind:e})=>{const r=this.participants.joined.get(s);r&&(r.emit("poorConnection",{score:t,kind:e}),this.participants.emit("poorConnection",{participantId:s,score:t,kind:e}))}),this.context.getValue("peerSessionStore").on(P.CONSUMER_SCORE_UPDATE,({score:s,kind:t,appData:e,peerId:r,scoreStats:i})=>{var c;const n=t==="video"&&((c=e==null?void 0:e.screenShare)!=null?c:!1),o=this.participants.joined.get(r);o&&(o.emit("mediaScoreUpdate",{kind:t,isScreenshare:n,score:s,participantId:r,scoreStats:i}),this.participants.emit("mediaScoreUpdate",{kind:t,isScreenshare:n,score:s,participantId:r,scoreStats:i}))}),this.context.getValue("peerSessionStore").onAsync(P.KICK_PEER,async({peerId:s})=>{const t=this.participants.joined.get(s);this.roomNodeClient.kick(s),await this.roomSocketHandler.kick(s),t?t.emit("kicked"):this.participants.joined.emit("kicked",{id:s})}),this.context.getValue("peerSessionStore").on(P.UPDATE_ACTIVE,({viewMode:s,page:t}={})=>{this.isRebuildingReconnectSnapshot||(this.logger.info(`UPDATE_ACTIVE event received - viewMode: ${a(this,hs).mode}, page: ${t}`),this.updateMediaSubscribedMaps(s,{page:t}),this.scheduleSyncConsumers({source:"UPDATE_ACTIVE"}))})}async onParticipantPinned(s){if(!s){this.self.isPinned&&this.self.setIsPinned(!1),this.participants.pinned.size!==0&&this.updatePinnedParticipants();return}if(s===this.self.id){this.participants.pinned.size!==0&&this.updatePinnedParticipants(),this.self.setIsPinned(!0);return}const t=this.participants.joined.get(s);this.self.isPinned&&this.self.setIsPinned(!1),this.updatePinnedParticipants(),t.setIsPinned(!0),this.participants.pinned.add(t)}async onParticipantSocketJoined(s){var t,e,r;this.self.id!==s.id&&!((t=s.flags)!=null&&t.recorder)&&!((e=s.flags)!=null&&e.hidden_participant)&&!((r=s.flags)!=null&&r.hiddenParticipant)&&(this.isRebuildingReconnectSnapshot||(this.participants.videoSubscribed.delete(s.id),this.participants.audioSubscribed.delete(s.id)),this.participants.joined.add(s),this.participants.waitlisted.delete(s.id),s.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&this.context.getValue("peerSessionStore").emit(P.UPDATE_STAGE_REQUESTS,{request:{displayName:s.name,userId:s.userId,peerId:s.id},add:!0})),this.context.getValue("peerSessionStore").emit(P.PEER_JOINED_INTERNAL,s)}async onParticipantLeave(s){var n;this.logger.info(`peer ${s} has left. Deleting peer from participant maps`);const t=this.participants.joined.get(s);this.participants.joined.delete(s,!0,!0),this.participants.pinned.delete(s,!0,!0),this.participants.waitlisted.delete(s,!0,!0),(n=this.pip)==null||n.removeSource(s),this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage}),t&&t.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&this.context.getValue("peerSessionStore").emit(P.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!1});const{currentPage:e}=this.participants,r=this.maxPreferredStreams*(e-1),i=this.participants.videoSubscribed.get(s);this.participants.viewMode==="MANUAL"?this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:e}):r===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=r?e===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(e-1):i&&this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:e})}processMedia(s){var h;const t=this.roomNodeClient.getConsumers(),{peerId:e,kind:r,appData:i,track:n,producerId:o,rtpReceiver:c,paused:d,localId:l}=(h=t.get(s))!=null?h:{};if(!e)return this.logger.warn("processMedia::Peer ID is undefined",{consumer:{id:s,kind:r,peerId:e,appData:{supportsRemoteControl:!!(i!=null&&i.supportsRemoteControl),screenShare:!!(i!=null&&i.screenShare)},remotelyPaused:d,producerId:o}}),{};const u=i;return r==="video"&&u.screenShare!==!0&&this.videoPeerConsumerMap.set(e,s),this.logger.info("ParticipantController::processMedia",{consumer:{id:s,peerId:e,kind:r,appData:u,remotelyPaused:d,producerId:o}}),this.consumerPeerMap.set(s,{type:r,peerId:e,appData:u,remotelyPaused:d,producerId:o,trackId:n==null?void 0:n.id}),{peerId:e,kind:r,appData:u,remotelyPaused:d,track:n,producerId:o,rtpReceiver:c,localId:l}}processConsumerClosed(s){var l;const{peerId:t,type:e,appData:r,remotelyPaused:i,producerId:n,trackId:o}=this.consumerPeerMap.get(s)||{},c=this.participants.joined.get(t);if(this.logger.info("ParticipantController::processConsumerClosed",{consumer:{id:s,peerId:t,appData:r,kind:e,remotelyPaused:i,producerId:n}}),this.consumerPeerMap.delete(s),e==="video"&&(r==null?void 0:r.screenShare)!==!0&&this.videoPeerConsumerMap.get(t)===s&&this.videoPeerConsumerMap.delete(t),r!=null&&r.e2ee&&o&&this.context.getValue("peerSessionStore").emit(P.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:o}),!c)return;r!=null&&r.screenShare?this.context.getValue("callstats").consumerSharedMediaState(s,{screen:!1}):e==="audio"?this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!1}):e==="video"&&this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1});const d=c.producers.find(u=>u.producerId===n);if(((l=d==null?void 0:d.consumer)==null?void 0:l.id)!==s){this.logger.info(`Ignoring stale consumer media cleanup: consumerId=${s}, producerId=${n}, peerId=${t}.`);return}d.consumer={id:s,peerId:t,kind:void 0,appData:r,paused:i,producerId:n,rtpReceiver:void 0,localId:void 0},!(e!=="audio"&&e!=="video")&&this.clearParticipantMediaState(c,e,(r==null?void 0:r.screenShare)===!0)}processConsumerResumed(s){var f;const t=this.processMedia(s),{peerId:e,kind:r,appData:i,track:n,remotelyPaused:o,producerId:c,rtpReceiver:d,localId:l}=t;if(!e)return;this.logger.info("ParticipantController::processConsumerResumed",{consumer:{id:s,peerId:e,kind:r,appData:i,remotelyPaused:o,producerId:c}});const u=this.participants.joined.get(e);if(!u)return;const h=u.producers.find(S=>S.producerId===c);if(h&&(h.consumer={id:s,peerId:e,kind:r,appData:i,paused:o,producerId:c,rtpReceiver:d,localId:l}),i.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:d,track:n}),i.screenShare){r==="video"?u.screenShareTracks.video=n:r==="audio"&&(u.screenShareTracks.audio=n),u.setScreenShareEnabled(!0),(f=this.context)==null||f.getValue("callstats").consumerSharedMediaState(s,{screen:!0});return}r==="video"?(u.videoTrack=n,u.setVideoEnabled(!0),this.updatePipSource(u.id,!0),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!0})):r==="audio"&&(u.audioTrack=n,u.setAudioEnabled(u.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:u.audioEnabled}))}processConsumerPaused(s){this.logger.info(`ParticipantController::processConsumerPaused called for consumerId: ${s}`);const{peerId:t,kind:e,track:r,appData:i,remotelyPaused:n,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processConsumerPaused",{consumer:{id:s,peerId:t,kind:e,appData:i,remotelyPaused:n,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(h=>h.producerId===o);u&&(u.consumer={id:s,peerId:t,kind:e,appData:i,paused:n,producerId:o,rtpReceiver:c,localId:d}),r&&i.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:r.id}),e==="video"?(l.videoTrack=r,l.setVideoEnabled(!1),this.updatePipSource(l.id,!1),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1})):e==="audio"&&(l.audioTrack=r,l.setAudioEnabled(l.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:l.audioEnabled}))}processNewConsumer(s){const{peerId:t,kind:e,remotelyPaused:r,track:i,appData:n,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processNewConsumer",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:n,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(h=>h.producerId===o);if(u&&(u.consumer={id:s,peerId:t,kind:e,appData:n,paused:r,producerId:o,rtpReceiver:c,localId:d}),n.screenShare){e==="video"?l.screenShareTracks.video=i:e==="audio"&&(l.screenShareTracks.audio=i),(!r||this.self.permissions.isRecorder)&&l.setScreenShareEnabled(!0),n.supportsRemoteControl&&(l.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:o,peerId:t,screenShare:!0,consumerId:s,consumerPeerId:this.self.id}),this.logger.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:n,producerId:o}});return}e==="video"?(l.videoTrack=i,r||(l.setVideoEnabled(!0),this.updatePipSource(l.id,!0)),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!r})):e==="audio"&&(l.audioTrack=i,r||l.setAudioEnabled(!0),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!r})),!r&&n.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:c,track:i}),this.context.getValue("peerSessionStore").emit(P.ENABLE_E2EE_CRYPTOR_ON_NEW_CONSUMER,{appData:n,peerId:l.id})}static formatSocketPeerMessage(s){var e,r,i,n,o,c;if(!s)return;const t=rp(s.stageType);return{id:s.peerId,userId:s.userId,name:s.displayName,displayName:s.displayName,stageType:t,customParticipantId:s.customParticipantId,presetId:s.presetId,picture:s.displayPictureUrl,waitlisted:s.waitlisted,stageStatus:t,metadata:{preset_name:(e=s.flags)==null?void 0:e.presetName},recorderType:(r=s.flags)==null?void 0:r.recorderType,flags:{hiddenParticipant:(i=s.flags)==null?void 0:i.hiddenParticipant,hidden_participant:(n=s.flags)==null?void 0:n.hiddenParticipant,recorder:((o=s.flags)==null?void 0:o.recorderType)!==void 0&&((c=s.flags)==null?void 0:c.recorderType)!=="NONE"}}}async onSelectedPeers(s,t){this.participants.viewMode==="ACTIVE_GRID"&&this.computeActivateParticipants(s,t)}updateActiveParticipantsWithPriorities(s,t=!1){if(this.participants.viewMode==="MANUAL")return;if(!this.mediaJoined){this.logger.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.mediaJoined});return}s.forEach(r=>{this.selectedPeers.add(r.peerId,r.priority,this.context)});const e=this.selectedPeers.activeSpeakerPeers.at(0);e!==void 0&&e!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=e,this.participants.emit("activeSpeaker",{peerId:e,volume:1})),t&&this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}},hs=new WeakMap,Bs=new WeakMap,pi=new WeakMap,Ze=new WeakMap,Pr=new WeakMap,un=new WeakMap,hn=new WeakSet,Ed=function(s){a(this,Pr)===void 0&&(g(this,Pr,Date.now()),this.logger.info(`Consumer deletion aging paused: reason="${s}", consumerIds=[${Array.from(a(this,Ze).keys()).join(",")}].`))},tu=new WeakSet,iT=function(){if(a(this,Pr)===void 0)return;const s=Date.now()-a(this,Pr);a(this,Ze).forEach((t,e)=>{a(this,Ze).set(e,t+s)}),g(this,Pr,void 0),this.logger.info(`Consumer deletion aging resumed: pausedDurationMs=${s}, consumerIds=[${Array.from(a(this,Ze).keys()).join(",")}].`)},su=new WeakSet,nT=function(s){return a(this,Ze).has(s.id)?!1:(a(this,Ze).set(s.id,Date.now()),!0)},uc=new WeakSet,zp=function(s,t){const e=s.peerId,r=!t.consumer||t.consumer.peerId!==t.producingPeerId||e!==t.producingPeerId;s.reassignPeer(t.producingPeerId);const i=a(this,Ze).delete(s.id);return r&&this.processNewConsumer(s.id),{needsRemap:r,wasMarkedForDeletion:i}},ru=new WeakSet,aT=function(){g(this,un,setInterval(()=>{a(this,Ze).size!==0&&(this.logger.info(`Consumer deletion sweep scheduling reconciliation: consumerIds=[${Array.from(a(this,Ze).keys()).join(",")}].`),this.scheduleSyncConsumers({source:"CONSUMER_DELETION_SWEEP"}))},x1))},iu=new WeakSet,oT=function(){a(this,un)!==void 0&&(clearInterval(a(this,un)),g(this,un,void 0))},nu=new WeakMap,jv);let pr=_o;Ui([y.trace("ParticipantController.setupEvents")],pr.prototype,"setupEvents",1),Ui([y.trace("ParticipantController.setupEvents")],pr.prototype,"setupEventsGlobal",1),Ui([y.trace("ParticipantController.processMedia")],pr.prototype,"processMedia",1),Ui([y.trace("ParticipantController.processConsumerClosed")],pr.prototype,"processConsumerClosed",1),Ui([y.trace("ParticipantController.processConsumerResumed")],pr.prototype,"processConsumerResumed",1),Ui([y.trace("ParticipantController.processConsumerPaused")],pr.prototype,"processConsumerPaused",1),Ui([y.trace("ParticipantController.processNewConsumer")],pr.prototype,"processNewConsumer",1);const De=Ls(Rh().permissions),ou=class extends Ft{constructor(e,r,i,n=!1){const o=e.getValue("logger");super(o);m(this,Pt);m(this,Y,void 0);m(this,_a,void 0);m(this,ka,void 0);m(this,au,e=>{var l,u,h;const{chat:r,connectedMeetings:i,plugins:n,polls:o,media:c,...d}=e;if(r&&(r.private&&Ur(a(this,Y).chat.private,r.private),r.public&&Ur(a(this,Y).chat.public,r.public),this.emit("chatUpdate")),i&&Ur(a(this,Y).connectedMeetings,i),c){const f=E=>{switch(E){case Br.NONE:return G.Allowed;case Br.ALLOWED:return G.Allowed;case Br.NOT_ALLOWED:return G.NotAllowed;case Br.CAN_REQUEST:return G.CanRequest;default:return}},S={audio:void 0,video:void 0,screenshare:void 0};(l=c.audio)!=null&&l.canProduce&&(S.audio={canProduce:f(c.audio.canProduce)}),(u=c.video)!=null&&u.canProduce&&(S.video={canProduce:f(c.video.canProduce)}),(h=c.screenshare)!=null&&h.canProduce&&(S.screenshare={canProduce:f(c.screenshare.canProduce)}),Ur(a(this,Y).media,S)}n&&(Ur(a(this,Y).plugins,n),this.emit("pluginsUpdate")),o&&(Ur(a(this,Y).polls,o),this.emit("pollsUpdate")),Object.keys(d).length!==0&&Ur(a(this,Y),d),this.emit("permissionsUpdate",e)});if(!r)throw this.logger.error("PermissionPreset::load_preset_permissions_failed"),new C("Could not load preset permissions.","0904");g(this,ka,e),g(this,_a,i),g(this,Y,r),n&&this.setupEvents()}setupEvents(){a(this,ka).getValue("peerSessionStore").on(P.UPDATE_PERMISSIONS,a(this,au))}static init(e,r,i){let n;return i?n=new ou(e,i,r,!0):n=new ou(e,De,r),n}get mediaRoomType(){return"CF"}get stageEnabled(){var e;return((e=a(this,Y))==null?void 0:e.stageEnabled)||a(this,_a)===vs.Webinar||a(this,_a)===vs.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=a(this,Y))==null?void 0:e.acceptStageRequests)||((r=a(this,Y))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,i;return((e=a(this,Y))==null?void 0:e.stageAccess)===G.NotAllowed?G.NotAllowed:((r=a(this,Y))==null?void 0:r.stageAccess)===G.CanRequest?G.CanRequest:((i=a(this,Y))==null?void 0:i.stageAccess)===G.Allowed||a(this,Y).media.audio.canProduce===G.Allowed||a(this,Y).media.video.canProduce===G.Allowed||a(this,Y).media.screenshare.canProduce===G.Allowed?G.Allowed:a(this,Y).media.audio.canProduce===G.CanRequest||a(this,Y).media.video.canProduce===G.CanRequest||a(this,Y).media.screenshare.canProduce===G.CanRequest?G.CanRequest:G.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.acceptWaitingRequests)!=null?r:De.acceptWaitingRequests}get requestProduceVideo(){var e,r,i;return((i=(r=(e=a(this,Y))==null?void 0:e.media)==null?void 0:r.video)==null?void 0:i.canProduce)===G.CanRequest}get requestProduceAudio(){var e,r,i;return((i=(r=(e=a(this,Y))==null?void 0:e.media)==null?void 0:r.audio)==null?void 0:i.canProduce)===G.CanRequest}get requestProduceScreenshare(){var e,r,i;return((i=(r=(e=a(this,Y))==null?void 0:e.media)==null?void 0:r.screenshare)==null?void 0:i.canProduce)===G.CanRequest}get canAllowParticipantAudio(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.disableParticipantAudio)!=null?r:De.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.canAcceptProductionRequests)!=null?r:De.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.disableParticipantVideo)!=null?r:De.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.kickParticipant)!=null?r:De.kickParticipant}get pinParticipant(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.pinParticipant)!=null?r:De.pinParticipant}get canRecord(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.canRecord)!=null?r:De.canRecord}get waitingRoomBehaviour(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.waitingRoomType)!=null?r:De.waitingRoomType}get plugins(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.plugins)!=null?r:De.plugins}get polls(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.polls)!=null?r:De.polls}get canProduceVideo(){var r;const e=(r=a(this,Y).media.video.canProduce)!=null?r:De.media.video.canProduce;return this.stageEnabled&&(a(this,Pt,es)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Pt,es)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,Pt,es)==="OFF_STAGE"||a(this,Pt,es)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get canProduceScreenshare(){var r;const e=(r=a(this,Y).media.screenshare.canProduce)!=null?r:De.media.screenshare.canProduce;return this.stageEnabled&&(a(this,Pt,es)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Pt,es)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,Pt,es)==="OFF_STAGE"||a(this,Pt,es)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get canProduceAudio(){var r;const e=(r=a(this,Y).media.audio.canProduce)!=null?r:De.media.audio.canProduce;return this.stageEnabled&&(a(this,Pt,es)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Pt,es)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,Pt,es)==="OFF_STAGE"||a(this,Pt,es)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get chatPublic(){var e,r,i;return(i=(r=(e=a(this,Y))==null?void 0:e.chat)==null?void 0:r.public)!=null?i:De.chat.public}get chatPrivate(){var e,r,i;return(i=(r=(e=a(this,Y))==null?void 0:e.chat)==null?void 0:r.private)!=null?i:De.chat.private}get connectedMeetings(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.connectedMeetings)!=null?r:De==null?void 0:De.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.hiddenParticipant)!=null?r:De.hiddenParticipant}get showParticipantList(){var e;return(e=a(this,Y).showParticipantList)!=null?e:De.showParticipantList}get canChangeParticipantPermissions(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.canChangeParticipantPermissions)!=null?r:De.canChangeParticipantPermissions}get canEditDisplayName(){var e;return(e=a(this,Y).canEditDisplayName)!=null?e:!1}get isRecorder(){return a(this,Y).isRecorder}get canSpotlight(){return a(this,Y).canSpotlight}get canLivestream(){return a(this,Y).canLivestream}get transcriptionEnabled(){return a(this,Y).transcriptionEnabled}};let gp=ou;Y=new WeakMap,_a=new WeakMap,ka=new WeakMap,au=new WeakMap,Pt=new WeakSet,es=function(){return a(this,ka).getValue("stageStatus")};class KS extends Ft{constructor(e,r){super(r);p(this,"localMediaHandler");m(this,zt,void 0);g(this,zt,e)}async updatePermission(){var d,l;const e=(u,h)=>{this.mediaPermissions[u]=h;const f={message:this.mediaPermissions[u],kind:u};h==="DENIED"?a(this,zt).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_ERROR,f):a(this,zt).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,f)};if(Pe.getName()==="firefox")return;const r="microphone",i="camera",n=await((d=navigator==null?void 0:navigator.permissions)==null?void 0:d.query({name:r})),o=await((l=navigator==null?void 0:navigator.permissions)==null?void 0:l.query({name:i})),c=(u,h)=>{switch(h){case"granted":e(u,"ACCEPTED");break;case"denied":e(u,"DENIED");break;case"prompt":e(u,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};n&&(n.onchange=()=>c("audio",n.state)),o&&(o.onchange=()=>c("video",o.state))}async populateMediaPermissionsInCallstats({message:e,kind:r}){var i,n,o,c;switch(r){case"audio":{(i=a(this,zt))==null||i.getValue("callstats").mediaPermission("AUDIO",e),(n=a(this,zt))==null||n.getValue("callstats").mediaPermission("SPEAKER",e);break}case"video":{(o=a(this,zt))==null||o.getValue("callstats").mediaPermission("VIDEO",e);break}case"screenshare":{(c=a(this,zt))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",e);break}}}get peerId(){var e;return(e=a(this,zt))==null?void 0:e.getValue("peerId")}async init(e={},r=!1,i=null){var n,o,c,d,l,u,h;if(Pe.init(),i&&g(this,zt,i),!this.localMediaHandler)try{let f=!0;if((n=i==null?void 0:i.getValue("defaults"))!=null&&n.mediaHandler)f=!1,this.localMediaHandler=i.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:S}=navigator;this.localMediaHandler=await S.init(e)}else this.localMediaHandler=new Dt(i,e.constraints,(o=i==null?void 0:i.getValue("defaults"))==null?void 0:o.isNonPreferredDevice,(c=i==null?void 0:i.getValue("defaults"))==null?void 0:c.autoSwitchAudioDevice);if(i==null||i.getValue("peerSessionStore").on(P.MEDIA_PERMISSION_UPDATE,async S=>{if(this.populateMediaPermissionsInCallstats({message:S.message,kind:S.kind}),S.message==="NOT_REQUESTED")switch(S==null?void 0:S.kind){case"audio":this.rawAudioTrack&&(this.logger.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(this.logger.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",S)}),i==null||i.getValue("peerSessionStore").on(P.MEDIA_PERMISSION_ERROR,async S=>{const{kind:E,message:k,constraints:R}=S;this.populateMediaPermissionsInCallstats({message:k,kind:E}),E==="audio"?(this.logger.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):E==="video"&&(this.logger.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),this.logger.error("SelfController::mediaPermissionError",{error:{message:k},constraints:R,mediaPermissionsErrors:{kind:E,message:k}}),this.emit("mediaPermissionError",S),this.emit("mediaPermissionUpdate",{message:k,kind:E})}),f){this.logger.info(`Setting up SelfMedia streams using media handler. audio:${(d=e==null?void 0:e.audio)!=null?d:!0} video:${(l=e==null?void 0:e.video)!=null?l:!0}`);const S=this.localMediaHandler.setupStreams({video:(u=e==null?void 0:e.video)!=null?u:!0,audio:(h=e==null?void 0:e.audio)!=null?h:!0});r||await S}}catch(f){this.logger.error("Self::init::Failed To Setup Streams",{error:{name:f.name,message:f.message}})}}set context(e){g(this,zt,e),this.localMediaHandler.context=e}get audioTrack(){return this.localMediaHandler.audioTrack}get rawAudioTrack(){return this.localMediaHandler.rawAudioTrack}get mediaPermissions(){return this.localMediaHandler.permissions}async addAudioMiddleware(e){return this.localMediaHandler.addAudioMiddleware(e)}async removeAudioMiddleware(e){return this.localMediaHandler.removeAudioMiddleware(e)}async removeAllAudioMiddlewares(){return this.localMediaHandler.removeAllAudioMiddlewares()}get videoTrack(){return this.localMediaHandler.videoTrack}get rawVideoTrack(){return this.localMediaHandler.rawVideoTrack}async addVideoMiddleware(e){return this.localMediaHandler.addVideoMiddleware(e)}async setVideoMiddlewareGlobalConfig(e={disablePerFrameCanvasRendering:!1}){return this.localMediaHandler.setVideoMiddlewareGlobalConfig(e)}async removeVideoMiddleware(e){return this.localMediaHandler.removeVideoMiddleware(e)}async removeAllVideoMiddlewares(){return this.localMediaHandler.removeAllVideoMiddlewares()}get screenShareTracks(){return this.localMediaHandler.screenShareTracks}get audioEnabled(){return this.localMediaHandler.audioEnabled}get videoEnabled(){return this.localMediaHandler.videoEnabled}get screenShareEnabled(){return this.localMediaHandler.screenShareEnabled}async enableAudio(){await this.localMediaHandler.enableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableVideo(){await this.localMediaHandler.enableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}async disableAudio(){this.localMediaHandler.disableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableScreenShare(){await this.localMediaHandler.enableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableScreenShare(){await this.localMediaHandler.disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableVideo(){await this.localMediaHandler.disableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}getCurrentDevices(){return this.localMediaHandler.getCurrentDevices()}async getAudioDevices(){return await this.localMediaHandler.getAudioDevices()}async getVideoDevices(){return await this.localMediaHandler.getVideoDevices()}async getSpeakerDevices(){return await this.localMediaHandler.getSpeakerDevices()}getDeviceById(e,r){let i;return r==="audio"?i="audioinput":r==="video"?i="videoinput":r==="speaker"&&(i="audiooutput"),this.localMediaHandler.getDeviceById(e,i)}async setDevice(e){switch(e.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(e,{saveDevicePreference:!0})}catch(r){}finally{this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":await this.localMediaHandler.setSpeakerDevice(e,{saveDevicePreference:!0});break;case"videoinput":try{await this.localMediaHandler.setVideoDevice(e,{saveDevicePreference:!0})}catch(r){}finally{this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})}}zt=new WeakMap;var U1=Object.defineProperty,F1=Object.getOwnPropertyDescriptor,yt=(s,t,e,r)=>{for(var i=r>1?void 0:r?F1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&U1(t,e,i),i};let ze=(Gv=class extends KS{constructor(t,e,r,i,n){const o=t.getValue("logger");super(t,o);m(this,_r);m(this,tt);m(this,Ia);m(this,Be);m(this,hc);p(this,"name");p(this,"picture");p(this,"customParticipantId");p(this,"waitlistStatus");m(this,Ca,void 0);m(this,_t,void 0);m(this,Ra,void 0);p(this,"role");p(this,"userId");p(this,"organizationId");p(this,"supportsRemoteControl",!1);p(this,"device");m(this,et,void 0);p(this,"hidden",!1);p(this,"presetName");p(this,"roomState","init");m(this,Aa,new Set);m(this,Ma,new Set);g(this,et,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=e.customParticipantId,this.waitlistStatus="none",g(this,_t,r),g(this,Ca,i),this.hidden=!1,g(this,Ra,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=Pe.isElectron(),this.device=Pe.getDeviceInfo(),this.presetName=n,this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),I(this,hc,Yp).call(this)}get telemetry(){return a(this,et).getValue("telemetry")}get stageStatus(){return a(this,et).getValue("stageStatus")}get producers(){var t,e;return Array.from((e=(t=a(this,tt,vt).getProducers())==null?void 0:t.values())!=null?e:[])}get id(){return this.peerId}get peerId(){return a(this,et).getValue("peerId")}static async __init__(t,e,r,i,n,o=!1){var f,S,E,k,R,D;let c=(S=(f=t.getValue("defaults"))==null?void 0:f.audio)!=null?S:!0,d=(k=(E=t.getValue("defaults"))==null?void 0:E.video)!=null?k:!0;r.canProduceAudio!=="ALLOWED"&&(c=!1),r.canProduceVideo!=="ALLOWED"&&(d=!1);const l=new ze(t,e,r,i,n),u=KD(i.mediaConstraints);Ur(u,(R=t.getValue("defaults"))==null?void 0:R.mediaConfiguration);const h=(D=t.getValue("defaults"))==null?void 0:D.mediaHandler;return h&&(h.context=t),await l.init({audio:c,video:d,constraints:u},o,t),l.setupEvents(),l}cleanupEvents(){this.removeAllListeners("videoUpdate"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("VIDEO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_LIST_UPDATED"),this.localMediaHandler.removeAllListeners("SCREENSHARE_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("SCREENSHARE_ENDED"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_SILENT"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_AUDIO"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_VIDEO"),a(this,_t).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",I(this,hc,Yp));const t=a(this,Ia,Qu);t&&t.onError(e=>{this.emit("autoplayError",e)}),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::AUDIO_TRACK_CHANGE",{...$i(this)}),a(this,Be,Je)&&this.audioEnabled)try{await a(this,tt,vt).shareMic(this.audioTrack)}catch(e){this.logger.error("Self::setupEvents::Error while sharing mic",{error:e}),this.localMediaHandler.disableAudio()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}),this.localMediaHandler.on("VIDEO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::VIDEO_TRACK_CHANGE",{...$i(this)}),a(this,Be,Je)&&this.rawVideoTrack===void 0)this.logger.info("Self::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&a(this,Be,Je))try{await a(this,tt,vt).shareWebcam(this.videoTrack)}catch(e){this.logger.error("Self::setupEvents::failed shareWebcam",{error:e}),this.videoEnabled&&await this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}),this.localMediaHandler.on("DEVICE_CHANGE",async({device:e})=>{var r;this.emit("deviceUpdate",{device:e}),e.kind==="audiooutput"&&typeof HTMLAudioElement.prototype.setSinkId=="function"&&((r=a(this,Ia,Qu))==null||r.setSpeakerDevice(e.deviceId))}),this.localMediaHandler.on("DEVICE_LIST_UPDATED",e=>{this.emit("deviceListUpdate",e)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",async()=>{if(!a(this,Be,Je)){this.logger.error("Self.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await a(this,tt,vt).shareScreen(this.screenShareTracks)}catch(e){this.logger.error("Self::setupEvents::Error while sharing screen",{error:e}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.logger.info("Self::setupEvents::SCREENSHARE_TRACK_CHANGE",{...$i(this)}),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}),this.localMediaHandler.on("SCREENSHARE_ENDED",async()=>{this.logger.log("Disabling screenshare due to SCREENSHARE_ENDED"),await this.disableScreenShare(),this.logger.info("Self::setupEvents::SCREENSHARE_ENDED",{...$i(this)})}),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{var e;(e=a(this,et))==null||e.getValue("callstats").mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",async()=>{var e;a(this,Be,Je)&&await a(this,tt,vt).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(e=a(this,et))==null||e.getValue("callstats").videoOff()}),a(this,_t).on("permissionsUpdate",e=>{var r,i,n;(r=e==null?void 0:e.media)!=null&&r.audio&&a(this,_t).canProduceAudio!==G.Allowed&&(this.disableAudio(),this.logger.info(`Disabled audio due to dynamic preset change: canProduceAudio: ${this.permissions.canProduceAudio}`)),(i=e==null?void 0:e.media)!=null&&i.video&&a(this,_t).canProduceVideo!==G.Allowed&&(this.disableVideo(),this.logger.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(n=e==null?void 0:e.media)!=null&&n.screenshare&&a(this,_t).canProduceScreenshare!==G.Allowed&&(this.disableScreenShare(),this.logger.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return a(this,_t)}get config(){return a(this,Ca)}get roomJoined(){var t;return a(this,Ca).viewType===vs.Livestream&&this.stageStatus!=="ON_STAGE"?((t=a(this,et).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:a(this,Be,Je)}setName(t){if(!t)throw new C("Name cannot be empty.","1103");this.name=t}async setupTracks(t={}){t.forceReset,await this.disableAudio(),await this.disableVideo(),this.localMediaHandler.removeAudioTrack(),this.localMediaHandler.removeVideoTrack(),t.audio&&await this.enableAudio(),t.video&&await this.enableVideo()}async destructMediaHandler(){return this.localMediaHandler.destruct()}async removeDocumentEventListeners(){return this.localMediaHandler.removeDocumentEventListeners()}async enableAudio(t){var e;if(this.permissions.canProduceAudio!==G.NotAllowed&&!(a(this,_t).canProduceAudio===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if((e=a(this,et))==null||e.getValue("callstats").audioOn(),await this.localMediaHandler.enableAudio(t),a(this,Be,Je)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await a(this,tt,vt).shareMic(this.audioTrack)}catch(r){this.logger.error("Self::enableAudio::Error while sharing mic",{error:r}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}}async enableVideo(t){var e;if(a(this,_t).canProduceVideo!==G.NotAllowed&&!(a(this,_t).canProduceVideo===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if((e=a(this,et))==null||e.getValue("callstats").videoOn(),await this.localMediaHandler.enableVideo(t),a(this,Be,Je)&&this.stageStatus==="ON_STAGE")try{await a(this,tt,vt).shareWebcam(this.videoTrack)}catch(r){this.logger.error("Self::enableVideo::Error while sharing video",{error:r}),this.videoEnabled&&this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),this.logger.info("Self.enableVideo",{...$i(this)})}}async updateVideoConstraints(t){if(!this.localMediaHandler.updateVideoConstraints)throw new C("Unsupported","1102");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){if(!a(this,Be,Je))throw new C("Can`t enable screenshare without joining room","1105");if(a(this,_t).canProduceScreenshare!==G.NotAllowed&&!(a(this,_t).canProduceScreenshare===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.screenShareEnabled&&(await this.localMediaHandler.enableScreenShare(),this.screenShareTracks.audio||this.screenShareTracks.video)){try{await a(this,tt,vt).shareScreen(this.screenShareTracks)}catch(t){this.logger.error("Self::enableScreenShare::Error while sharing screen",{error:t}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}}async updateScreenshareConstraints(t){if(!this.localMediaHandler.updateScreenshareConstraints)throw new C("Unsupported","1102");await this.localMediaHandler.updateScreenshareConstraints(t)}async disableAudio(){var t;this.audioEnabled&&(this.localMediaHandler.disableAudio(),a(this,Be,Je)&&a(this,tt,vt).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),(t=a(this,et))==null||t.getValue("callstats").audioOff())}async disableVideo(){var t;this.videoEnabled&&(await this.localMediaHandler.disableVideo(),a(this,Be,Je)&&await a(this,tt,vt).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(t=a(this,et))==null||t.getValue("callstats").videoOff())}async disableScreenShare(){this.screenShareEnabled&&(await this.localMediaHandler.disableScreenShare(),a(this,Be,Je)&&await a(this,tt,vt).disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var i;g(this,Ra,t);const r=t?"pinned":"unpinned";(i=a(this,_r,Dn))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return a(this,Ra)}async pin(){if(!a(this,Be,Je))throw new C("Can`t pin participants without joining room","1105");return this.show(),a(this,tt,vt).pinPeer(this.id)}async unpin(){if(!a(this,Be,Je))throw new C("Can`t unpin participants without joining room","1105");return a(this,tt,vt).pinPeer(null)}async hide(){if(!a(this,Be,Je))throw new C("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})}show(){if(!a(this,Be,Je))throw new C("Can`t toggle participant tile without joining room","1105");this.hidden=!1,this.emit("toggleTile",{hidden:this.hidden})}async setDevice(t){var r,i,n;if(!t)throw new C("No device selected","1104");const e=this.getCurrentDevices();switch(t.deviceId&&(((r=e==null?void 0:e.audio)==null?void 0:r.deviceId)===t.deviceId||((i=e==null?void 0:e.video)==null?void 0:i.deviceId)===t.deviceId||((n=e==null?void 0:e.speaker)==null?void 0:n.deviceId)===t.deviceId)&&this.logger.warn("Self.setDevice.setting_to_in_use_device",{devices:[t]}),t.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(t,{saveDevicePreference:!0})}catch(o){a(this,Be,Je)&&await a(this,tt,vt).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":await this.localMediaHandler.setSpeakerDevice(t,{saveDevicePreference:!0});break;case"videoinput":try{await this.localMediaHandler.setVideoDevice(t,{saveDevicePreference:!0})}catch(o){a(this,Be,Je)&&await a(this,tt,vt).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}}cleanUpTracks(){var t,e,r,i;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(r=this.videoTrack)==null||r.stop(),(i=this.rawVideoTrack)==null||i.stop()}playAudio(){var t;return(t=a(this,Ia,Qu))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?a(this,Aa).add(t):a(this,Ma).add(t),this.updateVideo(t),e||(i=a(this,_r,Dn))==null||i.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(r=this.raised)!=null?r:!1))}deregisterVideoElement(t,e=!1){if(!t){a(this,_r,Dn).removeSource(this.id);return}t.srcObject=void 0,e?a(this,Aa).delete(t):(a(this,Ma).delete(t),a(this,_r,Dn).removeSource(this.id))}updateVideo(t,e=!1){var r,i,n;if(this.videoEnabled){if(this.videoTrack==null)return;const o=(r=t.srcObject)==null?void 0:r.getTracks()[0];if((o==null?void 0:o.id)===this.videoTrack.id)return;const c=new MediaStream;c.addTrack(this.videoTrack),t.srcObject=c,e||(i=a(this,_r,Dn))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(n=a(this,_r,Dn))==null||n.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},Ca=new WeakMap,_t=new WeakMap,Ra=new WeakMap,et=new WeakMap,_r=new WeakSet,Dn=function(){return a(this,et).getValue("pip")},tt=new WeakSet,vt=function(){return a(this,et).getValue("roomNodeClient")},Ia=new WeakSet,Qu=function(){return a(this,et).getValue("audioPlayback")},Be=new WeakSet,Je=function(){var t;return((t=a(this,et).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Aa=new WeakMap,Ma=new WeakMap,hc=new WeakSet,Yp=function(){Array.from(a(this,Ma)).forEach(t=>this.updateVideo(t,!1)),Array.from(a(this,Aa)).forEach(t=>this.updateVideo(t,!0))},Gv);yt([y.trace("Self.cleanupEvents")],ze.prototype,"cleanupEvents",1),yt([y.trace("Self.setupEvents")],ze.prototype,"setupEvents",1),yt([y.trace("Self.setupTracks")],ze.prototype,"setupTracks",1),yt([y.trace("Self.destructMediaHandler")],ze.prototype,"destructMediaHandler",1),yt([y.trace("Self.removeDocumentEventListeners")],ze.prototype,"removeDocumentEventListeners",1),yt([ur.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"Self.toggleAudio",timeout:3e3}),y.trace("Self.enableAudio")],ze.prototype,"enableAudio",1),yt([ur.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"Self.toggleVideo",timeout:3e3}),y.trace("Self.enableVideo")],ze.prototype,"enableVideo",1),yt([y.trace("Self.updateVideoConstraints")],ze.prototype,"updateVideoConstraints",1),yt([y.trace("Self.enableScreenShare"),ur.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3})],ze.prototype,"enableScreenShare",1),yt([y.trace("Self.updateScreenshareConstraints")],ze.prototype,"updateScreenshareConstraints",1),yt([ur.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"Self.toggleAudio",timeout:3e3}),y.trace("Self.disableAudio")],ze.prototype,"disableAudio",1),yt([ur.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"Self.toggleVideo",timeout:3e3}),y.trace("Self.disableVideo")],ze.prototype,"disableVideo",1),yt([ur.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3}),y.trace("Self.disableScreenShare")],ze.prototype,"disableScreenShare",1),yt([y.trace("Self.setDevice")],ze.prototype,"setDevice",1),ze=yt([pt("1100")],ze);class fp extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,fp)}}class Sp extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Sp)}}class vp{constructor(t,e=!1){p(this,"pendingTasks",new Map);p(this,"nextTaskId",0);p(this,"stopping",!1);m(this,pc,void 0);this.log=e,g(this,pc,{info:e&&t?t.info:()=>{}})}get size(){return this.pendingTasks.size}async push(t,e,r){if(e=e!=null?e:t.name,typeof t!="function")throw new TypeError("given task is not a function");if(e)try{Object.defineProperty(t,"name",{value:e})}catch(i){}return new Promise((i,n)=>{const o={id:this.nextTaskId++,task:t,metadata:r,name:e,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:c=>{if(o.completed)return;o.completed=!0,this.pendingTasks.delete(o.id),i(c);const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)},reject:c=>{if(!o.completed&&(o.completed=!0,this.pendingTasks.delete(o.id),n(c),!this.stopping)){const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)}}};this.pendingTasks.set(o.id,o),this.pendingTasks.size===1&&this.execute(o)})}stop(){this.stopping=!0;for(const t of this.pendingTasks.values())t.reject(new fp);this.stopping=!1}remove(t){const e=Array.from(this.pendingTasks.values())[t];e&&e.reject(new Sp)}get(t){return Array.from(this.pendingTasks.values())[t]}dump(){const t=Date.now();let e=0;return Array.from(this.pendingTasks.values()).map(r=>({idx:e++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:t-r.enqueuedAt,executionTime:r.executedAt?t-r.executedAt:0}))}async execute(t){if(t.executedAt)throw new Error("task already being executed");t.executedAt=Date.now();try{const e=this.pendingTasks.size,r=await t.task(),i=Date.now();a(this,pc).info(`AwaitQueue.push(${t.name})_timings`,{awaitQueueTask:{id:t.id,metadata:t.metadata,queueSizeAtStart:e,execTime:(i-t.executedAt)/1e3,taskStartTime:(t.executedAt-t.enqueuedAt)/1e3}}),t.resolve(r)}catch(e){t.reject(e)}}}pc=new WeakMap;class ko extends Error{constructor(t){super(t),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,ko):this.stack=new Error(t).stack}}class Nt extends Error{constructor(t){super(t),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Nt):this.stack=new Error(t).stack}}class Jr extends Error{constructor(t){super(t),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Nt):this.stack=new Error(t).stack}}const zS=s=>new Promise(t=>setTimeout(t,s));async function yl(s,t){return new Promise(async(e,r)=>{const{strategy:i,maxRetryCount:n,delayTime:o}={strategy:"linear",maxRetryCount:3,delayTime:10,...t};let c=0,d,l=!1;const u=h=>{l=!0,r(h)};for(;c<n;){try{const h=await s(c,u);return e(h)}catch(h){if(d=h,l)break;if(c<n)i==="linear"?await zS(o*(c+1)):i==="exponential"&&await zS(o*(c+Math.max(0,c-1)));else break}c+=1}return r(d)})}function B1(s){return s.map(t=>({channels:t.channels,clockRate:t.clockRate,mimeType:t.mimeType,sdpFmtpLine:t.sdpFmtpLine}))}function H1(s){return s.map(t=>({uri:t.uri}))}function El(s){return{codecs:B1(s.codecs),headerExtensions:H1(s.headerExtensions?s.headerExtensions:[])}}function q1(s){const t=RTCRtpReceiver.getCapabilities("audio"),e=RTCRtpReceiver.getCapabilities("video"),r=RTCRtpSender.getCapabilities("audio"),i=RTCRtpSender.getCapabilities("video");s&&(e.codecs=e.codecs.filter(({mimeType:d})=>s===d),i.codecs=i.codecs.filter(({mimeType:d})=>s===d));const n={audio:El(t),video:El(e)};return{sender:{audio:El(r),video:El(i)},receiver:n}}var YS={},bl={},j1={get exports(){return bl},set exports(s){bl=s}},QS=j1.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(s){return s.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(s){return s.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(s){var t="candidate:%s %d %s %d %s %d typ %s";return t+=s.raddr!=null?" raddr %s rport %d":"%v%v",t+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(t+=" generation %d"),t+=s["network-id"]!=null?" network-id %d":"%v",t+=s["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(s){var t="ssrc:%d";return s.attribute!=null&&(t+=" %s",s.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(s){return s.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(s){return s.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(s){return"imageattr:%s %s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(s){return"simulcast:%s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var t="mediaclk:";return t+=s.id!=null?"id=%s %s":"%v%s",t+=s.mediaClockValue!=null?"=%s":"",t+=s.rateNumerator!=null?" rate=%s":"",t+=s.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(QS).forEach(function(s){var t=QS[s];t.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})}),function(s){var t=function(c){return String(Number(c))===c?Number(c):c},e=function(c,d,l,u){if(u&&!l)d[u]=t(c[1]);else for(var h=0;h<l.length;h+=1)c[h+1]!=null&&(d[l[h]]=t(c[h+1]))},r=function(c,d,l){var u=c.name&&c.names;c.push&&!d[c.push]?d[c.push]=[]:u&&!d[c.name]&&(d[c.name]={});var h=c.push?{}:u?d[c.name]:d;e(l.match(c.reg),h,c.names,c.name),c.push&&d[c.push].push(h)},i=bl,n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);s.parse=function(c){var d={},l=[],u=d;return c.split(/(\r\n|\r|\n)/).filter(n).forEach(function(h){var f=h[0],S=h.slice(2);f==="m"&&(l.push({rtp:[],fmtp:[]}),u=l[l.length-1]);for(var E=0;E<(i[f]||[]).length;E+=1){var k=i[f][E];if(k.reg.test(S))return r(k,u,S)}}),d.media=l,d};var o=function(c,d){var l=d.split(/=(.+)/,2);return l.length===2?c[l[0]]=t(l[1]):l.length===1&&d.length>1&&(c[l[0]]=void 0),c};s.parseParams=function(c){return c.split(/;\s?/).reduce(o,{})},s.parseFmtpConfig=s.parseParams,s.parsePayloads=function(c){return c.toString().split(" ").map(Number)},s.parseRemoteCandidates=function(c){for(var d=[],l=c.split(" ").map(t),u=0;u<l.length;u+=3)d.push({component:l[u],ip:l[u+1],port:l[u+2]});return d},s.parseImageAttributes=function(c){return c.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(o,{})})},s.parseSimulcastStreamList=function(c){return c.split(";").map(function(d){return d.split(",").map(function(l){var u,h=!1;return l[0]!=="~"?u=t(l):(u=t(l.substring(1,l.length)),h=!0),{scid:u,paused:h}})})}}(YS);var Tp=bl,G1=/%[sdv%]/g,W1=function(s){var t=1,e=arguments,r=e.length;return s.replace(G1,function(i){if(t>=r)return i;var n=e[t];switch(t+=1,i){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}})},Co=function(s,t,e){var r=t.format instanceof Function?t.format(t.push?e:e[t.name]):t.format,i=[s+"="+r];if(t.names)for(var n=0;n<t.names.length;n+=1){var o=t.names[n];t.name?i.push(e[t.name][o]):i.push(e[t.names[n]])}else i.push(e[t.name]);return W1.apply(null,i)},J1=["v","o","s","i","u","e","p","c","b","t","r","z","a"],K1=["i","c","b","a"],z1=function(s,t){t=t||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(n){n.payloads==null&&(n.payloads="")});var e=t.outerOrder||J1,r=t.innerOrder||K1,i=[];return e.forEach(function(n){Tp[n].forEach(function(o){o.name in s&&s[o.name]!=null?i.push(Co(n,o,s)):o.push in s&&s[o.push]!=null&&s[o.push].forEach(function(c){i.push(Co(n,o,c))})})}),s.media.forEach(function(n){i.push(Co("m",Tp.m[0],n)),r.forEach(function(o){Tp[o].forEach(function(c){c.name in n&&n[c.name]!=null?i.push(Co(o,c,n)):c.push in n&&n[c.push]!=null&&n[c.push].forEach(function(d){i.push(Co(o,c,d))})})})}),i.join(`\r
|
|
15
15
|
`)+`\r
|
|
16
16
|
`},Fi=YS,Y1=z1,wl=Y1,Bi=Fi.parse;Fi.parseParams,Fi.parseFmtpConfig,Fi.parsePayloads,Fi.parseRemoteCandidates,Fi.parseImageAttributes,Fi.parseSimulcastStreamList;class Pl extends Tt.EventEmitter{constructor(e){super();m(this,mc,void 0);g(this,mc,e),this.setMaxListeners(1/0)}get logger(){return a(this,mc).getValue("logger")}safeEmit(e,...r){const i=this.listenerCount(e);try{return this.emit(e,...r)}catch(n){return this.logger.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:n}),Boolean(i)}}async safeEmitAsPromise(e,...r){const i={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,i,...r)}async safeEmitAsPromiseWithTimeout(e,r,...i){return new Promise((n,o)=>{setTimeout(o,r,"event request timeout");try{this.emit(e.toString(),...i,n,o)}catch(c){this.logger.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:c}),o(c)}})}}mc=new WeakMap;function Q1(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}class X1 extends Pl{constructor(e,r){var i;super(e);m(this,qs);m(this,fc);m(this,du);m(this,lu);p(this,"rtpReceiver");p(this,"id");p(this,"localId");p(this,"producerId");p(this,"producingTransportId");p(this,"mimeType");p(this,"track");p(this,"peerId");p(this,"appData");p(this,"transceiver");m(this,gc,void 0);m(this,pn,void 0);m(this,Hs,void 0);m(this,cu,void 0);this.id=r.id,this.localId=r.localId,g(this,gc,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,g(this,Hs,!1),this.producerId=r.producerId,this.track=r.track,g(this,pn,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,I(this,du,cT).call(this),g(this,cu,e)}get closed(){return a(this,Hs)}get kind(){return this.track.kind}get paused(){return a(this,pn)}reassignPeer(e){this.peerId=e}close(e,r){a(this,Hs)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,qs,wi)),g(this,Hs,!0),r&&(I(this,lu,dT).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(a(this,Hs))throw new Nt("closed");return a(this,gc).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",a(this,qs,wi)),a(this,Hs)){this.logger.error("consumer::pause() | Consumer closed",a(this,qs,wi));return}g(this,pn,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,qs,wi)),a(this,Hs)){this.logger.error("Consumer::resume() | Consumer closed",a(this,qs,wi));return}g(this,pn,!1),this.track.enabled=!0,this.safeEmit("resume")}}gc=new WeakMap,pn=new WeakMap,Hs=new WeakMap,cu=new WeakMap,qs=new WeakSet,wi=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},fc=new WeakSet,Qp=function(){this.logger.debug('Consumer::track "ended" event',a(this,qs,wi)),this.safeEmit("trackended")},du=new WeakSet,cT=function(){this.track.addEventListener("ended",I(this,fc,Qp).bind(this))},lu=new WeakSet,dT=function(){try{this.track.removeEventListener("ended",I(this,fc,Qp)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...a(this,qs,wi),error:e})}};class Z1 extends Pl{constructor(e,r){var i,n;super(e);m(this,Yt);p(this,"id");p(this,"localId");m(this,Cs,void 0);p(this,"kind");p(this,"appData");p(this,"rtpSender");m(this,Oa,void 0);m(this,Da,void 0);m(this,mn,void 0);m(this,ps,!1);m(this,dt,void 0);m(this,mi,void 0);m(this,Na,void 0);m(this,uu,void 0);this.id=r.id,this.localId=r.localId,g(this,dt,r.track),this.kind=(i=r.track)==null?void 0:i.kind,g(this,mi,r.disableTrackOnPause?!((n=r.track)!=null&&n.enabled):!1),g(this,Na,void 0),g(this,Oa,r.stopTracks),g(this,Da,r.disableTrackOnPause),g(this,mn,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),g(this,Cs,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),g(this,uu,e)}get closed(){return a(this,ps)}get track(){return a(this,dt)}get paused(){return a(this,mi)}get maxSpatialLayer(){return a(this,Na)}async close(e){if(a(this,ps))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,Yt,As)),g(this,ps,!0),this._destroyTrack(),e===_l){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await a(this,Cs).stopSending(this.localId),{answer:n}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(n)}async getStats(){if(a(this,ps))throw new Nt("closed");return a(this,Cs).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",a(this,Yt,As)),a(this,ps)&&this.logger.error("Producer::pause() | Producer closed",a(this,Yt,As)),g(this,mi,!0),a(this,dt)&&a(this,Da)&&(a(this,dt).enabled=!1),a(this,mn)&&a(this,Cs).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,Yt,As)),a(this,ps)){this.logger.error("Producer::resume() | Producer closed",a(this,Yt,As));return}g(this,mi,!1),a(this,dt)&&a(this,Da)&&(a(this,dt).enabled=!0),a(this,mn)&&a(this,Cs).replaceTrack(this.localId,a(this,dt)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,a(this,Yt,As)),a(this,ps)){if(e&&a(this,Oa))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...a(this,Yt,As),error:r})}throw new Nt("closed")}else if(e&&e.readyState==="ended")throw new Nt("track ended");if(e===a(this,dt)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,a(this,Yt,As));return}(!a(this,mn)||!a(this,mi))&&await a(this,Cs).replaceTrack(this.localId,e),this._destroyTrack(),g(this,dt,e),this._handleTrack()}async setMaxSpatialLayer(e){if(a(this,ps))throw new Nt("closed");if(this.kind!=="video")throw new ko("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await a(this,Cs).setMaxSpatialLayer(this.localId,e),g(this,Na,e)}async setRtpEncodingParameters(e){if(a(this,ps))throw new Nt("closed");if(typeof e!="object")throw new TypeError("invalid params");await a(this,Cs).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,Yt,As)),this.safeEmit("trackended",this.track.id)}_handleTrack(){a(this,dt)&&a(this,dt).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(a(this,dt))try{a(this,dt).removeEventListener("ended",this._onTrackEnded),a(this,Oa)&&a(this,dt).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...a(this,Yt,As),error:r})}}}Cs=new WeakMap,Oa=new WeakMap,Da=new WeakMap,mn=new WeakMap,ps=new WeakMap,dt=new WeakMap,mi=new WeakMap,Na=new WeakMap,uu=new WeakMap,Yt=new WeakSet,As=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};const _l="transport closed",eN=3e4,Va=class extends Pl{constructor(e,{id:r,direction:i,handlerFactory:n,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:h}){var k,R,D;super(e);p(this,"awaitQueue");p(this,"observer");p(this,"id");p(this,"serverId");p(this,"direction");p(this,"maxSctpMessageSize");p(this,"handler");p(this,"connectionState","new");p(this,"producers");p(this,"consumers");p(this,"connected",!1);p(this,"transportConnectionPromise");p(this,"consumerTrackEvents");p(this,"unknownTracksMap");p(this,"appData");m(this,La,void 0);g(this,La,e);const f=e.getValue("logger");f.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const S=Q1(l,{});delete S.iceServers,delete S.iceTransportPolicy,delete S.bundlePolicy,delete S.rtcpMuxPolicy,delete S.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new vp(f,!0),this.handler=n(),this.handler.enableHighBitrate=(k=h==null?void 0:h.enableHighBitrate)!=null?k:!1,this.handler.enableStereo=(R=h==null?void 0:h.enableStereo)!=null?R:!1,this.handler.enableDtx=(D=h==null?void 0:h.enableDtx)!=null?D:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=u||{};const E=3e4;this.transportConnectionPromise=new Promise(N=>{const F=setTimeout(()=>{f.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),N(!1)},E);this.once("connected",()=>{clearTimeout(F),N(!0)}),this.once("disconnect",()=>{clearTimeout(F),N(!1)}),this.once("close",()=>{clearTimeout(F),N(!1)})}),this.handler.on("@connectionstatechange",N=>{N!==this.connectionState&&(this.connectionState=N,N==="connected"&&(this.connected=!0,this.emit("connected")),N==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(N==="failed"||N==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",N))}),this.handler.on("@icecandidate",({candidate:N})=>{this.closed||this.safeEmit("icecandidate",N)})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId!==e&&(this.serverId=e,this.emit("serveridchange",e))}close(){this.closed||(this.logger.debug("Transport close called"),this.connectionState="closed",this.awaitQueue.stop(),this.awaitQueue=void 0,this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(_l).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(_l)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new Nt("closed");return this.handler.getTransportStats()}async connect(e){try{if(await this.awaitQueue.push(async()=>{const{offerSdp:r,callback:i}=await this.handler.connect(),{transportId:n,answer:o}=await e(r);this.setServerId(n),await i(o)}),!await this.transportConnectionPromise)throw new Error("ice connection failed")}catch(r){throw this.logger.error("transport failed to connect:",{error:r}),r}}async restartIce(){if(this.logger.debug("restartIce()"),this.closed)throw new Nt("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new ko("not a sending Transport");if(r.readyState==="ended")throw new Nt("track ended");if(i&&typeof i!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!await this.transportConnectionPromise)throw new Jr("transport not connected");return!0}async produce(e,r){if(!await this.canProduce(e))throw new Error("Cannot produce");const{track:n,encodings:o,codecOptions:c,stopTracks:d=!0,disableTrackOnPause:l=!0,zeroRtpOnPause:u=!1,appData:h={}}=e;this.logger.debug(`produce() [track:${n.id}]`);const{producerId:f,localId:S,rtpSender:E}=await this.awaitQueue.push(async()=>{const{offerSdp:k,callback:R,sender:D,mid:N}=await this.handler.send({track:n,encodings:o,codecOptions:c,screenShare:h==null?void 0:h.screenShare}),{answer:F,producerId:U}=await r({offer:k,kind:n.kind,paused:l?!n.enabled||Object.hasOwn(n,"fakeTracks"):!1,appData:{...h||{},mid:N},codecOptions:c,producingTransportId:this.serverId}),B=await R(F);return{producerId:U,localId:B,rtpSender:D}},"Transport.produce");return this.createProducerObject({id:f,localId:S,track:n,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:h,handler:this.handler,rtpSender:E})}async createProducerObject(e){const r=new Z1(a(this,La),e);return this.producers.set(r.id,r),r.once("close",()=>{this.producers.delete(r.id)}),this.emit("newproducer",r),r}async closeProducer(e){await this.awaitQueue.push(e.close.bind(e),"Transport.closeProducer")}async canConsume(){if(this.closed)throw new Nt("closed");if(this.direction!=="recv")throw new ko("not a receiving transport");if(!await this.transportConnectionPromise)throw new Jr("transport not connected");return!0}async consume(e,r,i){return this.awaitQueue.push(async()=>{const n={},{consumerStates:o,sessionDescription:c,failedProducers:d}=await r(e);o.forEach((u,h)=>{n[h]=this.createConsumerObjectAndWaitForTrack({...u,producerId:h})}),c&&(this.logger.info("Session description found, sending negotiation request"),await i(c));const l=[];return await Promise.all(Object.entries(n).map(([u,h])=>h.then(f=>l.push(f)).catch(()=>{this.logger.error(`Failed to create consumer object, producer: ${u}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:l,failedProducers:d}},"Transport.consume",{producersLength:e.length})}static parseCodecAndFmtpMappings(e,r){const i=Bi(e.sdp),n={};return i.media.forEach(o=>{r.includes(o.mid.toString())&&(n[o.mid.toString()]={rtp:o.rtp,fmtp:o.fmtp,payloads:o.payloads,rtcpFb:o.rtcpFb})}),n}static setCodecAndFmtpMappings(e,r,i){const n=Bi(e.sdp);return n.media=n.media.map(c=>{if(r.includes(c.mid.toString())){const d={...c};return d.rtp=i[c.mid.toString()].rtp,d.fmtp=i[c.mid.toString()].fmtp,d.payloads=i[c.mid.toString()].payloads,d.rtcpFb=i[c.mid.toString()].rtcpFb,d}return c}),{...e,sdp:wl(n)}}static parseHeaderExtensionMappings(e){const r=Bi(e.sdp),i={};return r.media.forEach(n=>{i[n.mid]=n.ext}),i}static setHeaderExtensionMappings(e,r){const i=Bi(e.sdp);return i.media=i.media.map(o=>{const c={...o};return c.ext=r[o.mid],c}),{...e,sdp:wl(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),n=Va.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=Va.parseHeaderExtensionMappings(this.handler.pc.remoteDescription);this.logger.info("Stopping transceivers",{consumerIds:e.map(({id:l})=>l)}),e.forEach(l=>l.close(void 0,!0));let c=await this.handler.pc.createOffer();this.logger.info("[SDP] Created offer for closing consumers",{sdp:c.sdp}),c=Va.setCodecAndFmtpMappings(c,i,n),c=Va.setHeaderExtensionMappings(c,o),this.logger.info("[SDP] Updated codec and fmtp mappings in close consumer offer",{sdp:c.sdp}),await this.setLocalDescription(c),this.logger.info("Successfully set local description in close consumers");const d=await r(e,c);this.logger.info("[SDP] Received answer in close consumers",{sdp:d.sdp}),await this.setRemoteDescription(d),this.logger.info("[SDP] Remote description was set successfully in close consumers",{sdp:d.sdp})}catch(i){this.logger.error("Failed to close consumers",{error:i})}}async setRemoteOffer(e){try{this.logger.info("[SDP] Received offer from SFU",{sdp:e.sdp}),await this.setRemoteDescription(e);const r=await this.handler.pc.createAnswer();this.logger.info("[SDP] Created answer corresponding to received offer",{sdp:r.sdp});const i=Bi(r.sdp);return i.media=i.media.map(n=>{if(n.type==="audio"){const o={...n},c=o.fmtp.find(l=>l.payload===111);return c&&(c.config+=";stereo=1;sprop-stereo=1"),o.rtcpFb||(o.rtcpFb=[]),o.rtcpFb.some(l=>l.type==="nack")||o.rtcpFb.push({payload:parseInt(o.payloads,10),type:"nack"}),o}return n}),r.sdp=wl(i),this.logger.info("[SDP] Setting munged SDP",{sdp:r.sdp}),await this.setLocalDescription(r),this.logger.info("[SDP] Successfully set local description",{sdp:r.sdp}),r}catch(r){throw this.logger.error("Set remote offer failed",{error:r}),r}}_ontrack(e){const{track:r,transceiver:i}=e;this.logger.info(`track event received [trackId: ${r.id}] [mid: ${i.mid}]`);const n=`${i.mid}:${r.kind}`;r.addEventListener("ended",()=>{this.logger.info(`rtc consumer track ended [trackId: ${r.id}]`),this.unknownTracksMap.delete(n)});const o=this.consumerTrackEvents.get(n);o?(o(r,i),this.consumerTrackEvents.delete(n)):(this.logger.warn(`track event handler not found ${n}`),this.unknownTracksMap.set(n,e))}async createConsumerObjectAndWaitForTrack(e){const{consumerId:r,producerId:i,producingPeerId:n,producingTransportId:o,streamId:c,paused:d,screenShare:l,appData:u,kind:h,mimeType:f}=e,S=`${c}:${h}`,E={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(k,R)=>{const D=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${S} producingPeerId: ${n}`),this.consumerTrackEvents.delete(S),E.isTimedout=!0,R(E)},eN),N=(U,B)=>{try{if(U.readyState==="ended")clearTimeout(D),R(E);else{const Z=U;Z.enabled=!0,this.handler.midTransceiverMap.set(B.mid,B);const ie=new X1(a(this,La),{id:r,localId:B.mid,transceiver:B,track:Z,paused:d,producerId:i,producingPeerId:n,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:n},rtpReceiver:B.receiver,mimeType:f});this.consumers.set(r,ie),ie.once("close",()=>{this.consumers.delete(ie.id),this.handler.midTransceiverMap.delete(B.mid)}),this.logger.info(`${l?"screenshare":"participant"} ${h} consumer ${r} created for producer ${i} of remote producing peer ${n} with track ${U.id} on mid ${B.mid}`),this.emit("newconsumer",ie),clearTimeout(D),k(ie)}}catch(Z){this.logger.error(`Error while creating ${l?"screenshare":"participant"} ${h} consumer for producerId ${i} of remote peer ${n}`,Z),clearTimeout(D),R(E)}},F=this.unknownTracksMap.get(S);F?(this.logger.info(`track event already received for ${l?"screenshare":"participant"} ${h} consumer ${r} of a remote peer ${n} with trackId ${F.track.id} on mid ${F.transceiver.mid} having key ${S}`),this.unknownTracksMap.delete(S),N(F.track,F.transceiver)):(this.logger.info(`Registering onTrack handler for ${l?"screenshare":"participant"} ${h} consumer ${r} of a remote peer ${n} with key ${S}`),this.consumerTrackEvents.set(S,N))})}async setRemoteDescription(e){await this.handler.pc.setRemoteDescription(e)}async setLocalDescription(e){this.logger.debug(`[SDP] ${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),await this.handler.pc.setLocalDescription(e)}};let yp=Va;La=new WeakMap;class tN{constructor(t){m(this,st,void 0);p(this,"events");g(this,st,t),this.events=Es}async joinRoom(t,e,r,i=!1){const n={roomUuid:t,displayName:e,prejoined:i,capabilities:r};return(await a(this,st).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:hR.toBinary(n),timeout:5e3})).payload}async connectTransport(t){const e=(await a(this,st).sendMessagePromise(this.events.createWebRTCTransport,FC.toBinary(t))).payload,{transportId:r,description:i,producerIds:n}=Uf.fromBinary(e),o={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:r,answer:o,producerIds:n}}async produce(t){var n,o;const e=(await a(this,st).sendMessagePromise(this.events.produce,CR.toBinary(t))).payload,r=cI.fromBinary(e);return{answer:{sdp:(n=r==null?void 0:r.description)==null?void 0:n.sdp,type:(o=r==null?void 0:r.description)==null?void 0:o.type},producerId:r.producerId}}async consume(t){const e=(await a(this,st).sendMessagePromise(this.events.consume,ER.toBinary(t))).payload,{consumerIdsMap:{map:r},description:i}=aI.fromBinary(e);return{consumerStateMap:r,sessionDescription:i}}async closeProducer(t){const e=(await a(this,st).sendMessagePromise(this.events.closeProducer,NR.toBinary(t))).payload,{description:r}=gI.fromBinary(e);return r}async closeConsumer(t){return(await a(this,st).sendMessagePromise(this.events.closeConsumer,VR.toBinary(t))).payload}async updateConsumersSimulcastConfig(t){return(await a(this,st).sendMessagePromise(this.events.updateConsumersSimulcastConfig,_R.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},i=(await a(this,st).sendMessagePromise(this.events.hostControlPeer,HR.toBinary(r))).payload;if(!i)return!1;const{status:n}=bI.fromBinary(i);return n==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await a(this,st).sendMessagePromise(this.events.hostControlAllPeers,jR.toBinary(e))).payload;if(!r)return!1;const{status:i}=PI.fromBinary(r);return i==="success"}async kickAll(){const t={propagateKickAcrossRooms:!1};a(this,st).sendMessagePromise($.kickAll,Gf.toBinary(t))}async kickPeer(t){a(this,st).sendMessagePromise($.kick,aS.toBinary(t))}async changeDisplayName(t){const e=(await a(this,st).sendMessagePromise(this.events.changeDisplayName,FR.toBinary(t))).payload;if(!e)return!1;const{status:r}=kI.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await a(this,st).sendMessagePromise(this.events.selfJoinComplete,mR.toBinary(t))).payload;return xh.fromBinary(e)}async audioActivity(t){a(this,st).sendMessage(this.events.audioActivity,HC.toBinary(t))}}st=new WeakMap;var as=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s.CLOSED="closed",s))(as||{});class Ep extends Pl{constructor(){super(...arguments);p(this,"_sendWebStream",new MediaStream);p(this,"_sendScreenShareStream",new MediaStream);p(this,"_direction");p(this,"pc");p(this,"_transportReady",!1);p(this,"_mapMidTransceiver",new Map);p(this,"enableHighBitrate",!1);p(this,"enableStereo",!1);p(this,"enableDtx",!0)}get midTransceiverMap(){return this._mapMidTransceiver}close(){if(this.logger.debug(`${this.name}::close()`),this.pc)try{this.pc.close()}catch(e){this.logger.error(`${this.name}::pc.close()`,{error:e})}}async restartIce(){this.logger.debug(`${this.name}::restartIce()`);const e=await this.pc.createOffer({iceRestart:!0});return this.logger.debug(`[SDP] ${this.name}::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:async i=>{this.logger.info(`[SDP] ${this.name}::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this.pc.setRemoteDescription(i)}}}init({direction:e,iceServers:r,iceTransportPolicy:i,additionalSettings:n,proprietaryConstraints:o,onTrackHandler:c}){this.logger.debug("HandlerInterface::init()"),this._direction=e,this.pc=new RTCPeerConnection({iceServers:r||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...n},o),c&&this.pc.addEventListener("track",d=>{c(d)}),this._addEventListeners()}async connect(){this.pc.addTransceiver("audio",{direction:"sendonly"}),this.pc.addTransceiver("video",{direction:"sendonly",...this._direction==="send"?{sendEncodings:[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]}:{}});const e=await this.pc.createOffer();return await this.pc.setLocalDescription(e),this.logger.info(`[SDP] connect offer: ${JSON.stringify(e)}`),{offerSdp:e,callback:async i=>{this.logger.debug(`[SDP] ${this.name}::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this.pc.setRemoteDescription(i)}}}async getTransportStats(){return this.pc.getStats()}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}async getReceiverStats(e){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()}async stopSending(e){this._assertSendDirection(),this.logger.debug(`stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.sender.replaceTrack(null),this.pc.removeTrack(r.sender),r.direction="inactive";const i=await this.pc.createOffer();return this.logger.debug(`[SDP] stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(i)}]`),await this.pc.setLocalDescription(i),{offerSdp:i,callback:async o=>{this.logger.debug(`[SDP] stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(o)}]`),await this.pc.setRemoteDescription(o),this.midTransceiverMap.delete(e)}}}async replaceTrack(e,r){this._assertSendDirection(),r?this.logger.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):this.logger.debug(`replaceTrack() [localId:${e}, no track]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");await i.sender.replaceTrack(r)}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters();n.encodings.forEach((o,c)=>{c<=r?o.active=!0:o.active=!1}),await i.sender.setParameters(n)}async setRtpEncodingParameters(e,r){this._assertSendDirection(),this.logger.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters();n.encodings.forEach((o,c)=>{n.encodings[c]={...o,...r}}),await i.sender.setParameters(n)}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}_addEventListeners(){this.pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this.pc.addEventListener("iceconnectionstatechange",()=>{switch(this.pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),this.logger.debug("negotiationneeded")}),this.pc.addEventListener("icegatheringstatechange",()=>{switch(this.pc.iceGatheringState){case"gathering":this.logger.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":this.logger.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("icecandidateerror",e=>{this.logger.warn("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})})}}class bp extends Ep{static createFactory(t){return()=>new bp(t)}get name(){return"Chrome74"}init({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:i,proprietaryConstraints:n,onTrackHandler:o}){this._direction=t,this.pc=new RTCPeerConnection({iceServers:e||[],iceTransportPolicy:r||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...i},n),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection();const n=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e});if(!navigator.isReactNative){this.logger.debug("creating new transceiver");const d=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`senders available params: ${JSON.stringify(d)}`);const l=[];r&&r.length&&r.forEach(u=>{var f;const h=d.codecs.find(S=>S.mimeType.includes(u.name));if(u.parameters){this.logger.debug(`codecOption.parameters:${JSON.stringify(u.parameters)}`);const S=((f=h.sdpFmtpLine)==null?void 0:f.split(";"))||[];S.push(...u.parameters);const E=Array.from(new Set(S).values());h.sdpFmtpLine=E.join(";")}l.push(h)}),this.logger.info(`selected codecs: ${JSON.stringify(l)}`),n.setCodecPreferences(l)}const o=await this.pc.createOffer();if(await this.pc.setLocalDescription(o),r&&r.findIndex(({name:d})=>d==="opus")>=0){const{enableDtx:d,enableStereo:l}=this,u=this.enableHighBitrate?l?128e3:64e3:l?64e3:32e3;o.sdp=o.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${d?"usedtx=1;":""}${l?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${u}`),o.sdp+=`a=rtcp-fb:111 nack\r
|
|
17
|
-
`}this.midTransceiverMap.set(n.mid,n);const c=async d=>(this.logger.debug(`[SDP] send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),await this.pc.setRemoteDescription(d),n.mid);return this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(o,void 0,2)}]`),{offerSdp:o,callback:c,sender:n.sender,mid:n.mid}}}class kl extends Ep{constructor(e,r){super(e);p(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new kl(e,r)}get name(){return"Firefox60"}async send({track:e,encodings:r,codecOptions:i,screenShare:n}){this._assertSendDirection();const o=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(e,{direction:"sendonly",streams:[n?this._sendScreenShareStream:this._sendWebStream],...o});if(!this.supportsSendEncodings&&r){r.reverse();const h=c.sender.getParameters();h.encodings=r,await c.sender.setParameters(h)}const d=(h,f)=>{var F;const S=Bi(h),E=S.media[S.media.length-1],k=E.rtp.filter(U=>f.some(B=>B.name===U.codec)),R=E.fmtp.filter(U=>k.some(B=>B.payload===U.payload)),D=(F=E.rtcpFb)==null?void 0:F.filter(U=>k.some(B=>B.payload===U.payload)),N=k.map(U=>U.payload);return S.media[S.media.length-1].rtp=k,S.media[S.media.length-1].fmtp=R,S.media[S.media.length-1].rtcpFb=D,S.media[S.media.length-1].payloads=N.join(" "),wl(S)},l=await this.pc.createOffer();if(l.sdp=d(l.sdp,i),this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),await this.pc.setLocalDescription(l),e==="audio"||e.kind==="audio"){const{enableDtx:h,enableStereo:f}=this,S=this.enableHighBitrate?f?128e3:64e3:f?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${f?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${S}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:l,callback:async h=>(this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),await this.pc.setRemoteDescription(h),c.mid),sender:c.sender,mid:c.mid}}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters(),o=n.encodings.length-1-r;n.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),await i.sender.setParameters(n)}}class wp extends Ep{static createFactory(t){return()=>new wp(t)}get name(){return"Safari12"}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection(),this.logger.debug("Safari12::creating new transceiver");const n=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e}),o=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`Safari12::senders available params: ${JSON.stringify(o)}`);const c=[];r&&r.length>0&&r.forEach(u=>{var f;const h=o.codecs.find(S=>S.mimeType.includes(u.name));if(u.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(u.parameters)}`);const S=((f=h.sdpFmtpLine)==null?void 0:f.split(";"))||[];S.push(...u.parameters);const E=[...new Set(S).values()];h.sdpFmtpLine=E.join(";")}c.push(h)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(c)}`),n.setCodecPreferences(c);const d=await this.pc.createOffer();if(await this.pc.setLocalDescription(d),t==="audio"||t.kind==="audio"){const{enableStereo:u,enableDtx:h}=this,f=this.enableHighBitrate?u?128e3:64e3:u?64e3:32e3;d.sdp=d.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${u?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${f}`)}return this.midTransceiverMap.set(n.mid,n),{offerSdp:d,callback:async u=>(this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),await this.pc.setRemoteDescription(u),n.mid),sender:n.sender,mid:n.mid}}}function sN(s){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){s.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return s.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=Sm.getParser(t),r=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=55",chromium:">=55"}))return;if(e.satisfies({firefox:">=110"}))return"Firefox110";if(e.satisfies({firefox:">=60"}))return"Firefox60";if(e.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||e.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(e.satisfies({safari:">=11"})||e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return;if(r.name&&r.name.toLowerCase()==="blink"){const i=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return i?Number(i[1])>=74?"Chrome74":void 0:"Chrome74"}if(r.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;s.warn("Device::this._detectDevice() | browser not supported");return}s.warn("Device::this._detectDevice() | unknown device")}class rN{constructor(t,{handlerName:e,handlerFactory:r}={}){p(this,"handlerFactory");m(this,kr,void 0);m(this,gn,void 0);const i=t.getValue("logger");if(i.debug("Device constructor() called."),g(this,kr,t),g(this,gn,i),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)a(this,gn).debug(`Device::constructor() | handler given: ${e}`);else if(e=sN(a(this,gn)),e)a(this,gn).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=bp.createFactory(a(this,kr));break;case"Safari12":this.handlerFactory=wp.createFactory(a(this,kr));break;case"Firefox60":this.handlerFactory=kl.createFactory(a(this,kr),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=kl.createFactory(a(this,kr),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=ki();return new yp(a(this,kr),{id:e,...t,handlerFactory:this.handlerFactory})}}kr=new WeakMap,gn=new WeakMap;const iN=2e3;class nN extends Tt.EventEmitter{constructor(e,r){super();m(this,Gs);m(this,yc);m(this,hu);m(this,Ec);m(this,pu);m(this,mu);m(this,gu);m(this,fu);m(this,Su);m(this,bc);m(this,Ws);p(this,"context");m(this,xa,void 0);m(this,rt,void 0);m(this,it,void 0);m(this,Sc,void 0);m(this,vc,void 0);m(this,fn,void 0);m(this,$a,void 0);m(this,Tc,void 0);m(this,Ua,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});m(this,Sn,void 0);m(this,js,"all");this.context=e,g(this,fn,r),g(this,xa,new rN(e)),g(this,$a,new tN(r)),g(this,Tc,Es),a(this,Gs,Pi).mediaState={send:{state:as.NEW},recv:{state:as.NEW}},po(this.context,"forceRelay")&&g(this,js,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,js)}`),I(this,yc,Xp).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,fn)}get socketHandler(){return a(this,$a)}get sendTransport(){return a(this,rt)}get recvTransport(){return a(this,it)}get events(){return a(this,Tc)}set sendTransportConnectedCallback(e){g(this,Sc,e)}set recvTransportConnectedCallback(e){g(this,vc,e)}async setupTransports(e){await I(this,hu,lT).call(this,e);let r,i;e.send&&(r=I(this,Ec,Zp).call(this,a(this,rt)).then(n=>{try{a(this,Sc).call(this,n)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=I(this,Ec,Zp).call(this,a(this,it)).then(n=>{try{a(this,vc).call(this,n)}catch(o){this.logger.error("Failed to run recv transport callback")}})),await Promise.all([r,i])}stopTransports(e){var r,i;if(e.send&&this.sendTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,rt);this.logger.info("Closing send transport",{transport:{id:n,serverId:o,type:c}}),a(this,rt).close(),a(this,rt).removeAllListeners(),g(this,rt,void 0)}if(e.send&&(a(this,Gs,Pi).mediaState.send.state!==as.CLOSED||a(this,Gs,Pi).mediaState.send.sfuSessionId!==void 0)&&I(this,Ws,_i).call(this,{direction:"send",state:as.CLOSED}),e.recv&&this.recvTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,it);this.logger.info("Closing recv transport",{transport:{id:n,serverId:o,type:c}}),(r=a(this,it))==null||r.close(),(i=a(this,it))==null||i.removeAllListeners(),g(this,it,void 0)}e.recv&&(a(this,Gs,Pi).mediaState.recv.state!==as.CLOSED||a(this,Gs,Pi).mediaState.recv.sfuSessionId!==void 0)&&I(this,Ws,_i).call(this,{direction:"recv",state:as.CLOSED}),I(this,yc,Xp).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}xa=new WeakMap,rt=new WeakMap,it=new WeakMap,Sc=new WeakMap,vc=new WeakMap,fn=new WeakMap,$a=new WeakMap,Tc=new WeakMap,Ua=new WeakMap,Sn=new WeakMap,js=new WeakMap,Gs=new WeakSet,Pi=function(){return this.context.getValue("connectionHandler")},yc=new WeakSet,Xp=function(){g(this,Sn,{send:void 0,recv:void 0})},hu=new WeakSet,lT=async function(e){var o,c,d,l,u,h,f,S;po(this.context,"forceRelay")&&g(this,js,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,js)}`);const n=await Ht().getICEServers().catch(E=>(this.logger.warn(`failed to get iceservers from server: ${E.message}`),[]));e.send&&I(this,mu,hT).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(o=this.context.getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(l=(d=(c=this.context.getValue("defaults").mediaConfiguration)==null?void 0:c.audio)==null?void 0:d.enableHighBitrate)!=null?l:!1,enableStereo:(f=(h=(u=this.context.getValue("defaults").mediaConfiguration)==null?void 0:u.audio)==null?void 0:h.enableStereo)!=null?f:!1,enableDtx:!1},iceTransportPolicy:a(this,js)}),e.recv&&I(this,gu,pT).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(S=this.context.getValue("modules").e2ee)==null?void 0:S.enabled},iceTransportPolicy:a(this,js)})},Ec=new WeakSet,Zp=async function(e){const{id:r,serverId:i,direction:n}=e;I(this,fu,mT).call(this,e);try{return await yl(async(c,d)=>{c>0&&this.logger.info(`Retrying ${n} transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:n}});try{if(e.closed)throw new Jr("Cannot reconnect closed transport");await I(this,pu,uT).call(this,e)}catch(l){if(l instanceof Jr){this.logger.error(`Failed to connect ${n} transport. It will not be retried.`,{transport:e,error:l}),d(l);return}throw this.logger.error(`Failed to connect ${n} transport, retrying`,{transport:e,error:l}),l}},{delayTime:100,strategy:"exponential",maxRetryCount:15}),e}catch(o){throw this.logger.error(`Failed to connect ${n} transport after retries: ${e.id}. Transport reconnection will not be retried.`,{error:o,transport:{id:r,serverId:i,type:n}}),e.close(),e.removeAllListeners(),o}},pu=new WeakSet,uT=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!a(this,fn).isConnected)throw new Jr("Socket is not connected");if(e.connectionState==="closed")throw new Jr("Transport is closed");try{await e.connect(n=>I(this,Su,gT).call(this,i,n)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(n){throw a(this,Ua).transportFailureCount[i]+=1,n.message==="ice connection failed"?new Jr(n.message):n}},mu=new WeakSet,hT=function(e){var r,i;if(a(this,rt)&&a(this,rt).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=a(this,rt))==null?void 0:r.id,serverId:(i=a(this,rt))==null?void 0:i.serverId,type:"send"}});return}g(this,rt,a(this,xa).createTransport({...e,direction:"send"})),I(this,Ws,_i).call(this,{state:as.NEW,direction:"send",sfuSessionId:a(this,rt).serverId}),this.context.getValue("callstats").configureSendTransport(a(this,rt))},gu=new WeakSet,pT=function(e){var r,i;if(a(this,it)&&a(this,it).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=a(this,it))==null?void 0:r.id,serverId:(i=a(this,it))==null?void 0:i.serverId,type:"recv"}});return}g(this,it,a(this,xa).createTransport({...e,direction:"recv"})),I(this,Ws,_i).call(this,{state:as.NEW,direction:"recv",sfuSessionId:a(this,it).serverId}),this.context.getValue("callstats").configureRecvTransport(a(this,it))},fu=new WeakSet,mT=function(e){const{direction:r,id:i}=e;e.on("serveridchange",n=>{I(this,Ws,_i).call(this,{state:e.connectionState,direction:r,sfuSessionId:n})}),e.on("connectionstatechange",async n=>{I(this,Ws,_i).call(this,{state:n,direction:r,sfuSessionId:e.serverId}),this.logger.info(`Transport connection state changed to ${n} for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:n}});const o=()=>{const c=a(this,Sn)[r];c!==void 0&&(clearTimeout(c),a(this,Sn)[r]=void 0)};switch(n){case"connected":o(),a(this,Ua).lastConnectionTime=performance.now();break;case"disconnected":a(this,Sn)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await I(this,bc,em).call(this,e.direction)},iN);break;case"failed":if(e.closed)return;o(),this.logger.warn(`${r} transport is in failed state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await I(this,bc,em).call(this,e.direction);break}}),e.on("icecandidate",async n=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:n})})},Su=new WeakSet,gT=async function(e,r){const i=e==="recv";try{const{sdp:n,type:o}=r,c={consuming:i,description:{sdp:n,type:o,target:i?nr.SUBSCRIBER:nr.PUBLISHER},producers:[]};return a(this,$a).connectTransport(c)}catch(n){throw this.logger.error(`Error in ${e} transport connection:`,{error:n}),n}},bc=new WeakSet,em=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),a(this,fn).isConnected&&a(this,Ua).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),g(this,js,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:a(this,rt)}),this.context.getValue("peerSessionStore").emit(P.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,it)}),this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE);break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}const r=e==="send"?a(this,rt):a(this,it);I(this,Ws,_i).call(this,{state:as.CONNECTED,direction:e,sfuSessionId:r.serverId})},Ws=new WeakSet,_i=function(e){const{state:r,direction:i,sfuSessionId:n}=e;a(this,Gs,Pi).mediaState[i]={state:r,sfuSessionId:n},this.context.getValue("peerSessionStore").emit(P.TRANSPORT_STATE_UPDATE,{transport:i,...a(this,Gs,Pi).mediaState[i]})};class aN{constructor(t,e,r,i,n){m(this,vu,void 0);m(this,ms,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=n,g(this,vu,t),g(this,ms,t.getValue("logger"))}async create(t){if(!t||t&&t.length===0)throw new Error("List of producers is required");const e=new Map,r=[];t.forEach(d=>{const{producingPeerId:l,producerId:u,producingTransportId:h}=d,f={simulcast:{preferredRid:"f",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}};e.set(u,l),r.push({producingPeerId:l,producerId:u,producingTransportId:h,...f})});const i=await this.socketHandler.consume({requests:r,consumingTransportId:this.recvTransport.serverId}),n=new Map;t.forEach(d=>n.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const u=n.get(d);if(!u)return;if(l.errorCode){a(this,ms).warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),c.push({...u,errorCode:l.errorCode});return}let h={};try{h=JSON.parse(l.producerState.appData)}catch(f){}o.set(d,{consumerId:l.consumerId,producingTransportId:u.producingTransportId,producingPeerId:u.producingPeerId,kind:u.kind,paused:u.pause,streamId:l.producerTrack.streamId,trackId:l.producerTrack.trackId,screenShare:u.screenShare,mimeType:u.mimeType,appData:h})}),{consumerStates:o,sessionDescription:i.sessionDescription,failedProducers:c}}async negotiate(t){try{a(this,ms).info("Negotiating socket consumer",{transport:this.recvTransport}),a(this,ms).debug(`[SDP] setting remote offer: ${JSON.stringify(t)} on recvTransport`,{transport:this.recvTransport});const e=await this.recvTransport.setRemoteOffer(t),r={transportId:this.recvTransport.serverId,description:{sdp:e.sdp,type:e.type,target:nr.SUBSCRIBER}};return a(this,ms).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,GC.toBinary(r)),a(this,ms).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){a(this,ms).error("Failed to renegotiate",{error:e});return}}async close(t){if(!t.length)return;const e=async(r,i)=>{const n=r.map(l=>l.localId);a(this,ms).info(`Closing consumers: ${JSON.stringify(n)}`);const o={description:{sdp:i.sdp,type:i.type,target:nr.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=SI.fromBinary(c).description;return{sdp:d.sdp,type:d.type}};await this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(t,e),"SocketConsumerStrategy.close",{consumersLength:t.length})}async switchConsumersToLayer(t,e){const r={requests:[],consumingTransportId:this.recvTransport.serverId},i=t.filter(n=>n&&n.id);i.forEach(({id:n,producingTransportId:o,localId:c})=>{r.requests.push({producerId:n,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),await this.socketHandler.updateConsumersSimulcastConfig(r),a(this,ms).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:n})=>n)})}}vu=new WeakMap,ms=new WeakMap;class Pp{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return Bi(t).media.filter(n=>e==="video"?n.type==="video":n.type==="audio").at(-1).msid}async create({offer:t,kind:e,paused:r,appData:i,codecOptions:n,producingTransportId:o}){var h,f;const c=Pp.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:nr.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(h=i.screenShare)!=null?h:!1,mimeType:`${e}/${(f=n[0])==null?void 0:f.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}function oN(s){try{const t=JSON.parse(s.message);if(typeof t!="object"||t===null)return{};const{errorCode:e,errorDescription:r}=t;return{...typeof e=="string"&&{errorCode:e},...typeof r=="string"&&{errorDescription:r}}}catch(t){return{}}}class cN extends nN{constructor(e,r){super(e,r);m(this,Pc);m(this,yu);m(this,Eu);m(this,bu);m(this,wu);m(this,vn,void 0);m(this,Js,void 0);m(this,wc,void 0);m(this,Ks,void 0);m(this,Tu,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});m(this,Cr,[]);m(this,Fa,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{g(this,wc,new Pp(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{g(this,Ks,new aN(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,vn)}get consumers(){return a(this,Js)}get logger(){return this.context.getValue("logger")}reset(){g(this,vn,new Map),g(this,Js,new Map)}async createProducer(e,r){var i,n,o;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const c=await this.sendTransport.produce(e,I(this,yu,fT).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,c),I(this,Eu,ST).call(this,c,r),this.logger.info(`Created ${(n=c.appData)!=null&&n.screenShare?"screenshare":"participant"} ${c.kind} producer ${c.id} for local peer on mid ${c.localId}.`),c}catch(c){throw this.logger.error(`Failed to create ${((o=e==null?void 0:e.track)==null?void 0:o.kind)||"unknown"} producer`,{error:c}),a(this,Tu).producerCreationFailureCount+=1,c}}async closeProducer(e,r){var n,o;const i=this.producers.get(e);if(!i){this.logger.warn(`Producer with ID ${e} was not found`);return}r!=null&&r.stopTrack&&i.track.stop();try{await this.sendTransport.closeProducer(i),this.logger.info(`Closed ${(n=i.appData)!=null&&n.screenShare?"screenshare":"participant"} ${i.kind} producer ${e} of local peer on mid ${i.localId}. `),(o=this.context.getValue("modules").e2ee)!=null&&o.enabled&&this.context.getValue("peerSessionStore").emit(P.E2EE_INACTIVE_PRODUCER,i)}catch(c){this.logger.error("Failed to close producer on server",{error:c,producer:i})}}closeAllProducers(){return Promise.all(Array.from(a(this,vn).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){a(this,Fa)||clearTimeout(a(this,Fa)),g(this,Cr,a(this,Cr).concat(e)),await I(this,Pc,tm).call(this)}removeClosedConsumers(e){return e.filter(r=>{const i=a(this,Js).get(r);return i!=null&&i.closed?(a(this,Js).delete(r),!0):!1})}async closeConsumers(e){if(!a(this,Ks))return;const r=e.map(i=>this.consumers.get(i)).filter(i=>i!==void 0);r.length!==0&&await a(this,Ks).close(r)}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,Js).keys()))}async switchConsumersToLayer(e,r){a(this,Ks).switchConsumersToLayer(e,r)}}vn=new WeakMap,Js=new WeakMap,wc=new WeakMap,Ks=new WeakMap,Tu=new WeakMap,Cr=new WeakMap,Fa=new WeakMap,Pc=new WeakSet,tm=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=a(this,Cr).splice(0,a(this,Cr).length);try{const i=new Set(Array.from(this.consumers.values()).map(({producerId:d})=>d)),n=r.filter(({producerId:d})=>!this.producers.get(d)&&!i.has(d));if(n.length===0)return;const{consumers:o,failedProducers:c}=await this.recvTransport.consume(n,I(this,bu,vT).bind(this),a(this,Ks).negotiate.bind(a(this,Ks)));if(o.forEach(I(this,wu,TT).bind(this)),c!=null&&c.length){this.logger.error("Failed to create consumers for producers",{producers:c});const d=c.filter(({errorCode:l,producerId:u})=>l==="not_found_track_error"?(this.logger.error(`Track not found for producer: ${u}. This will not be retried.`),!1):l==="backend_error"?(this.logger.error("Unrecoverable error: backend error"),!1):!0);g(this,Cr,a(this,Cr).concat(d)),g(this,Fa,setTimeout(I(this,Pc,tm).bind(this),e))}}catch(i){const n=i instanceof Error?i:new Error(String(i));this.logger.error("failed to consume on transport",{error:n});const{errorCode:o,errorDescription:c}=oN(n);if(o==="internal_error"&&c==="Backend error"||o==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:o,message:c}});try{this.stopTransports({recv:!0})}catch(d){}await this.setupTransports({recv:!0})}}},yu=new WeakSet,fT=function(e){return a(this,wc).create(e)},Eu=new WeakSet,ST=function(e,r){e.on("close",async(i,n)=>{const{reason:o}=i,{offer:c}=i;if(this.logger.info("producer::closing",{debuggingHint:o,producer:{...e,status:"closing"}}),o!==_l){const d={producerId:e.id,description:{sdp:c.sdp,type:c.type,target:nr.PUBLISHER}};try{const l=await this.socketHandler.closeProducer(d),u={sdp:l==null?void 0:l.sdp,type:l==null?void 0:l.type};this.logger.info("producer::closed",{producer:{...e,status:"closed"}}),n({answer:u})}catch(l){this.logger.error("producer close error",l)}}this.producers.delete(e.id),r()}),e.on("trackended",()=>{this.logger.info("producer::trackended",{producer:{...e,status:"UNKNOWN"}})}),a(this,vn).set(e.id,e)},bu=new WeakSet,vT=async function(e){try{return await this.recvTransport.canConsume(),await a(this,Ks).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},wu=new WeakSet,TT=function(e){e.on("close",async r=>{this.logger.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),a(this,Js).delete(e.id),this.context.getValue("peerSessionStore").emit(P.CONSUMER_CLOSED,{id:e.id})}),a(this,Js).set(e.id,e),this.context.getValue("peerSessionStore").emit(P.NEW_CONSUMER_CREATED,{id:e.id,appData:e.appData,peerId:e.peerId})};const Ru=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:n=.95,voiceAdaptationRate:o=.99,minEnergyThreshold:c=.005,maxEnergyThreshold:d=.2,energyRatioThreshold:l=1.5,noiseHistorySize:u=50}={}){m(this,Pu);m(this,_u);m(this,_c,void 0);m(this,kc,void 0);m(this,Cc,void 0);m(this,Ba,void 0);m(this,Ha,void 0);m(this,qa,void 0);m(this,Rc,void 0);m(this,Ic,void 0);m(this,ja,void 0);m(this,xt,void 0);m(this,Rs,void 0);m(this,Is,!1);m(this,Tn,0);m(this,yn,0);m(this,Rr,[]);m(this,Ac,void 0);g(this,Ba,t),g(this,xt,t),g(this,_c,e),g(this,kc,r),g(this,Cc,i),g(this,Ha,n),g(this,qa,o),g(this,Rc,c),g(this,Ic,d),g(this,ja,l),g(this,Ac,u),g(this,Rs,t/2)}get voiceDetected(){return a(this,Is)}processAudioChunk(t){var o,c;const e=I(o=Ru,ku,bT).call(o,t),r=I(c=Ru,Cu,wT).call(c,t);return I(this,Pu,yT).call(this,e),e/a(this,Rs)>a(this,ja)&&e>a(this,xt)&&r>a(this,_c)?(g(this,Tn,a(this,Tn)+1),g(this,yn,a(this,Cc)),a(this,Tn)>=a(this,kc)&&g(this,Is,!0)):(g(this,Tn,0),a(this,yn)>0?g(this,yn,a(this,yn)-1):a(this,Is)&&g(this,Is,!1),a(this,Is)||I(this,_u,ET).call(this,e)),{energy:e,isVoice:a(this,Is)}}reset(){g(this,Is,!1),g(this,Tn,0),g(this,yn,0),g(this,xt,a(this,Ba)),g(this,Rs,a(this,Ba)/2),g(this,Rr,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,xt),backgroundNoiseEnergy:a(this,Rs),energyRatioThreshold:a(this,ja)}}};let Ro=Ru;_c=new WeakMap,kc=new WeakMap,Cc=new WeakMap,Ba=new WeakMap,Ha=new WeakMap,qa=new WeakMap,Rc=new WeakMap,Ic=new WeakMap,ja=new WeakMap,xt=new WeakMap,Rs=new WeakMap,Is=new WeakMap,Tn=new WeakMap,yn=new WeakMap,Rr=new WeakMap,Ac=new WeakMap,Pu=new WeakSet,yT=function(t){a(this,Is)?g(this,xt,a(this,qa)*a(this,xt)+(1-a(this,qa))*t):g(this,xt,a(this,Ha)*a(this,xt)+(1-a(this,Ha))*a(this,Rs)),g(this,xt,Math.max(a(this,Rc),Math.min(a(this,Ic),a(this,xt))))},_u=new WeakSet,ET=function(t){if(t<a(this,xt)*1.2)if(a(this,Rr).push(t),a(this,Rr).length>a(this,Ac)&&a(this,Rr).shift(),a(this,Rr).length>=10){const e=[...a(this,Rr)].sort((i,n)=>i-n),r=Math.floor(e.length/2);g(this,Rs,e[r])}else g(this,Rs,.95*a(this,Rs)+.05*t)},ku=new WeakSet,bT=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Cu=new WeakSet,wT=function(t){let e=0;for(let r=1;r<t.length;r+=1)(t[r]>=0&&t[r-1]<0||t[r]<0&&t[r-1]>=0)&&(e+=1);return e},m(Ro,ku),m(Ro,Cu);class XS{constructor(t){p(this,"RNAudioSampleHandler");m(this,Mc,void 0);g(this,Mc,t);const{RNAudioSampleHandlerImpl:e}=navigator;e==null||e.init().then(r=>{this.RNAudioSampleHandler=r}).catch(r=>{this.logger.error("ReactNativeAudioSampler: Failed to initialize audio sampler",r)})}get logger(){return a(this,Mc).getValue("logger")}get samples(){var e;const t=new Float32Array(1024);return(e=this.RNAudioSampleHandler)==null||e.getFloatTimeDomainData(t),t}stop(){var t;(t=this.RNAudioSampleHandler)==null||t.destructor()}}Mc=new WeakMap;class ZS{constructor(t){p(this,"audioContext");p(this,"analyser");m(this,Oc,void 0);g(this,Oc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return a(this,Oc).getValue("logger")}get samples(){if(this.audioContext.state==="suspended")try{this.audioContext.resume()}catch(e){this.logger.error("AudioContextSampler: Failed to resume audio context",e)}const t=new Float32Array(this.analyser.frequencyBinCount);return this.analyser.getFloatTimeDomainData(t),t}set audioTrack(t){const e=new MediaStream;e.addTrack(t),this.audioContext.createMediaStreamSource(e).connect(this.analyser)}}Oc=new WeakMap;class ev{static setInterval(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setInterval(t,e,...r):global.setInterval(t,e,...r)}static clearInterval(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearInterval(t):global.clearInterval(t)}static setTimeout(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setTimeout(t,e,...r):global.setTimeout(t,e,...r)}static clearTimeout(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearTimeout(t):global.clearTimeout(t)}}const dN=60,lN=400,xc=class{constructor(t,e){m(this,Nc);m(this,Iu);m(this,Vc);m(this,Ir,void 0);m(this,Ar,void 0);m(this,Mr,void 0);m(this,Dc,void 0);m(this,Ga,void 0);m(this,Wa,void 0);m(this,gi,void 0);m(this,En,void 0);m(this,Ja,void 0);m(this,bn,void 0);m(this,Or,void 0);m(this,zs,void 0);this.reportRequest=e,g(this,bn,t),g(this,Wa,new Ro);const{isReactNative:r}=navigator;g(this,Or,r?new XS(a(this,bn)):new ZS(a(this,bn))),g(this,zs,r?ev:cp)}get logger(){return a(this,bn).getValue("logger")}set producerId(t){g(this,Mr,t)}set audioTrack(t){g(this,Dc,t),a(this,Or)instanceof ZS&&(a(this,Or).audioTrack=t)}start(t=!1){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter of audio producer ${a(this,Mr)}.`),a(this,Ir)&&a(this,zs).clearInterval(a(this,Ir)),g(this,Ir,a(this,zs).setInterval(I(this,Nc,sm).bind(this),dN)),a(this,Ar)&&a(this,zs).clearInterval(a(this,Ar)),g(this,Ar,a(this,zs).setInterval(I(this,Vc,im).bind(this),lN)),t&&(I(this,Nc,sm).call(this),I(this,Vc,im).call(this))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter of audio producer ${a(this,Mr)}`),a(this,Ir)&&(a(this,zs).clearInterval(a(this,Ir)),g(this,Ir,void 0)),a(this,Ar)&&(a(this,zs).clearInterval(a(this,Ar)),g(this,Ar,void 0))}catch(t){}a(this,Wa).reset(),a(this,Or)instanceof XS&&a(this,Or).stop()}};let Io=xc;Ir=new WeakMap,Ar=new WeakMap,Mr=new WeakMap,Dc=new WeakMap,Ga=new WeakMap,Wa=new WeakMap,gi=new WeakMap,En=new WeakMap,Ja=new WeakMap,bn=new WeakMap,Or=new WeakMap,zs=new WeakMap,Nc=new WeakSet,sm=function(){var i;if(!a(this,Dc)||!a(this,Mr))return;const{energy:t}=I(this,Iu,PT).call(this),e=I(i=xc,Lc,rm).call(i,t);let r=.9;a(this,Ja)!==e&&a(this,Ja)?r=.9:e?r=.3:r=.5,g(this,Ga,(a(this,Ga)||0)*(1-r)+t*r)},Iu=new WeakSet,PT=function(){var o;const{samples:t}=a(this,Or),{energy:e,isVoice:r}=a(this,Wa).processAudioChunk(t),i=I(o=xc,Au,_T).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,gi)||i<a(this,gi))&&g(this,gi,i),(!a(this,En)||i>a(this,En))&&g(this,En,i),{energy:(i-a(this,gi))/(a(this,En)-a(this,gi))*10||0,isVoice:r})},Lc=new WeakSet,rm=function(t){return t<5},Vc=new WeakSet,im=function(t=a(this,Ga)){var r;if(!a(this,Mr)||!t)return;const e={producerId:a(this,Mr),energy:Math.round(t),silent:I(r=xc,Lc,rm).call(r,t)};g(this,Ja,e.silent),this.reportRequest(e)},Au=new WeakSet,_T=function(t){const e=Math.log10(t);return Math.round(e)},m(Io,Lc),m(Io,Au);var uN=Object.defineProperty,hN=Object.getOwnPropertyDescriptor,he=(s,t,e,r)=>{for(var i=r>1?void 0:r?hN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&uN(t,e,i),i};class de{constructor(t,e){m(this,Lr);m(this,Bc);m(this,Ou);m(this,Du);m(this,Nu);m(this,Hc);m(this,Lu);m(this,Vu);m(this,lt);m(this,_n);m(this,xu);m(this,$u);m(this,Uu);m(this,Fu);p(this,"context");p(this,"authToken");p(this,"e2ee");m(this,$c,void 0);m(this,Uc,void 0);m(this,nt,void 0);m(this,j,void 0);m(this,Mu,void 0);m(this,kt,void 0);m(this,Dr,void 0);m(this,wn,void 0);m(this,Pn,void 0);m(this,Fc,void 0);m(this,Qt,null);m(this,Nr,void 0);m(this,Ct,void 0);m(this,Rt,void 0);var i,n;this.context=t;const{socket:r}=e;this.mediaJoined=!1,g(this,nt,r),g(this,Dr,!1),g(this,j,new cN(t,r)),g(this,kt,a(this,j).events),g(this,Nr,new Set),g(this,Ct,new Map),g(this,wn,!1),g(this,Pn,new vp(t.getValue("logger"))),g(this,Rt,new Io(this.context,a(this,j).socketHandler.audioActivity.bind(a(this,j).socketHandler))),this.e2ee=(n=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),g(this,Fc,wh(async()=>{if(!a(this,Lr,Nn).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(a(this,Uc),a(this,$c),!0);o&&(this.context.getValue("peerSessionStore").emit(P.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return a(this,Lr,Nn).mediaJoined}set mediaJoined(t){a(this,Lr,Nn).mediaJoined=t}reset({resetTransportQueue:t}){this.logger.info(`Resetting media node client: closing all transports, producers, consumers, and queues(resetTransportQueue: ${t}).`),a(this,j).closeAllProducers(),a(this,j).closeAllConsumers(),a(this,Ct).clear(),a(this,Nr).clear(),g(this,Qt,null),t&&a(this,Pn).stop(),a(this,j).stopAllTransports(),a(this,j).reset(),t&&g(this,Pn,new vp)}async joinRoom(t,e,r=!1,i={}){a(this,Lr,Nn).mediaJoinAttempted=!0,g(this,Dr,!0);const n=this.peerId;try{const o=await a(this,Pn).push(()=>I(this,Ou,kT).call(this,t,e,r,i),"joinRoom");return o.roomJoined||I(this,Bc,nm).call(this,n),o}catch(o){return this.logger.error("Error in room joining process",{error:o}),I(this,Bc,nm).call(this,n),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_FAILED),{roomJoined:!1,error:o}}}async initializeConnection(t,e,r=!1,i={}){return a(this,Qt)?a(this,Qt):(g(this,Qt,(async()=>{try{await I(this,Hc,am).call(this,t,e,r,i)}catch(n){throw g(this,Qt,null),n}})()),a(this,Qt))}getConsumers(){return a(this,j).consumers}getProducers(){return a(this,j).producers}handoverPeerProducers(t,e){const r=new Set(e);return Array.from(a(this,j).consumers.values()).filter(i=>r.has(i.producerId)?(i.reassignPeer(t),!0):!1)}async leaveRoom(){var r;(r=a(this,Rt))==null||r.stop(),a(this,j).stopAllTransports(),g(this,wn,!1),a(this,Lr,Nn).mediaJoinAttempted=!1;const t={closeRoom:!1};try{a(this,nt).sendMessage(a(this,kt).leaveRoom,fR.toBinary(t))||this.logger.warn("MediaNodeClient.leaveRoom: media leave was not sent")}catch(i){this.logger.error("MediaNodeClient.leaveRoom: media leave failed",{error:i})}this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct().catch(i=>{this.logger.error("leaveRoom::telemetry_destruct_failed",{error:i})})}async activatePeers(t){return this.createConsumers(t)}async createConsumers(t){return t.length===0?Promise.resolve():a(this,j).createConsumers(t)}removeClosedConsumers(t){return a(this,j).removeClosedConsumers(t)}async closeConsumersById(t){t.length&&await a(this,j).closeConsumers(t)}async _shareWebcam(t){var u,h,f,S;const e=Re.WEBCAM,r=I(this,lt,Mt).call(this,e);if(r){const E=await r;if(a(this,j).producers.has(E)){const k=a(this,j).producers.get(E);if(!k.closed)return await k.replaceTrack({track:t}),await this.resumeWebcam(e),t;await this.disableWebcam()}return this._shareWebcam(t)}const i=I(this,Fu,NT).call(this,t),n=po(this.context,"disableSimulcast"),o=(h=(u=this.context)==null?void 0:u.getValue("overrides"))==null?void 0:h.simulcastConfig;n||o&&o.disable||!((S=(f=this.context)==null?void 0:f.getValue("theme"))!=null&&S.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),i.encodings=WD(this.context,t),this.logger.info(`Simulcast encodings: ${JSON.stringify(i.encodings)}`));const d=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,Ct).delete(e)},l=a(this,j).createProducer(i,d);return I(this,_n,bd).call(this,e,l.then(E=>E.id)),l.then(E=>E.track)}async shareWebcam(t){return t===void 0?null:(this.logger.debug("Calling _shareWebcam with VP8 codec"),this._shareWebcam(t))}async shareScreen(t){const{video:e,audio:r}=t;if(e===void 0)return;const i=await I(this,lt,Mt).call(this,Re.SCREENSHARE_VIDEO),n=await I(this,lt,Mt).call(this,Re.SCREENSHARE_AUDIO),o=a(this,j).producers.get(i),c=a(this,j).producers.get(n),d=[];if(o&&!o.closed)d.push(o.replaceTrack({track:e}));else{const l={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Pe.isElectron()},stopTracks:!1},u=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Ct).delete(Re.SCREENSHARE_VIDEO),a(this,Ct).delete(Re.SCREENSHARE_AUDIO)},h=a(this,j).createProducer(l,u);I(this,_n,bd).call(this,Re.SCREENSHARE_VIDEO,h.then(f=>f.id)),d.push(h)}if(r)if(c&&!c.closed)d.push(c.replaceTrack({track:r}));else{const l={track:r,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Pe.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},u=()=>{},h=a(this,j).createProducer(l,u);I(this,_n,bd).call(this,Re.SCREENSHARE_AUDIO,h.then(f=>f.id)),d.push(h)}await Promise.all(d),this.context.getValue("callstats").screenShareStart()}async shareMic(t){try{if(t===void 0)throw new Nt("track undefined");const e=I(this,lt,Mt).call(this,Re.MIC);if(e){const o=await e;if(a(this,j).producers.has(o)){const c=a(this,j).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),a(this,Rt)&&(a(this,Rt).audioTrack=t,a(this,Rt).producerId=o,a(this,Rt).start(!0));return}await a(this,j).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=I(this,Uu,DT).call(this,t),i=()=>{a(this,Ct).delete(Re.MIC)},n=a(this,j).createProducer(r,i);I(this,_n,bd).call(this,Re.MIC,n.then(o=>o.id)),await n.then(o=>{a(this,Rt)&&(a(this,Rt).audioTrack=o.track,a(this,Rt).producerId=o.id,a(this,Rt).start())})}catch(e){throw new C(e)}}async pauseMic(){var i;const t=await I(this,lt,Mt).call(this,Re.MIC),e=a(this,j).producers.get(t);if(!e){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(e.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}e.pause(),(i=a(this,Rt))==null||i.stop();const r={producerId:e.id,pause:!0};a(this,nt).sendMessage(a(this,kt).toggleProducer,il.toBinary(r)),this.logger.info(`Paused mic producer ${e.id} of local peer ${this.peerId}. Remote peers will stop hearing this peer.`)}async pauseWebcam(){const t=await I(this,lt,Mt).call(this,Re.WEBCAM),e=a(this,j).producers.get(t);if(!e){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}e.pause();const r={producerId:e.id,pause:!0};a(this,nt).sendMessage(a(this,kt).toggleProducer,il.toBinary(r)),this.logger.info(`Paused webcam producer ${e.id} of local peer ${this.peerId}. Remote peers will stop seeing this peer.`)}async resumeMic(){const t=await I(this,lt,Mt).call(this,Re.MIC),e=a(this,j).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,nt).sendMessage(a(this,kt).toggleProducer,il.toBinary(r)),this.logger.info(`Resumed mic producer ${e.id} of local peer ${this.peerId}. Remote peers will start hearing this peer.`)}async resumeWebcam(t=Re.WEBCAM){const e=await I(this,lt,Mt).call(this,t),r=a(this,j).producers.get(e);if(!r){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!r.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}r.resume(),r.appData.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};a(this,nt).sendMessage(a(this,kt).toggleProducer,il.toBinary(i)),this.logger.info(`Resumed webcam producer ${r.id} of local peer ${this.peerId}. Remote peers will start seeing this peer.`)}async disableWebcam(){const t=Re.WEBCAM,e=await I(this,lt,Mt).call(this,t);I(this,xu,MT).call(this,t),e&&await a(this,j).closeProducer(e)}async disableMic(){var e;const t=await I(this,lt,Mt).call(this,Re.MIC);t&&await a(this,j).closeProducer(t),(e=a(this,Rt))==null||e.stop(),a(this,Ct).delete(Re.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await I(this,lt,Mt).call(this,Re.SCREENSHARE_VIDEO),e=await I(this,lt,Mt).call(this,Re.SCREENSHARE_AUDIO);t&&await a(this,j).closeProducer(t),e&&await a(this,j).closeProducer(e),a(this,Nr).clear(),a(this,Ct).delete(Re.SCREENSHARE_VIDEO),a(this,Ct).delete(Re.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await I(this,lt,Mt).call(this,Re.WEBCAM);await a(this,j).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await I(this,lt,Mt).call(this,Re.SCREENSHARE_VIDEO);await a(this,j).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:e})}}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await a(this,j).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};a(this,j).socketHandler.kickPeer(e)}kickAll(){a(this,j).socketHandler.kickAll()}async muteAll(t){if(!await a(this,j).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,j).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await a(this,j).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await a(this,j).socketHandler.hostControlForPeer(t,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(t){const e={participantId:t!=null?t:""};try{await a(this,nt).sendMessagePromise(a(this,kt).globalPinPeer,AR.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&a(this,j).producers.get(t.producerId)&&a(this,Nr).add(t.consumerPeerId),a(this,Nr).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));a(this,j).switchConsumersToLayer(r,e)}async handleSocketEvents(){a(this,nt).on(a(this,kt).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{I(this,$u,OT).call(this,DI.fromBinary(t))}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),a(this,nt).on(a(this,kt).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const e=Yf.fromBinary(t),{participantId:r,initiatorParticipantId:i,producerState:{kind:n,pause:o,producerId:c,screenShare:d}}=e;if(d)return;const l=n===Ns.AUDIO?"audio":"video";if(this.logger.info(`Received participant ${l} producer ${o?"paused":"resumed"} broadcast for ${r===this.peerId?"local":"remote"} producer ${c} of peer ${r}. payload: ${Yf.toJsonString(e)}`),r===this.peerId&&i!==this.peerId&&o&&(this.logger.info(`${i?`Remote peer ${i}`:"Kick/Kick-all api"} has paused the ${l==="audio"?"audio":"video"} feed of local peer ${this.peerId}. Reconciling the local state.`),this.context.getValue("peerSessionStore").emit(l==="audio"?P.MUTE_SELF:P.MUTE_SELF_VIDEO)),r===this.peerId)return;this.context.getValue("peerSessionStore").emit(P.PRODUCER_TOGGLE,{peerId:r,producerId:c,paused:o,kind:l}),Array.from(this.getConsumers().values()).filter(h=>h.producerId===c).forEach(h=>{h.kind==="video"&&o||h.paused!==o&&(this.logger.debug(`consumer state mismatched for ${h.id}. updating consumer pause state ${h.paused} to ${o}`),o?(h.pause(),this.context.getValue("peerSessionStore").emit(P.CONSUMER_PAUSED,{id:h.id})):(h.resume(),this.context.getValue("peerSessionStore").emit(P.CONSUMER_RESUMED,{id:h.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,nt).on(a(this,kt).peerLeaveBroadcast,async({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=$h.fromBinary(t);if(e===this.peerId)return;this.logger.info(`Received peer left broadcast of remote peer ${e}`),a(this,Nr).delete(e),this.context.getValue("peerSessionStore").emit(P.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast of remote peer",{error:e})}}),a(this,nt).on(a(this,kt).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=VI.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(P.PRODUCER_CLOSED,{peerId:e,producerId:r})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,nt).on(a(this,kt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,Dr)&&!a(this,wn)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_DISCONNECTED),a(this,Fc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=a(this,j).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(P.CONSUMER_SCORE_UPDATE,{id:r,kind:i.kind,peerId:i.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,r)=>{const i=Array.from(a(this,j).producers.values()).find(n=>n.id===r);i&&this.context.getValue("peerSessionStore").emit(P.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}}$c=new WeakMap,Uc=new WeakMap,nt=new WeakMap,j=new WeakMap,Mu=new WeakMap,kt=new WeakMap,Dr=new WeakMap,wn=new WeakMap,Pn=new WeakMap,Fc=new WeakMap,Qt=new WeakMap,Nr=new WeakMap,Ct=new WeakMap,Rt=new WeakMap,Lr=new WeakSet,Nn=function(){return this.context.getValue("connectionHandler")},Bc=new WeakSet,nm=function(t){this.mediaJoined=!1,g(this,Dr,!1),a(this,nt).isConnected&&this.peerId===t&&this.context.getValue("peerSessionStore").emit(P.MEDIA_ROOM_JOIN_FAILED)},Ou=new WeakSet,kT=async function(t,e,r,i){var o;g(this,Uc,t);let n=!1;if(r){const{recv:c,send:d}=(o=a(this,Lr,Nn).mediaState)!=null?o:{};(d==null?void 0:d.state)===as.CONNECTED&&(c==null?void 0:c.state)===as.CONNECTED?(this.logger.info("MediaNodeClient.joinRoom: transports healthy — preserving all producers for ownership handover"),g(this,Qt,null),n=!0):(this.logger.info("MediaNodeClient.joinRoom: transports unhealthy — full reset"),this.reset({resetTransportQueue:!1}))}try{a(this,Qt)?await a(this,Qt):await I(this,Hc,am).call(this,t,e,r,i,n),I(this,Nu,RT).call(this,e);const{joined:c,error:d}=await I(this,Du,CT).call(this);return{roomJoined:c,error:d}}catch(c){return this.logger.error("Failed to complete room join",{error:c}),{roomJoined:!1,error:c}}finally{g(this,Qt,null)}},Du=new WeakSet,CT=async function(){const t=this.peerId;try{this.mediaJoined=!0;const{roomState:e}=await yl(async(r,i)=>{if(!a(this,nt).isConnected||this.peerId!==t){const n=new Error("Media room join completion superseded by a newer connection");throw i(n),n}return r>0&&this.logger.warn(`Retrying media room join completion for peer ${t}: attempt=${r+1}`),a(this,j).socketHandler.notifySelfJoinComplete()},{strategy:"exponential",maxRetryCount:3,delayTime:1e3});return g(this,$c,e.roomUuid),g(this,wn,!0),g(this,Dr,!1),{joined:!0}}catch(e){return this.logger.error("Error completing room join",{error:e}),this.mediaJoined=!1,g(this,Dr,!1),{joined:!1,error:e}}},Nu=new WeakSet,RT=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...Pe.getDeviceInfo(),userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency},sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};this.context.getValue("callstats").roomJoined(r)}catch(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},Hc=new WeakSet,am=async function(t,e,r,i,n=!1){try{const o=I(this,Lu,IT).call(this);await I(this,Vu,AT).call(this,t,e,r,o),n?this.logger.info("MediaNodeClient: reusing existing transports on rejoin"):await a(this,j).setupTransports({send:!0,recv:!0})}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},Lu=new WeakSet,IT=function(){const t=q1("video/VP8");return g(this,Mu,t),t},Vu=new WeakSet,AT=async function(t,e,r,i){await yl(async(n,o)=>{if(!a(this,nt).isConnected){o(new Error("Socket is not connected"));return}n>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${n}`});try{await a(this,j).socketHandler.joinRoom(e,t,i,r)}catch(c){throw this.logger.error("Failed to send joinRoom message after retries",{error:c}),c}},{delayTime:1e3,strategy:"exponential",maxRetryCount:15})},lt=new WeakSet,Mt=function(t){return a(this,Ct).get(t)},_n=new WeakSet,bd=function(t,e){return a(this,Ct).set(t,e)},xu=new WeakSet,MT=function(t){return a(this,Ct).delete(t)},$u=new WeakSet,OT=function({participantId:t,producerState:e}){var i;if(t===this.peerId||!e)return;this.logger.info(`Received remote ${e.screenShare?"screenshare":"participant"} ${e.kind===Ns.AUDIO?"audio":"video"} producer created broadcast for peer ${t} with producer state ${JSON.stringify(e)}.`);const r=(i=e.mimeType)!=null?i:e.kind===Ns.AUDIO?"audio/opus":"video/VP8";this.context.getValue("peerSessionStore").emit(P.NEW_PRODUCER,{peerId:t,producer:{...e,mimeType:r,kind:e.kind===Ns.AUDIO?"audio":"video",producingPeerId:t}})},Uu=new WeakSet,DT=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},Fu=new WeakSet,NT=function(t){return{track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},he([y.trace("MediaNodeClient.reset")],de.prototype,"reset",1),he([y.trace("MediaNodeClient.joinRoom")],de.prototype,"joinRoom",1),he([y.trace("MediaNodeClient.leaveRoom")],de.prototype,"leaveRoom",1),he([y.trace("MediaNodeClient.activatePeers")],de.prototype,"activatePeers",1),he([y.trace("MediaNodeClient.createConsumers")],de.prototype,"createConsumers",1),he([y.trace("MediaNodeClient.closeConsumersById")],de.prototype,"closeConsumersById",1),he([y.trace("MediaNodeClient._shareWebcam")],de.prototype,"_shareWebcam",1),he([y.trace("MediaNodeClient.shareWebcam")],de.prototype,"shareWebcam",1),he([y.trace("MediaNodeClient.shareScreen")],de.prototype,"shareScreen",1),he([y.trace("MediaNodeClient.shareMic")],de.prototype,"shareMic",1),he([y.trace("MediaNodeClient.pauseMic")],de.prototype,"pauseMic",1),he([y.trace("MediaNodeClient.pauseWebcam")],de.prototype,"pauseWebcam",1),he([y.trace("MediaNodeClient.resumeMic")],de.prototype,"resumeMic",1),he([y.trace("MediaNodeClient.resumeWebcam")],de.prototype,"resumeWebcam",1),he([y.trace("MediaNodeClient.disableWebcam")],de.prototype,"disableWebcam",1),he([y.trace("MediaNodeClient.disableMic")],de.prototype,"disableMic",1),he([y.trace("MediaNodeClient.disableScreenShare")],de.prototype,"disableScreenShare",1),he([y.trace("MediaNodeClient.muteSelf")],de.prototype,"muteSelf",1),he([y.trace("MediaNodeClient.resetVideoProducers")],de.prototype,"resetVideoProducers",1),he([y.trace("MediaNodeClient.changeDisplayName")],de.prototype,"changeDisplayName",1),he([y.trace("MediaNodeClient.kickPeer")],de.prototype,"kick",1),he([y.trace("MediaNodeClient.kickAllPeers")],de.prototype,"kickAll",1),he([y.trace("MediaNodeClient.muteAll")],de.prototype,"muteAll",1),he([y.trace("MediaNodeClient.muteAllVideo")],de.prototype,"muteAllVideo",1),he([y.trace("MediaNodeClient.disableAudio")],de.prototype,"disableAudio",1),he([y.trace("MediaNodeClient.disableVideo")],de.prototype,"disableVideo",1),he([y.trace("MediaNodeClient.pinPeer")],de.prototype,"pinPeer",1),he([y.trace("MediaNodeClient.validateScreenShare")],de.prototype,"validateScreenShare",1);function tv(s,t){const e=s.getValue("roomNodeClient");if(e){if(e)return e;throw new Error("Room node client already set up.")}const r=new de(s,t);return s.setValue("roomNodeClient",r),r}function pN(s){const t=s.getValue("roomNodeClient");try{t==null||t.leaveRoom()}catch(e){s.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}s.setValue("roomNodeClient",void 0)}var mN=Object.defineProperty,gN=Object.getOwnPropertyDescriptor,Hi=(s,t,e,r)=>{for(var i=r>1?void 0:r?gN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&mN(t,e,i),i};const sv=(Wv=class{constructor(s,t,e,r){m(this,ft);p(this,"self");p(this,"authToken");m(this,Ka,void 0);p(this,"viewType");m(this,gs,void 0);m(this,ee,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,g(this,ee,s),this.viewType=r,this.authToken=n,g(this,Ka,i),g(this,gs,e),this.setupEvents()}get peerId(){return a(this,ee).getValue("peerId")}get telemetry(){return a(this,ee).getValue("telemetry")}get logger(){return a(this,ee).getValue("logger")}get mediaJoined(){return a(this,ee).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=Ht(),o=!!s.getValue("cachedUserDetails"),c=await ze.__init__(s,e,r,i,i.name,o);s.setValue("self",c);const d=s.getValue("logger");return navigator.product!=="ReactNative"?setTimeout(async()=>{const u=await c.getAllDevices();d.info("populated_full_device_list",{devices:JSON.stringify(u)}),s.getValue("callstats").devices("AUDIO",u==null?void 0:u.filter(h=>h.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",u==null?void 0:u.filter(h=>h.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",u==null?void 0:u.filter(h=>h.kind==="audiooutput")),d.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:s.getValue("peerId"),engineName:Pe.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:d,apiHostnames:Lk(s),skipConnectivityChecks:!0,authToken:s.getValue("authToken")}),t.socket.updateCallstatsPeerId(s.getValue("peerId")),d.info("Callstats:: initialized")}catch(h){d.error("Callstats:: initialization failed",{error:h})}},0):d.info("Callstats:: Skipped initialization due to navigator product being ReactNative."),new sv(s,c,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:n,screenShareTracks:o}=this.self;if(e.canProduceAudio===G.Allowed&&r)if((s==null?void 0:s.readyState)==="live")try{await a(this,ft,Ut).shareMic(s),this.self.audioEnabled||a(this,ft,Ut).pauseMic()}catch(d){this.self.disableAudio()}else this.logger.warn("shareMediaTracks: audio track is dead, disabling audio"),this.self.disableAudio();if(e.canProduceVideo===G.Allowed&&i)if((t==null?void 0:t.readyState)==="live")try{await a(this,ft,Ut).shareWebcam(t),this.self.videoEnabled||a(this,ft,Ut).pauseWebcam()}catch(d){this.self.disableVideo()}else this.logger.warn("shareMediaTracks: video track is dead, disabling video"),this.self.disableVideo();if(e.canProduceScreenshare===G.Allowed&&n){const d=o.video,l=o.audio;if((d==null?void 0:d.readyState)==="live")try{await((c=a(this,ft,Ut))==null?void 0:c.shareScreen({video:d,audio:(l==null?void 0:l.readyState)==="live"?l:void 0}))}catch(u){this.self.disableScreenShare()}else this.logger.warn("shareMediaTracks: screenshare video track is dead, disabling screenshare"),this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){var r;const{wasSocketJoinAttempted:t,wasMediaJoinAttempted:e}=s;a(this,ee).getValue("callstats").callEnded(),t||e?(this.logger.info(`Resetting Self post reconnect. Peer has earlier tried joining the ${e?"media room":"socket room only"}. Not closing transports.`),await this.joinRoom({reconnected:!0,joinAttempts:s})):(this.logger.info("Resetting Self post reconnect. User never joined the room so doing full reset."),(r=a(this,ft,Ut))==null||r.reset({resetTransportQueue:!0}))}setupEvents(){a(this,ee).getValue("peerSessionStore").on(P.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&await this.shareMediaTracks()}),a(this,ee).getValue("peerSessionStore").on(P.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,ee).getValue("peerSessionStore").on(P.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,ee).getValue("peerSessionStore").on(P.ROOM_NODE_FAILED,()=>{this.logger.error("Room node failed. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,ee).getValue("peerSessionStore").on(P.SOCKET_SERVICE_RECONNECTED,s=>{!s.wasSocketJoinAttempted&&!s.wasMediaJoinAttempted&&(this.self.roomState="init"),this.resetSelf(s).catch(t=>{this.logger.error("Failed to reset self after socket reconnection",{error:t})})}),a(this,ee).getValue("peerSessionStore").on(P.SOCKET_SERVICE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,ee).getValue("peerSessionStore").on(P.SOCKET_SERVICE_FAILED,()=>{this.logger.error("Socket reconnection failed after exhausting all attempts. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,gs).on($.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,gs).on(ll.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,ee).getValue("peerSessionStore").emit(P.UPDATE_PERMISSIONS,t.patch)})}),a(this,gs).on($.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,gs).on($.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,gs).on($.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,ee).getValue("peerSessionStore").onAsync(P.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,ee).getValue("peerSessionStore").on(P.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var n;const i=(n=e==null?void 0:e.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),a(this,ee).getValue("peerSessionStore").on(P.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,ee).getValue("callstats").audioOff())}),a(this,ee).getValue("peerSessionStore").on(P.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,ee).getValue("callstats").videoOff())}),a(this,ee).getValue("peerSessionStore").onAsync(P.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,ee).getValue("peerSessionStore").on(P.PIP_HANGUP,this.leaveRoom.bind(this))}async joinSocketRoomWithRetry(){const s=this.self.id;return yl(async(t,e)=>{if(!a(this,Ka).isConnected||this.self.id!==s){const i=new Error("Socket room join superseded by a newer connection");throw e(i),i}t>0&&this.logger.warn(`Retrying socket room join for peer ${s}: attempt=${t+1}`);const r=await a(this,gs).joinRoom(this.self);if(this.self.id!==s){const i=new Error("Socket room join completed for a superseded peer ID");throw e(i),i}return r},{strategy:"exponential",maxRetryCount:3,delayTime:1e3})}async joinRoom({reconnected:s=!1,joinAttempts:t}={}){var e,r;try{this.logger.info("Local peer is joining socket room.");const{peer:i}=await this.joinSocketRoomWithRetry();this.logger.info("Local peer has joined socket room."),a(this,gs).socket.flush();const n=rp(i.stageType);if(a(this,ee).setValue("stageStatus",n,!1),i.waitlisted){this.logger.info("Peer was waitlisted. Skipped joining media room."),s&&(this.logger.info("Peer reconnected while waitlisted. Resetting media node client."),(e=a(this,ft,Ut))==null||e.reset({resetTransportQueue:!0})),this.waitlistedHandler();return}}catch(i){throw this.logger.error("SelfController.joinRoom: socket join failed",{error:i}),new C("Check the network and try again.","0002")}if(this.viewType===vs.Livestream&&(t!=null&&t.wasSocketJoinAttempted)&&!t.wasMediaJoinAttempted&&a(this,ee).getValue("stageStatus")!=="ON_STAGE"){this.logger.info("Local livestream peer that only joined the socket room is not ON_STAGE. Closing transports, if any."),(r=a(this,ft,Ut))==null||r.reset({resetTransportQueue:!0}),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s}),a(this,ee).notify("stageStatus");return}try{this.logger.info("Local peer is joining media room."),await this.joinMediaRoom(s),this.logger.info("Local peer has joined media room."),a(this,ee).notify("stageStatus")}catch(i){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:i}),i instanceof Jr&&i.message==="ice connection failed"?new C("A firewall or network restriction may be blocking the connection.","0014"):new C("Check the network and try again.","0014")}}async leaveRoom(s="left"){var e;if(this.logger.info(`Leaving room with state: ${s}`),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}if(this.self.setIsPinned(!1),a(this,ee).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,ee).setValue("roomNodeClient",void 0),a(this,ee).notify("stageStatus"),a(this,ee).getValue("connectionHandler").socketJoined)try{a(this,gs).leaveRoom(this.self)||this.logger.warn("SelfController.leaveRoom: socket leave was not sent")}catch(r){this.logger.error("SelfController.leaveRoom: socket leave failed",{error:r})}(e=a(this,ee).getValue("roomSocketHandler"))==null||e.cleanup(),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var n,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,ee).getAllValues();try{if(e===vs.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}tv(a(this,ee),{socket:a(this,Ka),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:h}=(o=await((n=a(this,ft,Ut))==null?void 0:n.joinRoom(this.self.name,r,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)throw h!=null?h:new Error("Could not connect to media server");this.logger.info(i==="ON_STAGE"?"Peer is on stage. Sharing media tracks":"Peer is not on stage. Not sharing media tracks"),i==="ON_STAGE"&&await this.shareMediaTracks(),this.logger.info(i==="ON_STAGE"?"Peer is on stage. Shared media tracks":"Peer is not on stage. Did not share media tracks"),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("SelfController.mediaRoomJoin",{error:c}),c}}async leaveMediaRoom(s){const t=a(this,ee).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===vs.Webinar)&&a(this,ft,Ut)&&(a(this,ft,Ut).mediaJoined&&s!=="disconnected"&&await a(this,ft,Ut).leaveRoom(),!(s==="stageLeft"&&t===vs.Livestream)&&(a(this,ft,Ut).mediaJoined=!1))}async cleanupSelf(){await this.self.disableAudio(),await this.self.disableVideo(),await this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()}},Ka=new WeakMap,gs=new WeakMap,ee=new WeakMap,ft=new WeakSet,Ut=function(){return a(this,ee).getValue("roomNodeClient")},Wv);let Kr=sv;Hi([y.trace("SelfController.resetSelf")],Kr.prototype,"resetSelf",1),Hi([y.trace("SelfController.setupEvents")],Kr.prototype,"setupEvents",1),Hi([y.trace("SelfController.joinRoom")],Kr.prototype,"joinRoom",1),Hi([y.trace("SelfController.leaveRoom")],Kr.prototype,"leaveRoom",1),Hi([y.trace("SelfController.joinMediaRoom")],Kr.prototype,"joinMediaRoom",1),Hi([y.trace("SelfController.leaveMediaRoom")],Kr.prototype,"leaveMediaRoom",1),Hi([y.trace("SelfController.init")],Kr,"init",1);class fN{constructor(t){m(this,qc,void 0);g(this,qc,t)}on(t,e){let r;t===$.roomPeerCount?r=Zf.fromBinary.bind(Zf):r=pS.fromBinary.bind(pS),a(this,qc).on(t,({payload:i})=>{if(t===$.roomPeerCount&&!i)return;const n=r(i);e(n)})}}qc=new WeakMap;class SN{constructor(t,e){m(this,jc,void 0);m(this,Gc,void 0);g(this,jc,e),g(this,Gc,t)}get logger(){return a(this,Gc).getValue("logger")}on(t,e){let r,i;switch(t){case $.transcript:{r=Uh.fromBinary.bind(Uh),i=Uh.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,jc).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}jc=new WeakMap,Gc=new WeakMap;var vN=Object.defineProperty,TN=Object.getOwnPropertyDescriptor,_p=(s,t,e,r)=>{for(var i=r>1?void 0:r?TN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&vN(t,e,i),i};class Cl{constructor(t,e){m(this,Vr,void 0);m(this,za,void 0);g(this,Vr,e),g(this,za,t)}get logger(){return a(this,za).getValue("logger")}get telemetry(){return a(this,za).getValue("telemetry")}getPolls(){return a(this,Vr).sendMessagePromise(cr.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Vr).sendMessage(cr.createPoll,pO.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Vr).sendMessage(cr.votePoll,gO.toBinary(r))}on(t,e){let r,i;switch(t){case cr.updatePoll:case cr.createPoll:case cr.votePoll:{r=Qh.fromBinary.bind(Qh),i=Qh.create();break}}a(this,Vr).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){a(this,Vr).removeListeners(t)}}Vr=new WeakMap,za=new WeakMap,_p([y.trace("PollSocketHandler.getPolls")],Cl.prototype,"getPolls",1),_p([y.trace("PollSocketHandler.createPoll")],Cl.prototype,"createPoll",1),_p([y.trace("PollSocketHandler.votePoll")],Cl.prototype,"votePoll",1);var yN=Object.defineProperty,EN=Object.getOwnPropertyDescriptor,bN=(s,t,e,r)=>{for(var i=r>1?void 0:r?EN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&yN(t,e,i),i};class rv{constructor(t,e){p(this,"socket");m(this,Xt,void 0);g(this,Xt,t),this.socket=e,this.handleSocketEvents(),a(this,Xt).setValue("roomSocketHandler",this)}get telemetry(){return a(this,Xt).getValue("telemetry")}get logger(){return a(this,Xt).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}async joinRoom(t){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise($.joinRoom,p0.toBinary(e));try{const{peer:n}=Bn.fromBinary((await r).payload);a(this,Xt).getValue("connectionHandler").socketJoined=!0,a(this,Xt).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_ROOM_JOINED,{peer:n});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return a(this,Xt).getValue("peerSessionStore").emit(P.ROOM_STATE,d),a(this,Xt).getValue("peerSessionStore").emit(P.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),n}}async getAllAddedParticipants(){try{return Q0.fromBinary((await this.socket.sendMessagePromise($.getAllAddedParticipants)).payload).participants.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}async getRoomPeers(t,e,r){let i;try{const n={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise($.getRoomPeersInfo,r0.toBinary(n));i=Hh.fromBinary(o.payload)}catch(n){this.logger.error("getRoomPeers::binary_decode_error",{error:n})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise($.getRoomPeersInfo);t=Hh.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getStagePeers(){let t;try{const e=await this.socket.sendMessagePromise($.getRoomPeersInfo);t=Hh.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getPeerInfo(t){let e;try{const r=await this.socket.sendMessagePromise($.getPeerInfo,sS.toBinary({peerId:t}));e=Bn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=tS.create();try{const e=await this.socket.sendMessagePromise($.getRoomInfo);t=tS.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=cS.create();try{const e=await this.socket.sendMessagePromise($.getRoomStageState);t=cS.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t}async broadcastMessage(t,e){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise($.broadcastMessage,fo.toBinary(r))}async broadcastToMeetings(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise($.broadcastToEntity,fo.toBinary(i))}async broadcastToPeers(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage($.broadcastToEntity,fo.toBinary(i))}leaveRoom(t){this.socket.joinAttempted=!1;const e={peer:{peerId:t.peerId,userId:t.userId,displayName:t.name,waitlisted:t.waitlistStatus==="waiting"}};return this.socket.sendMessage($.leaveRoom,g0.toBinary(e))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage($.kick,aS.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage($.kickAll,Gf.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage($.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage($.acceptWaitingRoomRequests,rA.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage($.denyWaitingRoomRequests,nA.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(ll.updateUserPreset,NA.toBinary(r))}handleSocketEvents(){this.socket.on($.broadcastMessage,({payload:t})=>{try{const e=fo.fromBinary(t);a(this,Xt).getValue("peerSessionStore").emit(P.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on($.broadcastToEntity,({payload:t})=>{try{const e=fo.fromBinary(t);a(this,Xt).getValue("peerSessionStore").emit(P.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case $.joinRoom:case $.leaveRoom:case $.kick:case $.kickAll:{r=Bn.fromBinary.bind(Bn),i=Bn.create();break}case $.getWaitingRoomRequests:{r=(n,o)=>n?oS.fromBinary(n,o):{requests:[]},i=oS.create();break}case $.recordingPaused:case $.recordingStarted:case $.recordingStopped:{r=SS.fromBinary.bind(SS);break}case ll.updateUserPreset:{r=lS.fromBinary.bind(lS);break}case Es.peerJoinedBroadcast:case qr.peerJoinedBroadcast:{r=Kf.fromBinary.bind(Kf);break}case Es.selfJoinComplete:case qr.selfJoinComplete:{r=xh.fromBinary.bind(xh);break}case Es.globalPeerPinBroadcast:case qr.globalPeerPinBroadcast:{r=Qf.fromBinary.bind(Qf);break}case Es.selectedPeer:case qr.selectedPeer:{r=Vh.fromBinary.bind(Vh);break}case Es.selectedPeerDiff:case qr.selectedPeerDiff:{r=Jf.fromBinary.bind(Jf);break}case Es.leaveRoom:case qr.leaveRoom:{r=$h.fromBinary.bind($h);break}}this.socket.on(t,({payload:n})=>{let o=i;if(!r)return e(void 0);try{o=r(n)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}async getUserPermissions(t){const e={userIds:[t]};try{const r=await this.socket.sendMessagePromise(ll.getUserPresets,CA.toBinary(e)),i=MA.fromBinary(r.payload).peerPresets[0],n=new TextDecoder().decode(i.preset),o=JSON.parse(n).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}}}Xt=new WeakMap,bN([y.trace("RoomSocketHandler.joinRoom")],rv.prototype,"joinRoom",1);class wN{constructor(t){m(this,$t,void 0);g(this,$t,t)}async getStageRequests(){const{payload:t}=await a(this,$t).sendMessagePromise($.getStageRequests);return t?Yh.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,$t).sendMessage($.requestStageAccess)}cancelRequestAccess(){a(this,$t).sendMessage($.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,$t).sendMessage($.grantStageAccess,rO.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,$t).sendMessage($.denyStageAccess,nO.toBinary(e))}joinStage(){return a(this,$t).sendMessagePromise($.joinStage,void 0,void 0,$.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,$t).sendMessagePromise($.leaveStage,gS.toBinary(e),void 0,$.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,$t).sendMessagePromise($.leaveStage,gS.toBinary(e))}on(t,e){let r;switch(t){case $.grantStageAccess:case $.denyStageAccess:{r=void 0;break}case $.getStagePeers:{r=mS.fromBinary.bind(mS);break}case $.getStageRequests:case $.requestStageAccess:case $.cancelStageRequest:{r=Yh.fromBinary.bind(Yh);break}case $.peerStageStatusUpdate:{r=Xf.fromBinary.bind(Xf);break}}a(this,$t).on(t,({payload:i,id:n})=>{if(!i||!r)return e(void 0,n);const o=r(i);return e(o,n)})}async getPeerInfo(t){const e=await a(this,$t).sendMessagePromise($.getPeerInfo,sS.toBinary({peerId:t}));return Bn.fromBinary(e.payload)}}$t=new WeakMap;class PN{constructor(t,e){m(this,fi,void 0);m(this,Ya,void 0);g(this,fi,e),g(this,Ya,t)}get logger(){return a(this,Ya).getValue("logger")}get peerId(){return a(this,Ya).getValue("peerId")}storeInsertKeys(t,e,r,i){const n={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,fi).sendMessage(or.storeInsertKeys,xM.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,fi).sendMessage(or.storeGetKeys,UM.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,fi).sendMessage(or.storeDeleteKeys,BM.toBinary(n),i)}on(t,e){const r=hS.fromBinary.bind(hS);a(this,fi).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}fi=new WeakMap,Ya=new WeakMap;var _N=Object.defineProperty,kN=(s,t,e)=>t in s?_N(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,CN=(s,t,e)=>(kN(s,typeof t!="symbol"?t+"":t,e),e),kp=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},M=(s,t,e)=>(kp(s,t,"read from private field"),e?e.call(s):t.get(s)),pe=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},ae=(s,t,e,r)=>(kp(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),oe=(s,t,e)=>(kp(s,t,"access private method"),e),Rl={},RN={get exports(){return Rl},set exports(s){Rl=s}},Jn=typeof Reflect=="object"?Reflect:null,iv=Jn&&typeof Jn.apply=="function"?Jn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},Il;Jn&&typeof Jn.ownKeys=="function"?Il=Jn.ownKeys:Object.getOwnPropertySymbols?Il=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:Il=function(s){return Object.getOwnPropertyNames(s)};function IN(s){console&&console.warn&&console.warn(s)}var nv=Number.isNaN||function(s){return s!==s};function me(){me.init.call(this)}RN.exports=me,Rl.once=DN,me.EventEmitter=me,me.prototype._events=void 0,me.prototype._eventsCount=0,me.prototype._maxListeners=void 0;var av=10;function Al(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(me,"defaultMaxListeners",{enumerable:!0,get:function(){return av},set:function(s){if(typeof s!="number"||s<0||nv(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");av=s}}),me.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},me.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||nv(s))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+s+".");return this._maxListeners=s,this};function ov(s){return s._maxListeners===void 0?me.defaultMaxListeners:s._maxListeners}me.prototype.getMaxListeners=function(){return ov(this)},me.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var n;if(t.length>0&&(n=t[0]),n instanceof Error)throw n;var o=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw o.context=n,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")iv(c,this,t);else for(var d=c.length,l=hv(c,d),e=0;e<d;++e)iv(l[e],this,t);return!0};function cv(s,t,e,r){var i,n,o;if(Al(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=ov(s),i>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=s,c.type=t,c.count=o.length,IN(c)}return s}me.prototype.addListener=function(s,t){return cv(this,s,t,!1)},me.prototype.on=me.prototype.addListener,me.prototype.prependListener=function(s,t){return cv(this,s,t,!0)};function AN(){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 dv(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=AN.bind(r);return i.listener=e,r.wrapFn=i,i}me.prototype.once=function(s,t){return Al(t),this.on(s,dv(this,s,t)),this},me.prototype.prependOnceListener=function(s,t){return Al(t),this.prependListener(s,dv(this,s,t)),this},me.prototype.removeListener=function(s,t){var e,r,i,n,o;if(Al(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,n=e.length-1;n>=0;n--)if(e[n]===t||e[n].listener===t){o=e[n].listener,i=n;break}if(i<0)return this;i===0?e.shift():MN(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this},me.prototype.off=me.prototype.removeListener,me.prototype.removeAllListeners=function(s){var t,e,r;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[s]),this;if(arguments.length===0){var i=Object.keys(e),n;for(r=0;r<i.length;++r)n=i[r],n!=="removeListener"&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=e[s],typeof t=="function")this.removeListener(s,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(s,t[r]);return this};function lv(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?ON(i):hv(i,i.length)}me.prototype.listeners=function(s){return lv(this,s,!0)},me.prototype.rawListeners=function(s){return lv(this,s,!1)},me.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):uv.call(s,t)},me.prototype.listenerCount=uv;function uv(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}me.prototype.eventNames=function(){return this._eventsCount>0?Il(this._events):[]};function hv(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function MN(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function ON(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function DN(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,n),r(o)}function n(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}pv(s,t,n,{once:!0}),t!=="error"&&NN(s,i,{once:!0})})}function NN(s,t,e){typeof s.on=="function"&&pv(s,"error",t,e)}function pv(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(n){r.once&&s.removeEventListener(t,i),e(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class LN extends T{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 mv=new LN;class gv{static encode(t){return mv.toBinary(t)}static decode(t){return mv.fromBinary(new Uint8Array(t))}}function VN(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var zr;class xN{constructor(t={}){CN(this,"opts"),pe(this,zr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ae(this,zr,0)}async wait(){ae(this,zr,M(this,zr)+1);const t=VN(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**M(this,zr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return M(this,zr)}reset(){ae(this,zr,0)}}zr=new WeakMap;const Yr={debug:0,info:1,warn:2,error:3};var qi,ji;class $N{constructor(t){pe(this,qi,void 0),pe(this,ji,void 0),ae(this,qi,console),ae(this,ji,t)}debug(...t){Yr[M(this,ji)]>Yr.debug||M(this,qi).debug("[Sockrates]:",...t)}info(...t){Yr[M(this,ji)]>Yr.info||M(this,qi).info("[Sockrates]:",...t)}warn(...t){Yr[M(this,ji)]>Yr.warn||M(this,qi).warn("[Sockrates]:",...t)}error(...t){Yr[M(this,ji)]>Yr.error||M(this,qi).error("[Sockrates]:",...t)}}qi=new WeakMap,ji=new WeakMap;var fv=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(fv||{});const Sv="2",vv="3";var Ne,Kn,ge,Oe,Qr,Ye,mr,Xr,ws,zn,Yn,gr,Cp,Tv,Ao,Ml,Rp,yv,Ol,Ip,Dl,Ap,Mp,Ev,Mo,Nl,Qn,Oo,Ll,Op,Xn,Do,Dp,bv,No,Vl,Lo,xl;class UN{constructor(t,e){var E,k,R,D,N,F,U,B,Z,ie,H,re;pe(this,Cp),pe(this,Ao),pe(this,Rp),pe(this,Ol),pe(this,Dl),pe(this,Mp),pe(this,Mo),pe(this,Qn),pe(this,Ll),pe(this,Xn),pe(this,Dp),pe(this,No),pe(this,Lo),pe(this,Ne,void 0),pe(this,Kn,void 0),pe(this,ge,void 0),pe(this,Oe,void 0),pe(this,Qr,void 0),pe(this,Ye,void 0),pe(this,mr,void 0),pe(this,Xr,void 0),pe(this,ws,void 0),pe(this,zn,void 0),pe(this,Yn,void 0),pe(this,gr,void 0);var r,i,n,o,c,d,l,u,h,f,S;ae(this,Kn,t),ae(this,Qr,[]),ae(this,Ye,new Rl),ae(this,mr,!0),ae(this,ws,!1),ae(this,ge,e!=null?e:{}),(E=(r=M(this,ge)).autoReconnect)!=null||(r.autoReconnect=!0),(k=(i=M(this,ge)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(R=(n=M(this,ge)).pingTimeout)!=null||(n.pingTimeout=3e4),(D=(o=M(this,ge)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(N=(c=M(this,ge)).debug)!=null||(c.debug=!0),(F=(d=M(this,ge)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(U=(l=M(this,ge)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(B=(u=M(this,ge)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(Z=(h=M(this,ge)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),(ie=(f=M(this,ge)).clientInitiatedPings)!=null||(f.clientInitiatedPings=!1),(H=(S=M(this,ge)).clientInitiatedPingInterval)!=null||(S.clientInitiatedPingInterval=3e4),ae(this,Xr,{code:void 0,reason:void 0}),ae(this,Oe,(re=M(this,ge).logger)!=null?re:new $N(M(this,ge).debug?"debug":"info")),ae(this,gr,new xN)}get readyState(){var t;return(t=M(this,Ne))==null?void 0:t.readyState}get url(){return M(this,Kn)}updateURL(t){ae(this,Kn,t),oe(this,Mp,Ev).call(this)}get config(){return M(this,ge)}get sendQueue(){return M(this,Qr)}flush(){if(!M(this,ge).queueOnDisconnect)return!1;const t=[];return M(this,Qr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ae(this,Qr,t),M(this,Qr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){M(this,Oe).debug("Websocket was already connecting or connected.");return}if(M(this,mr)!==!1)return new Promise((e,r)=>{oe(this,Xn,Do).call(this),oe(this,Lo,xl).call(this);try{ae(this,Ne,new WebSocket(oe(this,Cp,Tv).call(this,M(this,Kn)))),M(this,Ne).binaryType="arraybuffer",M(this,Oe).debug("Connecting");const i=setTimeout(()=>{M(this,Oe).debug("Connection timeout. Closing socket"),ae(this,mr,!0),oe(this,Lo,xl).call(this),M(this,Ne).close(3001,"Connection Timeout"),M(this,ge).autoReconnect&&!M(this,ws)&&(M(this,Ye).emit("reconnecting"),oe(this,Mo,Nl).call(this)),r(new Error("Connection timed out!"))},M(this,ge).connectionTimeout);M(this,Ne).onopen=()=>{M(this,Oe).debug(`Ready State: ${fv[M(this,Ne).readyState]}`),i&&clearTimeout(i),oe(this,Ll,Op).call(this),oe(this,Dp,bv).call(this),ae(this,Xr,{code:void 0,reason:void 0}),M(this,Ye).emit("connected"),M(this,ge).flushOnReconnect&&this.flush(),e()},M(this,Ne).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),M(this,Oe).debug("Socket closed. Close event:",{event:n}),M(this,Oe).debug(`Connection closed code: ${o}`),M(this,Oe).debug(`Connection closed reason: ${c}`),M(this,ws)||oe(this,Dl,Ap).call(this,o,c)}catch(o){oe(this,Ao,Ml).call(this,o)}},M(this,Ne).onerror=n=>{oe(this,Ao,Ml).call(this,n)},M(this,Ne).onmessage=n=>oe(this,Rp,yv).call(this,n)}catch(i){oe(this,Ao,Ml).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(M(this,ge).queueOnDisconnect&&(!M(this,Ne)||M(this,Ne).readyState!==1))return M(this,Oe).debug("Queuing message since socket is not connected!",n),M(this,Qr).push(n),!1;const o=gv.encode(n);return oe(this,Qn,Oo).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return oe(this,Qn,Oo).call(this,t)}receive(t,e){return M(this,Ye).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){M(this,Ye).on(t,e);return}this.receive(t,e)}removeAllListeners(){M(this,Ye).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){M(this,Ye).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){M(this,Ye).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ae(this,mr,!1),oe(this,Xn,Do).call(this),oe(this,No,Vl).call(this),this.removeAllListeners(),ae(this,Xr,{code:1e3,reason:"Sockrates disconnect method called"}),M(this,Ne).close(1e3,"Sockrates disconnect method called.")}}Ne=new WeakMap,Kn=new WeakMap,ge=new WeakMap,Oe=new WeakMap,Qr=new WeakMap,Ye=new WeakMap,mr=new WeakMap,Xr=new WeakMap,ws=new WeakMap,zn=new WeakMap,Yn=new WeakMap,gr=new WeakMap,Cp=new WeakSet,Tv=function(s){if(s.startsWith("ws://")||s.startsWith("wss://"))return s;if(s.startsWith("https://"))return`wss://${s.substring(8)}`;if(s.startsWith("http://"))return`ws://${s.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},Ao=new WeakSet,Ml=function(s,t){M(this,Oe).error("Error:",{error:s}),M(this,Ye).emit("errored",{error:s}),t==null||t(s)},Rp=new WeakSet,yv=function(s){if(oe(this,Ll,Op).call(this),s.data===Sv){M(this,Oe).debug("Received ping from server"),oe(this,Qn,Oo).call(this,vv);return}if(s.data===vv){M(this,Oe).debug("Received pong from server");return}const t=gv.decode(s.data),{id:e,payload:r}=t;M(this,Oe).debug("Received message",{event:t.event,messageID:e}),M(this,Ye).emit(t.event.toString(),{id:e,payload:r})},Ol=new WeakSet,Ip=function(){return M(this,Ne).readyState===1},Dl=new WeakSet,Ap=function(s,t){ae(this,Xr,{reason:t,code:s}),M(this,Ye).emit("disconnected",{code:s,reason:t})},Mp=new WeakSet,Ev=function(){const{reason:s,code:t}=M(this,Xr);t&&t!==1e3&&M(this,mr)&&M(this,ge).autoReconnect&&!M(this,ws)&&(M(this,Oe).debug(`Triggering reconnection due to ${s}.`),M(this,Ye).emit("reconnecting"),oe(this,Mo,Nl).call(this))},Mo=new WeakSet,Nl=async function(s=!0){if(s&&M(this,ws)){M(this,Oe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(M(this,ws)||M(this,gr).reset(),M(this,ge).maxReconnectionAttempts!==null&&M(this,gr).getAttempts()>=M(this,ge).maxReconnectionAttempts){M(this,Ye).emit("failed"),ae(this,ws,!1);return}ae(this,ws,!0),oe(this,Lo,xl).call(this),oe(this,Xn,Do).call(this);try{if(await M(this,gr).wait(),M(this,mr)===!1)return;if(M(this,Oe).debug(`Reconnection attempt ${M(this,gr).getAttempts()}`),M(this,Ye).emit("reconnectAttempt",{attempt:M(this,gr).getAttempts()}),await this.connect(),!oe(this,Ol,Ip).call(this))throw Error("Reconnect Failed");ae(this,ws,!1),ae(this,Xr,{code:void 0,reason:void 0}),M(this,Ye).emit("reconnected")}catch(t){M(this,Oe).debug("Failed to reconnect."),M(this,Ye).emit("reconnectFailure",{attempt:M(this,gr).getAttempts()}),oe(this,Mo,Nl).call(this,!1)}},Qn=new WeakSet,Oo=function(s){try{return M(this,Ne).send(s),!0}catch(t){return M(this,Oe).error(t.message),!1}},Ll=new WeakSet,Op=function(){this.config.disconnectOnPingTimeout&&(M(this,Oe).debug("Resetting ping timeout"),oe(this,Xn,Do).call(this),ae(this,zn,setTimeout(()=>{var s;M(this,Oe).debug("Disconnecting the socket due to ping timeout"),ae(this,mr,!0);const t=3002,e="Ping timeout";(s=M(this,Ne))==null||s.close(t,e),oe(this,Dl,Ap).call(this,t,e)},M(this,ge).pingTimeout)))},Xn=new WeakSet,Do=function(){M(this,zn)&&(clearTimeout(M(this,zn)),ae(this,zn,void 0))},Dp=new WeakSet,bv=function(){oe(this,No,Vl).call(this),M(this,ge).clientInitiatedPings&&ae(this,Yn,setInterval(()=>{oe(this,Ol,Ip).call(this)&&(M(this,Oe).debug("Sending client-initiated ping"),oe(this,Qn,Oo).call(this,Sv))},M(this,ge).clientInitiatedPingInterval))},No=new WeakSet,Vl=function(){M(this,Yn)&&(clearInterval(M(this,Yn)),ae(this,Yn,void 0))},Lo=new WeakSet,xl=function(){oe(this,No,Vl).call(this),M(this,Ne)&&(M(this,Ne).onopen=void 0,M(this,Ne).onerror=void 0,M(this,Ne).onmessage=void 0,M(this,Ne).onclose=void 0)};function wv(s){return`${s.slice(0,10)}...${s.slice(-10)}`}function FN(s,t){s.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c — not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://developers.cloudflare.com/api/resources/realtime_kit/subresources/meetings/methods/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:e,orgId:r,participantId:i}=JSON.parse(atob(s.split(".")[1]));if(!e)throw Error(`Received V1 auth token ${s}`);let n=Oi.baseURI.prod;t&&(n=t);const o=`https://${Wd({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new C("Invalid auth token","0004")}}var BN=Object.defineProperty,HN=Object.getOwnPropertyDescriptor,$l=(s,t,e,r)=>{for(var i=r>1?void 0:r?HN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&BN(t,e,i),i};const Pv=65535,qN=3,jN=15e3,GN=8e3,WN=50,JN=1e3,KN=1e4,_v=(xp=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,ut);m(this,Wc);m(this,Bu);m(this,Hu);m(this,qu);m(this,Jc);m(this,Kc);m(this,In);m(this,Gu);m(this,zc);m(this,Yc);m(this,Qc);m(this,Wu);m(this,Xc);m(this,Zc);m(this,Ys,void 0);m(this,Qa,void 0);m(this,Ie,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");m(this,Si,[]);m(this,vi,void 0);m(this,kn,!1);m(this,Cn,void 0);m(this,Ti,void 0);m(this,Qs,void 0);m(this,Xs,void 0);m(this,yi,void 0);m(this,Rn,void 0);m(this,It,0);m(this,Ei,void 0);m(this,At,!0);m(this,We,void 0);if(!t||!e||!r)throw new C("peerId, meetingId, or authToken can not be empty","0404");g(this,We,s),g(this,Xs,navigator.isReactNative?ev:cp),this.capabilities=i,this.roomName=e,this.authToken=r,g(this,Ys,I(this,Wc,om).call(this,t)),g(this,Qa,t);const n=i.includes("PING");g(this,Ie,new UN(a(this,Ys),{autoReconnect:!1,disconnectOnPingTimeout:n,queueOnDisconnect:!1,flushOnReconnect:!1,logger:this.logger,clientInitiatedPings:!n,clientInitiatedPingInterval:15e3})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,ut,Ot).socketJoinAttempted}set joinAttempted(s){a(this,ut,Ot).socketJoinAttempted=s}get telemetry(){return a(this,We).getValue("telemetry")}get logger(){return a(this,We).getValue("logger")}get peerId(){return a(this,We).getValue("peerId")}get supersededLocalPeerIds(){return a(this,Si).filter(s=>s!==this.peerId)}updateCallstatsPeerId(s){const t=a(this,We).getValue("callstats");t.peerId=s,t.backend&&(t.backend.peerId=s,t.backend.eventHandler&&Object.assign(t.backend.eventHandler,{peerId:s}))}updateURL(s){var t;g(this,Ys,I(this,Wc,om).call(this,s)),g(this,Qa,s),a(this,We).getValue("telemetry").resetPeerId(s),(t=a(this,We).getValue("apiClient"))==null||t.setHeader("tracing-id",s),this.updateCallstatsPeerId(s),Fr.remapContext(s,a(this,We)),this.logger.info(`Attempting websocket connection with URL: ${a(this,In,wd)}`),a(this,Ie).updateURL(a(this,Ys))}get url(){return a(this,Ys)}async connect(){var t;const s=a(this,It)+1;g(this,It,s),I(this,zc,lm).call(this),g(this,At,!0),I(this,qu,xT).call(this);try{if(await a(this,Ie).connect(),!a(this,At)||s!==a(this,It))throw new Error("Socket connection was canceled");I(this,Kc,dm).call(this,this.peerId),(t=a(this,Qs))!=null||g(this,Qs,this.peerId),a(this,ut,Ot).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}catch(e){throw this.logger.error(`Websocket connection failed with URL: ${a(this,In,wd)}`,{error:e}),a(this,At)&&s===a(this,It)&&I(this,Qc,hm).call(this,s),e}}disconnect(){g(this,It,a(this,It)+1),g(this,At,!1),I(this,zc,lm).call(this),I(this,Jc,cm).call(this),g(this,Qs,void 0),a(this,Ie).disconnect(),a(this,ut,Ot).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Ie).readyState===1}catch(s){return!1}}sendMessage(s,t,e){if(!a(this,Xc,pm))return!1;const r={};return a(this,We).getValue("telemetry").injectContext(r),a(this,Ie).send(s,e!=null?e:I(this,Zc,mm).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:i,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:i}){if(!a(this,Xc,pm))return Promise.reject(new Error("Socket is not connected for the current peer ID"));const n=i!=null?i:s;return new Promise((o,c)=>{let d;const l=(R,D)=>{d&&clearTimeout(d),a(this,Ie).removeListener(n,R),a(this,Ie).removeListener(Pv,D),a(this,Ie).removeListener(qr.errorResponse,D),a(this,Ie).removeListener(Es.errorResponse,D)},u=r!=null?r:I(this,Zc,mm).call(this),h={};a(this,We).getValue("telemetry").injectContext(h);const S=({id:R,payload:D})=>{if(u===R){let N;try{const F=KR.fromBinary(D);N=new Error(F.errorMessage)}catch(F){N=new Error("failed to parse error message",{cause:F});try{const U=YI.fromBinary(D);N=new Error(U.message)}catch(U){N=new Error("failed to parse error message",{cause:U})}}c(N),l(E,S)}},E=({id:R,payload:D})=>{u===R&&(o({id:R,payload:D}),l(E,S))};a(this,Ie).on(n,E),a(this,Ie).on(Pv,S),a(this,Ie).on(qr.errorResponse,S),a(this,Ie).on(Es.errorResponse,S),d=setTimeout(()=>{l(E,S),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Ie).send(s,u,e,new TextEncoder().encode(JSON.stringify(h)))||(l(E,S),c(new Error("Socket message could not be sent for the current peer ID")))})}on(s,t){a(this,Ie).on(s,t)}onStateEvent(s,t){a(this,Ie).on(s,t)}removeListener(s,t){a(this,Ie).removeListener(s,t)}removeListeners(s){a(this,Ie).removeListeners(s)}flush(){return a(this,Ie).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{var s;this.logger.info(`Websocket connected with URL: ${a(this,In,wd)}`),(s=a(this,Qs))!=null||g(this,Qs,this.peerId),a(this,ut,Ot).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{!a(this,At)||a(this,Ei)===a(this,It)||(this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}}),a(this,ut,Ot).updateSocketConnectionState("disconnected"),a(this,We).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,ut,Ot).joinAttempted}),I(this,Qc,hm).call(this,a(this,It)))})}},Ys=new WeakMap,Qa=new WeakMap,Ie=new WeakMap,ut=new WeakSet,Ot=function(){return a(this,We).getValue("connectionHandler")},Si=new WeakMap,vi=new WeakMap,kn=new WeakMap,Cn=new WeakMap,Ti=new WeakMap,Qs=new WeakMap,Xs=new WeakMap,yi=new WeakMap,Rn=new WeakMap,It=new WeakMap,Ei=new WeakMap,At=new WeakMap,We=new WeakMap,Wc=new WeakSet,om=function(s){let t=kh({servicePrefix:"ws",baseURI:a(this,We).getValue("baseURI")});const e=po(a(this,We),"socket_server_base");if(typeof e=="string"){const n=/^(http|ws):\/\//i.test(e),o=e.replace(/^(https?|wss?):\/\//i,"").replace(/\/+$/,"");t=`${n?"ws":"wss"}://${o}/ws`}const r=new URL(t),i={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...a(this,Si).length>0&&{oldPeerIds:a(this,Si).join(",")},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(n=>nl[n]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0,apiVersion:"23-09-2026"};return Object.entries(i).forEach(([n,o])=>{r.searchParams.append(n,o.toString())}),r.href},Bu=new WeakSet,LT=function(){if(!a(this,Qs))return;const s=new URL(a(this,Ys));return s.protocol=s.protocol==="ws:"?"http:":"https:",s.pathname=`${s.pathname.replace(/\/+$/,"")}/ping`,s.search="",s.searchParams.set("peerId",a(this,Qs)),s.href},Hu=new WeakSet,VT=async function(){const s=I(this,Bu,LT).call(this);if(!s||a(this,kn))return;const t={},e=typeof AbortController=="function"?new AbortController:void 0;let r;g(this,kn,!0),g(this,Ti,t),g(this,Cn,e);try{e&&(r=a(this,Xs).setTimeout(()=>e.abort(),GN));const i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${this.authToken}`},...e&&{signal:e.signal}});i.ok||this.logger.warn("SocketService::API ping request failed",{networkCall:{status:i.status,url:s}})}catch(i){a(this,Ti)===t&&this.logger.warn("SocketService::API ping request failed",{error:i,networkCall:{url:s}})}finally{r!==void 0&&a(this,Xs).clearTimeout(r),a(this,Ti)===t&&(g(this,kn,!1),g(this,Ti,void 0),g(this,Cn,void 0))}},qu=new WeakSet,xT=function(){a(this,vi)===void 0&&g(this,vi,a(this,Xs).setInterval(()=>I(this,Hu,VT).call(this),jN))},Jc=new WeakSet,cm=function(){var s;a(this,vi)!==void 0&&a(this,Xs).clearInterval(a(this,vi)),(s=a(this,Cn))==null||s.abort(),g(this,vi,void 0),g(this,kn,!1),g(this,Ti,void 0),g(this,Cn,void 0)},Kc=new WeakSet,dm=function(s){g(this,Si,[s,...a(this,Si).filter(t=>t!==s)].slice(0,qN))},In=new WeakSet,wd=function(){const s=new URL(a(this,Ys)),t=s.searchParams.get("authToken");return t&&s.searchParams.set("authToken",wv(t)),s.href},ju=new WeakSet,$T=function(s){const t=Math.min(KN,JN*2**(s-1));return Math.floor(Math.random()*(t+1))},Gu=new WeakSet,UT=function(s){return new Promise(t=>{var e;g(this,Rn,t),g(this,yi,a(this,Xs).setTimeout(()=>{g(this,yi,void 0),g(this,Rn,void 0),t()},I(e=_v,ju,$T).call(e,s)))})},zc=new WeakSet,lm=function(){var s;a(this,yi)!==void 0&&(a(this,Xs).clearTimeout(a(this,yi)),g(this,yi,void 0)),(s=a(this,Rn))==null||s.call(this),g(this,Rn,void 0)},Yc=new WeakSet,um=function(s,t){!a(this,At)||s!==a(this,It)||(t&&this.logger.error("SocketService::Reconnect loop failed",{error:t}),g(this,At,!1),I(this,Jc,cm).call(this),g(this,Qs,void 0),a(this,ut,Ot).updateSocketConnectionState("failed"),a(this,We).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_FAILED))},Qc=new WeakSet,hm=function(s){!a(this,At)||a(this,Ei)===s||(g(this,Ei,s),a(this,ut,Ot).updateSocketConnectionState("reconnecting"),I(this,Wu,FT).call(this,s).catch(t=>I(this,Yc,um).call(this,s,t)))},Wu=new WeakSet,FT=async function(s){try{for(let t=1;t<=WN;t+=1){if(!a(this,At)||s!==a(this,It)||(await I(this,Gu,UT).call(this,t),!a(this,At)||s!==a(this,It)))return;this.updateURL(ki()),this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:t}}),a(this,ut,Ot).updateSocketConnectionState("reconnectAttempt",t);try{if(await a(this,Ie).connect(!0),!a(this,At)||s!==a(this,It))return;if(!this.isConnected)throw new Error("Reconnect failed");I(this,Kc,dm).call(this,this.peerId),g(this,Qs,this.peerId),a(this,ut,Ot).updateSocketConnectionState("reconnected"),a(this,We).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_RECONNECTED,{wasSocketJoinAttempted:a(this,ut,Ot).socketJoinAttempted,wasMediaJoinAttempted:a(this,ut,Ot).mediaJoinAttempted});return}catch(e){if(!a(this,At)||s!==a(this,It))return;this.logger.error(`Websocket connection retry attempt ${t} failed with URL: ${a(this,In,wd)}`,{error:e,socket:{retryAttempt:t}}),a(this,ut,Ot).updateSocketConnectionState("reconnectFailure",t)}}I(this,Yc,um).call(this,s)}finally{a(this,Ei)===s&&g(this,Ei,void 0)}},Xc=new WeakSet,pm=function(){return this.isConnected&&a(this,Qa)===this.peerId},Zc=new WeakSet,mm=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},m(xp,ju),xp);let Vo=_v;$l([y.trace("SocketService.connect")],Vo.prototype,"connect",1),$l([y.trace("SocketService.disconnect")],Vo.prototype,"disconnect",1),$l([y.trace("SocketService.sendMessagePromise")],Vo.prototype,"sendMessagePromise",1),$l([y.trace("SocketService.sendMessagePromiseWithTimeout")],Vo.prototype,"sendMessagePromiseWithTimeout",1);class zN{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=w0.fromBinary(t),r=e.meetings.map(o=>{var c;return{id:o.id,title:o.title,participants:(c=o.participants)!=null?c:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(n=e.parentMeeting.participants)!=null?n:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=z0.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=nS.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return iS.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return U0.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise($.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise($.createConnectedRooms,C0.toBinary({payloads:t}));return iS.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}async updateConnectedRooms(t){}async disableConnectedRooms(t){const e=t.map(i=>({id:i})),r=await this.socketService.sendMessagePromise($.deleteConnectedRooms,x0.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise($.movePeers,G0.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}}}var YN=Object.defineProperty,QN=Object.getOwnPropertyDescriptor,XN=(s,t,e,r)=>{for(var i=r>1?void 0:r?QN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&YN(t,e,i),i};class kv extends Ft{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);m(this,Zt,void 0);g(this,Zt,e)}get isActive(){return this.meetings.length!==0}validateAlterAction(){const e=a(this,Zt).getValue("self").permissions.connectedMeetings;if(!(e!=null&&e.canAlterConnectedMeetings))throw new Error("You are not allowed to perform this action. Please enable canAlterConnectedMeetings permission in your preset.")}validateMoveAction(e,r){var d;if(!(r!=null&&r.length))throw new Error("You're trying to move participants with an empty list.");const i=a(this,Zt).getValue("self").permissions.connectedMeetings;if(!i)throw new Error("You are not allowed to perform this action. Please enable connected meetings permissions in your preset.");if(i.canAlterConnectedMeetings)return;const n=a(this,Zt).getValue("userId");if(!(r.length===1&&r[0]===n))throw new Error("You are not allowed to move other participants. Please enable canAlterConnectedMeetings permission in your preset.");if(e===((d=this.parentMeeting)==null?void 0:d.id)){if(!i.canSwitchToParentMeeting)throw new Error("You are not allowed to move to the parent meeting. Please enable canSwitchToParentMeeting permission in your preset.");return}if(!i.canSwitchConnectedMeetings)throw new Error("You are not allowed to move to a connected meeting. Please enable canSwitchConnectedMeetings permission in your preset.")}async getConnectedMeetings(){this.logger.info("Getting connected meetings dump");const e=await a(this,Zt).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateAlterAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await a(this,Zt).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateAlterAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await a(this,Zt).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)}async deleteMeetings(e){this.validateAlterAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),await Promise.all(r);const i=await a(this,Zt).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateMoveAction(r,i),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,Zt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return n.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),n}async moveParticipantsWithCustomPreset(e,r,i){this.validateMoveAction(r,i.map(o=>o.id)),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,Zt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return n.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),n}moveSuccessHandler(e,r,i){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>n.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>n.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>n.get(d)));return{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}Zt=new WeakMap,XN([qt({maxInvocations:60,period:60})],kv.prototype,"getConnectedMeetings",1);var ZN=Object.defineProperty,eL=Object.getOwnPropertyDescriptor,Np=(s,t,e,r)=>{for(var i=r>1?void 0:r?eL(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ZN(t,e,i),i};const Cv=(Jv=class{constructor(s){p(this,"connectedMeetings");m(this,be,void 0);g(this,be,s),this.connectedMeetings=new kv(s)}get telemetry(){return a(this,be).getValue("telemetry")}get logger(){return a(this,be).getValue("logger")}static init(s){const t=new Cv(s);return s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings()),t.setupEvents(),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,be).getValue("connectedMeetingsSocketHandler").socketService.on($.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,be).getValue("connectedMeetingsSocketHandler").socketService.on($.transferPeer,this.handleTransferPeer.bind(this)),a(this,be).getValue("connectedMeetingsSocketHandler").socketService.on($.movedPeer,this.handleMovedPeer.bind(this)),a(this,be).getValue("connectedMeetingsSocketHandler").socketService.on($.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,be).getValue("connectedMeetingsSocketHandler").socketService.on($.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=a(this,be).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,n,o,c;this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:a(this,be).getValue("self").videoEnabled,audio:a(this,be).getValue("self").audioEnabled};try{a(this,be).getValue("self").cleanupEvents(),await a(this,be).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,be).getValue("meeting"))==null?void 0:i.meta)==null?void 0:n.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await Iv.init({...a(this,be).getValue("options"),cachedUserDetails:null,defaults:{...a(this,be).getValue("options").defaults,...e,mediaHandler:a(this,be).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=a(this,be).getValue("self");r.self.setName(a(this,be).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=a(this,be).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return a(this,be).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,be).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s),e=new Map;this.connectedMeetings.meetings.forEach(r=>{e.set(r.id,r)}),t.forEach(r=>{e.has(r.id)?e.get(r.id).title=r.title:e.set(r.id,{...r,participants:[]})}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=a(this,be).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},be=new WeakMap,Jv);let Ul=Cv;Np([y.trace("ConnectedMeetingsController.getConnectedMeetings")],Ul.prototype,"getConnectedMeetings",1),Np([y.trace("ConnectedMeetingsController.setupEvents")],Ul.prototype,"setupEvents",1),Np([y.trace("ConnectedMeetingsController.switchMeeting")],Ul.prototype,"switchMeeting",1);var tL=Object.defineProperty,sL=Object.getOwnPropertyDescriptor,Lp=(s,t,e,r)=>{for(var i=r>1?void 0:r?sL(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&tL(t,e,i),i};const xo=class{constructor(s,t,e){p(this,"apiBase");p(this,"selfController");p(this,"pollController");p(this,"chatController");p(this,"metaController");p(this,"storesManager");p(this,"stageController");p(this,"pluginController");p(this,"internalsController");p(this,"recordingController");p(this,"livestreamController");p(this,"participantController");p(this,"connectedMeetingsController");p(this,"telemetry");p(this,"logger");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController,this.connectedMeetingsController=t.connectedMeetingsController,this.telemetry=e.getValue("telemetry"),this.logger=e.getValue("logger")}static async init(s){var F,U;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(pN(s),Pe.isSupported()===!1)throw new C("Browser not supported","0010",c,!0);const d=jO(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(n),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new kD(s);s.setValue("connectionHandler",l);let u="",h=null;c.info("CF SFU is being used.");const f=xo.createSocketService(s),S=f.connect();S.catch(()=>{});const E=d.getUserDetails();try{h=await E,u=((F=h.meeting)==null?void 0:F.title)||"",s.setValue("presetName",h.preset.name)}catch(B){throw c.error("Failed to get user details",{error:B}),f.disconnect(),B instanceof ul?B.status===401?new C("Unauthorized. The auth token may be invalid or expired. (401)","0004"):B.status===403?new C("Access denied. Insufficient permissions to join the meeting. (403)","0004"):B.status===404?(c.error("[ERROR:0004] participant-details returned 404."),new C("The auth token is not associated with an active participant in this meeting. The meeting may have ended, or the participant may no longer exist. (404)","0004")):B.status>=500?new C(`The server encountered an error. Try again. (${B.status})`,"0001"):B.isHttpError?new C(`Request rejected by the server. (${B.status})`,"0001"):B.isTimeout?new C("Connection timed out. Check the network and try again.","0001"):new C("Unable to connect to the server. Check the internet connection.","0001"):new C((B==null?void 0:B.message)||"Failed to initialize.","0001")}try{await S}catch(B){c.error("[Controller]: Failed to connect to socket server:",{error:B})}const k=pp.init(h.preset,!s.getValue("modules").theme);s.setValue("theme",k);const R=gp.init(s,k.viewType,h.preset.permissions),D=xo.setupControllers(f,s,h,u,k,R);mD(k)&&((U=xo.createRoomNodeClient(s,f).initializeConnection(h.participant.name,i,!1,R))==null||U.catch(Z=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:Z})}));const{controllers:N}=await D;return sC(),new xo(e,N,s)}static async setupControllers(s,t,e,r,i,n){var fe,V,_;const o=t.getValue("modules"),{participant:c}=e,d=t.getValue("defaults"),l=t.getValue("logger"),{viewType:u,mediaConstraints:{audio:h}}=i;t.setValue("viewType",u),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(fe=h.enableHighBitrate)!=null?fe:!1,enableStereo:(V=h.enableStereo)!=null?V:!1}},...d}),t.setValue("maxPreferredStreams",Pe.isMobile()?i.maxVideoStreams.mobile:i.maxVideoStreams.desktop);let f,S,E,k,R,D,N,F,U;const B=new SN(t,s),Z=new zN(s);t.setValue("connectedMeetingsSocketHandler",Z);const ie=new Cl(t,s),H=new dr(t,s),re=new wN(s),we=new rv(t,s),St=new PN(t,s),A=new fN(s),v=await Kr.init(t,we,c,n,i);t.setValue("selfController",v);const w=await _S.init(t,v.self,we,B,r);o.participant&&(F=new pr(t,v.self,we)),(_=o.e2ee)!=null&&_.enabled&&o.e2ee.manager.init(l,t.getValue("peerSessionStore")),o.chat&&(S=await vo.init(t,H,v.self,F.participants)),o.internals&&(R=await op.init(t)),o.livestream&&i.viewType===vs.Livestream&&(N=new WS(t,v.self,A)),o.poll&&(f=await bS.init(t,v.self,ie)),o.recording&&(D=new OS(t,v.self,we)),o.stage&&(E=new kS(t,re,we,v.self,F.participants));const x=new P1(t,St);if(o.plugin){if(!F)throw new C("The plugin module cannot be initialized without the `participant` module","0102");const He=d.plugins||[];k=await AS.init(t,He,v.self,x)}if(o.connectedMeetings&&(U=await Ul.init(t)),o.pip){const He=await Ih._init(t,v.self);t.setValue("pip",He)}return{theme:i,permissions:n,controllers:{storesManager:x,pollController:f,selfController:v,metaController:w,chatController:S,stageController:E,pluginController:k,recordingController:D,internalsController:R,livestreamController:N,participantController:F,connectedMeetingsController:U}}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return tv(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=[];return new Vo(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Fl=xo;Lp([y.trace("Controller.init")],Fl,"init",1),Lp([y.trace("Controller.createRoomNodeClient")],Fl,"createRoomNodeClient",1),Lp([y.trace("Controller.createSocketService")],Fl,"createSocketService",1);class rL{constructor(){p(this,"battery");p(this,"logger");p(this,"init",async t=>{this.logger=t;try{"getBattery"in navigator&&(this.battery=await navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){t.error("Error getting battery",e)}});p(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});p(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});p(this,"cleanup",()=>{var t,e;"getBattery"in navigator&&((t=this.battery)==null||t.removeEventListener("chargingchange",this.updateChargeInfo),(e=this.battery)==null||e.removeEventListener("levelchange",this.updateLevelInfo))})}}const Rv=new rL;class iL{constructor(){m(this,Ju);m(this,bi,new Audio);m(this,An,new MediaStream);m(this,Mn,new Map);m(this,ed,void 0);a(this,bi).srcObject=a(this,An),a(this,bi).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,Mn).has(e.id)||(a(this,An).addTrack(e),a(this,Mn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,bi).setSinkId(t)}removeTrack(t){const e=a(this,Mn).get(t);e&&(a(this,An).removeTrack(e),a(this,Mn).delete(t))}async play(){return a(this,bi).srcObject=a(this,An),a(this,bi).play().catch(t=>{I(this,Ju,BT).call(this,t)})}onError(t){g(this,ed,t)}}bi=new WeakMap,An=new WeakMap,Mn=new WeakMap,ed=new WeakMap,Ju=new WeakSet,BT=function(t){var e;(e=a(this,ed))==null||e.call(this,t)};class nL extends iL{constructor(){super();m(this,Zs,void 0);g(this,Zs,new Map)}addParticipantTrack(e,r){a(this,Zs).set(e,r.id),this.playTracks([r])}reassignParticipantTrack(e,r){const i=a(this,Zs).get(e);i&&(a(this,Zs).delete(e),a(this,Zs).set(r,i))}removeParticipantTrack(e){const r=a(this,Zs).get(e);r&&this.removeTrack(r),a(this,Zs).delete(e)}}Zs=new WeakMap;var aL=Object.defineProperty,oL=Object.getOwnPropertyDescriptor,Bl=(s,t,e,r)=>{for(var i=r>1?void 0:r?oL(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&aL(t,e,i),i};let Zr=(Kv=class{constructor(t,e){m(this,qe,void 0);m(this,On,void 0);g(this,On,t),g(this,qe,e)}get peerId(){return a(this,On).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:ki(),n=Fr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new KS(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var f,S,E,k,R,D,N;Pe.init();const e=(S=(f=t==null?void 0:t.cachedUserDetails)==null?void 0:f.peerId)!=null?S:ki(),{authToken:r,baseURI:i}=t,{meetingId:n,...o}=FN(r,i);if((E=o.baseURI)!=null&&E.includes("dyte.io"))throw new C("Dyte Base URIs are no longer supported. Use RealtimeKit Base URIs.","0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=Zr.setupContext(e,t,n,o),d=c.getValue("telemetry"),l=c.getValue("logger");GT(l),Rv.init(l),d.init(c,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(R=(k=t.modules)==null?void 0:k.tracing)!=null?R:!0,(N=(D=t==null?void 0:t.modules)==null?void 0:D.devTools)==null?void 0:N.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:wv(t.authToken)}});const u=await Fl.init(c),h=new Zr(c,u);return c.setValue("meeting",h),l.info(`Meeting view type: ${h.meta.viewType}`),h}static setupContext(t,e,r,i){var d,l;const n=Fr.createContext(t,e),o={...Dk,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return n.setValue("options",e),n.setValue("peerId",t),n.setValue("modules",o),n.setValue("sdkName","web-core"),n.setValue("meetingId",r),n.setValue("apiBase",i.apiBase),n.setValue("baseURI",i.baseURI),n.setValue("userId",i.participantId),n.setValue("organizationId",i.orgId),n.setValue("authToken",e.authToken),n.setValue("overrides",(d=e.overrides)!=null?d:{}),n.setValue("env",Nk({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Ls(e.cachedUserDetails)),n.setValue("sdkVersion","2.0.4-staging.5"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new nL),n}async join(){const{selfController:t}=a(this,qe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){var r;Rv.cleanup(),a(this,On).getValue("peerSessionStore").reset(),(r=a(this,qe).pluginController)==null||r.cleanup();const{selfController:e}=a(this,qe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,qe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,qe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,qe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,qe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,qe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,qe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,qe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,qe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,qe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,qe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,qe).stageController)==null?void 0:t.stage}get stores(){return a(this,qe).storesManager}get audio(){return a(this,On).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,qe).internalsController)==null?void 0:t.internals}},qe=new WeakMap,On=new WeakMap,Kv);Bl([pt("0002"),ur.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Zr.prototype,"join",1),Bl([pt("0003")],Zr.prototype,"leave",1),Bl([pt("0001"),ur.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Zr,"init",1),Zr=Bl([pt("0000")],Zr);const Iv=Zr;return Iv}();
|
|
17
|
+
`}this.midTransceiverMap.set(n.mid,n);const c=async d=>(this.logger.debug(`[SDP] send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),await this.pc.setRemoteDescription(d),n.mid);return this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(o,void 0,2)}]`),{offerSdp:o,callback:c,sender:n.sender,mid:n.mid}}}class kl extends Ep{constructor(e,r){super(e);p(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new kl(e,r)}get name(){return"Firefox60"}async send({track:e,encodings:r,codecOptions:i,screenShare:n}){this._assertSendDirection();const o=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(e,{direction:"sendonly",streams:[n?this._sendScreenShareStream:this._sendWebStream],...o});if(!this.supportsSendEncodings&&r){r.reverse();const h=c.sender.getParameters();h.encodings=r,await c.sender.setParameters(h)}const d=(h,f)=>{var F;const S=Bi(h),E=S.media[S.media.length-1],k=E.rtp.filter(U=>f.some(B=>B.name===U.codec)),R=E.fmtp.filter(U=>k.some(B=>B.payload===U.payload)),D=(F=E.rtcpFb)==null?void 0:F.filter(U=>k.some(B=>B.payload===U.payload)),N=k.map(U=>U.payload);return S.media[S.media.length-1].rtp=k,S.media[S.media.length-1].fmtp=R,S.media[S.media.length-1].rtcpFb=D,S.media[S.media.length-1].payloads=N.join(" "),wl(S)},l=await this.pc.createOffer();if(l.sdp=d(l.sdp,i),this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),await this.pc.setLocalDescription(l),e==="audio"||e.kind==="audio"){const{enableDtx:h,enableStereo:f}=this,S=this.enableHighBitrate?f?128e3:64e3:f?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${f?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${S}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:l,callback:async h=>(this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),await this.pc.setRemoteDescription(h),c.mid),sender:c.sender,mid:c.mid}}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters(),o=n.encodings.length-1-r;n.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),await i.sender.setParameters(n)}}class wp extends Ep{static createFactory(t){return()=>new wp(t)}get name(){return"Safari12"}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection(),this.logger.debug("Safari12::creating new transceiver");const n=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e}),o=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`Safari12::senders available params: ${JSON.stringify(o)}`);const c=[];r&&r.length>0&&r.forEach(u=>{var f;const h=o.codecs.find(S=>S.mimeType.includes(u.name));if(u.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(u.parameters)}`);const S=((f=h.sdpFmtpLine)==null?void 0:f.split(";"))||[];S.push(...u.parameters);const E=[...new Set(S).values()];h.sdpFmtpLine=E.join(";")}c.push(h)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(c)}`),n.setCodecPreferences(c);const d=await this.pc.createOffer();if(await this.pc.setLocalDescription(d),t==="audio"||t.kind==="audio"){const{enableStereo:u,enableDtx:h}=this,f=this.enableHighBitrate?u?128e3:64e3:u?64e3:32e3;d.sdp=d.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${u?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${f}`)}return this.midTransceiverMap.set(n.mid,n),{offerSdp:d,callback:async u=>(this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),await this.pc.setRemoteDescription(u),n.mid),sender:n.sender,mid:n.mid}}}function sN(s){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){s.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return s.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=Sm.getParser(t),r=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=55",chromium:">=55"}))return;if(e.satisfies({firefox:">=110"}))return"Firefox110";if(e.satisfies({firefox:">=60"}))return"Firefox60";if(e.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||e.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(e.satisfies({safari:">=11"})||e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return;if(r.name&&r.name.toLowerCase()==="blink"){const i=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return i?Number(i[1])>=74?"Chrome74":void 0:"Chrome74"}if(r.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;s.warn("Device::this._detectDevice() | browser not supported");return}s.warn("Device::this._detectDevice() | unknown device")}class rN{constructor(t,{handlerName:e,handlerFactory:r}={}){p(this,"handlerFactory");m(this,kr,void 0);m(this,gn,void 0);const i=t.getValue("logger");if(i.debug("Device constructor() called."),g(this,kr,t),g(this,gn,i),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)a(this,gn).debug(`Device::constructor() | handler given: ${e}`);else if(e=sN(a(this,gn)),e)a(this,gn).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=bp.createFactory(a(this,kr));break;case"Safari12":this.handlerFactory=wp.createFactory(a(this,kr));break;case"Firefox60":this.handlerFactory=kl.createFactory(a(this,kr),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=kl.createFactory(a(this,kr),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=ki();return new yp(a(this,kr),{id:e,...t,handlerFactory:this.handlerFactory})}}kr=new WeakMap,gn=new WeakMap;const iN=2e3;class nN extends Tt.EventEmitter{constructor(e,r){super();m(this,Gs);m(this,yc);m(this,hu);m(this,Ec);m(this,pu);m(this,mu);m(this,gu);m(this,fu);m(this,Su);m(this,bc);m(this,Ws);p(this,"context");m(this,xa,void 0);m(this,rt,void 0);m(this,it,void 0);m(this,Sc,void 0);m(this,vc,void 0);m(this,fn,void 0);m(this,$a,void 0);m(this,Tc,void 0);m(this,Ua,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});m(this,Sn,void 0);m(this,js,"all");this.context=e,g(this,fn,r),g(this,xa,new rN(e)),g(this,$a,new tN(r)),g(this,Tc,Es),a(this,Gs,Pi).mediaState={send:{state:as.NEW},recv:{state:as.NEW}},po(this.context,"forceRelay")&&g(this,js,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,js)}`),I(this,yc,Xp).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,fn)}get socketHandler(){return a(this,$a)}get sendTransport(){return a(this,rt)}get recvTransport(){return a(this,it)}get events(){return a(this,Tc)}set sendTransportConnectedCallback(e){g(this,Sc,e)}set recvTransportConnectedCallback(e){g(this,vc,e)}async setupTransports(e){await I(this,hu,lT).call(this,e);let r,i;e.send&&(r=I(this,Ec,Zp).call(this,a(this,rt)).then(n=>{try{a(this,Sc).call(this,n)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=I(this,Ec,Zp).call(this,a(this,it)).then(n=>{try{a(this,vc).call(this,n)}catch(o){this.logger.error("Failed to run recv transport callback")}})),await Promise.all([r,i])}stopTransports(e){var r,i;if(e.send&&this.sendTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,rt);this.logger.info("Closing send transport",{transport:{id:n,serverId:o,type:c}}),a(this,rt).close(),a(this,rt).removeAllListeners(),g(this,rt,void 0)}if(e.send&&(a(this,Gs,Pi).mediaState.send.state!==as.CLOSED||a(this,Gs,Pi).mediaState.send.sfuSessionId!==void 0)&&I(this,Ws,_i).call(this,{direction:"send",state:as.CLOSED}),e.recv&&this.recvTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,it);this.logger.info("Closing recv transport",{transport:{id:n,serverId:o,type:c}}),(r=a(this,it))==null||r.close(),(i=a(this,it))==null||i.removeAllListeners(),g(this,it,void 0)}e.recv&&(a(this,Gs,Pi).mediaState.recv.state!==as.CLOSED||a(this,Gs,Pi).mediaState.recv.sfuSessionId!==void 0)&&I(this,Ws,_i).call(this,{direction:"recv",state:as.CLOSED}),I(this,yc,Xp).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}xa=new WeakMap,rt=new WeakMap,it=new WeakMap,Sc=new WeakMap,vc=new WeakMap,fn=new WeakMap,$a=new WeakMap,Tc=new WeakMap,Ua=new WeakMap,Sn=new WeakMap,js=new WeakMap,Gs=new WeakSet,Pi=function(){return this.context.getValue("connectionHandler")},yc=new WeakSet,Xp=function(){g(this,Sn,{send:void 0,recv:void 0})},hu=new WeakSet,lT=async function(e){var o,c,d,l,u,h,f,S;po(this.context,"forceRelay")&&g(this,js,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,js)}`);const n=await Ht().getICEServers().catch(E=>(this.logger.warn(`failed to get iceservers from server: ${E.message}`),[]));e.send&&I(this,mu,hT).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(o=this.context.getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(l=(d=(c=this.context.getValue("defaults").mediaConfiguration)==null?void 0:c.audio)==null?void 0:d.enableHighBitrate)!=null?l:!1,enableStereo:(f=(h=(u=this.context.getValue("defaults").mediaConfiguration)==null?void 0:u.audio)==null?void 0:h.enableStereo)!=null?f:!1,enableDtx:!1},iceTransportPolicy:a(this,js)}),e.recv&&I(this,gu,pT).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(S=this.context.getValue("modules").e2ee)==null?void 0:S.enabled},iceTransportPolicy:a(this,js)})},Ec=new WeakSet,Zp=async function(e){const{id:r,serverId:i,direction:n}=e;I(this,fu,mT).call(this,e);try{return await yl(async(c,d)=>{c>0&&this.logger.info(`Retrying ${n} transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:n}});try{if(e.closed)throw new Jr("Cannot reconnect closed transport");await I(this,pu,uT).call(this,e)}catch(l){if(l instanceof Jr){this.logger.error(`Failed to connect ${n} transport. It will not be retried.`,{transport:e,error:l}),d(l);return}throw this.logger.error(`Failed to connect ${n} transport, retrying`,{transport:e,error:l}),l}},{delayTime:100,strategy:"exponential",maxRetryCount:15}),e}catch(o){throw this.logger.error(`Failed to connect ${n} transport after retries: ${e.id}. Transport reconnection will not be retried.`,{error:o,transport:{id:r,serverId:i,type:n}}),e.close(),e.removeAllListeners(),o}},pu=new WeakSet,uT=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!a(this,fn).isConnected)throw new Jr("Socket is not connected");if(e.connectionState==="closed")throw new Jr("Transport is closed");try{await e.connect(n=>I(this,Su,gT).call(this,i,n)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(n){throw a(this,Ua).transportFailureCount[i]+=1,n.message==="ice connection failed"?new Jr(n.message):n}},mu=new WeakSet,hT=function(e){var r,i;if(a(this,rt)&&a(this,rt).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=a(this,rt))==null?void 0:r.id,serverId:(i=a(this,rt))==null?void 0:i.serverId,type:"send"}});return}g(this,rt,a(this,xa).createTransport({...e,direction:"send"})),I(this,Ws,_i).call(this,{state:as.NEW,direction:"send",sfuSessionId:a(this,rt).serverId}),this.context.getValue("callstats").configureSendTransport(a(this,rt))},gu=new WeakSet,pT=function(e){var r,i;if(a(this,it)&&a(this,it).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=a(this,it))==null?void 0:r.id,serverId:(i=a(this,it))==null?void 0:i.serverId,type:"recv"}});return}g(this,it,a(this,xa).createTransport({...e,direction:"recv"})),I(this,Ws,_i).call(this,{state:as.NEW,direction:"recv",sfuSessionId:a(this,it).serverId}),this.context.getValue("callstats").configureRecvTransport(a(this,it))},fu=new WeakSet,mT=function(e){const{direction:r,id:i}=e;e.on("serveridchange",n=>{I(this,Ws,_i).call(this,{state:e.connectionState,direction:r,sfuSessionId:n})}),e.on("connectionstatechange",async n=>{I(this,Ws,_i).call(this,{state:n,direction:r,sfuSessionId:e.serverId}),this.logger.info(`Transport connection state changed to ${n} for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:n}});const o=()=>{const c=a(this,Sn)[r];c!==void 0&&(clearTimeout(c),a(this,Sn)[r]=void 0)};switch(n){case"connected":o(),a(this,Ua).lastConnectionTime=performance.now();break;case"disconnected":a(this,Sn)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await I(this,bc,em).call(this,e.direction)},iN);break;case"failed":if(e.closed)return;o(),this.logger.warn(`${r} transport is in failed state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await I(this,bc,em).call(this,e.direction);break}}),e.on("icecandidate",async n=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:n})})},Su=new WeakSet,gT=async function(e,r){const i=e==="recv";try{const{sdp:n,type:o}=r,c={consuming:i,description:{sdp:n,type:o,target:i?nr.SUBSCRIBER:nr.PUBLISHER},producers:[]};return a(this,$a).connectTransport(c)}catch(n){throw this.logger.error(`Error in ${e} transport connection:`,{error:n}),n}},bc=new WeakSet,em=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),a(this,fn).isConnected&&a(this,Ua).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),g(this,js,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:a(this,rt)}),this.context.getValue("peerSessionStore").emit(P.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,it)}),this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE);break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}const r=e==="send"?a(this,rt):a(this,it);I(this,Ws,_i).call(this,{state:as.CONNECTED,direction:e,sfuSessionId:r.serverId})},Ws=new WeakSet,_i=function(e){const{state:r,direction:i,sfuSessionId:n}=e;a(this,Gs,Pi).mediaState[i]={state:r,sfuSessionId:n},this.context.getValue("peerSessionStore").emit(P.TRANSPORT_STATE_UPDATE,{transport:i,...a(this,Gs,Pi).mediaState[i]})};class aN{constructor(t,e,r,i,n){m(this,vu,void 0);m(this,ms,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=n,g(this,vu,t),g(this,ms,t.getValue("logger"))}async create(t){if(!t||t&&t.length===0)throw new Error("List of producers is required");const e=new Map,r=[];t.forEach(d=>{const{producingPeerId:l,producerId:u,producingTransportId:h}=d,f={simulcast:{preferredRid:"f",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}};e.set(u,l),r.push({producingPeerId:l,producerId:u,producingTransportId:h,...f})});const i=await this.socketHandler.consume({requests:r,consumingTransportId:this.recvTransport.serverId}),n=new Map;t.forEach(d=>n.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const u=n.get(d);if(!u)return;if(l.errorCode){a(this,ms).warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),c.push({...u,errorCode:l.errorCode});return}let h={};try{h=JSON.parse(l.producerState.appData)}catch(f){}o.set(d,{consumerId:l.consumerId,producingTransportId:u.producingTransportId,producingPeerId:u.producingPeerId,kind:u.kind,paused:u.pause,streamId:l.producerTrack.streamId,trackId:l.producerTrack.trackId,screenShare:u.screenShare,mimeType:u.mimeType,appData:h})}),{consumerStates:o,sessionDescription:i.sessionDescription,failedProducers:c}}async negotiate(t){try{a(this,ms).info("Negotiating socket consumer",{transport:this.recvTransport}),a(this,ms).debug(`[SDP] setting remote offer: ${JSON.stringify(t)} on recvTransport`,{transport:this.recvTransport});const e=await this.recvTransport.setRemoteOffer(t),r={transportId:this.recvTransport.serverId,description:{sdp:e.sdp,type:e.type,target:nr.SUBSCRIBER}};return a(this,ms).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,GC.toBinary(r)),a(this,ms).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){a(this,ms).error("Failed to renegotiate",{error:e});return}}async close(t){if(!t.length)return;const e=async(r,i)=>{const n=r.map(l=>l.localId);a(this,ms).info(`Closing consumers: ${JSON.stringify(n)}`);const o={description:{sdp:i.sdp,type:i.type,target:nr.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=SI.fromBinary(c).description;return{sdp:d.sdp,type:d.type}};await this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(t,e),"SocketConsumerStrategy.close",{consumersLength:t.length})}async switchConsumersToLayer(t,e){const r={requests:[],consumingTransportId:this.recvTransport.serverId},i=t.filter(n=>n&&n.id);i.forEach(({id:n,producingTransportId:o,localId:c})=>{r.requests.push({producerId:n,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),await this.socketHandler.updateConsumersSimulcastConfig(r),a(this,ms).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:n})=>n)})}}vu=new WeakMap,ms=new WeakMap;class Pp{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return Bi(t).media.filter(n=>e==="video"?n.type==="video":n.type==="audio").at(-1).msid}async create({offer:t,kind:e,paused:r,appData:i,codecOptions:n,producingTransportId:o}){var h,f;const c=Pp.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:nr.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(h=i.screenShare)!=null?h:!1,mimeType:`${e}/${(f=n[0])==null?void 0:f.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}function oN(s){try{const t=JSON.parse(s.message);if(typeof t!="object"||t===null)return{};const{errorCode:e,errorDescription:r}=t;return{...typeof e=="string"&&{errorCode:e},...typeof r=="string"&&{errorDescription:r}}}catch(t){return{}}}class cN extends nN{constructor(e,r){super(e,r);m(this,Pc);m(this,yu);m(this,Eu);m(this,bu);m(this,wu);m(this,vn,void 0);m(this,Js,void 0);m(this,wc,void 0);m(this,Ks,void 0);m(this,Tu,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});m(this,Cr,[]);m(this,Fa,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{g(this,wc,new Pp(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{g(this,Ks,new aN(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,vn)}get consumers(){return a(this,Js)}get logger(){return this.context.getValue("logger")}reset(){g(this,vn,new Map),g(this,Js,new Map)}async createProducer(e,r){var i,n,o;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const c=await this.sendTransport.produce(e,I(this,yu,fT).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,c),I(this,Eu,ST).call(this,c,r),this.logger.info(`Created ${(n=c.appData)!=null&&n.screenShare?"screenshare":"participant"} ${c.kind} producer ${c.id} for local peer on mid ${c.localId}.`),c}catch(c){throw this.logger.error(`Failed to create ${((o=e==null?void 0:e.track)==null?void 0:o.kind)||"unknown"} producer`,{error:c}),a(this,Tu).producerCreationFailureCount+=1,c}}async closeProducer(e,r){var n,o;const i=this.producers.get(e);if(!i){this.logger.warn(`Producer with ID ${e} was not found`);return}r!=null&&r.stopTrack&&i.track.stop();try{await this.sendTransport.closeProducer(i),this.logger.info(`Closed ${(n=i.appData)!=null&&n.screenShare?"screenshare":"participant"} ${i.kind} producer ${e} of local peer on mid ${i.localId}. `),(o=this.context.getValue("modules").e2ee)!=null&&o.enabled&&this.context.getValue("peerSessionStore").emit(P.E2EE_INACTIVE_PRODUCER,i)}catch(c){this.logger.error("Failed to close producer on server",{error:c,producer:i})}}closeAllProducers(){return Promise.all(Array.from(a(this,vn).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){a(this,Fa)||clearTimeout(a(this,Fa)),g(this,Cr,a(this,Cr).concat(e)),await I(this,Pc,tm).call(this)}removeClosedConsumers(e){return e.filter(r=>{const i=a(this,Js).get(r);return i!=null&&i.closed?(a(this,Js).delete(r),!0):!1})}async closeConsumers(e){if(!a(this,Ks))return;const r=e.map(i=>this.consumers.get(i)).filter(i=>i!==void 0);r.length!==0&&await a(this,Ks).close(r)}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,Js).keys()))}async switchConsumersToLayer(e,r){a(this,Ks).switchConsumersToLayer(e,r)}}vn=new WeakMap,Js=new WeakMap,wc=new WeakMap,Ks=new WeakMap,Tu=new WeakMap,Cr=new WeakMap,Fa=new WeakMap,Pc=new WeakSet,tm=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=a(this,Cr).splice(0,a(this,Cr).length);try{const i=new Set(Array.from(this.consumers.values()).map(({producerId:d})=>d)),n=r.filter(({producerId:d})=>!this.producers.get(d)&&!i.has(d));if(n.length===0)return;const{consumers:o,failedProducers:c}=await this.recvTransport.consume(n,I(this,bu,vT).bind(this),a(this,Ks).negotiate.bind(a(this,Ks)));if(o.forEach(I(this,wu,TT).bind(this)),c!=null&&c.length){this.logger.error("Failed to create consumers for producers",{producers:c});const d=c.filter(({errorCode:l,producerId:u})=>l==="not_found_track_error"?(this.logger.error(`Track not found for producer: ${u}. This will not be retried.`),!1):l==="backend_error"?(this.logger.error("Unrecoverable error: backend error"),!1):!0);g(this,Cr,a(this,Cr).concat(d)),g(this,Fa,setTimeout(I(this,Pc,tm).bind(this),e))}}catch(i){const n=i instanceof Error?i:new Error(String(i));this.logger.error("failed to consume on transport",{error:n});const{errorCode:o,errorDescription:c}=oN(n);if(o==="internal_error"&&c==="Backend error"||o==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:o,message:c}});try{this.stopTransports({recv:!0})}catch(d){}await this.setupTransports({recv:!0})}}},yu=new WeakSet,fT=function(e){return a(this,wc).create(e)},Eu=new WeakSet,ST=function(e,r){e.on("close",async(i,n)=>{const{reason:o}=i,{offer:c}=i;if(this.logger.info("producer::closing",{debuggingHint:o,producer:{...e,status:"closing"}}),o!==_l){const d={producerId:e.id,description:{sdp:c.sdp,type:c.type,target:nr.PUBLISHER}};try{const l=await this.socketHandler.closeProducer(d),u={sdp:l==null?void 0:l.sdp,type:l==null?void 0:l.type};this.logger.info("producer::closed",{producer:{...e,status:"closed"}}),n({answer:u})}catch(l){this.logger.error("producer close error",l)}}this.producers.delete(e.id),r()}),e.on("trackended",()=>{this.logger.info("producer::trackended",{producer:{...e,status:"UNKNOWN"}})}),a(this,vn).set(e.id,e)},bu=new WeakSet,vT=async function(e){try{return await this.recvTransport.canConsume(),await a(this,Ks).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},wu=new WeakSet,TT=function(e){e.on("close",async r=>{this.logger.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),a(this,Js).delete(e.id),this.context.getValue("peerSessionStore").emit(P.CONSUMER_CLOSED,{id:e.id})}),a(this,Js).set(e.id,e),this.context.getValue("peerSessionStore").emit(P.NEW_CONSUMER_CREATED,{id:e.id,appData:e.appData,peerId:e.peerId})};const Ru=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:n=.95,voiceAdaptationRate:o=.99,minEnergyThreshold:c=.005,maxEnergyThreshold:d=.2,energyRatioThreshold:l=1.5,noiseHistorySize:u=50}={}){m(this,Pu);m(this,_u);m(this,_c,void 0);m(this,kc,void 0);m(this,Cc,void 0);m(this,Ba,void 0);m(this,Ha,void 0);m(this,qa,void 0);m(this,Rc,void 0);m(this,Ic,void 0);m(this,ja,void 0);m(this,xt,void 0);m(this,Rs,void 0);m(this,Is,!1);m(this,Tn,0);m(this,yn,0);m(this,Rr,[]);m(this,Ac,void 0);g(this,Ba,t),g(this,xt,t),g(this,_c,e),g(this,kc,r),g(this,Cc,i),g(this,Ha,n),g(this,qa,o),g(this,Rc,c),g(this,Ic,d),g(this,ja,l),g(this,Ac,u),g(this,Rs,t/2)}get voiceDetected(){return a(this,Is)}processAudioChunk(t){var o,c;const e=I(o=Ru,ku,bT).call(o,t),r=I(c=Ru,Cu,wT).call(c,t);return I(this,Pu,yT).call(this,e),e/a(this,Rs)>a(this,ja)&&e>a(this,xt)&&r>a(this,_c)?(g(this,Tn,a(this,Tn)+1),g(this,yn,a(this,Cc)),a(this,Tn)>=a(this,kc)&&g(this,Is,!0)):(g(this,Tn,0),a(this,yn)>0?g(this,yn,a(this,yn)-1):a(this,Is)&&g(this,Is,!1),a(this,Is)||I(this,_u,ET).call(this,e)),{energy:e,isVoice:a(this,Is)}}reset(){g(this,Is,!1),g(this,Tn,0),g(this,yn,0),g(this,xt,a(this,Ba)),g(this,Rs,a(this,Ba)/2),g(this,Rr,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,xt),backgroundNoiseEnergy:a(this,Rs),energyRatioThreshold:a(this,ja)}}};let Ro=Ru;_c=new WeakMap,kc=new WeakMap,Cc=new WeakMap,Ba=new WeakMap,Ha=new WeakMap,qa=new WeakMap,Rc=new WeakMap,Ic=new WeakMap,ja=new WeakMap,xt=new WeakMap,Rs=new WeakMap,Is=new WeakMap,Tn=new WeakMap,yn=new WeakMap,Rr=new WeakMap,Ac=new WeakMap,Pu=new WeakSet,yT=function(t){a(this,Is)?g(this,xt,a(this,qa)*a(this,xt)+(1-a(this,qa))*t):g(this,xt,a(this,Ha)*a(this,xt)+(1-a(this,Ha))*a(this,Rs)),g(this,xt,Math.max(a(this,Rc),Math.min(a(this,Ic),a(this,xt))))},_u=new WeakSet,ET=function(t){if(t<a(this,xt)*1.2)if(a(this,Rr).push(t),a(this,Rr).length>a(this,Ac)&&a(this,Rr).shift(),a(this,Rr).length>=10){const e=[...a(this,Rr)].sort((i,n)=>i-n),r=Math.floor(e.length/2);g(this,Rs,e[r])}else g(this,Rs,.95*a(this,Rs)+.05*t)},ku=new WeakSet,bT=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Cu=new WeakSet,wT=function(t){let e=0;for(let r=1;r<t.length;r+=1)(t[r]>=0&&t[r-1]<0||t[r]<0&&t[r-1]>=0)&&(e+=1);return e},m(Ro,ku),m(Ro,Cu);class XS{constructor(t){p(this,"RNAudioSampleHandler");m(this,Mc,void 0);g(this,Mc,t);const{RNAudioSampleHandlerImpl:e}=navigator;e==null||e.init().then(r=>{this.RNAudioSampleHandler=r}).catch(r=>{this.logger.error("ReactNativeAudioSampler: Failed to initialize audio sampler",r)})}get logger(){return a(this,Mc).getValue("logger")}get samples(){var e;const t=new Float32Array(1024);return(e=this.RNAudioSampleHandler)==null||e.getFloatTimeDomainData(t),t}stop(){var t;(t=this.RNAudioSampleHandler)==null||t.destructor()}}Mc=new WeakMap;class ZS{constructor(t){p(this,"audioContext");p(this,"analyser");m(this,Oc,void 0);g(this,Oc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return a(this,Oc).getValue("logger")}get samples(){if(this.audioContext.state==="suspended")try{this.audioContext.resume()}catch(e){this.logger.error("AudioContextSampler: Failed to resume audio context",e)}const t=new Float32Array(this.analyser.frequencyBinCount);return this.analyser.getFloatTimeDomainData(t),t}set audioTrack(t){const e=new MediaStream;e.addTrack(t),this.audioContext.createMediaStreamSource(e).connect(this.analyser)}}Oc=new WeakMap;class ev{static setInterval(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setInterval(t,e,...r):global.setInterval(t,e,...r)}static clearInterval(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearInterval(t):global.clearInterval(t)}static setTimeout(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setTimeout(t,e,...r):global.setTimeout(t,e,...r)}static clearTimeout(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearTimeout(t):global.clearTimeout(t)}}const dN=60,lN=400,xc=class{constructor(t,e){m(this,Nc);m(this,Iu);m(this,Vc);m(this,Ir,void 0);m(this,Ar,void 0);m(this,Mr,void 0);m(this,Dc,void 0);m(this,Ga,void 0);m(this,Wa,void 0);m(this,gi,void 0);m(this,En,void 0);m(this,Ja,void 0);m(this,bn,void 0);m(this,Or,void 0);m(this,zs,void 0);this.reportRequest=e,g(this,bn,t),g(this,Wa,new Ro);const{isReactNative:r}=navigator;g(this,Or,r?new XS(a(this,bn)):new ZS(a(this,bn))),g(this,zs,r?ev:cp)}get logger(){return a(this,bn).getValue("logger")}set producerId(t){g(this,Mr,t)}set audioTrack(t){g(this,Dc,t),a(this,Or)instanceof ZS&&(a(this,Or).audioTrack=t)}start(t=!1){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter of audio producer ${a(this,Mr)}.`),a(this,Ir)&&a(this,zs).clearInterval(a(this,Ir)),g(this,Ir,a(this,zs).setInterval(I(this,Nc,sm).bind(this),dN)),a(this,Ar)&&a(this,zs).clearInterval(a(this,Ar)),g(this,Ar,a(this,zs).setInterval(I(this,Vc,im).bind(this),lN)),t&&(I(this,Nc,sm).call(this),I(this,Vc,im).call(this))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter of audio producer ${a(this,Mr)}`),a(this,Ir)&&(a(this,zs).clearInterval(a(this,Ir)),g(this,Ir,void 0)),a(this,Ar)&&(a(this,zs).clearInterval(a(this,Ar)),g(this,Ar,void 0))}catch(t){}a(this,Wa).reset(),a(this,Or)instanceof XS&&a(this,Or).stop()}};let Io=xc;Ir=new WeakMap,Ar=new WeakMap,Mr=new WeakMap,Dc=new WeakMap,Ga=new WeakMap,Wa=new WeakMap,gi=new WeakMap,En=new WeakMap,Ja=new WeakMap,bn=new WeakMap,Or=new WeakMap,zs=new WeakMap,Nc=new WeakSet,sm=function(){var i;if(!a(this,Dc)||!a(this,Mr))return;const{energy:t}=I(this,Iu,PT).call(this),e=I(i=xc,Lc,rm).call(i,t);let r=.9;a(this,Ja)!==e&&a(this,Ja)?r=.9:e?r=.3:r=.5,g(this,Ga,(a(this,Ga)||0)*(1-r)+t*r)},Iu=new WeakSet,PT=function(){var o;const{samples:t}=a(this,Or),{energy:e,isVoice:r}=a(this,Wa).processAudioChunk(t),i=I(o=xc,Au,_T).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,gi)||i<a(this,gi))&&g(this,gi,i),(!a(this,En)||i>a(this,En))&&g(this,En,i),{energy:(i-a(this,gi))/(a(this,En)-a(this,gi))*10||0,isVoice:r})},Lc=new WeakSet,rm=function(t){return t<5},Vc=new WeakSet,im=function(t=a(this,Ga)){var r;if(!a(this,Mr)||!t)return;const e={producerId:a(this,Mr),energy:Math.round(t),silent:I(r=xc,Lc,rm).call(r,t)};g(this,Ja,e.silent),this.reportRequest(e)},Au=new WeakSet,_T=function(t){const e=Math.log10(t);return Math.round(e)},m(Io,Lc),m(Io,Au);var uN=Object.defineProperty,hN=Object.getOwnPropertyDescriptor,he=(s,t,e,r)=>{for(var i=r>1?void 0:r?hN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&uN(t,e,i),i};class de{constructor(t,e){m(this,Lr);m(this,Bc);m(this,Ou);m(this,Du);m(this,Nu);m(this,Hc);m(this,Lu);m(this,Vu);m(this,lt);m(this,_n);m(this,xu);m(this,$u);m(this,Uu);m(this,Fu);p(this,"context");p(this,"authToken");p(this,"e2ee");m(this,$c,void 0);m(this,Uc,void 0);m(this,nt,void 0);m(this,j,void 0);m(this,Mu,void 0);m(this,kt,void 0);m(this,Dr,void 0);m(this,wn,void 0);m(this,Pn,void 0);m(this,Fc,void 0);m(this,Qt,null);m(this,Nr,void 0);m(this,Ct,void 0);m(this,Rt,void 0);var i,n;this.context=t;const{socket:r}=e;this.mediaJoined=!1,g(this,nt,r),g(this,Dr,!1),g(this,j,new cN(t,r)),g(this,kt,a(this,j).events),g(this,Nr,new Set),g(this,Ct,new Map),g(this,wn,!1),g(this,Pn,new vp(t.getValue("logger"))),g(this,Rt,new Io(this.context,a(this,j).socketHandler.audioActivity.bind(a(this,j).socketHandler))),this.e2ee=(n=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),g(this,Fc,wh(async()=>{if(!a(this,Lr,Nn).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(a(this,Uc),a(this,$c),!0);o&&(this.context.getValue("peerSessionStore").emit(P.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return a(this,Lr,Nn).mediaJoined}set mediaJoined(t){a(this,Lr,Nn).mediaJoined=t}reset({resetTransportQueue:t}){this.logger.info(`Resetting media node client: closing all transports, producers, consumers, and queues(resetTransportQueue: ${t}).`),a(this,j).closeAllProducers(),a(this,j).closeAllConsumers(),a(this,Ct).clear(),a(this,Nr).clear(),g(this,Qt,null),t&&a(this,Pn).stop(),a(this,j).stopAllTransports(),a(this,j).reset(),t&&g(this,Pn,new vp)}async joinRoom(t,e,r=!1,i={}){a(this,Lr,Nn).mediaJoinAttempted=!0,g(this,Dr,!0);const n=this.peerId;try{const o=await a(this,Pn).push(()=>I(this,Ou,kT).call(this,t,e,r,i),"joinRoom");return o.roomJoined||I(this,Bc,nm).call(this,n),o}catch(o){return this.logger.error("Error in room joining process",{error:o}),I(this,Bc,nm).call(this,n),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_FAILED),{roomJoined:!1,error:o}}}async initializeConnection(t,e,r=!1,i={}){return a(this,Qt)?a(this,Qt):(g(this,Qt,(async()=>{try{await I(this,Hc,am).call(this,t,e,r,i)}catch(n){throw g(this,Qt,null),n}})()),a(this,Qt))}getConsumers(){return a(this,j).consumers}getProducers(){return a(this,j).producers}handoverPeerProducers(t,e){const r=new Set(e);return Array.from(a(this,j).consumers.values()).filter(i=>r.has(i.producerId)?(i.reassignPeer(t),!0):!1)}async leaveRoom(){var r;(r=a(this,Rt))==null||r.stop(),a(this,j).stopAllTransports(),g(this,wn,!1),a(this,Lr,Nn).mediaJoinAttempted=!1;const t={closeRoom:!1};try{a(this,nt).sendMessage(a(this,kt).leaveRoom,fR.toBinary(t))||this.logger.warn("MediaNodeClient.leaveRoom: media leave was not sent")}catch(i){this.logger.error("MediaNodeClient.leaveRoom: media leave failed",{error:i})}this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct().catch(i=>{this.logger.error("leaveRoom::telemetry_destruct_failed",{error:i})})}async activatePeers(t){return this.createConsumers(t)}async createConsumers(t){return t.length===0?Promise.resolve():a(this,j).createConsumers(t)}removeClosedConsumers(t){return a(this,j).removeClosedConsumers(t)}async closeConsumersById(t){t.length&&await a(this,j).closeConsumers(t)}async _shareWebcam(t){var u,h,f,S;const e=Re.WEBCAM,r=I(this,lt,Mt).call(this,e);if(r){const E=await r;if(a(this,j).producers.has(E)){const k=a(this,j).producers.get(E);if(!k.closed)return await k.replaceTrack({track:t}),await this.resumeWebcam(e),t;await this.disableWebcam()}return this._shareWebcam(t)}const i=I(this,Fu,NT).call(this,t),n=po(this.context,"disableSimulcast"),o=(h=(u=this.context)==null?void 0:u.getValue("overrides"))==null?void 0:h.simulcastConfig;n||o&&o.disable||!((S=(f=this.context)==null?void 0:f.getValue("theme"))!=null&&S.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),i.encodings=WD(this.context,t),this.logger.info(`Simulcast encodings: ${JSON.stringify(i.encodings)}`));const d=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,Ct).delete(e)},l=a(this,j).createProducer(i,d);return I(this,_n,bd).call(this,e,l.then(E=>E.id)),l.then(E=>E.track)}async shareWebcam(t){return t===void 0?null:(this.logger.debug("Calling _shareWebcam with VP8 codec"),this._shareWebcam(t))}async shareScreen(t){const{video:e,audio:r}=t;if(e===void 0)return;const i=await I(this,lt,Mt).call(this,Re.SCREENSHARE_VIDEO),n=await I(this,lt,Mt).call(this,Re.SCREENSHARE_AUDIO),o=a(this,j).producers.get(i),c=a(this,j).producers.get(n),d=[];if(o&&!o.closed)d.push(o.replaceTrack({track:e}));else{const l={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Pe.isElectron()},stopTracks:!1},u=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Ct).delete(Re.SCREENSHARE_VIDEO),a(this,Ct).delete(Re.SCREENSHARE_AUDIO)},h=a(this,j).createProducer(l,u);I(this,_n,bd).call(this,Re.SCREENSHARE_VIDEO,h.then(f=>f.id)),d.push(h)}if(r)if(c&&!c.closed)d.push(c.replaceTrack({track:r}));else{const l={track:r,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Pe.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},u=()=>{},h=a(this,j).createProducer(l,u);I(this,_n,bd).call(this,Re.SCREENSHARE_AUDIO,h.then(f=>f.id)),d.push(h)}await Promise.all(d),this.context.getValue("callstats").screenShareStart()}async shareMic(t){try{if(t===void 0)throw new Nt("track undefined");const e=I(this,lt,Mt).call(this,Re.MIC);if(e){const o=await e;if(a(this,j).producers.has(o)){const c=a(this,j).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),a(this,Rt)&&(a(this,Rt).audioTrack=t,a(this,Rt).producerId=o,a(this,Rt).start(!0));return}await a(this,j).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=I(this,Uu,DT).call(this,t),i=()=>{a(this,Ct).delete(Re.MIC)},n=a(this,j).createProducer(r,i);I(this,_n,bd).call(this,Re.MIC,n.then(o=>o.id)),await n.then(o=>{a(this,Rt)&&(a(this,Rt).audioTrack=o.track,a(this,Rt).producerId=o.id,a(this,Rt).start())})}catch(e){throw new C(e)}}async pauseMic(){var i;const t=await I(this,lt,Mt).call(this,Re.MIC),e=a(this,j).producers.get(t);if(!e){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(e.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}e.pause(),(i=a(this,Rt))==null||i.stop();const r={producerId:e.id,pause:!0};a(this,nt).sendMessage(a(this,kt).toggleProducer,il.toBinary(r)),this.logger.info(`Paused mic producer ${e.id} of local peer ${this.peerId}. Remote peers will stop hearing this peer.`)}async pauseWebcam(){const t=await I(this,lt,Mt).call(this,Re.WEBCAM),e=a(this,j).producers.get(t);if(!e){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}e.pause();const r={producerId:e.id,pause:!0};a(this,nt).sendMessage(a(this,kt).toggleProducer,il.toBinary(r)),this.logger.info(`Paused webcam producer ${e.id} of local peer ${this.peerId}. Remote peers will stop seeing this peer.`)}async resumeMic(){const t=await I(this,lt,Mt).call(this,Re.MIC),e=a(this,j).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,nt).sendMessage(a(this,kt).toggleProducer,il.toBinary(r)),this.logger.info(`Resumed mic producer ${e.id} of local peer ${this.peerId}. Remote peers will start hearing this peer.`)}async resumeWebcam(t=Re.WEBCAM){const e=await I(this,lt,Mt).call(this,t),r=a(this,j).producers.get(e);if(!r){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!r.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}r.resume(),r.appData.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};a(this,nt).sendMessage(a(this,kt).toggleProducer,il.toBinary(i)),this.logger.info(`Resumed webcam producer ${r.id} of local peer ${this.peerId}. Remote peers will start seeing this peer.`)}async disableWebcam(){const t=Re.WEBCAM,e=await I(this,lt,Mt).call(this,t);I(this,xu,MT).call(this,t),e&&await a(this,j).closeProducer(e)}async disableMic(){var e;const t=await I(this,lt,Mt).call(this,Re.MIC);t&&await a(this,j).closeProducer(t),(e=a(this,Rt))==null||e.stop(),a(this,Ct).delete(Re.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await I(this,lt,Mt).call(this,Re.SCREENSHARE_VIDEO),e=await I(this,lt,Mt).call(this,Re.SCREENSHARE_AUDIO);t&&await a(this,j).closeProducer(t),e&&await a(this,j).closeProducer(e),a(this,Nr).clear(),a(this,Ct).delete(Re.SCREENSHARE_VIDEO),a(this,Ct).delete(Re.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await I(this,lt,Mt).call(this,Re.WEBCAM);await a(this,j).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await I(this,lt,Mt).call(this,Re.SCREENSHARE_VIDEO);await a(this,j).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:e})}}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await a(this,j).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};a(this,j).socketHandler.kickPeer(e)}kickAll(){a(this,j).socketHandler.kickAll()}async muteAll(t){if(!await a(this,j).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,j).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await a(this,j).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await a(this,j).socketHandler.hostControlForPeer(t,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(t){const e={participantId:t!=null?t:""};try{await a(this,nt).sendMessagePromise(a(this,kt).globalPinPeer,AR.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&a(this,j).producers.get(t.producerId)&&a(this,Nr).add(t.consumerPeerId),a(this,Nr).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));a(this,j).switchConsumersToLayer(r,e)}async handleSocketEvents(){a(this,nt).on(a(this,kt).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{I(this,$u,OT).call(this,DI.fromBinary(t))}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),a(this,nt).on(a(this,kt).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const e=Yf.fromBinary(t),{participantId:r,initiatorParticipantId:i,producerState:{kind:n,pause:o,producerId:c,screenShare:d}}=e;if(d)return;const l=n===Ns.AUDIO?"audio":"video";if(this.logger.info(`Received participant ${l} producer ${o?"paused":"resumed"} broadcast for ${r===this.peerId?"local":"remote"} producer ${c} of peer ${r}. payload: ${Yf.toJsonString(e)}`),r===this.peerId&&i!==this.peerId&&o&&(this.logger.info(`${i?`Remote peer ${i}`:"Kick/Kick-all api"} has paused the ${l==="audio"?"audio":"video"} feed of local peer ${this.peerId}. Reconciling the local state.`),this.context.getValue("peerSessionStore").emit(l==="audio"?P.MUTE_SELF:P.MUTE_SELF_VIDEO)),r===this.peerId)return;this.context.getValue("peerSessionStore").emit(P.PRODUCER_TOGGLE,{peerId:r,producerId:c,paused:o,kind:l}),Array.from(this.getConsumers().values()).filter(h=>h.producerId===c).forEach(h=>{h.kind==="video"&&o||h.paused!==o&&(this.logger.debug(`consumer state mismatched for ${h.id}. updating consumer pause state ${h.paused} to ${o}`),o?(h.pause(),this.context.getValue("peerSessionStore").emit(P.CONSUMER_PAUSED,{id:h.id})):(h.resume(),this.context.getValue("peerSessionStore").emit(P.CONSUMER_RESUMED,{id:h.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,nt).on(a(this,kt).peerLeaveBroadcast,async({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=$h.fromBinary(t);if(e===this.peerId)return;this.logger.info(`Received peer left broadcast of remote peer ${e}`),a(this,Nr).delete(e),this.context.getValue("peerSessionStore").emit(P.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast of remote peer",{error:e})}}),a(this,nt).on(a(this,kt).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=VI.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(P.PRODUCER_CLOSED,{peerId:e,producerId:r})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,nt).on(a(this,kt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,Dr)&&!a(this,wn)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_DISCONNECTED),a(this,Fc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=a(this,j).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(P.CONSUMER_SCORE_UPDATE,{id:r,kind:i.kind,peerId:i.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,r)=>{const i=Array.from(a(this,j).producers.values()).find(n=>n.id===r);i&&this.context.getValue("peerSessionStore").emit(P.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}}$c=new WeakMap,Uc=new WeakMap,nt=new WeakMap,j=new WeakMap,Mu=new WeakMap,kt=new WeakMap,Dr=new WeakMap,wn=new WeakMap,Pn=new WeakMap,Fc=new WeakMap,Qt=new WeakMap,Nr=new WeakMap,Ct=new WeakMap,Rt=new WeakMap,Lr=new WeakSet,Nn=function(){return this.context.getValue("connectionHandler")},Bc=new WeakSet,nm=function(t){this.mediaJoined=!1,g(this,Dr,!1),a(this,nt).isConnected&&this.peerId===t&&this.context.getValue("peerSessionStore").emit(P.MEDIA_ROOM_JOIN_FAILED)},Ou=new WeakSet,kT=async function(t,e,r,i){var o;g(this,Uc,t);let n=!1;if(r){const{recv:c,send:d}=(o=a(this,Lr,Nn).mediaState)!=null?o:{};(d==null?void 0:d.state)===as.CONNECTED&&(c==null?void 0:c.state)===as.CONNECTED?(this.logger.info("MediaNodeClient.joinRoom: transports healthy — preserving all producers for ownership handover"),g(this,Qt,null),n=!0):(this.logger.info("MediaNodeClient.joinRoom: transports unhealthy — full reset"),this.reset({resetTransportQueue:!1}))}try{a(this,Qt)?await a(this,Qt):await I(this,Hc,am).call(this,t,e,r,i,n),I(this,Nu,RT).call(this,e);const{joined:c,error:d}=await I(this,Du,CT).call(this);return{roomJoined:c,error:d}}catch(c){return this.logger.error("Failed to complete room join",{error:c}),{roomJoined:!1,error:c}}finally{g(this,Qt,null)}},Du=new WeakSet,CT=async function(){const t=this.peerId;try{this.mediaJoined=!0;const{roomState:e}=await yl(async(r,i)=>{if(!a(this,nt).isConnected||this.peerId!==t){const n=new Error("Media room join completion superseded by a newer connection");throw i(n),n}return r>0&&this.logger.warn(`Retrying media room join completion for peer ${t}: attempt=${r+1}`),a(this,j).socketHandler.notifySelfJoinComplete()},{strategy:"exponential",maxRetryCount:3,delayTime:1e3});return g(this,$c,e.roomUuid),g(this,wn,!0),g(this,Dr,!1),{joined:!0}}catch(e){return this.logger.error("Error completing room join",{error:e}),this.mediaJoined=!1,g(this,Dr,!1),{joined:!1,error:e}}},Nu=new WeakSet,RT=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...Pe.getDeviceInfo(),userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency},sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};this.context.getValue("callstats").roomJoined(r)}catch(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},Hc=new WeakSet,am=async function(t,e,r,i,n=!1){try{const o=I(this,Lu,IT).call(this);await I(this,Vu,AT).call(this,t,e,r,o),n?this.logger.info("MediaNodeClient: reusing existing transports on rejoin"):await a(this,j).setupTransports({send:!0,recv:!0})}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},Lu=new WeakSet,IT=function(){const t=q1("video/VP8");return g(this,Mu,t),t},Vu=new WeakSet,AT=async function(t,e,r,i){await yl(async(n,o)=>{if(!a(this,nt).isConnected){o(new Error("Socket is not connected"));return}n>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${n}`});try{await a(this,j).socketHandler.joinRoom(e,t,i,r)}catch(c){throw this.logger.error("Failed to send joinRoom message after retries",{error:c}),c}},{delayTime:1e3,strategy:"exponential",maxRetryCount:15})},lt=new WeakSet,Mt=function(t){return a(this,Ct).get(t)},_n=new WeakSet,bd=function(t,e){return a(this,Ct).set(t,e)},xu=new WeakSet,MT=function(t){return a(this,Ct).delete(t)},$u=new WeakSet,OT=function({participantId:t,producerState:e}){var i;if(t===this.peerId||!e)return;this.logger.info(`Received remote ${e.screenShare?"screenshare":"participant"} ${e.kind===Ns.AUDIO?"audio":"video"} producer created broadcast for peer ${t} with producer state ${JSON.stringify(e)}.`);const r=(i=e.mimeType)!=null?i:e.kind===Ns.AUDIO?"audio/opus":"video/VP8";this.context.getValue("peerSessionStore").emit(P.NEW_PRODUCER,{peerId:t,producer:{...e,mimeType:r,kind:e.kind===Ns.AUDIO?"audio":"video",producingPeerId:t}})},Uu=new WeakSet,DT=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},Fu=new WeakSet,NT=function(t){return{track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},he([y.trace("MediaNodeClient.reset")],de.prototype,"reset",1),he([y.trace("MediaNodeClient.joinRoom")],de.prototype,"joinRoom",1),he([y.trace("MediaNodeClient.leaveRoom")],de.prototype,"leaveRoom",1),he([y.trace("MediaNodeClient.activatePeers")],de.prototype,"activatePeers",1),he([y.trace("MediaNodeClient.createConsumers")],de.prototype,"createConsumers",1),he([y.trace("MediaNodeClient.closeConsumersById")],de.prototype,"closeConsumersById",1),he([y.trace("MediaNodeClient._shareWebcam")],de.prototype,"_shareWebcam",1),he([y.trace("MediaNodeClient.shareWebcam")],de.prototype,"shareWebcam",1),he([y.trace("MediaNodeClient.shareScreen")],de.prototype,"shareScreen",1),he([y.trace("MediaNodeClient.shareMic")],de.prototype,"shareMic",1),he([y.trace("MediaNodeClient.pauseMic")],de.prototype,"pauseMic",1),he([y.trace("MediaNodeClient.pauseWebcam")],de.prototype,"pauseWebcam",1),he([y.trace("MediaNodeClient.resumeMic")],de.prototype,"resumeMic",1),he([y.trace("MediaNodeClient.resumeWebcam")],de.prototype,"resumeWebcam",1),he([y.trace("MediaNodeClient.disableWebcam")],de.prototype,"disableWebcam",1),he([y.trace("MediaNodeClient.disableMic")],de.prototype,"disableMic",1),he([y.trace("MediaNodeClient.disableScreenShare")],de.prototype,"disableScreenShare",1),he([y.trace("MediaNodeClient.muteSelf")],de.prototype,"muteSelf",1),he([y.trace("MediaNodeClient.resetVideoProducers")],de.prototype,"resetVideoProducers",1),he([y.trace("MediaNodeClient.changeDisplayName")],de.prototype,"changeDisplayName",1),he([y.trace("MediaNodeClient.kickPeer")],de.prototype,"kick",1),he([y.trace("MediaNodeClient.kickAllPeers")],de.prototype,"kickAll",1),he([y.trace("MediaNodeClient.muteAll")],de.prototype,"muteAll",1),he([y.trace("MediaNodeClient.muteAllVideo")],de.prototype,"muteAllVideo",1),he([y.trace("MediaNodeClient.disableAudio")],de.prototype,"disableAudio",1),he([y.trace("MediaNodeClient.disableVideo")],de.prototype,"disableVideo",1),he([y.trace("MediaNodeClient.pinPeer")],de.prototype,"pinPeer",1),he([y.trace("MediaNodeClient.validateScreenShare")],de.prototype,"validateScreenShare",1);function tv(s,t){const e=s.getValue("roomNodeClient");if(e){if(e)return e;throw new Error("Room node client already set up.")}const r=new de(s,t);return s.setValue("roomNodeClient",r),r}function pN(s){const t=s.getValue("roomNodeClient");try{t==null||t.leaveRoom()}catch(e){s.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}s.setValue("roomNodeClient",void 0)}var mN=Object.defineProperty,gN=Object.getOwnPropertyDescriptor,Hi=(s,t,e,r)=>{for(var i=r>1?void 0:r?gN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&mN(t,e,i),i};const sv=(Wv=class{constructor(s,t,e,r){m(this,ft);p(this,"self");p(this,"authToken");m(this,Ka,void 0);p(this,"viewType");m(this,gs,void 0);m(this,ee,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,g(this,ee,s),this.viewType=r,this.authToken=n,g(this,Ka,i),g(this,gs,e),this.setupEvents()}get peerId(){return a(this,ee).getValue("peerId")}get telemetry(){return a(this,ee).getValue("telemetry")}get logger(){return a(this,ee).getValue("logger")}get mediaJoined(){return a(this,ee).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=Ht(),o=!!s.getValue("cachedUserDetails"),c=await ze.__init__(s,e,r,i,i.name,o);s.setValue("self",c);const d=s.getValue("logger");return navigator.product!=="ReactNative"?setTimeout(async()=>{const u=await c.getAllDevices();d.info("populated_full_device_list",{devices:JSON.stringify(u)}),s.getValue("callstats").devices("AUDIO",u==null?void 0:u.filter(h=>h.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",u==null?void 0:u.filter(h=>h.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",u==null?void 0:u.filter(h=>h.kind==="audiooutput")),d.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:s.getValue("peerId"),engineName:Pe.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:d,apiHostnames:Lk(s),skipConnectivityChecks:!0,authToken:s.getValue("authToken")}),t.socket.updateCallstatsPeerId(s.getValue("peerId")),d.info("Callstats:: initialized")}catch(h){d.error("Callstats:: initialization failed",{error:h})}},0):d.info("Callstats:: Skipped initialization due to navigator product being ReactNative."),new sv(s,c,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:n,screenShareTracks:o}=this.self;if(e.canProduceAudio===G.Allowed&&r)if((s==null?void 0:s.readyState)==="live")try{await a(this,ft,Ut).shareMic(s),this.self.audioEnabled||a(this,ft,Ut).pauseMic()}catch(d){this.self.disableAudio()}else this.logger.warn("shareMediaTracks: audio track is dead, disabling audio"),this.self.disableAudio();if(e.canProduceVideo===G.Allowed&&i)if((t==null?void 0:t.readyState)==="live")try{await a(this,ft,Ut).shareWebcam(t),this.self.videoEnabled||a(this,ft,Ut).pauseWebcam()}catch(d){this.self.disableVideo()}else this.logger.warn("shareMediaTracks: video track is dead, disabling video"),this.self.disableVideo();if(e.canProduceScreenshare===G.Allowed&&n){const d=o.video,l=o.audio;if((d==null?void 0:d.readyState)==="live")try{await((c=a(this,ft,Ut))==null?void 0:c.shareScreen({video:d,audio:(l==null?void 0:l.readyState)==="live"?l:void 0}))}catch(u){this.self.disableScreenShare()}else this.logger.warn("shareMediaTracks: screenshare video track is dead, disabling screenshare"),this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){var r;const{wasSocketJoinAttempted:t,wasMediaJoinAttempted:e}=s;a(this,ee).getValue("callstats").callEnded(),t||e?(this.logger.info(`Resetting Self post reconnect. Peer has earlier tried joining the ${e?"media room":"socket room only"}. Not closing transports.`),await this.joinRoom({reconnected:!0,joinAttempts:s})):(this.logger.info("Resetting Self post reconnect. User never joined the room so doing full reset."),(r=a(this,ft,Ut))==null||r.reset({resetTransportQueue:!0}))}setupEvents(){a(this,ee).getValue("peerSessionStore").on(P.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&await this.shareMediaTracks()}),a(this,ee).getValue("peerSessionStore").on(P.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,ee).getValue("peerSessionStore").on(P.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,ee).getValue("peerSessionStore").on(P.ROOM_NODE_FAILED,()=>{this.logger.error("Room node failed. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,ee).getValue("peerSessionStore").on(P.SOCKET_SERVICE_RECONNECTED,s=>{!s.wasSocketJoinAttempted&&!s.wasMediaJoinAttempted&&(this.self.roomState="init"),this.resetSelf(s).catch(t=>{this.logger.error("Failed to reset self after socket reconnection",{error:t})})}),a(this,ee).getValue("peerSessionStore").on(P.SOCKET_SERVICE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,ee).getValue("peerSessionStore").on(P.SOCKET_SERVICE_FAILED,()=>{this.logger.error("Socket reconnection failed after exhausting all attempts. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,gs).on($.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,gs).on(ll.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,ee).getValue("peerSessionStore").emit(P.UPDATE_PERMISSIONS,t.patch)})}),a(this,gs).on($.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,gs).on($.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,gs).on($.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,ee).getValue("peerSessionStore").onAsync(P.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,ee).getValue("peerSessionStore").on(P.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var n;const i=(n=e==null?void 0:e.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),a(this,ee).getValue("peerSessionStore").on(P.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,ee).getValue("callstats").audioOff())}),a(this,ee).getValue("peerSessionStore").on(P.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,ee).getValue("callstats").videoOff())}),a(this,ee).getValue("peerSessionStore").onAsync(P.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,ee).getValue("peerSessionStore").on(P.PIP_HANGUP,this.leaveRoom.bind(this))}async joinSocketRoomWithRetry(){const s=this.self.id;return yl(async(t,e)=>{if(!a(this,Ka).isConnected||this.self.id!==s){const i=new Error("Socket room join superseded by a newer connection");throw e(i),i}t>0&&this.logger.warn(`Retrying socket room join for peer ${s}: attempt=${t+1}`);const r=await a(this,gs).joinRoom(this.self);if(this.self.id!==s){const i=new Error("Socket room join completed for a superseded peer ID");throw e(i),i}return r},{strategy:"exponential",maxRetryCount:3,delayTime:1e3})}async joinRoom({reconnected:s=!1,joinAttempts:t}={}){var e,r;try{this.logger.info("Local peer is joining socket room.");const{peer:i}=await this.joinSocketRoomWithRetry();this.logger.info("Local peer has joined socket room."),a(this,gs).socket.flush();const n=rp(i.stageType);if(a(this,ee).setValue("stageStatus",n,!1),i.waitlisted){this.logger.info("Peer was waitlisted. Skipped joining media room."),s&&(this.logger.info("Peer reconnected while waitlisted. Resetting media node client."),(e=a(this,ft,Ut))==null||e.reset({resetTransportQueue:!0})),this.waitlistedHandler();return}}catch(i){throw this.logger.error("SelfController.joinRoom: socket join failed",{error:i}),new C("Check the network and try again.","0002")}if(this.viewType===vs.Livestream&&(t!=null&&t.wasSocketJoinAttempted)&&!t.wasMediaJoinAttempted&&a(this,ee).getValue("stageStatus")!=="ON_STAGE"){this.logger.info("Local livestream peer that only joined the socket room is not ON_STAGE. Closing transports, if any."),(r=a(this,ft,Ut))==null||r.reset({resetTransportQueue:!0}),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s}),a(this,ee).notify("stageStatus");return}try{this.logger.info("Local peer is joining media room."),await this.joinMediaRoom(s),this.logger.info("Local peer has joined media room."),a(this,ee).notify("stageStatus")}catch(i){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:i}),i instanceof Jr&&i.message==="ice connection failed"?new C("A firewall or network restriction may be blocking the connection.","0014"):new C("Check the network and try again.","0014")}}async leaveRoom(s="left"){var e;if(this.logger.info(`Leaving room with state: ${s}`),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}if(this.self.setIsPinned(!1),a(this,ee).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,ee).setValue("roomNodeClient",void 0),a(this,ee).notify("stageStatus"),a(this,ee).getValue("connectionHandler").socketJoined)try{a(this,gs).leaveRoom(this.self)||this.logger.warn("SelfController.leaveRoom: socket leave was not sent")}catch(r){this.logger.error("SelfController.leaveRoom: socket leave failed",{error:r})}(e=a(this,ee).getValue("roomSocketHandler"))==null||e.cleanup(),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var n,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,ee).getAllValues();try{if(e===vs.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}tv(a(this,ee),{socket:a(this,Ka),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:h}=(o=await((n=a(this,ft,Ut))==null?void 0:n.joinRoom(this.self.name,r,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)throw h!=null?h:new Error("Could not connect to media server");this.logger.info(i==="ON_STAGE"?"Peer is on stage. Sharing media tracks":"Peer is not on stage. Not sharing media tracks"),i==="ON_STAGE"&&await this.shareMediaTracks(),this.logger.info(i==="ON_STAGE"?"Peer is on stage. Shared media tracks":"Peer is not on stage. Did not share media tracks"),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("SelfController.mediaRoomJoin",{error:c}),c}}async leaveMediaRoom(s){const t=a(this,ee).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===vs.Webinar)&&a(this,ft,Ut)&&(a(this,ft,Ut).mediaJoined&&s!=="disconnected"&&await a(this,ft,Ut).leaveRoom(),!(s==="stageLeft"&&t===vs.Livestream)&&(a(this,ft,Ut).mediaJoined=!1))}async cleanupSelf(){await this.self.disableAudio(),await this.self.disableVideo(),await this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()}},Ka=new WeakMap,gs=new WeakMap,ee=new WeakMap,ft=new WeakSet,Ut=function(){return a(this,ee).getValue("roomNodeClient")},Wv);let Kr=sv;Hi([y.trace("SelfController.resetSelf")],Kr.prototype,"resetSelf",1),Hi([y.trace("SelfController.setupEvents")],Kr.prototype,"setupEvents",1),Hi([y.trace("SelfController.joinRoom")],Kr.prototype,"joinRoom",1),Hi([y.trace("SelfController.leaveRoom")],Kr.prototype,"leaveRoom",1),Hi([y.trace("SelfController.joinMediaRoom")],Kr.prototype,"joinMediaRoom",1),Hi([y.trace("SelfController.leaveMediaRoom")],Kr.prototype,"leaveMediaRoom",1),Hi([y.trace("SelfController.init")],Kr,"init",1);class fN{constructor(t){m(this,qc,void 0);g(this,qc,t)}on(t,e){let r;t===$.roomPeerCount?r=Zf.fromBinary.bind(Zf):r=pS.fromBinary.bind(pS),a(this,qc).on(t,({payload:i})=>{if(t===$.roomPeerCount&&!i)return;const n=r(i);e(n)})}}qc=new WeakMap;class SN{constructor(t,e){m(this,jc,void 0);m(this,Gc,void 0);g(this,jc,e),g(this,Gc,t)}get logger(){return a(this,Gc).getValue("logger")}on(t,e){let r,i;switch(t){case $.transcript:{r=Uh.fromBinary.bind(Uh),i=Uh.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,jc).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}jc=new WeakMap,Gc=new WeakMap;var vN=Object.defineProperty,TN=Object.getOwnPropertyDescriptor,_p=(s,t,e,r)=>{for(var i=r>1?void 0:r?TN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&vN(t,e,i),i};class Cl{constructor(t,e){m(this,Vr,void 0);m(this,za,void 0);g(this,Vr,e),g(this,za,t)}get logger(){return a(this,za).getValue("logger")}get telemetry(){return a(this,za).getValue("telemetry")}getPolls(){return a(this,Vr).sendMessagePromise(cr.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Vr).sendMessage(cr.createPoll,pO.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Vr).sendMessage(cr.votePoll,gO.toBinary(r))}on(t,e){let r,i;switch(t){case cr.updatePoll:case cr.createPoll:case cr.votePoll:{r=Qh.fromBinary.bind(Qh),i=Qh.create();break}}a(this,Vr).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){a(this,Vr).removeListeners(t)}}Vr=new WeakMap,za=new WeakMap,_p([y.trace("PollSocketHandler.getPolls")],Cl.prototype,"getPolls",1),_p([y.trace("PollSocketHandler.createPoll")],Cl.prototype,"createPoll",1),_p([y.trace("PollSocketHandler.votePoll")],Cl.prototype,"votePoll",1);var yN=Object.defineProperty,EN=Object.getOwnPropertyDescriptor,bN=(s,t,e,r)=>{for(var i=r>1?void 0:r?EN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&yN(t,e,i),i};class rv{constructor(t,e){p(this,"socket");m(this,Xt,void 0);g(this,Xt,t),this.socket=e,this.handleSocketEvents(),a(this,Xt).setValue("roomSocketHandler",this)}get telemetry(){return a(this,Xt).getValue("telemetry")}get logger(){return a(this,Xt).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}async joinRoom(t){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise($.joinRoom,p0.toBinary(e));try{const{peer:n}=Bn.fromBinary((await r).payload);a(this,Xt).getValue("connectionHandler").socketJoined=!0,a(this,Xt).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_ROOM_JOINED,{peer:n});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return a(this,Xt).getValue("peerSessionStore").emit(P.ROOM_STATE,d),a(this,Xt).getValue("peerSessionStore").emit(P.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),n}}async getAllAddedParticipants(){try{return Q0.fromBinary((await this.socket.sendMessagePromise($.getAllAddedParticipants)).payload).participants.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}async getRoomPeers(t,e,r){let i;try{const n={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise($.getRoomPeersInfo,r0.toBinary(n));i=Hh.fromBinary(o.payload)}catch(n){this.logger.error("getRoomPeers::binary_decode_error",{error:n})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise($.getRoomPeersInfo);t=Hh.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getStagePeers(){let t;try{const e=await this.socket.sendMessagePromise($.getRoomPeersInfo);t=Hh.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getPeerInfo(t){let e;try{const r=await this.socket.sendMessagePromise($.getPeerInfo,sS.toBinary({peerId:t}));e=Bn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=tS.create();try{const e=await this.socket.sendMessagePromise($.getRoomInfo);t=tS.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=cS.create();try{const e=await this.socket.sendMessagePromise($.getRoomStageState);t=cS.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t}async broadcastMessage(t,e){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise($.broadcastMessage,fo.toBinary(r))}async broadcastToMeetings(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise($.broadcastToEntity,fo.toBinary(i))}async broadcastToPeers(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage($.broadcastToEntity,fo.toBinary(i))}leaveRoom(t){this.socket.joinAttempted=!1;const e={peer:{peerId:t.peerId,userId:t.userId,displayName:t.name,waitlisted:t.waitlistStatus==="waiting"}};return this.socket.sendMessage($.leaveRoom,g0.toBinary(e))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage($.kick,aS.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage($.kickAll,Gf.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage($.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage($.acceptWaitingRoomRequests,rA.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage($.denyWaitingRoomRequests,nA.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(ll.updateUserPreset,NA.toBinary(r))}handleSocketEvents(){this.socket.on($.broadcastMessage,({payload:t})=>{try{const e=fo.fromBinary(t);a(this,Xt).getValue("peerSessionStore").emit(P.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on($.broadcastToEntity,({payload:t})=>{try{const e=fo.fromBinary(t);a(this,Xt).getValue("peerSessionStore").emit(P.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case $.joinRoom:case $.leaveRoom:case $.kick:case $.kickAll:{r=Bn.fromBinary.bind(Bn),i=Bn.create();break}case $.getWaitingRoomRequests:{r=(n,o)=>n?oS.fromBinary(n,o):{requests:[]},i=oS.create();break}case $.recordingPaused:case $.recordingStarted:case $.recordingStopped:{r=SS.fromBinary.bind(SS);break}case ll.updateUserPreset:{r=lS.fromBinary.bind(lS);break}case Es.peerJoinedBroadcast:case qr.peerJoinedBroadcast:{r=Kf.fromBinary.bind(Kf);break}case Es.selfJoinComplete:case qr.selfJoinComplete:{r=xh.fromBinary.bind(xh);break}case Es.globalPeerPinBroadcast:case qr.globalPeerPinBroadcast:{r=Qf.fromBinary.bind(Qf);break}case Es.selectedPeer:case qr.selectedPeer:{r=Vh.fromBinary.bind(Vh);break}case Es.selectedPeerDiff:case qr.selectedPeerDiff:{r=Jf.fromBinary.bind(Jf);break}case Es.leaveRoom:case qr.leaveRoom:{r=$h.fromBinary.bind($h);break}}this.socket.on(t,({payload:n})=>{let o=i;if(!r)return e(void 0);try{o=r(n)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}async getUserPermissions(t){const e={userIds:[t]};try{const r=await this.socket.sendMessagePromise(ll.getUserPresets,CA.toBinary(e)),i=MA.fromBinary(r.payload).peerPresets[0],n=new TextDecoder().decode(i.preset),o=JSON.parse(n).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}}}Xt=new WeakMap,bN([y.trace("RoomSocketHandler.joinRoom")],rv.prototype,"joinRoom",1);class wN{constructor(t){m(this,$t,void 0);g(this,$t,t)}async getStageRequests(){const{payload:t}=await a(this,$t).sendMessagePromise($.getStageRequests);return t?Yh.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,$t).sendMessage($.requestStageAccess)}cancelRequestAccess(){a(this,$t).sendMessage($.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,$t).sendMessage($.grantStageAccess,rO.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,$t).sendMessage($.denyStageAccess,nO.toBinary(e))}joinStage(){return a(this,$t).sendMessagePromise($.joinStage,void 0,void 0,$.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,$t).sendMessagePromise($.leaveStage,gS.toBinary(e),void 0,$.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,$t).sendMessagePromise($.leaveStage,gS.toBinary(e))}on(t,e){let r;switch(t){case $.grantStageAccess:case $.denyStageAccess:{r=void 0;break}case $.getStagePeers:{r=mS.fromBinary.bind(mS);break}case $.getStageRequests:case $.requestStageAccess:case $.cancelStageRequest:{r=Yh.fromBinary.bind(Yh);break}case $.peerStageStatusUpdate:{r=Xf.fromBinary.bind(Xf);break}}a(this,$t).on(t,({payload:i,id:n})=>{if(!i||!r)return e(void 0,n);const o=r(i);return e(o,n)})}async getPeerInfo(t){const e=await a(this,$t).sendMessagePromise($.getPeerInfo,sS.toBinary({peerId:t}));return Bn.fromBinary(e.payload)}}$t=new WeakMap;class PN{constructor(t,e){m(this,fi,void 0);m(this,Ya,void 0);g(this,fi,e),g(this,Ya,t)}get logger(){return a(this,Ya).getValue("logger")}get peerId(){return a(this,Ya).getValue("peerId")}storeInsertKeys(t,e,r,i){const n={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,fi).sendMessage(or.storeInsertKeys,xM.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,fi).sendMessage(or.storeGetKeys,UM.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,fi).sendMessage(or.storeDeleteKeys,BM.toBinary(n),i)}on(t,e){const r=hS.fromBinary.bind(hS);a(this,fi).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}fi=new WeakMap,Ya=new WeakMap;var _N=Object.defineProperty,kN=(s,t,e)=>t in s?_N(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,CN=(s,t,e)=>(kN(s,typeof t!="symbol"?t+"":t,e),e),kp=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},M=(s,t,e)=>(kp(s,t,"read from private field"),e?e.call(s):t.get(s)),pe=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},ae=(s,t,e,r)=>(kp(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),oe=(s,t,e)=>(kp(s,t,"access private method"),e),Rl={},RN={get exports(){return Rl},set exports(s){Rl=s}},Jn=typeof Reflect=="object"?Reflect:null,iv=Jn&&typeof Jn.apply=="function"?Jn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},Il;Jn&&typeof Jn.ownKeys=="function"?Il=Jn.ownKeys:Object.getOwnPropertySymbols?Il=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:Il=function(s){return Object.getOwnPropertyNames(s)};function IN(s){console&&console.warn&&console.warn(s)}var nv=Number.isNaN||function(s){return s!==s};function me(){me.init.call(this)}RN.exports=me,Rl.once=DN,me.EventEmitter=me,me.prototype._events=void 0,me.prototype._eventsCount=0,me.prototype._maxListeners=void 0;var av=10;function Al(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(me,"defaultMaxListeners",{enumerable:!0,get:function(){return av},set:function(s){if(typeof s!="number"||s<0||nv(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");av=s}}),me.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},me.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||nv(s))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+s+".");return this._maxListeners=s,this};function ov(s){return s._maxListeners===void 0?me.defaultMaxListeners:s._maxListeners}me.prototype.getMaxListeners=function(){return ov(this)},me.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var n;if(t.length>0&&(n=t[0]),n instanceof Error)throw n;var o=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw o.context=n,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")iv(c,this,t);else for(var d=c.length,l=hv(c,d),e=0;e<d;++e)iv(l[e],this,t);return!0};function cv(s,t,e,r){var i,n,o;if(Al(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=ov(s),i>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=s,c.type=t,c.count=o.length,IN(c)}return s}me.prototype.addListener=function(s,t){return cv(this,s,t,!1)},me.prototype.on=me.prototype.addListener,me.prototype.prependListener=function(s,t){return cv(this,s,t,!0)};function AN(){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 dv(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=AN.bind(r);return i.listener=e,r.wrapFn=i,i}me.prototype.once=function(s,t){return Al(t),this.on(s,dv(this,s,t)),this},me.prototype.prependOnceListener=function(s,t){return Al(t),this.prependListener(s,dv(this,s,t)),this},me.prototype.removeListener=function(s,t){var e,r,i,n,o;if(Al(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,n=e.length-1;n>=0;n--)if(e[n]===t||e[n].listener===t){o=e[n].listener,i=n;break}if(i<0)return this;i===0?e.shift():MN(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this},me.prototype.off=me.prototype.removeListener,me.prototype.removeAllListeners=function(s){var t,e,r;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[s]),this;if(arguments.length===0){var i=Object.keys(e),n;for(r=0;r<i.length;++r)n=i[r],n!=="removeListener"&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=e[s],typeof t=="function")this.removeListener(s,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(s,t[r]);return this};function lv(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?ON(i):hv(i,i.length)}me.prototype.listeners=function(s){return lv(this,s,!0)},me.prototype.rawListeners=function(s){return lv(this,s,!1)},me.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):uv.call(s,t)},me.prototype.listenerCount=uv;function uv(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}me.prototype.eventNames=function(){return this._eventsCount>0?Il(this._events):[]};function hv(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function MN(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function ON(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function DN(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,n),r(o)}function n(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}pv(s,t,n,{once:!0}),t!=="error"&&NN(s,i,{once:!0})})}function NN(s,t,e){typeof s.on=="function"&&pv(s,"error",t,e)}function pv(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(n){r.once&&s.removeEventListener(t,i),e(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class LN extends T{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 mv=new LN;class gv{static encode(t){return mv.toBinary(t)}static decode(t){return mv.fromBinary(new Uint8Array(t))}}function VN(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var zr;class xN{constructor(t={}){CN(this,"opts"),pe(this,zr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ae(this,zr,0)}async wait(){ae(this,zr,M(this,zr)+1);const t=VN(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**M(this,zr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return M(this,zr)}reset(){ae(this,zr,0)}}zr=new WeakMap;const Yr={debug:0,info:1,warn:2,error:3};var qi,ji;class $N{constructor(t){pe(this,qi,void 0),pe(this,ji,void 0),ae(this,qi,console),ae(this,ji,t)}debug(...t){Yr[M(this,ji)]>Yr.debug||M(this,qi).debug("[Sockrates]:",...t)}info(...t){Yr[M(this,ji)]>Yr.info||M(this,qi).info("[Sockrates]:",...t)}warn(...t){Yr[M(this,ji)]>Yr.warn||M(this,qi).warn("[Sockrates]:",...t)}error(...t){Yr[M(this,ji)]>Yr.error||M(this,qi).error("[Sockrates]:",...t)}}qi=new WeakMap,ji=new WeakMap;var fv=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(fv||{});const Sv="2",vv="3";var Ne,Kn,ge,Oe,Qr,Ye,mr,Xr,ws,zn,Yn,gr,Cp,Tv,Ao,Ml,Rp,yv,Ol,Ip,Dl,Ap,Mp,Ev,Mo,Nl,Qn,Oo,Ll,Op,Xn,Do,Dp,bv,No,Vl,Lo,xl;class UN{constructor(t,e){var E,k,R,D,N,F,U,B,Z,ie,H,re;pe(this,Cp),pe(this,Ao),pe(this,Rp),pe(this,Ol),pe(this,Dl),pe(this,Mp),pe(this,Mo),pe(this,Qn),pe(this,Ll),pe(this,Xn),pe(this,Dp),pe(this,No),pe(this,Lo),pe(this,Ne,void 0),pe(this,Kn,void 0),pe(this,ge,void 0),pe(this,Oe,void 0),pe(this,Qr,void 0),pe(this,Ye,void 0),pe(this,mr,void 0),pe(this,Xr,void 0),pe(this,ws,void 0),pe(this,zn,void 0),pe(this,Yn,void 0),pe(this,gr,void 0);var r,i,n,o,c,d,l,u,h,f,S;ae(this,Kn,t),ae(this,Qr,[]),ae(this,Ye,new Rl),ae(this,mr,!0),ae(this,ws,!1),ae(this,ge,e!=null?e:{}),(E=(r=M(this,ge)).autoReconnect)!=null||(r.autoReconnect=!0),(k=(i=M(this,ge)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(R=(n=M(this,ge)).pingTimeout)!=null||(n.pingTimeout=3e4),(D=(o=M(this,ge)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(N=(c=M(this,ge)).debug)!=null||(c.debug=!0),(F=(d=M(this,ge)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(U=(l=M(this,ge)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(B=(u=M(this,ge)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(Z=(h=M(this,ge)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),(ie=(f=M(this,ge)).clientInitiatedPings)!=null||(f.clientInitiatedPings=!1),(H=(S=M(this,ge)).clientInitiatedPingInterval)!=null||(S.clientInitiatedPingInterval=3e4),ae(this,Xr,{code:void 0,reason:void 0}),ae(this,Oe,(re=M(this,ge).logger)!=null?re:new $N(M(this,ge).debug?"debug":"info")),ae(this,gr,new xN)}get readyState(){var t;return(t=M(this,Ne))==null?void 0:t.readyState}get url(){return M(this,Kn)}updateURL(t){ae(this,Kn,t),oe(this,Mp,Ev).call(this)}get config(){return M(this,ge)}get sendQueue(){return M(this,Qr)}flush(){if(!M(this,ge).queueOnDisconnect)return!1;const t=[];return M(this,Qr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ae(this,Qr,t),M(this,Qr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){M(this,Oe).debug("Websocket was already connecting or connected.");return}if(M(this,mr)!==!1)return new Promise((e,r)=>{oe(this,Xn,Do).call(this),oe(this,Lo,xl).call(this);try{ae(this,Ne,new WebSocket(oe(this,Cp,Tv).call(this,M(this,Kn)))),M(this,Ne).binaryType="arraybuffer",M(this,Oe).debug("Connecting");const i=setTimeout(()=>{M(this,Oe).debug("Connection timeout. Closing socket"),ae(this,mr,!0),oe(this,Lo,xl).call(this),M(this,Ne).close(3001,"Connection Timeout"),M(this,ge).autoReconnect&&!M(this,ws)&&(M(this,Ye).emit("reconnecting"),oe(this,Mo,Nl).call(this)),r(new Error("Connection timed out!"))},M(this,ge).connectionTimeout);M(this,Ne).onopen=()=>{M(this,Oe).debug(`Ready State: ${fv[M(this,Ne).readyState]}`),i&&clearTimeout(i),oe(this,Ll,Op).call(this),oe(this,Dp,bv).call(this),ae(this,Xr,{code:void 0,reason:void 0}),M(this,Ye).emit("connected"),M(this,ge).flushOnReconnect&&this.flush(),e()},M(this,Ne).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),M(this,Oe).debug("Socket closed. Close event:",{event:n}),M(this,Oe).debug(`Connection closed code: ${o}`),M(this,Oe).debug(`Connection closed reason: ${c}`),M(this,ws)||oe(this,Dl,Ap).call(this,o,c)}catch(o){oe(this,Ao,Ml).call(this,o)}},M(this,Ne).onerror=n=>{oe(this,Ao,Ml).call(this,n)},M(this,Ne).onmessage=n=>oe(this,Rp,yv).call(this,n)}catch(i){oe(this,Ao,Ml).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(M(this,ge).queueOnDisconnect&&(!M(this,Ne)||M(this,Ne).readyState!==1))return M(this,Oe).debug("Queuing message since socket is not connected!",n),M(this,Qr).push(n),!1;const o=gv.encode(n);return oe(this,Qn,Oo).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return oe(this,Qn,Oo).call(this,t)}receive(t,e){return M(this,Ye).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){M(this,Ye).on(t,e);return}this.receive(t,e)}removeAllListeners(){M(this,Ye).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){M(this,Ye).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){M(this,Ye).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ae(this,mr,!1),oe(this,Xn,Do).call(this),oe(this,No,Vl).call(this),this.removeAllListeners(),ae(this,Xr,{code:1e3,reason:"Sockrates disconnect method called"}),M(this,Ne).close(1e3,"Sockrates disconnect method called.")}}Ne=new WeakMap,Kn=new WeakMap,ge=new WeakMap,Oe=new WeakMap,Qr=new WeakMap,Ye=new WeakMap,mr=new WeakMap,Xr=new WeakMap,ws=new WeakMap,zn=new WeakMap,Yn=new WeakMap,gr=new WeakMap,Cp=new WeakSet,Tv=function(s){if(s.startsWith("ws://")||s.startsWith("wss://"))return s;if(s.startsWith("https://"))return`wss://${s.substring(8)}`;if(s.startsWith("http://"))return`ws://${s.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},Ao=new WeakSet,Ml=function(s,t){M(this,Oe).error("Error:",{error:s}),M(this,Ye).emit("errored",{error:s}),t==null||t(s)},Rp=new WeakSet,yv=function(s){if(oe(this,Ll,Op).call(this),s.data===Sv){M(this,Oe).debug("Received ping from server"),oe(this,Qn,Oo).call(this,vv);return}if(s.data===vv){M(this,Oe).debug("Received pong from server");return}const t=gv.decode(s.data),{id:e,payload:r}=t;M(this,Oe).debug("Received message",{event:t.event,messageID:e}),M(this,Ye).emit(t.event.toString(),{id:e,payload:r})},Ol=new WeakSet,Ip=function(){return M(this,Ne).readyState===1},Dl=new WeakSet,Ap=function(s,t){ae(this,Xr,{reason:t,code:s}),M(this,Ye).emit("disconnected",{code:s,reason:t})},Mp=new WeakSet,Ev=function(){const{reason:s,code:t}=M(this,Xr);t&&t!==1e3&&M(this,mr)&&M(this,ge).autoReconnect&&!M(this,ws)&&(M(this,Oe).debug(`Triggering reconnection due to ${s}.`),M(this,Ye).emit("reconnecting"),oe(this,Mo,Nl).call(this))},Mo=new WeakSet,Nl=async function(s=!0){if(s&&M(this,ws)){M(this,Oe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(M(this,ws)||M(this,gr).reset(),M(this,ge).maxReconnectionAttempts!==null&&M(this,gr).getAttempts()>=M(this,ge).maxReconnectionAttempts){M(this,Ye).emit("failed"),ae(this,ws,!1);return}ae(this,ws,!0),oe(this,Lo,xl).call(this),oe(this,Xn,Do).call(this);try{if(await M(this,gr).wait(),M(this,mr)===!1)return;if(M(this,Oe).debug(`Reconnection attempt ${M(this,gr).getAttempts()}`),M(this,Ye).emit("reconnectAttempt",{attempt:M(this,gr).getAttempts()}),await this.connect(),!oe(this,Ol,Ip).call(this))throw Error("Reconnect Failed");ae(this,ws,!1),ae(this,Xr,{code:void 0,reason:void 0}),M(this,Ye).emit("reconnected")}catch(t){M(this,Oe).debug("Failed to reconnect."),M(this,Ye).emit("reconnectFailure",{attempt:M(this,gr).getAttempts()}),oe(this,Mo,Nl).call(this,!1)}},Qn=new WeakSet,Oo=function(s){try{return M(this,Ne).send(s),!0}catch(t){return M(this,Oe).error(t.message),!1}},Ll=new WeakSet,Op=function(){this.config.disconnectOnPingTimeout&&(M(this,Oe).debug("Resetting ping timeout"),oe(this,Xn,Do).call(this),ae(this,zn,setTimeout(()=>{var s;M(this,Oe).debug("Disconnecting the socket due to ping timeout"),ae(this,mr,!0);const t=3002,e="Ping timeout";(s=M(this,Ne))==null||s.close(t,e),oe(this,Dl,Ap).call(this,t,e)},M(this,ge).pingTimeout)))},Xn=new WeakSet,Do=function(){M(this,zn)&&(clearTimeout(M(this,zn)),ae(this,zn,void 0))},Dp=new WeakSet,bv=function(){oe(this,No,Vl).call(this),M(this,ge).clientInitiatedPings&&ae(this,Yn,setInterval(()=>{oe(this,Ol,Ip).call(this)&&(M(this,Oe).debug("Sending client-initiated ping"),oe(this,Qn,Oo).call(this,Sv))},M(this,ge).clientInitiatedPingInterval))},No=new WeakSet,Vl=function(){M(this,Yn)&&(clearInterval(M(this,Yn)),ae(this,Yn,void 0))},Lo=new WeakSet,xl=function(){oe(this,No,Vl).call(this),M(this,Ne)&&(M(this,Ne).onopen=void 0,M(this,Ne).onerror=void 0,M(this,Ne).onmessage=void 0,M(this,Ne).onclose=void 0)};function wv(s){return`${s.slice(0,10)}...${s.slice(-10)}`}function FN(s,t){s.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c — not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://developers.cloudflare.com/api/resources/realtime_kit/subresources/meetings/methods/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:e,orgId:r,participantId:i}=JSON.parse(atob(s.split(".")[1]));if(!e)throw Error(`Received V1 auth token ${s}`);let n=Oi.baseURI.prod;t&&(n=t);const o=`https://${Wd({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new C("Invalid auth token","0004")}}var BN=Object.defineProperty,HN=Object.getOwnPropertyDescriptor,$l=(s,t,e,r)=>{for(var i=r>1?void 0:r?HN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&BN(t,e,i),i};const Pv=65535,qN=3,jN=15e3,GN=8e3,WN=50,JN=1e3,KN=1e4,_v=(xp=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,ut);m(this,Wc);m(this,Bu);m(this,Hu);m(this,qu);m(this,Jc);m(this,Kc);m(this,In);m(this,Gu);m(this,zc);m(this,Yc);m(this,Qc);m(this,Wu);m(this,Xc);m(this,Zc);m(this,Ys,void 0);m(this,Qa,void 0);m(this,Ie,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");m(this,Si,[]);m(this,vi,void 0);m(this,kn,!1);m(this,Cn,void 0);m(this,Ti,void 0);m(this,Qs,void 0);m(this,Xs,void 0);m(this,yi,void 0);m(this,Rn,void 0);m(this,It,0);m(this,Ei,void 0);m(this,At,!0);m(this,We,void 0);if(!t||!e||!r)throw new C("peerId, meetingId, or authToken can not be empty","0404");g(this,We,s),g(this,Xs,navigator.isReactNative?ev:cp),this.capabilities=i,this.roomName=e,this.authToken=r,g(this,Ys,I(this,Wc,om).call(this,t)),g(this,Qa,t);const n=i.includes("PING");g(this,Ie,new UN(a(this,Ys),{autoReconnect:!1,disconnectOnPingTimeout:n,queueOnDisconnect:!1,flushOnReconnect:!1,logger:this.logger,clientInitiatedPings:!n,clientInitiatedPingInterval:15e3})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,ut,Ot).socketJoinAttempted}set joinAttempted(s){a(this,ut,Ot).socketJoinAttempted=s}get telemetry(){return a(this,We).getValue("telemetry")}get logger(){return a(this,We).getValue("logger")}get peerId(){return a(this,We).getValue("peerId")}get supersededLocalPeerIds(){return a(this,Si).filter(s=>s!==this.peerId)}updateCallstatsPeerId(s){const t=a(this,We).getValue("callstats");t.peerId=s,t.backend&&(t.backend.peerId=s,t.backend.eventHandler&&Object.assign(t.backend.eventHandler,{peerId:s}))}updateURL(s){var t;g(this,Ys,I(this,Wc,om).call(this,s)),g(this,Qa,s),a(this,We).getValue("telemetry").resetPeerId(s),(t=a(this,We).getValue("apiClient"))==null||t.setHeader("tracing-id",s),this.updateCallstatsPeerId(s),Fr.remapContext(s,a(this,We)),this.logger.info(`Attempting websocket connection with URL: ${a(this,In,wd)}`),a(this,Ie).updateURL(a(this,Ys))}get url(){return a(this,Ys)}async connect(){var t;const s=a(this,It)+1;g(this,It,s),I(this,zc,lm).call(this),g(this,At,!0),I(this,qu,xT).call(this);try{if(await a(this,Ie).connect(),!a(this,At)||s!==a(this,It))throw new Error("Socket connection was canceled");I(this,Kc,dm).call(this,this.peerId),(t=a(this,Qs))!=null||g(this,Qs,this.peerId),a(this,ut,Ot).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}catch(e){throw this.logger.error(`Websocket connection failed with URL: ${a(this,In,wd)}`,{error:e}),a(this,At)&&s===a(this,It)&&I(this,Qc,hm).call(this,s),e}}disconnect(){g(this,It,a(this,It)+1),g(this,At,!1),I(this,zc,lm).call(this),I(this,Jc,cm).call(this),g(this,Qs,void 0),a(this,Ie).disconnect(),a(this,ut,Ot).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Ie).readyState===1}catch(s){return!1}}sendMessage(s,t,e){if(!a(this,Xc,pm))return!1;const r={};return a(this,We).getValue("telemetry").injectContext(r),a(this,Ie).send(s,e!=null?e:I(this,Zc,mm).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:i,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:i}){if(!a(this,Xc,pm))return Promise.reject(new Error("Socket is not connected for the current peer ID"));const n=i!=null?i:s;return new Promise((o,c)=>{let d;const l=(R,D)=>{d&&clearTimeout(d),a(this,Ie).removeListener(n,R),a(this,Ie).removeListener(Pv,D),a(this,Ie).removeListener(qr.errorResponse,D),a(this,Ie).removeListener(Es.errorResponse,D)},u=r!=null?r:I(this,Zc,mm).call(this),h={};a(this,We).getValue("telemetry").injectContext(h);const S=({id:R,payload:D})=>{if(u===R){let N;try{const F=KR.fromBinary(D);N=new Error(F.errorMessage)}catch(F){N=new Error("failed to parse error message",{cause:F});try{const U=YI.fromBinary(D);N=new Error(U.message)}catch(U){N=new Error("failed to parse error message",{cause:U})}}c(N),l(E,S)}},E=({id:R,payload:D})=>{u===R&&(o({id:R,payload:D}),l(E,S))};a(this,Ie).on(n,E),a(this,Ie).on(Pv,S),a(this,Ie).on(qr.errorResponse,S),a(this,Ie).on(Es.errorResponse,S),d=setTimeout(()=>{l(E,S),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Ie).send(s,u,e,new TextEncoder().encode(JSON.stringify(h)))||(l(E,S),c(new Error("Socket message could not be sent for the current peer ID")))})}on(s,t){a(this,Ie).on(s,t)}onStateEvent(s,t){a(this,Ie).on(s,t)}removeListener(s,t){a(this,Ie).removeListener(s,t)}removeListeners(s){a(this,Ie).removeListeners(s)}flush(){return a(this,Ie).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{var s;this.logger.info(`Websocket connected with URL: ${a(this,In,wd)}`),(s=a(this,Qs))!=null||g(this,Qs,this.peerId),a(this,ut,Ot).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{!a(this,At)||a(this,Ei)===a(this,It)||(this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}}),a(this,ut,Ot).updateSocketConnectionState("disconnected"),a(this,We).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,ut,Ot).joinAttempted}),I(this,Qc,hm).call(this,a(this,It)))})}},Ys=new WeakMap,Qa=new WeakMap,Ie=new WeakMap,ut=new WeakSet,Ot=function(){return a(this,We).getValue("connectionHandler")},Si=new WeakMap,vi=new WeakMap,kn=new WeakMap,Cn=new WeakMap,Ti=new WeakMap,Qs=new WeakMap,Xs=new WeakMap,yi=new WeakMap,Rn=new WeakMap,It=new WeakMap,Ei=new WeakMap,At=new WeakMap,We=new WeakMap,Wc=new WeakSet,om=function(s){let t=kh({servicePrefix:"ws",baseURI:a(this,We).getValue("baseURI")});const e=po(a(this,We),"socket_server_base");if(typeof e=="string"){const n=/^(http|ws):\/\//i.test(e),o=e.replace(/^(https?|wss?):\/\//i,"").replace(/\/+$/,"");t=`${n?"ws":"wss"}://${o}/ws`}const r=new URL(t),i={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...a(this,Si).length>0&&{oldPeerIds:a(this,Si).join(",")},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(n=>nl[n]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0,apiVersion:"23-09-2026"};return Object.entries(i).forEach(([n,o])=>{r.searchParams.append(n,o.toString())}),r.href},Bu=new WeakSet,LT=function(){if(!a(this,Qs))return;const s=new URL(a(this,Ys));return s.protocol=s.protocol==="ws:"?"http:":"https:",s.pathname=`${s.pathname.replace(/\/+$/,"")}/ping`,s.search="",s.searchParams.set("peerId",a(this,Qs)),s.href},Hu=new WeakSet,VT=async function(){const s=I(this,Bu,LT).call(this);if(!s||a(this,kn))return;const t={},e=typeof AbortController=="function"?new AbortController:void 0;let r;g(this,kn,!0),g(this,Ti,t),g(this,Cn,e);try{e&&(r=a(this,Xs).setTimeout(()=>e.abort(),GN));const i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${this.authToken}`},...e&&{signal:e.signal}});i.ok||this.logger.warn("SocketService::API ping request failed",{networkCall:{status:i.status,url:s}})}catch(i){a(this,Ti)===t&&this.logger.warn("SocketService::API ping request failed",{error:i,networkCall:{url:s}})}finally{r!==void 0&&a(this,Xs).clearTimeout(r),a(this,Ti)===t&&(g(this,kn,!1),g(this,Ti,void 0),g(this,Cn,void 0))}},qu=new WeakSet,xT=function(){a(this,vi)===void 0&&g(this,vi,a(this,Xs).setInterval(()=>I(this,Hu,VT).call(this),jN))},Jc=new WeakSet,cm=function(){var s;a(this,vi)!==void 0&&a(this,Xs).clearInterval(a(this,vi)),(s=a(this,Cn))==null||s.abort(),g(this,vi,void 0),g(this,kn,!1),g(this,Ti,void 0),g(this,Cn,void 0)},Kc=new WeakSet,dm=function(s){g(this,Si,[s,...a(this,Si).filter(t=>t!==s)].slice(0,qN))},In=new WeakSet,wd=function(){const s=new URL(a(this,Ys)),t=s.searchParams.get("authToken");return t&&s.searchParams.set("authToken",wv(t)),s.href},ju=new WeakSet,$T=function(s){const t=Math.min(KN,JN*2**(s-1));return Math.floor(Math.random()*(t+1))},Gu=new WeakSet,UT=function(s){return new Promise(t=>{var e;g(this,Rn,t),g(this,yi,a(this,Xs).setTimeout(()=>{g(this,yi,void 0),g(this,Rn,void 0),t()},I(e=_v,ju,$T).call(e,s)))})},zc=new WeakSet,lm=function(){var s;a(this,yi)!==void 0&&(a(this,Xs).clearTimeout(a(this,yi)),g(this,yi,void 0)),(s=a(this,Rn))==null||s.call(this),g(this,Rn,void 0)},Yc=new WeakSet,um=function(s,t){!a(this,At)||s!==a(this,It)||(t&&this.logger.error("SocketService::Reconnect loop failed",{error:t}),g(this,At,!1),I(this,Jc,cm).call(this),g(this,Qs,void 0),a(this,ut,Ot).updateSocketConnectionState("failed"),a(this,We).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_FAILED))},Qc=new WeakSet,hm=function(s){!a(this,At)||a(this,Ei)===s||(g(this,Ei,s),a(this,ut,Ot).updateSocketConnectionState("reconnecting"),I(this,Wu,FT).call(this,s).catch(t=>I(this,Yc,um).call(this,s,t)))},Wu=new WeakSet,FT=async function(s){try{for(let t=1;t<=WN;t+=1){if(!a(this,At)||s!==a(this,It)||(await I(this,Gu,UT).call(this,t),!a(this,At)||s!==a(this,It)))return;this.updateURL(ki()),this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:t}}),a(this,ut,Ot).updateSocketConnectionState("reconnectAttempt",t);try{if(await a(this,Ie).connect(!0),!a(this,At)||s!==a(this,It))return;if(!this.isConnected)throw new Error("Reconnect failed");I(this,Kc,dm).call(this,this.peerId),g(this,Qs,this.peerId),a(this,ut,Ot).updateSocketConnectionState("reconnected"),a(this,We).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_RECONNECTED,{wasSocketJoinAttempted:a(this,ut,Ot).socketJoinAttempted,wasMediaJoinAttempted:a(this,ut,Ot).mediaJoinAttempted});return}catch(e){if(!a(this,At)||s!==a(this,It))return;this.logger.error(`Websocket connection retry attempt ${t} failed with URL: ${a(this,In,wd)}`,{error:e,socket:{retryAttempt:t}}),a(this,ut,Ot).updateSocketConnectionState("reconnectFailure",t)}}I(this,Yc,um).call(this,s)}finally{a(this,Ei)===s&&g(this,Ei,void 0)}},Xc=new WeakSet,pm=function(){return this.isConnected&&a(this,Qa)===this.peerId},Zc=new WeakSet,mm=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},m(xp,ju),xp);let Vo=_v;$l([y.trace("SocketService.connect")],Vo.prototype,"connect",1),$l([y.trace("SocketService.disconnect")],Vo.prototype,"disconnect",1),$l([y.trace("SocketService.sendMessagePromise")],Vo.prototype,"sendMessagePromise",1),$l([y.trace("SocketService.sendMessagePromiseWithTimeout")],Vo.prototype,"sendMessagePromiseWithTimeout",1);class zN{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=w0.fromBinary(t),r=e.meetings.map(o=>{var c;return{id:o.id,title:o.title,participants:(c=o.participants)!=null?c:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(n=e.parentMeeting.participants)!=null?n:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=z0.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=nS.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return iS.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return U0.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise($.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise($.createConnectedRooms,C0.toBinary({payloads:t}));return iS.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}async updateConnectedRooms(t){}async disableConnectedRooms(t){const e=t.map(i=>({id:i})),r=await this.socketService.sendMessagePromise($.deleteConnectedRooms,x0.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise($.movePeers,G0.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}}}var YN=Object.defineProperty,QN=Object.getOwnPropertyDescriptor,XN=(s,t,e,r)=>{for(var i=r>1?void 0:r?QN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&YN(t,e,i),i};class kv extends Ft{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);m(this,Zt,void 0);g(this,Zt,e)}get isActive(){return this.meetings.length!==0}validateAlterAction(){const e=a(this,Zt).getValue("self").permissions.connectedMeetings;if(!(e!=null&&e.canAlterConnectedMeetings))throw new Error("You are not allowed to perform this action. Please enable canAlterConnectedMeetings permission in your preset.")}validateMoveAction(e,r){var d;if(!(r!=null&&r.length))throw new Error("You're trying to move participants with an empty list.");const i=a(this,Zt).getValue("self").permissions.connectedMeetings;if(!i)throw new Error("You are not allowed to perform this action. Please enable connected meetings permissions in your preset.");if(i.canAlterConnectedMeetings)return;const n=a(this,Zt).getValue("userId");if(!(r.length===1&&r[0]===n))throw new Error("You are not allowed to move other participants. Please enable canAlterConnectedMeetings permission in your preset.");if(e===((d=this.parentMeeting)==null?void 0:d.id)){if(!i.canSwitchToParentMeeting)throw new Error("You are not allowed to move to the parent meeting. Please enable canSwitchToParentMeeting permission in your preset.");return}if(!i.canSwitchConnectedMeetings)throw new Error("You are not allowed to move to a connected meeting. Please enable canSwitchConnectedMeetings permission in your preset.")}async getConnectedMeetings(){this.logger.info("Getting connected meetings dump");const e=await a(this,Zt).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateAlterAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await a(this,Zt).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateAlterAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await a(this,Zt).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)}async deleteMeetings(e){this.validateAlterAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),await Promise.all(r);const i=await a(this,Zt).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateMoveAction(r,i),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,Zt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return n.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),n}async moveParticipantsWithCustomPreset(e,r,i){this.validateMoveAction(r,i.map(o=>o.id)),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,Zt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return n.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),n}moveSuccessHandler(e,r,i){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>n.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>n.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>n.get(d)));return{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}Zt=new WeakMap,XN([qt({maxInvocations:60,period:60})],kv.prototype,"getConnectedMeetings",1);var ZN=Object.defineProperty,eL=Object.getOwnPropertyDescriptor,Np=(s,t,e,r)=>{for(var i=r>1?void 0:r?eL(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ZN(t,e,i),i};const Cv=(Jv=class{constructor(s){p(this,"connectedMeetings");m(this,be,void 0);g(this,be,s),this.connectedMeetings=new kv(s)}get telemetry(){return a(this,be).getValue("telemetry")}get logger(){return a(this,be).getValue("logger")}static init(s){const t=new Cv(s);return s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings()),t.setupEvents(),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,be).getValue("connectedMeetingsSocketHandler").socketService.on($.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,be).getValue("connectedMeetingsSocketHandler").socketService.on($.transferPeer,this.handleTransferPeer.bind(this)),a(this,be).getValue("connectedMeetingsSocketHandler").socketService.on($.movedPeer,this.handleMovedPeer.bind(this)),a(this,be).getValue("connectedMeetingsSocketHandler").socketService.on($.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,be).getValue("connectedMeetingsSocketHandler").socketService.on($.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=a(this,be).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,n,o,c;this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:a(this,be).getValue("self").videoEnabled,audio:a(this,be).getValue("self").audioEnabled};try{a(this,be).getValue("self").cleanupEvents(),await a(this,be).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,be).getValue("meeting"))==null?void 0:i.meta)==null?void 0:n.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await Iv.init({...a(this,be).getValue("options"),cachedUserDetails:null,defaults:{...a(this,be).getValue("options").defaults,...e,mediaHandler:a(this,be).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=a(this,be).getValue("self");r.self.setName(a(this,be).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=a(this,be).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return a(this,be).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,be).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s),e=new Map;this.connectedMeetings.meetings.forEach(r=>{e.set(r.id,r)}),t.forEach(r=>{e.has(r.id)?e.get(r.id).title=r.title:e.set(r.id,{...r,participants:[]})}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=a(this,be).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},be=new WeakMap,Jv);let Ul=Cv;Np([y.trace("ConnectedMeetingsController.getConnectedMeetings")],Ul.prototype,"getConnectedMeetings",1),Np([y.trace("ConnectedMeetingsController.setupEvents")],Ul.prototype,"setupEvents",1),Np([y.trace("ConnectedMeetingsController.switchMeeting")],Ul.prototype,"switchMeeting",1);var tL=Object.defineProperty,sL=Object.getOwnPropertyDescriptor,Lp=(s,t,e,r)=>{for(var i=r>1?void 0:r?sL(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&tL(t,e,i),i};const xo=class{constructor(s,t,e){p(this,"apiBase");p(this,"selfController");p(this,"pollController");p(this,"chatController");p(this,"metaController");p(this,"storesManager");p(this,"stageController");p(this,"pluginController");p(this,"internalsController");p(this,"recordingController");p(this,"livestreamController");p(this,"participantController");p(this,"connectedMeetingsController");p(this,"telemetry");p(this,"logger");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController,this.connectedMeetingsController=t.connectedMeetingsController,this.telemetry=e.getValue("telemetry"),this.logger=e.getValue("logger")}static async init(s){var F,U;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(pN(s),Pe.isSupported()===!1)throw new C("Browser not supported","0010",c,!0);const d=jO(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(n),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new kD(s);s.setValue("connectionHandler",l);let u="",h=null;c.info("CF SFU is being used.");const f=xo.createSocketService(s),S=f.connect();S.catch(()=>{});const E=d.getUserDetails();try{h=await E,u=((F=h.meeting)==null?void 0:F.title)||"",s.setValue("presetName",h.preset.name)}catch(B){throw c.error("Failed to get user details",{error:B}),f.disconnect(),B instanceof ul?B.status===401?new C("Unauthorized. The auth token may be invalid or expired. (401)","0004"):B.status===403?new C("Access denied. Insufficient permissions to join the meeting. (403)","0004"):B.status===404?(c.error("[ERROR:0004] participant-details returned 404."),new C("The auth token is not associated with an active participant in this meeting. The meeting may have ended, or the participant may no longer exist. (404)","0004")):B.status>=500?new C(`The server encountered an error. Try again. (${B.status})`,"0001"):B.isHttpError?new C(`Request rejected by the server. (${B.status})`,"0001"):B.isTimeout?new C("Connection timed out. Check the network and try again.","0001"):new C("Unable to connect to the server. Check the internet connection.","0001"):new C((B==null?void 0:B.message)||"Failed to initialize.","0001")}try{await S}catch(B){c.error("[Controller]: Failed to connect to socket server:",{error:B})}const k=pp.init(h.preset,!s.getValue("modules").theme);s.setValue("theme",k);const R=gp.init(s,k.viewType,h.preset.permissions),D=xo.setupControllers(f,s,h,u,k,R);mD(k)&&((U=xo.createRoomNodeClient(s,f).initializeConnection(h.participant.name,i,!1,R))==null||U.catch(Z=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:Z})}));const{controllers:N}=await D;return sC(),new xo(e,N,s)}static async setupControllers(s,t,e,r,i,n){var fe,V,_;const o=t.getValue("modules"),{participant:c}=e,d=t.getValue("defaults"),l=t.getValue("logger"),{viewType:u,mediaConstraints:{audio:h}}=i;t.setValue("viewType",u),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(fe=h.enableHighBitrate)!=null?fe:!1,enableStereo:(V=h.enableStereo)!=null?V:!1}},...d}),t.setValue("maxPreferredStreams",Pe.isMobile()?i.maxVideoStreams.mobile:i.maxVideoStreams.desktop);let f,S,E,k,R,D,N,F,U;const B=new SN(t,s),Z=new zN(s);t.setValue("connectedMeetingsSocketHandler",Z);const ie=new Cl(t,s),H=new dr(t,s),re=new wN(s),we=new rv(t,s),St=new PN(t,s),A=new fN(s),v=await Kr.init(t,we,c,n,i);t.setValue("selfController",v);const w=await _S.init(t,v.self,we,B,r);o.participant&&(F=new pr(t,v.self,we)),(_=o.e2ee)!=null&&_.enabled&&o.e2ee.manager.init(l,t.getValue("peerSessionStore")),o.chat&&(S=await vo.init(t,H,v.self,F.participants)),o.internals&&(R=await op.init(t)),o.livestream&&i.viewType===vs.Livestream&&(N=new WS(t,v.self,A)),o.poll&&(f=await bS.init(t,v.self,ie)),o.recording&&(D=new OS(t,v.self,we)),o.stage&&(E=new kS(t,re,we,v.self,F.participants));const x=new P1(t,St);if(o.plugin){if(!F)throw new C("The plugin module cannot be initialized without the `participant` module","0102");const He=d.plugins||[];k=await AS.init(t,He,v.self,x)}if(o.connectedMeetings&&(U=await Ul.init(t)),o.pip){const He=await Ih._init(t,v.self);t.setValue("pip",He)}return{theme:i,permissions:n,controllers:{storesManager:x,pollController:f,selfController:v,metaController:w,chatController:S,stageController:E,pluginController:k,recordingController:D,internalsController:R,livestreamController:N,participantController:F,connectedMeetingsController:U}}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return tv(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=[];return new Vo(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Fl=xo;Lp([y.trace("Controller.init")],Fl,"init",1),Lp([y.trace("Controller.createRoomNodeClient")],Fl,"createRoomNodeClient",1),Lp([y.trace("Controller.createSocketService")],Fl,"createSocketService",1);class rL{constructor(){p(this,"battery");p(this,"logger");p(this,"init",async t=>{this.logger=t;try{"getBattery"in navigator&&(this.battery=await navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){t.error("Error getting battery",e)}});p(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});p(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});p(this,"cleanup",()=>{var t,e;"getBattery"in navigator&&((t=this.battery)==null||t.removeEventListener("chargingchange",this.updateChargeInfo),(e=this.battery)==null||e.removeEventListener("levelchange",this.updateLevelInfo))})}}const Rv=new rL;class iL{constructor(){m(this,Ju);m(this,bi,new Audio);m(this,An,new MediaStream);m(this,Mn,new Map);m(this,ed,void 0);a(this,bi).srcObject=a(this,An),a(this,bi).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,Mn).has(e.id)||(a(this,An).addTrack(e),a(this,Mn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,bi).setSinkId(t)}removeTrack(t){const e=a(this,Mn).get(t);e&&(a(this,An).removeTrack(e),a(this,Mn).delete(t))}async play(){return a(this,bi).srcObject=a(this,An),a(this,bi).play().catch(t=>{I(this,Ju,BT).call(this,t)})}onError(t){g(this,ed,t)}}bi=new WeakMap,An=new WeakMap,Mn=new WeakMap,ed=new WeakMap,Ju=new WeakSet,BT=function(t){var e;(e=a(this,ed))==null||e.call(this,t)};class nL extends iL{constructor(){super();m(this,Zs,void 0);g(this,Zs,new Map)}addParticipantTrack(e,r){a(this,Zs).set(e,r.id),this.playTracks([r])}reassignParticipantTrack(e,r){const i=a(this,Zs).get(e);i&&(a(this,Zs).delete(e),a(this,Zs).set(r,i))}removeParticipantTrack(e){const r=a(this,Zs).get(e);r&&this.removeTrack(r),a(this,Zs).delete(e)}}Zs=new WeakMap;var aL=Object.defineProperty,oL=Object.getOwnPropertyDescriptor,Bl=(s,t,e,r)=>{for(var i=r>1?void 0:r?oL(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&aL(t,e,i),i};let Zr=(Kv=class{constructor(t,e){m(this,qe,void 0);m(this,On,void 0);g(this,On,t),g(this,qe,e)}get peerId(){return a(this,On).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:ki(),n=Fr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new KS(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var f,S,E,k,R,D,N;Pe.init();const e=(S=(f=t==null?void 0:t.cachedUserDetails)==null?void 0:f.peerId)!=null?S:ki(),{authToken:r,baseURI:i}=t,{meetingId:n,...o}=FN(r,i);if((E=o.baseURI)!=null&&E.includes("dyte.io"))throw new C("Dyte Base URIs are no longer supported. Use RealtimeKit Base URIs.","0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=Zr.setupContext(e,t,n,o),d=c.getValue("telemetry"),l=c.getValue("logger");GT(l),Rv.init(l),d.init(c,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(R=(k=t.modules)==null?void 0:k.tracing)!=null?R:!0,(N=(D=t==null?void 0:t.modules)==null?void 0:D.devTools)==null?void 0:N.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:wv(t.authToken)}});const u=await Fl.init(c),h=new Zr(c,u);return c.setValue("meeting",h),l.info(`Meeting view type: ${h.meta.viewType}`),h}static setupContext(t,e,r,i){var d,l;const n=Fr.createContext(t,e),o={...Dk,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return n.setValue("options",e),n.setValue("peerId",t),n.setValue("modules",o),n.setValue("sdkName","web-core"),n.setValue("meetingId",r),n.setValue("apiBase",i.apiBase),n.setValue("baseURI",i.baseURI),n.setValue("userId",i.participantId),n.setValue("organizationId",i.orgId),n.setValue("authToken",e.authToken),n.setValue("overrides",(d=e.overrides)!=null?d:{}),n.setValue("env",Nk({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Ls(e.cachedUserDetails)),n.setValue("sdkVersion","2.0.4"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new nL),n}async join(){const{selfController:t}=a(this,qe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){var r;Rv.cleanup(),a(this,On).getValue("peerSessionStore").reset(),(r=a(this,qe).pluginController)==null||r.cleanup();const{selfController:e}=a(this,qe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,qe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,qe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,qe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,qe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,qe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,qe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,qe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,qe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,qe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,qe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,qe).stageController)==null?void 0:t.stage}get stores(){return a(this,qe).storesManager}get audio(){return a(this,On).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,qe).internalsController)==null?void 0:t.internals}},qe=new WeakMap,On=new WeakMap,Kv);Bl([pt("0002"),ur.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Zr.prototype,"join",1),Bl([pt("0003")],Zr.prototype,"leave",1),Bl([pt("0001"),ur.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Zr,"init",1),Zr=Bl([pt("0000")],Zr);const Iv=Zr;return Iv}();
|