@cloudflare/realtimekit 2.1.0-staging.6 → 2.1.1-staging.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.rn.js CHANGED
@@ -6,4 +6,4 @@ b=AS:${this.constrainVideoBitrateKbps}\r
6
6
  ${this.message}`;try{let l=a&&!!i;r&&r.endsWith("00")&&i&&(l=!0),l&&i.error("ClientError",{error:{message:this.message,name:this.name,code:r}});const u=ii.getContext(ii.getMostRecentPeerId());if(u){const h=u.getValue("onError");try{h(this)}catch(f){}}typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("ClientError",{detail:this}))}catch(l){}}}function od(s,t,e,r){if(r instanceof C)throw r;if(r instanceof t){const i=new C(r.message,e);throw i.stack=r.stack,i}else throw r}function hg(s,t,e){if(!s.value){const i=s.get,a=s.set;return i&&(s.get=function(){try{return i.apply(this)}catch(o){od(this,t,e,o)}}),a&&(s.set=function(o){try{return a.apply(this,[o])}catch(c){od(this,t,e,c)}}),s}const r=s.value;return s.value=function(...i){try{const a=r.apply(this,i);return a&&a instanceof Promise?a.catch(o=>{od(this,t,e,o)}):a}catch(a){od(this,t,e,a)}},s}function AC(s,t){return(e,r,i)=>{if(i)return hg(i,s,t);for(const a of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,a);(o.value instanceof Function||o.get instanceof Function||o.set instanceof Function)&&Object.defineProperty(e.prototype,a,hg(o,s,t))}}}const it=s=>AC(Error,s);var hs=(s=>(s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT",s))(hs||{}),j=(s=>(s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST",s))(j||{}),Zg;typeof process!="undefined"&&(Zg=process==null?void 0:process.env)!=null&&Zg.FLAGSMITH_ENVIRONMENT_KEY&&process.env.FLAGSMITH_ENVIRONMENT_KEY;var Df=[-2,-1,0,1,2],IC=[0,1,2,3,4];function DC(s){s=s.trim();let t="0",e="0",r="0";return s.length==4?(t=`0x${s[1]}${s[1]}`,e=`0x${s[2]}${s[2]}`,r=`0x${s[3]}${s[3]}`):s.length>6&&(t=`0x${s[1]}${s[2]}`,e=`0x${s[3]}${s[4]}`,r=`0x${s[5]}${s[6]}`),[+t,+e,+r]}var OC=(s,t,e)=>{let r,i,a;if(t==0)r=i=a=e;else{const o=(l,u,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?l+(u-l)*6*h:h<.5?u:h<.6666666666666666?l+(u-l)*(.6666666666666666-h)*6:l),c=e<.5?e*(1+t):e+t-e*t,d=2*e-c;r=o(d,c,s+1/3),i=o(d,c,s),a=o(d,c,s-1/3)}return[Math.round(r*255),Math.round(i*255),Math.round(a*255)]},NC=(s,t,e)=>{s/=255,t/=255,e/=255;const r=Math.max(s,t,e),i=Math.min(s,t,e);let a,o;const c=(r+i)/2;if(r==i)a=o=0;else{const d=r-i;switch(o=c>.5?d/(2-r-i):d/(r+i),r){case s:a=(t-e)/d+(t<e?6:0);break;case t:a=(e-s)/d+2;break;case e:a=(s-t)/d+4;break}a/=6}return[a,o,c]},LC=(s,t,e)=>{const r=i=>i.toString(16).padStart(2,"0");return`#${r(s)}${r(t)}${r(e)}`},Of=(s,t=Df,e=.4)=>{const r=[],[i,a,o]=DC(s),[c,d,l]=NC(i,a,o),u=Math.round(l*100);u>70?e=.8:u>60?e=.9:u<10?e=.075:u<42&&(e=.3);const h=t.findIndex(M=>M===0);if(h===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const f=5-h,S=h+1,E=(100-u)/f,R=u/S;for(const M of t){let D;M<0?D=u+M*R*e:M>0?D=u+M*E*e:D=u;const[I,x,$]=OC(c,d,D/100);r.push(LC(I,x,$))}return r},pg={dark:{background:{1e3:"#252525",900:"#2F2F2F",800:"#323232",700:"#3E3E3E",600:"#4A4A4A"},text:"#F5F5F5","video-bg":"#1C1C1C"},light:{background:{1e3:"#FFFFFF",900:"#F5F5F5",800:"#EBEBEB",700:"#E0E0E0",600:"#D6D6D6"},text:"#111111","text-on-brand":"#ffffff","video-bg":"#DADADA"}},VC=s=>{const[t,e,r,i,a]=Of(s,Df);return{300:t,400:e,500:r,600:i,700:a}},$C=s=>{if(s==="#FFFFFF")return pg.light.background;if(s==="#000000")return pg.dark.background;const[t,e,r,i,a]=Of(s,IC);return{1e3:t,900:e,800:r,700:i,600:a}},xC={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:VC("#2160FD"),background:$C("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function Nf(){return sp(xC)}var UC={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED",can_consume:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED",can_consume:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1},channel:{can_create:"ALL",can_delete:"ALL",can_update:"ALL",can_read_all:!1},message:{can_delete:"ALL",can_edit:"ALL",delete_cutoff_time_seconds:0,edit_cutoff_time_seconds:0}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{oldTheme:{setup_screen:{is_enabled:!1},alone_here:{is_enabled:!1},waiting_room:{is_enabled:!1,enable_preview:!0},control_bar:{is_enabled:!0,elements:{plugins:!0,screenshare:!0,invite:!1,participants:!0,chat:!0,reactions:!1,polls:!0,fullscreen:!0,layout:!0}},header:{is_enabled:!0,elements:{timer:!0,title:!0,participant_count:!0,change_layout:!0}},pip_mode:!0,auto_tune:!0,colors:{primary:"#2160FD",secondary:"#1A1A1A",text:"#EEEEEE",background:"#1A1A1A",textPrimary:"#EEEEEE",videoBackground:"#1A1A1A"},dimensions:{mode:"fillParent"},grid:{multi:{maxVideoCount:6,videoFit:"cover"},single:{maxVideoCount:6,videoFit:"cover"},defaultView:"MULTI"},controls:{pip_toggle:!1},plugins:[]},design_tokens:Nf(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:30,simulcast:!1},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"hybrid"};function HC(){return sp(UC)}var BC={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{design_tokens:Nf(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:30,simulcast:!1},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"2.0.0"};function ap(){return sp(BC)}function FC(){ye.isElectron()&&window.electronGetDisplayMediaSource&&(navigator.mediaDevices.getDisplayMedia=async()=>{const s=await window.electronGetDisplayMediaSource({types:["window","screen"]});let t=[];if(s&&(Array.isArray(s)?t=s:t=[s]),!(t!=null&&t.length))throw new Error("Couldn't find any media source for screen share.");let e=t.find(a=>{var o;return(o=a.id)==null?void 0:o.includes("screen")});e=e!=null?e:t[0];const r={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e.id}}};return await navigator.mediaDevices.getUserMedia(r)})}var w=(s=>(s.NEW_PRODUCER="NEW_PRODUCER",s.PRODUCER_HANDOVER="PRODUCER_HANDOVER",s.ROOM_NODE_CONNECTION_ERROR="ROOM_NODE_CONNECTION_ERROR",s.SOCKET_SERVICE_ROOM_JOINED="SOCKET_SERVICE_ROOM_JOINED",s.SOCKET_SERVICE_RECONNECTED="SOCKET_SERVICE_RECONNECTED",s.SOCKET_SERVICE_DISCONNECTED="SOCKET_SERVICE_DISCONNECTED",s.SOCKET_SERVICE_FAILED="SOCKET_SERVICE_FAILED",s.SOCKET_STATE_UPDATE="SOCKET_STATE_UPDATE",s.ROOM_NODE_RECONNECTED="ROOM_NODE_RECONNECTED",s.ROOM_NODE_DISCONNECTED="ROOM_NODE_DISCONNECTED",s.ROOM_NODE_FAILED="ROOM_NODE_FAILED",s.MEDIA_ROOM_JOIN_FAILED="MEDIA_ROOM_JOIN_FAILED",s.TRANSPORT_STATE_UPDATE="TRANSPORT_STATE_UPDATE",s.PRODUCER_SCORE_UPDATE="PRODUCER_SCORE_UPDATE",s.CONSUMER_SCORE_UPDATE="CONSUMER_SCORE_UPDATE",s.PRODUCER_STATUS_UPDATE="PRODUCER_STATUS_UPDATE",s.CONSUMER_STATUS_UPDATE="CONSUMER_STATUS_UPDATE",s.LOW_CONSUMER_SCORE="LOW_CONSUMER_SCORE",s.MEDIA_PERMISSION_ERROR="MEDIA_PERMISSION_ERROR",s.MEDIA_PERMISSION_UPDATE="MEDIA_PERMISSION_UPDATE",s.MESSAGE="websocket/message",s.ROOM_MESSAGE="websocket/room-message",s.PEER_JOINED_INTERNAL="peer/joined-internal",s.PEER_CLOSED="websocket/peer-closed",s.CONSUMER_CLOSED="websocket/consumer-closed",s.CONSUMER_PAUSED="websocket/consumer-paused",s.CONSUMER_RESUMED="websocket/consumer-resumed",s.NEW_CONSUMER_CREATED="NEW_CONSUMER_CREATED",s.PRODUCER_CLOSED="websocket/producer-closed",s.PRODUCER_SCORE="websocket/producer-score",s.CONSUMER_SCORE="websocket/consumer-score",s.PRODUCER_TOGGLE="cf/producer-toggle",s.UPDATE_ACTIVE="media/update-active",s.RESET_PRODUCER_STATE="cf/reset-producer-state",s.ROOM_STATE="sockethub/room-state",s.GET_STAGE_REQUESTS="GET_STAGE_REQUESTS",s.UPDATE_STAGE_REQUESTS="UPDATE_STAGE_REQUESTS",s.KICK_PEER="KICK_PEER",s.UPDATE_PEER_STAGE_STATUS="UPDATE_PEER_STAGE_STATUS",s.JOIN_MEDIA_ROOM="JOIN_MEDIA_ROOM",s.LEAVE_MEDIA_ROOM="LEAVE_MEDIA_ROOM",s.PIP_HANGUP="PIP_HANGUP",s.E2EE_ACTIVE_PRODUCER="E2EE_ACTIVE_PRODUCER",s.E2EE_INACTIVE_PRODUCER="E2EE_INACTIVE_PRODUCER",s.E2EE_ACTIVE_CONSUMER="E2EE_ACTIVE_CONSUMER",s.E2EE_INACTIVE_CONSUMER="E2EE_INACTIVE_CONSUMER",s.ENABLE_E2EE_CRYPTOR_ON_NEW_CONSUMER="ENABLE_E2EE_CRYPTOR_ON_NEW_CONSUMER",s.SOCKET_PEERS="SOCKET_PEERS",s.UPDATE_PERMISSIONS="UPDATE_PERMISSIONS",s.MAX_SPATIAL_LAYER_CHANGE="MAX_SPATIAL_LAYER_CHANGE",s.MUTE_SELF="MUTE_SELF",s.MUTE_SELF_VIDEO="MUTE_SELF_VIDEO",s))(w||{});const gg=(s,t)=>!s.includes("currentColor")||!t?s:s.replace(/currentColor/g,t);function jC(s,t=2){return s.replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w\s]/g,"").trim().split(/\s+/).slice(0,t).map(i=>i.charAt(0)).join("").toUpperCase()}const mg=1080,fg=1920,qC=(s,t,e,r,i,a)=>{let o=.5,c=.5;const d=i,l=a,u=Math.min(e/d,r/l);let h=d*u,f=l*u,S,E,R,M,D=1;return h<e&&(D=e/h),Math.abs(D-1)<1e-14&&f<r&&(D=r/f),h*=D,f*=D,R=d/(h/e),M=l/(f/r),S=(d-R)*o,E=(l-M)*c,S<0&&(S=0),E<0&&(E=0),R>d&&(R=d),M>l&&(M=l),[S,E,R,M,s,t,e,r]};var yt,Or,st,jt,_e,qt,qs,Ne,Me,On,Nn,Ln,Gs,Vn,Jd,No;const kp=class extends xt{constructor(e,r,i,a){const o=e.getValue("logger");super(o);g(this,yt,void 0);g(this,Or,void 0);g(this,st,void 0);g(this,jt,void 0);g(this,_e,{height:mg,width:fg});g(this,qt,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});g(this,qs,void 0);g(this,Ne,{});g(this,Me,void 0);g(this,On,void 0);g(this,Nn,void 0);g(this,Ln,void 0);g(this,Gs,void 0);g(this,Vn,!1);g(this,Jd,e=>{const r=n(this,On);if(m(this,On,e),!r||r===e)return;const i=n(this,Ne)[r];i&&(delete n(this,Ne)[r],!n(this,Ne)[e]&&(n(this,Ne)[e]={...i,id:e}))});p(this,"cleanupEventListeners",()=>{n(this,Or).unsubscribe("stageStatus",this.handlePipMediaControls),n(this,Me).removeListener("videoUpdate",this.onSelfVideoUpdateListener),n(this,Me).removeListener("audioUpdate",this.onSelfAudioUpdateListener),n(this,Me).removeListener("roomLeft",n(this,No))});g(this,No,({state:e})=>{e!=="disconnected"&&this.disable()});p(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()});p(this,"onSelfVideoUpdateListener",({videoEnabled:e})=>{this.updateMediaSession("CAMERA",e)});p(this,"onSelfAudioUpdateListener",({audioEnabled:e})=>{this.updateMediaSession("MIC",e)});p(this,"handlePipMediaControls",e=>{e==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()});p(this,"eventCallback",e=>{e==="CAMERA"&&(n(this,Me).videoEnabled?n(this,Me).disableVideo():n(this,Me).enableVideo(),this.emit("cameraToggled")),e==="MIC"&&(n(this,Me).audioEnabled?n(this,Me).disableAudio():n(this,Me).enableAudio(),this.emit("micToggled")),e==="END"&&(n(this,Or).getValue("peerSessionStore").emit(w.PIP_HANGUP),this.cleanupEventListeners(),this.emit("hangup"),this.cleanup())});p(this,"unmountEvents",()=>{navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("togglemicrophone",void 0),navigator.mediaSession.setActionHandler("togglecamera",void 0))});p(this,"animate",()=>{if(!this.isActive&&n(this,Gs)==="active"){this.disable(!0);return}n(this,Ne)!==void 0&&this.paintCanvas(),n(this,qs)!==void 0&&m(this,qs,requestAnimationFrame(()=>this.animate()))});p(this,"disable",(e=!1)=>{m(this,Gs,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(n(this,qs)),e!==!0&&document.body.removeChild(n(this,st)),m(this,qs,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});m(this,Or,e),m(this,Gs,"idle"),m(this,Me,r),m(this,On,e.getValue("peerId")),n(this,Or).subscribe("peerId",n(this,Jd)),m(this,qt,{brand:r.config.designTokens.colors.brand[500],background:r.config.designTokens.colors.background[1e3],text:r.config.designTokens.colors.text,videoBackground:r.config.designTokens.colors.videoBg,textOnBrand:r.config.designTokens.colors.textOnBrand}),i&&this.setupIcon("pin",i),a&&this.setupIcon("handRaise",a)}static async _init(e,r){var o,c,d;let i,a;try{const l=(d=(c=(o=r.config)==null?void 0:o.designTokens)==null?void 0:c.colors)==null?void 0:d.textOnBrand;i=await ad(gg(PC,l)),a=await ad(gg(wC,l))}catch(l){}return new kp(e,r,i,a)}async setupIcon(e,r){switch(e){case"handRaise":m(this,Ln,r);break;case"pin":m(this,Nn,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":m(this,Ln,await ad(r));break;case"pin":m(this,Nn,await ad(r));break}}constructImage(e){const r=new Image,i=new Blob([e],{type:"image/svg+xml"}),a=window.URL.createObjectURL(i);return new Promise(o=>{r.onload=()=>{o(r),window.URL.revokeObjectURL(a)},r.src=a})}createVideoContainer(){m(this,st,document.createElement("div")),n(this,st).style.width="0.1px",n(this,st).style.height="0.1px",n(this,st).style.overflow="hidden",n(this,st).style.position="absolute",n(this,st).style.bottom="0",n(this,st).style.right="0",n(this,st).style.opacity="0",n(this,st).appendChild(n(this,jt))}setupEventListeners(){n(this,Or).subscribe("stageStatus",this.handlePipMediaControls),n(this,Me).addListener("videoUpdate",this.onSelfVideoUpdateListener),n(this,Me).addListener("audioUpdate",this.onSelfAudioUpdateListener),n(this,Me).addListener("roomLeft",n(this,No))}createCanvas(){const e=document.createElement("canvas");e.height=n(this,_e).height,e.width=n(this,_e).width,m(this,yt,e)}setupMediaSessionEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("hangup",()=>{this.eventCallback("END")}),this.mountAudioEvents(),this.mountVideoEvents())}mountAudioEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setMicrophoneActive===void 0||n(this,Me).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||n(this,Me).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const r=Object.values(n(this,Ne)).reduce((i,a)=>(i[a.pinned?"pinned":"regular"].push(a),i),{pinned:[],regular:[]});return[...r.pinned,...r.regular]}drawEmptyTile(e,r,i,a){if(n(this,yt)===void 0)return;const o=n(this,yt).getContext("2d"),c=n(this,yt).width,d=0,l=0,u=r-d*2,h=i-d*2,f=Math.floor(c/u),S=Math.floor(e/f),R=e%f*(u+d)+d,M=S*(h+d)+d,{displayText:D,image:I}=a!=null?a:{};o.fillStyle=D||I?n(this,qt).videoBackground:n(this,qt).background,o.strokeStyle=n(this,qt).brand,o.beginPath(),o.moveTo(R+l,M),o.arcTo(R+u,M,R+u,M+l,l),o.arcTo(R+u,M+h,R+u-l,M+h,l),o.arcTo(R,M+h,R,M+h-l,l),o.arcTo(R,M,R+l,M,l),o.closePath(),o.fill(),o.stroke();const x=u/6,$=u/2+R,B=h/2+M;o.save(),(D||I)&&(o.beginPath(),o.arc($,B,x,0,Math.PI*2),o.fillStyle=n(this,qt).brand,o.fill(),I?(o.clip(),o.drawImage(I,$-x,B-x,x*2,x*2),o.restore()):D&&(o.fillStyle=n(this,qt).textOnBrand,o.font=`${x/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(D,$,B)),this.drawIcons(a,R,M,Math.max(u,h)))}drawIcons(e,r,i,a){const o=Math.min(Math.max(a*.15,100),200),c=o*.2,d=o*.2;let l=r+c;const u=i+c,h=f=>{const S=n(this,yt).getContext("2d");S.save(),S.fillStyle=n(this,qt).background,S.beginPath(),S.moveTo(l+d,u),S.arcTo(l+o,u,l+o,u+d,d),S.arcTo(l+o,u+o,l+o-d,u+o,d),S.arcTo(l,u+o,l,u+o-d,d),S.arcTo(l,u,l+d,u,d),S.closePath(),S.fill(),typeof f=="string"?(S.font=`${o/1.5}px sans-serif`,S.fillStyle=n(this,qt).text,S.textAlign="center",S.textBaseline="top",S.fillText(f,o/2+l,u+c)):S.drawImage(f,l+c,u+c,o-c*2,o-c*2),l+=o+c,S.restore()};e.pinned&&h(n(this,Nn)),e.handRaised&&h(n(this,Ln)),e.reaction&&h(e.reaction)}drawTile(e,r,i){var l,u;if(n(this,yt)===void 0)return;const a=n(this,yt).getContext("2d");a.fillStyle=n(this,qt).background,a.fillRect(0,0,n(this,yt).width,n(this,yt).height);const o=this.getSources();let c=0,d=0;for(;c<n(this,_e).height-5;){let h=0;for(;h<n(this,_e).width-5&&d<i;){if((l=o[d])!=null&&l.enabled){const f=o[d].element,[S,E,R,M,D,I,x,$]=qC(h,c,e,r,f.videoWidth,f.videoHeight);((u=f==null?void 0:f.classList)==null?void 0:u.contains("mirror"))?(a.save(),a.scale(-1,1),a.drawImage(f,S,E,R,M,-1*D,I,-1*x,$),a.restore()):a.drawImage(f,S,E,R,M,D,I,x,$),this.drawIcons(o[d],D,I,Math.max(x,$))}else this.drawEmptyTile(d,e,r,o[d]);d+=1,h+=e}c+=r}}calcGridElemSize(e){switch(e){case 0:case 1:return[n(this,_e).width,n(this,_e).height];case 2:return[Math.floor(n(this,_e).width/2),n(this,_e).height];case 3:case 4:return[Math.floor(n(this,_e).width/2),Math.floor(n(this,_e).height/2)];case 5:case 6:return[Math.floor(n(this,_e).width/3),Math.floor(n(this,_e).height/2)];case 7:case 8:case 9:return[Math.floor(n(this,_e).width/3),Math.floor(n(this,_e).height/3)];default:return[Math.floor(n(this,_e).width/3),Math.floor(n(this,_e).height/2)]}}paintCanvas(){let e=this.getSources().length;e!==1&&(e=e%2>0?e+1:e);const[r,i]=this.calcGridElemSize(e);this.drawTile(r,i,e)}isSupported(){var e;return!!window.chrome&&document.pictureInPictureEnabled&&((e=n(this,Me).config)==null?void 0:e.viewType)!=="LIVESTREAM"}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(m(this,Vn,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),n(this,st))try{document.body.removeChild(n(this,st))}catch(e){}this.removeAllSources(),m(this,yt,void 0),m(this,jt,void 0),m(this,qs,void 0)}init({height:e,width:r}={}){if(!this.isSupported())throw this.logger.error("Pip.unsupported"),new Error("Picture-in-picture is not available in this environment");if(n(this,Vn))return;m(this,Vn,!0),this.createCanvas();const i=document.createElement("video");m(this,_e,{height:e!=null?e:mg,width:r!=null?r:fg}),i.height=n(this,_e).height,i.width=n(this,_e).width,i.autoplay=!0,i.muted=!0,i.srcObject=n(this,yt).captureStream(24),m(this,jt,i),n(this,jt).onloadedmetadata=()=>{try{this.emit("pipStarted"),n(this,jt).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(a){this.emit("pipEnded")}},this.createVideoContainer(),this.paintCanvas()}updateMediaSession(e,r){navigator.mediaSession!==void 0&&(e==="CAMERA"&&navigator.mediaSession.setCameraActive!==void 0&&navigator.mediaSession.setCameraActive(r),e==="MIC"&&navigator.mediaSession.setMicrophoneActive!==void 0&&navigator.mediaSession.setMicrophoneActive(r))}enableSource(e){n(this,Ne)[e]!==void 0&&(n(this,Ne)[e].enabled=!0)}disableSource(e){n(this,Ne)[e]!==void 0&&(n(this,Ne)[e].enabled=!1)}async generateAvatar(e,r){if(!r)return;const i=new Image;try{const a=await(await fetch(r)).blob(),o=window.URL.createObjectURL(a);i.onload=()=>{this.updateSource(e,{image:i}),window.URL.revokeObjectURL(o)},i.src=o}catch(a){this.logger.error("Pip::GenerateAvatar",{error:a})}}addSource(e,r,i,a=!1,o=void 0,c=void 0,d=!1){this.logger.debug("Pip::AddSource",{pip:{id:e,handRaised:d}}),n(this,Ne)[e]={id:e,element:r,enabled:i,pinned:a,displayText:o?jC(o):void 0,imageUrl:c,handRaised:d},c&&this.generateAvatar(e,c)}updateSource(e,r){this.logger.info("Pip::UpdateSource",{pip:{id:e,handRaised:r.handRaised,reaction:r.reaction}});const i=n(this,Ne)[e];i&&(n(this,Ne)[e]={...i,...r})}removeSource(e){delete n(this,Ne)[e]}removePinnedSource(){Object.values(n(this,Ne)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){m(this,Ne,{})}enable(){m(this,Gs,"activating"),this.setupEventListeners(),this.setupMediaSessionEvents(),this.updateMediaSession("CAMERA",n(this,Me).videoEnabled),this.updateMediaSession("MIC",n(this,Me).audioEnabled),document.body.appendChild(n(this,st)),m(this,qs,requestAnimationFrame(()=>this.animate())),n(this,jt).onloadedmetadata=()=>{n(this,jt).requestPictureInPicture().then(()=>{m(this,Gs,"active")})},n(this,jt).readyState===4&&n(this,jt).requestPictureInPicture().then(()=>{m(this,Gs,"active")})}};let qu=kp;yt=new WeakMap,Or=new WeakMap,st=new WeakMap,jt=new WeakMap,_e=new WeakMap,qt=new WeakMap,qs=new WeakMap,Ne=new WeakMap,Me=new WeakMap,On=new WeakMap,Nn=new WeakMap,Ln=new WeakMap,Gs=new WeakMap,Vn=new WeakMap,Jd=new WeakMap,No=new WeakMap;var mr;(function(s){s[s.PUBLISHER=0]="PUBLISHER",s[s.SUBSCRIBER=1]="SUBSCRIBER"})(mr||(mr={}));var Ds;(function(s){s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO"})(Ds||(Ds={}));class GC extends v.MessageType{constructor(){super("media.Codec",[{no:1,name:"channels",kind:"scalar",opt:!0,T:5},{no:2,name:"clock_rate",kind:"scalar",T:5},{no:3,name:"mime_type",kind:"scalar",T:9},{no:4,name:"sdp_fmtp_line",kind:"scalar",opt:!0,T:9},{no:5,name:"payload_type",kind:"scalar",opt:!0,T:13}])}}const Lf=new GC;class WC extends v.MessageType{constructor(){super("media.HeaderExtension",[{no:1,name:"direction",kind:"scalar",opt:!0,T:9},{no:2,name:"uri",kind:"scalar",T:9}])}}const JC=new WC;class KC extends v.MessageType{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new KC;class zC extends v.MessageType{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",mr]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const ms=new zC;class YC extends v.MessageType{constructor(){super("media.ProducerPayload",[{no:1,name:"kind",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"msid",kind:"scalar",T:9},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"mime_type",kind:"scalar",opt:!0,T:9}])}}const QC=new YC;class XC extends v.MessageType{constructor(){super("media.CreateTransportRequest",[{no:1,name:"consuming",kind:"scalar",T:8},{no:2,name:"force_tcp",kind:"scalar",opt:!0,T:8},{no:3,name:"description",kind:"message",T:()=>ms},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>QC}])}}const ZC=new XC;class eR extends v.MessageType{constructor(){super("media.AudioActivityRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"energy",kind:"scalar",T:5},{no:3,name:"silent",kind:"scalar",T:8}])}}const tR=new eR;class sR extends v.MessageType{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ms},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const Vf=new sR;class rR extends v.MessageType{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ms}])}}const iR=new rR;class nR extends v.MessageType{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ms}])}}new nR;class aR extends v.MessageType{constructor(){super("media.NestedScore",[{no:1,name:"encoding_idx",kind:"scalar",T:5},{no:2,name:"rid",kind:"scalar",T:9},{no:3,name:"score",kind:"scalar",T:5},{no:4,name:"ssrc",kind:"scalar",T:3,L:0}])}}const oR=new aR;class cR extends v.MessageType{constructor(){super("media.ProducerTrack",[{no:1,name:"track_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9},{no:3,name:"stream_id",kind:"scalar",T:9}])}}const dR=new cR;class lR extends v.MessageType{constructor(){super("media.ProducerEntry",[{no:1,name:"producing_transport_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9}])}}new lR;class uR extends v.MessageType{constructor(){super("media.ConsumerEntry",[{no:1,name:"consuming_transport_id",kind:"scalar",T:9},{no:2,name:"consumer_id",kind:"scalar",T:9}])}}new uR;class hR extends v.MessageType{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",Ds]},{no:3,name:"pause",kind:"scalar",T:8},{no:4,name:"screen_share",kind:"scalar",T:8},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9},{no:8,name:"codec",kind:"message",T:()=>Lf}])}}const Zc=new hR;class pR extends v.MessageType{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Zc},{no:3,name:"producer_track",kind:"message",T:()=>dR},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const gR=new pR;class mR extends v.MessageType{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>gR}}])}}const $f=new mR;class fR extends v.MessageType{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>Sg},{no:2,name:"receiver",kind:"message",T:()=>Sg}])}}const xf=new fR;class TR extends v.MessageType{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>Lf},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>JC}])}}const Tg=new TR;class SR extends v.MessageType{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>Tg},{no:2,name:"video",kind:"message",T:()=>Tg}])}}const Sg=new SR;class vR extends v.MessageType{constructor(){super("media.PreferredCodec",[{no:1,name:"audio",kind:"scalar",opt:!0,T:9},{no:2,name:"video",kind:"scalar",opt:!0,T:9}])}}const yR=new vR;class ER extends v.MessageType{constructor(){super("media.Simulcast",[{no:1,name:"preferred_rid",kind:"scalar",opt:!0,T:9},{no:2,name:"priority_ordering",kind:"scalar",opt:!0,T:9},{no:3,name:"rid_not_available",kind:"scalar",opt:!0,T:9}])}}const Uf=new ER;class PR extends v.MessageType{constructor(){super("media.edge.GeoLocation",[{no:1,name:"latitude",kind:"scalar",T:2},{no:2,name:"longitude",kind:"scalar",T:2},{no:3,name:"region",kind:"scalar",opt:!0,T:9}])}}const wR=new PR;class _R extends v.MessageType{constructor(){super("media.edge.PeerJoinRequest",[{no:1,name:"display_name",kind:"scalar",opt:!0,T:9},{no:2,name:"prejoined",kind:"scalar",T:8},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:5,name:"preset",kind:"scalar",opt:!0,T:12},{no:6,name:"user_id",kind:"scalar",opt:!0,T:9},{no:7,name:"organization_id",kind:"scalar",opt:!0,T:9},{no:8,name:"location",kind:"message",T:()=>wR},{no:9,name:"capabilities",kind:"message",T:()=>xf}])}}const CR=new _R;class RR extends v.MessageType{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const kR=new RR;class bR extends v.MessageType{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const MR=new bR;class AR extends v.MessageType{constructor(){super("media.edge.ConsumeMultipleProducerRequest",[{no:1,name:"producer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8}])}}new AR;class IR extends v.MessageType{constructor(){super("media.edge.ConsumePeerRequest",[{no:1,name:"producing_peer_id",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8},{no:3,name:"producer_id",kind:"scalar",opt:!0,T:9},{no:4,name:"preferred_codec",kind:"message",T:()=>yR},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:6,name:"simulcast",kind:"message",T:()=>Uf}])}}const DR=new IR;class OR extends v.MessageType{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>DR},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const NR=new OR;class LR extends v.MessageType{constructor(){super("media.edge.UpdateConsumerSimulcastConfigRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"simulcast",kind:"message",T:()=>Uf},{no:3,name:"producing_transport_id",kind:"scalar",T:9},{no:4,name:"mid",kind:"scalar",T:9}])}}const VR=new LR;class $R extends v.MessageType{constructor(){super("media.edge.UpdateConsumersSimulcastConfigRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>VR},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const xR=new $R;class UR extends v.MessageType{constructor(){super("media.edge.ProducerCreateRequest",[{no:1,name:"kind",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"description",kind:"message",T:()=>ms},{no:5,name:"msid",kind:"scalar",T:9},{no:6,name:"app_data",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9},{no:8,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const HR=new UR;class BR extends v.MessageType{constructor(){super("media.edge.SelectedPeersRequest",[])}}new BR;class FR extends v.MessageType{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const jR=new FR;class qR extends v.MessageType{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const cd=new qR;class GR extends v.MessageType{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}new GR;class WR extends v.MessageType{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ms},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const JR=new WR;class KR extends v.MessageType{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>ms},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const zR=new KR;class YR extends v.MessageType{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new YR;class QR extends v.MessageType{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const Hf=new QR;class XR extends v.MessageType{constructor(){super("media.edge.PeerDisplayNameEditRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}const ZR=new XR;class ek extends v.MessageType{constructor(){super("media.edge.HostMediaControlForPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"audio",kind:"scalar",T:8},{no:3,name:"video",kind:"scalar",T:8},{no:4,name:"scree_share",kind:"scalar",T:8}])}}const tk=new ek;class sk extends v.MessageType{constructor(){super("media.edge.HostMediaControlForAllPeerRequest",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8}])}}const rk=new sk;class ik extends v.MessageType{constructor(){super("media.edge.GetRoomStateResponse",[{no:1,name:"display_title",kind:"scalar",T:9},{no:2,name:"locked_mode",kind:"scalar",T:8},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"room_name",kind:"scalar",T:9},{no:5,name:"current_peer_id",kind:"scalar",T:9},{no:6,name:"is_recording",kind:"scalar",opt:!0,T:8},{no:7,name:"recorder_participant_id",kind:"scalar",opt:!0,T:9},{no:8,name:"pinned_peer_ids",kind:"scalar",repeat:2,T:9}])}}const nk=new ik;class ak extends v.MessageType{constructor(){super("media.edge.ErrorResponse",[{no:1,name:"error_message",kind:"scalar",T:9},{no:2,name:"event_id",kind:"scalar",T:5}])}}const ok=new ak;class ck extends v.MessageType{constructor(){super("media.edge.EmptyResponse",[])}}new ck;class dk extends v.MessageType{constructor(){super("media.edge.RoomParticipants",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"producer_states",kind:"message",repeat:1,T:()=>Zc},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"user_id",kind:"scalar",opt:!0,T:9},{no:5,name:"capabilities",kind:"message",T:()=>xf}])}}const Bf=new dk;class lk extends v.MessageType{constructor(){super("media.edge.SelectedPeersResponse",[{no:1,name:"audio_peers",kind:"scalar",repeat:2,T:9},{no:2,name:"compulsory_peers",kind:"scalar",repeat:2,T:9}])}}const Gu=new lk;class uk extends v.MessageType{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const hk=new uk;class pk extends v.MessageType{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>hk}])}}const vg=new pk;class gk extends v.MessageType{constructor(){super("media.edge.PeerJoinResponse",[])}}new gk;class mk extends v.MessageType{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>nk},{no:2,name:"participants",kind:"message",repeat:1,T:()=>Bf},{no:3,name:"selected_peers",kind:"message",T:()=>Gu},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const Wu=new mk;class fk extends v.MessageType{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}new fk;class Tk extends v.MessageType{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>$f}])}}new Tk;class Sk extends v.MessageType{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>$f},{no:3,name:"description",kind:"message",T:()=>ms}])}}const vk=new Sk;class yk extends v.MessageType{constructor(){super("media.edge.ProducerCreateResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"producer_id",kind:"scalar",T:9},{no:4,name:"description",kind:"message",T:()=>ms}])}}const Ek=new yk;class Pk extends v.MessageType{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>oR}])}}new Pk;class wk extends v.MessageType{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new wk;class _k extends v.MessageType{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new _k;class Ck extends v.MessageType{constructor(){super("media.edge.ProducerToggleResponse",[])}}new Ck;class Rk extends v.MessageType{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new Rk;class kk extends v.MessageType{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>ms}])}}const bk=new kk;class Mk extends v.MessageType{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>ms}])}}const Ak=new Mk;class Ik extends v.MessageType{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new Ik;class Dk extends v.MessageType{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new Dk;class Ok extends v.MessageType{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new Ok;class Nk extends v.MessageType{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Lk=new Nk;class Vk extends v.MessageType{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const $k=new Vk;class xk extends v.MessageType{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Uk=new xk;class Hk extends v.MessageType{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>Bf},{no:2,name:"producer_handover_from_peer_id",kind:"scalar",opt:!0,T:9}])}}const yg=new Hk;class Bk extends v.MessageType{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const Eg=new Bk;class Fk extends v.MessageType{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>Eg},{no:3,name:"screenshare",kind:"message",T:()=>Eg}])}}const jk=new Fk;class qk extends v.MessageType{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>Vf},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>jk}])}}new qk;class Gk extends v.MessageType{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Zc},{no:3,name:"producer_handover_from_peer_id",kind:"scalar",opt:!0,T:9}])}}const Wk=new Gk;class Jk extends v.MessageType{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Zc},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const Pg=new Jk;class Kk extends v.MessageType{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Zc}])}}const zk=new Kk;class Yk extends v.MessageType{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Ju=new Yk;class Qk extends v.MessageType{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const wg=new Qk;class Xk extends v.MessageType{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new Xk;class Zk extends v.MessageType{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new Zk;class eb extends v.MessageType{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new eb;class tb extends v.MessageType{constructor(){super("media.edge.PeerDisplayNameEditBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}new tb;class sb extends v.MessageType{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new sb;class rb extends v.MessageType{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new rb;class ib extends v.MessageType{constructor(){super("socket.ai.TranscriptSpeaker",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"participant_id",kind:"scalar",T:9},{no:3,name:"custom_participant_id",kind:"scalar",T:9},{no:4,name:"display_name",kind:"scalar",T:9}])}}const nb=new ib;class ab extends v.MessageType{constructor(){super("socket.ai.MeetingTranscript",[{no:1,name:"meeting_id",kind:"scalar",T:9},{no:2,name:"transcript",kind:"scalar",T:9},{no:3,name:"is_partial",kind:"scalar",T:8},{no:4,name:"sentence",kind:"scalar",T:9},{no:5,name:"speaker",kind:"message",T:()=>nb},{no:6,name:"started_at",kind:"scalar",T:4,L:2},{no:7,name:"ended_at",kind:"scalar",T:4,L:2},{no:8,name:"confidence",kind:"scalar",T:2}])}}const Ru=new ab;class ob extends v.MessageType{constructor(){super("socket.api.BaseSocketHubMessage",[{no:1,name:"event",kind:"scalar",T:5},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9},{no:4,name:"room_id",kind:"scalar",T:9},{no:5,name:"user_id",kind:"scalar",T:9},{no:6,name:"payload",kind:"scalar",T:12},{no:7,name:"error",kind:"scalar",opt:!0,T:8},{no:8,name:"sid",kind:"scalar",opt:!0,T:9}])}}new ob;class cb extends v.MessageType{constructor(){super("socket.api.ErrorMessage",[{no:1,name:"code",kind:"scalar",opt:!0,T:5},{no:2,name:"message",kind:"scalar",T:9}])}}const db=new cb;var an;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(an||(an={}));var lr;(function(s){s[s.UNSPECIFIED=0]="UNSPECIFIED",s[s.ON_STAGE=1]="ON_STAGE",s[s.APPROVED_STAGE=2]="APPROVED_STAGE",s[s.REQUESTED_STAGE=3]="REQUESTED_STAGE",s[s.OFF_STAGE=4]="OFF_STAGE"})(lr||(lr={}));var Ku;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(Ku||(Ku={}));var zu;(function(s){s[s.PEERS=0]="PEERS",s[s.ROOMS=1]="ROOMS"})(zu||(zu={}));var Ld;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(Ld||(Ld={}));class lb extends v.MessageType{constructor(){super("socket.room.PeerFlags",[{no:1,name:"preset_name",kind:"scalar",T:9},{no:2,name:"recorder_type",kind:"scalar",T:9},{no:3,name:"hidden_participant",kind:"scalar",T:8}])}}const ub=new lb;class hb extends v.MessageType{constructor(){super("socket.room.Peer",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",lr,"STAGE_TYPE_"]},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_id",kind:"scalar",opt:!0,T:9},{no:7,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:8,name:"waitlisted",kind:"scalar",T:8},{no:9,name:"flags",kind:"message",T:()=>ub}])}}const lu=new hb;class pb extends v.MessageType{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>lu}])}}const Sn=new pb;class gb extends v.MessageType{constructor(){super("socket.room.PeerStatusUpdate",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",lr,"STAGE_TYPE_"]}])}}const _g=new gb;class mb extends v.MessageType{constructor(){super("socket.room.RoomPeersInfoRequest",[{no:1,name:"seach_query",kind:"scalar",T:9},{no:2,name:"limit",kind:"scalar",T:5},{no:3,name:"offset",kind:"scalar",T:5}])}}const fb=new mb;class Tb extends v.MessageType{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>lu}])}}const ku=new Tb;class Sb extends v.MessageType{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const Cg=new Sb;class vb extends v.MessageType{constructor(){super("socket.room.Room",[{no:1,name:"room_id",kind:"scalar",T:9},{no:2,name:"title",kind:"scalar",T:9},{no:4,name:"created_at",kind:"scalar",T:4,L:2},{no:5,name:"active_recordings",kind:"message",repeat:1,T:()=>Eb},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const Ff=new vb;class yb extends v.MessageType{constructor(){super("socket.room.ActiveRecording",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",an]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const Eb=new yb;class Pb extends v.MessageType{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>Ff}])}}const Rg=new Pb;class wb extends v.MessageType{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const jf=new wb;class _b extends v.MessageType{constructor(){super("socket.room.UpdatePeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9}])}}new _b;class Cb extends v.MessageType{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>lu},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"organization_id",kind:"scalar",opt:!0,T:9},{no:5,name:"use_hive",kind:"scalar",opt:!0,T:8},{no:6,name:"preset",kind:"scalar",opt:!0,T:12},{no:7,name:"capabilities",kind:"enum",repeat:1,T:()=>["socket.room.Capabilities",Ld,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const Rb=new Cb;class kb extends v.MessageType{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>lu},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const bb=new kb;class Mb extends v.MessageType{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>Ff}])}}const dd=new Mb;class Ab extends v.MessageType{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new Ab;class Ib extends v.MessageType{constructor(){super("socket.room.ServiceError",[{no:1,name:"message",kind:"scalar",opt:!0,T:9},{no:2,name:"code",kind:"scalar",opt:!0,T:9}])}}const op=new Ib;class Db extends v.MessageType{constructor(){super("socket.room.ConnectedMeetingPeer",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9},{no:3,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:4,name:"preset_id",kind:"scalar",opt:!0,T:9},{no:5,name:"display_picture_url",kind:"scalar",opt:!0,T:9}])}}const Ob=new Db;class Nb extends v.MessageType{constructor(){super("socket.room.ConnectedMeetingDump",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9},{no:3,name:"participants",kind:"message",repeat:1,T:()=>Ob}])}}const kg=new Nb;class Lb extends v.MessageType{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>kg},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>kg}])}}const Vb=new Lb;class $b extends v.MessageType{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const xb=new $b;class Ub extends v.MessageType{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>xb}])}}const Hb=new Ub;class Bb extends v.MessageType{constructor(){super("socket.room.CreateRoomResponsePayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9},{no:3,name:"error",kind:"message",T:()=>op}])}}const Fb=new Bb;class jb extends v.MessageType{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Fb}])}}const qb=new jb;class Gb extends v.MessageType{constructor(){super("socket.room.UpdateRoomRequestPayload",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9}])}}const Wb=new Gb;class Jb extends v.MessageType{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Wb}])}}const Kb=new Jb;class zb extends v.MessageType{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const Yb=new zb;class Qb extends v.MessageType{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Yb}])}}const Xb=new Qb;class Zb extends v.MessageType{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>sM}])}}const eM=new Zb;class tM extends v.MessageType{constructor(){super("socket.room.DisableConnectedRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"status",kind:"scalar",opt:!0,T:9},{no:3,name:"title",kind:"scalar",opt:!0,T:9},{no:4,name:"error",kind:"message",T:()=>op}])}}const sM=new tM;class rM extends v.MessageType{constructor(){super("socket.room.MovePeerPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"preset_id",kind:"scalar",opt:!0,T:9}])}}const iM=new rM;class nM extends v.MessageType{constructor(){super("socket.room.MovePeersBetweenRoomsRequest",[{no:1,name:"source_meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"destination_meeting_id",kind:"scalar",opt:!0,T:9},{no:3,name:"participants",kind:"message",repeat:1,T:()=>iM}])}}const aM=new nM;class oM extends v.MessageType{constructor(){super("socket.room.MovedPeer",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:3,name:"error",kind:"message",T:()=>op}])}}const qf=new oM;class cM extends v.MessageType{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>qf}])}}new cM;class dM extends v.MessageType{constructor(){super("socket.room.TransferPeer",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"auth_token",kind:"scalar",opt:!0,T:9}])}}const lM=new dM;class uM extends v.MessageType{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>gM}])}}const hM=new uM;class pM extends v.MessageType{constructor(){super("socket.room.AddedParticipant",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",opt:!0,T:9},{no:3,name:"picture",kind:"scalar",opt:!0,T:9},{no:4,name:"custom_participant_id",kind:"scalar",T:9}])}}const gM=new pM;class mM extends v.MessageType{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const Gf=new mM;class fM extends v.MessageType{constructor(){super("socket.room.BroadcastMessage",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"timestamp",kind:"scalar",T:4,L:2},{no:4,name:"ids",kind:"scalar",repeat:2,T:9},{no:5,name:"broadcast_type",kind:"enum",opt:!0,T:()=>["socket.room.BroadcastType",zu,"BROADCAST_TYPE_"]}])}}const Za=new fM;class TM extends v.MessageType{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const SM=new TM;class vM extends v.MessageType{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const yM=new vM;class EM extends v.MessageType{constructor(){super("socket.room.WaitingRoomRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"picture",kind:"scalar",opt:!0,T:9},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_name",kind:"scalar",opt:!0,T:9}])}}const PM=new EM;class wM extends v.MessageType{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>PM}])}}const bg=new wM;class _M extends v.MessageType{constructor(){super("socket.room.GetRoomStageStateResponse",[{no:1,name:"on_stage_peers",kind:"scalar",repeat:2,T:9},{no:2,name:"approved_stage_peers",kind:"scalar",repeat:2,T:9},{no:3,name:"requested_stage_peers",kind:"scalar",repeat:2,T:9}])}}const Mg=new _M;var Yu;(function(s){s[s.NONE=0]="NONE",s[s.SKIP=1]="SKIP",s[s.ON_PRIVILEGED_USER_ENTRY=2]="ON_PRIVILEGED_USER_ENTRY",s[s.SKIP_ON_ACCEPT=3]="SKIP_ON_ACCEPT"})(Yu||(Yu={}));var si;(function(s){s[s.NONE=0]="NONE",s[s.ALLOWED=1]="ALLOWED",s[s.NOT_ALLOWED=2]="NOT_ALLOWED",s[s.CAN_REQUEST=3]="CAN_REQUEST"})(si||(si={}));class CM extends v.MessageType{constructor(){super("socket.preset.PollsPermissionUpdate",[{no:1,name:"can_create",kind:"scalar",opt:!0,T:8},{no:2,name:"can_vote",kind:"scalar",opt:!0,T:8},{no:3,name:"can_view",kind:"scalar",opt:!0,T:8}])}}const RM=new CM;class kM extends v.MessageType{constructor(){super("socket.preset.PluginsPermissionsUpdate",[{no:1,name:"can_close",kind:"scalar",opt:!0,T:8},{no:2,name:"can_start",kind:"scalar",opt:!0,T:8}])}}const bM=new kM;class MM extends v.MessageType{constructor(){super("socket.preset.PublicChatPermission",[{no:1,name:"can_send",kind:"scalar",opt:!0,T:8},{no:2,name:"text",kind:"scalar",opt:!0,T:8},{no:3,name:"files",kind:"scalar",opt:!0,T:8}])}}const AM=new MM;class IM extends v.MessageType{constructor(){super("socket.preset.PrivateChatPermission",[{no:1,name:"can_send",kind:"scalar",opt:!0,T:8},{no:2,name:"can_receive",kind:"scalar",opt:!0,T:8},{no:3,name:"text",kind:"scalar",opt:!0,T:8},{no:4,name:"files",kind:"scalar",opt:!0,T:8}])}}const DM=new IM;class OM extends v.MessageType{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>AM},{no:2,name:"private",kind:"message",T:()=>DM}])}}const NM=new OM;class LM extends v.MessageType{constructor(){super("socket.preset.ConnectedMeetingPermissionUpdate",[{no:1,name:"can_alter_connected_meetings",kind:"scalar",opt:!0,T:8},{no:2,name:"can_switch_to_parent_meeting",kind:"scalar",opt:!0,T:8},{no:3,name:"can_switch_connected_meetings",kind:"scalar",opt:!0,T:8}])}}const VM=new LM;class $M extends v.MessageType{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",si,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",si,"STREAM_PERMISSION_TYPE_"]}])}}const bu=new $M;class xM extends v.MessageType{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>bu},{no:2,name:"audio",kind:"message",T:()=>bu},{no:3,name:"screenshare",kind:"message",T:()=>bu}])}}const UM=new xM;class HM extends v.MessageType{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>RM},{no:2,name:"plugins",kind:"message",T:()=>bM},{no:3,name:"chat",kind:"message",T:()=>NM},{no:4,name:"accept_waiting_requests",kind:"scalar",opt:!0,T:8},{no:5,name:"can_accept_production_requests",kind:"scalar",opt:!0,T:8},{no:6,name:"can_edit_display_name",kind:"scalar",opt:!0,T:8},{no:7,name:"can_record",kind:"scalar",opt:!0,T:8},{no:8,name:"can_livestream",kind:"scalar",opt:!0,T:8},{no:9,name:"can_spotlight",kind:"scalar",opt:!0,T:8},{no:10,name:"disable_participant_audio",kind:"scalar",opt:!0,T:8},{no:11,name:"disable_participant_screensharing",kind:"scalar",opt:!0,T:8},{no:12,name:"disable_participant_video",kind:"scalar",opt:!0,T:8},{no:13,name:"kick_participant",kind:"scalar",opt:!0,T:8},{no:14,name:"pin_participant",kind:"scalar",opt:!0,T:8},{no:15,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:16,name:"waiting_room_type",kind:"enum",opt:!0,T:()=>["socket.preset.WaitingRoomType",Yu,"WAITING_ROOM_TYPE_"]},{no:17,name:"is_recorder",kind:"scalar",opt:!0,T:8},{no:18,name:"recorder_type",kind:"enum",opt:!0,T:()=>["socket.room.RecorderType",Ku,"RECORDER_TYPE_"]},{no:19,name:"hidden_participant",kind:"scalar",opt:!0,T:8},{no:20,name:"show_participant_list",kind:"scalar",opt:!0,T:8},{no:21,name:"can_change_participant_permissions",kind:"scalar",opt:!0,T:8},{no:22,name:"connected_meetings",kind:"message",T:()=>VM},{no:23,name:"media",kind:"message",T:()=>UM}])}}const cp=new HM;class BM extends v.MessageType{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const FM=new BM;class jM extends v.MessageType{constructor(){super("socket.preset.PeerPreset",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"preset",kind:"scalar",T:12}])}}const qM=new jM;class GM extends v.MessageType{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>qM}])}}const WM=new GM;class JM extends v.MessageType{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>cp}])}}const Wf=new JM;class KM extends v.MessageType{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Wf}])}}const zM=new KM;class YM extends v.MessageType{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Wf}])}}const Ag=new YM;class QM extends v.MessageType{constructor(){super("socket.preset.PeerUserIDMap",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9}])}}const XM=new QM;class ZM extends v.MessageType{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>XM},{no:2,name:"patch",kind:"message",T:()=>cp}])}}new ZM;class eA extends v.MessageType{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>cp}])}}new eA;class tA extends v.MessageType{constructor(){super("socket.chat.ChatMessage",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"user_id",kind:"scalar",T:9},{no:4,name:"display_name",kind:"scalar",T:9},{no:5,name:"pinned",kind:"scalar",T:8},{no:6,name:"is_edited",kind:"scalar",T:8},{no:7,name:"payload_type",kind:"scalar",T:5},{no:8,name:"payload",kind:"scalar",T:9},{no:10,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:11,name:"created_at",kind:"scalar",T:4,L:2},{no:12,name:"created_at_ms",kind:"scalar",opt:!0,T:4,L:2},{no:13,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:14,name:"channel_index",kind:"scalar",opt:!0,T:9}])}}const ai=new tA;class sA extends v.MessageType{constructor(){super("socket.chat.GetPaginatedChatMessageFilters",[{no:1,name:"pinned",kind:"scalar",oneof:"filters",T:8},{no:2,name:"user_id",kind:"scalar",oneof:"filters",T:9}])}}const rA=new sA;class iA extends v.MessageType{constructor(){super("socket.chat.GetPaginatedChatMessageRoomRequest",[{no:1,name:"time_stamp",kind:"scalar",T:4,L:2},{no:2,name:"size",kind:"scalar",T:5},{no:3,name:"from",kind:"scalar",T:5},{no:4,name:"reversed",kind:"scalar",T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:6,name:"filters",kind:"message",T:()=>rA}])}}const nA=new iA;class aA extends v.MessageType{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>ai},{no:2,name:"next",kind:"scalar",T:8}])}}const oA=new aA;class cA extends v.MessageType{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>ai}])}}const Jf=new cA;class dA extends v.MessageType{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const lA=new dA;class uA extends v.MessageType{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>ai}])}}const Mu=new uA;class hA extends v.MessageType{constructor(){super("socket.chat.SendChatMessageToPeersRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"payload_type",kind:"scalar",T:5},{no:3,name:"payload",kind:"scalar",T:9}])}}const pA=new hA;class gA extends v.MessageType{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>ai}])}}const Au=new gA;class mA extends v.MessageType{constructor(){super("socket.chat.SendChatMessageToChannelRequest",[{no:1,name:"channel_id",kind:"scalar",T:9},{no:2,name:"payload_type",kind:"scalar",T:5},{no:3,name:"payload",kind:"scalar",T:9}])}}new mA;class fA extends v.MessageType{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>ai}])}}new fA;class TA extends v.MessageType{constructor(){super("socket.chat.EditChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"payload_type",kind:"scalar",opt:!0,T:5},{no:3,name:"payload",kind:"scalar",opt:!0,T:9},{no:4,name:"pinned",kind:"scalar",opt:!0,T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const SA=new TA;class vA extends v.MessageType{constructor(){super("socket.chat.PinChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"pinned",kind:"scalar",T:8},{no:3,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const yA=new vA;class EA extends v.MessageType{constructor(){super("socket.chat.PinChatMessageResponse",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"pinned",kind:"scalar",T:8},{no:3,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:4,name:"message",kind:"message",T:()=>ai}])}}const ld=new EA;class PA extends v.MessageType{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>ai}])}}const ud=new PA;class wA extends v.MessageType{constructor(){super("socket.chat.DeleteChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const _A=new wA;class CA extends v.MessageType{constructor(){super("socket.chat.DeleteChatMessageResponse",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const hd=new CA;class RA extends v.MessageType{constructor(){super("socket.chat.SearchChatMessagesRequest",[{no:1,name:"time_stamp",kind:"scalar",T:4,L:2},{no:2,name:"size",kind:"scalar",T:5},{no:3,name:"from",kind:"scalar",T:5},{no:4,name:"reversed",kind:"scalar",T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:6,name:"search_term",kind:"scalar",T:9}])}}const kA=new RA;class bA extends v.MessageType{constructor(){super("socket.chat.MarkChannelIndexAsReadRequest",[{no:1,name:"channel_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"channel_index",kind:"scalar",T:9}])}}new bA;class MA extends v.MessageType{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}new MA;class AA extends v.MessageType{constructor(){super("socket.chat.CreateChatChannelRequest",[{no:1,name:"display_name",kind:"scalar",T:9},{no:2,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:4,name:"visibility",kind:"scalar",T:9},{no:5,name:"is_direct_message",kind:"scalar",T:8}])}}new AA;class IA extends v.MessageType{constructor(){super("socket.chat.UpdateChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9},{no:3,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:4,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:5,name:"visibility",kind:"scalar",opt:!0,T:9},{no:6,name:"is_direct_message",kind:"scalar",opt:!0,T:8}])}}new IA;class DA extends v.MessageType{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new DA;class OA extends v.MessageType{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new OA;class NA extends v.MessageType{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>ai},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const LA=new NA;class VA extends v.MessageType{constructor(){super("socket.chat.ChatChannel",[{no:1,name:"chat_channel_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9},{no:3,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:4,name:"visibility",kind:"scalar",T:9},{no:5,name:"is_direct_message",kind:"scalar",T:8},{no:6,name:"latest_message_and_unread_count",kind:"message",T:()=>LA},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const $A=new VA;class xA extends v.MessageType{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>$A}])}}new xA;class UA extends v.MessageType{constructor(){super("socket.chat.ChannelMember",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",opt:!0,T:9},{no:3,name:"picture",kind:"scalar",opt:!0,T:9},{no:4,name:"custom_participant_id",kind:"scalar",T:9}])}}const HA=new UA;class BA extends v.MessageType{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>HA}])}}new BA;class FA extends v.MessageType{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}new FA;class jA extends v.MessageType{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}new jA;class qA extends v.MessageType{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new qA;class GA extends v.MessageType{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new GA;class WA extends v.MessageType{constructor(){super("socket.plugin.EnablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}new WA;class JA extends v.MessageType{constructor(){super("socket.plugin.DisablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}new JA;class KA extends v.MessageType{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}new KA;class zA extends v.MessageType{constructor(){super("socket.plugin.PluginEventToPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"plugin_data",kind:"scalar",T:12}])}}new zA;class YA extends v.MessageType{constructor(){super("socket.plugin.StoreKeys",[{no:1,name:"store_key",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",opt:!0,T:12}])}}const dp=new YA;class QA extends v.MessageType{constructor(){super("socket.plugin.PluginStoreInsertKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"insert_keys",kind:"message",repeat:1,T:()=>dp}])}}const XA=new QA;class ZA extends v.MessageType{constructor(){super("socket.plugin.PluginStoreGetKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"get_keys",kind:"message",repeat:1,T:()=>dp}])}}const eI=new ZA;class tI extends v.MessageType{constructor(){super("socket.plugin.PluginStoreDeleteKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"delete_keys",kind:"message",repeat:1,T:()=>dp}])}}const sI=new tI;class rI extends v.MessageType{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}new rI;class iI extends v.MessageType{constructor(){super("socket.plugin.EnablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"enabled_by",kind:"scalar",T:9}])}}const nI=new iI;class aI extends v.MessageType{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>nI}])}}new aI;class oI extends v.MessageType{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}new oI;class cI extends v.MessageType{constructor(){super("socket.plugin.PluginStoreItem",[{no:1,name:"timestamp",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"store_key",kind:"scalar",T:9},{no:4,name:"payload",kind:"scalar",T:12}])}}const dI=new cI;class lI extends v.MessageType{constructor(){super("socket.plugin.PluginStoreResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"store_items",kind:"message",repeat:1,T:()=>dI}])}}const Ig=new lI;class uI extends v.MessageType{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}new uI;class hI extends v.MessageType{constructor(){super("socket.livestreaming.LiveStreamingEvent",[{no:1,name:"livestream_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",T:9},{no:5,name:"playback_url",kind:"scalar",T:9},{no:6,name:"org_id",kind:"scalar",T:9},{no:7,name:"room_name",kind:"scalar",T:9},{no:8,name:"room_uuid",kind:"scalar",T:9},{no:9,name:"status",kind:"scalar",T:9},{no:10,name:"manual_ingest",kind:"scalar",opt:!0,T:8}])}}const Dg=new hI;class pI extends v.MessageType{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const Og=new pI;class gI extends v.MessageType{constructor(){super("socket.livestreaming.StageRequest",[{no:1,name:"display_name",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9}])}}const mI=new gI;class fI extends v.MessageType{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>mI}])}}const Iu=new fI;class TI extends v.MessageType{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const SI=new TI;class vI extends v.MessageType{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const yI=new vI;class EI extends v.MessageType{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Ng=new EI;class PI extends v.MessageType{constructor(){super("socket.polls.Poll",[{no:1,name:"poll_id",kind:"scalar",T:9},{no:2,name:"created_by",kind:"scalar",T:9},{no:3,name:"created_by_user_id",kind:"scalar",T:9},{no:4,name:"question",kind:"scalar",T:9},{no:5,name:"options",kind:"message",repeat:1,T:()=>_I},{no:6,name:"hide_votes",kind:"scalar",T:8},{no:7,name:"anonymous",kind:"scalar",T:8},{no:8,name:"votes",kind:"scalar",repeat:2,T:9}])}}const Kf=new PI;class wI extends v.MessageType{constructor(){super("socket.polls.PollOption",[{no:1,name:"text",kind:"scalar",T:9},{no:2,name:"count",kind:"scalar",opt:!0,T:4,L:2},{no:3,name:"votes",kind:"message",repeat:1,T:()=>RI}])}}const _I=new wI;class CI extends v.MessageType{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const RI=new CI;class kI extends v.MessageType{constructor(){super("socket.polls.NewPollRequest",[{no:1,name:"question",kind:"scalar",T:9},{no:2,name:"options",kind:"scalar",repeat:2,T:9},{no:3,name:"anonymous",kind:"scalar",T:8},{no:4,name:"hide_votes",kind:"scalar",T:8},{no:5,name:"created_by",kind:"scalar",opt:!0,T:9},{no:6,name:"created_by_user_id",kind:"scalar",opt:!0,T:9}])}}const bI=new kI;class MI extends v.MessageType{constructor(){super("socket.polls.VotePollRequest",[{no:1,name:"poll_id",kind:"scalar",T:9},{no:2,name:"index",kind:"scalar",T:4,L:2}])}}const AI=new MI;class II extends v.MessageType{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>Kf}])}}const Du=new II;class DI extends v.MessageType{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>Kf}])}}const OI=new DI;class NI extends v.MessageType{constructor(){super("socket.recording.RecordingEvent",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",an]}])}}const Lg=new NI;class LI extends v.MessageType{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:0},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const t=this.create(),e=Date.now();return t.seconds=v.PbLong.from(Math.floor(e/1e3)).toBigInt(),t.nanos=e%1e3*1e6,t}toDate(t){return new Date(v.PbLong.from(t.seconds).toNumber()*1e3+Math.ceil(t.nanos/1e6))}fromDate(t){const e=this.create(),r=t.getTime();return e.seconds=v.PbLong.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}internalJsonWrite(t,e){let r=v.PbLong.from(t.seconds).toNumber()*1e3;if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(t.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let i="Z";if(t.nanos>0){let a=(t.nanos+1e9).toString().substring(1);a.substring(3)==="000000"?i="."+a.substring(0,3)+"Z":a.substring(6)==="000"?i="."+a.substring(0,6)+"Z":i="."+a+"Z"}return new Date(r).toISOString().replace(".000Z",i)}internalJsonRead(t,e,r){if(typeof t!="string")throw new Error("Unable to parse Timestamp from JSON "+v.typeofJsonValue(t)+".");let i=t.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let a=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(a))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(a<Date.parse("0001-01-01T00:00:00Z")||a>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return r||(r=this.create()),r.seconds=v.PbLong.from(a/1e3).toBigInt(),r.nanos=0,i[7]&&(r.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),r}}new LI;class VI extends v.MessageType{constructor(){super("common.BaseHubMessage",[{no:1,name:"event",kind:"scalar",T:5},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9},{no:4,name:"room_id",kind:"scalar",T:9},{no:5,name:"user_id",kind:"scalar",T:9},{no:6,name:"payload",kind:"scalar",T:12},{no:7,name:"error",kind:"scalar",opt:!0,T:8},{no:8,name:"sid",kind:"scalar",opt:!0,T:9},{no:9,name:"room_object_id",kind:"scalar",opt:!0,T:9},{no:10,name:"preset",kind:"scalar",opt:!0,T:9},{no:11,name:"use_start_session",kind:"scalar",opt:!0,T:8}])}}const Qu=new VI;class $I extends v.MessageType{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Qu}])}}new $I;class xI extends v.MessageType{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>Qu},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>Qu}])}}new xI;const UI=0,HI=1,BI=2,FI=3,jI=5,qI={getPeerInfo:0,updatePeerInfo:1,getRoomPeersInfo:2,joinRoom:3,leaveRoom:4,getRoomInfo:5,updateRoomInfo:6,closeRoom:7,startedLivestream:8,stoppedLivestream:9,erroredLivestream:10,getStagePeers:11,getStageRequests:12,requestStageAccess:13,cancelStageRequest:14,grantStageAccess:15,denyStageAccess:16,roomPeerCount:17,joinStage:18,leaveStage:19,getConnectedRoomsDump:20,createConnectedRooms:21,deleteConnectedRooms:22,movePeers:23,transferPeer:24,movedPeer:25,connectedRoomsUpdated:26,connectedRoomsDeleted:27,getAllAddedParticipants:28,broadcastMessage:29,kick:30,kickAll:31,transcript:32,getWaitingRoomRequests:33,acceptWaitingRoomRequests:34,waitingRoomRequestAccepted:35,denyWaitingRoomRequests:36,waitingRoomRequestDenied:37,peerStageStatusUpdate:38,broadcastToEntity:39,recordingStarted:40,recordingStopped:41,recordingPaused:42,getRoomStageState:43,livestreamingInvoked:44,updateConnectedRooms:45},GI={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,searchChannelMessages:7,pinMessage:10},WI={getPlugins:0,addPlugin:1,enablePluginForRoom:2,disablePluginForPeers:3,enablePluginForPeers:4,disablePluginForRoom:5,removePlugin:6,customPluginEventToRoom:7,customPluginEventToPeers:8,storeInsertKeys:9,storeGetKeys:10,storeDeleteKeys:11,storeDelete:12},JI={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},zf={unknown:0,createWebRTCTransport:1,produce:2,consume:3,toggleProducer:4,toggleConsumer:5,closeProducer:6,closeConsumer:7,updateConsumersSimulcastConfig:8,joinRoom:16,leaveRoom:17,selectedPeer:18,globalPinPeer:19,selfJoinComplete:20,peerJoinedBroadcast:25,peerLeaveBroadcast:26,peerProducerCreateBroadcast:27,peerProducerToggleBroadcast:28,peerProducerCloseBroadcast:29,globalPeerPinBroadcast:30,recordingStartedBroadcast:31,recordingStoppedBroadcast:32,peerDisplayNameEditBroadcast:33,mediaRoomTerminationBroadcastResponse:36,selectedPeerDiff:40,renegotiateSessionDescription:50,errorResponse:60,kickPeer:90,kickAll:91,changeDisplayName:92,hostControlPeer:93,hostControlAllPeers:94,audioActivity:100},KI={getUserPresets:0,updateUserPreset:1};function ed(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function Yf(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const L=ed(UI,qI),We=ed(HI,GI),Hs=ed(BI,WI),Bs=ed(FI,JI),Ir=Yf(zf,16777216),us=Yf(zf,50331648),Sd=ed(jI,KI);var zI=Object.defineProperty,YI=Object.getOwnPropertyDescriptor,oi=(s,t,e,r)=>{for(var i=r>1?void 0:r?YI(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&zI(t,e,i),i},Xt=(s=>(s[s.TEXT=0]="TEXT",s[s.IMAGE=1]="IMAGE",s[s.FILE=2]="FILE",s[s.CUSTOM=3]="CUSTOM",s))(Xt||{}),kt,$n;class vr{constructor(t,e){g(this,kt,void 0);g(this,$n,void 0);m(this,kt,e),m(this,$n,t)}get telemetry(){return n(this,$n).getValue("telemetry")}get logger(){return n(this,$n).getValue("logger")}getChatMessages(){return n(this,kt).sendMessagePromise(We.getMessages)}async getChatMessagesPaginated(t,e,r,i){const a={timeStamp:t,size:e,from:0,reversed:r,...i&&{filters:{filters:i}}},o=await n(this,kt).sendMessagePromise(We.getPaginatedMessages,nA.toBinary(a));return o.payload?oA.fromBinary(o.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};n(this,kt).sendMessage(We.sendMessageToRoom,lA.toBinary(r))}sendMessageToPeers(t,e,r){const i={payloadType:e,peerIds:r,payload:t};n(this,kt).sendMessage(We.sendMessageToPeers,pA.toBinary(i))}sendMessage(t,e,r){if(r&&r.length>0){this.sendMessageToPeers(t,e,r);return}this.sendMessageToRoom(t,e)}async editMessage(t,e,r,i){const a={chatId:t,payloadType:r,payload:e};i!==void 0&&(a.pinned=i);const o=await n(this,kt).sendMessagePromise(We.editMessage,SA.toBinary(a));return ud.fromBinary(o.payload).message}async deleteMessage(t){const e={chatId:t},r=await n(this,kt).sendMessagePromise(We.deleteMessage,_A.toBinary(e));return{id:hd.fromBinary(r.payload).chatId}}async searchMessages(t,e){var i,a,o,c;const r={searchTerm:t,timeStamp:(i=e.timestamp)!=null?i:Date.now(),size:(a=e.limit)!=null?a:75,from:(o=e.offset)!=null?o:0,reversed:(c=e.reversed)!=null?c:!0};try{const d=await n(this,kt).sendMessagePromise(We.searchChannelMessages,kA.toBinary(r));return Jf.fromBinary(d.payload).messages}catch(d){return[]}}async setPinState(t,e){const r={chatId:t,pinned:e},i=await n(this,kt).sendMessagePromise(We.pinMessage,yA.toBinary(r));return ld.fromBinary(i.payload)}on(t,e){let r,i;switch(t){case We.sendMessageToRoom:{r=Mu.fromBinary.bind(Mu),i=Mu.create();break}case We.sendMessageToPeers:{r=Au.fromBinary.bind(Au),i=Au.create();break}case We.editMessage:{r=ud.fromBinary.bind(ud),i=ud.create();break}case We.pinMessage:{r=ld.fromBinary.bind(ld),i=ld.create();break}case We.deleteMessage:{r=hd.fromBinary.bind(hd),i=hd.create();break}}if(!r){this.logger.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}n(this,kt).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}kt=new WeakMap,$n=new WeakMap;oi([y.trace("SocketService.getChatMessages")],vr.prototype,"getChatMessages",1);oi([y.trace("SocketService.getChatMessagesPaginated")],vr.prototype,"getChatMessagesPaginated",1);oi([y.trace("SocketService.sendMessageToRoom")],vr.prototype,"sendMessageToRoom",1);oi([y.trace("SocketService.sendMessageToPeers")],vr.prototype,"sendMessageToPeers",1);oi([y.trace("SocketService.sendMessage")],vr.prototype,"sendMessage",1);oi([y.trace("SocketService.editMessage")],vr.prototype,"editMessage",1);oi([y.trace("SocketService.deleteMessage")],vr.prototype,"deleteMessage",1);oi([y.trace("SocketService.searchMessages")],vr.prototype,"searchMessages",1);function QI(s){return s.replace(/([-_]\w)/g,t=>t[1].toUpperCase())}function Os(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Os(e));const t={};return Object.keys(s).forEach(e=>{const r=pr.validate(e)?e:QI(e);t[r]=Os(s[e])}),t}function XI(s){return s.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Qf(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Qf(e));const t={};return Object.keys(s).forEach(e=>{const r=pr.validate(e)?e:XI(e);t[r]=s[e]}),t}class Vd extends Error{constructor(e){const r=e instanceof Error?e.message:`Request failed with status ${e.status}`;super(r);p(this,"status");p(this,"response");p(this,"isTimeout");e instanceof Error?(this.stack=e.stack,this.isTimeout=e.name==="AbortError"):(this.status=e.status,this.response=e,this.isTimeout=!1),this.name="RequestError"}get isHttpError(){return this.status!==void 0}get isNetworkError(){return this.status===void 0&&!this.isTimeout}}class Vg{constructor(t){p(this,"defaults");this.defaults={baseURL:t.baseURL,headers:{common:{}},timeout:t.timeout,retry:t.retry,retryDelay:t.retryDelay}}buildURL(t,e){const{baseURL:r}=this.defaults,i=t.startsWith("http")?t:`${r}${t.startsWith("/")?t:`/${t}`}`;if(e){const a=new URLSearchParams;return Object.entries(e).forEach(([o,c])=>{a.append(o,c)}),`${i}${i.includes("?")?"&":"?"}${a.toString()}`}return i}async request(t){var h;const e=((h=t.method)==null?void 0:h.toUpperCase())||"GET",r=this.buildURL(t.url||"",t.params),i={...this.defaults.headers.common,...t.headers};e!=="GET"&&e!=="HEAD"&&t.data&&!i["Content-Type"]&&(i["Content-Type"]="application/json");const o=i["Content-Type"]==="application/json"?JSON.stringify(t.data):t.data,c={method:e,headers:i,body:e!=="GET"&&e!=="HEAD"&&t.data?o:void 0},d=t.timeout||this.defaults.timeout,l=t.retry!==void 0?t.retry:this.defaults.retry,u=t.retryDelay||this.defaults.retryDelay;try{const f=new AbortController,S=setTimeout(()=>f.abort(),d);c.signal=f.signal;const E=await fetch(r,c);clearTimeout(S);let R=null;const M=E.headers.get("content-type");M&&M.includes("application/json")?R=await E.json():R=await E.text();const D={};E.headers.forEach((x,$)=>{D[$]=x});const I={data:R,status:E.status,statusText:E.statusText,headers:D,config:t};if(!E.ok)throw I;return I}catch(f){if(f instanceof Error&&l>0)return await new Promise(S=>setTimeout(S,u)),this.defaults.baseURL===fi.apiBase.prod?this.defaults.baseURL=fi.apiBase.prodAlternate:this.defaults.baseURL===fi.apiBase.prodAlternate&&(this.defaults.baseURL=fi.apiBase.prod),this.request({...t,retry:l-1});throw f}}async get(t,e={}){return this.request({...e,method:"GET",url:t})}async post(t,e,r={}){return this.request({...r,method:"POST",url:t,data:e})}async put(t,e,r={}){return this.request({...r,method:"PUT",url:t,data:e})}}const ZI=3,e0=30,t0=8e3;class s0{constructor(t,e){p(this,"fetchClient");p(this,"requests");p(this,"roomName");p(this,"roomUUID");p(this,"authToken");p(this,"organizationId");p(this,"iceServers");p(this,"userDetails");p(this,"roomDetails");p(this,"context");this.context=t;const{timeout:r=t0,retry:i=ZI,retryDelay:a=e0,baseURL:o=fi.apiBase.prod,authToken:c,cachedUserDetails:d}=e||{};this.iceServers=d==null?void 0:d.iceServers,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=new Vg({baseURL:o,timeout:r,retry:i,retryDelay:a,responseType:"json"}),this.fetchClient=new Vg({baseURL:"",timeout:r,retry:i,retryDelay:a,responseType:"json"}),this.setAuthToken(c,{bearer:!0});const l=this.requests.request.bind(this.requests);this.requests.request=async u=>{var f,S,E,R,M,D;const h=t.getValue("telemetry");try{h.injectContext(this.requests.defaults.headers.common);const I=await l(u);return u.url!==h.logsEndpoint&&this.logger.debug(`XHR - Fetched ${u.method}:${u.url} with status ${I.status}`,{networkCall:{status:I.status,statusText:I.statusText,baseURL:u.baseURL||this.requests.defaults.baseURL,url:u.url,method:u.method}}),I}catch(I){if(!I)throw new C("Unknown network error occurred","0011");if(I instanceof C||I instanceof Vd)throw I;((f=I.config)==null?void 0:f.url)!==h.logsEndpoint&&this.logger.error(`XHR - Fetch failed on ${u.method}:${u.url} with status ${I.status}. Retry: ${(S=I.config)==null?void 0:S.retry}`,{error:I,networkCall:{status:I.status,statusText:I.statusText,baseURL:((E=I.config)==null?void 0:E.baseURL)||this.requests.defaults.baseURL,url:(R=I.config)==null?void 0:R.url,retries:(M=I.config)==null?void 0:M.retry,method:(D=I.config)==null?void 0:D.method,isOnline:navigator.onLine?"online":"offline"}});const x=I instanceof Error&&I.message||"Network request failed";throw new C(x,"0011"),new Vd(I)}}}get peerId(){return this.context.getValue("peerId")}get logger(){return this.context.getValue("logger")}setAuthToken(t,e){const{bearer:r}=e||{};this.authToken=t,this.requests.defaults.headers.common.Authorization=r?`Bearer ${t}`:t}setHeader(t,e){this.requests.defaults.headers.common[t]=e}setRoomName(t){this.roomName=t}setRoomUUID(t){this.roomUUID=t}setOrganizationId(t){this.organizationId=t}}var r0=Object.defineProperty,i0=Object.getOwnPropertyDescriptor,yr=(s,t,e,r)=>{for(var i=r>1?void 0:r?i0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&r0(t,e,i),i};class Vs extends s0{constructor(e,r){super(e,r);p(this,"telemetry");this.telemetry=e.getValue("telemetry"),this.setHeader("x-realtimekit-version",e.getValue("sdkVersion"))}async getICEServers(){if(this.iceServers)return this.iceServers;const{success:e,iceServers:r}=(await this.requests.get("/iceservers")).data;if(e)return(r==null?void 0:r.length)>0&&(this.iceServers=r),r}async getPresignedUrls(e){const r=Ao(this.context,"chat_upload_expiry"),i={roomUUID:this.roomUUID,filename:e,expiry:typeof r=="number"?r:void 0},{get_location:a,put_location:o}=(await this.requests.post("/v2/meetings/chat-upload",i)).data.data;return{getLocation:a,putLocation:o}}async uploadFile(e,r){if(navigator.isReactNative&&"uri"in e)try{await fetch(r,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:{uri:e.uri,name:e.name}})}catch(i){this.logger.error(`sendFileMessage::${i}`)}else await this.fetchClient.put(r,e,{headers:{"Content-Type":e.type}})}async startLivestreaming({manualIngestion:e}){const r=Os(await this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/livestreams`,{manual_ingest:!!e})).data.data;return{playbackUrl:r.playbackUrl,status:r.status,manualIngest:r.manualIngest,ingestionCredentials:r.streamKey?{ingestionServer:r.ingestServer,streamKey:r.streamKey}:null}}async stopLivestreaming(){return this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream/stop`)}async getActiveLivestream(){const e=Os((await this.requests.get(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream`)).data.data);return{playbackUrl:e.playbackUrl,status:e.status,manualIngest:e.manualIngest,ingestionCredentials:e.streamKey?{ingestionServer:e.ingestServer,streamKey:e.streamKey}:null}}async getUserDetails(){if(this.userDetails)return this.userDetails;const e=(await this.requests.get("v2/internals/participant-details")).data.data;return Os(e)}async startRecording(e,r){return(await this.requests.post("/v2/recordings",{...Qf(e),meeting_id:this.context.getValue("meetingId"),allow_multiple_recordings:!!r})).data.data.id}async updateRecording(e,r){return this.requests.put(`v2/recordings/${e}`,{action:r})}async getActiveRecording(){const{status:e,id:r}=(await this.requests.get(`v2/recordings/active-recording/${this.context.getValue("meetingId")}`)).data.data;return{status:e,id:r}}async getActiveTranscript(){const{transcript_download_url:e}=(await this.requests.get(`v2/meetings/${this.context.getValue("meetingId")}/active-transcript`)).data.data;try{return{transcript:(await this.fetchClient.get(e)).data}}catch(r){throw new C("Cant fetch transcript s3 url","1801")}}}yr([y.trace("APIClient.getICEServers")],Vs.prototype,"getICEServers",1);yr([y.trace("APIClient.startLivestreaming")],Vs.prototype,"startLivestreaming",1);yr([y.trace("APIClient.stopLivestreaming")],Vs.prototype,"stopLivestreaming",1);yr([y.trace("APIClient.getActiveLivestream")],Vs.prototype,"getActiveLivestream",1);yr([y.trace("APIClient.getUserDetails")],Vs.prototype,"getUserDetails",1);yr([y.trace("APIClient.startRecording")],Vs.prototype,"startRecording",1);yr([y.trace("APIClient.stopRecording")],Vs.prototype,"updateRecording",1);yr([y.trace("APIClient.getActiveRecording")],Vs.prototype,"getActiveRecording",1);yr([y.trace("APIClient.getActiveTranscript")],Vs.prototype,"getActiveTranscript",1);let Xu;function n0(s,t){return Xu=new Vs(s,t),Xu}function Lt(){return Xu}const Oa={maxInvocations:5,period:1};function Ut(s,t){return function(e,r,i){const a=i.value;let o=0,c=Date.now();return i.value=function(...d){const l=Date.now(),u=t?this[t]:s;if(l-c>u.period*1e3&&(c=l,o=0),o>=u.maxInvocations)throw new C(`Method rate limit ${u.maxInvocations} invocations/${u.period}sec exceeded`,"0013");return o+=1,a.apply(this,d)},i}}var a0=Object.defineProperty,o0=Object.getOwnPropertyDescriptor,$s=(s,t,e,r)=>{for(var i=r>1?void 0:r?o0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&a0(t,e,i),i};const c0=["text","image","file","custom","poll"],vd={maxInvocations:180,period:60};var ee,Ti,ze,xn,Kd,Xf,Lo,Zu,em;let es=(em=class extends xt{constructor(t,e,r,i){const a=t.getValue("logger");super(a);g(this,Kd);g(this,Lo);p(this,"messages");g(this,ee,void 0);g(this,Ti,void 0);g(this,ze,void 0);g(this,xn,void 0);p(this,"maxTextLimit",2e3);m(this,xn,t),m(this,ze,e),m(this,ee,r),m(this,Ti,i),this.messages=[]}get telemetry(){return n(this,xn).getValue("telemetry")}setMaxTextLimit(t){this.maxTextLimit=t}async sendMessageInternal(t,e){switch(t.type){case"text":{await this.sendTextMessageInternal(t.message,e);break}case"image":await this.sendImageMessageInternal(t.image,e);break;case"file":await this.sendFileMessageInternal(t.file,e);break;default:this.logger.error("sendMessage::message_type_not_supported",{chat:{messageType:t.type}});break}}async sendTextMessageInternal(t,e){var i,a,o,c,d,l;if(t.length>this.maxTextLimit)throw new C("Max character limit breached","0503");if(e&&e.length>0){if(!((i=n(this,ee).permissions)!=null&&i.chatPrivate.canSend)||!((a=n(this,ee).permissions)!=null&&a.chatPrivate.text))throw this.logger.error("sendTextMessage::private_chat_permission_denied"),new C("Could not send message to private chat.","0501")}else if(!((c=(o=n(this,ee).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=n(this,ee).permissions)==null?void 0:d.chatPublic)!=null&&l.text))throw this.logger.error("sendTextMessage::public_chat_permission_denied"),new C("Could not send message to public chat.","0501");if(!t)throw this.logger.error("sendTextMessage::message_can_not_be_empty"),new C("Message can not be empty.","0502");let r=[];e&&e.length>0&&(e.push(n(this,ee).id),r=n(this,Ti).joined.toArray().filter(u=>e.includes(u.id)).map(u=>u.userId),r.push(n(this,ee).userId)),n(this,ze).sendMessage(t,Xt.TEXT,e)}async sendImageMessageInternal(t,e){var i,a,o,c,d,l;if(e&&e.length>0){if(!((i=n(this,ee).permissions)!=null&&i.chatPrivate.canSend)||!((a=n(this,ee).permissions)!=null&&a.chatPrivate.files)){this.logger.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((c=(o=n(this,ee).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=n(this,ee).permissions)==null?void 0:d.chatPublic)!=null&&l.files)){this.logger.error("sendImageMessage::permission_denied");return}if(!t){this.logger.error("sendImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(t.type)){this.logger.error("sendImageMessage::image_type_not_supported",{chat:{imageType:t.type}});return}try{const u=Lt(),{getLocation:h,putLocation:f}=await u.getPresignedUrls(t.name);await u.uploadFile(t,f);let S=[];e&&e.length>0&&(e.push(n(this,ee).id),S=n(this,Ti).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),S.push(n(this,ee).userId)),n(this,ze).sendMessage(h,Xt.IMAGE,e)}catch(u){throw new C("Error sending image message.","0500",this.logger)}}async sendFileMessageInternal(t,e){var r,i,a,o,c,d;if(e&&e.length>0){if(!((r=n(this,ee).permissions)!=null&&r.chatPrivate.canSend)||!((i=n(this,ee).permissions)!=null&&i.chatPrivate.files)){this.logger.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(a=n(this,ee).permissions)==null?void 0:a.chatPublic)!=null&&o.canSend)||!((d=(c=n(this,ee).permissions)==null?void 0:c.chatPublic)!=null&&d.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!t){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const l=Lt(),{getLocation:u,putLocation:h}=await l.getPresignedUrls(t.name);await l.uploadFile(t,h);let f=[];e&&e.length>0&&(e.push(n(this,ee).id),f=n(this,Ti).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),f.push(n(this,ee).userId));const S=JSON.stringify({link:u,name:t.name,size:"size"in t?t.size:0});n(this,ze).sendMessage(S,Xt.FILE,e)}catch(l){throw new C("Error sending file message.","0500",this.logger)}}get rateLimits(){return vd}updateRateLimits(t,e){vd.maxInvocations=t,vd.period=e}async sendTextMessage(t,e){return this.sendTextMessageInternal(t,e)}async sendCustomMessage(t,e){var a,o,c,d,l,u,h,f,S,E,R,M,D,I,x;if(e&&e.length>0){if(!((a=n(this,ee).permissions)!=null&&a.chatPrivate.canSend)||!((o=n(this,ee).permissions)!=null&&o.chatPrivate.files)||!((c=n(this,ee).permissions)!=null&&c.chatPrivate.text)){this.logger.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((l=(d=n(this,ee).permissions)==null?void 0:d.chatPublic)!=null&&l.canSend)||!((h=(u=n(this,ee).permissions)==null?void 0:u.chatPublic)!=null&&h.files)||!((S=(f=n(this,ee).permissions)==null?void 0:f.chatPublic)!=null&&S.text)){this.logger.error("sendCustomMessage::permission_denied");return}const r=async $=>{try{if(typeof $=="string")return{link:$};const B=Lt(),{getLocation:z,putLocation:Z}=await B.getPresignedUrls($.name);return await B.uploadFile($,Z),{link:z,type:$.type,name:$.name,size:$.size}}catch(B){throw new C("Error sending image message.","0500",this.logger)}},i={...t,files:await Promise.all((R=(E=t.files)!=null?E:[])==null?void 0:R.map(async $=>r($))),images:await Promise.all((D=(M=t.images)!=null?M:[])==null?void 0:D.map(async $=>r($))),videos:await Promise.all((x=(I=t.videos)!=null?I:[])==null?void 0:x.map(async $=>r($)))};n(this,ze).sendMessage(JSON.stringify(i),Xt.CUSTOM,e)}async sendImageMessage(t,e){return this.sendImageMessageInternal(t,e)}async sendFileMessage(t,e){return this.sendFileMessageInternal(t,e)}async sendMessage(t,e){return this.sendMessageInternal(t,e)}async editTextMessage(t,e){var r,i,a,o;if(!((i=(r=n(this,ee).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(a=n(this,ee).permissions)==null?void 0:a.chatPublic)!=null&&o.text)){this.logger.error("editTextMessage::permission_denied");return}if(!e){this.logger.error("editTextMessage::message_can_not_be_empty");return}n(this,ze).editMessage(t,e,Xt.TEXT)}async editImageMessage(t,e){var i,a,o,c;if(!((a=(i=n(this,ee).permissions)==null?void 0:i.chatPublic)!=null&&a.canSend)||!((c=(o=n(this,ee).permissions)==null?void 0:o.chatPublic)!=null&&c.files)){this.logger.error("editImageMessage::permission_denied");return}if(!e){this.logger.error("editImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(e.type)){this.logger.error("sendImageMessage::image_type_not_supported",{chat:{imageType:e.type}});return}try{const d=Lt(),{getLocation:l,putLocation:u}=await d.getPresignedUrls(e.name);await d.uploadFile(e,u),n(this,ze).editMessage(t,l,Xt.IMAGE)}catch(d){throw new C("Error editing image message.","0500",this.logger)}}async editFileMessage(t,e){var r,i,a,o;if(!((i=(r=n(this,ee).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(a=n(this,ee).permissions)==null?void 0:a.chatPublic)!=null&&o.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!e){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const c=Lt(),{getLocation:d,putLocation:l}=await c.getPresignedUrls(e.name);await c.uploadFile(e,l),n(this,ze).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),Xt.FILE)}catch(c){throw new C("Error editing file message.","0500",this.logger)}}async editMessage(t,e){switch(e.type){case"text":{this.editTextMessage(t,e.message);break}case"image":{this.editImageMessage(t,e.image);break}case"file":{this.editFileMessage(t,e.file);break}default:{this.logger.error("editMessage::message_type_not_supported",{chat:{messageType:e.type}});break}}}async deleteMessage(t){n(this,ze).deleteMessage(t)}async pin(t){if(!n(this,Lo,Zu))throw new C("Can`t pin message without joining room","0505");try{await n(this,ze).setPinState(t,!0)}catch(e){throw new C(`No message found with id: ${t}`,"0504")}}async unpin(t){if(!n(this,Lo,Zu))throw new C("Can`t unpin message without joining room","0505");try{await n(this,ze).setPinState(t,!1)}catch(e){throw new C(`No message found with id: ${t}`,"0504")}}async fetchPublicMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await n(this,ze).getChatMessagesPaginated(t,e,r==="before")).messages.map(o=>To.formatSocketPeerMessage(o))}async fetchPrivateMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after",userId:i}){return(await n(this,ze).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"userId",userId:i})).messages.map(c=>To.formatSocketPeerMessage(c))}async fetchPinnedMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await n(this,ze).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"pinned",pinned:!0})).messages.map(o=>To.formatSocketPeerMessage(o))}},ee=new WeakMap,Ti=new WeakMap,ze=new WeakMap,xn=new WeakMap,Kd=new WeakSet,Xf=function(){return n(this,xn).getValue("connectionHandler")},Lo=new WeakSet,Zu=function(){return n(this,Kd,Xf).socketJoined===!0},em);$s([y.trace("Chat.sendTextMessage"),Ut(vd)],es.prototype,"sendTextMessage",1);$s([y.trace("Chat.sendImageMessage"),Ut({maxInvocations:20,period:60})],es.prototype,"sendImageMessage",1);$s([y.trace("Chat.sendFileMessage"),Ut({maxInvocations:20,period:60})],es.prototype,"sendFileMessage",1);$s([y.trace("Chat.sendMessage"),Ut({maxInvocations:180,period:60})],es.prototype,"sendMessage",1);$s([y.trace("Chat.editTextMessage")],es.prototype,"editTextMessage",1);$s([y.trace("Chat.editImageMessage")],es.prototype,"editImageMessage",1);$s([y.trace("Chat.editFileMessage")],es.prototype,"editFileMessage",1);$s([y.trace("Chat.editMessage")],es.prototype,"editMessage",1);$s([y.trace("Chat.deleteMessage")],es.prototype,"deleteMessage",1);es=$s([it("0500")],es);var d0=Object.defineProperty,l0=Object.getOwnPropertyDescriptor,u0=(s,t,e,r)=>{for(var i=r>1?void 0:r?l0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&d0(t,e,i),i},Si,tm;const Cr=(tm=class{constructor(s,t,e,r){p(this,"chat");p(this,"chatSocketHandler");p(this,"self");g(this,Si,void 0);m(this,Si,s),this.chatSocketHandler=t,this.chat=new es(s,t,e,r),this.self=e,this.setupEvents()}get telemetry(){return n(this,Si).getValue("telemetry")}get logger(){return n(this,Si).getValue("logger")}static async init(s,t,e,r){return new Cr(s,t,e,r)}static formatMessage(s){return{...s,time:new Date(s.time),type:c0[s.type]}}static formatSocketPeerMessage(s){const t=s.createdAt*1e3,e={displayName:s.displayName,id:s.chatId,time:t,timeMs:s.createdAtMs,type:s.payloadType,isEdited:s.isEdited,userId:s.userId,targetUserIds:s.targetUserIds,message:"",link:"",name:"",html:"",images:[],videos:[],files:[],size:0,pinned:s.pinned};switch(e.type){case Xt.TEXT:{e.message=s.payload;break}case Xt.IMAGE:{e.link=s.payload;break}case Xt.FILE:{const{link:r,name:i,size:a}=JSON.parse(s.payload);e.link=r,e.name=i,e.size=a;break}case Xt.CUSTOM:{const{html:r,images:i,message:a,videos:o,files:c}=JSON.parse(s.payload);e.message=a,e.html=r,e.images=i,e.videos=o,e.files=c;break}}return Cr.formatMessage(e)}async getChatMessages(){if(this.self.config.viewType==="LIVESTREAM")return;const s=await this.chatSocketHandler.getChatMessages();if(!(s!=null&&s.payload))return;const t=Jf.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>Cr.formatSocketPeerMessage(e))}setupEvents(){n(this,Si).getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(We.sendMessageToRoom,s=>{if(!s.message)return;const t=Cr.formatSocketPeerMessage(s.message);this.chat.messages=[...this.chat.messages,t],this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(We.sendMessageToPeers,s=>{const t=Cr.formatSocketPeerMessage(s.message);this.chat.messages=[...this.chat.messages,t],this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(We.editMessage,s=>{if(!s.message)return;const t=Cr.formatSocketPeerMessage(s.message),e=this.chat.messages.findIndex(r=>r.id===t.id);e!==-1&&(this.chat.messages[e]=t),this.chat.emit("chatUpdate",{action:"edit",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(We.deleteMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId);let e={id:s.chatId};t!==-1&&([e]=this.chat.messages.splice(t,1)),this.chat.emit("chatUpdate",{action:"delete",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(We.pinMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId),e=Cr.formatSocketPeerMessage(s.message);t!==-1&&(this.chat.messages[t]=e),this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages}),s.pinned?this.chat.emit("pinMessage",{message:e,messages:this.chat.messages}):this.chat.emit("unpinMessage",{message:e,messages:this.chat.messages})})}},Si=new WeakMap,tm);let To=Cr;u0([y.trace("ChatController.setupEvents")],To.prototype,"setupEvents",1);var h0=Object.defineProperty,p0=Object.getOwnPropertyDescriptor,g0=(s,t,e,r)=>{for(var i=r>1?void 0:r?p0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&h0(t,e,i),i},zd,Zf,Yd,eT,Un,Hn,Vo,sm;let eh=(sm=class extends xt{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,zd);g(this,Yd);p(this,"items");g(this,Un,void 0);g(this,Hn,void 0);g(this,Vo,void 0);m(this,Vo,t),m(this,Un,e),m(this,Hn,r),this.items=[]}async create(t,e,r=!1,i=!1){if(!n(this,Yd,eT))throw new C("Can't create polls without joining room","0705");if(!n(this,Un).permissions.polls.canCreate){this.logger.error("Polls::create::permission_denied");return}if(!t||!e){this.logger.error("Polls::question_and_options_can_not_be_empty",{polls:{hasQuestion:!!t,optionsLength:e==null?void 0:e.length}});return}if(e.length<2){this.logger.error("Polls::there_must_be_at_least_two_options",{polls:{hasQuestion:!!t,optionsLength:e.length}});return}await n(this,Hn).createPoll(t,e,r,i)}async vote(t,e){if(!n(this,Un).permissions.polls.canVote){this.logger.error("Polls::vote::permission_denied");return}await n(this,Hn).votePoll(t,e)}},zd=new WeakSet,Zf=function(){return n(this,Vo).getValue("connectionHandler")},Yd=new WeakSet,eT=function(){var t;return((t=n(this,zd,Zf))==null?void 0:t.socketJoined)===!0},Un=new WeakMap,Hn=new WeakMap,Vo=new WeakMap,sm);eh=g0([it("0700")],eh);var m0=Object.defineProperty,f0=Object.getOwnPropertyDescriptor,T0=(s,t,e,r)=>{for(var i=r>1?void 0:r?f0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&m0(t,e,i),i},Nr,Bn,vi,rm;const vn=(rm=class{constructor(s,t,e){p(this,"polls");g(this,Nr,void 0);g(this,Bn,void 0);g(this,vi,void 0);this.polls=new eh(s,t,e),m(this,Bn,t),m(this,Nr,s),m(this,vi,e),this.setupEvents()}get telemetry(){return n(this,Nr).getValue("telemetry")}get logger(){return n(this,Nr).getValue("logger")}static async init(s,t,e){return new vn(s,t,e)}canViewPolls(){return n(this,Bn).permissions.polls.canView}setupEvents(){const s={[Bs.createPoll]:r=>{r.poll&&this.updatePoll(vn.formatSocketServicePoll(r.poll))},[Bs.updatePoll]:r=>{r.poll&&this.updatePoll(vn.formatSocketServicePoll(r.poll))},[Bs.votePoll]:r=>{r.poll&&this.updatePoll(vn.formatSocketServicePoll(r.poll))}},t=()=>{n(this,Nr).getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{n(this,vi).on(r,s[r])})},e=()=>{n(this,Nr).getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{n(this,vi).removeListeners(r)})};n(this,Bn).permissions.on("permissionsUpdate",async r=>{var i;r!=null&&r.polls&&((i=r==null?void 0:r.polls)!=null&&i.canView?(await this.getPolls(),t()):(this.polls.items=[],e()))}),this.canViewPolls()&&t()}updatePoll(s){if(!this.canViewPolls())return;const t=this.polls.items.findIndex(e=>e.id===s.id);if(t>-1){const e=JSON.stringify(this.polls.items[t]);this.polls.items[t]=s,e!==JSON.stringify(s)&&this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!1});return}this.polls.items=[...this.polls.items,s],this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!0})}async getPolls(){const s=await n(this,vi).getPolls();if(!(s!=null&&s.payload))return;const{polls:t}=OI.fromBinary(s.payload);this.polls.items=t.map(e=>vn.formatSocketServicePoll(e))}static formatSocketServicePoll(s){const t=s.options.map(e=>({count:e.count,text:e.text,votes:e.votes.map(r=>({id:r.userId,name:r.name}))}));return{anonymous:s.anonymous,createdBy:s.createdBy,createdByUserId:s.createdByUserId,hideVotes:s.hideVotes,id:s.pollId,options:t,question:s.question,voted:s.votes}}},Nr=new WeakMap,Bn=new WeakMap,vi=new WeakMap,rm);let tT=vn;T0([y.trace("PollController.setupEvents")],tT.prototype,"setupEvents",1);var S0=Object.defineProperty,v0=Object.getOwnPropertyDescriptor,y0=(s,t,e,r)=>{for(var i=r>1?void 0:r?v0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&S0(t,e,i),i};const $d=Symbol("ApplyRemoteTitleSync");var sT=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))(sT||{}),yi,$o,sh,Ws,Fn,im;let th=(im=class extends xt{constructor(t,e,r,i,a){const o=t.getValue("logger");super(o);g(this,$o);p(this,"selfActiveTab");p(this,"broadcastTabChanges");g(this,yi,void 0);g(this,Ws,void 0);g(this,Fn,void 0);p(this,"viewType");p(this,"meetingStartedTimestamp");p(this,"meetingTitle");p(this,"sessionId");m(this,yi,t),m(this,Ws,e),this.viewType=r,m(this,Fn,i),this.meetingTitle=a,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return n(this,$o,sh).socketState}get mediaState(){return n(this,$o,sh).mediaState}[$d](t){this.meetingTitle=t,this.emit("meetingTitleUpdate",{meetingTitle:t})}get meetingId(){return n(this,yi).getValue("meetingId")}async setMeetingTitle(t){var i,a,o;const e=(i=n(this,yi).getValue("meeting"))==null?void 0:i.connectedMeetings;if(((a=e==null?void 0:e.parentMeeting)==null?void 0:a.id)&&(e!=null&&e.isActive)){if(!((o=n(this,Ws).permissions.connectedMeetings)!=null&&o.canAlterConnectedMeetings))throw this.logger.error("Meta::setMeetingTitle::permission_denied"),new C("User does not have permission to edit the meeting title","0801");await e.updateMeetings([{id:this.meetingId,title:t}]);return}if(!n(this,Ws).permissions.canEditMeetingTitle)throw this.logger.error("Meta::setMeetingTitle::permission_denied"),new C("User does not have permission to edit the meeting title","0801");await n(this,Fn).updateRoomTitle(t)}setBroadcastTabChanges(t){if(!n(this,Ws).permissions.canSpotlight)throw this.logger.error("Spotlight::setSpotlighted::permission_denied"),new C("User does not have permission to toggle spotlight","0801");this.broadcastTabChanges=t,this.emit("broadcastTabChangesUpdate",this.broadcastTabChanges),this.broadcastTabChanges&&this.assertActiveTabToRoom()}setSelfActiveTab(t,e){var r;this.logger.info("Spotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(r=n(this,Ws).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){n(this,Fn).broadcastMessage("spotlight",{userId:n(this,Ws).userId,currentTab:this.selfActiveTab})}},yi=new WeakMap,$o=new WeakSet,sh=function(){return n(this,yi).getValue("connectionHandler")},Ws=new WeakMap,Fn=new WeakMap,im);th=y0([it("0800")],th);function E0(s){let t="",e=[""];const r=[e];let i=0,a=0,o=!0,c;for(c of s)c==='"'?(o&&c===t&&(e[i]+=c),o=!o):c===","&&o?c=e[++i]="":c===`
7
7
  `&&o?(t==="\r"&&(e[i]=e[i].slice(0,-1)),e=r[++a]=[c=""],i=0):e[i]+=c,t=c;return r}var P0=Object.defineProperty,w0=Object.getOwnPropertyDescriptor,rT=(s,t,e,r)=>{for(var i=r>1?void 0:r?w0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&P0(t,e,i),i},xo,nm;let on=(nm=class extends xt{constructor(t){const e=t.getValue("logger");super(e);p(this,"transcripts");g(this,xo,void 0);m(this,xo,t),this.transcripts=[]}get telemetry(){return n(this,xo).getValue("telemetry")}static async init(t,e){const r=new on(t),i=t.getValue("logger");try{e&&r.getActiveTranscript()}catch(a){i.error("Error fetching active transcriptions ",a)}return r}static parseTranscript(t,e=!1){if(!t)return;const[[r,i,a,o,c,d]]=E0(t);return{id:pr.v4(),name:c,peerId:i,userId:a,customParticipantId:o,transcript:d,isPartialTranscript:e,date:new Date(parseInt(r,10)*1e3)}}static parseTranscripts(t){return t?t.split(`
8
8
  `).map(e=>on.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=Lt(),{transcript:e}=await t.getActiveTranscript();this.transcripts=on.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)}},xo=new WeakMap,nm);rT([y.trace("Ai.getActiveTranscript")],on.prototype,"getActiveTranscript",1);on=rT([it("0000")],on);var _0=Object.defineProperty,C0=Object.getOwnPropertyDescriptor,R0=(s,t,e,r)=>{for(var i=r>1?void 0:r?C0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&_0(t,e,i),i},Lr,Ei,bt,am;const rh=(am=class{constructor(s,t,e,r,i,a){p(this,"meta");p(this,"ai");g(this,Lr,void 0);g(this,Ei,void 0);p(this,"aiSocketHandler");g(this,bt,void 0);m(this,bt,s),this.meta=new th(s,t,t.config.viewType,e,a),this.ai=r,m(this,Lr,t),m(this,Ei,e),this.aiSocketHandler=i,this.setupEvents()}get telemetry(){return n(this,bt).getValue("telemetry")}get logger(){return n(this,bt).getValue("logger")}static async init(s,t,e,r,i){const a=await on.init(s,t.permissions.transcriptionEnabled);return new rh(s,t,e,a,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,sT.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){n(this,bt).getValue("peerSessionStore").on(w.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),n(this,bt).getValue("peerSessionStore").on(w.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),n(this,bt).getValue("peerSessionStore").on(w.ROOM_STATE,({createdAt:s,roomUuid:t,title:e})=>{e&&e!==this.meta.meetingTitle&&this.meta[$d](e);const r=this.meta.meetingStartedTimestamp;if(t&&(this.meta.sessionId=t),s&&!r){const i=new Date(s*1e3);this.meta.meetingStartedTimestamp=i,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),n(this,bt).getValue("peerSessionStore").on(w.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),n(this,Lr).permissions.canSpotlight&&this.meta.selfActiveTab&&(this.logger.info("Asserting Spotlight status to other peers."),n(this,Ei).broadcastMessage("spotlight",{userId:n(this,Lr).userId,currentTab:this.meta.selfActiveTab})),n(this,bt).getValue("peerSessionStore").on(w.PEER_JOINED_INTERNAL,async s=>{n(this,Lr).permissions.canSpotlight&&this.meta.selfActiveTab&&n(this,Ei).broadcastToPeers("spotlight",[s.id],{userId:n(this,Lr).userId,currentTab:this.meta.selfActiveTab})}),n(this,bt).getValue("peerSessionStore").on(w.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)}),n(this,bt).getValue("peerSessionStore").on(w.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)}),n(this,Ei).on(L.updateRoomInfo,s=>{var e;const t=(e=s==null?void 0:s.room)==null?void 0:e.title;!t||t===this.meta.meetingTitle||this.meta[$d](t)}),this.aiSocketHandler.on(L.transcript,s=>{let t;try{t=rh.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:pr.v4(),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}},Lr=new WeakMap,Ei=new WeakMap,bt=new WeakMap,am);let iT=rh;R0([y.trace("MetaController.setupEvents")],iT.prototype,"setupEvents",1);const eo={},Er={executeWithLock({methodName:s,lockName:t,timeout:e}){return(r,i,a)=>{const o=a.value;return a.value=function(...d){var E,R;const l=(R=(this==null?void 0:this.peerId)||((E=d[0])==null?void 0:E.authToken))!=null?R:"",u=`${t}-${l}`,h=this==null?void 0:this.logger;if(eo[u]){const M=new Error(`Unsupported concurrent calls on method: ${s}.`);throw M.name="UnsupportedConcurrentMethodExecution",h==null||h.error("Locker::UnsupportedConcurrentMethodExecution",{error:{stack:M.stack},locker:{methodName:s,lockName:u}}),M}eo[u]=!0;const f=setTimeout(()=>delete eo[u],e),S=o.apply(this,d);return Promise.resolve(S).then(()=>{delete eo[u],clearTimeout(f)}).catch(()=>{delete eo[u],clearTimeout(f)}),S},a}}};var k0=Object.defineProperty,b0=Object.getOwnPropertyDescriptor,gn=(s,t,e,r)=>{for(var i=r>1?void 0:r?b0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&k0(t,e,i),i},Gt,Qd,ie,Uo,Ts,$e,Ho,ih,jn,yd;class ci extends xt{constructor(e,r,i,a,o){const c=e.getValue("logger");super(c);g(this,Ho);g(this,jn);g(this,Gt,void 0);g(this,Qd,void 0);g(this,ie,void 0);g(this,Uo,void 0);g(this,Ts,void 0);g(this,$e,void 0);m(this,$e,e),m(this,Gt,a),m(this,Qd,o),m(this,ie,r),m(this,Uo,i),m(this,Ts,[]),this.setupEvents()}get telemetry(){return n(this,$e).getValue("telemetry")}get status(){return n(this,$e).getValue("stageStatus")}setupEvents(){const e={[w.GET_STAGE_REQUESTS]:async a=>{m(this,Ts,a)},[w.UPDATE_STAGE_REQUESTS]:async({add:a})=>{const o=n(this,Ts).length,{stageRequests:c}=this.getAccessRequests();(a||c.length>o)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)}},r=()=>{Object.entries(e).forEach(([a,o])=>{n(this,$e).getValue("peerSessionStore").onAsync(a,o)})},i=()=>{Object.entries(e).forEach(([a,o])=>{n(this,$e).getValue("peerSessionStore").removeListener(a,o)})};n(this,ie).permissions.on("permissionsUpdate",a=>{const{canAcceptProductionRequests:o}=a;o!==void 0&&(n(this,ie).permissions.acceptStageRequests?(r(),n(this,Gt).getStageRequests()):(i(),m(this,Ts,[]),this.emit("stageAccessRequestUpdate",n(this,Ts))))}),n(this,ie).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!n(this,ie).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!n(this,ie).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=n(this,Uo).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return m(this,Ts,e),{stageRequests:n(this,Ts)}}async requestAccess(){if(!n(this,ie).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(n(this,ie).permissions.stageAccess===j.Allowed){k(this,jn,yd).call(this,"ACCEPTED_TO_JOIN_STAGE");return}n(this,Gt).requestAccess(),k(this,jn,yd).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!n(this,ie).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");n(this,Gt).cancelRequestAccess(),k(this,jn,yd).call(this,"OFF_STAGE")}grantAccess(e){if(!n(this,ie).roomJoined)throw new C("Can`t grant for participant without joining room");if(!n(this,ie).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!n(this,ie).permissions.acceptStageRequests)throw this.logger.error("Stage::grant_access::permission_denied"),new C("You do not have permission to perform this action","2001");return n(this,Gt).grantAccess(e)}denyAccess(e){if(!n(this,ie).roomJoined)throw new C("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!n(this,ie).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!n(this,ie).permissions.acceptStageRequests)throw this.logger.error("Stage::deny_access::permission_denied"),new C("You do not have permission to perform this action","2001");return n(this,Gt).denyAccess(e)}get peerId(){return n(this,$e).getValue("peerId")}async join(){const e=n(this,$e).getValue("viewType");if(this.status==="ON_STAGE")throw new C("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||n(this,ie).permissions.stageAccess===j.NotAllowed)throw new C(`Unable to join stage you are currently ${this.status}`,"2006");if(n(this,$e).setValue("stageStatus","ON_STAGE",!1),await n(this,Gt).joinStage(),e===hs.Livestream){await n(this,$e).getValue("selfController").joinRoom();return}n(this,$e).notify("stageStatus"),n(this,ie).audioEnabled&&n(this,Ho,ih).shareMic(n(this,ie).audioTrack),n(this,ie).videoEnabled&&n(this,Ho,ih).shareWebcam(n(this,ie).videoTrack)}async leave(){if(!n(this,ie).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");n(this,ie).setIsPinned(!1),n(this,$e).setValue("stageStatus","OFF_STAGE",!1),await n(this,Gt).leaveStage(n(this,ie).userId);try{await n(this,$e).getValue("peerSessionStore").emitAsync(w.LEAVE_MEDIA_ROOM,"stageLeft")}catch(e){this.logger.error("Stage::leave::emitAsync::failed",{error:e})}n(this,$e).notify("stageStatus")}async kick(e){if(!n(this,ie).roomJoined)throw new C("Can`t kick participant without joining room","2005");if(!n(this,ie).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!n(this,ie).permissions.acceptStageRequests)throw this.logger.error("Stage::kick::permission_denied"),new C("You do not have permissions for kick","2001");return n(this,Gt).kick(e)}}Gt=new WeakMap,Qd=new WeakMap,ie=new WeakMap,Uo=new WeakMap,Ts=new WeakMap,$e=new WeakMap,Ho=new WeakSet,ih=function(){return n(this,$e).getValue("roomNodeClient")},jn=new WeakSet,yd=async function(e){this.status!==e&&n(this,$e).setValue("stageStatus",e)};gn([y.trace("Stage.getStageRequests")],ci.prototype,"getAccessRequests",1);gn([y.trace("Stage.requestAccess")],ci.prototype,"requestAccess",1);gn([y.trace("Stage.cancelRequestAccess")],ci.prototype,"cancelRequestAccess",1);gn([y.trace("Stage.grantAccess")],ci.prototype,"grantAccess",1);gn([y.trace("Stage.denyAccess")],ci.prototype,"denyAccess",1);gn([Er.executeWithLock({methodName:"joinStage",lockName:"Stage.join",timeout:5e3}),y.trace("Stage.joinStage")],ci.prototype,"join",1);gn([y.trace("Stage.leaveStage")],ci.prototype,"leave",1);function M0(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function lp(s){switch(s){case lr.UNSPECIFIED:return"OFF_STAGE";case lr.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case lr.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case lr.OFF_STAGE:return"OFF_STAGE";case lr.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var A0=Object.defineProperty,I0=Object.getOwnPropertyDescriptor,D0=(s,t,e,r)=>{for(var i=r>1?void 0:r?I0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&A0(t,e,i),i},Vr,is,$r,Bo,ot;class nT{constructor(t,e,r,i,a){p(this,"stage");g(this,Vr,void 0);g(this,is,void 0);g(this,$r,void 0);g(this,Bo,0);g(this,ot,void 0);m(this,ot,t),this.stage=new ci(t,i,a,e,r),m(this,$r,e),m(this,Vr,i),m(this,is,a),this.setupEvents()}get telemetry(){return n(this,ot).getValue("telemetry")}get logger(){return n(this,ot).getValue("logger")}setupEvents(){n(this,ot).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),n(this,$r).on(L.grantStageAccess,()=>{n(this,Vr).permissions.stageAccess!==j.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),n(this,$r).on(L.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===n(this,Vr).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),n(this,$r).on(L.denyStageAccess,()=>{n(this,Vr).permissions.stageAccess!==j.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),n(this,$r).on(L.getStageRequests,async t=>{var r;if(n(this,Vr).permissions.stageAccess!==j.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await n(this,ot).getValue("peerSessionStore").emitAsync(w.GET_STAGE_REQUESTS,e),n(this,Bo)<e.length&&e.length>0&&this.stage.emit("newStageRequest",{count:e.length}),m(this,Bo,e.length),this.stage.emit("stageAccessRequestUpdate",e)})}getCurrentStageRequests(){return n(this,is).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&&n(this,ot).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=lp(t.stageType),r=n(this,ot).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:n(this,ot).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(r);break;case 0:case 4:default:n(this,ot).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}async peerStageStatusHandler(t){const e=n(this,is).joined.get(t.peerId),r=n(this,is).viewMode==="ACTIVE_GRID";if(!e){this.logger.warn("err::peerStageStatusUpdate: participant not found");return}switch(t.stageType){case 1:e.setStageStatus("ON_STAGE"),r&&n(this,ot).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:n(this,is).viewMode,page:n(this,is).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&&n(this,ot).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:n(this,is).viewMode,page:n(this,is).currentPage});break}n(this,ot).getValue("peerSessionStore").emit(w.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}Vr=new WeakMap,is=new WeakMap,$r=new WeakMap,Bo=new WeakMap,ot=new WeakMap;D0([y.trace("Stage.setupEvents")],nT.prototype,"setupEvents",1);var O0=Object.defineProperty,N0=Object.getOwnPropertyDescriptor,up=(s,t,e,r)=>{for(var i=r>1?void 0:r?N0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&O0(t,e,i),i},Pi,Js,Fo,jo,wi,om;let Io=(om=class extends Da{constructor(t,e,r,i){const a=t.getValue("logger");super(a);p(this,"name");p(this,"icon");p(this,"id");p(this,"permissions");g(this,Pi,void 0);g(this,Js,void 0);g(this,Fo,void 0);g(this,jo,void 0);g(this,wi,void 0);p(this,"active");p(this,"enabledBy");m(this,Fo,t);const o=t.getValue("meetingId");this.id=`${o}:${e.id}`,this.name=e.name,this.icon=e.icon,m(this,jo,e.component),this.permissions=e.permissions,m(this,Pi,i),m(this,Js,r),this.active=!1,this.enabledBy=""}get component(){return n(this,jo)}get telemetry(){return n(this,Fo).getValue("telemetry")}set activePluginsStore(t){m(this,Js,t)}activateForSelf(){m(this,wi,new Date),this.active=!0,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("enabled")}deactivateForSelf(){m(this,wi,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(!n(this,Js))throw new C("Cannot activate plugin: active plugins store is not available yet.","0604");await n(this,Js).set(this.id,{name:this.name,icon:this.icon,id:this.id,enabledBy:n(this,Pi).id}),this.enabledBy=n(this,Pi).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!==n(this,Pi).id)return;if(!n(this,Js))throw new C("Cannot deactivate plugin: active plugins store is not available yet.","0604");const t=n(this,wi)?new Date().getTime()-n(this,wi).getTime():0;await n(this,Js).set(this.id,null),this.deactivateForSelf(),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:t}})}},Pi=new WeakMap,Js=new WeakMap,Fo=new WeakMap,jo=new WeakMap,wi=new WeakMap,om);up([y.trace("Plugin.activatePlugin")],Io.prototype,"activate",1);up([y.trace("Plugin.deactivatePlugin")],Io.prototype,"deactivate",1);Io=up([it("0600")],Io);var Ae,_i;class aT extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:a,onClearEvent:o}=e;super();g(this,Ae,void 0);g(this,_i,void 0);p(this,"onAddEvent");p(this,"onDeleteEvent");p(this,"onClearEvent");m(this,Ae,new Da(r)),this.onAddEvent=i,this.onDeleteEvent=a,this.onClearEvent=o,m(this,_i,new Map)}emit(e,...r){return n(this,Ae).emit(e,...r)}on(e,r){return n(this,Ae).on(e,r)}addListener(e,r){return n(this,Ae).addListener(e,r)}off(e,r){return n(this,Ae).off(e,r)}once(e,r){return n(this,Ae).once(e,r)}prependListener(e,r){return n(this,Ae).prependListener(e,r)}prependOnceListener(e,r){return n(this,Ae).prependOnceListener(e,r)}removeListener(e,r){return n(this,Ae).removeListener(e,r)}removeAllListeners(e){return n(this,Ae).removeAllListeners(e)}listeners(e){return n(this,Ae).listeners(e)}listenerCount(e){return n(this,Ae).listenerCount(e)}getMaxListeners(){return n(this,Ae).getMaxListeners()}setMaxListeners(e){return n(this,Ae).setMaxListeners(e)}eventNames(){return n(this,Ae).eventNames()}add(e,r=!0){return this.set(e.id,e,r)}set(e,r,i=!0){const a=super.set(e,r),o=(c,...d)=>{this.emit(c,r,...d)};return n(this,_i).set(e,o),r.on("*",o),i&&n(this,Ae).emit(this.onAddEvent,r),a}delete(e,r=!0,i=!1){const a=this.get(e);if(!a)return!1;a.removeListener("*",n(this,_i).get(e));const o=super.delete(e);return i&&a.removeAllListeners(),r&&n(this,Ae).emit(this.onDeleteEvent,a),o}clear(e=!0,r=!1){this.forEach(a=>{a.removeListener("*",n(this,_i).get(a.id)),r&&a.removeAllListeners()});const i=super.clear();return e&&n(this,Ae).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}Ae=new WeakMap,_i=new WeakMap;class $g extends aT{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 L0=Object.defineProperty,V0=Object.getOwnPropertyDescriptor,$0=(s,t,e,r)=>{for(var i=r>1?void 0:r?V0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&L0(t,e,i),i};let nh=class{constructor(s){p(this,"all");p(this,"active");this.all=new $g(s),this.active=new $g(s)}};nh=$0([it("0600")],nh);var x0=Object.defineProperty,U0=Object.getOwnPropertyDescriptor,H0=(s,t,e,r)=>{for(var i=r>1?void 0:r?U0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&x0(t,e,i),i},ns,qn,xr,Ci,Xd,cT,qo,ah,Go,oh,Wo,ch,cm;const oT=(cm=class{constructor(s,t,e,r){g(this,Xd);g(this,qo);g(this,Go);g(this,Wo);p(this,"plugins");g(this,ns,void 0);g(this,qn,void 0);g(this,xr,void 0);g(this,Ci,null);m(this,xr,s),this.plugins=t,m(this,qn,e),m(this,ns,r),this.setupEvents()}get telemetry(){return n(this,xr).getValue("telemetry")}get logger(){return n(this,xr).getValue("logger")}static async init(s,t,e,r){var l,u;const i=s.getValue("logger"),a=s.getValue("connectionHandler"),o=new nh(i);let c;a.socketState.state==="connected"?(i.info("Creating active plugins store immediately. Socket is already connected."),c=await r.create(ju,!0)):i.info("Deferring active plugins store creation until socket connects."),t.forEach(h=>{const f=new Io(s,h,c,e);o.all.add(f)});const d=new oT(s,o,r,c);return c?k(l=d,Wo,ch).call(l):k(u=d,Xd,cT).call(u),d}cleanup(){k(this,qo,ah).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)}),n(this,xr).getValue("peerSessionStore").onAsync(w.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()}),!n(this,ns)){this.logger.warn("Active plugins store not available yet on ROOM_JOINED. Sync will be performed when store is created.");return}await k(this,Go,oh).call(this),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to sync active plugins.")})}},ns=new WeakMap,qn=new WeakMap,xr=new WeakMap,Ci=new WeakMap,Xd=new WeakSet,cT=function(){const s=n(this,xr).getValue("peerSessionStore"),t=async e=>{if(e.state==="connected"&&!n(this,ns))try{m(this,ns,await n(this,qn).create(ju,!0)),k(this,qo,ah).call(this),this.plugins.all.toArray().forEach(r=>{r.activePluginsStore=n(this,ns)}),k(this,Wo,ch).call(this),this.logger.info("Active plugins store created after socket connected"),await k(this,Go,oh).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(w.SOCKET_STATE_UPDATE,t),m(this,Ci,()=>{s.off(w.SOCKET_STATE_UPDATE,t)})},qo=new WeakSet,ah=function(){n(this,Ci)&&(n(this,Ci).call(this),m(this,Ci,null))},Go=new WeakSet,oh=async function(){try{await n(this,qn).refresh(n(this,ns).name)}catch(t){this.logger.error("Failed to refresh active plugins store, syncing from stale data.",{error:t})}const s=n(this,ns).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())})},Wo=new WeakSet,ch=function(){n(this,ns).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())})})},cm);let dT=oT;H0([y.trace("PluginController.setupEvents")],dT.prototype,"setupEvents",1);var Jo;class B0{constructor(t){p(this,"mediaJoined");p(this,"socketJoined");p(this,"socketJoinAttempted");p(this,"mediaJoinAttempted");p(this,"socketState");p(this,"mediaState");g(this,Jo,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},m(this,Jo,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,n(this,Jo).getValue("peerSessionStore").emit(w.SOCKET_STATE_UPDATE,r))}}Jo=new WeakMap;var F0=Object.defineProperty,j0=Object.getOwnPropertyDescriptor,td=(s,t,e,r)=>{for(var i=r>1?void 0:r?j0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&F0(t,e,i),i};const xg="Cannot start recording: another recording is already in progress.";var Gn,Wn,Jn,Ed,dm;let ln=(dm=class extends xt{constructor(t,e){const r=t.getValue("logger");super(r);g(this,Jn);g(this,Gn,void 0);g(this,Wn,void 0);p(this,"recordingPeerIds",[]);p(this,"recordings",[]);m(this,Wn,t),m(this,Gn,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 n(this,Wn).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!n(this,Gn).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(xg,"1005");try{const e=Lt(),{recording:r={}}=n(this,Wn).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 Vd&&e.status===409?new C(xg,"1005"):new C("Error while starting recording","1000",this.logger)}}async stop(t){await k(this,Jn,Ed).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await k(this,Jn,Ed).call(this,"pause",["RECORDING"],t)}async resume(t){await k(this,Jn,Ed).call(this,"resume",["PAUSED"],t)}},Gn=new WeakMap,Wn=new WeakMap,Jn=new WeakSet,Ed=async function(t,e,r){if(!n(this,Gn).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 a=this.recordings.find(o=>o.id===r);if(a===void 0)throw new C("Could not find the specified recording","1004");if(e.includes(a.state)){this.logger.error("Recording::stop::recording_not_in_expected_state",{recording:{state:a.state}});return}i.push(a)}else i=this.recordings.filter(a=>e.includes(a.state));i.forEach(async a=>{const o=a.state;t==="stop"&&(a.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{await Lt().updateRecording(a.id,t)}catch(c){throw this.logger.error("Recording::stop::recording_failed_to_stop",{error:c}),a.state!==o&&(a.state=o,this.emit("recordingUpdate",o)),new C("Error while stopping recording","1000",this.logger)}})},dm);td([y.trace("Recording.start")],ln.prototype,"start",1);td([y.trace("Recording.stop")],ln.prototype,"stop",1);td([y.trace("Recording.stop")],ln.prototype,"pause",1);td([y.trace("Recording.stop")],ln.prototype,"resume",1);ln=td([it("1000")],ln);var q0=Object.defineProperty,G0=Object.getOwnPropertyDescriptor,W0=(s,t,e,r)=>{for(var i=r>1?void 0:r?G0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&q0(t,e,i),i},Ri;class lT{constructor(t,e,r){p(this,"recording");p(this,"room");g(this,Ri,void 0);m(this,Ri,t),this.recording=new ln(t,e),this.room=r,this.setupEvents()}get telemetry(){return n(this,Ri).getValue("telemetry")}get logger(){return n(this,Ri).getValue("logger")}getRecordingTypeFromProtoType(t){let e;switch(t){case an.BROWSER:e="BROWSER";break;case an.COMPOSITE:e="COMPOSITE";break;case an.TRACK:e="TRACK";break;default:e="BROWSER"}return e}setupEvents(){n(this,Ri).getValue("peerSessionStore").on(w.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(L.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(L.recordingPaused,t=>{const e=[...this.recording.recordings];e.forEach(r=>{r.id===t.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(e)}),this.room.on(L.recordingStopped,t=>{const e=[...this.recording.recordings.filter(r=>r.id!==t.recordingId)];this.recording.updateRecordings(e)})}}Ri=new WeakMap;W0([y.trace("RecordingController.setupEvents")],lT.prototype,"setupEvents",1);var ki;class J0{constructor(t){g(this,ki,void 0);m(this,ki,t)}hasFeature(t){return n(this,ki).getValue("logger").warn("Unimplemented method: meeting.__internals__.hasFeature called"),!1}getFeatureValue(t){return n(this,ki).getValue("logger").warn("Unimplemented method: meeting.__internals__.getFeatureValue called"),null}getAllFeatures(){return n(this,ki).getValue("logger").warn("Unimplemented method: meeting.__internals__.getAllFeatures called"),{}}}ki=new WeakMap;class hp{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=ye,this.callStats=i}static init(t){return new hp(t.getValue("authToken"),t.getValue("logger"),new J0(t),t.getValue("callstats"))}}class pp{constructor(t){p(this,"internals");this.internals=t}static async init(t){const e=hp.init(t);return new pp(e)}}var K0=Object.defineProperty,z0=Object.getOwnPropertyDescriptor,Ht=(s,t,e,r)=>{for(var i=r>1?void 0:r?z0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&K0(t,e,i),i},Le,Se,me,Ks,Wt,Ko,Ce;class Ct extends Da{constructor(e,r,i=xd,a=!0){const o=e.getValue("logger");super(o);g(this,Le,void 0);g(this,Se,void 0);g(this,me,void 0);g(this,Ks,void 0);g(this,Wt,void 0);g(this,Ko,void 0);g(this,Ce,void 0);p(this,"audioUpdateInProgress");p(this,"videoUpdateInProgress");m(this,Ce,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,m(this,Le,new uT(e,r)),m(this,Se,new SD(e,n(this,Le),void 0,i)),m(this,me,new CD(e,n(this,Le),void 0,i)),m(this,Wt,new PD(n(this,Ce),n(this,Le))),m(this,Ks,new yD(e,n(this,Le))),m(this,Ko,a),n(this,Se).on("trackMuted",this.onAudioTrackMuted.bind(this)),n(this,Se).on("trackChanged",this.onAudioTrackChanged.bind(this)),n(this,me).on("trackChanged",this.onVideoTrackChanged.bind(this)),n(this,me).on("trackEnded",this.onVideoTrackEnded.bind(this)),n(this,Wt).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return n(this,Ce).getValue("telemetry")}set context(e){m(this,Ce,e)}async onVisibilityChange(){n(this,Ce).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?n(this,Ce).getValue("callstats").browserBackgrounded():(n(this,Ce).getValue("callstats").browserForegrounded(),await this.setupSpeaker())}async repopulateAvailableDevices(){return!0}async setupStreams({audio:e,video:r}){var o;e?n(this,Ce).getValue("callstats").audioOn():n(this,Ce).getValue("callstats").audioOff(),r?n(this,Ce).getValue("callstats").videoOn():n(this,Ce).getValue("callstats").videoOff();let i,a;if(e&&r)try{const c=await n(this,Le).getAudioAndVideoTrack(n(this,Se).userSelectedDevice,n(this,me).userSelectedDevice);i=c.audioTrack,a=c.videoTrack}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!i&&e)try{i=await n(this,Le).getAudioTrack(!1,n(this,Se).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!a&&r)try{a=await n(this,Le).getVideoTrack(n(this,me).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}e&&!i&&n(this,Ce).getValue("callstats").audioOff(),r&&!a&&n(this,Ce).getValue("callstats").videoOff(),await n(this,Se).setMediaTrack(i),await n(this,me).setMediaTrack(a);try{await this.setupSpeaker()}catch(c){}if(a){const c=await this.getDeviceById(a.getSettings().deviceId);n(this,Ce).getValue("callstats").selectedDevice("VIDEO",c)}if(i){const c=await this.getDeviceById(i.getSettings().deviceId);n(this,Ce).getValue("callstats").selectedDevice("AUDIO",c)}(o=n(this,Ks).currentDevice)!=null&&o.deviceId&&n(this,Ce).getValue("callstats").selectedDevice("SPEAKER",n(this,Ks).currentDevice),n(this,Le).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})}getCurrentDevices(){return{audio:n(this,Se).currentDevice,video:n(this,me).currentDevice,speaker:n(this,Ks).currentDevice}}get permissions(){return n(this,Le).permissions}getAllDevices(){return n(this,Le).getAvailableDevices()}getDeviceById(e,r){return n(this,Le).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return n(this,Se).mediaTrack}get audioTrack(){return n(this,Se).transformedMediaTrack}get audioEnabled(){return n(this,Se).trackEnabled}async enableAudio(e){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?await n(this,Se).enableTrack(!1,e):await n(this,Se).unmuteTrack()}catch(r){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){n(this,Se).mediaTrack&&!n(this,Se).isCustomTrack?n(this,Se).muteTrack():n(this,Se).disableTrack()}getAudioDevices(e){return n(this,Le).getAudioInputDevices(e)}async setAudioDevice(e,{saveDevicePreference:r}){await n(this,Se).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&n(this,Ce).getValue("callstats").selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async setupSpeaker(){const{speaker:e}=this.getCurrentDevices();await n(this,Ks).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 n(this,Ks).setupSpeaker(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&n(this,Ce).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 n(this,me).mediaTrack}get videoTrack(){return n(this,me).transformedMediaTrack}get videoEnabled(){return n(this,me).trackEnabled}async enableVideo(e){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?await n(this,me).enableTrack(!1,e):await n(this,me).unmuteTrack()}catch(r){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){n(this,me).disableTrack()}getVideoDevices(e){return n(this,Le).getVideoInputDevices(e)}async setVideoDevice(e,{saveDevicePreference:r}){await n(this,me).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&n(this,Ce).getValue("callstats").selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async updateVideoConstraints(e){await n(this,me).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:n(this,Wt).audioMediaTrack,video:n(this,Wt).videoMediaTrack}}get screenShareEnabled(){return n(this,Wt).trackEnabled}async enableScreenShare(){await n(this,Wt).enableScreenShare()}async disableScreenShare(){n(this,Wt).disableScreenShare()}async updateScreenshareConstraints(e){await n(this,Wt).updateConstraints(e)}getSpeakerDevices(e){return n(this,Le).getAudioOutputDevices(e)}addAudioMiddleware(e){return n(this,Se).addMiddleware(e)}removeAudioMiddleware(e){return n(this,Se).removeMiddleware(e)}removeAllAudioMiddlewares(){return n(this,Se).removeAllMiddlewares()}addVideoMiddleware(e){return n(this,me).addMiddleware(e)}removeVideoMiddleware(e){return n(this,me).removeMiddleware(e)}removeAllVideoMiddlewares(){return n(this,me).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return n(this,me).setVideoMiddlewareGlobalConfig(e)}destruct(){n(this,Se).disableTrack(),n(this,me).disableTrack(),n(this,me).terminateMiddlewareWebWorker(),n(this,Wt).disableScreenShare(),n(this,Le).destruct()}async onDeviceChange(e,r){var a,o;if(this.emit("DEVICE_LIST_UPDATED",e),r||!n(this,Ko))return;let i=!1;(a=e==null?void 0:e.added)==null||a.reverse().forEach(async c=>{var d;c&&!xd(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(){n(this,Se).disableTrack()}removeVideoTrack(){n(this,me).disableTrack(),n(this,me).terminateMiddlewareWebWorker()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}Le=new WeakMap,Se=new WeakMap,me=new WeakMap,Ks=new WeakMap,Wt=new WeakMap,Ko=new WeakMap,Ce=new WeakMap;Ht([y.trace("MediaHandler.setupStreams")],Ct.prototype,"setupStreams",1);Ht([y.trace("MediaHandler.enableAudio")],Ct.prototype,"enableAudio",1);Ht([y.trace("MediaHandler.disableAudio")],Ct.prototype,"disableAudio",1);Ht([y.trace("MediaHandler.setAudioDevice")],Ct.prototype,"setAudioDevice",1);Ht([y.trace("MediaHandler.enableVideo")],Ct.prototype,"enableVideo",1);Ht([y.trace("MediaHandler.disableVideo")],Ct.prototype,"disableVideo",1);Ht([y.trace("MediaHandler.setVideoDevice")],Ct.prototype,"setVideoDevice",1);Ht([y.trace("MediaHandler.updateVideoConstraints")],Ct.prototype,"updateVideoConstraints",1);Ht([y.trace("MediaHandler.enableScreenShare")],Ct.prototype,"enableScreenShare",1);Ht([y.trace("MediaHandler.disableScreenShare")],Ct.prototype,"disableScreenShare",1);Ht([y.trace("MediaHandler.updateScreenshareConstraints")],Ct.prototype,"updateScreenshareConstraints",1);Ht([y.trace("MediaHandler.destruct")],Ct.prototype,"destruct",1);Ht([y.trace("MediaHandler.onDeviceChange")],Ct.prototype,"onDeviceChange",1);function pd(s,t,e){switch(!0){case ye.isChromiumBased():switch(t){case"NotAllowedError":return e.includes("by system")?"SYSTEM_DENIED":s==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case ye.isSafari():switch(t){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case ye.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 Y0=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function xd(s){var e,r;const t=(e=s.label)==null?void 0:e.toLowerCase();return((r=ye._bowser)==null?void 0:r.getOSName())==="macOS"&&t.includes("iphone")?!0:Y0.some(i=>t==null?void 0:t.includes(i))}async function Q0(s,t,e){if(!(t!=null&&t.length))return e;const r=s.getValue("logger"),i=new AudioContext,a=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<a.length;l+=1)d.connect(a[l]),d=a[l];d.connect(c)}catch(d){return r.error("getTransformedAudioTrack::middleware_execution_failed",{error:d}),e}return c.stream.getAudioTracks()[0]}var bi,zo;class X0{constructor(t){g(this,bi,void 0);g(this,zo,void 0);m(this,zo,t)}get logger(){return n(this,zo).getValue("logger")}terminateMiddlewareWebWorker(){if(n(this,bi))try{go.clearInterval(n(this,bi)),m(this,bi,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"),a=await Promise.all(t==null?void 0:t.map(f=>f({canvas:i,WorkerTimers:go})));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<a.length;f+=1)typeof a[f]=="function"&&await a[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,m(this,bi,go.setInterval(l,50))},!1);const h=i.captureStream().getVideoTracks()[0];return Object.defineProperty(h,"originalSettings",{value:e.getSettings()}),h}}bi=new WeakMap,zo=new WeakMap;const Z0={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}}},eD=[[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}]]],tD=(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=eD,a=i.map(([h])=>h).sort((h,f)=>h-f);let o=Number.MAX_VALUE,c=0;return a.forEach((h,f)=>{Math.abs(h-r)<o&&(o=Math.abs(h-r),c=f)}),i[c][1]};var Te=(s=>(s.WEBCAM="webcam",s.WEBCAM_BACKUP="webcam_backup",s.MIC="mic",s.SCREENSHARE_VIDEO="screenshare_video",s.SCREENSHARE_AUDIO="screenshare_audio",s))(Te||{});const sD=HC(),Tn=Os(sD.config.media);function rD(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}var Mi,Zd;class iD{constructor(t,e){g(this,Mi,void 0);g(this,Zd,void 0);p(this,"getScreenShareConstraints",()=>{var l,u,h,f,S,E,R,M,D;const t=(l=n(this,Mi))==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=(R=(E=t==null?void 0:t.frameRate)==null?void 0:E.max)!=null?R:5,a=(D=(M=t==null?void 0:t.frameRate)==null?void 0:M.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:a,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 a,o,c,d,l,u,h;const e={},r=(a=n(this,Mi))==null?void 0:a.audio,i=r!=null&&r.enableStereo?2:1;return ye.isFirefox()||ye.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=n(this,Mi))==null?void 0:o.video,i=s_(Z0);let a=i.vga;if(typeof r=="string"){const l=i[r];l&&(a=l)}else r!==void 0&&(a.height.ideal=r.height.ideal,a.width.ideal=r.width.ideal,a.frameRate.ideal=(d=(c=r.frameRate)==null?void 0:c.ideal)!=null?d:30);return e.video=a,typeof e.video=="boolean"||(t?e.video.deviceId={exact:t}:e.video.facingMode="user"),e});m(this,Zd,t),m(this,Mi,e)}getUpdatedVideoConstraints(t){return t}}Mi=new WeakMap,Zd=new WeakMap;class Ou extends Error{constructor(e,r,i){super(r);p(this,"constraints");p(this,"name");this.name=e,this.constraints=i}}class nD{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 aD=Object.defineProperty,oD=Object.getOwnPropertyDescriptor,fs=(s,t,e,r)=>{for(var i=r>1?void 0:r?oD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&aD(t,e,i),i},Kn,Jt,xe,lm;let $t=(lm=class extends nD{constructor(t,e){super();g(this,Kn,void 0);g(this,Jt,void 0);g(this,xe,void 0);m(this,xe,t),m(this,Jt,new iD(t,e)),m(this,Kn,new AbortController)}get telemetry(){return n(this,xe).getValue("telemetry")}get logger(){return n(this,xe).getValue("logger")}get constraintsBuilder(){return n(this,Jt)}async destruct(){var t;(t=n(this,Kn))==null||t.abort()}handlePermissionErrors(t,e){const r=pd(t,e.name,e.message);return this.permissions[t]=r,n(this,xe).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}async getAudioAndVideoTrack(t,e){var r,i,a,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&&((a=d[0])!=null&&a.deviceId)&&(f=(o=d[0])==null?void 0:o.deviceId);const S={audio:n(this,Jt).getAudioConstraints(u).audio,video:n(this,Jt).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 R=E.getAudioTracks()[0];let M=E.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",M.label.includes("OBS Virtual")){const I=(await this.getVideoInputDevices()).find(x=>x.label.includes("OBS Virtual"));M=await this.getVideoTrack(I.deviceId)}return n(this,xe).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),n(this,xe).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:R,videoTrack:M}}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",n(this,xe).getValue("peerSessionStore").emit(w.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 a;e&&i?a=e:(c=r[0])!=null&&c.deviceId&&(a=(d=r[0])==null?void 0:d.deviceId);const o=async l=>{let u;try{r=r.filter(f=>f.deviceId!==l),u=n(this,Jt).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=pd("audio",h.name,h.message),S=new Ou(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 R=n(this,Jt).getAudioConstraints(E.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(R)}),o(E.deviceId)}throw S}};try{const l=await o(a);return l.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",n(this,xe).getValue("peerSessionStore").emit(w.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",n(this,xe).getValue("peerSessionStore").emit(w.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 a;t&&i?a=t:(d=r[0])!=null&&d.deviceId&&(a=(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:R}=S.getSettings(),{ideal:M}=f.width;S.applyConstraints({width:{ideal:M},height:{ideal:Math.floor(R*M/E)},frameRate:f.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(h)}),S}catch(h){const f=pd("video",h.name,h.message),S=new Ou(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 R=n(this,Jt).getVideoConstraints(E.deviceId);return this.logger.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(R)}),o({video:R.video})}throw S}};try{const u=n(this,Jt).getVideoConstraints(a),h=await o(u);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",n(this,xe).getValue("peerSessionStore").emit(w.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)}),n(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=pd("video",r.name,r.message),a=new Ou(r.name,r.message,e),o={video:!0};if(lC(e,o))throw a;if(i==="COULD_NOT_START")return t(o);throw a}};try{const e=n(this,Jt).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",n(this,xe).getValue("peerSessionStore").emit(w.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 a=((o=i.label)==null?void 0:o.toLowerCase())||"";return xd(i)?4:a.includes("airpods")||a.includes("airdopes")||a.includes("bluetooth")||a.includes("wireless")||a.includes("headphones")||a.includes("headset")&&!a.includes("earpiece")||a.includes("earbuds")||a.includes("usb")||a.includes("external")?0:i.deviceId==="default"||a.includes("default")?1:a.includes("built-in")||a.includes("internal")?2:3},r=i=>{var o;if(i.kind!=="videoinput")return!1;const a=((o=i.label)==null?void 0:o.toLowerCase())||"";return a.includes("front")||a.includes("user")||a.includes("selfie")?!0:!(a.includes("back")||a.includes("rear")||a.includes("environment"))};return t.sort((i,a)=>{var u,h;const o=e(i),c=e(a);if(o!==c)return o-c;const d=i.deviceId==="default"||((u=i.label)==null?void 0:u.toLowerCase().includes("default")),l=a.deviceId==="default"||((h=a.label)==null?void 0:h.toLowerCase().includes("default"));if(d&&!l)return-1;if(!d&&l)return 1;if(i.kind==="videoinput"&&a.kind==="videoinput"){const f=r(i),S=r(a);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(ye.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}`,a=new Set(e.map(h=>i(h))),o=await this.getAvailableDevices(),c=new Set(o.map(h=>i(h))),d={added:o.filter(h=>!a.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")&&n(this,xe).getValue("callstats").devices("AUDIO",o==null?void 0:o.filter(f=>f.kind==="audioinput")),h.some(f=>f.kind==="videoinput")&&n(this,xe).getValue("callstats").devices("VIDEO",o==null?void 0:o.filter(f=>f.kind==="videoinput")),h.some(f=>f.kind==="audiooutput")&&n(this,xe).getValue("callstats").devices("SPEAKER",o==null?void 0:o.filter(f=>f.kind==="audiooutput")),t(r,d,!1)}},{signal:n(this,Kn).signal})}}},Kn=new WeakMap,Jt=new WeakMap,xe=new WeakMap,lm);fs([y.trace("WebMediaInterface.destruct")],$t.prototype,"destruct",1);fs([y.trace("WebMediaInterface.handlePermissionErrors")],$t.prototype,"handlePermissionErrors",1);fs([y.trace("WebMediaInterface.getAudioAndVideoTrack")],$t.prototype,"getAudioAndVideoTrack",1);fs([y.trace("WebMediaInterface.getAudioTrack")],$t.prototype,"getAudioTrack",1);fs([y.trace("WebMediaInterface.getVideoTrack")],$t.prototype,"getVideoTrack",1);fs([y.trace("WebMediaInterface.getScreenShareTracks")],$t.prototype,"getScreenShareTracks",1);fs([y.trace("WebMediaInterface.getAvailableDevices")],$t.prototype,"getAvailableDevices",1);fs([y.trace("WebMediaInterface.getAvailableDevicesByKind")],$t.prototype,"getAvailableDevicesByKind",1);fs([y.trace("WebMediaInterface.getDevice")],$t.prototype,"getDevice",1);fs([y.trace("WebMediaInterface.onDeviceChange")],$t.prototype,"onDeviceChange",1);$t=fs([it("1600")],$t);const uT=$t,cn={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}},cD=(s=0)=>new Promise(t=>setTimeout(t,s)),dD=(s,t,e)=>{const r=typeof e=="number"?e:250,i=s.createMediaStreamSource(t),a=s.createAnalyser();a.fftSize=2048,i.connect(a);const o=new Uint8Array(a.fftSize);let c=!1;setTimeout(()=>{c=!0},r);function d(){return c?Promise.resolve(!0):(a.getByteTimeDomainData(o),o.some(l=>l!==128&&l!==0)?Promise.resolve(!1):cD().then(d))}return d().then(l=>(i.disconnect(),l),l=>{throw i.disconnect(),l})},lD=typeof AudioContext!="undefined"?AudioContext:null;class gp{constructor(t){p(this,"_AudioContext");p(this,"audioContext");p(this,"_audioContextRefContainers");const e={AudioContext:lD,...t};Object.defineProperties(this,{_AudioContext:{value:e.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:gp}})}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 Ug=new gp,uD=3,hD=250;function pD(s){const t={},e=Ug.getOrCreate(t);let r=uD;function i(){return r-=1,dD(e,s.srcObject,hD).then(a=>a?r>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{Ug.release(t)})}async function Hg(s,t){const e=new Audio,r=new MediaStream;r.addTrack(t),e.srcObject=r;let i=!1;try{const a=e.play();a&&await a,i=await pD(e),i&&s.info("checkIfAudioTrackIsSilent::silence_detected")}catch(a){s.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:a})}finally{e.pause(),e.remove()}return i}var gD=Object.defineProperty,mD=Object.getOwnPropertyDescriptor,hT=(s,t,e,r)=>{for(var i=r>1?void 0:r?mD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&gD(t,e,i),i};let Ud=class extends Da{constructor(t,e,r,i){var o;const a=t.getValue("logger");super(a);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=>cn.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>cn.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(ye.isWebKitBased()&&!(ye.isSafari()&&_C.test(ye.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))}};hT([y.trace("BaseMediaHandler.unmuteTrack")],Ud.prototype,"unmuteTrack",1);Ud=hT([it("1600")],Ud);const pT=Ud;var fD=Object.defineProperty,TD=Object.getOwnPropertyDescriptor,mp=(s,t,e,r)=>{for(var i=r>1?void 0:r?TD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&fD(t,e,i),i};const Nu="[Realtimekit]nonSilentDeviceLabels";class uu extends pT{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 Q0(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(),a=this.isNonPreferredDevice?i.filter(l=>l&&!this.isNonPreferredDevice(l)):i;if(!(a!=null&&a.length))return r;a.find(l=>l.deviceId===t.getSettings().deviceId)||(r.stop(),this.logger.info("localmediahandler::setupstreams::found_audio_non_preferred"),r=await this.mediaInterface.getAudioTrack(!1,a[0].deviceId));const o=JSON.parse(cn.getItem(Nu,this.logger));if(o!=null&&o.devices.some(l=>l.label===r.label))return r;if(!await Hg(this.logger,r)){const l=(d=o==null?void 0:o.devices.concat({label:r.label}))!=null?d:[{label:r.label}];return cn.setItem(Nu,JSON.stringify({devices:l}),this.logger),r}this.logger.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const c=r.getSettings().deviceId;return a.filter(l=>l.deviceId!==c).some(async l=>{var u;if(r=await this.mediaInterface.getAudioTrack(!1,l.deviceId),!await Hg(this.logger,r)){const h=(u=o==null?void 0:o.devices.concat({label:r.label}))!=null?u:[{label:r.label}];return cn.setItem(Nu,JSON.stringify({devices:h}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),r}}mp([y.trace("AudioMediaHandler.setTransformedTrack")],uu.prototype,"setTransformedTrack",1);mp([y.trace("AudioMediaHandler.onTrackEnded")],uu.prototype,"onTrackEnded",1);mp([y.trace("AudioMediaHandler.conditionallyChangeTrack")],uu.prototype,"conditionallyChangeTrack",1);const SD=uu;var Ai;class vD{constructor(t,e){g(this,Ai,void 0);p(this,"currentDevice");p(this,"userPreferredDeviceKey","Realtimekit::speaker::UserDeviceID");p(this,"logger");p(this,"setUserPreferredDevice",t=>cn.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>cn.getItem(this.userPreferredDeviceKey,this.logger));m(this,Ai,e),this.logger=t.getValue("logger")}async setPreferredSpeaker(){const t=this.getUserPreferredDevice(),e=await n(this,Ai).getAudioOutputDevices(),r=e==null?void 0:e.find(i=>i.deviceId===t);await this.setupSpeaker(r,{saveDevicePreference:!1})}async setupSpeaker(t,{saveDevicePreference:e}){var a,o;if(!(n(this,Ai)instanceof uT))return;let r=t;if(t||([r]=(await n(this,Ai).getAvailableDevicesByKind("audiooutput")).filter(d=>!xd(d))),!r)throw new C("No speaker found","1608");if(((a=this.currentDevice)==null?void 0:a.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){}})}}Ai=new WeakMap;const yD=vD;var Yo;class ED extends Da{constructor(e,r){const i=e.getValue("logger");super(i);p(this,"mediaInterface");p(this,"audioMediaTrack");p(this,"videoMediaTrack");p(this,"previousAudioMediaTrack");p(this,"previousVideoMediaTrack");g(this,Yo,void 0);m(this,Yo,e),this.mediaInterface=r,this.onTrackEnded=this.onTrackEnded.bind(this)}get trackEnabled(){return!!this.videoMediaTrack}async enableScreenShare(){var e,r,i,a,o,c;try{const{audioTrack:d,videoTrack:l}=await this.mediaInterface.getScreenShareTracks();this.audioMediaTrack=d,this.videoMediaTrack=l,this.addMediaTrackListeners(),this.mediaInterface.permissions&&this.mediaInterface.permissions.screenshare!=="ACCEPTED"&&(this.mediaInterface.permissions.screenshare="ACCEPTED",n(this,Yo).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"})),(this.previousAudioMediaTrack||this.previousVideoMediaTrack)&&((e=this.previousAudioMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(r=this.previousVideoMediaTrack)==null||r.removeEventListener("ended",this.onTrackEnded),(i=this.previousAudioMediaTrack)==null||i.removeEventListener("mute",this.onTrackEnded),(a=this.previousVideoMediaTrack)==null||a.removeEventListener("mute",this.onTrackEnded),(o=this.previousAudioMediaTrack)==null||o.stop(),(c=this.previousVideoMediaTrack)==null||c.stop()),this.previousAudioMediaTrack=this.audioMediaTrack,this.previousVideoMediaTrack=this.videoMediaTrack}catch(d){}}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,this.previousAudioMediaTrack=void 0,this.previousVideoMediaTrack=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),ye.isWebKitBased()&&((r=this.videoMediaTrack)==null||r.addEventListener("mute",this.onTrackEnded))}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")}}Yo=new WeakMap;const PD=ED;var wD=Object.defineProperty,_D=Object.getOwnPropertyDescriptor,hu=(s,t,e,r)=>{for(var i=r>1?void 0:r?_D(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&wD(t,e,i),i},zn,Qo;class sd extends pT{constructor(e,r,i,a){super(e,r,i,a);g(this,zn,void 0);g(this,Qo,{disablePerFrameCanvasRendering:!1});m(this,zn,new X0(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 n(this,zn).getTransformedVideoTrack(this.middlewares,this.mediaTrack,n(this,Qo)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){m(this,Qo,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(){n(this,zn).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 a=await this.mediaInterface.getVideoInputDevices(),o=this.isNonPreferredDevice?a.filter(c=>!this.isNonPreferredDevice(c)):a;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}}zn=new WeakMap,Qo=new WeakMap;hu([y.trace("VideoMediaHandler.setTransformedTrack")],sd.prototype,"setTransformedTrack",1);hu([y.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],sd.prototype,"setVideoMiddlewareGlobalConfig",1);hu([y.trace("VideoMediaHandler.onTrackEnded")],sd.prototype,"onTrackEnded",1);hu([y.trace("VideoMediaHandler.conditionallyChangeTrack")],sd.prototype,"conditionallyChangeTrack",1);const CD=sd,Bg=Os(ap());var ct,Ii,Xo,Yn;const Cn=class{constructor(t){g(this,ct,void 0);g(this,Ii,void 0);g(this,Xo,void 0);g(this,Yn,void 0);if(!t)throw new C("Could not load preset.","0904");m(this,ct,t.config),m(this,Xo,t.name),m(this,Ii,t.ui||Os(ap().ui)),m(this,Yn,t.permissions.plugins.config)}static fromResponse(t){return new Cn(t)}static default(){return new Cn(Bg)}static init(t,e=!0){return!t||e?new Cn(Bg):new Cn(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:n(this,Ii).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return n(this,ct).viewType}get livestreamViewerQualities(){return n(this,ct).livestreamViewerQualities||[]}get maxVideoStreams(){return n(this,ct).maxVideoStreams}get maxScreenShareCount(){return n(this,ct).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(n(this,Yn)).filter(t=>n(this,Yn)[t].disabled)}get designTokens(){return n(this,Ii).designTokens}get configDiff(){return n(this,Ii).configDiff}get isSimulcastEnabled(){var t,e,r,i;return(i=(r=(e=(t=n(this,ct))==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,a,o,c,d,l,u,h,f,S,E,R,M,D,I,x,$,B,z,Z,U;return{audio:{enableStereo:(i=(r=(e=(t=n(this,ct))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:Tn.audio.enableStereo,enableHighBitrate:(d=(c=(o=(a=n(this,ct))==null?void 0:a.media)==null?void 0:o.audio)==null?void 0:c.enableHighBitrate)!=null?d:Tn.audio.enableHighBitrate},video:{quality:(f=(h=(u=(l=n(this,ct))==null?void 0:l.media)==null?void 0:u.video)==null?void 0:h.quality)!=null?f:Tn.video.quality,frameRate:(M=(R=(E=(S=n(this,ct))==null?void 0:S.media)==null?void 0:E.video)==null?void 0:R.frameRate)!=null?M:Tn.video.frameRate},screenshare:{quality:($=(x=(I=(D=n(this,ct))==null?void 0:D.media)==null?void 0:I.screenshare)==null?void 0:x.quality)!=null?$:Tn.screenshare.quality,frameRate:(U=(Z=(z=(B=n(this,ct))==null?void 0:B.media)==null?void 0:z.screenshare)==null?void 0:Z.frameRate)!=null?U:Tn.screenshare.frameRate}}}get name(){return n(this,Xo)}};let dh=Cn;ct=new WeakMap,Ii=new WeakMap,Xo=new WeakMap,Yn=new WeakMap;var RD=Object.defineProperty,kD=Object.getOwnPropertyDescriptor,gT=(s,t,e,r)=>{for(var i=r>1?void 0:r?kD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&RD(t,e,i),i},Qn,Zo;class fp extends xt{constructor(e,r){const i=e.getValue("logger");super(i);g(this,Qn,void 0);p(this,"state","IDLE");p(this,"playbackUrl");p(this,"ingestionCredentials");p(this,"viewerCount");g(this,Zo,void 0);m(this,Qn,r),m(this,Zo,e),this.viewerCount=0}get telemetry(){return n(this,Zo).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(!n(this,Qn).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=Lt(),{playbackUrl:i,ingestionCredentials:a}=await r.startLivestreaming(e);this.playbackUrl=i,this.ingestionCredentials=a,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(!n(this,Qn).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 Lt().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)}}}Qn=new WeakMap,Zo=new WeakMap;gT([y.trace("livestream.start")],fp.prototype,"start",1);gT([y.trace("livestream.stop")],fp.prototype,"stop",1);var bD=Object.defineProperty,MD=Object.getOwnPropertyDescriptor,AD=(s,t,e,r)=>{for(var i=r>1?void 0:r?MD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&bD(t,e,i),i},Xn,Zn,zs,Ss;class mT{constructor(t,e,r){p(this,"livestream");g(this,Xn,void 0);g(this,Zn,void 0);g(this,zs,void 0);g(this,Ss,void 0);m(this,Ss,t),m(this,Zn,e),this.livestream=new fp(t,e),m(this,zs,r),this.setupEvents()}get logger(){return n(this,Ss).getValue("logger")}get telemetry(){return n(this,Ss).getValue("telemetry")}async fetchInitialLivestreamingState(){const t=Lt(),{status:e,playbackUrl:r,manualIngest:i,ingestionCredentials:a}=await t.getActiveLivestream();this.livestream.playbackUrl=r,this.livestream.ingestionCredentials=a,e==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),e==="INVOKED"&&i&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}setupEvents(){n(this,zs).on(L.startedLivestream,async t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{n(this,Zn).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}}),n(this,zs).on(L.livestreamingInvoked,async t=>{if(t.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{n(this,Zn).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}}),n(this,zs).on(L.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),n(this,zs).on(L.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),n(this,zs).on(L.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),n(this,Ss).getValue("peerSessionStore").on(w.PEER_JOINED_INTERNAL,async t=>{var e;((e=t.flags)==null?void 0:e.hiddenParticipant)===!0&&t.recorderType==="LIVESTREAMER"&&(m(this,Xn,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),n(this,Ss).getValue("peerSessionStore").on(w.PEER_CLOSED,t=>{t.id===n(this,Xn)&&(m(this,Xn,void 0),this.livestream.setLivestreamState("IDLE"))}),n(this,Ss).getValue("peerSessionStore").onAsync(w.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})}}}),n(this,Ss).getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Error: LivestreamController.fetchLivestream")}})}}Xn=new WeakMap,Zn=new WeakMap,zs=new WeakMap,Ss=new WeakMap;AD([y.trace("LivestreamController.setupEvents")],mT.prototype,"setupEvents",1);var ID=Object.defineProperty,DD=Object.getOwnPropertyDescriptor,rd=(s,t,e,r)=>{for(var i=r>1?void 0:r?DD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ID(t,e,i),i},Ye,Ur,Hr,el,fT;class Na{constructor({name:t,socketHandler:e,meetingId:r}){g(this,el);p(this,"name","");g(this,Ye,{});g(this,Ur,"");g(this,Hr,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"bulkRateLimitConfig",{maxInvocations:5,period:1});p(this,"listeners",{});this.name=t,m(this,Hr,e),m(this,Ur,r)}async set(t,e,r=!0,i=!1){n(this,Ye)[t]=e,r&&this.remoteSet(t,e),i&&(this.listeners[t]&&this.listeners[t].forEach(a=>a({[t]:n(this,Ye)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(a=>a({[t]:n(this,Ye)[t]})))}remoteSet(t,e){n(this,Hr).storeInsertKeys(n(this,Ur),this.name,[{key:t,payload:e}])}async bulkSet(t){t.forEach(({key:e,payload:r})=>{n(this,Ye)[e]=r}),n(this,Hr).storeInsertKeys(n(this,Ur),this.name,t)}async update(t,e,r=!0){k(this,el,fT).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(n(this,Ye)[t]&&delete n(this,Ye)[t],e)return n(this,Hr).storeDeleteKeys(n(this,Ur),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})=>{n(this,Ye)[e]&&delete n(this,Ye)[e]}),n(this,Hr).storeDeleteKeys(n(this,Ur),this.name,t)}get(t){if(n(this,Ye)[t])return n(this,Ye)[t]}getAll(){return n(this,Ye)}clear(){m(this,Ye,{})}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){m(this,Ye,t)}}Ye=new WeakMap,Ur=new WeakMap,Hr=new WeakMap,el=new WeakSet,fT=function(t,e,r=!0){let i;const a=n(this,Ye)[t],o=Object.prototype.toString.call(e),c=Object.prototype.toString.call(a);if(o!==c){this.set(t,e);return}switch(c){case"[object Array]":i=[...a,...e];break;case"[object Object]":i={...a,...e};break;case"[object Map]":i=new Map([...a,...e]);break;case"[object Set]":i=new Set([...a,...e]);break;default:i=e;break}this.set(t,i,r)};rd([Ut(Oa,"rateLimitConfig")],Na.prototype,"remoteSet",1);rd([Ut(Oa,"bulkRateLimitConfig")],Na.prototype,"bulkSet",1);rd([Ut(Oa,"rateLimitConfig")],Na.prototype,"update",1);rd([Ut(Oa,"rateLimitConfig")],Na.prototype,"delete",1);rd([Ut(Oa,"bulkRateLimitConfig")],Na.prototype,"bulkDelete",1);var Br,Fr,ec,lh,tc,as,tl,TT;class OD{constructor(t,e){g(this,ec);g(this,tl);p(this,"stores",new Map);g(this,Br,void 0);g(this,Fr,"");g(this,tc,void 0);g(this,as,new Map);m(this,Br,e),m(this,Fr,t.getValue("meetingId")),m(this,tc,t),k(this,tl,TT).call(this)}create(t,e=!1){if(CC.includes(t)&&!e)throw new C(`'${t}' is a reserved store name.`,"0601");const r=new Na({name:t,socketHandler:n(this,Br),meetingId:n(this,Fr)});return n(this,Br).storeGetKeys(n(this,Fr),t,[]),new Promise((a,o)=>{const c=setTimeout(()=>{n(this,as).delete(t),o(Error("Failed"))},3e3);n(this,as).set(t,{rejectTimeout:c,resolve:a,store:r})})}refresh(t){const e=this.stores.get(t);return e?(e.clear(),n(this,Br).storeGetKeys(n(this,Fr),t,[]),new Promise((i,a)=>{const o=setTimeout(()=>{n(this,as).delete(t),a(Error("Store refresh timed out"))},3e3);n(this,as).set(t,{rejectTimeout:o,resolve:i,store:e})})):Promise.reject(Error(`Store '${t}' does not exist`))}}Br=new WeakMap,Fr=new WeakMap,ec=new WeakSet,lh=function(){return n(this,tc).getValue("peerId")},tc=new WeakMap,as=new WeakMap,tl=new WeakSet,TT=function(){[Hs.storeInsertKeys,Hs.storeGetKeys,Hs.storeDeleteKeys].forEach(t=>{n(this,Br).on(t,async e=>{var a,o;if(e.pluginId!==n(this,Fr))return;const r=(a=e.storeItems)==null?void 0:a.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===Hs.storeGetKeys){const c=n(this,as).get(e.storeName),d=this.stores.get(e.storeName)||(c==null?void 0:c.store);if(n(this,as).get(e.storeName)&&(this.stores.set(e.storeName,c.store),c.resolve(d),clearTimeout(c.rejectTimeout),n(this,as).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=n(this,as).get(e.storeName))==null?void 0:o.store);i!==void 0&&(t===Hs.storeInsertKeys&&r.forEach(({key:c,peerId:d,payload:l})=>{d!==n(this,ec,lh)&&i.set(c,l,!1,!0)}),t===Hs.storeDeleteKeys&&r.forEach(({key:c,peerId:d})=>{d!==n(this,ec,lh)&&i.delete(c,!1,!0)}))})})};function mi(s){var t,e,r,i,a,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?(a=s.mediaPermissions)==null?void 0:a.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 ND=Object.defineProperty,LD=Object.getOwnPropertyDescriptor,La=(s,t,e,r)=>{for(var i=r>1?void 0:r?LD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ND(t,e,i),i};const VD=.8,$D=1.2;var ea,ta,Mt,Di,so,jr,yn,Oi,ro,sl,ST,dt,sc,qr,Ni,io,Ys,rl,rc,uh,il,vT,nl,yT,um;let fr=(um=class extends xt{constructor(t,e,r,i){const a=t.getValue("logger");super(a);g(this,Di);g(this,jr);g(this,Oi);g(this,sl);g(this,Ni);g(this,rc);g(this,il);g(this,nl);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");g(this,ea,void 0);p(this,"supportsRemoteControl",!1);g(this,ta,void 0);p(this,"presetName");g(this,Mt,void 0);g(this,dt,void 0);g(this,sc,void 0);g(this,qr,new Map);g(this,Ys,1);g(this,rl,ip(t=>{if(!this.videoTrack)return;const{clientWidth:e,clientHeight:r}=t,{width:i,height:a}=this.videoTrack.getSettings();if(!i||!a)return;const o=a/r,c=i/e,d=Math.max(o,c);d>$D&&n(this,Ys)===1?(m(this,Ys,0),n(this,Mt).getValue("peerSessionStore").emit(w.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:n(this,Ys)})):d<VD&&n(this,Ys)===0&&(m(this,Ys,1),n(this,Mt).getValue("peerSessionStore").emit(w.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:n(this,Ys)}))},2e3));m(this,Mt,t);const{id:o,userId:c,displayName:d,device:l,picture:u,isHost:h,flags:f,stageStatus:S,customParticipantId:E,audioMuted:R,audioTrack:M,videoEnabled:D=!1,videoTrack:I,producers:x,metadata:$}=e;this.id=o,this.userId=c,this.name=d,this.device=l,this.picture=u,this.isHost=h,this.flags=f,this.manualProducerConfig=SC,m(this,ta,S!=null?S:"ON_STAGE"),this.customParticipantId=E,this.audioEnabled=!R,this.audioTrack=M,this.videoEnabled=D,this.videoTrack=I,this.screenShareTracks={audio:void 0,video:void 0},this.producers=x!=null?x:[],this.presetName=$==null?void 0:$.preset_name,m(this,ea,!1),m(this,dt,r),m(this,sc,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),k(this,rc,uh).call(this)}get stageStatus(){return n(this,ta)}get telemetry(){return n(this,Mt).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("Participant::setVideoEnabled::videoUpdate",{...mi(this)}),this.logger.info(`Emitting videoUpdate to the UI Kit for remote peerId: ${this.id}. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(this.logger.info("Participant::setAudioEnabled::audioUpdate",{...mi(this)}),this.logger.info(`Emitting audioUpdate to the UI Kit for remote peerId: ${this.id}. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}))}setScreenShareEnabled(t,e=!0){var r;this.screenShareEnabled=t,e&&(this.logger.info(`Emitting screenShareUpdate to the UI Kit for remote peerId: ${this.id}. Screen sharing enabled: ${this.screenShareEnabled}. Video track available: ${!!((r=this.screenShareTracks)!=null&&r.video)}.`),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}setupEvents(){this.on("videoUpdate",k(this,rc,uh)),n(this,jr,yn)&&(this.on("audioUpdate",k(this,il,vT)),this.on("screenShareUpdate",k(this,nl,yT)))}async pin(){if(!n(this,Oi,ro))throw new C("Can`t pin participant without joining room","1205");if(!n(this,dt).permissions.pinParticipant)throw new C("You do not have permission to pin participants.","1201");return n(this,Di,so).pinPeer(this.id)}async unpin(){if(!n(this,Oi,ro))throw new C("Can`t unpin participant without joining room","1205");if(!n(this,dt).permissions.pinParticipant)throw new C("You do not have permission to unpin participants.","1201");return n(this,Di,so).pinPeer(null)}setIsPinned(t,e=!0){var i;m(this,ea,t);const r=t?"pinned":"unpinned";(i=n(this,Ni,io))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}async disableAudio(){const t=this.id;if(this.logger.info(`Local peer ${n(this,dt).id} is disabling mic of a remote peer ${t}`),!n(this,Oi,ro))throw new C("Can`t disable participant audio without joining room","1205");if(n(this,dt).permissions.canDisableParticipantAudio)return n(this,Di,so).disableAudio(t);throw this.logger.error(`Local peer ${n(this,dt).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 ${n(this,dt).id} is kicking a remote peer ${t} out of the meeting.`),!n(this,sl,ST))throw new C("Can`t kick participant without joining room","1205");if(n(this,dt).permissions.kickParticipant){await n(this,Mt).getValue("peerSessionStore").emitAsync(w.KICK_PEER,{peerId:t});return}throw this.logger.error(`Local peer ${n(this,dt).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 ${n(this,dt).id} is disabling webcam of a remote peer ${t}.`),!n(this,Oi,ro))throw new C("Can`t disable participant video without joining room","1205");if(n(this,dt).permissions.canDisableParticipantVideo)return n(this,Di,so).disableVideo(t);throw this.logger.error(`Local peer ${n(this,dt).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 n(this,sc).getUserPermissions(this.userId)}setStageStatus(t){m(this,ta,t),this.emit("stageStatusUpdate",this)}get isPinned(){return n(this,ea)}registerVideoElement(t){var r,i,a,o;if(!t)return;let e;(i=(r=n(this,qr).get(t))==null?void 0:r.observer)==null||i.disconnect(),"ResizeObserver"in window&&(e=new ResizeObserver(()=>n(this,rl).call(this,t)),e.observe(t)),n(this,qr).set(t,{observer:e}),this.updateVideo(t),(o=n(this,Ni,io))==null||o.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(a=this.raised)!=null?a:!1)}deregisterVideoElement(t){var e,r,i,a;if(!t){(e=n(this,Ni,io))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=n(this,qr).get(t))==null?void 0:r.observer)==null||i.disconnect(),n(this,qr).delete(t),(a=n(this,Ni,io))==null||a.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"}},ea=new WeakMap,ta=new WeakMap,Mt=new WeakMap,Di=new WeakSet,so=function(){return n(this,Mt).getValue("roomNodeClient")},jr=new WeakSet,yn=function(){return n(this,Mt).getValue("audioPlayback")},Oi=new WeakSet,ro=function(){return n(this,Mt).getValue("connectionHandler").mediaJoined},sl=new WeakSet,ST=function(){return n(this,Mt).getValue("connectionHandler").socketJoined},dt=new WeakMap,sc=new WeakMap,qr=new WeakMap,Ni=new WeakSet,io=function(){return n(this,Mt).getValue("pip")},Ys=new WeakMap,rl=new WeakMap,rc=new WeakSet,uh=function(){Array.from(n(this,qr).keys()).forEach(this.updateVideo)},il=new WeakSet,vT=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=n(this,jr,yn))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=n(this,jr,yn))==null||e.removeParticipantTrack(this.id)},nl=new WeakSet,yT=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=n(this,jr,yn))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=n(this,jr,yn))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},um);La([y.trace("Participant.disableAudio")],fr.prototype,"disableAudio",1);La([y.trace("Participant.kick")],fr.prototype,"kick",1);La([y.trace("Participant.disableVideo")],fr.prototype,"disableVideo",1);La([y.trace("Participant.getPermissions")],fr.prototype,"getPermissions",1);La([y.trace("Participant.setStageStatus")],fr.prototype,"setStageStatus",1);fr=La([it("1200")],fr);class to extends aT{constructor(t,e){const{onAddEvent:r="participantJoined",onDeleteEvent:i="participantLeft",onClearEvent:a="participantsCleared"}=e!=null?e:{};super({onAddEvent:r,onDeleteEvent:i,onClearEvent:a},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)}}var Gr;class xD extends Da{constructor(e){super(e);g(this,Gr,void 0);m(this,Gr,new Map)}__set(e,r){return n(this,Gr).set(e,r)}__clear(){return n(this,Gr).clear()}get(e){return n(this,Gr).get(e)}toArray(){return Array.from(n(this,Gr).values())}}Gr=new WeakMap;class UD{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 HD{constructor(){p(this,"_activeSpeakerPeers");p(this,"_compulsoryPeers");this._activeSpeakerPeers=new UD,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),a=this._compulsoryPeers.has(t);this.delete(t,r),a&&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 ET=new HD;var BD=Object.defineProperty,FD=Object.getOwnPropertyDescriptor,xs=(s,t,e,r)=>{for(var i=r>1?void 0:r?FD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&BD(t,e,i),i};const Fg=["ACTIVE_GRID","PAGINATED","MANUAL"];var Re,ic,hh,Li,no,sa,Pd,Vi,Et,hm;let ts=(hm=class extends xt{constructor(t,e,r){var o,c;const i=t.getValue("logger");super(i);g(this,ic);g(this,Li);g(this,sa);p(this,"waitlisted");p(this,"joined");p(this,"active");p(this,"videoSubscribed");p(this,"audioSubscribed");p(this,"pinned");p(this,"all");g(this,Re,void 0);g(this,Vi,void 0);g(this,Et,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"viewMode");p(this,"currentPage");p(this,"lastActiveSpeaker");p(this,"selectedPeers",ET);const a=(c=(o=t.getValue("defaults"))==null?void 0:o.viewMode)!=null?c:"ACTIVE_GRID";if(!Fg.includes(a))throw new C(`Invalid view mode: ${a}. Try ACTIVE_GRID, PAGINATED or MANUAL.`,"1207");m(this,Re,t),m(this,Vi,e),m(this,Et,r),this.waitlisted=new to(i),this.joined=new to(i),this.videoSubscribed=new to(i),this.audioSubscribed=new to(i),this.active=this.videoSubscribed,this.pinned=new to(i),this.all=new xD(i),this.viewMode=a,this.currentPage=this.viewMode==="PAGINATED"?1:0,this.setupEvents()}get pip(){return n(this,Re).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return n(this,Re).getValue("telemetry")}setupEvents(){n(this,Re).getValue("peerSessionStore").on(w.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=n(this,Re).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=n(this,Re).getValue("audioPlayback");t&&this.audioSubscribed.on("participantLeft",e=>{t.removeParticipantTrack(e.id)})}get count(){return this.joined.size}get maxActiveParticipantsCount(){var t;return(t=n(this,Re))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new C("0 <= Max active participants count limit <= 24","1203");n(this,Re).setValue("maxPreferredStreams",t),n(this,sa,Pd)&&n(this,Re).getValue("peerSessionStore").emit(w.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(!n(this,Li,no))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 n(this,Et).acceptWaitingRoomRequest([e])}async acceptAllWaitingRoomRequest(t){const e=t.map(r=>{var i,a;return(a=(i=this.waitlisted.get(r))==null?void 0:i.userId)!=null?a:r});return n(this,Et).acceptWaitingRoomRequest(e)}async rejectWaitingRoomRequest(t){var r,i;if(!n(this,Li,no))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;n(this,Et).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=>Fg.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,n(this,Re).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,n(this,Re).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,n(this,Re).getValue("peerSessionStore").emit(w.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)))}),n(this,Re).getValue("peerSessionStore").emit(w.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)))}),n(this,Re).getValue("peerSessionStore").emit(w.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)),a=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(a,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,n(this,Re).getValue("peerSessionStore").emit(w.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}}}),!n(this,sa,Pd))throw new C("Can`t disable all audio without joining room","1205");if(n(this,Vi).permissions.canAllowParticipantAudio)return n(this,ic,hh).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"),!n(this,sa,Pd))throw new C("Can`t disable all video without joining room","1205");if(n(this,Vi).permissions.canAllowParticipantVideo)return n(this,ic,hh).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"),n(this,Re).getValue("viewType")!=="LIVESTREAM"&&!n(this,Li,no))throw new C("Can`t kick all without joining room","1205");if(!n(this,Vi).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;n(this,Et).kickAll(e)}async broadcastMessage(t,e,r){if(this.logger.info("Participants::broadcastMessage"),!n(this,Li,no))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 n(this,Et).broadcastToMeetings(t,r.meetingIds,e);else{let i=[];"participantIds"in r?i=r.participantIds:i=this.joined.toArray().filter(a=>{var o;return(o=r.presetNames)==null?void 0:o.includes(a.presetName)}).map(a=>a.id),await n(this,Et).broadcastToPeers(t,i,e)}else await n(this,Et).broadcastMessage(t,e)}async getAllJoinedPeers(t,e,r){return(await n(this,Et).getRoomPeers(t,e,r)).peers.map(Pr.formatSocketPeerMessage)}async updatePermissions(t,e){const r=this.joined.toArray().filter(a=>t.includes(a.id)).map(a=>a.userId),i=[...new Set(r)];if(!i.length)throw new C("Cannot update permissions, no valid userIDs found","1204");n(this,Et).updatePermissions(i,e)}async getParticipantsInMeetingPreJoin(){return n(this,Et).getRoomPeersNonPaginated()}},Re=new WeakMap,ic=new WeakSet,hh=function(){return n(this,Re).getValue("roomNodeClient")},Li=new WeakSet,no=function(){var t;return((t=n(this,Re).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},sa=new WeakSet,Pd=function(){var t;return((t=n(this,Re).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Vi=new WeakMap,Et=new WeakMap,hm);xs([y.trace("Participants.setViewMode")],ts.prototype,"setViewMode",1);xs([y.trace("Participants.setPage")],ts.prototype,"setPage",1);xs([y.trace("Participants.disableAllAudio")],ts.prototype,"disableAllAudio",1);xs([y.trace("Participants.disableAllVideo")],ts.prototype,"disableAllVideo",1);xs([y.trace("Participants.kickAll")],ts.prototype,"kickAll",1);xs([y.trace("Participants.broadcastMessage"),Ut(Oa,"rateLimitConfig")],ts.prototype,"broadcastMessage",1);xs([y.trace("Participants.getAllJoinedPeers"),Ut({maxInvocations:10,period:60})],ts.prototype,"getAllJoinedPeers",1);xs([y.trace("Participant.updatePermissions"),Ut({maxInvocations:1e3,period:60})],ts.prototype,"updatePermissions",1);xs([y.trace("Participants.getParticipantsInMeetingPreJoin")],ts.prototype,"getParticipantsInMeetingPreJoin",1);ts=xs([it("1200")],ts);var jD=Object.defineProperty,qD=Object.getOwnPropertyDescriptor,mn=(s,t,e,r)=>{for(var i=r>1?void 0:r?qD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&jD(t,e,i),i};const GD=5e3,WD=1e4;var Kt,vs,Wr,Ue,Qs,$i,xi,ao,al,PT,ol,wT,nc,ph,cl,_T,dl,CT,ll,pm;const En=(pm=class{constructor(s,t,e){g(this,xi);g(this,al);g(this,ol);g(this,nc);g(this,cl);g(this,dl);p(this,"participants");p(this,"self");p(this,"selectedPeers",ET);p(this,"maxSpatialLayerUpdates",new Map);p(this,"consumerPeerMap");p(this,"events");p(this,"roomSocketHandler");p(this,"context");p(this,"videoPeerConsumerMap",new Map);g(this,Kt,{mode:"ACTIVE_GRID",page:0});g(this,vs,!1);g(this,Wr,!1);p(this,"isRebuildingReconnectSnapshot",!1);g(this,Ue,new Map);g(this,Qs,void 0);g(this,$i,void 0);g(this,ll,({state:s})=>{s==="disconnected"||s==="stageLeft"||(this.isRebuildingReconnectSnapshot=!1,k(this,dl,CT).call(this),n(this,Ue).clear(),m(this,Qs,void 0))});p(this,"updateConsumerSpatialLayers",ip(()=>{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=${n(this,vs)}.`);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 ts(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,this.events=us,t.config.viewType!=="CHAT"&&(this.setupEventsGlobal(),k(this,cl,_T).call(this)),this.setupEvents(),this.self.on("roomLeft",n(this,ll))}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")}static async init(s,t,e){return new En(s,t,e)}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,a=this.context.getValue("viewType"),o=this.context.getValue("stageStatus"),c=this.mediaJoined&&(a!==hs.Livestream||o==="ON_STAGE");this.isRebuildingReconnectSnapshot=i&&c,this.isRebuildingReconnectSnapshot||(this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear()),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:a})=>a).join(",")}`),this.context.getValue("peerSessionStore").emit(w.PRODUCER_HANDOVER,{oldPeerId:t,newPeerId:s.peerId,producerIds:r.map(({producerId:a})=>a)})),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(L.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),this.context.getValue("peerSessionStore").on(w.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:a,producerStates:o})=>{this.logger.debug(`Processing media join for ${this.self.peerId===a?"local peer":"existing remote peer"} ${a}.`),this.onParticipantMediaJoined(a,o),this.logger.debug(`Processed media join for ${this.self.peerId===a?"local peer":"existing remote peer"} ${a}.`)}),this.isRebuildingReconnectSnapshot&&this.rewireConsumersOnLocalUserReconnect();const{audioPeers:r,compulsoryPeers:i}=t!=null?t:{};if(this.applyPinnedSnapshot(e.pinnedPeerIds),this.computeActivateParticipants(r!=null?r:[],i),this.participants.viewMode==="PAGINATED"){const a=Math.max(1,Math.min(this.participants.currentPage,this.participants.pageCount));a!==this.participants.currentPage&&await this.participants.setPage(a)}this.isRebuildingReconnectSnapshot=!1,this.logger.info("Participants reconciliation on local peer's media join is complete. Reconciling consumers."),this.context.getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}),this.context.getValue("peerSessionStore").on(w.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(w.PRODUCER_HANDOVER,s=>this.handleProducerHandover(s)),this.context.getValue("peerSessionStore").on(w.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:a})=>a===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(w.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(w.PRODUCER_TOGGLE,({peerId:s,producerId:t,paused:e,kind:r})=>{const i=this.participants.joined.get(s);if(i){const a=i.producers.find(o=>o.producerId===t);if(!a){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.`),a.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(w.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: ${n(this,vs)}, 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(a=>a.peerId))==null?void 0:i.join(", "))||"none"}`);const t=s.requests.filter(a=>!this.participants.waitlisted.get(a.peerId)),e=this.participants.waitlisted.toArray().filter(a=>!s.requests.find(o=>o.peerId===a.id));t.forEach(a=>this.participants.waitlisted.add(new fr(this.context,{id:a.peerId,displayName:a.displayName,audioMuted:!0,videoEnabled:!1,audioTrack:void 0,videoTrack:void 0,stageStatus:"OFF_STAGE",userId:a.userId,flags:{},isHost:!1,customParticipantId:a.customParticipantId,picture:a.picture,metadata:{preset_name:a.presetName}},this.self,this.roomSocketHandler))),e.forEach(a=>this.participants.waitlisted.delete(a.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)),a=Math.max((s-1)*(this.maxPreferredStreams-e.length-r.length)),o=s*(this.maxPreferredStreams-e.length-r.length);return e.concat(r,i.slice(a,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),[]),a=this.self.stageStatus==="ON_STAGE"?1:0,o=s-a,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&&n(this,Kt).mode!==s&&(n(this,Kt).mode=s),e&&n(this,Kt).page!==e&&(n(this,Kt).page=e);const{mode:r,page:i}=n(this,Kt);switch(r){case"PAGINATED":{if(!i)return;const a=this.selectPagePeers(i),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMap(this.participants.videoSubscribed,a),this.updateParticipantsMap(this.participants.audioSubscribed,o),this.logger.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:a});break}case"ACTIVE_GRID":{const a=this.selectActivePeers(this.participants.maxActiveParticipantsCount),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMapMinReplacement(this.participants.videoSubscribed,a),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=n(this,Kt))==null?void 0:e.mode)==="PAGINATED"&&!n(this,vs)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${s}, ViewMode: ${(r=n(this,Kt))==null?void 0:r.mode}, ConsumersSyncing: ${n(this,vs)}, Delay: ${t}, Page: ${(i=n(this,Kt))==null?void 0:i.page}`),setTimeout(()=>this.syncConsumers(),t)}async syncConsumers(){var M,D,I,x,$,B,z,Z;const s=this.context.getValue("connectionHandler");if((M=s==null?void 0:s.socketState)!=null&&M.state&&s.socketState.state!=="connected"){k(this,xi,ao).call(this,"socket not connected"),this.logger.info("syncConsumers: Socket not connected, deferring sync.");return}if(((I=(D=s==null?void 0:s.mediaState)==null?void 0:D.recv)==null?void 0:I.state)!=="connected"){k(this,xi,ao).call(this,"Recv transport not connected"),this.logger.info("syncConsumers: Connection not ready, exiting.");return}if(k(this,al,PT).call(this),n(this,vs)){m(this,Wr,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),m(this,vs,!0),m(this,Wr,!1);let t=[];this.participants.videoSubscribed.forEach(U=>{var et,b;const Y=this.participants.joined.get(U.id),ge=(b=(et=U.producers)==null?void 0:et.filter(T=>T.kind==="video"))!=null?b:[];Y&&(ge!=null&&ge.length)&&ge.forEach(T=>{var se,ae,N,_;const P=((ae=(se=Y.manualProducerConfig)==null?void 0:se.video)!=null?ae:!0)&&T.kind==="video"&&!T.screenShare,V=((_=(N=Y.manualProducerConfig)==null?void 0:N.screenshareVideo)!=null?_:!0)&&T.kind==="video"&&T.screenShare;(P||V)&&(T.pause||t.push(T))})}),this.participants.audioSubscribed.forEach(U=>{var et,b;const Y=this.participants.joined.get(U.id),ge=(b=(et=U.producers)==null?void 0:et.filter(T=>T.kind==="audio"))!=null?b:[];Y&&(ge!=null&&ge.length)&&ge.forEach(T=>{var se,ae,N,_;const P=((ae=(se=Y.manualProducerConfig)==null?void 0:se.audio)!=null?ae:!0)&&T.kind==="audio"&&!T.screenShare,V=((_=(N=Y.manualProducerConfig)==null?void 0:N.screenshareAudio)!=null?_:!0)&&T.kind==="audio"&&T.screenShare;(P||V)&&t.push(T)})}),t=TC(t,U=>U.producerId);const e=new Map;t.forEach(U=>{e.set(U.producerId,U)});const r=($=(x=this.roomNodeClient)==null?void 0:x.getConsumers())!=null?$:new Map,i=[];r.forEach(U=>{U.closed&&i.push(U.id)});const a=(z=(B=this.roomNodeClient)==null?void 0:B.removeClosedConsumers(i))!=null?z:[];a.forEach(U=>{n(this,Ue).delete(U),this.consumerPeerMap.has(U)&&this.processConsumerClosed(U)}),a.length>0&&this.logger.info(`syncConsumers: Removed closed consumers: consumerIds=[${a.join(",")}].`);let o=[];const c=new Set,d=[],l=[];e.forEach(U=>{const Y=r.get(U.producerId);if(!Y){o.push(U);return}c.add(Y.id);const{needsRemap:ge,wasMarkedForDeletion:et}=k(this,nc,ph).call(this,Y,U);ge&&l.push(Y.id),et&&d.push(Y.id)});const u=[];r.forEach(U=>{U.closed||c.has(U.id)||k(this,ol,wT).call(this,U)&&u.push(U.id)});const h=Date.now(),f=[];let S=[];n(this,Ue).forEach((U,Y)=>{const ge=r.get(Y);if(!ge||ge.closed){n(this,Ue).delete(Y);return}if(c.has(Y)){n(this,Ue).delete(Y);return}h-U>=WD?S.push(Y):f.push(Y)}),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:U})=>U).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,R=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>R&&(this.logger.warn(`syncConsumers: Too many remote consumers ready to close: ${S.length}. Only removing ${R} in this run.`),S=S.slice(0,R),this.scheduleSyncConsumers({source:"SOFT_CAPPED_REMOVE_CONSUMERS"}));try{o.length>0||S.length>0?(this.logger.info(`syncConsumers: Calling updateConsumers: createProducerIds=[${o.map(({producerId:U})=>U).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(U){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:U})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),m(this,vs,!1),(Z=s==null?void 0:s.socketState)!=null&&Z.state&&s.socketState.state!=="connected"&&m(this,Wr,!0)}n(this,Wr)&&(this.logger.info("syncConsumers: Resync required, calling syncConsumers again."),this.syncConsumers())}computeActivateParticipants(s,t){const e=s.map((i,a)=>({peerId:i,priority:a+1})),r=t==null?void 0:t.map((i,a)=>({peerId:i,priority:-(a+1)}));e.push(...r!=null?r:[]),e.length>0&&this.updateActiveParticipantsWithPriorities(e)}createParticipantObjFromSocketPeer(s){const t=En.formatSocketPeerMessage(s);return new fr(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===Ds.AUDIO&&!r.screenShare?e.setAudioEnabled(!r.pause):r.kind===Ds.VIDEO&&!r.screenShare&&(e.setVideoEnabled(!r.pause),this.updatePipSource(e.id,!r.pause));const i={...r,producingTransportId:r.producingTransportId,kind:r.kind===Ds.AUDIO?"audio":"video",producingPeerId:s,mimeType:r.mimeType},a=e.producers.find(({producerId:o})=>o===i.producerId);a?Object.assign(a,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(w.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),a=[];e.forEach((o,c)=>{(!i.has(o)||!this.participants.joined.get(o))&&a.push(c)}),t.forEach(o=>{if(s.get(o))return;if(e.length<t.length){e.push(o);return}const c=a.shift();e[c]=o}),a.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),a=this.participants.joined.get(r);a&&i!==a&&(i&&s.delete(r,!1),s.add(a,!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||(k(this,nc,ph).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,a=i.get(t);if(!a)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",a),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),a=this.participants.joined.get(e);if(!i||!a||!i.userId||i.userId!==a.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}),a.manualProducerConfig={...i.manualProducerConfig},i.producers=i.producers.filter(({producerId:u})=>!c.has(u)),d.forEach(u=>{if(a.producers.some(({producerId:f})=>f===u.producerId))return;const h={...u};delete h.consumer,this.context.getValue("peerSessionStore").emit(w.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(w.NEW_CONSUMER_CREATED,{id:u.id,appData:u.appData,peerId:e})}),En.replaceParticipantInMap(this.participants.videoSubscribed,t,a,!0),En.replaceParticipantInMap(this.participants.audioSubscribed,t,a,!1),this.participants.pinned.has(t)&&(i.setIsPinned(!1),a.setIsPinned(!0),En.replaceParticipantInMap(this.participants.pinned,t,a,!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(L.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(L.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(w.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(w.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(w.MEDIA_ROOM_JOIN_FAILED,()=>{this.isRebuildingReconnectSnapshot&&(this.isRebuildingReconnectSnapshot=!1)}),this.context.getValue("peerSessionStore").on(w.SOCKET_SERVICE_DISCONNECTED,()=>{this.isRebuildingReconnectSnapshot=!1,m(this,Wr,!0),k(this,xi,ao).call(this,"socket disconnected"),this.logger.info("Socket disconnected — keeping participants visible for seamless reconnection")}),this.context.getValue("peerSessionStore").on(w.TRANSPORT_STATE_UPDATE,({transport:s,state:t})=>{if(s==="recv"){if(t!=="connected"){k(this,xi,ao).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(w.CONSUMER_PAUSED,({id:s})=>{this.processConsumerPaused(s)}),this.context.getValue("peerSessionStore").on(w.CONSUMER_RESUMED,({id:s})=>{this.processConsumerResumed(s)}),this.context.getValue("peerSessionStore").on(w.NEW_CONSUMER_CREATED,({id:s})=>{this.processNewConsumer(s)}),this.context.getValue("peerSessionStore").on(w.CONSUMER_CLOSED,({id:s})=>{const t=n(this,Ue).delete(s);this.logger.info(`Consumer closed: consumerId=${s}, wasMarkedForDeletion=${t}.`),this.processConsumerClosed(s)}),this.context.getValue("peerSessionStore").on(w.ROOM_MESSAGE,async({payload:s,type:t,timestamp:e})=>{this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(w.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(w.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(w.CONSUMER_SCORE_UPDATE,({score:s,kind:t,appData:e,peerId:r,scoreStats:i})=>{var c;const a=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:a,score:s,participantId:r,scoreStats:i}),this.participants.emit("mediaScoreUpdate",{kind:t,isScreenshare:a,score:s,participantId:r,scoreStats:i}))}),this.context.getValue("peerSessionStore").onAsync(w.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(w.UPDATE_ACTIVE,({viewMode:s,page:t}={})=>{this.isRebuildingReconnectSnapshot||(this.logger.info(`UPDATE_ACTIVE event received - viewMode: ${n(this,Kt).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(w.UPDATE_STAGE_REQUESTS,{request:{displayName:s.name,userId:s.userId,peerId:s.id},add:!0})),this.context.getValue("peerSessionStore").emit(w.PEER_JOINED_INTERNAL,s)}async onParticipantLeave(s){var e;this.logger.info(`peer ${s} has left. Deleting peer from participant maps`);const t=this.participants.joined.get(s);if(this.participants.joined.delete(s,!0,!0),this.participants.pinned.delete(s,!0,!0),this.participants.waitlisted.delete(s,!0,!0),(e=this.pip)==null||e.removeSource(s),t&&t.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&this.context.getValue("peerSessionStore").emit(w.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!1}),!this.isRebuildingReconnectSnapshot){if(this.participants.viewMode==="PAGINATED"){const r=Math.max(1,Math.min(this.participants.currentPage,this.participants.pageCount));if(r!==this.participants.currentPage){await this.participants.setPage(r);return}}this.context.getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}}processMedia(s){var h;const t=this.roomNodeClient.getConsumers(),{peerId:e,kind:r,appData:i,track:a,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:a==null?void 0:a.id}),{peerId:e,kind:r,appData:u,remotelyPaused:d,track:a,producerId:o,rtpReceiver:c,localId:l}}processConsumerClosed(s){var l;const{peerId:t,type:e,appData:r,remotelyPaused:i,producerId:a,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:a}}),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(w.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===a);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=${a}, peerId=${t}.`);return}d.consumer={id:s,peerId:t,kind:void 0,appData:r,paused:i,producerId:a,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:a,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(w.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:d,track:a}),i.screenShare){r==="video"?u.screenShareTracks.video=a:r==="audio"&&(u.screenShareTracks.audio=a),u.setScreenShareEnabled(!0),(f=this.context)==null||f.getValue("callstats").consumerSharedMediaState(s,{screen:!0});return}r==="video"?(u.videoTrack=a,u.setVideoEnabled(!0),this.updatePipSource(u.id,!0),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!0})):r==="audio"&&(u.audioTrack=a,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:a,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:a,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:a,producerId:o,rtpReceiver:c,localId:d}),r&&i.e2ee&&this.context.getValue("peerSessionStore").emit(w.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:a,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:a,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:a,paused:r,producerId:o,rtpReceiver:c,localId:d}),a.screenShare){e==="video"?l.screenShareTracks.video=i:e==="audio"&&(l.screenShareTracks.audio=i),(!r||this.self.permissions.isRecorder)&&l.setScreenShareEnabled(!0),a.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:a,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&&a.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:c,track:i}),this.context.getValue("peerSessionStore").emit(w.ENABLE_E2EE_CRYPTOR_ON_NEW_CONSUMER,{appData:a,peerId:l.id})}static formatSocketPeerMessage(s){var e,r,i,a,o,c;if(!s)return;const t=lp(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:(a=s.flags)==null?void 0:a.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(w.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}},Kt=new WeakMap,vs=new WeakMap,Wr=new WeakMap,Ue=new WeakMap,Qs=new WeakMap,$i=new WeakMap,xi=new WeakSet,ao=function(s){n(this,Qs)===void 0&&(m(this,Qs,Date.now()),this.logger.info(`Consumer deletion aging paused: reason="${s}", consumerIds=[${Array.from(n(this,Ue).keys()).join(",")}].`))},al=new WeakSet,PT=function(){if(n(this,Qs)===void 0)return;const s=Date.now()-n(this,Qs);n(this,Ue).forEach((t,e)=>{n(this,Ue).set(e,t+s)}),m(this,Qs,void 0),this.logger.info(`Consumer deletion aging resumed: pausedDurationMs=${s}, consumerIds=[${Array.from(n(this,Ue).keys()).join(",")}].`)},ol=new WeakSet,wT=function(s){return n(this,Ue).has(s.id)?!1:(n(this,Ue).set(s.id,Date.now()),!0)},nc=new WeakSet,ph=function(s,t){const e=s.peerId,r=!t.consumer||t.consumer.peerId!==t.producingPeerId||e!==t.producingPeerId;s.reassignPeer(t.producingPeerId);const i=n(this,Ue).delete(s.id);return r&&this.processNewConsumer(s.id),{needsRemap:r,wasMarkedForDeletion:i}},cl=new WeakSet,_T=function(){m(this,$i,setInterval(()=>{n(this,Ue).size!==0&&(this.logger.info(`Consumer deletion sweep scheduling reconciliation: consumerIds=[${Array.from(n(this,Ue).keys()).join(",")}].`),this.scheduleSyncConsumers({source:"CONSUMER_DELETION_SWEEP"}))},GD))},dl=new WeakSet,CT=function(){n(this,$i)!==void 0&&(clearInterval(n(this,$i)),m(this,$i,void 0))},ll=new WeakMap,pm);let Pr=En;mn([y.trace("ParticipantController.setupEvents")],Pr.prototype,"setupEvents",1);mn([y.trace("ParticipantController.setupEvents")],Pr.prototype,"setupEventsGlobal",1);mn([y.trace("ParticipantController.processMedia")],Pr.prototype,"processMedia",1);mn([y.trace("ParticipantController.processConsumerClosed")],Pr.prototype,"processConsumerClosed",1);mn([y.trace("ParticipantController.processConsumerResumed")],Pr.prototype,"processConsumerResumed",1);mn([y.trace("ParticipantController.processConsumerPaused")],Pr.prototype,"processConsumerPaused",1);mn([y.trace("ParticipantController.processNewConsumer")],Pr.prototype,"processNewConsumer",1);const we=Os(ap().permissions);var G,ra,ia,ul,lt,Rt;const hl=class extends xt{constructor(e,r,i,a=!1){const o=e.getValue("logger");super(o);g(this,lt);g(this,G,void 0);g(this,ra,void 0);g(this,ia,void 0);g(this,ul,e=>{var l,u,h;const{chat:r,connectedMeetings:i,plugins:a,polls:o,media:c,...d}=e;if(r&&(r.private&&_r(n(this,G).chat.private,r.private),r.public&&_r(n(this,G).chat.public,r.public),this.emit("chatUpdate")),i&&_r(n(this,G).connectedMeetings,i),c){const f=E=>{switch(E){case si.NONE:return j.Allowed;case si.ALLOWED:return j.Allowed;case si.NOT_ALLOWED:return j.NotAllowed;case si.CAN_REQUEST:return j.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)}),_r(n(this,G).media,S)}a&&(_r(n(this,G).plugins,a),this.emit("pluginsUpdate")),o&&(_r(n(this,G).polls,o),this.emit("pollsUpdate")),Object.keys(d).length!==0&&_r(n(this,G),d),this.emit("permissionsUpdate",e)});if(!r)throw this.logger.error("PermissionPreset::load_preset_permissions_failed"),new C("Could not load preset permissions.","0904");m(this,ia,e),m(this,ra,i),m(this,G,r),a&&this.setupEvents()}setupEvents(){n(this,ia).getValue("peerSessionStore").on(w.UPDATE_PERMISSIONS,n(this,ul))}static init(e,r,i){let a;return i?a=new hl(e,i,r,!0):a=new hl(e,we,r),a}get mediaRoomType(){return"CF"}get stageEnabled(){var e;return((e=n(this,G))==null?void 0:e.stageEnabled)||n(this,ra)===hs.Webinar||n(this,ra)===hs.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=n(this,G))==null?void 0:e.acceptStageRequests)||((r=n(this,G))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,i;return((e=n(this,G))==null?void 0:e.stageAccess)===j.NotAllowed?j.NotAllowed:((r=n(this,G))==null?void 0:r.stageAccess)===j.CanRequest?j.CanRequest:((i=n(this,G))==null?void 0:i.stageAccess)===j.Allowed||n(this,G).media.audio.canProduce===j.Allowed||n(this,G).media.video.canProduce===j.Allowed||n(this,G).media.screenshare.canProduce===j.Allowed?j.Allowed:n(this,G).media.audio.canProduce===j.CanRequest||n(this,G).media.video.canProduce===j.CanRequest||n(this,G).media.screenshare.canProduce===j.CanRequest?j.CanRequest:j.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=n(this,G))==null?void 0:e.acceptWaitingRequests)!=null?r:we.acceptWaitingRequests}get requestProduceVideo(){var e,r,i;return((i=(r=(e=n(this,G))==null?void 0:e.media)==null?void 0:r.video)==null?void 0:i.canProduce)===j.CanRequest}get requestProduceAudio(){var e,r,i;return((i=(r=(e=n(this,G))==null?void 0:e.media)==null?void 0:r.audio)==null?void 0:i.canProduce)===j.CanRequest}get requestProduceScreenshare(){var e,r,i;return((i=(r=(e=n(this,G))==null?void 0:e.media)==null?void 0:r.screenshare)==null?void 0:i.canProduce)===j.CanRequest}get canAllowParticipantAudio(){var e,r;return(r=(e=n(this,G))==null?void 0:e.disableParticipantAudio)!=null?r:we.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=n(this,G))==null?void 0:e.canAcceptProductionRequests)!=null?r:we.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=n(this,G))==null?void 0:e.disableParticipantVideo)!=null?r:we.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var e,r;return(r=(e=n(this,G))==null?void 0:e.kickParticipant)!=null?r:we.kickParticipant}get pinParticipant(){var e,r;return(r=(e=n(this,G))==null?void 0:e.pinParticipant)!=null?r:we.pinParticipant}get canRecord(){var e,r;return(r=(e=n(this,G))==null?void 0:e.canRecord)!=null?r:we.canRecord}get waitingRoomBehaviour(){var e,r;return(r=(e=n(this,G))==null?void 0:e.waitingRoomType)!=null?r:we.waitingRoomType}get plugins(){var e,r;return(r=(e=n(this,G))==null?void 0:e.plugins)!=null?r:we.plugins}get polls(){var e,r;return(r=(e=n(this,G))==null?void 0:e.polls)!=null?r:we.polls}get canProduceVideo(){var r;const e=(r=n(this,G).media.video.canProduce)!=null?r:we.media.video.canProduce;return this.stageEnabled&&(n(this,lt,Rt)==="ACCEPTED_TO_JOIN_STAGE"||n(this,lt,Rt)==="ON_STAGE")&&e===j.CanRequest?j.Allowed:this.stageEnabled&&(n(this,lt,Rt)==="OFF_STAGE"||n(this,lt,Rt)==="REQUESTED_TO_JOIN_STAGE")&&e===j.Allowed?j.NotAllowed:e}get canProduceScreenshare(){var r;const e=(r=n(this,G).media.screenshare.canProduce)!=null?r:we.media.screenshare.canProduce;return this.stageEnabled&&(n(this,lt,Rt)==="ACCEPTED_TO_JOIN_STAGE"||n(this,lt,Rt)==="ON_STAGE")&&e===j.CanRequest?j.Allowed:this.stageEnabled&&(n(this,lt,Rt)==="OFF_STAGE"||n(this,lt,Rt)==="REQUESTED_TO_JOIN_STAGE")&&e===j.Allowed?j.NotAllowed:e}get canProduceAudio(){var r;const e=(r=n(this,G).media.audio.canProduce)!=null?r:we.media.audio.canProduce;return this.stageEnabled&&(n(this,lt,Rt)==="ACCEPTED_TO_JOIN_STAGE"||n(this,lt,Rt)==="ON_STAGE")&&e===j.CanRequest?j.Allowed:this.stageEnabled&&(n(this,lt,Rt)==="OFF_STAGE"||n(this,lt,Rt)==="REQUESTED_TO_JOIN_STAGE")&&e===j.Allowed?j.NotAllowed:e}get chatPublic(){var e,r,i;return(i=(r=(e=n(this,G))==null?void 0:e.chat)==null?void 0:r.public)!=null?i:we.chat.public}get chatPrivate(){var e,r,i;return(i=(r=(e=n(this,G))==null?void 0:e.chat)==null?void 0:r.private)!=null?i:we.chat.private}get connectedMeetings(){var e,r;return(r=(e=n(this,G))==null?void 0:e.connectedMeetings)!=null?r:we==null?void 0:we.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=n(this,G))==null?void 0:e.hiddenParticipant)!=null?r:we.hiddenParticipant}get showParticipantList(){var e;return(e=n(this,G).showParticipantList)!=null?e:we.showParticipantList}get canChangeParticipantPermissions(){var e,r;return(r=(e=n(this,G))==null?void 0:e.canChangeParticipantPermissions)!=null?r:we.canChangeParticipantPermissions}get canEditDisplayName(){var e;return(e=n(this,G).canEditDisplayName)!=null?e:!1}get canEditMeetingTitle(){var e,r;return(r=(e=n(this,G))==null?void 0:e.canEditMeetingTitle)!=null?r:!1}get isRecorder(){return n(this,G).isRecorder}get canSpotlight(){return n(this,G).canSpotlight}get canLivestream(){return n(this,G).canLivestream}get transcriptionEnabled(){return n(this,G).transcriptionEnabled}};let gh=hl;G=new WeakMap,ra=new WeakMap,ia=new WeakMap,ul=new WeakMap,lt=new WeakSet,Rt=function(){return n(this,ia).getValue("stageStatus")};var At;class RT extends xt{constructor(e,r){super(r);p(this,"localMediaHandler");g(this,At,void 0);m(this,At,e)}async updatePermission(){var d,l;const e=(u,h)=>{this.mediaPermissions[u]=h;const f={message:this.mediaPermissions[u],kind:u};h==="DENIED"?n(this,At).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_ERROR,f):n(this,At).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,f)};if(ye.getName()==="firefox")return;const r="microphone",i="camera",a=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()};a&&(a.onchange=()=>c("audio",a.state)),o&&(o.onchange=()=>c("video",o.state))}async populateMediaPermissionsInCallstats({message:e,kind:r}){var i,a,o,c;switch(r){case"audio":{(i=n(this,At))==null||i.getValue("callstats").mediaPermission("AUDIO",e),(a=n(this,At))==null||a.getValue("callstats").mediaPermission("SPEAKER",e);break}case"video":{(o=n(this,At))==null||o.getValue("callstats").mediaPermission("VIDEO",e);break}case"screenshare":{(c=n(this,At))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",e);break}}}get peerId(){var e;return(e=n(this,At))==null?void 0:e.getValue("peerId")}async init(e={},r=!1,i=null){var a,o,c,d,l,u,h;if(ye.init(),i&&m(this,At,i),!this.localMediaHandler)try{let f=!0;if((a=i==null?void 0:i.getValue("defaults"))!=null&&a.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 Ct(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(w.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(w.MEDIA_PERMISSION_ERROR,async S=>{const{kind:E,message:R,constraints:M}=S;this.populateMediaPermissionsInCallstats({message:R,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:R},constraints:M,mediaPermissionsErrors:{kind:E,message:R}}),this.emit("mediaPermissionError",S),this.emit("mediaPermissionUpdate",{message:R,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){m(this,At,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.logger.info(`Emitting audioUpdate to the UI Kit for self. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableVideo(){await this.localMediaHandler.enableVideo(),this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}async disableAudio(){this.localMediaHandler.disableAudio(),this.logger.info(`Emitting audioUpdate to the UI Kit for self. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableScreenShare(){var e;await this.localMediaHandler.enableScreenShare(),this.logger.info(`Emitting screenShareUpdate to the UI Kit for self. Screen sharing enabled: ${this.screenShareEnabled}. Video track available: ${!!((e=this.screenShareTracks)!=null&&e.video)}.`),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableScreenShare(){var e;await this.localMediaHandler.disableScreenShare(),this.logger.info(`Emitting screenShareUpdate to the UI Kit for self. Screen sharing enabled: ${this.screenShareEnabled}. Video track available: ${!!((e=this.screenShareTracks)!=null&&e.video)}.`),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableVideo(){await this.localMediaHandler.disableVideo(),this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),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.logger.info(`Emitting audioUpdate to the UI Kit for self. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),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.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})}}At=new WeakMap;var JD=Object.defineProperty,KD=Object.getOwnPropertyDescriptor,St=(s,t,e,r)=>{for(var i=r>1?void 0:r?KD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&JD(t,e,i),i},na,ut,aa,He,Xs,ui,Be,tt,oa,wd,Ie,Oe,ca,da,ac,mh,gm;let Ke=(gm=class extends RT{constructor(t,e,r,i,a){const o=t.getValue("logger");super(t,o);g(this,Xs);g(this,Be);g(this,oa);g(this,Ie);g(this,ac);p(this,"name");p(this,"picture");p(this,"customParticipantId");p(this,"waitlistStatus");g(this,na,void 0);g(this,ut,void 0);g(this,aa,void 0);p(this,"role");p(this,"userId");p(this,"organizationId");p(this,"supportsRemoteControl",!1);p(this,"device");g(this,He,void 0);p(this,"hidden",!1);p(this,"presetName");p(this,"roomState","init");g(this,ca,new Set);g(this,da,new Set);m(this,He,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=e.customParticipantId,this.waitlistStatus="none",m(this,ut,r),m(this,na,i),this.hidden=!1,m(this,aa,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=ye.isElectron(),this.device=ye.getDeviceInfo(),this.presetName=a,this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),k(this,ac,mh).call(this)}get telemetry(){return n(this,He).getValue("telemetry")}get stageStatus(){return n(this,He).getValue("stageStatus")}get producers(){var t,e;return Array.from((e=(t=n(this,Be,tt).getProducers())==null?void 0:t.values())!=null?e:[])}get id(){return this.peerId}get peerId(){return n(this,He).getValue("peerId")}static async __init__(t,e,r,i,a,o=!1){var f,S,E,R,M,D;let c=(S=(f=t.getValue("defaults"))==null?void 0:f.audio)!=null?S:!0,d=(R=(E=t.getValue("defaults"))==null?void 0:E.video)!=null?R:!0;r.canProduceAudio!=="ALLOWED"&&(c=!1),r.canProduceVideo!=="ALLOWED"&&(d=!1);const l=new Ke(t,e,r,i,a),u=rD(i.mediaConstraints);_r(u,(M=t.getValue("defaults"))==null?void 0:M.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"),n(this,ut).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",k(this,ac,mh));const t=n(this,oa,wd);t&&t.onError(e=>{this.emit("autoplayError",e)}),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::AUDIO_TRACK_CHANGE",{...mi(this)}),n(this,Ie,Oe)&&this.audioEnabled)try{await n(this,Be,tt).shareMic(this.audioTrack)}catch(e){this.logger.error("Self::setupEvents::Error while sharing mic",{error:e}),this.localMediaHandler.disableAudio()}this.logger.info(`Emitting audioUpdate to the UI Kit for self. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),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",{...mi(this)}),n(this,Ie,Oe)&&this.rawVideoTrack===void 0)this.logger.info("Self::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&n(this,Ie,Oe))try{await n(this,Be,tt).shareWebcam(this.videoTrack)}catch(e){this.logger.error("Self::setupEvents::failed shareWebcam",{error:e}),this.videoEnabled&&await this.localMediaHandler.disableVideo()}this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),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=n(this,oa,wd))==null||r.setSpeakerDevice(e.deviceId))}),this.localMediaHandler.on("DEVICE_LIST_UPDATED",e=>{this.emit("deviceListUpdate",e)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",async()=>{var e;if(!n(this,Ie,Oe)){this.logger.error("Self.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await n(this,Be,tt).shareScreen(this.screenShareTracks)}catch(r){this.logger.error("Self::setupEvents::Error while sharing screen",{error:r}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.logger.info("Self::setupEvents::SCREENSHARE_TRACK_CHANGE",{...mi(this)}),this.logger.info(`Emitting screenShareUpdate to the UI Kit for self. Screen sharing enabled: ${this.screenShareEnabled}. Video track available: ${!!((e=this.screenShareTracks)!=null&&e.video)}.`),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",{...mi(this)})}),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{var e;(e=n(this,He))==null||e.getValue("callstats").mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",async()=>{var e;n(this,Ie,Oe)&&await n(this,Be,tt).pauseWebcam(),this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(e=n(this,He))==null||e.getValue("callstats").videoOff()}),n(this,ut).on("permissionsUpdate",e=>{var r,i,a;(r=e==null?void 0:e.media)!=null&&r.audio&&n(this,ut).canProduceAudio!==j.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&&n(this,ut).canProduceVideo!==j.Allowed&&(this.disableVideo(),this.logger.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(a=e==null?void 0:e.media)!=null&&a.screenshare&&n(this,ut).canProduceScreenshare!==j.Allowed&&(this.disableScreenShare(),this.logger.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return n(this,ut)}get config(){return n(this,na)}get roomJoined(){var t;return n(this,na).viewType===hs.Livestream&&this.stageStatus!=="ON_STAGE"?((t=n(this,He).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:n(this,Ie,Oe)}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!==j.NotAllowed&&!(n(this,ut).canProduceAudio===j.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if((e=n(this,He))==null||e.getValue("callstats").audioOn(),await this.localMediaHandler.enableAudio(t),n(this,Ie,Oe)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await n(this,Be,tt).shareMic(this.audioTrack)}catch(r){this.logger.error("Self::enableAudio::Error while sharing mic",{error:r}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return}this.logger.info(`Emitting audioUpdate to the UI Kit for self. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}}async enableVideo(t){var e;if(n(this,ut).canProduceVideo!==j.NotAllowed&&!(n(this,ut).canProduceVideo===j.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if((e=n(this,He))==null||e.getValue("callstats").videoOn(),await this.localMediaHandler.enableVideo(t),n(this,Ie,Oe)&&this.stageStatus==="ON_STAGE")try{await n(this,Be,tt).shareWebcam(this.videoTrack)}catch(r){this.logger.error("Self::enableVideo::Error while sharing video",{error:r}),this.videoEnabled&&this.localMediaHandler.disableVideo()}this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),this.logger.info("Self.enableVideo",{...mi(this)})}}async updateVideoConstraints(t){if(!this.localMediaHandler.updateVideoConstraints)throw new C("Unsupported","1102");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){var t;if(!n(this,Ie,Oe))throw new C("Can`t enable screenshare without joining room","1105");if(n(this,ut).canProduceScreenshare!==j.NotAllowed&&!(n(this,ut).canProduceScreenshare===j.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&(this.screenShareEnabled&&this.logger.info("An screen share is already active, showing picker to select a new screen share"),await this.localMediaHandler.enableScreenShare(),this.screenShareTracks.audio||this.screenShareTracks.video)){try{await n(this,Be,tt).shareScreen(this.screenShareTracks)}catch(e){this.logger.error("Self::enableScreenShare::Error while sharing screen",{error:e}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.logger.info(`Emitting screenShareUpdate to the UI Kit for self. Screen sharing enabled: ${this.screenShareEnabled}. Video track available: ${!!((t=this.screenShareTracks)!=null&&t.video)}.`),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(),n(this,Ie,Oe)&&n(this,Be,tt).muteSelf(),this.logger.info(`Emitting audioUpdate to the UI Kit for self. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),(t=n(this,He))==null||t.getValue("callstats").audioOff())}async disableVideo(){var t;this.videoEnabled&&(await this.localMediaHandler.disableVideo(),n(this,Ie,Oe)&&await n(this,Be,tt).pauseWebcam(),this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(t=n(this,He))==null||t.getValue("callstats").videoOff())}async disableScreenShare(){var t;this.screenShareEnabled&&(await this.localMediaHandler.disableScreenShare(),n(this,Ie,Oe)&&await n(this,Be,tt).disableScreenShare(),this.logger.info(`Emitting screenShareUpdate to the UI Kit for self. Screen sharing enabled: ${this.screenShareEnabled}. Video track available: ${!!((t=this.screenShareTracks)!=null&&t.video)}.`),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var i;m(this,aa,t);const r=t?"pinned":"unpinned";(i=n(this,Xs,ui))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return n(this,aa)}async pin(){if(!n(this,Ie,Oe))throw new C("Can`t pin participants without joining room","1105");return this.show(),n(this,Be,tt).pinPeer(this.id)}async unpin(){if(!n(this,Ie,Oe))throw new C("Can`t unpin participants without joining room","1105");return n(this,Be,tt).pinPeer(null)}async hide(){if(!n(this,Ie,Oe))throw new C("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})}show(){if(!n(this,Ie,Oe))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,a;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||((a=e==null?void 0:e.speaker)==null?void 0:a.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){n(this,Ie,Oe)&&await n(this,Be,tt).muteSelf(),this.logger.info(`Emitting audioUpdate to the UI Kit for self. Audio enabled: ${this.audioEnabled}. Audio track available: ${!!this.audioTrack}.`),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){n(this,Ie,Oe)&&await n(this,Be,tt).pauseWebcam(),this.logger.info(`Emitting videoUpdate to the UI Kit for self. Video enabled: ${this.videoEnabled}. Video track available: ${!!this.videoTrack}.`),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=n(this,oa,wd))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?n(this,ca).add(t):n(this,da).add(t),this.updateVideo(t),e||(i=n(this,Xs,ui))==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){n(this,Xs,ui).removeSource(this.id);return}t.srcObject=void 0,e?n(this,ca).delete(t):(n(this,da).delete(t),n(this,Xs,ui).removeSource(this.id))}updateVideo(t,e=!1){var r,i,a;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=n(this,Xs,ui))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(a=n(this,Xs,ui))==null||a.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},na=new WeakMap,ut=new WeakMap,aa=new WeakMap,He=new WeakMap,Xs=new WeakSet,ui=function(){return n(this,He).getValue("pip")},Be=new WeakSet,tt=function(){return n(this,He).getValue("roomNodeClient")},oa=new WeakSet,wd=function(){return n(this,He).getValue("audioPlayback")},Ie=new WeakSet,Oe=function(){var t;return((t=n(this,He).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},ca=new WeakMap,da=new WeakMap,ac=new WeakSet,mh=function(){Array.from(n(this,da)).forEach(t=>this.updateVideo(t,!1)),Array.from(n(this,ca)).forEach(t=>this.updateVideo(t,!0))},gm);St([y.trace("Self.cleanupEvents")],Ke.prototype,"cleanupEvents",1);St([y.trace("Self.setupEvents")],Ke.prototype,"setupEvents",1);St([y.trace("Self.setupTracks")],Ke.prototype,"setupTracks",1);St([y.trace("Self.destructMediaHandler")],Ke.prototype,"destructMediaHandler",1);St([y.trace("Self.removeDocumentEventListeners")],Ke.prototype,"removeDocumentEventListeners",1);St([Er.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"Self.toggleAudio",timeout:3e3}),y.trace("Self.enableAudio")],Ke.prototype,"enableAudio",1);St([Er.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"Self.toggleVideo",timeout:3e3}),y.trace("Self.enableVideo")],Ke.prototype,"enableVideo",1);St([y.trace("Self.updateVideoConstraints")],Ke.prototype,"updateVideoConstraints",1);St([y.trace("Self.enableScreenShare"),Er.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3})],Ke.prototype,"enableScreenShare",1);St([y.trace("Self.updateScreenshareConstraints")],Ke.prototype,"updateScreenshareConstraints",1);St([Er.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"Self.toggleAudio",timeout:3e3}),y.trace("Self.disableAudio")],Ke.prototype,"disableAudio",1);St([Er.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"Self.toggleVideo",timeout:3e3}),y.trace("Self.disableVideo")],Ke.prototype,"disableVideo",1);St([Er.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3}),y.trace("Self.disableScreenShare")],Ke.prototype,"disableScreenShare",1);St([y.trace("Self.setDevice")],Ke.prototype,"setDevice",1);Ke=St([it("1100")],Ke);class Tp extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Tp)}}class Sp extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Sp)}}var oc;class fh{constructor(t,e=!1){p(this,"pendingTasks",new Map);p(this,"nextTaskId",0);p(this,"stopping",!1);g(this,oc,void 0);this.log=e,m(this,oc,{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,a)=>{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),a(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 Tp);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();n(this,oc).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)}}}oc=new WeakMap;class Do extends Error{constructor(t){super(t),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Do):this.stack=new Error(t).stack}}class _t extends Error{constructor(t){super(t),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,_t):this.stack=new Error(t).stack}}class Dr extends Error{constructor(t){super(t),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,_t):this.stack=new Error(t).stack}}const jg=s=>new Promise(t=>setTimeout(t,s));async function Hd(s,t){return new Promise(async(e,r)=>{const{strategy:i,maxRetryCount:a,delayTime:o}={strategy:"linear",maxRetryCount:3,delayTime:10,...t};let c=0,d,l=!1;const u=h=>{l=!0,r(h)};for(;c<a;){try{const h=await s(c,u);return e(h)}catch(h){if(d=h,l)break;if(c<a)i==="linear"?await jg(o*(c+1)):i==="exponential"&&await jg(o*(c+Math.max(0,c-1)));else break}c+=1}return r(d)})}function zD(s){return s.map(t=>({channels:t.channels,clockRate:t.clockRate,mimeType:t.mimeType,sdpFmtpLine:t.sdpFmtpLine}))}function YD(s){return s.map(t=>({uri:t.uri}))}function gd(s){return{codecs:zD(s.codecs),headerExtensions:YD(s.headerExtensions?s.headerExtensions:[])}}function QD(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 a={audio:gd(t),video:gd(e)};return{sender:{audio:gd(r),video:gd(i)},receiver:a}}var cc;class pu extends Tt.EventEmitter{constructor(e){super();g(this,cc,void 0);m(this,cc,e),this.setMaxListeners(1/0)}get logger(){return n(this,cc).getValue("logger")}safeEmit(e,...r){const i=this.listenerCount(e);try{return this.emit(e,...r)}catch(a){return this.logger.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:a}),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((a,o)=>{setTimeout(o,r,"event request timeout");try{this.emit(e.toString(),...i,a,o)}catch(c){this.logger.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:c}),o(c)}})}}cc=new WeakMap;function XD(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}var dc,Ui,ys,pl,Es,Rr,lc,Th,gl,kT,ml,bT;class ZD extends pu{constructor(e,r){var i;super(e);g(this,Es);g(this,lc);g(this,gl);g(this,ml);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");g(this,dc,void 0);g(this,Ui,void 0);g(this,ys,void 0);g(this,pl,void 0);this.id=r.id,this.localId=r.localId,m(this,dc,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,m(this,ys,!1),this.producerId=r.producerId,this.track=r.track,m(this,Ui,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,k(this,gl,kT).call(this),m(this,pl,e)}get closed(){return n(this,ys)}get kind(){return this.track.kind}get paused(){return n(this,Ui)}reassignPeer(e){this.peerId=e}close(e,r){n(this,ys)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,n(this,Es,Rr)),m(this,ys,!0),r&&(k(this,ml,bT).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(n(this,ys))throw new _t("closed");return n(this,dc).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",n(this,Es,Rr)),n(this,ys)){this.logger.error("consumer::pause() | Consumer closed",n(this,Es,Rr));return}m(this,Ui,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",n(this,Es,Rr)),n(this,ys)){this.logger.error("Consumer::resume() | Consumer closed",n(this,Es,Rr));return}m(this,Ui,!1),this.track.enabled=!0,this.safeEmit("resume")}}dc=new WeakMap,Ui=new WeakMap,ys=new WeakMap,pl=new WeakMap,Es=new WeakSet,Rr=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},lc=new WeakSet,Th=function(){this.logger.debug('Consumer::track "ended" event',n(this,Es,Rr)),this.safeEmit("trackended")},gl=new WeakSet,kT=function(){this.track.addEventListener("ended",k(this,lc,Th).bind(this))},ml=new WeakSet,bT=function(){try{this.track.removeEventListener("ended",k(this,lc,Th)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...n(this,Es,Rr),error:e})}};var os,la,ua,Hi,zt,Qe,Jr,ha,fl,It,ss;class eO extends pu{constructor(e,r){var i,a;super(e);g(this,It);p(this,"id");p(this,"localId");g(this,os,void 0);p(this,"kind");p(this,"appData");p(this,"rtpSender");g(this,la,void 0);g(this,ua,void 0);g(this,Hi,void 0);g(this,zt,!1);g(this,Qe,void 0);g(this,Jr,void 0);g(this,ha,void 0);g(this,fl,void 0);this.id=r.id,this.localId=r.localId,m(this,Qe,r.track),this.kind=(i=r.track)==null?void 0:i.kind,m(this,Jr,r.disableTrackOnPause?!((a=r.track)!=null&&a.enabled):!1),m(this,ha,void 0),m(this,la,r.stopTracks),m(this,ua,r.disableTrackOnPause),m(this,Hi,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),m(this,os,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),m(this,fl,e)}get closed(){return n(this,zt)}get track(){return n(this,Qe)}get paused(){return n(this,Jr)}get maxSpatialLayer(){return n(this,ha)}async close(e){if(n(this,zt))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,n(this,It,ss)),m(this,zt,!0),this._destroyTrack(),e===Bd){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await n(this,os).stopSending(this.localId),{answer:a}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(a)}async getStats(){if(n(this,zt))throw new _t("closed");return n(this,os).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",n(this,It,ss)),n(this,zt)&&this.logger.error("Producer::pause() | Producer closed",n(this,It,ss)),m(this,Jr,!0),n(this,Qe)&&n(this,ua)&&(n(this,Qe).enabled=!1),n(this,Hi)&&n(this,os).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",n(this,It,ss)),n(this,zt)){this.logger.error("Producer::resume() | Producer closed",n(this,It,ss));return}m(this,Jr,!1),n(this,Qe)&&n(this,ua)&&(n(this,Qe).enabled=!0),n(this,Hi)&&n(this,os).replaceTrack(this.localId,n(this,Qe)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,n(this,It,ss)),n(this,zt)){if(e&&n(this,la))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...n(this,It,ss),error:r})}throw new _t("closed")}else if(e&&e.readyState==="ended")throw new _t("track ended");if(e===n(this,Qe)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,n(this,It,ss));return}(!n(this,Hi)||!n(this,Jr))&&await n(this,os).replaceTrack(this.localId,e),this._destroyTrack(),m(this,Qe,e),this._handleTrack()}async setMaxSpatialLayer(e){if(n(this,zt))throw new _t("closed");if(this.kind!=="video")throw new Do("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await n(this,os).setMaxSpatialLayer(this.localId,e),m(this,ha,e)}async setRtpEncodingParameters(e){if(n(this,zt))throw new _t("closed");if(typeof e!="object")throw new TypeError("invalid params");await n(this,os).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,n(this,It,ss)),this.safeEmit("trackended",this.track.id)}_handleTrack(){n(this,Qe)&&n(this,Qe).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(n(this,Qe))try{n(this,Qe).removeEventListener("ended",this._onTrackEnded),n(this,la)&&n(this,Qe).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...n(this,It,ss),error:r})}}}os=new WeakMap,la=new WeakMap,ua=new WeakMap,Hi=new WeakMap,zt=new WeakMap,Qe=new WeakMap,Jr=new WeakMap,ha=new WeakMap,fl=new WeakMap,It=new WeakSet,ss=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};const Bd="transport closed",tO=3e4;var pa;const Rn=class extends pu{constructor(e,{id:r,direction:i,handlerFactory:a,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:h}){var R,M,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");g(this,pa,void 0);m(this,pa,e);const f=e.getValue("logger");f.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const S=XD(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 fh(f,!0),this.handler=a(),this.handler.enableHighBitrate=(R=h==null?void 0:h.enableHighBitrate)!=null?R:!1,this.handler.enableStereo=(M=h==null?void 0:h.enableStereo)!=null?M:!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(I=>{const x=setTimeout(()=>{f.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),I(!1)},E);this.once("connected",()=>{clearTimeout(x),I(!0)}),this.once("disconnect",()=>{clearTimeout(x),I(!1)}),this.once("close",()=>{clearTimeout(x),I(!1)})}),this.handler.on("@connectionstatechange",I=>{I!==this.connectionState&&(this.connectionState=I,I==="connected"&&(this.connected=!0,this.emit("connected")),I==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(I==="failed"||I==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",I))}),this.handler.on("@icecandidate",({candidate:I})=>{this.closed||this.safeEmit("icecandidate",I)})}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(Bd).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(Bd)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new _t("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:a,answer:o}=await e(r);this.setServerId(a),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 _t("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new Do("not a sending Transport");if(r.readyState==="ended")throw new _t("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 Dr("transport not connected");return!0}async produce(e,r){if(!await this.canProduce(e))throw new Error("Cannot produce");const{track:a,encodings:o,codecOptions:c,stopTracks:d=!0,disableTrackOnPause:l=!0,zeroRtpOnPause:u=!1,appData:h={}}=e;this.logger.debug(`produce() [track:${a.id}]`);const{producerId:f,localId:S,rtpSender:E}=await this.awaitQueue.push(async()=>{const{offerSdp:R,callback:M,sender:D,mid:I}=await this.handler.send({track:a,encodings:o,codecOptions:c,screenShare:h==null?void 0:h.screenShare}),{answer:x,producerId:$}=await r({offer:R,kind:a.kind,paused:l?!a.enabled||Object.hasOwn(a,"fakeTracks"):!1,appData:{...h||{},mid:I},codecOptions:c,producingTransportId:this.serverId}),B=await M(x);return{producerId:$,localId:B,rtpSender:D}},"Transport.produce");return this.createProducerObject({id:f,localId:S,track:a,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:h,handler:this.handler,rtpSender:E})}async createProducerObject(e){const r=new eO(n(this,pa),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 _t("closed");if(this.direction!=="recv")throw new Do("not a receiving transport");if(!await this.transportConnectionPromise)throw new Dr("transport not connected");return!0}async consume(e,r,i){return this.awaitQueue.push(async()=>{const a={},{consumerStates:o,sessionDescription:c,failedProducers:d}=await r(e);o.forEach((u,h)=>{a[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(a).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=rs.parse(e.sdp),a={};return i.media.forEach(o=>{r.includes(o.mid.toString())&&(a[o.mid.toString()]={rtp:o.rtp,fmtp:o.fmtp,payloads:o.payloads,rtcpFb:o.rtcpFb})}),a}static setCodecAndFmtpMappings(e,r,i){const a=rs.parse(e.sdp);return a.media=a.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:rs.write(a)}}static parseHeaderExtensionMappings(e){const r=rs.parse(e.sdp),i={};return r.media.forEach(a=>{i[a.mid]=a.ext}),i}static setHeaderExtensionMappings(e,r){const i=rs.parse(e.sdp);return i.media=i.media.map(o=>{const c={...o};return c.ext=r[o.mid],c}),{...e,sdp:rs.write(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),a=Rn.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=Rn.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=Rn.setCodecAndFmtpMappings(c,i,a),c=Rn.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=rs.parse(r.sdp);return i.media=i.media.map(a=>{if(a.type==="audio"){const o={...a},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 a}),r.sdp=rs.write(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 a=`${i.mid}:${r.kind}`;r.addEventListener("ended",()=>{this.logger.info(`rtc consumer track ended [trackId: ${r.id}]`),this.unknownTracksMap.delete(a)});const o=this.consumerTrackEvents.get(a);o?(o(r,i),this.consumerTrackEvents.delete(a)):(this.logger.warn(`track event handler not found ${a}`),this.unknownTracksMap.set(a,e))}async createConsumerObjectAndWaitForTrack(e){const{consumerId:r,producerId:i,producingPeerId:a,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(R,M)=>{const D=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${S} producingPeerId: ${a}`),this.consumerTrackEvents.delete(S),E.isTimedout=!0,M(E)},tO),I=($,B)=>{try{if($.readyState==="ended")clearTimeout(D),M(E);else{const z=$;z.enabled=!0,this.handler.midTransceiverMap.set(B.mid,B);const Z=new ZD(n(this,pa),{id:r,localId:B.mid,transceiver:B,track:z,paused:d,producerId:i,producingPeerId:a,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:a},rtpReceiver:B.receiver,mimeType:f});this.consumers.set(r,Z),Z.once("close",()=>{this.consumers.delete(Z.id),this.handler.midTransceiverMap.delete(B.mid)}),this.logger.info(`${l?"screenshare":"participant"} ${h} consumer ${r} created for producer ${i} of remote producing peer ${a} with track ${$.id} on mid ${B.mid}`),this.emit("newconsumer",Z),clearTimeout(D),R(Z)}}catch(z){this.logger.error(`Error while creating ${l?"screenshare":"participant"} ${h} consumer for producerId ${i} of remote peer ${a}`,z),clearTimeout(D),M(E)}},x=this.unknownTracksMap.get(S);x?(this.logger.info(`track event already received for ${l?"screenshare":"participant"} ${h} consumer ${r} of a remote peer ${a} with trackId ${x.track.id} on mid ${x.transceiver.mid} having key ${S}`),this.unknownTracksMap.delete(S),I(x.track,x.transceiver)):(this.logger.info(`Registering onTrack handler for ${l?"screenshare":"participant"} ${h} consumer ${r} of a remote peer ${a} with key ${S}`),this.consumerTrackEvents.set(S,I))})}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 Sh=Rn;pa=new WeakMap;var Fe;class sO{constructor(t){g(this,Fe,void 0);p(this,"events");m(this,Fe,t),this.events=us}async joinRoom(t,e,r,i=!1){const a={roomUuid:t,displayName:e,prejoined:i,capabilities:r};return(await n(this,Fe).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:CR.toBinary(a),timeout:5e3})).payload}async connectTransport(t){const e=(await n(this,Fe).sendMessagePromise(this.events.createWebRTCTransport,ZC.toBinary(t))).payload,{transportId:r,description:i,producerIds:a}=Vf.fromBinary(e),o={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:r,answer:o,producerIds:a}}async produce(t){var a,o;const e=(await n(this,Fe).sendMessagePromise(this.events.produce,HR.toBinary(t))).payload,r=Ek.fromBinary(e);return{answer:{sdp:(a=r==null?void 0:r.description)==null?void 0:a.sdp,type:(o=r==null?void 0:r.description)==null?void 0:o.type},producerId:r.producerId}}async consume(t){const e=(await n(this,Fe).sendMessagePromise(this.events.consume,NR.toBinary(t))).payload,{consumerIdsMap:{map:r},description:i}=vk.fromBinary(e);return{consumerStateMap:r,sessionDescription:i}}async closeProducer(t){const e=(await n(this,Fe).sendMessagePromise(this.events.closeProducer,JR.toBinary(t))).payload,{description:r}=bk.fromBinary(e);return r}async closeConsumer(t){return(await n(this,Fe).sendMessagePromise(this.events.closeConsumer,zR.toBinary(t))).payload}async updateConsumersSimulcastConfig(t){return(await n(this,Fe).sendMessagePromise(this.events.updateConsumersSimulcastConfig,xR.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},i=(await n(this,Fe).sendMessagePromise(this.events.hostControlPeer,tk.toBinary(r))).payload;if(!i)return!1;const{status:a}=Lk.fromBinary(i);return a==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await n(this,Fe).sendMessagePromise(this.events.hostControlAllPeers,rk.toBinary(e))).payload;if(!r)return!1;const{status:i}=$k.fromBinary(r);return i==="success"}async kickAll(){const t={propagateKickAcrossRooms:!1};n(this,Fe).sendMessagePromise(L.kickAll,Hf.toBinary(t))}async kickPeer(t){n(this,Fe).sendMessagePromise(L.kick,Gf.toBinary(t))}async changeDisplayName(t){const e=(await n(this,Fe).sendMessagePromise(this.events.changeDisplayName,ZR.toBinary(t))).payload;if(!e)return!1;const{status:r}=Uk.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await n(this,Fe).sendMessagePromise(this.events.selfJoinComplete,kR.toBinary(t))).payload;return Wu.fromBinary(e)}async audioActivity(t){n(this,Fe).sendMessage(this.events.audioActivity,tR.toBinary(t))}}Fe=new WeakMap;var Ft=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s.CLOSED="closed",s))(Ft||{});class vp extends pu{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:a,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",...a},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 a=i.sender.getParameters();a.encodings.forEach((o,c)=>{c<=r?o.active=!0:o.active=!1}),await i.sender.setParameters(a)}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 a=i.sender.getParameters();a.encodings.forEach((o,c)=>{a.encodings[c]={...o,...r}}),await i.sender.setParameters(a)}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 yp extends vp{static createFactory(t){return()=>new yp(t)}get name(){return"Chrome74"}init({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:i,proprietaryConstraints:a,onTrackHandler:o}){this._direction=t,this.pc=new RTCPeerConnection({iceServers:e||[],iceTransportPolicy:r||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...i},a),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection();const a=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)}`),a.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
9
- `}this.midTransceiverMap.set(a.mid,a);const c=async d=>(this.logger.debug(`[SDP] send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),await this.pc.setRemoteDescription(d),a.mid);return this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(o,void 0,2)}]`),{offerSdp:o,callback:c,sender:a.sender,mid:a.mid}}}class Fd extends vp{constructor(e,r){super(e);p(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new Fd(e,r)}get name(){return"Firefox60"}async send({track:e,encodings:r,codecOptions:i,screenShare:a}){this._assertSendDirection();const o=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(e,{direction:"sendonly",streams:[a?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 x;const S=rs.parse(h),E=S.media[S.media.length-1],R=E.rtp.filter($=>f.some(B=>B.name===$.codec)),M=E.fmtp.filter($=>R.some(B=>B.payload===$.payload)),D=(x=E.rtcpFb)==null?void 0:x.filter($=>R.some(B=>B.payload===$.payload)),I=R.map($=>$.payload);return S.media[S.media.length-1].rtp=R,S.media[S.media.length-1].fmtp=M,S.media[S.media.length-1].rtcpFb=D,S.media[S.media.length-1].payloads=I.join(" "),rs.write(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 a=i.sender.getParameters(),o=a.encodings.length-1-r;a.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),await i.sender.setParameters(a)}}class Ep extends vp{static createFactory(t){return()=>new Ep(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 a=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)}`),a.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(a.mid,a),{offerSdp:d,callback:async u=>(this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),await this.pc.setRemoteDescription(u),a.mid),sender:a.sender,mid:a.mid}}}function rO(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")}var Zs,Bi;class iO{constructor(t,{handlerName:e,handlerFactory:r}={}){p(this,"handlerFactory");g(this,Zs,void 0);g(this,Bi,void 0);const i=t.getValue("logger");if(i.debug("Device constructor() called."),m(this,Zs,t),m(this,Bi,i),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)n(this,Bi).debug(`Device::constructor() | handler given: ${e}`);else if(e=rO(n(this,Bi)),e)n(this,Bi).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=yp.createFactory(n(this,Zs));break;case"Safari12":this.handlerFactory=Ep.createFactory(n(this,Zs));break;case"Firefox60":this.handlerFactory=Fd.createFactory(n(this,Zs),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=Fd.createFactory(n(this,Zs),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=pr.v4();return new Sh(n(this,Zs),{id:e,...t,handlerFactory:this.handlerFactory})}}Zs=new WeakMap,Bi=new WeakMap;const nO=2e3;var ga,je,qe,uc,hc,Fi,ma,pc,fa,ji,Ps,ws,kr,gc,vh,Tl,MT,mc,yh,Sl,AT,vl,IT,yl,DT,El,OT,Pl,NT,fc,Eh,_s,br;class aO extends Tt.EventEmitter{constructor(e,r){super();g(this,ws);g(this,gc);g(this,Tl);g(this,mc);g(this,Sl);g(this,vl);g(this,yl);g(this,El);g(this,Pl);g(this,fc);g(this,_s);p(this,"context");g(this,ga,void 0);g(this,je,void 0);g(this,qe,void 0);g(this,uc,void 0);g(this,hc,void 0);g(this,Fi,void 0);g(this,ma,void 0);g(this,pc,void 0);g(this,fa,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});g(this,ji,void 0);g(this,Ps,"all");this.context=e,m(this,Fi,r),m(this,ga,new iO(e)),m(this,ma,new sO(r)),m(this,pc,us),n(this,ws,kr).mediaState={send:{state:Ft.NEW},recv:{state:Ft.NEW}},Ao(this.context,"forceRelay")&&m(this,Ps,"relay"),this.logger.info(`ICE Transport Policy initially set to ${n(this,Ps)}`),k(this,gc,vh).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return n(this,Fi)}get socketHandler(){return n(this,ma)}get sendTransport(){return n(this,je)}get recvTransport(){return n(this,qe)}get events(){return n(this,pc)}set sendTransportConnectedCallback(e){m(this,uc,e)}set recvTransportConnectedCallback(e){m(this,hc,e)}async setupTransports(e){await k(this,Tl,MT).call(this,e);let r,i;e.send&&(r=k(this,mc,yh).call(this,n(this,je)).then(a=>{try{n(this,uc).call(this,a)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=k(this,mc,yh).call(this,n(this,qe)).then(a=>{try{n(this,hc).call(this,a)}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:a,serverId:o,direction:c}=n(this,je);this.logger.info("Closing send transport",{transport:{id:a,serverId:o,type:c}}),n(this,je).close(),n(this,je).removeAllListeners(),m(this,je,void 0)}if(e.send&&(n(this,ws,kr).mediaState.send.state!==Ft.CLOSED||n(this,ws,kr).mediaState.send.sfuSessionId!==void 0)&&k(this,_s,br).call(this,{direction:"send",state:Ft.CLOSED}),e.recv&&this.recvTransport!==void 0){const{id:a,serverId:o,direction:c}=n(this,qe);this.logger.info("Closing recv transport",{transport:{id:a,serverId:o,type:c}}),(r=n(this,qe))==null||r.close(),(i=n(this,qe))==null||i.removeAllListeners(),m(this,qe,void 0)}e.recv&&(n(this,ws,kr).mediaState.recv.state!==Ft.CLOSED||n(this,ws,kr).mediaState.recv.sfuSessionId!==void 0)&&k(this,_s,br).call(this,{direction:"recv",state:Ft.CLOSED}),k(this,gc,vh).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}ga=new WeakMap,je=new WeakMap,qe=new WeakMap,uc=new WeakMap,hc=new WeakMap,Fi=new WeakMap,ma=new WeakMap,pc=new WeakMap,fa=new WeakMap,ji=new WeakMap,Ps=new WeakMap,ws=new WeakSet,kr=function(){return this.context.getValue("connectionHandler")},gc=new WeakSet,vh=function(){m(this,ji,{send:void 0,recv:void 0})},Tl=new WeakSet,MT=async function(e){var o,c,d,l,u,h,f,S;Ao(this.context,"forceRelay")&&m(this,Ps,"relay"),this.logger.info(`ICE Transport Policy set to ${n(this,Ps)}`);const a=await Lt().getICEServers().catch(E=>(this.logger.warn(`failed to get iceservers from server: ${E.message}`),[]));e.send&&k(this,vl,IT).call(this,{iceServers:a,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:n(this,Ps)}),e.recv&&k(this,yl,DT).call(this,{iceServers:a,additionalSettings:{encodedInsertableStreams:(S=this.context.getValue("modules").e2ee)==null?void 0:S.enabled},iceTransportPolicy:n(this,Ps)})},mc=new WeakSet,yh=async function(e){const{id:r,serverId:i,direction:a}=e;k(this,El,OT).call(this,e);try{return await Hd(async(c,d)=>{c>0&&this.logger.info(`Retrying ${a} transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:a}});try{if(e.closed)throw new Dr("Cannot reconnect closed transport");await k(this,Sl,AT).call(this,e)}catch(l){if(l instanceof Dr){this.logger.error(`Failed to connect ${a} transport. It will not be retried.`,{transport:e,error:l}),d(l);return}throw this.logger.error(`Failed to connect ${a} transport, retrying`,{transport:e,error:l}),l}},{delayTime:100,strategy:"exponential",maxRetryCount:15}),e}catch(o){throw this.logger.error(`Failed to connect ${a} transport after retries: ${e.id}. Transport reconnection will not be retried.`,{error:o,transport:{id:r,serverId:i,type:a}}),e.close(),e.removeAllListeners(),o}},Sl=new WeakSet,AT=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!n(this,Fi).isConnected)throw new Dr("Socket is not connected");if(e.connectionState==="closed")throw new Dr("Transport is closed");try{await e.connect(a=>k(this,Pl,NT).call(this,i,a)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(a){throw n(this,fa).transportFailureCount[i]+=1,a.message==="ice connection failed"?new Dr(a.message):a}},vl=new WeakSet,IT=function(e){var r,i;if(n(this,je)&&n(this,je).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=n(this,je))==null?void 0:r.id,serverId:(i=n(this,je))==null?void 0:i.serverId,type:"send"}});return}m(this,je,n(this,ga).createTransport({...e,direction:"send"})),k(this,_s,br).call(this,{state:Ft.NEW,direction:"send",sfuSessionId:n(this,je).serverId}),this.context.getValue("callstats").configureSendTransport(n(this,je))},yl=new WeakSet,DT=function(e){var r,i;if(n(this,qe)&&n(this,qe).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=n(this,qe))==null?void 0:r.id,serverId:(i=n(this,qe))==null?void 0:i.serverId,type:"recv"}});return}m(this,qe,n(this,ga).createTransport({...e,direction:"recv"})),k(this,_s,br).call(this,{state:Ft.NEW,direction:"recv",sfuSessionId:n(this,qe).serverId}),this.context.getValue("callstats").configureRecvTransport(n(this,qe))},El=new WeakSet,OT=function(e){const{direction:r,id:i}=e;e.on("serveridchange",a=>{k(this,_s,br).call(this,{state:e.connectionState,direction:r,sfuSessionId:a})}),e.on("connectionstatechange",async a=>{k(this,_s,br).call(this,{state:a,direction:r,sfuSessionId:e.serverId}),this.logger.info(`Transport connection state changed to ${a} for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:a}});const o=()=>{const c=n(this,ji)[r];c!==void 0&&(clearTimeout(c),n(this,ji)[r]=void 0)};switch(a){case"connected":o(),n(this,fa).lastConnectionTime=performance.now();break;case"disconnected":n(this,ji)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await k(this,fc,Eh).call(this,e.direction)},nO);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 k(this,fc,Eh).call(this,e.direction);break}}),e.on("icecandidate",async a=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:a})})},Pl=new WeakSet,NT=async function(e,r){const i=e==="recv";try{const{sdp:a,type:o}=r,c={consuming:i,description:{sdp:a,type:o,target:i?mr.SUBSCRIBER:mr.PUBLISHER},producers:[]};return n(this,ma).connectTransport(c)}catch(a){throw this.logger.error(`Error in ${e} transport connection:`,{error:a}),a}},fc=new WeakSet,Eh=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),n(this,Fi).isConnected&&n(this,fa).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),m(this,Ps,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:n(this,je)}),this.context.getValue("peerSessionStore").emit(w.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:n(this,qe)}),this.context.getValue("peerSessionStore").emit(w.UPDATE_ACTIVE);break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}const r=e==="send"?n(this,je):n(this,qe);k(this,_s,br).call(this,{state:Ft.CONNECTED,direction:e,sfuSessionId:r.serverId})},_s=new WeakSet,br=function(e){const{state:r,direction:i,sfuSessionId:a}=e;n(this,ws,kr).mediaState[i]={state:r,sfuSessionId:a},this.context.getValue("peerSessionStore").emit(w.TRANSPORT_STATE_UPDATE,{transport:i,...n(this,ws,kr).mediaState[i]})};var wl,Yt;class oO{constructor(t,e,r,i,a){g(this,wl,void 0);g(this,Yt,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=a,m(this,wl,t),m(this,Yt,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}),a=new Map;t.forEach(d=>a.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const u=a.get(d);if(!u)return;if(l.errorCode){n(this,Yt).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{n(this,Yt).info("Negotiating socket consumer",{transport:this.recvTransport}),n(this,Yt).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:mr.SUBSCRIBER}};return n(this,Yt).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,iR.toBinary(r)),n(this,Yt).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){n(this,Yt).error("Failed to renegotiate",{error:e});return}}async close(t){if(!t.length)return;const e=async(r,i)=>{const a=r.map(l=>l.localId);n(this,Yt).info(`Closing consumers: ${JSON.stringify(a)}`);const o={description:{sdp:i.sdp,type:i.type,target:mr.SUBSCRIBER},consumerIds:a,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=Ak.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(a=>a&&a.id);i.forEach(({id:a,producingTransportId:o,localId:c})=>{r.requests.push({producerId:a,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),await this.socketHandler.updateConsumersSimulcastConfig(r),n(this,Yt).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:a})=>a)})}}wl=new WeakMap,Yt=new WeakMap;class Pp{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return rs.parse(t).media.filter(a=>e==="video"?a.type==="video":a.type==="audio").at(-1).msid}async create({offer:t,kind:e,paused:r,appData:i,codecOptions:a,producingTransportId:o}){var h,f;const c=Pp.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:mr.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(h=i.screenShare)!=null?h:!1,mimeType:`${e}/${(f=a[0])==null?void 0:f.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}function cO(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{}}}var qi,Cs,Tc,Rs,_l,er,Ta,Sc,Ph,Cl,LT,Rl,VT,kl,$T,bl,xT;class dO extends aO{constructor(e,r){super(e,r);g(this,Sc);g(this,Cl);g(this,Rl);g(this,kl);g(this,bl);g(this,qi,void 0);g(this,Cs,void 0);g(this,Tc,void 0);g(this,Rs,void 0);g(this,_l,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});g(this,er,[]);g(this,Ta,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{m(this,Tc,new Pp(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{m(this,Rs,new oO(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return n(this,qi)}get consumers(){return n(this,Cs)}get logger(){return this.context.getValue("logger")}reset(){m(this,qi,new Map),m(this,Cs,new Map)}async createProducer(e,r){var i,a,o;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const c=await this.sendTransport.produce(e,k(this,Cl,LT).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_ACTIVE_PRODUCER,c),k(this,Rl,VT).call(this,c,r),this.logger.info(`Created ${(a=c.appData)!=null&&a.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}),n(this,_l).producerCreationFailureCount+=1,c}}async closeProducer(e,r){var a,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 ${(a=i.appData)!=null&&a.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(w.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(n(this,qi).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){n(this,Ta)||clearTimeout(n(this,Ta)),m(this,er,n(this,er).concat(e)),await k(this,Sc,Ph).call(this)}removeClosedConsumers(e){return e.filter(r=>{const i=n(this,Cs).get(r);return i!=null&&i.closed?(n(this,Cs).delete(r),!0):!1})}async closeConsumers(e){if(!n(this,Rs))return;const r=e.map(i=>this.consumers.get(i)).filter(i=>i!==void 0);r.length!==0&&await n(this,Rs).close(r)}closeAllConsumers(){return this.closeConsumers(Array.from(n(this,Cs).keys()))}async switchConsumersToLayer(e,r){n(this,Rs).switchConsumersToLayer(e,r)}}qi=new WeakMap,Cs=new WeakMap,Tc=new WeakMap,Rs=new WeakMap,_l=new WeakMap,er=new WeakMap,Ta=new WeakMap,Sc=new WeakSet,Ph=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=n(this,er).splice(0,n(this,er).length);try{const i=new Set(Array.from(this.consumers.values()).map(({producerId:d})=>d)),a=r.filter(({producerId:d})=>!this.producers.get(d)&&!i.has(d));if(a.length===0)return;const{consumers:o,failedProducers:c}=await this.recvTransport.consume(a,k(this,kl,$T).bind(this),n(this,Rs).negotiate.bind(n(this,Rs)));if(o.forEach(k(this,bl,xT).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);m(this,er,n(this,er).concat(d)),m(this,Ta,setTimeout(k(this,Sc,Ph).bind(this),e))}}catch(i){const a=i instanceof Error?i:new Error(String(i));this.logger.error("failed to consume on transport",{error:a});const{errorCode:o,errorDescription:c}=cO(a);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})}}},Cl=new WeakSet,LT=function(e){return n(this,Tc).create(e)},Rl=new WeakSet,VT=function(e,r){e.on("close",async(i,a)=>{const{reason:o}=i,{offer:c}=i;if(this.logger.info("producer::closing",{debuggingHint:o,producer:{...e,status:"closing"}}),o!==Bd){const d={producerId:e.id,description:{sdp:c.sdp,type:c.type,target:mr.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"}}),a({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"}})}),n(this,qi).set(e.id,e)},kl=new WeakSet,$T=async function(e){try{return await this.recvTransport.canConsume(),await n(this,Rs).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},bl=new WeakSet,xT=function(e){e.on("close",async r=>{this.logger.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),n(this,Cs).delete(e.id),this.context.getValue("peerSessionStore").emit(w.CONSUMER_CLOSED,{id:e.id})}),n(this,Cs).set(e.id,e),this.context.getValue("peerSessionStore").emit(w.NEW_CONSUMER_CREATED,{id:e.id,appData:e.appData,peerId:e.peerId})};var vc,yc,Ec,Sa,va,ya,Pc,wc,Ea,Pt,cs,ds,Gi,Wi,tr,_c,Ml,UT,Al,HT,Il,BT,Dl,FT;const Ol=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:a=.95,voiceAdaptationRate:o=.99,minEnergyThreshold:c=.005,maxEnergyThreshold:d=.2,energyRatioThreshold:l=1.5,noiseHistorySize:u=50}={}){g(this,Ml);g(this,Al);g(this,vc,void 0);g(this,yc,void 0);g(this,Ec,void 0);g(this,Sa,void 0);g(this,va,void 0);g(this,ya,void 0);g(this,Pc,void 0);g(this,wc,void 0);g(this,Ea,void 0);g(this,Pt,void 0);g(this,cs,void 0);g(this,ds,!1);g(this,Gi,0);g(this,Wi,0);g(this,tr,[]);g(this,_c,void 0);m(this,Sa,t),m(this,Pt,t),m(this,vc,e),m(this,yc,r),m(this,Ec,i),m(this,va,a),m(this,ya,o),m(this,Pc,c),m(this,wc,d),m(this,Ea,l),m(this,_c,u),m(this,cs,t/2)}get voiceDetected(){return n(this,ds)}processAudioChunk(t){var o,c;const e=k(o=Ol,Il,BT).call(o,t),r=k(c=Ol,Dl,FT).call(c,t);return k(this,Ml,UT).call(this,e),e/n(this,cs)>n(this,Ea)&&e>n(this,Pt)&&r>n(this,vc)?(m(this,Gi,n(this,Gi)+1),m(this,Wi,n(this,Ec)),n(this,Gi)>=n(this,yc)&&m(this,ds,!0)):(m(this,Gi,0),n(this,Wi)>0?m(this,Wi,n(this,Wi)-1):n(this,ds)&&m(this,ds,!1),n(this,ds)||k(this,Al,HT).call(this,e)),{energy:e,isVoice:n(this,ds)}}reset(){m(this,ds,!1),m(this,Gi,0),m(this,Wi,0),m(this,Pt,n(this,Sa)),m(this,cs,n(this,Sa)/2),m(this,tr,[])}getThresholdInfo(){return{currentEnergyThreshold:n(this,Pt),backgroundNoiseEnergy:n(this,cs),energyRatioThreshold:n(this,Ea)}}};let oo=Ol;vc=new WeakMap,yc=new WeakMap,Ec=new WeakMap,Sa=new WeakMap,va=new WeakMap,ya=new WeakMap,Pc=new WeakMap,wc=new WeakMap,Ea=new WeakMap,Pt=new WeakMap,cs=new WeakMap,ds=new WeakMap,Gi=new WeakMap,Wi=new WeakMap,tr=new WeakMap,_c=new WeakMap,Ml=new WeakSet,UT=function(t){n(this,ds)?m(this,Pt,n(this,ya)*n(this,Pt)+(1-n(this,ya))*t):m(this,Pt,n(this,va)*n(this,Pt)+(1-n(this,va))*n(this,cs)),m(this,Pt,Math.max(n(this,Pc),Math.min(n(this,wc),n(this,Pt))))},Al=new WeakSet,HT=function(t){if(t<n(this,Pt)*1.2)if(n(this,tr).push(t),n(this,tr).length>n(this,_c)&&n(this,tr).shift(),n(this,tr).length>=10){const e=[...n(this,tr)].sort((i,a)=>i-a),r=Math.floor(e.length/2);m(this,cs,e[r])}else m(this,cs,.95*n(this,cs)+.05*t)},Il=new WeakSet,BT=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Dl=new WeakSet,FT=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},g(oo,Il),g(oo,Dl);var Cc;class qg{constructor(t){p(this,"RNAudioSampleHandler");g(this,Cc,void 0);m(this,Cc,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 n(this,Cc).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()}}Cc=new WeakMap;var Rc;class Gg{constructor(t){p(this,"audioContext");p(this,"analyser");g(this,Rc,void 0);m(this,Rc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return n(this,Rc).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)}}Rc=new WeakMap;class jT{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 lO=60,uO=400;var sr,rr,ir,kc,Pa,wa,Kr,Ji,_a,Ki,nr,ks,bc,wh,Nl,qT,Mc,_h,Ac,Ch,Ll,GT;const wo=class{constructor(t,e){g(this,bc);g(this,Nl);g(this,Ac);g(this,sr,void 0);g(this,rr,void 0);g(this,ir,void 0);g(this,kc,void 0);g(this,Pa,void 0);g(this,wa,void 0);g(this,Kr,void 0);g(this,Ji,void 0);g(this,_a,void 0);g(this,Ki,void 0);g(this,nr,void 0);g(this,ks,void 0);this.reportRequest=e,m(this,Ki,t),m(this,wa,new oo);const{isReactNative:r}=navigator;m(this,nr,r?new qg(n(this,Ki)):new Gg(n(this,Ki))),m(this,ks,r?jT:go)}get logger(){return n(this,Ki).getValue("logger")}set producerId(t){m(this,ir,t)}set audioTrack(t){m(this,kc,t),n(this,nr)instanceof Gg&&(n(this,nr).audioTrack=t)}start(t=!1){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter of audio producer ${n(this,ir)}.`),n(this,sr)&&n(this,ks).clearInterval(n(this,sr)),m(this,sr,n(this,ks).setInterval(k(this,bc,wh).bind(this),lO)),n(this,rr)&&n(this,ks).clearInterval(n(this,rr)),m(this,rr,n(this,ks).setInterval(k(this,Ac,Ch).bind(this),uO)),t&&(k(this,bc,wh).call(this),k(this,Ac,Ch).call(this))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter of audio producer ${n(this,ir)}`),n(this,sr)&&(n(this,ks).clearInterval(n(this,sr)),m(this,sr,void 0)),n(this,rr)&&(n(this,ks).clearInterval(n(this,rr)),m(this,rr,void 0))}catch(t){}n(this,wa).reset(),n(this,nr)instanceof qg&&n(this,nr).stop()}};let co=wo;sr=new WeakMap,rr=new WeakMap,ir=new WeakMap,kc=new WeakMap,Pa=new WeakMap,wa=new WeakMap,Kr=new WeakMap,Ji=new WeakMap,_a=new WeakMap,Ki=new WeakMap,nr=new WeakMap,ks=new WeakMap,bc=new WeakSet,wh=function(){var i;if(!n(this,kc)||!n(this,ir))return;const{energy:t}=k(this,Nl,qT).call(this),e=k(i=wo,Mc,_h).call(i,t);let r=.9;n(this,_a)!==e&&n(this,_a)?r=.9:e?r=.3:r=.5,m(this,Pa,(n(this,Pa)||0)*(1-r)+t*r)},Nl=new WeakSet,qT=function(){var o;const{samples:t}=n(this,nr),{energy:e,isVoice:r}=n(this,wa).processAudioChunk(t),i=k(o=wo,Ll,GT).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!n(this,Kr)||i<n(this,Kr))&&m(this,Kr,i),(!n(this,Ji)||i>n(this,Ji))&&m(this,Ji,i),{energy:(i-n(this,Kr))/(n(this,Ji)-n(this,Kr))*10||0,isVoice:r})},Mc=new WeakSet,_h=function(t){return t<5},Ac=new WeakSet,Ch=function(t=n(this,Pa)){var r;if(!n(this,ir)||!t)return;const e={producerId:n(this,ir),energy:Math.round(t),silent:k(r=wo,Mc,_h).call(r,t)};m(this,_a,e.silent),this.reportRequest(e)},Ll=new WeakSet,GT=function(t){const e=Math.log10(t);return Math.round(e)},g(co,Mc),g(co,Ll);var hO=Object.defineProperty,pO=Object.getOwnPropertyDescriptor,ue=(s,t,e,r)=>{for(var i=r>1?void 0:r?pO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&hO(t,e,i),i},Ic,Dc,Ge,H,Vl,ht,ar,zi,Yi,Oc,Dt,or,pt,gt,cr,hi,Nc,Rh,$l,WT,xl,JT,Ul,KT,Lc,kh,Hl,zT,Bl,YT,Xe,nt,Qi,lo,Vc,bh,Fl,QT,jl,XT,ql,ZT;class ne{constructor(t,e){g(this,cr);g(this,Nc);g(this,$l);g(this,xl);g(this,Ul);g(this,Lc);g(this,Hl);g(this,Bl);g(this,Xe);g(this,Qi);g(this,Vc);g(this,Fl);g(this,jl);g(this,ql);p(this,"context");p(this,"authToken");p(this,"e2ee");g(this,Ic,void 0);g(this,Dc,void 0);g(this,Ge,void 0);g(this,H,void 0);g(this,Vl,void 0);g(this,ht,void 0);g(this,ar,void 0);g(this,zi,void 0);g(this,Yi,void 0);g(this,Oc,void 0);g(this,Dt,null);g(this,or,void 0);g(this,pt,void 0);g(this,gt,void 0);var i,a;this.context=t;const{socket:r}=e;this.mediaJoined=!1,m(this,Ge,r),m(this,ar,!1),m(this,H,new dO(t,r)),m(this,ht,n(this,H).events),m(this,or,new Set),m(this,pt,new Map),m(this,zi,!1),m(this,Yi,new fh(t.getValue("logger"))),m(this,gt,new co(this.context,n(this,H).socketHandler.audioActivity.bind(n(this,H).socketHandler))),this.e2ee=(a=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?a:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),m(this,Oc,ip(async()=>{if(!n(this,cr,hi).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(n(this,Dc),n(this,Ic),!0);o&&(this.context.getValue("peerSessionStore").emit(w.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return n(this,cr,hi).mediaJoined}set mediaJoined(t){n(this,cr,hi).mediaJoined=t}reset({resetTransportQueue:t}){this.logger.info(`Resetting media node client: closing all transports, producers, consumers, and queues(resetTransportQueue: ${t}).`),n(this,H).closeAllProducers(),n(this,H).closeAllConsumers(),n(this,pt).clear(),n(this,or).clear(),m(this,Dt,null),t&&n(this,Yi).stop(),n(this,H).stopAllTransports(),n(this,H).reset(),t&&m(this,Yi,new fh)}async joinRoom(t,e,r=!1,i={}){n(this,cr,hi).mediaJoinAttempted=!0,m(this,ar,!0);const a=this.peerId;try{const o=await n(this,Yi).push(()=>k(this,$l,WT).call(this,t,e,r,i),"joinRoom");return o.roomJoined||k(this,Nc,Rh).call(this,a),o}catch(o){return this.logger.error("Error in room joining process",{error:o}),k(this,Nc,Rh).call(this,a),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_FAILED),{roomJoined:!1,error:o}}}async initializeConnection(t,e,r=!1,i={}){return n(this,Dt)?n(this,Dt):(m(this,Dt,(async()=>{try{await k(this,Lc,kh).call(this,t,e,r,i)}catch(a){throw m(this,Dt,null),a}})()),n(this,Dt))}getConsumers(){return n(this,H).consumers}getProducers(){return n(this,H).producers}handoverPeerProducers(t,e){const r=new Set(e);return Array.from(n(this,H).consumers.values()).filter(i=>r.has(i.producerId)?(i.reassignPeer(t),!0):!1)}async leaveRoom(){var r;(r=n(this,gt))==null||r.stop(),n(this,H).stopAllTransports(),m(this,zi,!1),n(this,cr,hi).mediaJoinAttempted=!1;const t={closeRoom:!1};try{n(this,Ge).sendMessage(n(this,ht).leaveRoom,MR.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():n(this,H).createConsumers(t)}removeClosedConsumers(t){return n(this,H).removeClosedConsumers(t)}async closeConsumersById(t){t.length&&await n(this,H).closeConsumers(t)}async _shareWebcam(t){var u,h,f,S;const e=Te.WEBCAM,r=k(this,Xe,nt).call(this,e);if(r){const E=await r;if(n(this,H).producers.has(E)){const R=n(this,H).producers.get(E);if(!R.closed)return await R.replaceTrack({track:t}),await this.resumeWebcam(e),t;await this.disableWebcam()}return this._shareWebcam(t)}const i=k(this,ql,ZT).call(this,t),a=Ao(this.context,"disableSimulcast"),o=(h=(u=this.context)==null?void 0:u.getValue("overrides"))==null?void 0:h.simulcastConfig;a||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=tD(this.context,t),this.logger.info(`Simulcast encodings: ${JSON.stringify(i.encodings)}`));const d=()=>{this.logger.info("Disabling video due to the producer closure"),n(this,pt).delete(e)},l=n(this,H).createProducer(i,d);return k(this,Qi,lo).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 k(this,Xe,nt).call(this,Te.SCREENSHARE_VIDEO),a=await k(this,Xe,nt).call(this,Te.SCREENSHARE_AUDIO),o=n(this,H).producers.get(i),c=n(this,H).producers.get(a),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:ye.isElectron()},stopTracks:!1},u=()=>{this.logger.info("Disabling screenShare due to the producer closure"),n(this,pt).delete(Te.SCREENSHARE_VIDEO),n(this,pt).delete(Te.SCREENSHARE_AUDIO)},h=n(this,H).createProducer(l,u);k(this,Qi,lo).call(this,Te.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:ye.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},u=()=>{},h=n(this,H).createProducer(l,u);k(this,Qi,lo).call(this,Te.SCREENSHARE_AUDIO,h.then(f=>f.id)),d.push(h)}else a&&(k(this,Vc,bh).call(this,Te.SCREENSHARE_AUDIO),d.push(n(this,H).closeProducer(a)));await Promise.all(d),this.context.getValue("callstats").screenShareStart()}async shareMic(t){try{if(t===void 0)throw new _t("track undefined");const e=k(this,Xe,nt).call(this,Te.MIC);if(e){const o=await e;if(n(this,H).producers.has(o)){const c=n(this,H).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),n(this,gt)&&(n(this,gt).audioTrack=t,n(this,gt).producerId=o,n(this,gt).start(!0));return}await n(this,H).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=k(this,jl,XT).call(this,t),i=()=>{n(this,pt).delete(Te.MIC)},a=n(this,H).createProducer(r,i);k(this,Qi,lo).call(this,Te.MIC,a.then(o=>o.id)),await a.then(o=>{n(this,gt)&&(n(this,gt).audioTrack=o.track,n(this,gt).producerId=o.id,n(this,gt).start())})}catch(e){throw new C(e)}}async pauseMic(){var i;const t=await k(this,Xe,nt).call(this,Te.MIC),e=n(this,H).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=n(this,gt))==null||i.stop();const r={producerId:e.id,pause:!0};n(this,Ge).sendMessage(n(this,ht).toggleProducer,cd.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 k(this,Xe,nt).call(this,Te.WEBCAM),e=n(this,H).producers.get(t);if(!e){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}e.pause();const r={producerId:e.id,pause:!0};n(this,Ge).sendMessage(n(this,ht).toggleProducer,cd.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 k(this,Xe,nt).call(this,Te.MIC),e=n(this,H).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(w.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};n(this,Ge).sendMessage(n(this,ht).toggleProducer,cd.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=Te.WEBCAM){const e=await k(this,Xe,nt).call(this,t),r=n(this,H).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(w.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};n(this,Ge).sendMessage(n(this,ht).toggleProducer,cd.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=Te.WEBCAM,e=await k(this,Xe,nt).call(this,t);k(this,Vc,bh).call(this,t),e&&await n(this,H).closeProducer(e)}async disableMic(){var e;const t=await k(this,Xe,nt).call(this,Te.MIC);t&&await n(this,H).closeProducer(t),(e=n(this,gt))==null||e.stop(),n(this,pt).delete(Te.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await k(this,Xe,nt).call(this,Te.SCREENSHARE_VIDEO),e=await k(this,Xe,nt).call(this,Te.SCREENSHARE_AUDIO);t&&await n(this,H).closeProducer(t),e&&await n(this,H).closeProducer(e),n(this,or).clear(),n(this,pt).delete(Te.SCREENSHARE_VIDEO),n(this,pt).delete(Te.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await k(this,Xe,nt).call(this,Te.WEBCAM);await n(this,H).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await k(this,Xe,nt).call(this,Te.SCREENSHARE_VIDEO);await n(this,H).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:e})}}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await n(this,H).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};n(this,H).socketHandler.kickPeer(e)}kickAll(){n(this,H).socketHandler.kickAll()}async muteAll(t){if(!await n(this,H).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await n(this,H).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await n(this,H).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await n(this,H).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 n(this,Ge).sendMessagePromise(n(this,ht).globalPinPeer,jR.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&n(this,H).producers.get(t.producerId)&&n(this,or).add(t.consumerPeerId),n(this,or).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));n(this,H).switchConsumersToLayer(r,e)}async handleSocketEvents(){n(this,Ge).on(n(this,ht).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{k(this,Fl,QT).call(this,Wk.fromBinary(t))}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),n(this,Ge).on(n(this,ht).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const e=Pg.fromBinary(t),{participantId:r,initiatorParticipantId:i,producerState:{kind:a,pause:o,producerId:c,screenShare:d}}=e;if(d)return;const l=a===Ds.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: ${Pg.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"?w.MUTE_SELF:w.MUTE_SELF_VIDEO)),r===this.peerId)return;this.context.getValue("peerSessionStore").emit(w.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(w.CONSUMER_PAUSED,{id:h.id})):(h.resume(),this.context.getValue("peerSessionStore").emit(w.CONSUMER_RESUMED,{id:h.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),n(this,Ge).on(n(this,ht).peerLeaveBroadcast,async({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=Ju.fromBinary(t);if(e===this.peerId)return;this.logger.info(`Received peer left broadcast of remote peer ${e}`),n(this,or).delete(e),this.context.getValue("peerSessionStore").emit(w.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast of remote peer",{error:e})}}),n(this,Ge).on(n(this,ht).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=zk.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(w.PRODUCER_CLOSED,{peerId:e,producerId:r})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),n(this,Ge).on(n(this,ht).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!n(this,ar)&&!n(this,zi)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_DISCONNECTED),n(this,Oc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=n(this,H).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(w.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(n(this,H).producers.values()).find(a=>a.id===r);i&&this.context.getValue("peerSessionStore").emit(w.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}}Ic=new WeakMap,Dc=new WeakMap,Ge=new WeakMap,H=new WeakMap,Vl=new WeakMap,ht=new WeakMap,ar=new WeakMap,zi=new WeakMap,Yi=new WeakMap,Oc=new WeakMap,Dt=new WeakMap,or=new WeakMap,pt=new WeakMap,gt=new WeakMap,cr=new WeakSet,hi=function(){return this.context.getValue("connectionHandler")},Nc=new WeakSet,Rh=function(t){this.mediaJoined=!1,m(this,ar,!1),n(this,Ge).isConnected&&this.peerId===t&&this.context.getValue("peerSessionStore").emit(w.MEDIA_ROOM_JOIN_FAILED)},$l=new WeakSet,WT=async function(t,e,r,i){var o;m(this,Dc,t);let a=!1;if(r){const{recv:c,send:d}=(o=n(this,cr,hi).mediaState)!=null?o:{};(d==null?void 0:d.state)===Ft.CONNECTED&&(c==null?void 0:c.state)===Ft.CONNECTED?(this.logger.info("MediaNodeClient.joinRoom: transports healthy — preserving all producers for ownership handover"),m(this,Dt,null),a=!0):(this.logger.info("MediaNodeClient.joinRoom: transports unhealthy — full reset"),this.reset({resetTransportQueue:!1}))}try{n(this,Dt)?await n(this,Dt):await k(this,Lc,kh).call(this,t,e,r,i,a),k(this,Ul,KT).call(this,e);const{joined:c,error:d}=await k(this,xl,JT).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{m(this,Dt,null)}},xl=new WeakSet,JT=async function(){const t=this.peerId;try{this.mediaJoined=!0;const{roomState:e}=await Hd(async(r,i)=>{if(!n(this,Ge).isConnected||this.peerId!==t){const a=new Error("Media room join completion superseded by a newer connection");throw i(a),a}return r>0&&this.logger.warn(`Retrying media room join completion for peer ${t}: attempt=${r+1}`),n(this,H).socketHandler.notifySelfJoinComplete()},{strategy:"exponential",maxRetryCount:3,delayTime:1e3});return m(this,Ic,e.roomUuid),m(this,zi,!0),m(this,ar,!1),{joined:!0}}catch(e){return this.logger.error("Error completing room join",{error:e}),this.mediaJoined=!1,m(this,ar,!1),{joined:!1,error:e}}},Ul=new WeakSet,KT=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...ye.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)},Lc=new WeakSet,kh=async function(t,e,r,i,a=!1){try{const o=k(this,Hl,zT).call(this);await k(this,Bl,YT).call(this,t,e,r,o),a?this.logger.info("MediaNodeClient: reusing existing transports on rejoin"):await n(this,H).setupTransports({send:!0,recv:!0})}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},Hl=new WeakSet,zT=function(){const t=QD("video/VP8");return m(this,Vl,t),t},Bl=new WeakSet,YT=async function(t,e,r,i){await Hd(async(a,o)=>{if(!n(this,Ge).isConnected){o(new Error("Socket is not connected"));return}a>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${a}`});try{await n(this,H).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})},Xe=new WeakSet,nt=function(t){return n(this,pt).get(t)},Qi=new WeakSet,lo=function(t,e){return n(this,pt).set(t,e)},Vc=new WeakSet,bh=function(t){return n(this,pt).delete(t)},Fl=new WeakSet,QT=function({participantId:t,producerState:e}){var i;if(t===this.peerId||!e)return;this.logger.info(`Received remote ${e.screenShare?"screenshare":"participant"} ${e.kind===Ds.AUDIO?"audio":"video"} producer created broadcast for peer ${t} with producer state ${JSON.stringify(e)}.`);const r=(i=e.mimeType)!=null?i:e.kind===Ds.AUDIO?"audio/opus":"video/VP8";this.context.getValue("peerSessionStore").emit(w.NEW_PRODUCER,{peerId:t,producer:{...e,mimeType:r,kind:e.kind===Ds.AUDIO?"audio":"video",producingPeerId:t}})},jl=new WeakSet,XT=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},ql=new WeakSet,ZT=function(t){return{track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}};ue([y.trace("MediaNodeClient.reset")],ne.prototype,"reset",1);ue([y.trace("MediaNodeClient.joinRoom")],ne.prototype,"joinRoom",1);ue([y.trace("MediaNodeClient.leaveRoom")],ne.prototype,"leaveRoom",1);ue([y.trace("MediaNodeClient.activatePeers")],ne.prototype,"activatePeers",1);ue([y.trace("MediaNodeClient.createConsumers")],ne.prototype,"createConsumers",1);ue([y.trace("MediaNodeClient.closeConsumersById")],ne.prototype,"closeConsumersById",1);ue([y.trace("MediaNodeClient._shareWebcam")],ne.prototype,"_shareWebcam",1);ue([y.trace("MediaNodeClient.shareWebcam")],ne.prototype,"shareWebcam",1);ue([y.trace("MediaNodeClient.shareScreen")],ne.prototype,"shareScreen",1);ue([y.trace("MediaNodeClient.shareMic")],ne.prototype,"shareMic",1);ue([y.trace("MediaNodeClient.pauseMic")],ne.prototype,"pauseMic",1);ue([y.trace("MediaNodeClient.pauseWebcam")],ne.prototype,"pauseWebcam",1);ue([y.trace("MediaNodeClient.resumeMic")],ne.prototype,"resumeMic",1);ue([y.trace("MediaNodeClient.resumeWebcam")],ne.prototype,"resumeWebcam",1);ue([y.trace("MediaNodeClient.disableWebcam")],ne.prototype,"disableWebcam",1);ue([y.trace("MediaNodeClient.disableMic")],ne.prototype,"disableMic",1);ue([y.trace("MediaNodeClient.disableScreenShare")],ne.prototype,"disableScreenShare",1);ue([y.trace("MediaNodeClient.muteSelf")],ne.prototype,"muteSelf",1);ue([y.trace("MediaNodeClient.resetVideoProducers")],ne.prototype,"resetVideoProducers",1);ue([y.trace("MediaNodeClient.changeDisplayName")],ne.prototype,"changeDisplayName",1);ue([y.trace("MediaNodeClient.kickPeer")],ne.prototype,"kick",1);ue([y.trace("MediaNodeClient.kickAllPeers")],ne.prototype,"kickAll",1);ue([y.trace("MediaNodeClient.muteAll")],ne.prototype,"muteAll",1);ue([y.trace("MediaNodeClient.muteAllVideo")],ne.prototype,"muteAllVideo",1);ue([y.trace("MediaNodeClient.disableAudio")],ne.prototype,"disableAudio",1);ue([y.trace("MediaNodeClient.disableVideo")],ne.prototype,"disableVideo",1);ue([y.trace("MediaNodeClient.pinPeer")],ne.prototype,"pinPeer",1);ue([y.trace("MediaNodeClient.validateScreenShare")],ne.prototype,"validateScreenShare",1);function eS(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 ne(s,t);return s.setValue("roomNodeClient",r),r}function gO(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 mO=Object.defineProperty,fO=Object.getOwnPropertyDescriptor,fn=(s,t,e,r)=>{for(var i=r>1?void 0:r?fO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&mO(t,e,i),i},Ca,Qt,Q,rt,vt,mm;const tS=(mm=class{constructor(s,t,e,r){g(this,rt);p(this,"self");p(this,"authToken");g(this,Ca,void 0);p(this,"viewType");g(this,Qt,void 0);g(this,Q,void 0);const{socket:i}=e,a=s.getValue("authToken");this.self=t,m(this,Q,s),this.viewType=r,this.authToken=a,m(this,Ca,i),m(this,Qt,e),this.setupEvents()}get peerId(){return n(this,Q).getValue("peerId")}get telemetry(){return n(this,Q).getValue("telemetry")}get logger(){return n(this,Q).getValue("logger")}get mediaJoined(){return n(this,Q).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const a=Lt(),o=!!s.getValue("cachedUserDetails"),c=await Ke.__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:ye.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:await a.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:d,apiHostnames:EC(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 tS(s,c,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:a,screenShareTracks:o}=this.self;if(e.canProduceAudio===j.Allowed&&r)if((s==null?void 0:s.readyState)==="live")try{await n(this,rt,vt).shareMic(s),this.self.audioEnabled||n(this,rt,vt).pauseMic()}catch(d){this.self.disableAudio()}else this.logger.warn("shareMediaTracks: audio track is dead, disabling audio"),this.self.disableAudio();if(e.canProduceVideo===j.Allowed&&i)if((t==null?void 0:t.readyState)==="live")try{await n(this,rt,vt).shareWebcam(t),this.self.videoEnabled||n(this,rt,vt).pauseWebcam()}catch(d){this.self.disableVideo()}else this.logger.warn("shareMediaTracks: video track is dead, disabling video"),this.self.disableVideo();if(e.canProduceScreenshare===j.Allowed&&a){const d=o.video,l=o.audio;if((d==null?void 0:d.readyState)==="live")try{await((c=n(this,rt,vt))==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;n(this,Q).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=n(this,rt,vt))==null||r.reset({resetTransportQueue:!0}))}setupEvents(){n(this,Q).getValue("peerSessionStore").on(w.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&await this.shareMediaTracks()}),n(this,Q).getValue("peerSessionStore").on(w.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),n(this,Q).getValue("peerSessionStore").on(w.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),n(this,Q).getValue("peerSessionStore").on(w.ROOM_NODE_FAILED,()=>{this.logger.error("Room node failed. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,Q).getValue("peerSessionStore").on(w.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})})}),n(this,Q).getValue("peerSessionStore").on(w.SOCKET_SERVICE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),n(this,Q).getValue("peerSessionStore").on(w.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"})}),n(this,Qt).on(L.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),n(this,Qt).on(Sd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&n(this,Q).getValue("peerSessionStore").emit(w.UPDATE_PERMISSIONS,t.patch)})}),n(this,Qt).on(L.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),n(this,Qt).on(L.kick,()=>{this.kickHandler({kickType:"kick"})}),n(this,Qt).on(L.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),n(this,Q).getValue("peerSessionStore").onAsync(w.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),n(this,Q).getValue("peerSessionStore").on(w.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var a;const i=(a=e==null?void 0:e.screenShare)!=null?a:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),n(this,Q).getValue("peerSessionStore").on(w.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),n(this,Q).getValue("callstats").audioOff())}),n(this,Q).getValue("peerSessionStore").on(w.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),n(this,Q).getValue("callstats").videoOff())}),n(this,Q).getValue("peerSessionStore").onAsync(w.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),n(this,Q).getValue("peerSessionStore").on(w.PIP_HANGUP,this.leaveRoom.bind(this))}async joinSocketRoomWithRetry(){const s=this.self.id;return Hd(async(t,e)=>{if(!n(this,Ca).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 n(this,Qt).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."),n(this,Qt).socket.flush();const a=lp(i.stageType);if(n(this,Q).setValue("stageStatus",a,!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=n(this,rt,vt))==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===hs.Livestream&&(t!=null&&t.wasSocketJoinAttempted)&&!t.wasMediaJoinAttempted&&n(this,Q).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=n(this,rt,vt))==null||r.reset({resetTransportQueue:!0}),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s}),n(this,Q).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."),n(this,Q).notify("stageStatus")}catch(i){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:i}),i instanceof Dr&&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),n(this,Q).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),n(this,Q).setValue("roomNodeClient",void 0),n(this,Q).notify("stageStatus"),n(this,Q).getValue("connectionHandler").socketJoined)try{n(this,Qt).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=n(this,Q).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 a,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=n(this,Q).getAllValues();try{if(e===hs.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}eS(n(this,Q),{socket:n(this,Ca),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:h}=(o=await((a=n(this,rt,vt))==null?void 0:a.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=n(this,Q).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===hs.Webinar)&&n(this,rt,vt)&&(n(this,rt,vt).mediaJoined&&s!=="disconnected"&&await n(this,rt,vt).leaveRoom(),!(s==="stageLeft"&&t===hs.Livestream)&&(n(this,rt,vt).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()}},Ca=new WeakMap,Qt=new WeakMap,Q=new WeakMap,rt=new WeakSet,vt=function(){return n(this,Q).getValue("roomNodeClient")},mm);let di=tS;fn([y.trace("SelfController.resetSelf")],di.prototype,"resetSelf",1);fn([y.trace("SelfController.setupEvents")],di.prototype,"setupEvents",1);fn([y.trace("SelfController.joinRoom")],di.prototype,"joinRoom",1);fn([y.trace("SelfController.leaveRoom")],di.prototype,"leaveRoom",1);fn([y.trace("SelfController.joinMediaRoom")],di.prototype,"joinMediaRoom",1);fn([y.trace("SelfController.leaveMediaRoom")],di.prototype,"leaveMediaRoom",1);fn([y.trace("SelfController.init")],di,"init",1);var $c;class TO{constructor(t){g(this,$c,void 0);m(this,$c,t)}on(t,e){let r;t===L.roomPeerCount?r=Cg.fromBinary.bind(Cg):r=Dg.fromBinary.bind(Dg),n(this,$c).on(t,({payload:i})=>{if(t===L.roomPeerCount&&!i)return;const a=r(i);e(a)})}}$c=new WeakMap;var xc,Uc;class SO{constructor(t,e){g(this,xc,void 0);g(this,Uc,void 0);m(this,xc,e),m(this,Uc,t)}get logger(){return n(this,Uc).getValue("logger")}on(t,e){let r,i;switch(t){case L.transcript:{r=Ru.fromBinary.bind(Ru),i=Ru.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}n(this,xc).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}xc=new WeakMap,Uc=new WeakMap;var vO=Object.defineProperty,yO=Object.getOwnPropertyDescriptor,wp=(s,t,e,r)=>{for(var i=r>1?void 0:r?yO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&vO(t,e,i),i},dr,Ra;class gu{constructor(t,e){g(this,dr,void 0);g(this,Ra,void 0);m(this,dr,e),m(this,Ra,t)}get logger(){return n(this,Ra).getValue("logger")}get telemetry(){return n(this,Ra).getValue("telemetry")}getPolls(){return n(this,dr).sendMessagePromise(Bs.getPolls)}createPoll(t,e,r=!1,i=!1){const a={anonymous:r,hideVotes:i,question:t,options:e};return n(this,dr).sendMessage(Bs.createPoll,bI.toBinary(a))}votePoll(t,e){const r={index:e,pollId:t};return n(this,dr).sendMessage(Bs.votePoll,AI.toBinary(r))}on(t,e){let r,i;switch(t){case Bs.updatePoll:case Bs.createPoll:case Bs.votePoll:{r=Du.fromBinary.bind(Du),i=Du.create();break}}n(this,dr).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){n(this,dr).removeListeners(t)}}dr=new WeakMap,Ra=new WeakMap;wp([y.trace("PollSocketHandler.getPolls")],gu.prototype,"getPolls",1);wp([y.trace("PollSocketHandler.createPoll")],gu.prototype,"createPoll",1);wp([y.trace("PollSocketHandler.votePoll")],gu.prototype,"votePoll",1);var EO=Object.defineProperty,PO=Object.getOwnPropertyDescriptor,wO=(s,t,e,r)=>{for(var i=r>1?void 0:r?PO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&EO(t,e,i),i},Ot;class sS{constructor(t,e){p(this,"socket");g(this,Ot,void 0);m(this,Ot,t),this.socket=e,this.handleSocketEvents(),n(this,Ot).setValue("roomSocketHandler",this)}get telemetry(){return n(this,Ot).getValue("telemetry")}get logger(){return n(this,Ot).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}async joinRoom(t){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(L.joinRoom,Rb.toBinary(e));try{const{peer:a}=Sn.fromBinary((await r).payload);n(this,Ot).getValue("connectionHandler").socketJoined=!0,n(this,Ot).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_ROOM_JOINED,{peer:a});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return n(this,Ot).getValue("peerSessionStore").emit(w.ROOM_STATE,d),n(this,Ot).getValue("peerSessionStore").emit(w.SOCKET_PEERS,l),{peer:a}}catch(a){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:a}),a}}async getAllAddedParticipants(){try{return hM.fromBinary((await this.socket.sendMessagePromise(L.getAllAddedParticipants)).payload).participants.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}async getRoomPeers(t,e,r){let i;try{const a={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise(L.getRoomPeersInfo,fb.toBinary(a));i=ku.fromBinary(o.payload)}catch(a){this.logger.error("getRoomPeers::binary_decode_error",{error:a})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise(L.getRoomPeersInfo);t=ku.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getStagePeers(){let t;try{const e=await this.socket.sendMessagePromise(L.getRoomPeersInfo);t=ku.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getPeerInfo(t){let e;try{const r=await this.socket.sendMessagePromise(L.getPeerInfo,jf.toBinary({peerId:t}));e=Sn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=Rg.create();try{const e=await this.socket.sendMessagePromise(L.getRoomInfo);t=Rg.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=Mg.create();try{const e=await this.socket.sendMessagePromise(L.getRoomStageState);t=Mg.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t}updateRoomTitle(t){return this.socket.sendMessagePromise(L.updateRoomInfo,dd.toBinary(dd.create({room:{title:t}})))}async broadcastMessage(t,e){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(L.broadcastMessage,Za.toBinary(r))}async broadcastToMeetings(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(L.broadcastToEntity,Za.toBinary(i))}async broadcastToPeers(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(L.broadcastToEntity,Za.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(L.leaveRoom,bb.toBinary(e))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(L.kick,Gf.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(L.kickAll,Hf.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(L.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(L.acceptWaitingRoomRequests,SM.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(L.denyWaitingRoomRequests,yM.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Sd.updateUserPreset,zM.toBinary(r))}handleSocketEvents(){this.socket.on(L.broadcastMessage,({payload:t})=>{try{const e=Za.fromBinary(t);n(this,Ot).getValue("peerSessionStore").emit(w.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on(L.broadcastToEntity,({payload:t})=>{try{const e=Za.fromBinary(t);n(this,Ot).getValue("peerSessionStore").emit(w.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case L.joinRoom:case L.leaveRoom:case L.kick:case L.kickAll:{r=Sn.fromBinary.bind(Sn),i=Sn.create();break}case L.getWaitingRoomRequests:{r=(a,o)=>a?bg.fromBinary(a,o):{requests:[]},i=bg.create();break}case L.recordingPaused:case L.recordingStarted:case L.recordingStopped:{r=Lg.fromBinary.bind(Lg);break}case Sd.updateUserPreset:{r=Ag.fromBinary.bind(Ag);break}case us.peerJoinedBroadcast:case Ir.peerJoinedBroadcast:{r=yg.fromBinary.bind(yg);break}case us.selfJoinComplete:case Ir.selfJoinComplete:{r=Wu.fromBinary.bind(Wu);break}case us.globalPeerPinBroadcast:case Ir.globalPeerPinBroadcast:{r=wg.fromBinary.bind(wg);break}case us.selectedPeer:case Ir.selectedPeer:{r=Gu.fromBinary.bind(Gu);break}case us.selectedPeerDiff:case Ir.selectedPeerDiff:{r=vg.fromBinary.bind(vg);break}case us.leaveRoom:case Ir.leaveRoom:{r=Ju.fromBinary.bind(Ju);break}case L.updateRoomInfo:{r=dd.fromBinary.bind(dd);break}}this.socket.on(t,({payload:a})=>{let o=i;if(!r)return e(void 0);try{o=r(a)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}async getUserPermissions(t){const e={userIds:[t]};try{const r=await this.socket.sendMessagePromise(Sd.getUserPresets,FM.toBinary(e)),i=WM.fromBinary(r.payload).peerPresets[0],a=new TextDecoder().decode(i.preset),o=JSON.parse(a).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}}}Ot=new WeakMap;wO([y.trace("RoomSocketHandler.joinRoom")],sS.prototype,"joinRoom",1);var wt;class _O{constructor(t){g(this,wt,void 0);m(this,wt,t)}async getStageRequests(){const{payload:t}=await n(this,wt).sendMessagePromise(L.getStageRequests);return t?Iu.fromBinary(t):{stageRequests:[]}}requestAccess(){n(this,wt).sendMessage(L.requestStageAccess)}cancelRequestAccess(){n(this,wt).sendMessage(L.cancelStageRequest)}async grantAccess(t){const e={userIds:t};n(this,wt).sendMessage(L.grantStageAccess,SI.toBinary(e))}async denyAccess(t){const e={userIds:t};n(this,wt).sendMessage(L.denyStageAccess,yI.toBinary(e))}joinStage(){return n(this,wt).sendMessagePromise(L.joinStage,void 0,void 0,L.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return n(this,wt).sendMessagePromise(L.leaveStage,Ng.toBinary(e),void 0,L.peerStageStatusUpdate)}kick(t){const e={userIds:t};return n(this,wt).sendMessagePromise(L.leaveStage,Ng.toBinary(e))}on(t,e){let r;switch(t){case L.grantStageAccess:case L.denyStageAccess:{r=void 0;break}case L.getStagePeers:{r=Og.fromBinary.bind(Og);break}case L.getStageRequests:case L.requestStageAccess:case L.cancelStageRequest:{r=Iu.fromBinary.bind(Iu);break}case L.peerStageStatusUpdate:{r=_g.fromBinary.bind(_g);break}}n(this,wt).on(t,({payload:i,id:a})=>{if(!i||!r)return e(void 0,a);const o=r(i);return e(o,a)})}async getPeerInfo(t){const e=await n(this,wt).sendMessagePromise(L.getPeerInfo,jf.toBinary({peerId:t}));return Sn.fromBinary(e.payload)}}wt=new WeakMap;var zr,ka;class CO{constructor(t,e){g(this,zr,void 0);g(this,ka,void 0);m(this,zr,e),m(this,ka,t)}get logger(){return n(this,ka).getValue("logger")}get peerId(){return n(this,ka).getValue("peerId")}storeInsertKeys(t,e,r,i){const a={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};n(this,zr).sendMessage(Hs.storeInsertKeys,XA.toBinary(a),i)}storeGetKeys(t,e,r,i){const a={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};n(this,zr).sendMessage(Hs.storeGetKeys,eI.toBinary(a),i)}storeDeleteKeys(t,e,r,i){const a={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};n(this,zr).sendMessage(Hs.storeDeleteKeys,sI.toBinary(a),i)}on(t,e){const r=Ig.fromBinary.bind(Ig);n(this,zr).on(t,({payload:i,id:a})=>{const o=r(i);return e(o,a)})}}zr=new WeakMap,ka=new WeakMap;var RO=Object.defineProperty,kO=(s,t,e)=>t in s?RO(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,bO=(s,t,e)=>(kO(s,typeof t!="symbol"?t+"":t,e),e),_p=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},A=(s,t,e)=>(_p(s,t,"read from private field"),e?e.call(s):t.get(s)),oe=(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)},te=(s,t,e,r)=>(_p(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),re=(s,t,e)=>(_p(s,t,"access private method"),e),jd={},MO={get exports(){return jd},set exports(s){jd=s}},An=typeof Reflect=="object"?Reflect:null,Wg=An&&typeof An.apply=="function"?An.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},_d;An&&typeof An.ownKeys=="function"?_d=An.ownKeys:Object.getOwnPropertySymbols?_d=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:_d=function(s){return Object.getOwnPropertyNames(s)};function AO(s){console&&console.warn&&console.warn(s)}var rS=Number.isNaN||function(s){return s!==s};function le(){le.init.call(this)}MO.exports=le;jd.once=NO;le.EventEmitter=le;le.prototype._events=void 0;le.prototype._eventsCount=0;le.prototype._maxListeners=void 0;var Jg=10;function mu(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(le,"defaultMaxListeners",{enumerable:!0,get:function(){return Jg},set:function(s){if(typeof s!="number"||s<0||rS(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Jg=s}});le.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};le.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||rS(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 iS(s){return s._maxListeners===void 0?le.defaultMaxListeners:s._maxListeners}le.prototype.getMaxListeners=function(){return iS(this)};le.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")Wg(c,this,t);else for(var d=c.length,l=dS(c,d),e=0;e<d;++e)Wg(l[e],this,t);return!0};function nS(s,t,e,r){var i,a,o;if(mu(e),a=s._events,a===void 0?(a=s._events=Object.create(null),s._eventsCount=0):(a.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),a=s._events),o=a[t]),o===void 0)o=a[t]=e,++s._eventsCount;else if(typeof o=="function"?o=a[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=iS(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,AO(c)}return s}le.prototype.addListener=function(s,t){return nS(this,s,t,!1)};le.prototype.on=le.prototype.addListener;le.prototype.prependListener=function(s,t){return nS(this,s,t,!0)};function IO(){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 aS(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=IO.bind(r);return i.listener=e,r.wrapFn=i,i}le.prototype.once=function(s,t){return mu(t),this.on(s,aS(this,s,t)),this};le.prototype.prependOnceListener=function(s,t){return mu(t),this.prependListener(s,aS(this,s,t)),this};le.prototype.removeListener=function(s,t){var e,r,i,a,o;if(mu(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,a=e.length-1;a>=0;a--)if(e[a]===t||e[a].listener===t){o=e[a].listener,i=a;break}if(i<0)return this;i===0?e.shift():DO(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this};le.prototype.off=le.prototype.removeListener;le.prototype.removeAllListeners=function(s){var t,e,r;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[s]),this;if(arguments.length===0){var i=Object.keys(e),a;for(r=0;r<i.length;++r)a=i[r],a!=="removeListener"&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=e[s],typeof t=="function")this.removeListener(s,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(s,t[r]);return this};function oS(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?OO(i):dS(i,i.length)}le.prototype.listeners=function(s){return oS(this,s,!0)};le.prototype.rawListeners=function(s){return oS(this,s,!1)};le.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):cS.call(s,t)};le.prototype.listenerCount=cS;function cS(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}le.prototype.eventNames=function(){return this._eventsCount>0?_d(this._events):[]};function dS(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function DO(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function OO(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function NO(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,a),r(o)}function a(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}lS(s,t,a,{once:!0}),t!=="error"&&LO(s,i,{once:!0})})}function LO(s,t,e){typeof s.on=="function"&&lS(s,"error",t,e)}function lS(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(a){r.once&&s.removeEventListener(t,i),e(a)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class VO extends v.MessageType{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const Kg=new VO;class uS{static encode(t){return Kg.toBinary(t)}static decode(t){return Kg.fromBinary(new Uint8Array(t))}}function $O(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Mr;class xO{constructor(t={}){bO(this,"opts"),oe(this,Mr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},te(this,Mr,0)}async wait(){te(this,Mr,A(this,Mr)+1);const t=$O(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**A(this,Mr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return A(this,Mr)}reset(){te(this,Mr,0)}}Mr=new WeakMap;const wr={debug:0,info:1,warn:2,error:3};var pi,gi;class UO{constructor(t){oe(this,pi,void 0),oe(this,gi,void 0),te(this,pi,console),te(this,gi,t)}debug(...t){wr[A(this,gi)]>wr.debug||A(this,pi).debug("[Sockrates]:",...t)}info(...t){wr[A(this,gi)]>wr.info||A(this,pi).info("[Sockrates]:",...t)}warn(...t){wr[A(this,gi)]>wr.warn||A(this,pi).warn("[Sockrates]:",...t)}error(...t){wr[A(this,gi)]>wr.error||A(this,pi).error("[Sockrates]:",...t)}}pi=new WeakMap,gi=new WeakMap;var hS=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(hS||{});const zg="2",Yg="3";var ke,Pn,ce,Pe,Ar,Je,ur,ri,ls,wn,_n,Us,Mh,pS,uo,Cd,Ah,gS,Rd,Lu,qd,Ih,Dh,mS,So,kd,In,vo,Gd,Oh,Dn,yo,Nh,fS,Eo,bd,Po,Wd;class HO{constructor(t,e){var E,R,M,D,I,x,$,B,z,Z,U,Y;oe(this,Mh),oe(this,uo),oe(this,Ah),oe(this,Rd),oe(this,qd),oe(this,Dh),oe(this,So),oe(this,In),oe(this,Gd),oe(this,Dn),oe(this,Nh),oe(this,Eo),oe(this,Po),oe(this,ke,void 0),oe(this,Pn,void 0),oe(this,ce,void 0),oe(this,Pe,void 0),oe(this,Ar,void 0),oe(this,Je,void 0),oe(this,ur,void 0),oe(this,ri,void 0),oe(this,ls,void 0),oe(this,wn,void 0),oe(this,_n,void 0),oe(this,Us,void 0);var r,i,a,o,c,d,l,u,h,f,S;te(this,Pn,t),te(this,Ar,[]),te(this,Je,new jd),te(this,ur,!0),te(this,ls,!1),te(this,ce,e!=null?e:{}),(E=(r=A(this,ce)).autoReconnect)!=null||(r.autoReconnect=!0),(R=(i=A(this,ce)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(M=(a=A(this,ce)).pingTimeout)!=null||(a.pingTimeout=3e4),(D=(o=A(this,ce)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(I=(c=A(this,ce)).debug)!=null||(c.debug=!0),(x=(d=A(this,ce)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),($=(l=A(this,ce)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(B=(u=A(this,ce)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(z=(h=A(this,ce)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),(Z=(f=A(this,ce)).clientInitiatedPings)!=null||(f.clientInitiatedPings=!1),(U=(S=A(this,ce)).clientInitiatedPingInterval)!=null||(S.clientInitiatedPingInterval=3e4),te(this,ri,{code:void 0,reason:void 0}),te(this,Pe,(Y=A(this,ce).logger)!=null?Y:new UO(A(this,ce).debug?"debug":"info")),te(this,Us,new xO)}get readyState(){var t;return(t=A(this,ke))==null?void 0:t.readyState}get url(){return A(this,Pn)}updateURL(t){te(this,Pn,t),re(this,Dh,mS).call(this)}get config(){return A(this,ce)}get sendQueue(){return A(this,Ar)}flush(){if(!A(this,ce).queueOnDisconnect)return!1;const t=[];return A(this,Ar).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),te(this,Ar,t),A(this,Ar)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){A(this,Pe).debug("Websocket was already connecting or connected.");return}if(A(this,ur)!==!1)return new Promise((e,r)=>{re(this,Dn,yo).call(this),re(this,Po,Wd).call(this);try{te(this,ke,new WebSocket(re(this,Mh,pS).call(this,A(this,Pn)))),A(this,ke).binaryType="arraybuffer",A(this,Pe).debug("Connecting");const i=setTimeout(()=>{A(this,Pe).debug("Connection timeout. Closing socket"),te(this,ur,!0),re(this,Po,Wd).call(this),A(this,ke).close(3001,"Connection Timeout"),A(this,ce).autoReconnect&&!A(this,ls)&&(A(this,Je).emit("reconnecting"),re(this,So,kd).call(this)),r(new Error("Connection timed out!"))},A(this,ce).connectionTimeout);A(this,ke).onopen=()=>{A(this,Pe).debug(`Ready State: ${hS[A(this,ke).readyState]}`),i&&clearTimeout(i),re(this,Gd,Oh).call(this),re(this,Nh,fS).call(this),te(this,ri,{code:void 0,reason:void 0}),A(this,Je).emit("connected"),A(this,ce).flushOnReconnect&&this.flush(),e()},A(this,ke).onclose=a=>{try{i&&clearTimeout(i);const{code:o,reason:c}=a;r(c),A(this,Pe).debug("Socket closed. Close event:",{event:a}),A(this,Pe).debug(`Connection closed code: ${o}`),A(this,Pe).debug(`Connection closed reason: ${c}`),A(this,ls)||re(this,qd,Ih).call(this,o,c)}catch(o){re(this,uo,Cd).call(this,o)}},A(this,ke).onerror=a=>{re(this,uo,Cd).call(this,a)},A(this,ke).onmessage=a=>re(this,Ah,gS).call(this,a)}catch(i){re(this,uo,Cd).call(this,i,r)}})}send(t,e,r,i){const a={event:t,id:e,payload:r,metadata:i};if(A(this,ce).queueOnDisconnect&&(!A(this,ke)||A(this,ke).readyState!==1))return A(this,Pe).debug("Queuing message since socket is not connected!",a),A(this,Ar).push(a),!1;const o=uS.encode(a);return re(this,In,vo).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return re(this,In,vo).call(this,t)}receive(t,e){return A(this,Je).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){A(this,Je).on(t,e);return}this.receive(t,e)}removeAllListeners(){A(this,Je).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){A(this,Je).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){A(this,Je).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){te(this,ur,!1),re(this,Dn,yo).call(this),re(this,Eo,bd).call(this),this.removeAllListeners(),te(this,ri,{code:1e3,reason:"Sockrates disconnect method called"}),A(this,ke).close(1e3,"Sockrates disconnect method called.")}}ke=new WeakMap,Pn=new WeakMap,ce=new WeakMap,Pe=new WeakMap,Ar=new WeakMap,Je=new WeakMap,ur=new WeakMap,ri=new WeakMap,ls=new WeakMap,wn=new WeakMap,_n=new WeakMap,Us=new WeakMap,Mh=new WeakSet,pS=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)://.")},uo=new WeakSet,Cd=function(s,t){A(this,Pe).error("Error:",{error:s}),A(this,Je).emit("errored",{error:s}),t==null||t(s)},Ah=new WeakSet,gS=function(s){if(re(this,Gd,Oh).call(this),s.data===zg){A(this,Pe).debug("Received ping from server"),re(this,In,vo).call(this,Yg);return}if(s.data===Yg){A(this,Pe).debug("Received pong from server");return}const t=uS.decode(s.data),{id:e,payload:r}=t;A(this,Pe).debug("Received message",{event:t.event,messageID:e}),A(this,Je).emit(t.event.toString(),{id:e,payload:r})},Rd=new WeakSet,Lu=function(){return A(this,ke).readyState===1},qd=new WeakSet,Ih=function(s,t){te(this,ri,{reason:t,code:s}),A(this,Je).emit("disconnected",{code:s,reason:t})},Dh=new WeakSet,mS=function(){const{reason:s,code:t}=A(this,ri);t&&t!==1e3&&A(this,ur)&&A(this,ce).autoReconnect&&!A(this,ls)&&(A(this,Pe).debug(`Triggering reconnection due to ${s}.`),A(this,Je).emit("reconnecting"),re(this,So,kd).call(this))},So=new WeakSet,kd=async function(s=!0){if(s&&A(this,ls)){A(this,Pe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(A(this,ls)||A(this,Us).reset(),A(this,ce).maxReconnectionAttempts!==null&&A(this,Us).getAttempts()>=A(this,ce).maxReconnectionAttempts){A(this,Je).emit("failed"),te(this,ls,!1);return}te(this,ls,!0),re(this,Po,Wd).call(this),re(this,Dn,yo).call(this);try{if(await A(this,Us).wait(),A(this,ur)===!1)return;if(A(this,Pe).debug(`Reconnection attempt ${A(this,Us).getAttempts()}`),A(this,Je).emit("reconnectAttempt",{attempt:A(this,Us).getAttempts()}),await this.connect(),!re(this,Rd,Lu).call(this))throw Error("Reconnect Failed");te(this,ls,!1),te(this,ri,{code:void 0,reason:void 0}),A(this,Je).emit("reconnected")}catch(t){A(this,Pe).debug("Failed to reconnect."),A(this,Je).emit("reconnectFailure",{attempt:A(this,Us).getAttempts()}),re(this,So,kd).call(this,!1)}},In=new WeakSet,vo=function(s){try{return A(this,ke).send(s),!0}catch(t){return A(this,Pe).error(t.message),!1}},Gd=new WeakSet,Oh=function(){this.config.disconnectOnPingTimeout&&(A(this,Pe).debug("Resetting ping timeout"),re(this,Dn,yo).call(this),te(this,wn,setTimeout(()=>{var s;A(this,Pe).debug("Disconnecting the socket due to ping timeout"),te(this,ur,!0);const t=3002,e="Ping timeout";(s=A(this,ke))==null||s.close(t,e),re(this,qd,Ih).call(this,t,e)},A(this,ce).pingTimeout)))},Dn=new WeakSet,yo=function(){A(this,wn)&&(clearTimeout(A(this,wn)),te(this,wn,void 0))},Nh=new WeakSet,fS=function(){re(this,Eo,bd).call(this),A(this,ce).clientInitiatedPings&&te(this,_n,setInterval(()=>{re(this,Rd,Lu).call(this)&&(A(this,Pe).debug("Sending client-initiated ping"),re(this,In,vo).call(this,zg))},A(this,ce).clientInitiatedPingInterval))},Eo=new WeakSet,bd=function(){A(this,_n)&&(clearInterval(A(this,_n)),te(this,_n,void 0))},Po=new WeakSet,Wd=function(){re(this,Eo,bd).call(this),A(this,ke)&&(A(this,ke).onopen=void 0,A(this,ke).onerror=void 0,A(this,ke).onmessage=void 0,A(this,ke).onclose=void 0)};function TS(s){return`${s.slice(0,10)}...${s.slice(-10)}`}function BO(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 a=fi.baseURI.prod;t&&(a=t);const o=`https://${Mf({servicePrefix:"api",baseURI:a})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:a,apiBase:o}}catch(e){throw new C("Invalid auth token","0004")}}var FO=Object.defineProperty,jO=Object.getOwnPropertyDescriptor,fu=(s,t,e,r)=>{for(var i=r>1?void 0:r?jO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&FO(t,e,i),i};const Qg=65535,qO=3,GO=15e3,WO=8e3,JO=50,KO=1e3,zO=1e4;var bs,ba,Ee,Ze,at,Yr,Qr,Xi,Zi,Xr,Ms,As,Zr,en,mt,ei,ft,Ve,Hc,Lh,Gl,vS,Wl,yS,Jl,ES,Bc,Vh,Fc,$h,tn,ho,Kl,Vu,PS,zl,wS,jc,xh,qc,Uh,Gc,Hh,Yl,_S,Wc,Bh,Jc,Fh;const SS=(Vu=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,Ze);g(this,Hc);g(this,Gl);g(this,Wl);g(this,Jl);g(this,Bc);g(this,Fc);g(this,tn);g(this,zl);g(this,jc);g(this,qc);g(this,Gc);g(this,Yl);g(this,Wc);g(this,Jc);g(this,bs,void 0);g(this,ba,void 0);g(this,Ee,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");g(this,Yr,[]);g(this,Qr,void 0);g(this,Xi,!1);g(this,Zi,void 0);g(this,Xr,void 0);g(this,Ms,void 0);g(this,As,void 0);g(this,Zr,void 0);g(this,en,void 0);g(this,mt,0);g(this,ei,void 0);g(this,ft,!0);g(this,Ve,void 0);if(!t||!e||!r)throw new C("peerId, meetingId, or authToken can not be empty","0404");m(this,Ve,s),m(this,As,navigator.isReactNative?jT:go),this.capabilities=i,this.roomName=e,this.authToken=r,m(this,bs,k(this,Hc,Lh).call(this,t)),m(this,ba,t);const a=i.includes("PING");m(this,Ee,new HO(n(this,bs),{autoReconnect:!1,disconnectOnPingTimeout:a,queueOnDisconnect:!1,flushOnReconnect:!1,logger:this.logger,clientInitiatedPings:!a,clientInitiatedPingInterval:15e3})),this.handleSocketConnectionEvents()}get joinAttempted(){return n(this,Ze,at).socketJoinAttempted}set joinAttempted(s){n(this,Ze,at).socketJoinAttempted=s}get telemetry(){return n(this,Ve).getValue("telemetry")}get logger(){return n(this,Ve).getValue("logger")}get peerId(){return n(this,Ve).getValue("peerId")}get supersededLocalPeerIds(){return n(this,Yr).filter(s=>s!==this.peerId)}updateCallstatsPeerId(s){const t=n(this,Ve).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;m(this,bs,k(this,Hc,Lh).call(this,s)),m(this,ba,s),n(this,Ve).getValue("telemetry").resetPeerId(s),(t=n(this,Ve).getValue("apiClient"))==null||t.setHeader("tracing-id",s),this.updateCallstatsPeerId(s),ii.remapContext(s,n(this,Ve)),this.logger.info(`Attempting websocket connection with URL: ${n(this,tn,ho)}`),n(this,Ee).updateURL(n(this,bs))}get url(){return n(this,bs)}async connect(){var t;const s=n(this,mt)+1;m(this,mt,s),k(this,jc,xh).call(this),m(this,ft,!0),k(this,Jl,ES).call(this);try{if(await n(this,Ee).connect(),!n(this,ft)||s!==n(this,mt))throw new Error("Socket connection was canceled");k(this,Fc,$h).call(this,this.peerId),(t=n(this,Ms))!=null||m(this,Ms,this.peerId),n(this,Ze,at).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}catch(e){throw this.logger.error(`Websocket connection failed with URL: ${n(this,tn,ho)}`,{error:e}),n(this,ft)&&s===n(this,mt)&&k(this,Gc,Hh).call(this,s),e}}disconnect(){m(this,mt,n(this,mt)+1),m(this,ft,!1),k(this,jc,xh).call(this),k(this,Bc,Vh).call(this),m(this,Ms,void 0),n(this,Ee).disconnect(),n(this,Ze,at).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return n(this,Ee).readyState===1}catch(s){return!1}}sendMessage(s,t,e){if(!n(this,Wc,Bh))return!1;const r={};return n(this,Ve).getValue("telemetry").injectContext(r),n(this,Ee).send(s,e!=null?e:k(this,Jc,Fh).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(!n(this,Wc,Bh))return Promise.reject(new Error("Socket is not connected for the current peer ID"));const a=i!=null?i:s;return new Promise((o,c)=>{let d;const l=(M,D)=>{d&&clearTimeout(d),n(this,Ee).removeListener(a,M),n(this,Ee).removeListener(Qg,D),n(this,Ee).removeListener(Ir.errorResponse,D),n(this,Ee).removeListener(us.errorResponse,D)},u=r!=null?r:k(this,Jc,Fh).call(this),h={};n(this,Ve).getValue("telemetry").injectContext(h);const S=({id:M,payload:D})=>{if(u===M){let I;try{const x=ok.fromBinary(D);I=new Error(x.errorMessage)}catch(x){I=new Error("failed to parse error message",{cause:x});try{const $=db.fromBinary(D);I=new Error($.message)}catch($){I=new Error("failed to parse error message",{cause:$})}}c(I),l(E,S)}},E=({id:M,payload:D})=>{u===M&&(o({id:M,payload:D}),l(E,S))};n(this,Ee).on(a,E),n(this,Ee).on(Qg,S),n(this,Ee).on(Ir.errorResponse,S),n(this,Ee).on(us.errorResponse,S),d=setTimeout(()=>{l(E,S),c(new Error(`request timeout for callback eventId:${s}`))},t),n(this,Ee).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){n(this,Ee).on(s,t)}onStateEvent(s,t){n(this,Ee).on(s,t)}removeListener(s,t){n(this,Ee).removeListener(s,t)}removeListeners(s){n(this,Ee).removeListeners(s)}flush(){return n(this,Ee).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{var s;this.logger.info(`Websocket connected with URL: ${n(this,tn,ho)}`),(s=n(this,Ms))!=null||m(this,Ms,this.peerId),n(this,Ze,at).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{!n(this,ft)||n(this,ei)===n(this,mt)||(this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}}),n(this,Ze,at).updateSocketConnectionState("disconnected"),n(this,Ve).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,Ze,at).joinAttempted}),k(this,Gc,Hh).call(this,n(this,mt)))})}},bs=new WeakMap,ba=new WeakMap,Ee=new WeakMap,Ze=new WeakSet,at=function(){return n(this,Ve).getValue("connectionHandler")},Yr=new WeakMap,Qr=new WeakMap,Xi=new WeakMap,Zi=new WeakMap,Xr=new WeakMap,Ms=new WeakMap,As=new WeakMap,Zr=new WeakMap,en=new WeakMap,mt=new WeakMap,ei=new WeakMap,ft=new WeakMap,Ve=new WeakMap,Hc=new WeakSet,Lh=function(s){let t=np({servicePrefix:"ws",baseURI:n(this,Ve).getValue("baseURI")});const e=Ao(n(this,Ve),"socket_server_base");if(typeof e=="string"){const a=/^(http|ws):\/\//i.test(e),o=e.replace(/^(https?|wss?):\/\//i,"").replace(/\/+$/,"");t=`${a?"ws":"wss"}://${o}/ws`}const r=new URL(t),i={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...n(this,Yr).length>0&&{oldPeerIds:n(this,Yr).join(",")},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(a=>Ld[a]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0,apiVersion:"23-09-2026"};return Object.entries(i).forEach(([a,o])=>{r.searchParams.append(a,o.toString())}),r.href},Gl=new WeakSet,vS=function(){if(!n(this,Ms))return;const s=new URL(n(this,bs));return s.protocol=s.protocol==="ws:"?"http:":"https:",s.pathname=`${s.pathname.replace(/\/+$/,"")}/ping`,s.search="",s.searchParams.set("peerId",n(this,Ms)),s.href},Wl=new WeakSet,yS=async function(){const s=k(this,Gl,vS).call(this);if(!s||n(this,Xi))return;const t={},e=typeof AbortController=="function"?new AbortController:void 0;let r;m(this,Xi,!0),m(this,Xr,t),m(this,Zi,e);try{e&&(r=n(this,As).setTimeout(()=>e.abort(),WO));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){n(this,Xr)===t&&this.logger.warn("SocketService::API ping request failed",{error:i,networkCall:{url:s}})}finally{r!==void 0&&n(this,As).clearTimeout(r),n(this,Xr)===t&&(m(this,Xi,!1),m(this,Xr,void 0),m(this,Zi,void 0))}},Jl=new WeakSet,ES=function(){n(this,Qr)===void 0&&m(this,Qr,n(this,As).setInterval(()=>k(this,Wl,yS).call(this),GO))},Bc=new WeakSet,Vh=function(){var s;n(this,Qr)!==void 0&&n(this,As).clearInterval(n(this,Qr)),(s=n(this,Zi))==null||s.abort(),m(this,Qr,void 0),m(this,Xi,!1),m(this,Xr,void 0),m(this,Zi,void 0)},Fc=new WeakSet,$h=function(s){m(this,Yr,[s,...n(this,Yr).filter(t=>t!==s)].slice(0,qO))},tn=new WeakSet,ho=function(){const s=new URL(n(this,bs)),t=s.searchParams.get("authToken");return t&&s.searchParams.set("authToken",TS(t)),s.href},Kl=new WeakSet,PS=function(s){const t=Math.min(zO,KO*2**(s-1));return Math.floor(Math.random()*(t+1))},zl=new WeakSet,wS=function(s){return new Promise(t=>{var e;m(this,en,t),m(this,Zr,n(this,As).setTimeout(()=>{m(this,Zr,void 0),m(this,en,void 0),t()},k(e=SS,Kl,PS).call(e,s)))})},jc=new WeakSet,xh=function(){var s;n(this,Zr)!==void 0&&(n(this,As).clearTimeout(n(this,Zr)),m(this,Zr,void 0)),(s=n(this,en))==null||s.call(this),m(this,en,void 0)},qc=new WeakSet,Uh=function(s,t){!n(this,ft)||s!==n(this,mt)||(t&&this.logger.error("SocketService::Reconnect loop failed",{error:t}),m(this,ft,!1),k(this,Bc,Vh).call(this),m(this,Ms,void 0),n(this,Ze,at).updateSocketConnectionState("failed"),n(this,Ve).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_FAILED))},Gc=new WeakSet,Hh=function(s){!n(this,ft)||n(this,ei)===s||(m(this,ei,s),n(this,Ze,at).updateSocketConnectionState("reconnecting"),k(this,Yl,_S).call(this,s).catch(t=>k(this,qc,Uh).call(this,s,t)))},Yl=new WeakSet,_S=async function(s){try{for(let t=1;t<=JO;t+=1){if(!n(this,ft)||s!==n(this,mt)||(await k(this,zl,wS).call(this,t),!n(this,ft)||s!==n(this,mt)))return;this.updateURL(pr.v4()),this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:t}}),n(this,Ze,at).updateSocketConnectionState("reconnectAttempt",t);try{if(await n(this,Ee).connect(!0),!n(this,ft)||s!==n(this,mt))return;if(!this.isConnected)throw new Error("Reconnect failed");k(this,Fc,$h).call(this,this.peerId),m(this,Ms,this.peerId),n(this,Ze,at).updateSocketConnectionState("reconnected"),n(this,Ve).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_RECONNECTED,{wasSocketJoinAttempted:n(this,Ze,at).socketJoinAttempted,wasMediaJoinAttempted:n(this,Ze,at).mediaJoinAttempted});return}catch(e){if(!n(this,ft)||s!==n(this,mt))return;this.logger.error(`Websocket connection retry attempt ${t} failed with URL: ${n(this,tn,ho)}`,{error:e,socket:{retryAttempt:t}}),n(this,Ze,at).updateSocketConnectionState("reconnectFailure",t)}}k(this,qc,Uh).call(this,s)}finally{n(this,ei)===s&&m(this,ei,void 0)}},Wc=new WeakSet,Bh=function(){return this.isConnected&&n(this,ba)===this.peerId},Jc=new WeakSet,Fh=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},g(Vu,Kl),Vu);let id=SS;fu([y.trace("SocketService.connect")],id.prototype,"connect",1);fu([y.trace("SocketService.disconnect")],id.prototype,"disconnect",1);fu([y.trace("SocketService.sendMessagePromise")],id.prototype,"sendMessagePromise",1);fu([y.trace("SocketService.sendMessagePromiseWithTimeout")],id.prototype,"sendMessagePromiseWithTimeout",1);class YO{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var a;const e=Vb.fromBinary(t),r=e.meetings.map(o=>{var c;return{id:o.id,title:o.title,participants:(c=o.participants)!=null?c:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(a=e.parentMeeting.participants)!=null?a:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=lM.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=qf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return qb.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title,error:r.error}))}handleConnectedRoomsDeletedRaw({payload:t}){return eM.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(L.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const e=await this.socketService.sendMessagePromise(L.createConnectedRooms,Hb.toBinary({payloads:t}));return this.handleConnectedRoomsUpdatedRaw(e)}async updateConnectedRooms(t){const e=await this.socketService.sendMessagePromise(L.updateConnectedRooms,Kb.toBinary({payloads:t}));return this.handleConnectedRoomsUpdatedRaw(e)}async disableConnectedRooms(t){const e=t.map(i=>({id:i})),r=await this.socketService.sendMessagePromise(L.deleteConnectedRooms,Xb.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(L.movePeers,aM.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 QO=Object.defineProperty,XO=Object.getOwnPropertyDescriptor,ZO=(s,t,e,r)=>{for(var i=r>1?void 0:r?XO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&QO(t,e,i),i},Nt;class CS extends xt{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);g(this,Nt,void 0);m(this,Nt,e)}get isActive(){return this.meetings.length!==0}validateAlterAction(){const e=n(this,Nt).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=n(this,Nt).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 a=n(this,Nt).getValue("userId");if(!(r.length===1&&r[0]===a))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 n(this,Nt).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 n(this,Nt).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)}`);const r=await n(this,Nt).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(o=>({meetingId:o.id,title:o.title})));this.logger.info(`Updated connected meetings ${JSON.stringify(r)}`);const i=new Set(r.filter(o=>!o.error).map(o=>o.id)),a=[...new Set(e.map(o=>o.id))].filter(o=>!i.has(o));if(a.length>0)throw new Error(`Could not update connected meetings: ${a.join(", ")}`)}async deleteMeetings(e){this.validateAlterAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(a=>e.includes(a.id)&&a.participants.length!==0?this.moveParticipants(a.id,this.parentMeeting.id,a.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),await Promise.all(r);const i=await n(this,Nt).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 a=await n(this,Nt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return a.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),a}async moveParticipantsWithCustomPreset(e,r,i){this.validateMoveAction(r,i.map(o=>o.id)),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const a=await n(this,Nt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return a.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),a}moveSuccessHandler(e,r,i){const a=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>a.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>a.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>a.get(d)));return{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}Nt=new WeakMap;ZO([Ut({maxInvocations:60,period:60})],CS.prototype,"getConnectedMeetings",1);var e1=Object.defineProperty,t1=Object.getOwnPropertyDescriptor,Cp=(s,t,e,r)=>{for(var i=r>1?void 0:r?t1(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&e1(t,e,i),i},pe,fm;const RS=(fm=class{constructor(s){p(this,"connectedMeetings");g(this,pe,void 0);m(this,pe,s),this.connectedMeetings=new CS(s)}get telemetry(){return n(this,pe).getValue("telemetry")}get logger(){return n(this,pe).getValue("logger")}static init(s){const t=new RS(s);return s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings()),t.setupEvents(),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){n(this,pe).getValue("connectedMeetingsSocketHandler").socketService.on(L.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),n(this,pe).getValue("connectedMeetingsSocketHandler").socketService.on(L.transferPeer,this.handleTransferPeer.bind(this)),n(this,pe).getValue("connectedMeetingsSocketHandler").socketService.on(L.movedPeer,this.handleMovedPeer.bind(this)),n(this,pe).getValue("connectedMeetingsSocketHandler").socketService.on(L.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),n(this,pe).getValue("connectedMeetingsSocketHandler").socketService.on(L.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=n(this,pe).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,a,o,c;this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:n(this,pe).getValue("self").videoEnabled,audio:n(this,pe).getValue("self").audioEnabled};try{n(this,pe).getValue("self").cleanupEvents(),await n(this,pe).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(a=(i=n(this,pe).getValue("meeting"))==null?void 0:i.meta)==null?void 0:a.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await bS.init({...n(this,pe).getValue("options"),cachedUserDetails:null,defaults:{...n(this,pe).getValue("options").defaults,...e,mediaHandler:n(this,pe).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=n(this,pe).getValue("self");r.self.setName(n(this,pe).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=n(this,pe).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return n(this,pe).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){var a;const t=n(this,pe).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s).filter(o=>!o.error),e=new Map(this.connectedMeetings.meetings.map(o=>[o.id,o]));t.forEach(o=>{var l;const{parentMeeting:c}=this.connectedMeetings;if(o.id===(c==null?void 0:c.id)){this.connectedMeetings.parentMeeting={...c,title:o.title};return}const d=e.get(o.id);e.set(o.id,{...d,id:o.id,title:o.title,participants:(l=d==null?void 0:d.participants)!=null?l:[]})}),this.connectedMeetings.meetings=Array.from(e.values());const r=(a=n(this,pe).getValue("meeting"))==null?void 0:a.meta,i=t.find(o=>o.id===(r==null?void 0:r.meetingId));r&&i&&i.title!==r.meetingTitle&&r[$d](i.title),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=n(this,pe).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},pe=new WeakMap,fm);let Tu=RS;Cp([y.trace("ConnectedMeetingsController.getConnectedMeetings")],Tu.prototype,"getConnectedMeetings",1);Cp([y.trace("ConnectedMeetingsController.setupEvents")],Tu.prototype,"setupEvents",1);Cp([y.trace("ConnectedMeetingsController.switchMeeting")],Tu.prototype,"switchMeeting",1);var s1=Object.defineProperty,r1=Object.getOwnPropertyDescriptor,Rp=(s,t,e,r)=>{for(var i=r>1?void 0:r?r1(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&s1(t,e,i),i};function i1(s){switch(s){case"participant_token_not_yet_valid":return"The participant authentication token is not valid yet.";case"participant_token_expired":return"The participant authentication token has expired.";case"participant_token_revoked":return"The participant authentication token has been revoked.";case"participant_token_invalid":return"The participant authentication token is invalid.";case"meeting_inactive":return"The meeting is inactive and is not accepting participants.";default:return"The participant authentication token may be invalid, expired, or not yet valid. Verify the token and its validity window."}}const po=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 x,$,B,z,Z;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:a,cachedUserDetails:o,logger:c}=s.getAllValues();if(gO(s),ye.isSupported()===!1)throw new C("Browser not supported","0010",c,!0);const d=n0(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(a),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new B0(s);s.setValue("connectionHandler",l);let u="",h=null;c.info("CF SFU is being used.");const f=po.createSocketService(s),S=f.connect();S.catch(()=>{});const E=d.getUserDetails();try{h=await E,u=((x=h.meeting)==null?void 0:x.title)||"",s.setValue("presetName",h.preset.name)}catch(U){if(c.error("Failed to get user details",{error:U}),f.disconnect(),U instanceof Vd){if(U.status===401||U.status===403){const Y=(z=(B=($=U.response)==null?void 0:$.data)==null?void 0:B.error)==null?void 0:z.reason;throw new C(i1(Y),"0004",void 0,!1,Y)}throw U.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")):U.status>=500?new C(`The server encountered an error. Try again. (${U.status})`,"0001"):U.isHttpError?new C(`Request rejected by the server. (${U.status})`,"0001"):U.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")}throw new C((U==null?void 0:U.message)||"Failed to initialize.","0001")}try{await S}catch(U){c.error("[Controller]: Failed to connect to socket server:",{error:U})}const R=dh.init(h.preset,!s.getValue("modules").theme);s.setValue("theme",R);const M=gh.init(s,R.viewType,h.preset.permissions),D=po.setupControllers(f,s,h,u,R,M);M0(R)&&((Z=po.createRoomNodeClient(s,f).initializeConnection(h.participant.name,i,!1,M))==null||Z.catch(Y=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:Y})}));const{controllers:I}=await D;return FC(),new po(e,I,s)}static async setupControllers(s,t,e,r,i,a){var ae,N,_;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:(ae=h.enableHighBitrate)!=null?ae:!1,enableStereo:(N=h.enableStereo)!=null?N:!1}},...d}),t.setValue("maxPreferredStreams",ye.isMobile()?i.maxVideoStreams.mobile:i.maxVideoStreams.desktop);let f,S,E,R,M,D,I,x,$;const B=new SO(t,s),z=new YO(s);t.setValue("connectedMeetingsSocketHandler",z);const Z=new gu(t,s),U=new vr(t,s),Y=new _O(s),ge=new sS(t,s),et=new CO(t,s),b=new TO(s),T=await di.init(t,ge,c,a,i);t.setValue("selfController",T);const P=await iT.init(t,T.self,ge,B,r);o.participant&&(x=await Pr.init(t,T.self,ge)),(_=o.e2ee)!=null&&_.enabled&&o.e2ee.manager.init(l,t.getValue("peerSessionStore")),o.chat&&(S=await To.init(t,U,T.self,x.participants)),o.internals&&(M=await pp.init(t)),o.livestream&&i.viewType===hs.Livestream&&(I=new mT(t,T.self,b)),o.poll&&(f=await tT.init(t,T.self,Z)),o.recording&&(D=new lT(t,T.self,ge)),o.stage&&(E=new nT(t,Y,ge,T.self,x.participants));const V=new OD(t,et);if(o.plugin){if(!x)throw new C("The plugin module cannot be initialized without the `participant` module","0102");const be=d.plugins||[];R=await dT.init(t,be,T.self,V)}if(o.connectedMeetings&&($=await Tu.init(t)),o.pip){const be=await qu._init(t,T.self);t.setValue("pip",be)}return{theme:i,permissions:a,controllers:{storesManager:V,pollController:f,selfController:T,metaController:P,chatController:S,stageController:E,pluginController:R,recordingController:D,internalsController:M,livestreamController:I,participantController:x,connectedMeetingsController:$}}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return eS(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=[];return new id(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Su=po;Rp([y.trace("Controller.init")],Su,"init",1);Rp([y.trace("Controller.createRoomNodeClient")],Su,"createRoomNodeClient",1);Rp([y.trace("Controller.createSocketService")],Su,"createSocketService",1);class n1{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 Xg=new n1;var ti,sn,rn,Kc,Ql,kS;class a1{constructor(){g(this,Ql);g(this,ti,new Audio);g(this,sn,new MediaStream);g(this,rn,new Map);g(this,Kc,void 0);n(this,ti).srcObject=n(this,sn),n(this,ti).autoplay=!0}async playTracks(t){return t.forEach(e=>{n(this,rn).has(e.id)||(n(this,sn).addTrack(e),n(this,rn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&n(this,ti).setSinkId(t)}removeTrack(t){const e=n(this,rn).get(t);e&&(n(this,sn).removeTrack(e),n(this,rn).delete(t))}async play(){return n(this,ti).srcObject=n(this,sn),n(this,ti).play().catch(t=>{k(this,Ql,kS).call(this,t)})}onError(t){m(this,Kc,t)}}ti=new WeakMap,sn=new WeakMap,rn=new WeakMap,Kc=new WeakMap,Ql=new WeakSet,kS=function(t){var e;(e=n(this,Kc))==null||e.call(this,t)};var Is;class o1 extends a1{constructor(){super();g(this,Is,void 0);m(this,Is,new Map)}addParticipantTrack(e,r){n(this,Is).set(e,r.id),this.playTracks([r])}reassignParticipantTrack(e,r){const i=n(this,Is).get(e);i&&(n(this,Is).delete(e),n(this,Is).set(r,i))}removeParticipantTrack(e){const r=n(this,Is).get(e);r&&this.removeTrack(r),n(this,Is).delete(e)}}Is=new WeakMap;var c1=Object.defineProperty,d1=Object.getOwnPropertyDescriptor,vu=(s,t,e,r)=>{for(var i=r>1?void 0:r?d1(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&c1(t,e,i),i},De,nn,Tm;let ni=(Tm=class{constructor(t,e){g(this,De,void 0);g(this,nn,void 0);m(this,nn,t),m(this,De,e)}get peerId(){return n(this,nn).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:pr.v4(),a=ii.createContext(i,{peerId:i}),o=a.getValue("logger");o.init(a);const c=new RT(a,o);return await c.init(t,e,a),a.setValue("defaults",{mediaHandler:c}),c}static async init(t){var f,S,E,R,M,D,I;ye.init();const e=(S=(f=t==null?void 0:t.cachedUserDetails)==null?void 0:f.peerId)!=null?S:pr.v4(),{authToken:r,baseURI:i}=t,{meetingId:a,...o}=BO(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=ni.setupContext(e,t,a,o),d=c.getValue("telemetry"),l=c.getValue("logger");LS(l),Xg.init(l),d.init(c,{roomName:a,userId:o.participantId,organizationId:o.orgId,peerId:e},(M=(R=t.modules)==null?void 0:R.tracing)!=null?M:!0,(I=(D=t==null?void 0:t.modules)==null?void 0:D.devTools)==null?void 0:I.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:TS(t.authToken)}});const u=await Su.init(c),h=new ni(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 a=ii.createContext(t,e),o={...vC,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return a.setValue("options",e),a.setValue("peerId",t),a.setValue("modules",o),a.setValue("sdkName","web-core"),a.setValue("meetingId",r),a.setValue("apiBase",i.apiBase),a.setValue("baseURI",i.baseURI),a.setValue("userId",i.participantId),a.setValue("organizationId",i.orgId),a.setValue("authToken",e.authToken),a.setValue("overrides",(d=e.overrides)!=null?d:{}),a.setValue("env",yC({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",Os(e.cachedUserDetails)),a.setValue("sdkVersion","2.1.0-staging.6"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new o1),a}async join(){const{selfController:t}=n(this,De);return t.self.roomJoined?null:t.joinRoom()}async leave(t){var r;Xg.cleanup(),n(this,nn).getValue("peerSessionStore").reset(),(r=n(this,De).pluginController)==null||r.cleanup();const{selfController:e}=n(this,De);return e.leaveRoom(t)}get participants(){var t;return(t=n(this,De).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,De).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,De).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,De).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,De).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,De).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,De).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,De).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,De).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,De).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,De).stageController)==null?void 0:t.stage}get stores(){return n(this,De).storesManager}get audio(){return n(this,nn).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,De).internalsController)==null?void 0:t.internals}},De=new WeakMap,nn=new WeakMap,Tm);vu([it("0002"),Er.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],ni.prototype,"join",1);vu([it("0003")],ni.prototype,"leave",1);vu([it("0001"),Er.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],ni,"init",1);ni=vu([it("0000")],ni);const bS=ni;module.exports=bS;
9
+ `}this.midTransceiverMap.set(a.mid,a);const c=async d=>(this.logger.debug(`[SDP] send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),await this.pc.setRemoteDescription(d),a.mid);return this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(o,void 0,2)}]`),{offerSdp:o,callback:c,sender:a.sender,mid:a.mid}}}class Fd extends vp{constructor(e,r){super(e);p(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new Fd(e,r)}get name(){return"Firefox60"}async send({track:e,encodings:r,codecOptions:i,screenShare:a}){this._assertSendDirection();const o=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(e,{direction:"sendonly",streams:[a?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 x;const S=rs.parse(h),E=S.media[S.media.length-1],R=E.rtp.filter($=>f.some(B=>B.name===$.codec)),M=E.fmtp.filter($=>R.some(B=>B.payload===$.payload)),D=(x=E.rtcpFb)==null?void 0:x.filter($=>R.some(B=>B.payload===$.payload)),I=R.map($=>$.payload);return S.media[S.media.length-1].rtp=R,S.media[S.media.length-1].fmtp=M,S.media[S.media.length-1].rtcpFb=D,S.media[S.media.length-1].payloads=I.join(" "),rs.write(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 a=i.sender.getParameters(),o=a.encodings.length-1-r;a.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),await i.sender.setParameters(a)}}class Ep extends vp{static createFactory(t){return()=>new Ep(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 a=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)}`),a.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(a.mid,a),{offerSdp:d,callback:async u=>(this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),await this.pc.setRemoteDescription(u),a.mid),sender:a.sender,mid:a.mid}}}function rO(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")}var Zs,Bi;class iO{constructor(t,{handlerName:e,handlerFactory:r}={}){p(this,"handlerFactory");g(this,Zs,void 0);g(this,Bi,void 0);const i=t.getValue("logger");if(i.debug("Device constructor() called."),m(this,Zs,t),m(this,Bi,i),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)n(this,Bi).debug(`Device::constructor() | handler given: ${e}`);else if(e=rO(n(this,Bi)),e)n(this,Bi).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=yp.createFactory(n(this,Zs));break;case"Safari12":this.handlerFactory=Ep.createFactory(n(this,Zs));break;case"Firefox60":this.handlerFactory=Fd.createFactory(n(this,Zs),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=Fd.createFactory(n(this,Zs),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=pr.v4();return new Sh(n(this,Zs),{id:e,...t,handlerFactory:this.handlerFactory})}}Zs=new WeakMap,Bi=new WeakMap;const nO=2e3;var ga,je,qe,uc,hc,Fi,ma,pc,fa,ji,Ps,ws,kr,gc,vh,Tl,MT,mc,yh,Sl,AT,vl,IT,yl,DT,El,OT,Pl,NT,fc,Eh,_s,br;class aO extends Tt.EventEmitter{constructor(e,r){super();g(this,ws);g(this,gc);g(this,Tl);g(this,mc);g(this,Sl);g(this,vl);g(this,yl);g(this,El);g(this,Pl);g(this,fc);g(this,_s);p(this,"context");g(this,ga,void 0);g(this,je,void 0);g(this,qe,void 0);g(this,uc,void 0);g(this,hc,void 0);g(this,Fi,void 0);g(this,ma,void 0);g(this,pc,void 0);g(this,fa,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});g(this,ji,void 0);g(this,Ps,"all");this.context=e,m(this,Fi,r),m(this,ga,new iO(e)),m(this,ma,new sO(r)),m(this,pc,us),n(this,ws,kr).mediaState={send:{state:Ft.NEW},recv:{state:Ft.NEW}},Ao(this.context,"forceRelay")&&m(this,Ps,"relay"),this.logger.info(`ICE Transport Policy initially set to ${n(this,Ps)}`),k(this,gc,vh).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return n(this,Fi)}get socketHandler(){return n(this,ma)}get sendTransport(){return n(this,je)}get recvTransport(){return n(this,qe)}get events(){return n(this,pc)}set sendTransportConnectedCallback(e){m(this,uc,e)}set recvTransportConnectedCallback(e){m(this,hc,e)}async setupTransports(e){await k(this,Tl,MT).call(this,e);let r,i;e.send&&(r=k(this,mc,yh).call(this,n(this,je)).then(a=>{try{n(this,uc).call(this,a)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=k(this,mc,yh).call(this,n(this,qe)).then(a=>{try{n(this,hc).call(this,a)}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:a,serverId:o,direction:c}=n(this,je);this.logger.info("Closing send transport",{transport:{id:a,serverId:o,type:c}}),n(this,je).close(),n(this,je).removeAllListeners(),m(this,je,void 0)}if(e.send&&(n(this,ws,kr).mediaState.send.state!==Ft.CLOSED||n(this,ws,kr).mediaState.send.sfuSessionId!==void 0)&&k(this,_s,br).call(this,{direction:"send",state:Ft.CLOSED}),e.recv&&this.recvTransport!==void 0){const{id:a,serverId:o,direction:c}=n(this,qe);this.logger.info("Closing recv transport",{transport:{id:a,serverId:o,type:c}}),(r=n(this,qe))==null||r.close(),(i=n(this,qe))==null||i.removeAllListeners(),m(this,qe,void 0)}e.recv&&(n(this,ws,kr).mediaState.recv.state!==Ft.CLOSED||n(this,ws,kr).mediaState.recv.sfuSessionId!==void 0)&&k(this,_s,br).call(this,{direction:"recv",state:Ft.CLOSED}),k(this,gc,vh).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}ga=new WeakMap,je=new WeakMap,qe=new WeakMap,uc=new WeakMap,hc=new WeakMap,Fi=new WeakMap,ma=new WeakMap,pc=new WeakMap,fa=new WeakMap,ji=new WeakMap,Ps=new WeakMap,ws=new WeakSet,kr=function(){return this.context.getValue("connectionHandler")},gc=new WeakSet,vh=function(){m(this,ji,{send:void 0,recv:void 0})},Tl=new WeakSet,MT=async function(e){var o,c,d,l,u,h,f,S;Ao(this.context,"forceRelay")&&m(this,Ps,"relay"),this.logger.info(`ICE Transport Policy set to ${n(this,Ps)}`);const a=await Lt().getICEServers().catch(E=>(this.logger.warn(`failed to get iceservers from server: ${E.message}`),[]));e.send&&k(this,vl,IT).call(this,{iceServers:a,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:n(this,Ps)}),e.recv&&k(this,yl,DT).call(this,{iceServers:a,additionalSettings:{encodedInsertableStreams:(S=this.context.getValue("modules").e2ee)==null?void 0:S.enabled},iceTransportPolicy:n(this,Ps)})},mc=new WeakSet,yh=async function(e){const{id:r,serverId:i,direction:a}=e;k(this,El,OT).call(this,e);try{return await Hd(async(c,d)=>{c>0&&this.logger.info(`Retrying ${a} transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:a}});try{if(e.closed)throw new Dr("Cannot reconnect closed transport");await k(this,Sl,AT).call(this,e)}catch(l){if(l instanceof Dr){this.logger.error(`Failed to connect ${a} transport. It will not be retried.`,{transport:e,error:l}),d(l);return}throw this.logger.error(`Failed to connect ${a} transport, retrying`,{transport:e,error:l}),l}},{delayTime:100,strategy:"exponential",maxRetryCount:15}),e}catch(o){throw this.logger.error(`Failed to connect ${a} transport after retries: ${e.id}. Transport reconnection will not be retried.`,{error:o,transport:{id:r,serverId:i,type:a}}),e.close(),e.removeAllListeners(),o}},Sl=new WeakSet,AT=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!n(this,Fi).isConnected)throw new Dr("Socket is not connected");if(e.connectionState==="closed")throw new Dr("Transport is closed");try{await e.connect(a=>k(this,Pl,NT).call(this,i,a)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(a){throw n(this,fa).transportFailureCount[i]+=1,a.message==="ice connection failed"?new Dr(a.message):a}},vl=new WeakSet,IT=function(e){var r,i;if(n(this,je)&&n(this,je).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=n(this,je))==null?void 0:r.id,serverId:(i=n(this,je))==null?void 0:i.serverId,type:"send"}});return}m(this,je,n(this,ga).createTransport({...e,direction:"send"})),k(this,_s,br).call(this,{state:Ft.NEW,direction:"send",sfuSessionId:n(this,je).serverId}),this.context.getValue("callstats").configureSendTransport(n(this,je))},yl=new WeakSet,DT=function(e){var r,i;if(n(this,qe)&&n(this,qe).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=n(this,qe))==null?void 0:r.id,serverId:(i=n(this,qe))==null?void 0:i.serverId,type:"recv"}});return}m(this,qe,n(this,ga).createTransport({...e,direction:"recv"})),k(this,_s,br).call(this,{state:Ft.NEW,direction:"recv",sfuSessionId:n(this,qe).serverId}),this.context.getValue("callstats").configureRecvTransport(n(this,qe))},El=new WeakSet,OT=function(e){const{direction:r,id:i}=e;e.on("serveridchange",a=>{k(this,_s,br).call(this,{state:e.connectionState,direction:r,sfuSessionId:a})}),e.on("connectionstatechange",async a=>{k(this,_s,br).call(this,{state:a,direction:r,sfuSessionId:e.serverId}),this.logger.info(`Transport connection state changed to ${a} for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:a}});const o=()=>{const c=n(this,ji)[r];c!==void 0&&(clearTimeout(c),n(this,ji)[r]=void 0)};switch(a){case"connected":o(),n(this,fa).lastConnectionTime=performance.now();break;case"disconnected":n(this,ji)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await k(this,fc,Eh).call(this,e.direction)},nO);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 k(this,fc,Eh).call(this,e.direction);break}}),e.on("icecandidate",async a=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:a})})},Pl=new WeakSet,NT=async function(e,r){const i=e==="recv";try{const{sdp:a,type:o}=r,c={consuming:i,description:{sdp:a,type:o,target:i?mr.SUBSCRIBER:mr.PUBLISHER},producers:[]};return n(this,ma).connectTransport(c)}catch(a){throw this.logger.error(`Error in ${e} transport connection:`,{error:a}),a}},fc=new WeakSet,Eh=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),n(this,Fi).isConnected&&n(this,fa).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),m(this,Ps,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:n(this,je)}),this.context.getValue("peerSessionStore").emit(w.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:n(this,qe)}),this.context.getValue("peerSessionStore").emit(w.UPDATE_ACTIVE);break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}const r=e==="send"?n(this,je):n(this,qe);k(this,_s,br).call(this,{state:Ft.CONNECTED,direction:e,sfuSessionId:r.serverId})},_s=new WeakSet,br=function(e){const{state:r,direction:i,sfuSessionId:a}=e;n(this,ws,kr).mediaState[i]={state:r,sfuSessionId:a},this.context.getValue("peerSessionStore").emit(w.TRANSPORT_STATE_UPDATE,{transport:i,...n(this,ws,kr).mediaState[i]})};var wl,Yt;class oO{constructor(t,e,r,i,a){g(this,wl,void 0);g(this,Yt,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=a,m(this,wl,t),m(this,Yt,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}),a=new Map;t.forEach(d=>a.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const u=a.get(d);if(!u)return;if(l.errorCode){n(this,Yt).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{n(this,Yt).info("Negotiating socket consumer",{transport:this.recvTransport}),n(this,Yt).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:mr.SUBSCRIBER}};return n(this,Yt).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,iR.toBinary(r)),n(this,Yt).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){n(this,Yt).error("Failed to renegotiate",{error:e});return}}async close(t){if(!t.length)return;const e=async(r,i)=>{const a=r.map(l=>l.localId);n(this,Yt).info(`Closing consumers: ${JSON.stringify(a)}`);const o={description:{sdp:i.sdp,type:i.type,target:mr.SUBSCRIBER},consumerIds:a,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=Ak.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(a=>a&&a.id);i.forEach(({id:a,producingTransportId:o,localId:c})=>{r.requests.push({producerId:a,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),await this.socketHandler.updateConsumersSimulcastConfig(r),n(this,Yt).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:a})=>a)})}}wl=new WeakMap,Yt=new WeakMap;class Pp{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return rs.parse(t).media.filter(a=>e==="video"?a.type==="video":a.type==="audio").at(-1).msid}async create({offer:t,kind:e,paused:r,appData:i,codecOptions:a,producingTransportId:o}){var h,f;const c=Pp.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:mr.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(h=i.screenShare)!=null?h:!1,mimeType:`${e}/${(f=a[0])==null?void 0:f.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}function cO(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{}}}var qi,Cs,Tc,Rs,_l,er,Ta,Sc,Ph,Cl,LT,Rl,VT,kl,$T,bl,xT;class dO extends aO{constructor(e,r){super(e,r);g(this,Sc);g(this,Cl);g(this,Rl);g(this,kl);g(this,bl);g(this,qi,void 0);g(this,Cs,void 0);g(this,Tc,void 0);g(this,Rs,void 0);g(this,_l,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});g(this,er,[]);g(this,Ta,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{m(this,Tc,new Pp(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{m(this,Rs,new oO(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return n(this,qi)}get consumers(){return n(this,Cs)}get logger(){return this.context.getValue("logger")}reset(){m(this,qi,new Map),m(this,Cs,new Map)}async createProducer(e,r){var i,a,o;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const c=await this.sendTransport.produce(e,k(this,Cl,LT).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_ACTIVE_PRODUCER,c),k(this,Rl,VT).call(this,c,r),this.logger.info(`Created ${(a=c.appData)!=null&&a.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}),n(this,_l).producerCreationFailureCount+=1,c}}async closeProducer(e,r){var a,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 ${(a=i.appData)!=null&&a.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(w.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(n(this,qi).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){n(this,Ta)||clearTimeout(n(this,Ta)),m(this,er,n(this,er).concat(e)),await k(this,Sc,Ph).call(this)}removeClosedConsumers(e){return e.filter(r=>{const i=n(this,Cs).get(r);return i!=null&&i.closed?(n(this,Cs).delete(r),!0):!1})}async closeConsumers(e){if(!n(this,Rs))return;const r=e.map(i=>this.consumers.get(i)).filter(i=>i!==void 0);r.length!==0&&await n(this,Rs).close(r)}closeAllConsumers(){return this.closeConsumers(Array.from(n(this,Cs).keys()))}async switchConsumersToLayer(e,r){n(this,Rs).switchConsumersToLayer(e,r)}}qi=new WeakMap,Cs=new WeakMap,Tc=new WeakMap,Rs=new WeakMap,_l=new WeakMap,er=new WeakMap,Ta=new WeakMap,Sc=new WeakSet,Ph=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=n(this,er).splice(0,n(this,er).length);try{const i=new Set(Array.from(this.consumers.values()).map(({producerId:d})=>d)),a=r.filter(({producerId:d})=>!this.producers.get(d)&&!i.has(d));if(a.length===0)return;const{consumers:o,failedProducers:c}=await this.recvTransport.consume(a,k(this,kl,$T).bind(this),n(this,Rs).negotiate.bind(n(this,Rs)));if(o.forEach(k(this,bl,xT).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);m(this,er,n(this,er).concat(d)),m(this,Ta,setTimeout(k(this,Sc,Ph).bind(this),e))}}catch(i){const a=i instanceof Error?i:new Error(String(i));this.logger.error("failed to consume on transport",{error:a});const{errorCode:o,errorDescription:c}=cO(a);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})}}},Cl=new WeakSet,LT=function(e){return n(this,Tc).create(e)},Rl=new WeakSet,VT=function(e,r){e.on("close",async(i,a)=>{const{reason:o}=i,{offer:c}=i;if(this.logger.info("producer::closing",{debuggingHint:o,producer:{...e,status:"closing"}}),o!==Bd){const d={producerId:e.id,description:{sdp:c.sdp,type:c.type,target:mr.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"}}),a({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"}})}),n(this,qi).set(e.id,e)},kl=new WeakSet,$T=async function(e){try{return await this.recvTransport.canConsume(),await n(this,Rs).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},bl=new WeakSet,xT=function(e){e.on("close",async r=>{this.logger.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),n(this,Cs).delete(e.id),this.context.getValue("peerSessionStore").emit(w.CONSUMER_CLOSED,{id:e.id})}),n(this,Cs).set(e.id,e),this.context.getValue("peerSessionStore").emit(w.NEW_CONSUMER_CREATED,{id:e.id,appData:e.appData,peerId:e.peerId})};var vc,yc,Ec,Sa,va,ya,Pc,wc,Ea,Pt,cs,ds,Gi,Wi,tr,_c,Ml,UT,Al,HT,Il,BT,Dl,FT;const Ol=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:a=.95,voiceAdaptationRate:o=.99,minEnergyThreshold:c=.005,maxEnergyThreshold:d=.2,energyRatioThreshold:l=1.5,noiseHistorySize:u=50}={}){g(this,Ml);g(this,Al);g(this,vc,void 0);g(this,yc,void 0);g(this,Ec,void 0);g(this,Sa,void 0);g(this,va,void 0);g(this,ya,void 0);g(this,Pc,void 0);g(this,wc,void 0);g(this,Ea,void 0);g(this,Pt,void 0);g(this,cs,void 0);g(this,ds,!1);g(this,Gi,0);g(this,Wi,0);g(this,tr,[]);g(this,_c,void 0);m(this,Sa,t),m(this,Pt,t),m(this,vc,e),m(this,yc,r),m(this,Ec,i),m(this,va,a),m(this,ya,o),m(this,Pc,c),m(this,wc,d),m(this,Ea,l),m(this,_c,u),m(this,cs,t/2)}get voiceDetected(){return n(this,ds)}processAudioChunk(t){var o,c;const e=k(o=Ol,Il,BT).call(o,t),r=k(c=Ol,Dl,FT).call(c,t);return k(this,Ml,UT).call(this,e),e/n(this,cs)>n(this,Ea)&&e>n(this,Pt)&&r>n(this,vc)?(m(this,Gi,n(this,Gi)+1),m(this,Wi,n(this,Ec)),n(this,Gi)>=n(this,yc)&&m(this,ds,!0)):(m(this,Gi,0),n(this,Wi)>0?m(this,Wi,n(this,Wi)-1):n(this,ds)&&m(this,ds,!1),n(this,ds)||k(this,Al,HT).call(this,e)),{energy:e,isVoice:n(this,ds)}}reset(){m(this,ds,!1),m(this,Gi,0),m(this,Wi,0),m(this,Pt,n(this,Sa)),m(this,cs,n(this,Sa)/2),m(this,tr,[])}getThresholdInfo(){return{currentEnergyThreshold:n(this,Pt),backgroundNoiseEnergy:n(this,cs),energyRatioThreshold:n(this,Ea)}}};let oo=Ol;vc=new WeakMap,yc=new WeakMap,Ec=new WeakMap,Sa=new WeakMap,va=new WeakMap,ya=new WeakMap,Pc=new WeakMap,wc=new WeakMap,Ea=new WeakMap,Pt=new WeakMap,cs=new WeakMap,ds=new WeakMap,Gi=new WeakMap,Wi=new WeakMap,tr=new WeakMap,_c=new WeakMap,Ml=new WeakSet,UT=function(t){n(this,ds)?m(this,Pt,n(this,ya)*n(this,Pt)+(1-n(this,ya))*t):m(this,Pt,n(this,va)*n(this,Pt)+(1-n(this,va))*n(this,cs)),m(this,Pt,Math.max(n(this,Pc),Math.min(n(this,wc),n(this,Pt))))},Al=new WeakSet,HT=function(t){if(t<n(this,Pt)*1.2)if(n(this,tr).push(t),n(this,tr).length>n(this,_c)&&n(this,tr).shift(),n(this,tr).length>=10){const e=[...n(this,tr)].sort((i,a)=>i-a),r=Math.floor(e.length/2);m(this,cs,e[r])}else m(this,cs,.95*n(this,cs)+.05*t)},Il=new WeakSet,BT=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Dl=new WeakSet,FT=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},g(oo,Il),g(oo,Dl);var Cc;class qg{constructor(t){p(this,"RNAudioSampleHandler");g(this,Cc,void 0);m(this,Cc,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 n(this,Cc).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()}}Cc=new WeakMap;var Rc;class Gg{constructor(t){p(this,"audioContext");p(this,"analyser");g(this,Rc,void 0);m(this,Rc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return n(this,Rc).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)}}Rc=new WeakMap;class jT{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 lO=60,uO=400;var sr,rr,ir,kc,Pa,wa,Kr,Ji,_a,Ki,nr,ks,bc,wh,Nl,qT,Mc,_h,Ac,Ch,Ll,GT;const wo=class{constructor(t,e){g(this,bc);g(this,Nl);g(this,Ac);g(this,sr,void 0);g(this,rr,void 0);g(this,ir,void 0);g(this,kc,void 0);g(this,Pa,void 0);g(this,wa,void 0);g(this,Kr,void 0);g(this,Ji,void 0);g(this,_a,void 0);g(this,Ki,void 0);g(this,nr,void 0);g(this,ks,void 0);this.reportRequest=e,m(this,Ki,t),m(this,wa,new oo);const{isReactNative:r}=navigator;m(this,nr,r?new qg(n(this,Ki)):new Gg(n(this,Ki))),m(this,ks,r?jT:go)}get logger(){return n(this,Ki).getValue("logger")}set producerId(t){m(this,ir,t)}set audioTrack(t){m(this,kc,t),n(this,nr)instanceof Gg&&(n(this,nr).audioTrack=t)}start(t=!1){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter of audio producer ${n(this,ir)}.`),n(this,sr)&&n(this,ks).clearInterval(n(this,sr)),m(this,sr,n(this,ks).setInterval(k(this,bc,wh).bind(this),lO)),n(this,rr)&&n(this,ks).clearInterval(n(this,rr)),m(this,rr,n(this,ks).setInterval(k(this,Ac,Ch).bind(this),uO)),t&&(k(this,bc,wh).call(this),k(this,Ac,Ch).call(this))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter of audio producer ${n(this,ir)}`),n(this,sr)&&(n(this,ks).clearInterval(n(this,sr)),m(this,sr,void 0)),n(this,rr)&&(n(this,ks).clearInterval(n(this,rr)),m(this,rr,void 0))}catch(t){}n(this,wa).reset(),n(this,nr)instanceof qg&&n(this,nr).stop()}};let co=wo;sr=new WeakMap,rr=new WeakMap,ir=new WeakMap,kc=new WeakMap,Pa=new WeakMap,wa=new WeakMap,Kr=new WeakMap,Ji=new WeakMap,_a=new WeakMap,Ki=new WeakMap,nr=new WeakMap,ks=new WeakMap,bc=new WeakSet,wh=function(){var i;if(!n(this,kc)||!n(this,ir))return;const{energy:t}=k(this,Nl,qT).call(this),e=k(i=wo,Mc,_h).call(i,t);let r=.9;n(this,_a)!==e&&n(this,_a)?r=.9:e?r=.3:r=.5,m(this,Pa,(n(this,Pa)||0)*(1-r)+t*r)},Nl=new WeakSet,qT=function(){var o;const{samples:t}=n(this,nr),{energy:e,isVoice:r}=n(this,wa).processAudioChunk(t),i=k(o=wo,Ll,GT).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!n(this,Kr)||i<n(this,Kr))&&m(this,Kr,i),(!n(this,Ji)||i>n(this,Ji))&&m(this,Ji,i),{energy:(i-n(this,Kr))/(n(this,Ji)-n(this,Kr))*10||0,isVoice:r})},Mc=new WeakSet,_h=function(t){return t<5},Ac=new WeakSet,Ch=function(t=n(this,Pa)){var r;if(!n(this,ir)||!t)return;const e={producerId:n(this,ir),energy:Math.round(t),silent:k(r=wo,Mc,_h).call(r,t)};m(this,_a,e.silent),this.reportRequest(e)},Ll=new WeakSet,GT=function(t){const e=Math.log10(t);return Math.round(e)},g(co,Mc),g(co,Ll);var hO=Object.defineProperty,pO=Object.getOwnPropertyDescriptor,ue=(s,t,e,r)=>{for(var i=r>1?void 0:r?pO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&hO(t,e,i),i},Ic,Dc,Ge,H,Vl,ht,ar,zi,Yi,Oc,Dt,or,pt,gt,cr,hi,Nc,Rh,$l,WT,xl,JT,Ul,KT,Lc,kh,Hl,zT,Bl,YT,Xe,nt,Qi,lo,Vc,bh,Fl,QT,jl,XT,ql,ZT;class ne{constructor(t,e){g(this,cr);g(this,Nc);g(this,$l);g(this,xl);g(this,Ul);g(this,Lc);g(this,Hl);g(this,Bl);g(this,Xe);g(this,Qi);g(this,Vc);g(this,Fl);g(this,jl);g(this,ql);p(this,"context");p(this,"authToken");p(this,"e2ee");g(this,Ic,void 0);g(this,Dc,void 0);g(this,Ge,void 0);g(this,H,void 0);g(this,Vl,void 0);g(this,ht,void 0);g(this,ar,void 0);g(this,zi,void 0);g(this,Yi,void 0);g(this,Oc,void 0);g(this,Dt,null);g(this,or,void 0);g(this,pt,void 0);g(this,gt,void 0);var i,a;this.context=t;const{socket:r}=e;this.mediaJoined=!1,m(this,Ge,r),m(this,ar,!1),m(this,H,new dO(t,r)),m(this,ht,n(this,H).events),m(this,or,new Set),m(this,pt,new Map),m(this,zi,!1),m(this,Yi,new fh(t.getValue("logger"))),m(this,gt,new co(this.context,n(this,H).socketHandler.audioActivity.bind(n(this,H).socketHandler))),this.e2ee=(a=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?a:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),m(this,Oc,ip(async()=>{if(!n(this,cr,hi).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(n(this,Dc),n(this,Ic),!0);o&&(this.context.getValue("peerSessionStore").emit(w.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return n(this,cr,hi).mediaJoined}set mediaJoined(t){n(this,cr,hi).mediaJoined=t}reset({resetTransportQueue:t}){this.logger.info(`Resetting media node client: closing all transports, producers, consumers, and queues(resetTransportQueue: ${t}).`),n(this,H).closeAllProducers(),n(this,H).closeAllConsumers(),n(this,pt).clear(),n(this,or).clear(),m(this,Dt,null),t&&n(this,Yi).stop(),n(this,H).stopAllTransports(),n(this,H).reset(),t&&m(this,Yi,new fh)}async joinRoom(t,e,r=!1,i={}){n(this,cr,hi).mediaJoinAttempted=!0,m(this,ar,!0);const a=this.peerId;try{const o=await n(this,Yi).push(()=>k(this,$l,WT).call(this,t,e,r,i),"joinRoom");return o.roomJoined||k(this,Nc,Rh).call(this,a),o}catch(o){return this.logger.error("Error in room joining process",{error:o}),k(this,Nc,Rh).call(this,a),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_FAILED),{roomJoined:!1,error:o}}}async initializeConnection(t,e,r=!1,i={}){return n(this,Dt)?n(this,Dt):(m(this,Dt,(async()=>{try{await k(this,Lc,kh).call(this,t,e,r,i)}catch(a){throw m(this,Dt,null),a}})()),n(this,Dt))}getConsumers(){return n(this,H).consumers}getProducers(){return n(this,H).producers}handoverPeerProducers(t,e){const r=new Set(e);return Array.from(n(this,H).consumers.values()).filter(i=>r.has(i.producerId)?(i.reassignPeer(t),!0):!1)}async leaveRoom(){var r;(r=n(this,gt))==null||r.stop(),n(this,H).stopAllTransports(),m(this,zi,!1),n(this,cr,hi).mediaJoinAttempted=!1;const t={closeRoom:!1};try{n(this,Ge).sendMessage(n(this,ht).leaveRoom,MR.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():n(this,H).createConsumers(t)}removeClosedConsumers(t){return n(this,H).removeClosedConsumers(t)}async closeConsumersById(t){t.length&&await n(this,H).closeConsumers(t)}async _shareWebcam(t){var u,h,f,S;const e=Te.WEBCAM,r=k(this,Xe,nt).call(this,e);if(r){const E=await r;if(n(this,H).producers.has(E)){const R=n(this,H).producers.get(E);if(!R.closed)return await R.replaceTrack({track:t}),await this.resumeWebcam(e),t;await this.disableWebcam()}return this._shareWebcam(t)}const i=k(this,ql,ZT).call(this,t),a=Ao(this.context,"disableSimulcast"),o=(h=(u=this.context)==null?void 0:u.getValue("overrides"))==null?void 0:h.simulcastConfig;a||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=tD(this.context,t),this.logger.info(`Simulcast encodings: ${JSON.stringify(i.encodings)}`));const d=()=>{this.logger.info("Disabling video due to the producer closure"),n(this,pt).delete(e)},l=n(this,H).createProducer(i,d);return k(this,Qi,lo).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 k(this,Xe,nt).call(this,Te.SCREENSHARE_VIDEO),a=await k(this,Xe,nt).call(this,Te.SCREENSHARE_AUDIO),o=n(this,H).producers.get(i),c=n(this,H).producers.get(a),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:ye.isElectron()},stopTracks:!1},u=()=>{this.logger.info("Disabling screenShare due to the producer closure"),n(this,pt).delete(Te.SCREENSHARE_VIDEO),n(this,pt).delete(Te.SCREENSHARE_AUDIO)},h=n(this,H).createProducer(l,u);k(this,Qi,lo).call(this,Te.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:ye.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},u=()=>{},h=n(this,H).createProducer(l,u);k(this,Qi,lo).call(this,Te.SCREENSHARE_AUDIO,h.then(f=>f.id)),d.push(h)}else a&&(k(this,Vc,bh).call(this,Te.SCREENSHARE_AUDIO),d.push(n(this,H).closeProducer(a)));await Promise.all(d),this.context.getValue("callstats").screenShareStart()}async shareMic(t){try{if(t===void 0)throw new _t("track undefined");const e=k(this,Xe,nt).call(this,Te.MIC);if(e){const o=await e;if(n(this,H).producers.has(o)){const c=n(this,H).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),n(this,gt)&&(n(this,gt).audioTrack=t,n(this,gt).producerId=o,n(this,gt).start(!0));return}await n(this,H).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=k(this,jl,XT).call(this,t),i=()=>{n(this,pt).delete(Te.MIC)},a=n(this,H).createProducer(r,i);k(this,Qi,lo).call(this,Te.MIC,a.then(o=>o.id)),await a.then(o=>{n(this,gt)&&(n(this,gt).audioTrack=o.track,n(this,gt).producerId=o.id,n(this,gt).start())})}catch(e){throw new C(e)}}async pauseMic(){var i;const t=await k(this,Xe,nt).call(this,Te.MIC),e=n(this,H).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=n(this,gt))==null||i.stop();const r={producerId:e.id,pause:!0};n(this,Ge).sendMessage(n(this,ht).toggleProducer,cd.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 k(this,Xe,nt).call(this,Te.WEBCAM),e=n(this,H).producers.get(t);if(!e){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}e.pause();const r={producerId:e.id,pause:!0};n(this,Ge).sendMessage(n(this,ht).toggleProducer,cd.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 k(this,Xe,nt).call(this,Te.MIC),e=n(this,H).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(w.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};n(this,Ge).sendMessage(n(this,ht).toggleProducer,cd.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=Te.WEBCAM){const e=await k(this,Xe,nt).call(this,t),r=n(this,H).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(w.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};n(this,Ge).sendMessage(n(this,ht).toggleProducer,cd.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=Te.WEBCAM,e=await k(this,Xe,nt).call(this,t);k(this,Vc,bh).call(this,t),e&&await n(this,H).closeProducer(e)}async disableMic(){var e;const t=await k(this,Xe,nt).call(this,Te.MIC);t&&await n(this,H).closeProducer(t),(e=n(this,gt))==null||e.stop(),n(this,pt).delete(Te.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await k(this,Xe,nt).call(this,Te.SCREENSHARE_VIDEO),e=await k(this,Xe,nt).call(this,Te.SCREENSHARE_AUDIO);t&&await n(this,H).closeProducer(t),e&&await n(this,H).closeProducer(e),n(this,or).clear(),n(this,pt).delete(Te.SCREENSHARE_VIDEO),n(this,pt).delete(Te.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await k(this,Xe,nt).call(this,Te.WEBCAM);await n(this,H).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await k(this,Xe,nt).call(this,Te.SCREENSHARE_VIDEO);await n(this,H).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:e})}}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await n(this,H).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};n(this,H).socketHandler.kickPeer(e)}kickAll(){n(this,H).socketHandler.kickAll()}async muteAll(t){if(!await n(this,H).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await n(this,H).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await n(this,H).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await n(this,H).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 n(this,Ge).sendMessagePromise(n(this,ht).globalPinPeer,jR.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&n(this,H).producers.get(t.producerId)&&n(this,or).add(t.consumerPeerId),n(this,or).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));n(this,H).switchConsumersToLayer(r,e)}async handleSocketEvents(){n(this,Ge).on(n(this,ht).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{k(this,Fl,QT).call(this,Wk.fromBinary(t))}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),n(this,Ge).on(n(this,ht).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const e=Pg.fromBinary(t),{participantId:r,initiatorParticipantId:i,producerState:{kind:a,pause:o,producerId:c,screenShare:d}}=e;if(d)return;const l=a===Ds.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: ${Pg.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"?w.MUTE_SELF:w.MUTE_SELF_VIDEO)),r===this.peerId)return;this.context.getValue("peerSessionStore").emit(w.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(w.CONSUMER_PAUSED,{id:h.id})):(h.resume(),this.context.getValue("peerSessionStore").emit(w.CONSUMER_RESUMED,{id:h.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),n(this,Ge).on(n(this,ht).peerLeaveBroadcast,async({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=Ju.fromBinary(t);if(e===this.peerId)return;this.logger.info(`Received peer left broadcast of remote peer ${e}`),n(this,or).delete(e),this.context.getValue("peerSessionStore").emit(w.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast of remote peer",{error:e})}}),n(this,Ge).on(n(this,ht).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=zk.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(w.PRODUCER_CLOSED,{peerId:e,producerId:r})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),n(this,Ge).on(n(this,ht).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!n(this,ar)&&!n(this,zi)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_DISCONNECTED),n(this,Oc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=n(this,H).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(w.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(n(this,H).producers.values()).find(a=>a.id===r);i&&this.context.getValue("peerSessionStore").emit(w.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}}Ic=new WeakMap,Dc=new WeakMap,Ge=new WeakMap,H=new WeakMap,Vl=new WeakMap,ht=new WeakMap,ar=new WeakMap,zi=new WeakMap,Yi=new WeakMap,Oc=new WeakMap,Dt=new WeakMap,or=new WeakMap,pt=new WeakMap,gt=new WeakMap,cr=new WeakSet,hi=function(){return this.context.getValue("connectionHandler")},Nc=new WeakSet,Rh=function(t){this.mediaJoined=!1,m(this,ar,!1),n(this,Ge).isConnected&&this.peerId===t&&this.context.getValue("peerSessionStore").emit(w.MEDIA_ROOM_JOIN_FAILED)},$l=new WeakSet,WT=async function(t,e,r,i){var o;m(this,Dc,t);let a=!1;if(r){const{recv:c,send:d}=(o=n(this,cr,hi).mediaState)!=null?o:{};(d==null?void 0:d.state)===Ft.CONNECTED&&(c==null?void 0:c.state)===Ft.CONNECTED?(this.logger.info("MediaNodeClient.joinRoom: transports healthy — preserving all producers for ownership handover"),m(this,Dt,null),a=!0):(this.logger.info("MediaNodeClient.joinRoom: transports unhealthy — full reset"),this.reset({resetTransportQueue:!1}))}try{n(this,Dt)?await n(this,Dt):await k(this,Lc,kh).call(this,t,e,r,i,a),k(this,Ul,KT).call(this,e);const{joined:c,error:d}=await k(this,xl,JT).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{m(this,Dt,null)}},xl=new WeakSet,JT=async function(){const t=this.peerId;try{this.mediaJoined=!0;const{roomState:e}=await Hd(async(r,i)=>{if(!n(this,Ge).isConnected||this.peerId!==t){const a=new Error("Media room join completion superseded by a newer connection");throw i(a),a}return r>0&&this.logger.warn(`Retrying media room join completion for peer ${t}: attempt=${r+1}`),n(this,H).socketHandler.notifySelfJoinComplete()},{strategy:"exponential",maxRetryCount:3,delayTime:1e3});return m(this,Ic,e.roomUuid),m(this,zi,!0),m(this,ar,!1),{joined:!0}}catch(e){return this.logger.error("Error completing room join",{error:e}),this.mediaJoined=!1,m(this,ar,!1),{joined:!1,error:e}}},Ul=new WeakSet,KT=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...ye.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)},Lc=new WeakSet,kh=async function(t,e,r,i,a=!1){try{const o=k(this,Hl,zT).call(this);await k(this,Bl,YT).call(this,t,e,r,o),a?this.logger.info("MediaNodeClient: reusing existing transports on rejoin"):await n(this,H).setupTransports({send:!0,recv:!0})}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},Hl=new WeakSet,zT=function(){const t=QD("video/VP8");return m(this,Vl,t),t},Bl=new WeakSet,YT=async function(t,e,r,i){await Hd(async(a,o)=>{if(!n(this,Ge).isConnected){o(new Error("Socket is not connected"));return}a>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${a}`});try{await n(this,H).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})},Xe=new WeakSet,nt=function(t){return n(this,pt).get(t)},Qi=new WeakSet,lo=function(t,e){return n(this,pt).set(t,e)},Vc=new WeakSet,bh=function(t){return n(this,pt).delete(t)},Fl=new WeakSet,QT=function({participantId:t,producerState:e}){var i;if(t===this.peerId||!e)return;this.logger.info(`Received remote ${e.screenShare?"screenshare":"participant"} ${e.kind===Ds.AUDIO?"audio":"video"} producer created broadcast for peer ${t} with producer state ${JSON.stringify(e)}.`);const r=(i=e.mimeType)!=null?i:e.kind===Ds.AUDIO?"audio/opus":"video/VP8";this.context.getValue("peerSessionStore").emit(w.NEW_PRODUCER,{peerId:t,producer:{...e,mimeType:r,kind:e.kind===Ds.AUDIO?"audio":"video",producingPeerId:t}})},jl=new WeakSet,XT=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},ql=new WeakSet,ZT=function(t){return{track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}};ue([y.trace("MediaNodeClient.reset")],ne.prototype,"reset",1);ue([y.trace("MediaNodeClient.joinRoom")],ne.prototype,"joinRoom",1);ue([y.trace("MediaNodeClient.leaveRoom")],ne.prototype,"leaveRoom",1);ue([y.trace("MediaNodeClient.activatePeers")],ne.prototype,"activatePeers",1);ue([y.trace("MediaNodeClient.createConsumers")],ne.prototype,"createConsumers",1);ue([y.trace("MediaNodeClient.closeConsumersById")],ne.prototype,"closeConsumersById",1);ue([y.trace("MediaNodeClient._shareWebcam")],ne.prototype,"_shareWebcam",1);ue([y.trace("MediaNodeClient.shareWebcam")],ne.prototype,"shareWebcam",1);ue([y.trace("MediaNodeClient.shareScreen")],ne.prototype,"shareScreen",1);ue([y.trace("MediaNodeClient.shareMic")],ne.prototype,"shareMic",1);ue([y.trace("MediaNodeClient.pauseMic")],ne.prototype,"pauseMic",1);ue([y.trace("MediaNodeClient.pauseWebcam")],ne.prototype,"pauseWebcam",1);ue([y.trace("MediaNodeClient.resumeMic")],ne.prototype,"resumeMic",1);ue([y.trace("MediaNodeClient.resumeWebcam")],ne.prototype,"resumeWebcam",1);ue([y.trace("MediaNodeClient.disableWebcam")],ne.prototype,"disableWebcam",1);ue([y.trace("MediaNodeClient.disableMic")],ne.prototype,"disableMic",1);ue([y.trace("MediaNodeClient.disableScreenShare")],ne.prototype,"disableScreenShare",1);ue([y.trace("MediaNodeClient.muteSelf")],ne.prototype,"muteSelf",1);ue([y.trace("MediaNodeClient.resetVideoProducers")],ne.prototype,"resetVideoProducers",1);ue([y.trace("MediaNodeClient.changeDisplayName")],ne.prototype,"changeDisplayName",1);ue([y.trace("MediaNodeClient.kickPeer")],ne.prototype,"kick",1);ue([y.trace("MediaNodeClient.kickAllPeers")],ne.prototype,"kickAll",1);ue([y.trace("MediaNodeClient.muteAll")],ne.prototype,"muteAll",1);ue([y.trace("MediaNodeClient.muteAllVideo")],ne.prototype,"muteAllVideo",1);ue([y.trace("MediaNodeClient.disableAudio")],ne.prototype,"disableAudio",1);ue([y.trace("MediaNodeClient.disableVideo")],ne.prototype,"disableVideo",1);ue([y.trace("MediaNodeClient.pinPeer")],ne.prototype,"pinPeer",1);ue([y.trace("MediaNodeClient.validateScreenShare")],ne.prototype,"validateScreenShare",1);function eS(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 ne(s,t);return s.setValue("roomNodeClient",r),r}function gO(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 mO=Object.defineProperty,fO=Object.getOwnPropertyDescriptor,fn=(s,t,e,r)=>{for(var i=r>1?void 0:r?fO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&mO(t,e,i),i},Ca,Qt,Q,rt,vt,mm;const tS=(mm=class{constructor(s,t,e,r){g(this,rt);p(this,"self");p(this,"authToken");g(this,Ca,void 0);p(this,"viewType");g(this,Qt,void 0);g(this,Q,void 0);const{socket:i}=e,a=s.getValue("authToken");this.self=t,m(this,Q,s),this.viewType=r,this.authToken=a,m(this,Ca,i),m(this,Qt,e),this.setupEvents()}get peerId(){return n(this,Q).getValue("peerId")}get telemetry(){return n(this,Q).getValue("telemetry")}get logger(){return n(this,Q).getValue("logger")}get mediaJoined(){return n(this,Q).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const a=Lt(),o=!!s.getValue("cachedUserDetails"),c=await Ke.__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:ye.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:await a.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:d,apiHostnames:EC(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 tS(s,c,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:a,screenShareTracks:o}=this.self;if(e.canProduceAudio===j.Allowed&&r)if((s==null?void 0:s.readyState)==="live")try{await n(this,rt,vt).shareMic(s),this.self.audioEnabled||n(this,rt,vt).pauseMic()}catch(d){this.self.disableAudio()}else this.logger.warn("shareMediaTracks: audio track is dead, disabling audio"),this.self.disableAudio();if(e.canProduceVideo===j.Allowed&&i)if((t==null?void 0:t.readyState)==="live")try{await n(this,rt,vt).shareWebcam(t),this.self.videoEnabled||n(this,rt,vt).pauseWebcam()}catch(d){this.self.disableVideo()}else this.logger.warn("shareMediaTracks: video track is dead, disabling video"),this.self.disableVideo();if(e.canProduceScreenshare===j.Allowed&&a){const d=o.video,l=o.audio;if((d==null?void 0:d.readyState)==="live")try{await((c=n(this,rt,vt))==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;n(this,Q).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=n(this,rt,vt))==null||r.reset({resetTransportQueue:!0}))}setupEvents(){n(this,Q).getValue("peerSessionStore").on(w.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&await this.shareMediaTracks()}),n(this,Q).getValue("peerSessionStore").on(w.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),n(this,Q).getValue("peerSessionStore").on(w.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),n(this,Q).getValue("peerSessionStore").on(w.ROOM_NODE_FAILED,()=>{this.logger.error("Room node failed. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,Q).getValue("peerSessionStore").on(w.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})})}),n(this,Q).getValue("peerSessionStore").on(w.SOCKET_SERVICE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),n(this,Q).getValue("peerSessionStore").on(w.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"})}),n(this,Qt).on(L.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),n(this,Qt).on(Sd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&n(this,Q).getValue("peerSessionStore").emit(w.UPDATE_PERMISSIONS,t.patch)})}),n(this,Qt).on(L.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),n(this,Qt).on(L.kick,()=>{this.kickHandler({kickType:"kick"})}),n(this,Qt).on(L.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),n(this,Q).getValue("peerSessionStore").onAsync(w.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),n(this,Q).getValue("peerSessionStore").on(w.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var a;const i=(a=e==null?void 0:e.screenShare)!=null?a:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),n(this,Q).getValue("peerSessionStore").on(w.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),n(this,Q).getValue("callstats").audioOff())}),n(this,Q).getValue("peerSessionStore").on(w.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),n(this,Q).getValue("callstats").videoOff())}),n(this,Q).getValue("peerSessionStore").onAsync(w.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),n(this,Q).getValue("peerSessionStore").on(w.PIP_HANGUP,this.leaveRoom.bind(this))}async joinSocketRoomWithRetry(){const s=this.self.id;return Hd(async(t,e)=>{if(!n(this,Ca).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 n(this,Qt).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."),n(this,Qt).socket.flush();const a=lp(i.stageType);if(n(this,Q).setValue("stageStatus",a,!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=n(this,rt,vt))==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===hs.Livestream&&(t!=null&&t.wasSocketJoinAttempted)&&!t.wasMediaJoinAttempted&&n(this,Q).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=n(this,rt,vt))==null||r.reset({resetTransportQueue:!0}),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s}),n(this,Q).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."),n(this,Q).notify("stageStatus")}catch(i){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:i}),i instanceof Dr&&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),n(this,Q).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),n(this,Q).setValue("roomNodeClient",void 0),n(this,Q).notify("stageStatus"),n(this,Q).getValue("connectionHandler").socketJoined)try{n(this,Qt).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=n(this,Q).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 a,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=n(this,Q).getAllValues();try{if(e===hs.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}eS(n(this,Q),{socket:n(this,Ca),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:h}=(o=await((a=n(this,rt,vt))==null?void 0:a.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=n(this,Q).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===hs.Webinar)&&n(this,rt,vt)&&(n(this,rt,vt).mediaJoined&&s!=="disconnected"&&await n(this,rt,vt).leaveRoom(),!(s==="stageLeft"&&t===hs.Livestream)&&(n(this,rt,vt).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()}},Ca=new WeakMap,Qt=new WeakMap,Q=new WeakMap,rt=new WeakSet,vt=function(){return n(this,Q).getValue("roomNodeClient")},mm);let di=tS;fn([y.trace("SelfController.resetSelf")],di.prototype,"resetSelf",1);fn([y.trace("SelfController.setupEvents")],di.prototype,"setupEvents",1);fn([y.trace("SelfController.joinRoom")],di.prototype,"joinRoom",1);fn([y.trace("SelfController.leaveRoom")],di.prototype,"leaveRoom",1);fn([y.trace("SelfController.joinMediaRoom")],di.prototype,"joinMediaRoom",1);fn([y.trace("SelfController.leaveMediaRoom")],di.prototype,"leaveMediaRoom",1);fn([y.trace("SelfController.init")],di,"init",1);var $c;class TO{constructor(t){g(this,$c,void 0);m(this,$c,t)}on(t,e){let r;t===L.roomPeerCount?r=Cg.fromBinary.bind(Cg):r=Dg.fromBinary.bind(Dg),n(this,$c).on(t,({payload:i})=>{if(t===L.roomPeerCount&&!i)return;const a=r(i);e(a)})}}$c=new WeakMap;var xc,Uc;class SO{constructor(t,e){g(this,xc,void 0);g(this,Uc,void 0);m(this,xc,e),m(this,Uc,t)}get logger(){return n(this,Uc).getValue("logger")}on(t,e){let r,i;switch(t){case L.transcript:{r=Ru.fromBinary.bind(Ru),i=Ru.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}n(this,xc).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}xc=new WeakMap,Uc=new WeakMap;var vO=Object.defineProperty,yO=Object.getOwnPropertyDescriptor,wp=(s,t,e,r)=>{for(var i=r>1?void 0:r?yO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&vO(t,e,i),i},dr,Ra;class gu{constructor(t,e){g(this,dr,void 0);g(this,Ra,void 0);m(this,dr,e),m(this,Ra,t)}get logger(){return n(this,Ra).getValue("logger")}get telemetry(){return n(this,Ra).getValue("telemetry")}getPolls(){return n(this,dr).sendMessagePromise(Bs.getPolls)}createPoll(t,e,r=!1,i=!1){const a={anonymous:r,hideVotes:i,question:t,options:e};return n(this,dr).sendMessage(Bs.createPoll,bI.toBinary(a))}votePoll(t,e){const r={index:e,pollId:t};return n(this,dr).sendMessage(Bs.votePoll,AI.toBinary(r))}on(t,e){let r,i;switch(t){case Bs.updatePoll:case Bs.createPoll:case Bs.votePoll:{r=Du.fromBinary.bind(Du),i=Du.create();break}}n(this,dr).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){n(this,dr).removeListeners(t)}}dr=new WeakMap,Ra=new WeakMap;wp([y.trace("PollSocketHandler.getPolls")],gu.prototype,"getPolls",1);wp([y.trace("PollSocketHandler.createPoll")],gu.prototype,"createPoll",1);wp([y.trace("PollSocketHandler.votePoll")],gu.prototype,"votePoll",1);var EO=Object.defineProperty,PO=Object.getOwnPropertyDescriptor,wO=(s,t,e,r)=>{for(var i=r>1?void 0:r?PO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&EO(t,e,i),i},Ot;class sS{constructor(t,e){p(this,"socket");g(this,Ot,void 0);m(this,Ot,t),this.socket=e,this.handleSocketEvents(),n(this,Ot).setValue("roomSocketHandler",this)}get telemetry(){return n(this,Ot).getValue("telemetry")}get logger(){return n(this,Ot).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}async joinRoom(t){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(L.joinRoom,Rb.toBinary(e));try{const{peer:a}=Sn.fromBinary((await r).payload);n(this,Ot).getValue("connectionHandler").socketJoined=!0,n(this,Ot).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_ROOM_JOINED,{peer:a});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return n(this,Ot).getValue("peerSessionStore").emit(w.ROOM_STATE,d),n(this,Ot).getValue("peerSessionStore").emit(w.SOCKET_PEERS,l),{peer:a}}catch(a){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:a}),a}}async getAllAddedParticipants(){try{return hM.fromBinary((await this.socket.sendMessagePromise(L.getAllAddedParticipants)).payload).participants.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}async getRoomPeers(t,e,r){let i;try{const a={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise(L.getRoomPeersInfo,fb.toBinary(a));i=ku.fromBinary(o.payload)}catch(a){this.logger.error("getRoomPeers::binary_decode_error",{error:a})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise(L.getRoomPeersInfo);t=ku.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getStagePeers(){let t;try{const e=await this.socket.sendMessagePromise(L.getRoomPeersInfo);t=ku.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getPeerInfo(t){let e;try{const r=await this.socket.sendMessagePromise(L.getPeerInfo,jf.toBinary({peerId:t}));e=Sn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=Rg.create();try{const e=await this.socket.sendMessagePromise(L.getRoomInfo);t=Rg.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=Mg.create();try{const e=await this.socket.sendMessagePromise(L.getRoomStageState);t=Mg.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t}updateRoomTitle(t){return this.socket.sendMessagePromise(L.updateRoomInfo,dd.toBinary(dd.create({room:{title:t}})))}async broadcastMessage(t,e){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(L.broadcastMessage,Za.toBinary(r))}async broadcastToMeetings(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(L.broadcastToEntity,Za.toBinary(i))}async broadcastToPeers(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(L.broadcastToEntity,Za.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(L.leaveRoom,bb.toBinary(e))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(L.kick,Gf.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(L.kickAll,Hf.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(L.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(L.acceptWaitingRoomRequests,SM.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(L.denyWaitingRoomRequests,yM.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Sd.updateUserPreset,zM.toBinary(r))}handleSocketEvents(){this.socket.on(L.broadcastMessage,({payload:t})=>{try{const e=Za.fromBinary(t);n(this,Ot).getValue("peerSessionStore").emit(w.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on(L.broadcastToEntity,({payload:t})=>{try{const e=Za.fromBinary(t);n(this,Ot).getValue("peerSessionStore").emit(w.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case L.joinRoom:case L.leaveRoom:case L.kick:case L.kickAll:{r=Sn.fromBinary.bind(Sn),i=Sn.create();break}case L.getWaitingRoomRequests:{r=(a,o)=>a?bg.fromBinary(a,o):{requests:[]},i=bg.create();break}case L.recordingPaused:case L.recordingStarted:case L.recordingStopped:{r=Lg.fromBinary.bind(Lg);break}case Sd.updateUserPreset:{r=Ag.fromBinary.bind(Ag);break}case us.peerJoinedBroadcast:case Ir.peerJoinedBroadcast:{r=yg.fromBinary.bind(yg);break}case us.selfJoinComplete:case Ir.selfJoinComplete:{r=Wu.fromBinary.bind(Wu);break}case us.globalPeerPinBroadcast:case Ir.globalPeerPinBroadcast:{r=wg.fromBinary.bind(wg);break}case us.selectedPeer:case Ir.selectedPeer:{r=Gu.fromBinary.bind(Gu);break}case us.selectedPeerDiff:case Ir.selectedPeerDiff:{r=vg.fromBinary.bind(vg);break}case us.leaveRoom:case Ir.leaveRoom:{r=Ju.fromBinary.bind(Ju);break}case L.updateRoomInfo:{r=dd.fromBinary.bind(dd);break}}this.socket.on(t,({payload:a})=>{let o=i;if(!r)return e(void 0);try{o=r(a)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}async getUserPermissions(t){const e={userIds:[t]};try{const r=await this.socket.sendMessagePromise(Sd.getUserPresets,FM.toBinary(e)),i=WM.fromBinary(r.payload).peerPresets[0],a=new TextDecoder().decode(i.preset),o=JSON.parse(a).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}}}Ot=new WeakMap;wO([y.trace("RoomSocketHandler.joinRoom")],sS.prototype,"joinRoom",1);var wt;class _O{constructor(t){g(this,wt,void 0);m(this,wt,t)}async getStageRequests(){const{payload:t}=await n(this,wt).sendMessagePromise(L.getStageRequests);return t?Iu.fromBinary(t):{stageRequests:[]}}requestAccess(){n(this,wt).sendMessage(L.requestStageAccess)}cancelRequestAccess(){n(this,wt).sendMessage(L.cancelStageRequest)}async grantAccess(t){const e={userIds:t};n(this,wt).sendMessage(L.grantStageAccess,SI.toBinary(e))}async denyAccess(t){const e={userIds:t};n(this,wt).sendMessage(L.denyStageAccess,yI.toBinary(e))}joinStage(){return n(this,wt).sendMessagePromise(L.joinStage,void 0,void 0,L.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return n(this,wt).sendMessagePromise(L.leaveStage,Ng.toBinary(e),void 0,L.peerStageStatusUpdate)}kick(t){const e={userIds:t};return n(this,wt).sendMessagePromise(L.leaveStage,Ng.toBinary(e))}on(t,e){let r;switch(t){case L.grantStageAccess:case L.denyStageAccess:{r=void 0;break}case L.getStagePeers:{r=Og.fromBinary.bind(Og);break}case L.getStageRequests:case L.requestStageAccess:case L.cancelStageRequest:{r=Iu.fromBinary.bind(Iu);break}case L.peerStageStatusUpdate:{r=_g.fromBinary.bind(_g);break}}n(this,wt).on(t,({payload:i,id:a})=>{if(!i||!r)return e(void 0,a);const o=r(i);return e(o,a)})}async getPeerInfo(t){const e=await n(this,wt).sendMessagePromise(L.getPeerInfo,jf.toBinary({peerId:t}));return Sn.fromBinary(e.payload)}}wt=new WeakMap;var zr,ka;class CO{constructor(t,e){g(this,zr,void 0);g(this,ka,void 0);m(this,zr,e),m(this,ka,t)}get logger(){return n(this,ka).getValue("logger")}get peerId(){return n(this,ka).getValue("peerId")}storeInsertKeys(t,e,r,i){const a={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};n(this,zr).sendMessage(Hs.storeInsertKeys,XA.toBinary(a),i)}storeGetKeys(t,e,r,i){const a={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};n(this,zr).sendMessage(Hs.storeGetKeys,eI.toBinary(a),i)}storeDeleteKeys(t,e,r,i){const a={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};n(this,zr).sendMessage(Hs.storeDeleteKeys,sI.toBinary(a),i)}on(t,e){const r=Ig.fromBinary.bind(Ig);n(this,zr).on(t,({payload:i,id:a})=>{const o=r(i);return e(o,a)})}}zr=new WeakMap,ka=new WeakMap;var RO=Object.defineProperty,kO=(s,t,e)=>t in s?RO(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,bO=(s,t,e)=>(kO(s,typeof t!="symbol"?t+"":t,e),e),_p=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},A=(s,t,e)=>(_p(s,t,"read from private field"),e?e.call(s):t.get(s)),oe=(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)},te=(s,t,e,r)=>(_p(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),re=(s,t,e)=>(_p(s,t,"access private method"),e),jd={},MO={get exports(){return jd},set exports(s){jd=s}},An=typeof Reflect=="object"?Reflect:null,Wg=An&&typeof An.apply=="function"?An.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},_d;An&&typeof An.ownKeys=="function"?_d=An.ownKeys:Object.getOwnPropertySymbols?_d=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:_d=function(s){return Object.getOwnPropertyNames(s)};function AO(s){console&&console.warn&&console.warn(s)}var rS=Number.isNaN||function(s){return s!==s};function le(){le.init.call(this)}MO.exports=le;jd.once=NO;le.EventEmitter=le;le.prototype._events=void 0;le.prototype._eventsCount=0;le.prototype._maxListeners=void 0;var Jg=10;function mu(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(le,"defaultMaxListeners",{enumerable:!0,get:function(){return Jg},set:function(s){if(typeof s!="number"||s<0||rS(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Jg=s}});le.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};le.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||rS(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 iS(s){return s._maxListeners===void 0?le.defaultMaxListeners:s._maxListeners}le.prototype.getMaxListeners=function(){return iS(this)};le.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")Wg(c,this,t);else for(var d=c.length,l=dS(c,d),e=0;e<d;++e)Wg(l[e],this,t);return!0};function nS(s,t,e,r){var i,a,o;if(mu(e),a=s._events,a===void 0?(a=s._events=Object.create(null),s._eventsCount=0):(a.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),a=s._events),o=a[t]),o===void 0)o=a[t]=e,++s._eventsCount;else if(typeof o=="function"?o=a[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=iS(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,AO(c)}return s}le.prototype.addListener=function(s,t){return nS(this,s,t,!1)};le.prototype.on=le.prototype.addListener;le.prototype.prependListener=function(s,t){return nS(this,s,t,!0)};function IO(){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 aS(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=IO.bind(r);return i.listener=e,r.wrapFn=i,i}le.prototype.once=function(s,t){return mu(t),this.on(s,aS(this,s,t)),this};le.prototype.prependOnceListener=function(s,t){return mu(t),this.prependListener(s,aS(this,s,t)),this};le.prototype.removeListener=function(s,t){var e,r,i,a,o;if(mu(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,a=e.length-1;a>=0;a--)if(e[a]===t||e[a].listener===t){o=e[a].listener,i=a;break}if(i<0)return this;i===0?e.shift():DO(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this};le.prototype.off=le.prototype.removeListener;le.prototype.removeAllListeners=function(s){var t,e,r;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[s]),this;if(arguments.length===0){var i=Object.keys(e),a;for(r=0;r<i.length;++r)a=i[r],a!=="removeListener"&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=e[s],typeof t=="function")this.removeListener(s,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(s,t[r]);return this};function oS(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?OO(i):dS(i,i.length)}le.prototype.listeners=function(s){return oS(this,s,!0)};le.prototype.rawListeners=function(s){return oS(this,s,!1)};le.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):cS.call(s,t)};le.prototype.listenerCount=cS;function cS(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}le.prototype.eventNames=function(){return this._eventsCount>0?_d(this._events):[]};function dS(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function DO(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function OO(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function NO(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,a),r(o)}function a(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}lS(s,t,a,{once:!0}),t!=="error"&&LO(s,i,{once:!0})})}function LO(s,t,e){typeof s.on=="function"&&lS(s,"error",t,e)}function lS(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(a){r.once&&s.removeEventListener(t,i),e(a)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class VO extends v.MessageType{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const Kg=new VO;class uS{static encode(t){return Kg.toBinary(t)}static decode(t){return Kg.fromBinary(new Uint8Array(t))}}function $O(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Mr;class xO{constructor(t={}){bO(this,"opts"),oe(this,Mr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},te(this,Mr,0)}async wait(){te(this,Mr,A(this,Mr)+1);const t=$O(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**A(this,Mr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return A(this,Mr)}reset(){te(this,Mr,0)}}Mr=new WeakMap;const wr={debug:0,info:1,warn:2,error:3};var pi,gi;class UO{constructor(t){oe(this,pi,void 0),oe(this,gi,void 0),te(this,pi,console),te(this,gi,t)}debug(...t){wr[A(this,gi)]>wr.debug||A(this,pi).debug("[Sockrates]:",...t)}info(...t){wr[A(this,gi)]>wr.info||A(this,pi).info("[Sockrates]:",...t)}warn(...t){wr[A(this,gi)]>wr.warn||A(this,pi).warn("[Sockrates]:",...t)}error(...t){wr[A(this,gi)]>wr.error||A(this,pi).error("[Sockrates]:",...t)}}pi=new WeakMap,gi=new WeakMap;var hS=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(hS||{});const zg="2",Yg="3";var ke,Pn,ce,Pe,Ar,Je,ur,ri,ls,wn,_n,Us,Mh,pS,uo,Cd,Ah,gS,Rd,Lu,qd,Ih,Dh,mS,So,kd,In,vo,Gd,Oh,Dn,yo,Nh,fS,Eo,bd,Po,Wd;class HO{constructor(t,e){var E,R,M,D,I,x,$,B,z,Z,U,Y;oe(this,Mh),oe(this,uo),oe(this,Ah),oe(this,Rd),oe(this,qd),oe(this,Dh),oe(this,So),oe(this,In),oe(this,Gd),oe(this,Dn),oe(this,Nh),oe(this,Eo),oe(this,Po),oe(this,ke,void 0),oe(this,Pn,void 0),oe(this,ce,void 0),oe(this,Pe,void 0),oe(this,Ar,void 0),oe(this,Je,void 0),oe(this,ur,void 0),oe(this,ri,void 0),oe(this,ls,void 0),oe(this,wn,void 0),oe(this,_n,void 0),oe(this,Us,void 0);var r,i,a,o,c,d,l,u,h,f,S;te(this,Pn,t),te(this,Ar,[]),te(this,Je,new jd),te(this,ur,!0),te(this,ls,!1),te(this,ce,e!=null?e:{}),(E=(r=A(this,ce)).autoReconnect)!=null||(r.autoReconnect=!0),(R=(i=A(this,ce)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(M=(a=A(this,ce)).pingTimeout)!=null||(a.pingTimeout=3e4),(D=(o=A(this,ce)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(I=(c=A(this,ce)).debug)!=null||(c.debug=!0),(x=(d=A(this,ce)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),($=(l=A(this,ce)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(B=(u=A(this,ce)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(z=(h=A(this,ce)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),(Z=(f=A(this,ce)).clientInitiatedPings)!=null||(f.clientInitiatedPings=!1),(U=(S=A(this,ce)).clientInitiatedPingInterval)!=null||(S.clientInitiatedPingInterval=3e4),te(this,ri,{code:void 0,reason:void 0}),te(this,Pe,(Y=A(this,ce).logger)!=null?Y:new UO(A(this,ce).debug?"debug":"info")),te(this,Us,new xO)}get readyState(){var t;return(t=A(this,ke))==null?void 0:t.readyState}get url(){return A(this,Pn)}updateURL(t){te(this,Pn,t),re(this,Dh,mS).call(this)}get config(){return A(this,ce)}get sendQueue(){return A(this,Ar)}flush(){if(!A(this,ce).queueOnDisconnect)return!1;const t=[];return A(this,Ar).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),te(this,Ar,t),A(this,Ar)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){A(this,Pe).debug("Websocket was already connecting or connected.");return}if(A(this,ur)!==!1)return new Promise((e,r)=>{re(this,Dn,yo).call(this),re(this,Po,Wd).call(this);try{te(this,ke,new WebSocket(re(this,Mh,pS).call(this,A(this,Pn)))),A(this,ke).binaryType="arraybuffer",A(this,Pe).debug("Connecting");const i=setTimeout(()=>{A(this,Pe).debug("Connection timeout. Closing socket"),te(this,ur,!0),re(this,Po,Wd).call(this),A(this,ke).close(3001,"Connection Timeout"),A(this,ce).autoReconnect&&!A(this,ls)&&(A(this,Je).emit("reconnecting"),re(this,So,kd).call(this)),r(new Error("Connection timed out!"))},A(this,ce).connectionTimeout);A(this,ke).onopen=()=>{A(this,Pe).debug(`Ready State: ${hS[A(this,ke).readyState]}`),i&&clearTimeout(i),re(this,Gd,Oh).call(this),re(this,Nh,fS).call(this),te(this,ri,{code:void 0,reason:void 0}),A(this,Je).emit("connected"),A(this,ce).flushOnReconnect&&this.flush(),e()},A(this,ke).onclose=a=>{try{i&&clearTimeout(i);const{code:o,reason:c}=a;r(c),A(this,Pe).debug("Socket closed. Close event:",{event:a}),A(this,Pe).debug(`Connection closed code: ${o}`),A(this,Pe).debug(`Connection closed reason: ${c}`),A(this,ls)||re(this,qd,Ih).call(this,o,c)}catch(o){re(this,uo,Cd).call(this,o)}},A(this,ke).onerror=a=>{re(this,uo,Cd).call(this,a)},A(this,ke).onmessage=a=>re(this,Ah,gS).call(this,a)}catch(i){re(this,uo,Cd).call(this,i,r)}})}send(t,e,r,i){const a={event:t,id:e,payload:r,metadata:i};if(A(this,ce).queueOnDisconnect&&(!A(this,ke)||A(this,ke).readyState!==1))return A(this,Pe).debug("Queuing message since socket is not connected!",a),A(this,Ar).push(a),!1;const o=uS.encode(a);return re(this,In,vo).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return re(this,In,vo).call(this,t)}receive(t,e){return A(this,Je).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){A(this,Je).on(t,e);return}this.receive(t,e)}removeAllListeners(){A(this,Je).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){A(this,Je).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){A(this,Je).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){te(this,ur,!1),re(this,Dn,yo).call(this),re(this,Eo,bd).call(this),this.removeAllListeners(),te(this,ri,{code:1e3,reason:"Sockrates disconnect method called"}),A(this,ke).close(1e3,"Sockrates disconnect method called.")}}ke=new WeakMap,Pn=new WeakMap,ce=new WeakMap,Pe=new WeakMap,Ar=new WeakMap,Je=new WeakMap,ur=new WeakMap,ri=new WeakMap,ls=new WeakMap,wn=new WeakMap,_n=new WeakMap,Us=new WeakMap,Mh=new WeakSet,pS=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)://.")},uo=new WeakSet,Cd=function(s,t){A(this,Pe).error("Error:",{error:s}),A(this,Je).emit("errored",{error:s}),t==null||t(s)},Ah=new WeakSet,gS=function(s){if(re(this,Gd,Oh).call(this),s.data===zg){A(this,Pe).debug("Received ping from server"),re(this,In,vo).call(this,Yg);return}if(s.data===Yg){A(this,Pe).debug("Received pong from server");return}const t=uS.decode(s.data),{id:e,payload:r}=t;A(this,Pe).debug("Received message",{event:t.event,messageID:e}),A(this,Je).emit(t.event.toString(),{id:e,payload:r})},Rd=new WeakSet,Lu=function(){return A(this,ke).readyState===1},qd=new WeakSet,Ih=function(s,t){te(this,ri,{reason:t,code:s}),A(this,Je).emit("disconnected",{code:s,reason:t})},Dh=new WeakSet,mS=function(){const{reason:s,code:t}=A(this,ri);t&&t!==1e3&&A(this,ur)&&A(this,ce).autoReconnect&&!A(this,ls)&&(A(this,Pe).debug(`Triggering reconnection due to ${s}.`),A(this,Je).emit("reconnecting"),re(this,So,kd).call(this))},So=new WeakSet,kd=async function(s=!0){if(s&&A(this,ls)){A(this,Pe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(A(this,ls)||A(this,Us).reset(),A(this,ce).maxReconnectionAttempts!==null&&A(this,Us).getAttempts()>=A(this,ce).maxReconnectionAttempts){A(this,Je).emit("failed"),te(this,ls,!1);return}te(this,ls,!0),re(this,Po,Wd).call(this),re(this,Dn,yo).call(this);try{if(await A(this,Us).wait(),A(this,ur)===!1)return;if(A(this,Pe).debug(`Reconnection attempt ${A(this,Us).getAttempts()}`),A(this,Je).emit("reconnectAttempt",{attempt:A(this,Us).getAttempts()}),await this.connect(),!re(this,Rd,Lu).call(this))throw Error("Reconnect Failed");te(this,ls,!1),te(this,ri,{code:void 0,reason:void 0}),A(this,Je).emit("reconnected")}catch(t){A(this,Pe).debug("Failed to reconnect."),A(this,Je).emit("reconnectFailure",{attempt:A(this,Us).getAttempts()}),re(this,So,kd).call(this,!1)}},In=new WeakSet,vo=function(s){try{return A(this,ke).send(s),!0}catch(t){return A(this,Pe).error(t.message),!1}},Gd=new WeakSet,Oh=function(){this.config.disconnectOnPingTimeout&&(A(this,Pe).debug("Resetting ping timeout"),re(this,Dn,yo).call(this),te(this,wn,setTimeout(()=>{var s;A(this,Pe).debug("Disconnecting the socket due to ping timeout"),te(this,ur,!0);const t=3002,e="Ping timeout";(s=A(this,ke))==null||s.close(t,e),re(this,qd,Ih).call(this,t,e)},A(this,ce).pingTimeout)))},Dn=new WeakSet,yo=function(){A(this,wn)&&(clearTimeout(A(this,wn)),te(this,wn,void 0))},Nh=new WeakSet,fS=function(){re(this,Eo,bd).call(this),A(this,ce).clientInitiatedPings&&te(this,_n,setInterval(()=>{re(this,Rd,Lu).call(this)&&(A(this,Pe).debug("Sending client-initiated ping"),re(this,In,vo).call(this,zg))},A(this,ce).clientInitiatedPingInterval))},Eo=new WeakSet,bd=function(){A(this,_n)&&(clearInterval(A(this,_n)),te(this,_n,void 0))},Po=new WeakSet,Wd=function(){re(this,Eo,bd).call(this),A(this,ke)&&(A(this,ke).onopen=void 0,A(this,ke).onerror=void 0,A(this,ke).onmessage=void 0,A(this,ke).onclose=void 0)};function TS(s){return`${s.slice(0,10)}...${s.slice(-10)}`}function BO(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 a=fi.baseURI.prod;t&&(a=t);const o=`https://${Mf({servicePrefix:"api",baseURI:a})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:a,apiBase:o}}catch(e){throw new C("Invalid auth token","0004")}}var FO=Object.defineProperty,jO=Object.getOwnPropertyDescriptor,fu=(s,t,e,r)=>{for(var i=r>1?void 0:r?jO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&FO(t,e,i),i};const Qg=65535,qO=3,GO=15e3,WO=8e3,JO=50,KO=1e3,zO=1e4;var bs,ba,Ee,Ze,at,Yr,Qr,Xi,Zi,Xr,Ms,As,Zr,en,mt,ei,ft,Ve,Hc,Lh,Gl,vS,Wl,yS,Jl,ES,Bc,Vh,Fc,$h,tn,ho,Kl,Vu,PS,zl,wS,jc,xh,qc,Uh,Gc,Hh,Yl,_S,Wc,Bh,Jc,Fh;const SS=(Vu=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,Ze);g(this,Hc);g(this,Gl);g(this,Wl);g(this,Jl);g(this,Bc);g(this,Fc);g(this,tn);g(this,zl);g(this,jc);g(this,qc);g(this,Gc);g(this,Yl);g(this,Wc);g(this,Jc);g(this,bs,void 0);g(this,ba,void 0);g(this,Ee,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");g(this,Yr,[]);g(this,Qr,void 0);g(this,Xi,!1);g(this,Zi,void 0);g(this,Xr,void 0);g(this,Ms,void 0);g(this,As,void 0);g(this,Zr,void 0);g(this,en,void 0);g(this,mt,0);g(this,ei,void 0);g(this,ft,!0);g(this,Ve,void 0);if(!t||!e||!r)throw new C("peerId, meetingId, or authToken can not be empty","0404");m(this,Ve,s),m(this,As,navigator.isReactNative?jT:go),this.capabilities=i,this.roomName=e,this.authToken=r,m(this,bs,k(this,Hc,Lh).call(this,t)),m(this,ba,t);const a=i.includes("PING");m(this,Ee,new HO(n(this,bs),{autoReconnect:!1,disconnectOnPingTimeout:a,queueOnDisconnect:!1,flushOnReconnect:!1,logger:this.logger,clientInitiatedPings:!a,clientInitiatedPingInterval:15e3})),this.handleSocketConnectionEvents()}get joinAttempted(){return n(this,Ze,at).socketJoinAttempted}set joinAttempted(s){n(this,Ze,at).socketJoinAttempted=s}get telemetry(){return n(this,Ve).getValue("telemetry")}get logger(){return n(this,Ve).getValue("logger")}get peerId(){return n(this,Ve).getValue("peerId")}get supersededLocalPeerIds(){return n(this,Yr).filter(s=>s!==this.peerId)}updateCallstatsPeerId(s){const t=n(this,Ve).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;m(this,bs,k(this,Hc,Lh).call(this,s)),m(this,ba,s),n(this,Ve).getValue("telemetry").resetPeerId(s),(t=n(this,Ve).getValue("apiClient"))==null||t.setHeader("tracing-id",s),this.updateCallstatsPeerId(s),ii.remapContext(s,n(this,Ve)),this.logger.info(`Attempting websocket connection with URL: ${n(this,tn,ho)}`),n(this,Ee).updateURL(n(this,bs))}get url(){return n(this,bs)}async connect(){var t;const s=n(this,mt)+1;m(this,mt,s),k(this,jc,xh).call(this),m(this,ft,!0),k(this,Jl,ES).call(this);try{if(await n(this,Ee).connect(),!n(this,ft)||s!==n(this,mt))throw new Error("Socket connection was canceled");k(this,Fc,$h).call(this,this.peerId),(t=n(this,Ms))!=null||m(this,Ms,this.peerId),n(this,Ze,at).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}catch(e){throw this.logger.error(`Websocket connection failed with URL: ${n(this,tn,ho)}`,{error:e}),n(this,ft)&&s===n(this,mt)&&k(this,Gc,Hh).call(this,s),e}}disconnect(){m(this,mt,n(this,mt)+1),m(this,ft,!1),k(this,jc,xh).call(this),k(this,Bc,Vh).call(this),m(this,Ms,void 0),n(this,Ee).disconnect(),n(this,Ze,at).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return n(this,Ee).readyState===1}catch(s){return!1}}sendMessage(s,t,e){if(!n(this,Wc,Bh))return!1;const r={};return n(this,Ve).getValue("telemetry").injectContext(r),n(this,Ee).send(s,e!=null?e:k(this,Jc,Fh).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(!n(this,Wc,Bh))return Promise.reject(new Error("Socket is not connected for the current peer ID"));const a=i!=null?i:s;return new Promise((o,c)=>{let d;const l=(M,D)=>{d&&clearTimeout(d),n(this,Ee).removeListener(a,M),n(this,Ee).removeListener(Qg,D),n(this,Ee).removeListener(Ir.errorResponse,D),n(this,Ee).removeListener(us.errorResponse,D)},u=r!=null?r:k(this,Jc,Fh).call(this),h={};n(this,Ve).getValue("telemetry").injectContext(h);const S=({id:M,payload:D})=>{if(u===M){let I;try{const x=ok.fromBinary(D);I=new Error(x.errorMessage)}catch(x){I=new Error("failed to parse error message",{cause:x});try{const $=db.fromBinary(D);I=new Error($.message)}catch($){I=new Error("failed to parse error message",{cause:$})}}c(I),l(E,S)}},E=({id:M,payload:D})=>{u===M&&(o({id:M,payload:D}),l(E,S))};n(this,Ee).on(a,E),n(this,Ee).on(Qg,S),n(this,Ee).on(Ir.errorResponse,S),n(this,Ee).on(us.errorResponse,S),d=setTimeout(()=>{l(E,S),c(new Error(`request timeout for callback eventId:${s}`))},t),n(this,Ee).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){n(this,Ee).on(s,t)}onStateEvent(s,t){n(this,Ee).on(s,t)}removeListener(s,t){n(this,Ee).removeListener(s,t)}removeListeners(s){n(this,Ee).removeListeners(s)}flush(){return n(this,Ee).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{var s;this.logger.info(`Websocket connected with URL: ${n(this,tn,ho)}`),(s=n(this,Ms))!=null||m(this,Ms,this.peerId),n(this,Ze,at).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{!n(this,ft)||n(this,ei)===n(this,mt)||(this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}}),n(this,Ze,at).updateSocketConnectionState("disconnected"),n(this,Ve).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,Ze,at).joinAttempted}),k(this,Gc,Hh).call(this,n(this,mt)))})}},bs=new WeakMap,ba=new WeakMap,Ee=new WeakMap,Ze=new WeakSet,at=function(){return n(this,Ve).getValue("connectionHandler")},Yr=new WeakMap,Qr=new WeakMap,Xi=new WeakMap,Zi=new WeakMap,Xr=new WeakMap,Ms=new WeakMap,As=new WeakMap,Zr=new WeakMap,en=new WeakMap,mt=new WeakMap,ei=new WeakMap,ft=new WeakMap,Ve=new WeakMap,Hc=new WeakSet,Lh=function(s){let t=np({servicePrefix:"ws",baseURI:n(this,Ve).getValue("baseURI")});const e=Ao(n(this,Ve),"socket_server_base");if(typeof e=="string"){const a=/^(http|ws):\/\//i.test(e),o=e.replace(/^(https?|wss?):\/\//i,"").replace(/\/+$/,"");t=`${a?"ws":"wss"}://${o}/ws`}const r=new URL(t),i={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...n(this,Yr).length>0&&{oldPeerIds:n(this,Yr).join(",")},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(a=>Ld[a]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0,apiVersion:"23-09-2026"};return Object.entries(i).forEach(([a,o])=>{r.searchParams.append(a,o.toString())}),r.href},Gl=new WeakSet,vS=function(){if(!n(this,Ms))return;const s=new URL(n(this,bs));return s.protocol=s.protocol==="ws:"?"http:":"https:",s.pathname=`${s.pathname.replace(/\/+$/,"")}/ping`,s.search="",s.searchParams.set("peerId",n(this,Ms)),s.href},Wl=new WeakSet,yS=async function(){const s=k(this,Gl,vS).call(this);if(!s||n(this,Xi))return;const t={},e=typeof AbortController=="function"?new AbortController:void 0;let r;m(this,Xi,!0),m(this,Xr,t),m(this,Zi,e);try{e&&(r=n(this,As).setTimeout(()=>e.abort(),WO));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){n(this,Xr)===t&&this.logger.warn("SocketService::API ping request failed",{error:i,networkCall:{url:s}})}finally{r!==void 0&&n(this,As).clearTimeout(r),n(this,Xr)===t&&(m(this,Xi,!1),m(this,Xr,void 0),m(this,Zi,void 0))}},Jl=new WeakSet,ES=function(){n(this,Qr)===void 0&&m(this,Qr,n(this,As).setInterval(()=>k(this,Wl,yS).call(this),GO))},Bc=new WeakSet,Vh=function(){var s;n(this,Qr)!==void 0&&n(this,As).clearInterval(n(this,Qr)),(s=n(this,Zi))==null||s.abort(),m(this,Qr,void 0),m(this,Xi,!1),m(this,Xr,void 0),m(this,Zi,void 0)},Fc=new WeakSet,$h=function(s){m(this,Yr,[s,...n(this,Yr).filter(t=>t!==s)].slice(0,qO))},tn=new WeakSet,ho=function(){const s=new URL(n(this,bs)),t=s.searchParams.get("authToken");return t&&s.searchParams.set("authToken",TS(t)),s.href},Kl=new WeakSet,PS=function(s){const t=Math.min(zO,KO*2**(s-1));return Math.floor(Math.random()*(t+1))},zl=new WeakSet,wS=function(s){return new Promise(t=>{var e;m(this,en,t),m(this,Zr,n(this,As).setTimeout(()=>{m(this,Zr,void 0),m(this,en,void 0),t()},k(e=SS,Kl,PS).call(e,s)))})},jc=new WeakSet,xh=function(){var s;n(this,Zr)!==void 0&&(n(this,As).clearTimeout(n(this,Zr)),m(this,Zr,void 0)),(s=n(this,en))==null||s.call(this),m(this,en,void 0)},qc=new WeakSet,Uh=function(s,t){!n(this,ft)||s!==n(this,mt)||(t&&this.logger.error("SocketService::Reconnect loop failed",{error:t}),m(this,ft,!1),k(this,Bc,Vh).call(this),m(this,Ms,void 0),n(this,Ze,at).updateSocketConnectionState("failed"),n(this,Ve).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_FAILED))},Gc=new WeakSet,Hh=function(s){!n(this,ft)||n(this,ei)===s||(m(this,ei,s),n(this,Ze,at).updateSocketConnectionState("reconnecting"),k(this,Yl,_S).call(this,s).catch(t=>k(this,qc,Uh).call(this,s,t)))},Yl=new WeakSet,_S=async function(s){try{for(let t=1;t<=JO;t+=1){if(!n(this,ft)||s!==n(this,mt)||(await k(this,zl,wS).call(this,t),!n(this,ft)||s!==n(this,mt)))return;this.updateURL(pr.v4()),this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:t}}),n(this,Ze,at).updateSocketConnectionState("reconnectAttempt",t);try{if(await n(this,Ee).connect(!0),!n(this,ft)||s!==n(this,mt))return;if(!this.isConnected)throw new Error("Reconnect failed");k(this,Fc,$h).call(this,this.peerId),m(this,Ms,this.peerId),n(this,Ze,at).updateSocketConnectionState("reconnected"),n(this,Ve).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_RECONNECTED,{wasSocketJoinAttempted:n(this,Ze,at).socketJoinAttempted,wasMediaJoinAttempted:n(this,Ze,at).mediaJoinAttempted});return}catch(e){if(!n(this,ft)||s!==n(this,mt))return;this.logger.error(`Websocket connection retry attempt ${t} failed with URL: ${n(this,tn,ho)}`,{error:e,socket:{retryAttempt:t}}),n(this,Ze,at).updateSocketConnectionState("reconnectFailure",t)}}k(this,qc,Uh).call(this,s)}finally{n(this,ei)===s&&m(this,ei,void 0)}},Wc=new WeakSet,Bh=function(){return this.isConnected&&n(this,ba)===this.peerId},Jc=new WeakSet,Fh=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},g(Vu,Kl),Vu);let id=SS;fu([y.trace("SocketService.connect")],id.prototype,"connect",1);fu([y.trace("SocketService.disconnect")],id.prototype,"disconnect",1);fu([y.trace("SocketService.sendMessagePromise")],id.prototype,"sendMessagePromise",1);fu([y.trace("SocketService.sendMessagePromiseWithTimeout")],id.prototype,"sendMessagePromiseWithTimeout",1);class YO{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var a;const e=Vb.fromBinary(t),r=e.meetings.map(o=>{var c;return{id:o.id,title:o.title,participants:(c=o.participants)!=null?c:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(a=e.parentMeeting.participants)!=null?a:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=lM.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=qf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return qb.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title,error:r.error}))}handleConnectedRoomsDeletedRaw({payload:t}){return eM.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(L.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const e=await this.socketService.sendMessagePromise(L.createConnectedRooms,Hb.toBinary({payloads:t}));return this.handleConnectedRoomsUpdatedRaw(e)}async updateConnectedRooms(t){const e=await this.socketService.sendMessagePromise(L.updateConnectedRooms,Kb.toBinary({payloads:t}));return this.handleConnectedRoomsUpdatedRaw(e)}async disableConnectedRooms(t){const e=t.map(i=>({id:i})),r=await this.socketService.sendMessagePromise(L.deleteConnectedRooms,Xb.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(L.movePeers,aM.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 QO=Object.defineProperty,XO=Object.getOwnPropertyDescriptor,ZO=(s,t,e,r)=>{for(var i=r>1?void 0:r?XO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&QO(t,e,i),i},Nt;class CS extends xt{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);g(this,Nt,void 0);m(this,Nt,e)}get isActive(){return this.meetings.length!==0}validateAlterAction(){const e=n(this,Nt).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=n(this,Nt).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 a=n(this,Nt).getValue("userId");if(!(r.length===1&&r[0]===a))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 n(this,Nt).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 n(this,Nt).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)}`);const r=await n(this,Nt).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(o=>({meetingId:o.id,title:o.title})));this.logger.info(`Updated connected meetings ${JSON.stringify(r)}`);const i=new Set(r.filter(o=>!o.error).map(o=>o.id)),a=[...new Set(e.map(o=>o.id))].filter(o=>!i.has(o));if(a.length>0)throw new Error(`Could not update connected meetings: ${a.join(", ")}`)}async deleteMeetings(e){this.validateAlterAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(a=>e.includes(a.id)&&a.participants.length!==0?this.moveParticipants(a.id,this.parentMeeting.id,a.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),await Promise.all(r);const i=await n(this,Nt).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 a=await n(this,Nt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return a.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),a}async moveParticipantsWithCustomPreset(e,r,i){this.validateMoveAction(r,i.map(o=>o.id)),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const a=await n(this,Nt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return a.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),a}moveSuccessHandler(e,r,i){const a=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>a.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>a.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>a.get(d)));return{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}Nt=new WeakMap;ZO([Ut({maxInvocations:60,period:60})],CS.prototype,"getConnectedMeetings",1);var e1=Object.defineProperty,t1=Object.getOwnPropertyDescriptor,Cp=(s,t,e,r)=>{for(var i=r>1?void 0:r?t1(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&e1(t,e,i),i},pe,fm;const RS=(fm=class{constructor(s){p(this,"connectedMeetings");g(this,pe,void 0);m(this,pe,s),this.connectedMeetings=new CS(s)}get telemetry(){return n(this,pe).getValue("telemetry")}get logger(){return n(this,pe).getValue("logger")}static init(s){const t=new RS(s);return s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings()),t.setupEvents(),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){n(this,pe).getValue("connectedMeetingsSocketHandler").socketService.on(L.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),n(this,pe).getValue("connectedMeetingsSocketHandler").socketService.on(L.transferPeer,this.handleTransferPeer.bind(this)),n(this,pe).getValue("connectedMeetingsSocketHandler").socketService.on(L.movedPeer,this.handleMovedPeer.bind(this)),n(this,pe).getValue("connectedMeetingsSocketHandler").socketService.on(L.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),n(this,pe).getValue("connectedMeetingsSocketHandler").socketService.on(L.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=n(this,pe).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,a,o,c;this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:n(this,pe).getValue("self").videoEnabled,audio:n(this,pe).getValue("self").audioEnabled};try{n(this,pe).getValue("self").cleanupEvents(),await n(this,pe).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(a=(i=n(this,pe).getValue("meeting"))==null?void 0:i.meta)==null?void 0:a.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await bS.init({...n(this,pe).getValue("options"),cachedUserDetails:null,defaults:{...n(this,pe).getValue("options").defaults,...e,mediaHandler:n(this,pe).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=n(this,pe).getValue("self");r.self.setName(n(this,pe).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=n(this,pe).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return n(this,pe).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){var a;const t=n(this,pe).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s).filter(o=>!o.error),e=new Map(this.connectedMeetings.meetings.map(o=>[o.id,o]));t.forEach(o=>{var l;const{parentMeeting:c}=this.connectedMeetings;if(o.id===(c==null?void 0:c.id)){this.connectedMeetings.parentMeeting={...c,title:o.title};return}const d=e.get(o.id);e.set(o.id,{...d,id:o.id,title:o.title,participants:(l=d==null?void 0:d.participants)!=null?l:[]})}),this.connectedMeetings.meetings=Array.from(e.values());const r=(a=n(this,pe).getValue("meeting"))==null?void 0:a.meta,i=t.find(o=>o.id===(r==null?void 0:r.meetingId));r&&i&&i.title!==r.meetingTitle&&r[$d](i.title),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=n(this,pe).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},pe=new WeakMap,fm);let Tu=RS;Cp([y.trace("ConnectedMeetingsController.getConnectedMeetings")],Tu.prototype,"getConnectedMeetings",1);Cp([y.trace("ConnectedMeetingsController.setupEvents")],Tu.prototype,"setupEvents",1);Cp([y.trace("ConnectedMeetingsController.switchMeeting")],Tu.prototype,"switchMeeting",1);var s1=Object.defineProperty,r1=Object.getOwnPropertyDescriptor,Rp=(s,t,e,r)=>{for(var i=r>1?void 0:r?r1(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&s1(t,e,i),i};function i1(s){switch(s){case"participant_token_not_yet_valid":return"The participant authentication token is not valid yet.";case"participant_token_expired":return"The participant authentication token has expired.";case"participant_token_revoked":return"The participant authentication token has been revoked.";case"participant_token_invalid":return"The participant authentication token is invalid.";case"meeting_inactive":return"The meeting is inactive and is not accepting participants.";default:return"The participant authentication token may be invalid, expired, or not yet valid. Verify the token and its validity window."}}const po=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 x,$,B,z,Z;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:a,cachedUserDetails:o,logger:c}=s.getAllValues();if(gO(s),ye.isSupported()===!1)throw new C("Browser not supported","0010",c,!0);const d=n0(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(a),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new B0(s);s.setValue("connectionHandler",l);let u="",h=null;c.info("CF SFU is being used.");const f=po.createSocketService(s),S=f.connect();S.catch(()=>{});const E=d.getUserDetails();try{h=await E,u=((x=h.meeting)==null?void 0:x.title)||"",s.setValue("presetName",h.preset.name)}catch(U){if(c.error("Failed to get user details",{error:U}),f.disconnect(),U instanceof Vd){if(U.status===401||U.status===403){const Y=(z=(B=($=U.response)==null?void 0:$.data)==null?void 0:B.error)==null?void 0:z.reason;throw new C(i1(Y),"0004",void 0,!1,Y)}throw U.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")):U.status>=500?new C(`The server encountered an error. Try again. (${U.status})`,"0001"):U.isHttpError?new C(`Request rejected by the server. (${U.status})`,"0001"):U.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")}throw new C((U==null?void 0:U.message)||"Failed to initialize.","0001")}try{await S}catch(U){c.error("[Controller]: Failed to connect to socket server:",{error:U})}const R=dh.init(h.preset,!s.getValue("modules").theme);s.setValue("theme",R);const M=gh.init(s,R.viewType,h.preset.permissions),D=po.setupControllers(f,s,h,u,R,M);M0(R)&&((Z=po.createRoomNodeClient(s,f).initializeConnection(h.participant.name,i,!1,M))==null||Z.catch(Y=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:Y})}));const{controllers:I}=await D;return FC(),new po(e,I,s)}static async setupControllers(s,t,e,r,i,a){var ae,N,_;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:(ae=h.enableHighBitrate)!=null?ae:!1,enableStereo:(N=h.enableStereo)!=null?N:!1}},...d}),t.setValue("maxPreferredStreams",ye.isMobile()?i.maxVideoStreams.mobile:i.maxVideoStreams.desktop);let f,S,E,R,M,D,I,x,$;const B=new SO(t,s),z=new YO(s);t.setValue("connectedMeetingsSocketHandler",z);const Z=new gu(t,s),U=new vr(t,s),Y=new _O(s),ge=new sS(t,s),et=new CO(t,s),b=new TO(s),T=await di.init(t,ge,c,a,i);t.setValue("selfController",T);const P=await iT.init(t,T.self,ge,B,r);o.participant&&(x=await Pr.init(t,T.self,ge)),(_=o.e2ee)!=null&&_.enabled&&o.e2ee.manager.init(l,t.getValue("peerSessionStore")),o.chat&&(S=await To.init(t,U,T.self,x.participants)),o.internals&&(M=await pp.init(t)),o.livestream&&i.viewType===hs.Livestream&&(I=new mT(t,T.self,b)),o.poll&&(f=await tT.init(t,T.self,Z)),o.recording&&(D=new lT(t,T.self,ge)),o.stage&&(E=new nT(t,Y,ge,T.self,x.participants));const V=new OD(t,et);if(o.plugin){if(!x)throw new C("The plugin module cannot be initialized without the `participant` module","0102");const be=d.plugins||[];R=await dT.init(t,be,T.self,V)}if(o.connectedMeetings&&($=await Tu.init(t)),o.pip){const be=await qu._init(t,T.self);t.setValue("pip",be)}return{theme:i,permissions:a,controllers:{storesManager:V,pollController:f,selfController:T,metaController:P,chatController:S,stageController:E,pluginController:R,recordingController:D,internalsController:M,livestreamController:I,participantController:x,connectedMeetingsController:$}}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return eS(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=[];return new id(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Su=po;Rp([y.trace("Controller.init")],Su,"init",1);Rp([y.trace("Controller.createRoomNodeClient")],Su,"createRoomNodeClient",1);Rp([y.trace("Controller.createSocketService")],Su,"createSocketService",1);class n1{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 Xg=new n1;var ti,sn,rn,Kc,Ql,kS;class a1{constructor(){g(this,Ql);g(this,ti,new Audio);g(this,sn,new MediaStream);g(this,rn,new Map);g(this,Kc,void 0);n(this,ti).srcObject=n(this,sn),n(this,ti).autoplay=!0}async playTracks(t){return t.forEach(e=>{n(this,rn).has(e.id)||(n(this,sn).addTrack(e),n(this,rn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&n(this,ti).setSinkId(t)}removeTrack(t){const e=n(this,rn).get(t);e&&(n(this,sn).removeTrack(e),n(this,rn).delete(t))}async play(){return n(this,ti).srcObject=n(this,sn),n(this,ti).play().catch(t=>{k(this,Ql,kS).call(this,t)})}onError(t){m(this,Kc,t)}}ti=new WeakMap,sn=new WeakMap,rn=new WeakMap,Kc=new WeakMap,Ql=new WeakSet,kS=function(t){var e;(e=n(this,Kc))==null||e.call(this,t)};var Is;class o1 extends a1{constructor(){super();g(this,Is,void 0);m(this,Is,new Map)}addParticipantTrack(e,r){n(this,Is).set(e,r.id),this.playTracks([r])}reassignParticipantTrack(e,r){const i=n(this,Is).get(e);i&&(n(this,Is).delete(e),n(this,Is).set(r,i))}removeParticipantTrack(e){const r=n(this,Is).get(e);r&&this.removeTrack(r),n(this,Is).delete(e)}}Is=new WeakMap;var c1=Object.defineProperty,d1=Object.getOwnPropertyDescriptor,vu=(s,t,e,r)=>{for(var i=r>1?void 0:r?d1(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&c1(t,e,i),i},De,nn,Tm;let ni=(Tm=class{constructor(t,e){g(this,De,void 0);g(this,nn,void 0);m(this,nn,t),m(this,De,e)}get peerId(){return n(this,nn).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:pr.v4(),a=ii.createContext(i,{peerId:i}),o=a.getValue("logger");o.init(a);const c=new RT(a,o);return await c.init(t,e,a),a.setValue("defaults",{mediaHandler:c}),c}static async init(t){var f,S,E,R,M,D,I;ye.init();const e=(S=(f=t==null?void 0:t.cachedUserDetails)==null?void 0:f.peerId)!=null?S:pr.v4(),{authToken:r,baseURI:i}=t,{meetingId:a,...o}=BO(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=ni.setupContext(e,t,a,o),d=c.getValue("telemetry"),l=c.getValue("logger");LS(l),Xg.init(l),d.init(c,{roomName:a,userId:o.participantId,organizationId:o.orgId,peerId:e},(M=(R=t.modules)==null?void 0:R.tracing)!=null?M:!0,(I=(D=t==null?void 0:t.modules)==null?void 0:D.devTools)==null?void 0:I.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:TS(t.authToken)}});const u=await Su.init(c),h=new ni(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 a=ii.createContext(t,e),o={...vC,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return a.setValue("options",e),a.setValue("peerId",t),a.setValue("modules",o),a.setValue("sdkName","web-core"),a.setValue("meetingId",r),a.setValue("apiBase",i.apiBase),a.setValue("baseURI",i.baseURI),a.setValue("userId",i.participantId),a.setValue("organizationId",i.orgId),a.setValue("authToken",e.authToken),a.setValue("overrides",(d=e.overrides)!=null?d:{}),a.setValue("env",yC({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",Os(e.cachedUserDetails)),a.setValue("sdkVersion","2.1.1-staging.1"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new o1),a}async join(){const{selfController:t}=n(this,De);return t.self.roomJoined?null:t.joinRoom()}async leave(t){var r;Xg.cleanup(),n(this,nn).getValue("peerSessionStore").reset(),(r=n(this,De).pluginController)==null||r.cleanup();const{selfController:e}=n(this,De);return e.leaveRoom(t)}get participants(){var t;return(t=n(this,De).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,De).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,De).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,De).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,De).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,De).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,De).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,De).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,De).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,De).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,De).stageController)==null?void 0:t.stage}get stores(){return n(this,De).storesManager}get audio(){return n(this,nn).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,De).internalsController)==null?void 0:t.internals}},De=new WeakMap,nn=new WeakMap,Tm);vu([it("0002"),Er.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],ni.prototype,"join",1);vu([it("0003")],ni.prototype,"leave",1);vu([it("0001"),Er.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],ni,"init",1);ni=vu([it("0000")],ni);const bS=ni;module.exports=bS;