@cloudflare/realtimekit 1.2.4-staging.4 → 1.2.4-staging.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.js CHANGED
@@ -10,7 +10,7 @@ b=AS:${this.constrainVideoBitrateKbps}\r
10
10
  ${this.message}`;try{let o=n&&!!i;r&&r.endsWith("00")&&i&&(o=!0),o&&i.error("ClientError",{error:{message:this.message,name:this.name,code:r}});const c=nr.getContext(nr.getMostRecentPeerId());if(c){const d=c.getValue("onError");try{d(this)}catch(l){}}typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("ClientError",{detail:this}))}catch(o){}}}function Vd(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 Nm(s,t,e){if(!s.value){const i=s.get,n=s.set;return i&&(s.get=function(){try{return i.apply(this)}catch(o){Vd(this,t,e,o)}}),n&&(s.set=function(o){try{return n.apply(this,[o])}catch(c){Vd(this,t,e,c)}}),s}const r=s.value;return s.value=function(...i){try{const n=r.apply(this,i);return n&&n instanceof Promise?n.catch(o=>{Vd(this,t,e,o)}):n}catch(n){Vd(this,t,e,n)}},s}function vC(s,t){return(e,r,i)=>{if(i)return Nm(i,s,t);for(const n of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,n);(o.value instanceof Function||o.get instanceof Function||o.set instanceof Function)&&Object.defineProperty(e.prototype,n,Nm(o,s,t))}}}const ut=s=>vC(Error,s);function SC(s){let t=0,e,r;if(!s)return t;for(e=0;e<s.length;e+=1)r=s.charCodeAt(e),t=(t<<5)-t+r,t|=0;return Math.abs(t)%100+1}function yC(){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(n=>{var o;return(o=n.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 R=(s=>(s.NEW_PRODUCER="NEW_PRODUCER",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.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.PRODUCER_CLOSED="websocket/producer-closed",s.NEW_CONSUMER="websocket/new-consumer",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.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))(R||{});class Fn extends lt.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.on(e,r)}addListener(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}class Gt extends lt.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.on(e,r)}addListener(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}function TC(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 Vm=1080,Lm=1920,EC=(s,t,e,r,i,n)=>{let o=.5,c=.5;const d=i,l=n,u=Math.min(e/d,r/l);let h=d*u,g=l*u,v,E,b,P,w=1;return h<e&&(w=e/h),Math.abs(w-1)<1e-14&&g<r&&(w=r/g),h*=w,g*=w,b=d/(h/e),P=l/(g/r),v=(d-b)*o,E=(l-P)*c,v<0&&(v=0),E<0&&(E=0),b>d&&(b=d),P>l&&(P=l),[v,E,b,P,s,t,e,r]},lp=class extends Gt{constructor(e,r,i,n){const o=e.getValue("logger");super(o);m(this,ls,void 0);m(this,Hi,void 0);m(this,mt,void 0);m(this,us,void 0);m(this,Ve,{height:Vm,width:Lm});m(this,As,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});m(this,Sr,void 0);m(this,Rt,{});m(this,$e,void 0);m(this,ea,void 0);m(this,ta,void 0);m(this,yr,void 0);m(this,sa,!1);p(this,"cleanupEventListeners",()=>{a(this,Hi).unsubscribe("stageStatus",this.handlePipMediaControls),a(this,$e).removeListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,$e).removeListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,$e).removeListener("roomLeft",()=>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"&&(a(this,$e).videoEnabled?a(this,$e).disableVideo():a(this,$e).enableVideo(),this.emit("cameraToggled")),e==="MIC"&&(a(this,$e).audioEnabled?a(this,$e).disableAudio():a(this,$e).enableAudio(),this.emit("micToggled")),e==="END"&&(a(this,Hi).getValue("peerSessionStore").emit(R.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&&a(this,yr)==="active"){this.disable(!0);return}a(this,Rt)!==void 0&&this.paintCanvas(),a(this,Sr)!==void 0&&f(this,Sr,requestAnimationFrame(()=>this.animate()))});p(this,"disable",(e=!1)=>{f(this,yr,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(a(this,Sr)),e!==!0&&document.body.removeChild(a(this,mt)),f(this,Sr,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});f(this,Hi,e),f(this,yr,"idle"),f(this,$e,r),f(this,As,{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),n&&this.setupIcon("handRaise",n)}static async _init(e,r){let i,n;try{i=await Dd(lC),n=await Dd(uC)}catch(o){}return new lp(e,r,i,n)}async setupIcon(e,r){switch(e){case"handRaise":f(this,ta,r);break;case"pin":f(this,ea,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":f(this,ta,await Dd(r));break;case"pin":f(this,ea,await Dd(r));break}}constructImage(e){const r=new Image,i=new Blob([e],{type:"image/svg+xml"}),n=window.URL.createObjectURL(i);return new Promise(o=>{r.onload=()=>{o(r),window.URL.revokeObjectURL(n)},r.src=n})}createVideoContainer(){f(this,mt,document.createElement("div")),a(this,mt).style.width="0.1px",a(this,mt).style.height="0.1px",a(this,mt).style.overflow="hidden",a(this,mt).style.position="absolute",a(this,mt).style.bottom="0",a(this,mt).style.right="0",a(this,mt).style.opacity="0",a(this,mt).appendChild(a(this,us))}setupEventListeners(){a(this,Hi).subscribe("stageStatus",this.handlePipMediaControls),a(this,$e).addListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,$e).addListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,$e).addListener("roomLeft",()=>this.disable())}createCanvas(){const e=document.createElement("canvas");e.height=a(this,Ve).height,e.width=a(this,Ve).width,f(this,ls,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||a(this,$e).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||a(this,$e).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const r=Object.values(a(this,Rt)).reduce((i,n)=>(i[n.pinned?"pinned":"regular"].push(n),i),{pinned:[],regular:[]});return[...r.pinned,...r.regular]}drawEmptyTile(e,r,i,n){if(a(this,ls)===void 0)return;const o=a(this,ls).getContext("2d"),c=a(this,ls).width,d=0,l=0,u=r-d*2,h=i-d*2,g=Math.floor(c/u),v=Math.floor(e/g),b=e%g*(u+d)+d,P=v*(h+d)+d,{displayText:w,image:L}=n!=null?n:{};o.fillStyle=w||L?a(this,As).videoBackground:a(this,As).background,o.strokeStyle=a(this,As).brand,o.beginPath(),o.moveTo(b+l,P),o.arcTo(b+u,P,b+u,P+l,l),o.arcTo(b+u,P+h,b+u-l,P+h,l),o.arcTo(b,P+h,b,P+h-l,l),o.arcTo(b,P,b+l,P,l),o.closePath(),o.fill(),o.stroke();const $=u/6,N=u/2+b,B=h/2+P;o.save(),(w||L)&&(o.beginPath(),o.arc(N,B,$,0,Math.PI*2),o.fillStyle=a(this,As).brand,o.fill(),L?(o.clip(),o.drawImage(L,N-$,B-$,$*2,$*2),o.restore()):w&&(o.fillStyle=a(this,As).textOnBrand,o.font=`${$/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(w,N,B)),this.drawIcons(n,b,P,Math.max(u,h)))}drawIcons(e,r,i,n){const o=Math.min(Math.max(n*.15,100),200),c=o*.2,d=o*.2;let l=r+c;const u=i+c,h=g=>{const v=a(this,ls).getContext("2d");v.save(),v.fillStyle=a(this,As).background,v.beginPath(),v.moveTo(l+d,u),v.arcTo(l+o,u,l+o,u+d,d),v.arcTo(l+o,u+o,l+o-d,u+o,d),v.arcTo(l,u+o,l,u+o-d,d),v.arcTo(l,u,l+d,u,d),v.closePath(),v.fill(),typeof g=="string"?(v.font=`${o/1.5}px sans-serif`,v.fillStyle=a(this,As).text,v.textAlign="center",v.textBaseline="top",v.fillText(g,o/2+l,u+c)):v.drawImage(g,l+c,u+c,o-c*2,o-c*2),l+=o+c,v.restore()};e.pinned&&h(a(this,ea)),e.handRaised&&h(a(this,ta)),e.reaction&&h(e.reaction)}drawTile(e,r,i){var l,u;if(a(this,ls)===void 0)return;const n=a(this,ls).getContext("2d"),o=this.getSources();let c=0,d=0;for(;c<a(this,Ve).height-5;){let h=0;for(;h<a(this,Ve).width-5&&d<i;){if((l=o[d])!=null&&l.enabled){const g=o[d].element,[v,E,b,P,w,L,$,N]=EC(h,c,e,r,g.videoWidth,g.videoHeight);((u=g==null?void 0:g.classList)==null?void 0:u.contains("mirror"))?(n.save(),n.scale(-1,1),n.drawImage(g,v,E,b,P,-1*w,L,-1*$,N),n.restore()):n.drawImage(g,v,E,b,P,w,L,$,N),this.drawIcons(o[d],w,L,Math.max($,N))}else this.drawEmptyTile(d,e,r,o[d]);d+=1,h+=e}c+=r}}calcGridElemSize(e){switch(e){case 0:case 1:return[a(this,Ve).width,a(this,Ve).height];case 2:return[Math.floor(a(this,Ve).width/2),a(this,Ve).height];case 3:case 4:return[Math.floor(a(this,Ve).width/2),Math.floor(a(this,Ve).height/2)];case 5:case 6:return[Math.floor(a(this,Ve).width/3),Math.floor(a(this,Ve).height/2)];case 7:case 8:case 9:return[Math.floor(a(this,Ve).width/3),Math.floor(a(this,Ve).height/3)];default:return[Math.floor(a(this,Ve).width/3),Math.floor(a(this,Ve).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=a(this,$e).config)==null?void 0:e.viewType)!=="LIVESTREAM"}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(f(this,sa,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),a(this,mt))try{document.body.removeChild(a(this,mt))}catch(e){}this.removeAllSources(),f(this,ls,void 0),f(this,us,void 0),f(this,Sr,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(a(this,sa))return;f(this,sa,!0),this.createCanvas(),this.setupMediaSessionEvents();const i=document.createElement("video");f(this,Ve,{height:e!=null?e:Vm,width:r!=null?r:Lm}),i.height=a(this,Ve).height,i.width=a(this,Ve).width,i.autoplay=!0,i.muted=!0,i.srcObject=a(this,ls).captureStream(24),f(this,us,i),a(this,us).onloadedmetadata=()=>{try{this.emit("pipStarted"),a(this,us).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(n){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){a(this,Rt)[e]!==void 0&&(a(this,Rt)[e].enabled=!0)}disableSource(e){a(this,Rt)[e]!==void 0&&(a(this,Rt)[e].enabled=!1)}async generateAvatar(e,r){if(!r)return;const i=new Image;try{const n=await(await fetch(r)).blob(),o=window.URL.createObjectURL(n);i.onload=()=>{this.updateSource(e,{image:i}),window.URL.revokeObjectURL(o)},i.src=o}catch(n){this.logger.error("Pip::GenerateAvatar",{error:n})}}addSource(e,r,i,n=!1,o=void 0,c=void 0,d=!1){this.logger.debug("Pip::AddSource",{pip:{id:e,handRaised:d}}),a(this,Rt)[e]={id:e,element:r,enabled:i,pinned:n,displayText:o?TC(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=a(this,Rt)[e];i&&(a(this,Rt)[e]={...i,...r})}removeSource(e){delete a(this,Rt)[e]}removePinnedSource(){Object.values(a(this,Rt)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){f(this,Rt,{})}enable(){f(this,yr,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",a(this,$e).videoEnabled),this.updateMediaSession("MIC",a(this,$e).audioEnabled),document.body.appendChild(a(this,mt)),f(this,Sr,requestAnimationFrame(()=>this.animate())),a(this,us).onloadedmetadata=()=>{a(this,us).requestPictureInPicture().then(()=>{f(this,yr,"active")})},a(this,us).readyState===4&&a(this,us).requestPictureInPicture().then(()=>{f(this,yr,"active")})}};let rh=lp;ls=new WeakMap,Hi=new WeakMap,mt=new WeakMap,us=new WeakMap,Ve=new WeakMap,As=new WeakMap,Sr=new WeakMap,Rt=new WeakMap,$e=new WeakMap,ea=new WeakMap,ta=new WeakMap,yr=new WeakMap,sa=new WeakMap;function ih(s){let t=typeof s;if(t=="object"){if(Array.isArray(s))return"array";if(s===null)return"null"}return t}function bC(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}let ar="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Ld=[];for(let s=0;s<ar.length;s++)Ld[ar[s].charCodeAt(0)]=s;Ld["-".charCodeAt(0)]=ar.indexOf("+"),Ld["_".charCodeAt(0)]=ar.indexOf("/");function wC(s){let t=s.length*3/4;s[s.length-2]=="="?t-=2:s[s.length-1]=="="&&(t-=1);let e=new Uint8Array(t),r=0,i=0,n,o=0;for(let c=0;c<s.length;c++){if(n=Ld[s.charCodeAt(c)],n===void 0)switch(s[c]){case"=":i=0;case`
11
11
  `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(i){case 0:o=n,i=1;break;case 1:e[r++]=o<<2|(n&48)>>4,o=n,i=2;break;case 2:e[r++]=(o&15)<<4|(n&60)>>2,o=n,i=3;break;case 3:e[r++]=(o&3)<<6|n,i=0;break}}if(i==1)throw Error("invalid base64 string.");return e.subarray(0,r)}function PC(s){let t="",e=0,r,i=0;for(let n=0;n<s.length;n++)switch(r=s[n],e){case 0:t+=ar[r>>2],i=(r&3)<<4,e=1;break;case 1:t+=ar[i|r>>4],i=(r&15)<<2,e=2;break;case 2:t+=ar[i|r>>6],t+=ar[r&63],e=0;break}return e&&(t+=ar[i],t+="=",e==1&&(t+="=")),t}var xd;(function(s){s.symbol=Symbol.for("protobuf-ts/unknown"),s.onRead=(e,r,i,n,o)=>{(t(r)?r[s.symbol]:r[s.symbol]=[]).push({no:i,wireType:n,data:o})},s.onWrite=(e,r,i)=>{for(let{no:n,wireType:o,data:c}of s.list(r))i.tag(n,o).raw(c)},s.list=(e,r)=>{if(t(e)){let i=e[s.symbol];return r?i.filter(n=>n.no==r):i}return[]},s.last=(e,r)=>s.list(e,r).slice(-1)[0];const t=e=>e&&Array.isArray(e[s.symbol])})(xd||(xd={}));var Ue;(function(s){s[s.Varint=0]="Varint",s[s.Bit64=1]="Bit64",s[s.LengthDelimited=2]="LengthDelimited",s[s.StartGroup=3]="StartGroup",s[s.EndGroup=4]="EndGroup",s[s.Bit32=5]="Bit32"})(Ue||(Ue={}));function _C(){let s=0,t=0;for(let r=0;r<28;r+=7){let i=this.buf[this.pos++];if(s|=(i&127)<<r,!(i&128))return this.assertBounds(),[s,t]}let e=this.buf[this.pos++];if(s|=(e&15)<<28,t=(e&112)>>4,!(e&128))return this.assertBounds(),[s,t];for(let r=3;r<=31;r+=7){let i=this.buf[this.pos++];if(t|=(i&127)<<r,!(i&128))return this.assertBounds(),[s,t]}throw new Error("invalid varint")}function nh(s,t,e){for(let n=0;n<28;n=n+7){const o=s>>>n,c=!(!(o>>>7)&&t==0),d=(c?o|128:o)&255;if(e.push(d),!c)return}const r=s>>>28&15|(t&7)<<4,i=!!(t>>3);if(e.push((i?r|128:r)&255),!!i){for(let n=3;n<31;n=n+7){const o=t>>>n,c=!!(o>>>7),d=(c?o|128:o)&255;if(e.push(d),!c)return}e.push(t>>>31&1)}}const Ud=(1<<16)*(1<<16);function xm(s){let t=s[0]=="-";t&&(s=s.slice(1));const e=1e6;let r=0,i=0;function n(o,c){const d=Number(s.slice(o,c));i*=e,r=r*e+d,r>=Ud&&(i=i+(r/Ud|0),r=r%Ud)}return n(-24,-18),n(-18,-12),n(-12,-6),n(-6),[t,r,i]}function ah(s,t){if(t>>>0<=2097151)return""+(Ud*t+(s>>>0));let e=s&16777215,r=(s>>>24|t<<8)>>>0&16777215,i=t>>16&65535,n=e+r*6777216+i*6710656,o=r+i*8147497,c=i*2,d=1e7;n>=d&&(o+=Math.floor(n/d),n%=d),o>=d&&(c+=Math.floor(o/d),o%=d);function l(u,h){let g=u?String(u):"";return h?"0000000".slice(g.length)+g:g}return l(c,0)+l(o,c)+l(n,1)}function Um(s,t){if(s>=0){for(;s>127;)t.push(s&127|128),s=s>>>7;t.push(s)}else{for(let e=0;e<9;e++)t.push(s&127|128),s=s>>7;t.push(1)}}function CC(){let s=this.buf[this.pos++],t=s&127;if(!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<7,!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<14,!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<21,!(s&128))return this.assertBounds(),t;s=this.buf[this.pos++],t|=(s&15)<<28;for(let e=5;s&128&&e<10;e++)s=this.buf[this.pos++];if(s&128)throw new Error("invalid varint");return this.assertBounds(),t>>>0}let ue;function RC(){const s=new DataView(new ArrayBuffer(8));ue=globalThis.BigInt!==void 0&&typeof s.getBigInt64=="function"&&typeof s.getBigUint64=="function"&&typeof s.setBigInt64=="function"&&typeof s.setBigUint64=="function"?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:s}:void 0}RC();function Fm(s){if(!s)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const $m=/^-?[0-9]+$/,Fd=4294967296,$d=2147483648;class Bm{constructor(t,e){this.lo=t|0,this.hi=e|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let t=this.hi*Fd+(this.lo>>>0);if(!Number.isSafeInteger(t))throw new Error("cannot convert to safe number");return t}}class ht extends Bm{static from(t){if(ue)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=ue.C(t);case"number":if(t===0)return this.ZERO;t=ue.C(t);case"bigint":if(!t)return this.ZERO;if(t<ue.UMIN)throw new Error("signed value for ulong");if(t>ue.UMAX)throw new Error("ulong too large");return ue.V.setBigUint64(0,t,!0),new ht(ue.V.getInt32(0,!0),ue.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!$m.test(t))throw new Error("string is no integer");let[e,r,i]=xm(t);if(e)throw new Error("signed value for ulong");return new ht(r,i);case"number":if(t==0)return this.ZERO;if(!Number.isSafeInteger(t))throw new Error("number is no integer");if(t<0)throw new Error("signed value for ulong");return new ht(t,t/Fd)}throw new Error("unknown value "+typeof t)}toString(){return ue?this.toBigInt().toString():ah(this.lo,this.hi)}toBigInt(){return Fm(ue),ue.V.setInt32(0,this.lo,!0),ue.V.setInt32(4,this.hi,!0),ue.V.getBigUint64(0,!0)}}ht.ZERO=new ht(0,0);class me extends Bm{static from(t){if(ue)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=ue.C(t);case"number":if(t===0)return this.ZERO;t=ue.C(t);case"bigint":if(!t)return this.ZERO;if(t<ue.MIN)throw new Error("signed long too small");if(t>ue.MAX)throw new Error("signed long too large");return ue.V.setBigInt64(0,t,!0),new me(ue.V.getInt32(0,!0),ue.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!$m.test(t))throw new Error("string is no integer");let[e,r,i]=xm(t);if(e){if(i>$d||i==$d&&r!=0)throw new Error("signed long too small")}else if(i>=$d)throw new Error("signed long too large");let n=new me(r,i);return e?n.negate():n;case"number":if(t==0)return this.ZERO;if(!Number.isSafeInteger(t))throw new Error("number is no integer");return t>0?new me(t,t/Fd):new me(-t,-t/Fd).negate()}throw new Error("unknown value "+typeof t)}isNegative(){return(this.hi&$d)!==0}negate(){let t=~this.hi,e=this.lo;return e?e=~e+1:t+=1,new me(e,t)}toString(){if(ue)return this.toBigInt().toString();if(this.isNegative()){let t=this.negate();return"-"+ah(t.lo,t.hi)}return ah(this.lo,this.hi)}toBigInt(){return Fm(ue),ue.V.setInt32(0,this.lo,!0),ue.V.setInt32(4,this.hi,!0),ue.V.getBigInt64(0,!0)}}me.ZERO=new me(0,0);const Hm={readUnknownField:!0,readerFactory:s=>new IC(s)};function kC(s){return s?Object.assign(Object.assign({},Hm),s):Hm}class IC{constructor(t,e){this.varint64=_C,this.uint32=CC,this.buf=t,this.len=t.length,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.textDecoder=e!=null?e:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let t=this.uint32(),e=t>>>3,r=t&7;if(e<=0||r<0||r>5)throw new Error("illegal tag: field no "+e+" wire type "+r);return[e,r]}skip(t){let e=this.pos;switch(t){case Ue.Varint:for(;this.buf[this.pos++]&128;);break;case Ue.Bit64:this.pos+=4;case Ue.Bit32:this.pos+=4;break;case Ue.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Ue.StartGroup:let i;for(;(i=this.tag()[1])!==Ue.EndGroup;)this.skip(i);break;default:throw new Error("cant skip wire type "+t)}return this.assertBounds(),this.buf.subarray(e,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)}int64(){return new me(...this.varint64())}uint64(){return new ht(...this.varint64())}sint64(){let[t,e]=this.varint64(),r=-(t&1);return t=(t>>>1|(e&1)<<31)^r,e=e>>>1^r,new me(t,e)}bool(){let[t,e]=this.varint64();return t!==0||e!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new ht(this.sfixed32(),this.sfixed32())}sfixed64(){return new me(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let t=this.uint32(),e=this.pos;return this.pos+=t,this.assertBounds(),this.buf.subarray(e,e+t)}string(){return this.textDecoder.decode(this.bytes())}}function se(s,t){if(!s)throw new Error(t)}const AC=34028234663852886e22,MC=-34028234663852886e22,OC=4294967295,DC=2147483647,NC=-2147483648;function To(s){if(typeof s!="number")throw new Error("invalid int 32: "+typeof s);if(!Number.isInteger(s)||s>DC||s<NC)throw new Error("invalid int 32: "+s)}function Bd(s){if(typeof s!="number")throw new Error("invalid uint 32: "+typeof s);if(!Number.isInteger(s)||s>OC||s<0)throw new Error("invalid uint 32: "+s)}function oh(s){if(typeof s!="number")throw new Error("invalid float 32: "+typeof s);if(Number.isFinite(s)&&(s>AC||s<MC))throw new Error("invalid float 32: "+s)}const qm={writeUnknownFields:!0,writerFactory:()=>new LC};function VC(s){return s?Object.assign(Object.assign({},qm),s):qm}class LC{constructor(t){this.stack=[],this.textEncoder=t!=null?t:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let t=0;for(let i=0;i<this.chunks.length;i++)t+=this.chunks[i].length;let e=new Uint8Array(t),r=0;for(let i=0;i<this.chunks.length;i++)e.set(this.chunks[i],r),r+=this.chunks[i].length;return this.chunks=[],e}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let t=this.finish(),e=this.stack.pop();if(!e)throw new Error("invalid state, fork stack empty");return this.chunks=e.chunks,this.buf=e.buf,this.uint32(t.byteLength),this.raw(t)}tag(t,e){return this.uint32((t<<3|e)>>>0)}raw(t){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(t),this}uint32(t){for(Bd(t);t>127;)this.buf.push(t&127|128),t=t>>>7;return this.buf.push(t),this}int32(t){return To(t),Um(t,this.buf),this}bool(t){return this.buf.push(t?1:0),this}bytes(t){return this.uint32(t.byteLength),this.raw(t)}string(t){let e=this.textEncoder.encode(t);return this.uint32(e.byteLength),this.raw(e)}float(t){oh(t);let e=new Uint8Array(4);return new DataView(e.buffer).setFloat32(0,t,!0),this.raw(e)}double(t){let e=new Uint8Array(8);return new DataView(e.buffer).setFloat64(0,t,!0),this.raw(e)}fixed32(t){Bd(t);let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),this.raw(e)}sfixed32(t){To(t);let e=new Uint8Array(4);return new DataView(e.buffer).setInt32(0,t,!0),this.raw(e)}sint32(t){return To(t),t=(t<<1^t>>31)>>>0,Um(t,this.buf),this}sfixed64(t){let e=new Uint8Array(8),r=new DataView(e.buffer),i=me.from(t);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(e)}fixed64(t){let e=new Uint8Array(8),r=new DataView(e.buffer),i=ht.from(t);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(e)}int64(t){let e=me.from(t);return nh(e.lo,e.hi,this.buf),this}sint64(t){let e=me.from(t),r=e.hi>>31,i=e.lo<<1^r,n=(e.hi<<1|e.lo>>>31)^r;return nh(i,n,this.buf),this}uint64(t){let e=ht.from(t);return nh(e.lo,e.hi,this.buf),this}}const jm={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},Gm={ignoreUnknownFields:!1};function xC(s){return s?Object.assign(Object.assign({},Gm),s):Gm}function UC(s){return s?Object.assign(Object.assign({},jm),s):jm}const Wm=Symbol.for("protobuf-ts/message-type");function Jm(s){let t=!1;const e=[];for(let r=0;r<s.length;r++){let i=s.charAt(r);i=="_"?t=!0:/\d/.test(i)?(e.push(i),t=!0):t?(e.push(i.toUpperCase()),t=!1):r==0?e.push(i.toLowerCase()):e.push(i)}return e.join("")}var A;(function(s){s[s.DOUBLE=1]="DOUBLE",s[s.FLOAT=2]="FLOAT",s[s.INT64=3]="INT64",s[s.UINT64=4]="UINT64",s[s.INT32=5]="INT32",s[s.FIXED64=6]="FIXED64",s[s.FIXED32=7]="FIXED32",s[s.BOOL=8]="BOOL",s[s.STRING=9]="STRING",s[s.BYTES=12]="BYTES",s[s.UINT32=13]="UINT32",s[s.SFIXED32=15]="SFIXED32",s[s.SFIXED64=16]="SFIXED64",s[s.SINT32=17]="SINT32",s[s.SINT64=18]="SINT64"})(A||(A={}));var Gs;(function(s){s[s.BIGINT=0]="BIGINT",s[s.STRING=1]="STRING",s[s.NUMBER=2]="NUMBER"})(Gs||(Gs={}));var Hd;(function(s){s[s.NO=0]="NO",s[s.PACKED=1]="PACKED",s[s.UNPACKED=2]="UNPACKED"})(Hd||(Hd={}));function FC(s){var t,e,r,i;return s.localName=(t=s.localName)!==null&&t!==void 0?t:Jm(s.name),s.jsonName=(e=s.jsonName)!==null&&e!==void 0?e:Jm(s.name),s.repeat=(r=s.repeat)!==null&&r!==void 0?r:Hd.NO,s.opt=(i=s.opt)!==null&&i!==void 0?i:s.repeat||s.oneof?!1:s.kind=="message",s}function $C(s){if(typeof s!="object"||s===null||!s.hasOwnProperty("oneofKind"))return!1;switch(typeof s.oneofKind){case"string":return s[s.oneofKind]===void 0?!1:Object.keys(s).length==2;case"undefined":return Object.keys(s).length==1;default:return!1}}class BC{constructor(t){var e;this.fields=(e=t.fields)!==null&&e!==void 0?e:[]}prepare(){if(this.data)return;const t=[],e=[],r=[];for(let i of this.fields)if(i.oneof)r.includes(i.oneof)||(r.push(i.oneof),t.push(i.oneof),e.push(i.oneof));else switch(e.push(i.localName),i.kind){case"scalar":case"enum":(!i.opt||i.repeat)&&t.push(i.localName);break;case"message":i.repeat&&t.push(i.localName);break;case"map":t.push(i.localName);break}this.data={req:t,known:e,oneofs:Object.values(r)}}is(t,e,r=!1){if(e<0)return!0;if(t==null||typeof t!="object")return!1;this.prepare();let i=Object.keys(t),n=this.data;if(i.length<n.req.length||n.req.some(o=>!i.includes(o))||!r&&i.some(o=>!n.known.includes(o)))return!1;if(e<1)return!0;for(const o of n.oneofs){const c=t[o];if(!$C(c))return!1;if(c.oneofKind===void 0)continue;const d=this.fields.find(l=>l.localName===c.oneofKind);if(!d||!this.field(c[c.oneofKind],d,r,e))return!1}for(const o of this.fields)if(o.oneof===void 0&&!this.field(t[o.localName],o,r,e))return!1;return!0}field(t,e,r,i){let n=e.repeat;switch(e.kind){case"scalar":return t===void 0?e.opt:n?this.scalars(t,e.T,i,e.L):this.scalar(t,e.T,e.L);case"enum":return t===void 0?e.opt:n?this.scalars(t,A.INT32,i):this.scalar(t,A.INT32);case"message":return t===void 0?!0:n?this.messages(t,e.T(),r,i):this.message(t,e.T(),r,i);case"map":if(typeof t!="object"||t===null)return!1;if(i<2)return!0;if(!this.mapKeys(t,e.K,i))return!1;switch(e.V.kind){case"scalar":return this.scalars(Object.values(t),e.V.T,i,e.V.L);case"enum":return this.scalars(Object.values(t),A.INT32,i);case"message":return this.messages(Object.values(t),e.V.T(),r,i)}break}return!0}message(t,e,r,i){return r?e.isAssignable(t,i):e.is(t,i)}messages(t,e,r,i){if(!Array.isArray(t))return!1;if(i<2)return!0;if(r){for(let n=0;n<t.length&&n<i;n++)if(!e.isAssignable(t[n],i-1))return!1}else for(let n=0;n<t.length&&n<i;n++)if(!e.is(t[n],i-1))return!1;return!0}scalar(t,e,r){let i=typeof t;switch(e){case A.UINT64:case A.FIXED64:case A.INT64:case A.SFIXED64:case A.SINT64:switch(r){case Gs.BIGINT:return i=="bigint";case Gs.NUMBER:return i=="number"&&!isNaN(t);default:return i=="string"}case A.BOOL:return i=="boolean";case A.STRING:return i=="string";case A.BYTES:return t instanceof Uint8Array;case A.DOUBLE:case A.FLOAT:return i=="number"&&!isNaN(t);default:return i=="number"&&Number.isInteger(t)}}scalars(t,e,r,i){if(!Array.isArray(t))return!1;if(r<2)return!0;if(Array.isArray(t)){for(let n=0;n<t.length&&n<r;n++)if(!this.scalar(t[n],e,i))return!1}return!0}mapKeys(t,e,r){let i=Object.keys(t);switch(e){case A.INT32:case A.FIXED32:case A.SFIXED32:case A.SINT32:case A.UINT32:return this.scalars(i.slice(0,r).map(n=>parseInt(n)),e,r);case A.BOOL:return this.scalars(i.slice(0,r).map(n=>n=="true"?!0:n=="false"?!1:n),e,r);default:return this.scalars(i,e,r,Gs.STRING)}}}function ws(s,t){switch(t){case Gs.BIGINT:return s.toBigInt();case Gs.NUMBER:return s.toNumber();default:return s.toString()}}class HC{constructor(t){this.info=t}prepare(){var t;if(this.fMap===void 0){this.fMap={};const e=(t=this.info.fields)!==null&&t!==void 0?t:[];for(const r of e)this.fMap[r.name]=r,this.fMap[r.jsonName]=r,this.fMap[r.localName]=r}}assert(t,e,r){if(!t){let i=ih(r);throw(i=="number"||i=="boolean")&&(i=r.toString()),new Error(`Cannot parse JSON ${i} for ${this.info.typeName}#${e}`)}}read(t,e,r){this.prepare();const i=[];for(const[n,o]of Object.entries(t)){const c=this.fMap[n];if(!c){if(!r.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${n}`);continue}const d=c.localName;let l;if(c.oneof){if(o===null&&(c.kind!=="enum"||c.T()[0]!=="google.protobuf.NullValue"))continue;if(i.includes(c.oneof))throw new Error(`Multiple members of the oneof group "${c.oneof}" of ${this.info.typeName} are present in JSON.`);i.push(c.oneof),l=e[c.oneof]={oneofKind:d}}else l=e;if(c.kind=="map"){if(o===null)continue;this.assert(bC(o),c.name,o);const u=l[d];for(const[h,g]of Object.entries(o)){this.assert(g!==null,c.name+" map value",null);let v;switch(c.V.kind){case"message":v=c.V.T().internalJsonRead(g,r);break;case"enum":if(v=this.enum(c.V.T(),g,c.name,r.ignoreUnknownFields),v===!1)continue;break;case"scalar":v=this.scalar(g,c.V.T,c.V.L,c.name);break}this.assert(v!==void 0,c.name+" map value",g);let E=h;c.K==A.BOOL&&(E=E=="true"?!0:E=="false"?!1:E),E=this.scalar(E,c.K,Gs.STRING,c.name).toString(),u[E]=v}}else if(c.repeat){if(o===null)continue;this.assert(Array.isArray(o),c.name,o);const u=l[d];for(const h of o){this.assert(h!==null,c.name,null);let g;switch(c.kind){case"message":g=c.T().internalJsonRead(h,r);break;case"enum":if(g=this.enum(c.T(),h,c.name,r.ignoreUnknownFields),g===!1)continue;break;case"scalar":g=this.scalar(h,c.T,c.L,c.name);break}this.assert(g!==void 0,c.name,o),u.push(g)}}else switch(c.kind){case"message":if(o===null&&c.T().typeName!="google.protobuf.Value"){this.assert(c.oneof===void 0,c.name+" (oneof member)",null);continue}l[d]=c.T().internalJsonRead(o,r,l[d]);break;case"enum":if(o===null)continue;let u=this.enum(c.T(),o,c.name,r.ignoreUnknownFields);if(u===!1)continue;l[d]=u;break;case"scalar":if(o===null)continue;l[d]=this.scalar(o,c.T,c.L,c.name);break}}}enum(t,e,r,i){if(t[0]=="google.protobuf.NullValue"&&se(e===null||e==="NULL_VALUE",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} only accepts null.`),e===null)return 0;switch(typeof e){case"number":return se(Number.isInteger(e),`Unable to parse field ${this.info.typeName}#${r}, enum can only be integral number, got ${e}.`),e;case"string":let n=e;t[2]&&e.substring(0,t[2].length)===t[2]&&(n=e.substring(t[2].length));let o=t[1][n];return typeof o=="undefined"&&i?!1:(se(typeof o=="number",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} has no value for "${e}".`),o)}se(!1,`Unable to parse field ${this.info.typeName}#${r}, cannot parse enum value from ${typeof e}".`)}scalar(t,e,r,i){let n;try{switch(e){case A.DOUBLE:case A.FLOAT:if(t===null)return 0;if(t==="NaN")return Number.NaN;if(t==="Infinity")return Number.POSITIVE_INFINITY;if(t==="-Infinity")return Number.NEGATIVE_INFINITY;if(t===""){n="empty string";break}if(typeof t=="string"&&t.trim().length!==t.length){n="extra whitespace";break}if(typeof t!="string"&&typeof t!="number")break;let o=Number(t);if(Number.isNaN(o)){n="not a number";break}if(!Number.isFinite(o)){n="too large or small";break}return e==A.FLOAT&&oh(o),o;case A.INT32:case A.FIXED32:case A.SFIXED32:case A.SINT32:case A.UINT32:if(t===null)return 0;let c;if(typeof t=="number"?c=t:t===""?n="empty string":typeof t=="string"&&(t.trim().length!==t.length?n="extra whitespace":c=Number(t)),c===void 0)break;return e==A.UINT32?Bd(c):To(c),c;case A.INT64:case A.SFIXED64:case A.SINT64:if(t===null)return ws(me.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return ws(me.from(t),r);case A.FIXED64:case A.UINT64:if(t===null)return ws(ht.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return ws(ht.from(t),r);case A.BOOL:if(t===null)return!1;if(typeof t!="boolean")break;return t;case A.STRING:if(t===null)return"";if(typeof t!="string"){n="extra whitespace";break}try{encodeURIComponent(t)}catch(d){d="invalid UTF8";break}return t;case A.BYTES:if(t===null||t==="")return new Uint8Array(0);if(typeof t!="string")break;return wC(t)}}catch(o){n=o.message}this.assert(!1,i+(n?" - "+n:""),t)}}class qC{constructor(t){var e;this.fields=(e=t.fields)!==null&&e!==void 0?e:[]}write(t,e){const r={},i=t;for(const n of this.fields){if(!n.oneof){let l=this.field(n,i[n.localName],e);l!==void 0&&(r[e.useProtoFieldName?n.name:n.jsonName]=l);continue}const o=i[n.oneof];if(o.oneofKind!==n.localName)continue;const c=n.kind=="scalar"||n.kind=="enum"?Object.assign(Object.assign({},e),{emitDefaultValues:!0}):e;let d=this.field(n,o[n.localName],c);se(d!==void 0),r[e.useProtoFieldName?n.name:n.jsonName]=d}return r}field(t,e,r){let i;if(t.kind=="map"){se(typeof e=="object"&&e!==null);const n={};switch(t.V.kind){case"scalar":for(const[d,l]of Object.entries(e)){const u=this.scalar(t.V.T,l,t.name,!1,!0);se(u!==void 0),n[d.toString()]=u}break;case"message":const o=t.V.T();for(const[d,l]of Object.entries(e)){const u=this.message(o,l,t.name,r);se(u!==void 0),n[d.toString()]=u}break;case"enum":const c=t.V.T();for(const[d,l]of Object.entries(e)){se(l===void 0||typeof l=="number");const u=this.enum(c,l,t.name,!1,!0,r.enumAsInteger);se(u!==void 0),n[d.toString()]=u}break}(r.emitDefaultValues||Object.keys(n).length>0)&&(i=n)}else if(t.repeat){se(Array.isArray(e));const n=[];switch(t.kind){case"scalar":for(let d=0;d<e.length;d++){const l=this.scalar(t.T,e[d],t.name,t.opt,!0);se(l!==void 0),n.push(l)}break;case"enum":const o=t.T();for(let d=0;d<e.length;d++){se(e[d]===void 0||typeof e[d]=="number");const l=this.enum(o,e[d],t.name,t.opt,!0,r.enumAsInteger);se(l!==void 0),n.push(l)}break;case"message":const c=t.T();for(let d=0;d<e.length;d++){const l=this.message(c,e[d],t.name,r);se(l!==void 0),n.push(l)}break}(r.emitDefaultValues||n.length>0||r.emitDefaultValues)&&(i=n)}else switch(t.kind){case"scalar":i=this.scalar(t.T,e,t.name,t.opt,r.emitDefaultValues);break;case"enum":i=this.enum(t.T(),e,t.name,t.opt,r.emitDefaultValues,r.enumAsInteger);break;case"message":i=this.message(t.T(),e,t.name,r);break}return i}enum(t,e,r,i,n,o){if(t[0]=="google.protobuf.NullValue")return!n&&!i?void 0:null;if(e===void 0){se(i);return}if(!(e===0&&!n&&!i))return se(typeof e=="number"),se(Number.isInteger(e)),o||!t[1].hasOwnProperty(e)?e:t[2]?t[2]+t[1][e]:t[1][e]}message(t,e,r,i){return e===void 0?i.emitDefaultValues?null:void 0:t.internalJsonWrite(e,i)}scalar(t,e,r,i,n){if(e===void 0){se(i);return}const o=n||i;switch(t){case A.INT32:case A.SFIXED32:case A.SINT32:return e===0?o?0:void 0:(To(e),e);case A.FIXED32:case A.UINT32:return e===0?o?0:void 0:(Bd(e),e);case A.FLOAT:oh(e);case A.DOUBLE:return e===0?o?0:void 0:(se(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e);case A.STRING:return e===""?o?"":void 0:(se(typeof e=="string"),e);case A.BOOL:return e===!1?o?!1:void 0:(se(typeof e=="boolean"),e);case A.UINT64:case A.FIXED64:se(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let c=ht.from(e);return c.isZero()&&!o?void 0:c.toString();case A.INT64:case A.SFIXED64:case A.SINT64:se(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let d=me.from(e);return d.isZero()&&!o?void 0:d.toString();case A.BYTES:return se(e instanceof Uint8Array),e.byteLength?PC(e):o?"":void 0}}}function ch(s,t=Gs.STRING){switch(s){case A.BOOL:return!1;case A.UINT64:case A.FIXED64:return ws(ht.ZERO,t);case A.INT64:case A.SFIXED64:case A.SINT64:return ws(me.ZERO,t);case A.DOUBLE:case A.FLOAT:return 0;case A.BYTES:return new Uint8Array(0);case A.STRING:return"";default:return 0}}class jC{constructor(t){this.info=t}prepare(){var t;if(!this.fieldNoToField){const e=(t=this.info.fields)!==null&&t!==void 0?t:[];this.fieldNoToField=new Map(e.map(r=>[r.no,r]))}}read(t,e,r,i){this.prepare();const n=i===void 0?t.len:t.pos+i;for(;t.pos<n;){const[o,c]=t.tag(),d=this.fieldNoToField.get(o);if(!d){let g=r.readUnknownField;if(g=="throw")throw new Error(`Unknown field ${o} (wire type ${c}) for ${this.info.typeName}`);let v=t.skip(c);g!==!1&&(g===!0?xd.onRead:g)(this.info.typeName,e,o,c,v);continue}let l=e,u=d.repeat,h=d.localName;switch(d.oneof&&(l=l[d.oneof],l.oneofKind!==h&&(l=e[d.oneof]={oneofKind:h})),d.kind){case"scalar":case"enum":let g=d.kind=="enum"?A.INT32:d.T,v=d.kind=="scalar"?d.L:void 0;if(u){let P=l[h];if(c==Ue.LengthDelimited&&g!=A.STRING&&g!=A.BYTES){let w=t.uint32()+t.pos;for(;t.pos<w;)P.push(this.scalar(t,g,v))}else P.push(this.scalar(t,g,v))}else l[h]=this.scalar(t,g,v);break;case"message":if(u){let P=l[h],w=d.T().internalBinaryRead(t,t.uint32(),r);P.push(w)}else l[h]=d.T().internalBinaryRead(t,t.uint32(),r,l[h]);break;case"map":let[E,b]=this.mapEntry(d,t,r);l[h][E]=b;break}}}mapEntry(t,e,r){let i=e.uint32(),n=e.pos+i,o,c;for(;e.pos<n;){let[d,l]=e.tag();switch(d){case 1:t.K==A.BOOL?o=e.bool().toString():o=this.scalar(e,t.K,Gs.STRING);break;case 2:switch(t.V.kind){case"scalar":c=this.scalar(e,t.V.T,t.V.L);break;case"enum":c=e.int32();break;case"message":c=t.V.T().internalBinaryRead(e,e.uint32(),r);break}break;default:throw new Error(`Unknown field ${d} (wire type ${l}) in map entry for ${this.info.typeName}#${t.name}`)}}if(o===void 0){let d=ch(t.K);o=t.K==A.BOOL?d.toString():d}if(c===void 0)switch(t.V.kind){case"scalar":c=ch(t.V.T,t.V.L);break;case"enum":c=0;break;case"message":c=t.V.T().create();break}return[o,c]}scalar(t,e,r){switch(e){case A.INT32:return t.int32();case A.STRING:return t.string();case A.BOOL:return t.bool();case A.DOUBLE:return t.double();case A.FLOAT:return t.float();case A.INT64:return ws(t.int64(),r);case A.UINT64:return ws(t.uint64(),r);case A.FIXED64:return ws(t.fixed64(),r);case A.FIXED32:return t.fixed32();case A.BYTES:return t.bytes();case A.UINT32:return t.uint32();case A.SFIXED32:return t.sfixed32();case A.SFIXED64:return ws(t.sfixed64(),r);case A.SINT32:return t.sint32();case A.SINT64:return ws(t.sint64(),r)}}}class GC{constructor(t){this.info=t}prepare(){if(!this.fields){const t=this.info.fields?this.info.fields.concat():[];this.fields=t.sort((e,r)=>e.no-r.no)}}write(t,e,r){this.prepare();for(const n of this.fields){let o,c,d=n.repeat,l=n.localName;if(n.oneof){const u=t[n.oneof];if(u.oneofKind!==l)continue;o=u[l],c=!0}else o=t[l],c=!1;switch(n.kind){case"scalar":case"enum":let u=n.kind=="enum"?A.INT32:n.T;if(d)if(se(Array.isArray(o)),d==Hd.PACKED)this.packed(e,u,n.no,o);else for(const h of o)this.scalar(e,u,n.no,h,!0);else o===void 0?se(n.opt):this.scalar(e,u,n.no,o,c||n.opt);break;case"message":if(d){se(Array.isArray(o));for(const h of o)this.message(e,r,n.T(),n.no,h)}else this.message(e,r,n.T(),n.no,o);break;case"map":se(typeof o=="object"&&o!==null);for(const[h,g]of Object.entries(o))this.mapEntry(e,r,n,h,g);break}}let i=r.writeUnknownFields;i!==!1&&(i===!0?xd.onWrite:i)(this.info.typeName,t,e)}mapEntry(t,e,r,i,n){t.tag(r.no,Ue.LengthDelimited),t.fork();let o=i;switch(r.K){case A.INT32:case A.FIXED32:case A.UINT32:case A.SFIXED32:case A.SINT32:o=Number.parseInt(i);break;case A.BOOL:se(i=="true"||i=="false"),o=i=="true";break}switch(this.scalar(t,r.K,1,o,!0),r.V.kind){case"scalar":this.scalar(t,r.V.T,2,n,!0);break;case"enum":this.scalar(t,A.INT32,2,n,!0);break;case"message":this.message(t,e,r.V.T(),2,n);break}t.join()}message(t,e,r,i,n){n!==void 0&&(r.internalBinaryWrite(n,t.tag(i,Ue.LengthDelimited).fork(),e),t.join())}scalar(t,e,r,i,n){let[o,c,d]=this.scalarInfo(e,i);(!d||n)&&(t.tag(r,o),t[c](i))}packed(t,e,r,i){if(!i.length)return;se(e!==A.BYTES&&e!==A.STRING),t.tag(r,Ue.LengthDelimited),t.fork();let[,n]=this.scalarInfo(e);for(let o=0;o<i.length;o++)t[n](i[o]);t.join()}scalarInfo(t,e){let r=Ue.Varint,i,n=e===void 0,o=e===0;switch(t){case A.INT32:i="int32";break;case A.STRING:o=n||!e.length,r=Ue.LengthDelimited,i="string";break;case A.BOOL:o=e===!1,i="bool";break;case A.UINT32:i="uint32";break;case A.DOUBLE:r=Ue.Bit64,i="double";break;case A.FLOAT:r=Ue.Bit32,i="float";break;case A.INT64:o=n||me.from(e).isZero(),i="int64";break;case A.UINT64:o=n||ht.from(e).isZero(),i="uint64";break;case A.FIXED64:o=n||ht.from(e).isZero(),r=Ue.Bit64,i="fixed64";break;case A.BYTES:o=n||!e.byteLength,r=Ue.LengthDelimited,i="bytes";break;case A.FIXED32:r=Ue.Bit32,i="fixed32";break;case A.SFIXED32:r=Ue.Bit32,i="sfixed32";break;case A.SFIXED64:o=n||me.from(e).isZero(),r=Ue.Bit64,i="sfixed64";break;case A.SINT32:i="sint32";break;case A.SINT64:o=n||me.from(e).isZero(),i="sint64";break}return[r,i,n||o]}}function WC(s){const t=s.messagePrototype?Object.create(s.messagePrototype):Object.defineProperty({},Wm,{value:s});for(let e of s.fields){let r=e.localName;if(!e.opt)if(e.oneof)t[e.oneof]={oneofKind:void 0};else if(e.repeat)t[r]=[];else switch(e.kind){case"scalar":t[r]=ch(e.T,e.L);break;case"enum":t[r]=0;break;case"map":t[r]={};break}}return t}function dh(s,t,e){let r,i=e,n;for(let o of s.fields){let c=o.localName;if(o.oneof){const d=i[o.oneof];if((d==null?void 0:d.oneofKind)==null)continue;if(r=d[c],n=t[o.oneof],n.oneofKind=d.oneofKind,r==null){delete n[c];continue}}else if(r=i[c],n=t,r==null)continue;switch(o.repeat&&(n[c].length=r.length),o.kind){case"scalar":case"enum":if(o.repeat)for(let l=0;l<r.length;l++)n[c][l]=r[l];else n[c]=r;break;case"message":let d=o.T();if(o.repeat)for(let l=0;l<r.length;l++)n[c][l]=d.create(r[l]);else n[c]===void 0?n[c]=d.create(r):d.mergePartial(n[c],r);break;case"map":switch(o.V.kind){case"scalar":case"enum":Object.assign(n[c],r);break;case"message":let l=o.V.T();for(let u of Object.keys(r))n[c][u]=l.create(r[u]);break}break}}}function JC(s,t,e){if(t===e)return!0;if(!t||!e)return!1;for(let r of s.fields){let i=r.localName,n=r.oneof?t[r.oneof][i]:t[i],o=r.oneof?e[r.oneof][i]:e[i];switch(r.kind){case"enum":case"scalar":let c=r.kind=="enum"?A.INT32:r.T;if(!(r.repeat?zm(c,n,o):Km(c,n,o)))return!1;break;case"map":if(!(r.V.kind=="message"?Ym(r.V.T(),qd(n),qd(o)):zm(r.V.kind=="enum"?A.INT32:r.V.T,qd(n),qd(o))))return!1;break;case"message":let d=r.T();if(!(r.repeat?Ym(d,n,o):d.equals(n,o)))return!1;break}}return!0}const qd=Object.values;function Km(s,t,e){if(t===e)return!0;if(s!==A.BYTES)return!1;let r=t,i=e;if(r.length!==i.length)return!1;for(let n=0;n<r.length;n++)if(r[n]!=i[n])return!1;return!0}function zm(s,t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!Km(s,t[r],e[r]))return!1;return!0}function Ym(s,t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!s.equals(t[r],e[r]))return!1;return!0}const KC=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));class S{constructor(t,e,r){this.defaultCheckDepth=16,this.typeName=t,this.fields=e.map(FC),this.options=r!=null?r:{},this.messagePrototype=Object.create(null,Object.assign(Object.assign({},KC),{[Wm]:{value:this}})),this.refTypeCheck=new BC(this),this.refJsonReader=new HC(this),this.refJsonWriter=new qC(this),this.refBinReader=new jC(this),this.refBinWriter=new GC(this)}create(t){let e=WC(this);return t!==void 0&&dh(this,e,t),e}clone(t){let e=this.create();return dh(this,e,t),e}equals(t,e){return JC(this,t,e)}is(t,e=this.defaultCheckDepth){return this.refTypeCheck.is(t,e,!1)}isAssignable(t,e=this.defaultCheckDepth){return this.refTypeCheck.is(t,e,!0)}mergePartial(t,e){dh(this,t,e)}fromBinary(t,e){let r=kC(e);return this.internalBinaryRead(r.readerFactory(t),t.byteLength,r)}fromJson(t,e){return this.internalJsonRead(t,xC(e))}fromJsonString(t,e){let r=JSON.parse(t);return this.fromJson(r,e)}toJson(t,e){return this.internalJsonWrite(t,UC(e))}toJsonString(t,e){var r;let i=this.toJson(t,e);return JSON.stringify(i,null,(r=e==null?void 0:e.prettySpaces)!==null&&r!==void 0?r:0)}toBinary(t,e){let r=VC(e);return this.internalBinaryWrite(t,r.writerFactory(),r).finish()}internalJsonRead(t,e,r){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let i=r!=null?r:this.create();return this.refJsonReader.read(t,i,e),i}throw new Error(`Unable to parse message ${this.typeName} from JSON ${ih(t)}.`)}internalJsonWrite(t,e){return this.refJsonWriter.write(t,e)}internalBinaryWrite(t,e,r){return this.refBinWriter.write(t,e,r),e}internalBinaryRead(t,e,r,i){let n=i!=null?i:this.create();return this.refBinReader.read(t,n,r,e),n}}var or;(function(s){s[s.PUBLISHER=0]="PUBLISHER",s[s.SUBSCRIBER=1]="SUBSCRIBER"})(or||(or={}));var Ws;(function(s){s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO"})(Ws||(Ws={}));class zC extends S{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 Qm=new zC;class YC extends S{constructor(){super("media.HeaderExtension",[{no:1,name:"direction",kind:"scalar",opt:!0,T:9},{no:2,name:"uri",kind:"scalar",T:9}])}}const QC=new YC;class XC extends S{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new XC;class ZC extends S{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",or]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const Ps=new ZC;class eR extends S{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 tR=new eR;class sR extends S{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:()=>Ps},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>tR}])}}const rR=new sR;class iR extends S{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 nR=new iR;class aR extends S{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Ps},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const Xm=new aR;class oR extends S{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Ps}])}}const cR=new oR;class dR extends S{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Ps}])}}new dR;class lR extends S{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 uR=new lR;class hR extends S{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 pR=new hR;class gR extends S{constructor(){super("media.ProducerEntry",[{no:1,name:"producing_transport_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9}])}}new gR;class mR extends S{constructor(){super("media.ConsumerEntry",[{no:1,name:"consuming_transport_id",kind:"scalar",T:9},{no:2,name:"consumer_id",kind:"scalar",T:9}])}}new mR;class fR extends S{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",Ws]},{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:()=>Qm}])}}const Eo=new fR;class vR extends S{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Eo},{no:3,name:"producer_track",kind:"message",T:()=>pR},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const SR=new vR;class yR extends S{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>SR}}])}}const Zm=new yR;class TR extends S{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>sf},{no:2,name:"receiver",kind:"message",T:()=>sf}])}}const ef=new TR;class ER extends S{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>Qm},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>QC}])}}const tf=new ER;class bR extends S{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>tf},{no:2,name:"video",kind:"message",T:()=>tf}])}}const sf=new bR;class wR extends S{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 PR=new wR;class _R extends S{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 rf=new _R;class CR extends S{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 RR=new CR;class kR extends S{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:()=>RR},{no:9,name:"capabilities",kind:"message",T:()=>ef}])}}const IR=new kR;class AR extends S{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const MR=new AR;class OR extends S{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const DR=new OR;class NR extends S{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 NR;class VR extends S{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:()=>PR},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:6,name:"simulcast",kind:"message",T:()=>rf}])}}const LR=new VR;class xR extends S{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>LR},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const UR=new xR;class FR extends S{constructor(){super("media.edge.UpdateConsumerSimulcastConfigRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"simulcast",kind:"message",T:()=>rf},{no:3,name:"producing_transport_id",kind:"scalar",T:9},{no:4,name:"mid",kind:"scalar",T:9}])}}const $R=new FR;class BR extends S{constructor(){super("media.edge.UpdateConsumersSimulcastConfigRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>$R},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const HR=new BR;class qR extends S{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:()=>Ps},{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 jR=new qR;class GR extends S{constructor(){super("media.edge.SelectedPeersRequest",[])}}new GR;class WR extends S{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const JR=new WR;class KR extends S{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const jd=new KR;class zR extends S{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}new zR;class YR extends S{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Ps},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const QR=new YR;class XR extends S{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>Ps},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const ZR=new XR;class ek extends S{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new ek;class tk extends S{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const nf=new tk;class sk extends S{constructor(){super("media.edge.PeerDisplayNameEditRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}const rk=new sk;class ik extends S{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 nk=new ik;class ak extends S{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 ok=new ak;class ck extends S{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 dk=new ck;class lk extends S{constructor(){super("media.edge.ErrorResponse",[{no:1,name:"error_message",kind:"scalar",T:9},{no:2,name:"event_id",kind:"scalar",T:5}])}}const uk=new lk;class hk extends S{constructor(){super("media.edge.EmptyResponse",[])}}new hk;class pk extends S{constructor(){super("media.edge.RoomParticipants",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"producer_states",kind:"message",repeat:1,T:()=>Eo},{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:()=>ef}])}}const af=new pk;class gk extends S{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 lh=new gk;class mk extends S{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const fk=new mk;class vk extends S{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>fk}])}}const of=new vk;class Sk extends S{constructor(){super("media.edge.PeerJoinResponse",[])}}new Sk;class yk extends S{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>dk},{no:2,name:"participants",kind:"message",repeat:1,T:()=>af},{no:3,name:"selected_peers",kind:"message",T:()=>lh},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const uh=new yk;class Tk extends S{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const Ek=new Tk;class bk extends S{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Zm}])}}new bk;class wk extends S{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Zm},{no:3,name:"description",kind:"message",T:()=>Ps}])}}const Pk=new wk;class _k extends S{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:()=>Ps}])}}const Ck=new _k;class Rk extends S{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>uR}])}}new Rk;class kk extends S{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new kk;class Ik extends S{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new Ik;class Ak extends S{constructor(){super("media.edge.ProducerToggleResponse",[])}}new Ak;class Mk extends S{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new Mk;class Ok extends S{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>Ps}])}}const Dk=new Ok;class Nk extends S{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>Ps}])}}const Vk=new Nk;class Lk extends S{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new Lk;class xk extends S{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new xk;class Uk extends S{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new Uk;class Fk extends S{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const $k=new Fk;class Bk extends S{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Hk=new Bk;class qk extends S{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const jk=new qk;class Gk extends S{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>af}])}}const cf=new Gk;class Wk extends S{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const df=new Wk;class Jk extends S{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>df},{no:3,name:"screenshare",kind:"message",T:()=>df}])}}const Kk=new Jk;class zk extends S{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>Xm},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>Kk}])}}new zk;class Yk extends S{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Eo}])}}const Qk=new Yk;class Xk extends S{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Eo},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const lf=new Xk;class Zk extends S{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Eo}])}}const eI=new Zk;class tI extends S{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const hh=new tI;class sI extends S{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const uf=new sI;class rI extends S{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new rI;class iI extends S{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new iI;class nI extends S{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new nI;class aI extends S{constructor(){super("media.edge.PeerDisplayNameEditBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}new aI;class oI extends S{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new oI;class cI extends S{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new cI;class dI extends S{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}])}}const ph=new dI;class lI extends S{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 lI;class uI extends S{constructor(){super("socket.api.ErrorMessage",[{no:1,name:"code",kind:"scalar",opt:!0,T:5},{no:2,name:"message",kind:"scalar",T:9}])}}const hI=new uI;var _i;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(_i||(_i={}));var cr;(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"})(cr||(cr={}));var gh;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(gh||(gh={}));var mh;(function(s){s[s.PEERS=0]="PEERS",s[s.ROOMS=1]="ROOMS"})(mh||(mh={}));var Gd;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(Gd||(Gd={}));class pI extends S{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 gI=new pI;class mI extends S{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",cr,"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:()=>gI}])}}const Wd=new mI;class fI extends S{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>Wd}])}}const $n=new fI;class vI extends S{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",cr,"STAGE_TYPE_"]}])}}const hf=new vI;class SI extends S{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 yI=new SI;class TI extends S{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>Wd}])}}const fh=new TI;class EI extends S{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const pf=new EI;class bI extends S{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:()=>PI},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const gf=new bI;class wI extends S{constructor(){super("socket.room.ActiveRecording",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",_i]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const PI=new wI;class _I extends S{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>gf}])}}const mf=new _I;class CI extends S{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const ff=new CI;class RI extends S{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 RI;class kI extends S{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Wd},{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",Gd,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const II=new kI;class AI extends S{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Wd},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const MI=new AI;class OI extends S{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>gf}])}}new OI;class DI extends S{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new DI;class NI extends S{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 vh=new NI;class VI extends S{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 LI=new VI;class xI extends S{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:()=>LI}])}}const vf=new xI;class UI extends S{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>vf},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>vf}])}}const FI=new UI;class $I extends S{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const BI=new $I;class HI extends S{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>BI}])}}const qI=new HI;class jI extends S{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:()=>vh}])}}const GI=new jI;class WI extends S{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>GI}])}}const Sf=new WI;class JI extends S{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 KI=new JI;class zI extends S{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>KI}])}}new zI;class YI extends S{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const QI=new YI;class XI extends S{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>QI}])}}const ZI=new XI;class eA extends S{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>rA}])}}const tA=new eA;class sA extends S{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:()=>vh}])}}const rA=new sA;class iA extends S{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 nA=new iA;class aA extends S{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:()=>nA}])}}const oA=new aA;class cA extends S{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:()=>vh}])}}const yf=new cA;class dA extends S{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>yf}])}}new dA;class lA extends S{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 uA=new lA;class hA extends S{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>mA}])}}const pA=new hA;class gA extends S{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 mA=new gA;class fA extends S{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const Tf=new fA;class vA extends S{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",mh,"BROADCAST_TYPE_"]}])}}const bo=new vA;class SA extends S{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const yA=new SA;class TA extends S{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const EA=new TA;class bA extends S{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 wA=new bA;class PA extends S{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>wA}])}}const Ef=new PA;class _A extends S{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 bf=new _A;var Sh;(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"})(Sh||(Sh={}));var $r;(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"})($r||($r={}));class CA extends S{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 RA=new CA;class kA extends S{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 IA=new kA;class AA extends S{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 MA=new AA;class OA extends S{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 DA=new OA;class NA extends S{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>MA},{no:2,name:"private",kind:"message",T:()=>DA}])}}const VA=new NA;class LA extends S{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 xA=new LA;class UA extends S{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",$r,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",$r,"STREAM_PERMISSION_TYPE_"]}])}}const yh=new UA;class FA extends S{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>yh},{no:2,name:"audio",kind:"message",T:()=>yh},{no:3,name:"screenshare",kind:"message",T:()=>yh}])}}const $A=new FA;class BA extends S{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>RA},{no:2,name:"plugins",kind:"message",T:()=>IA},{no:3,name:"chat",kind:"message",T:()=>VA},{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",Sh,"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",gh,"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:()=>xA},{no:23,name:"media",kind:"message",T:()=>$A}])}}const Th=new BA;class HA extends S{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const qA=new HA;class jA extends S{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 GA=new jA;class WA extends S{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>GA}])}}const JA=new WA;class KA extends S{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>Th}])}}const wf=new KA;class zA extends S{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>wf}])}}const YA=new zA;class QA extends S{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>wf}])}}const Pf=new QA;class XA extends S{constructor(){super("socket.preset.PeerUserIDMap",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9}])}}const ZA=new XA;class e0 extends S{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>ZA},{no:2,name:"patch",kind:"message",T:()=>Th}])}}new e0;class t0 extends S{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>Th}])}}new t0;class s0 extends S{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 Ci=new s0;class r0 extends S{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}])}}const i0=new r0;class n0 extends S{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Ci},{no:2,name:"next",kind:"scalar",T:8}])}}const a0=new n0;class o0 extends S{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Ci}])}}const _f=new o0;class c0 extends S{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const d0=new c0;class l0 extends S{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Ci}])}}const Eh=new l0;class u0 extends S{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 h0=new u0;class p0 extends S{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Ci}])}}const bh=new p0;class g0 extends S{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}])}}const m0=new g0;class f0 extends S{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Ci}])}}new f0;class v0 extends S{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 S0=new v0;class y0 extends S{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 T0=new y0;class E0 extends S{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}])}}const Jd=new E0;class b0 extends S{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Ci}])}}const Kd=new b0;class w0 extends S{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 P0=new w0;class _0 extends S{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 zd=new _0;class C0 extends S{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 R0=new C0;class k0 extends S{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}])}}const I0=new k0;class A0 extends S{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}const M0=new A0;class O0 extends S{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}])}}const D0=new O0;class N0 extends S{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}])}}const V0=new N0;class L0 extends S{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new L0;class x0 extends S{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}const U0=new x0;class F0 extends S{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>Ci},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const $0=new F0;class B0 extends S{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:()=>$0},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const H0=new B0;class q0 extends S{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>H0}])}}const dr=new q0;class j0 extends S{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 G0=new j0;class W0 extends S{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>G0}])}}const J0=new W0;class K0 extends S{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const z0=new K0;class Y0 extends S{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const Q0=new Y0;class X0 extends S{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const Z0=new X0;class eM extends S{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const tM=new eM;class sM extends S{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}])}}const rM=new sM;class iM extends S{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}])}}const nM=new iM;class aM extends S{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const oM=new aM;class cM extends S{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}])}}const dM=new cM;class lM extends S{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 wh=new lM;class uM extends S{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:()=>wh}])}}const Cf=new uM;class hM extends S{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:()=>wh}])}}const pM=new hM;class gM extends S{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:()=>wh}])}}const mM=new gM;class fM extends S{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}const vM=new fM;class SM extends S{constructor(){super("socket.plugin.EnablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"enabled_by",kind:"scalar",T:9}])}}const Ph=new SM;class yM extends S{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>Ph}])}}const TM=new yM;class EM extends S{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}const Rf=new EM;class bM extends S{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 wM=new bM;class PM extends S{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:()=>wM}])}}const kf=new PM;class _M extends S{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const If=new _M;class CM extends S{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 Af=new CM;class RM extends S{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const Mf=new RM;class kM extends S{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 IM=new kM;class AM extends S{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>IM}])}}const _h=new AM;class MM extends S{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const OM=new MM;class DM extends S{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const NM=new DM;class VM extends S{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Of=new VM;class LM extends S{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:()=>UM},{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 Df=new LM;class xM extends S{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:()=>$M}])}}const UM=new xM;class FM extends S{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const $M=new FM;class BM extends S{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 HM=new BM;class qM extends S{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 jM=new qM;class GM extends S{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>Df}])}}const Ch=new GM;class WM extends S{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>Df}])}}const JM=new WM;class KM extends S{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",_i]}])}}const Nf=new KM;class zM extends S{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=me.from(Math.floor(e/1e3)).toBigInt(),t.nanos=e%1e3*1e6,t}toDate(t){return new Date(me.from(t.seconds).toNumber()*1e3+Math.ceil(t.nanos/1e6))}fromDate(t){const e=this.create(),r=t.getTime();return e.seconds=me.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}internalJsonWrite(t,e){let r=me.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 n=(t.nanos+1e9).toString().substring(1);n.substring(3)==="000000"?i="."+n.substring(0,3)+"Z":n.substring(6)==="000"?i="."+n.substring(0,6)+"Z":i="."+n+"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 "+ih(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 n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(n<Date.parse("0001-01-01T00:00:00Z")||n>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=me.from(n/1e3).toBigInt(),r.nanos=0,i[7]&&(r.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),r}}new zM;class YM extends S{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 Rh=new YM;class QM extends S{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Rh}])}}new QM;class XM extends S{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>Rh},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>Rh}])}}new XM;const ZM=0,eO=1,tO=2,sO=3,rO=4,iO=5,nO={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},aO={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,sendMessageToChannel:6,searchChannelMessages:7,getAllChatChannels:8,markChannelIndexAsRead:9,pinMessage:10},oO={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},cO={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},Vf={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},dO={createChatChannel:0,getChatChannel:1,deprecatedGetAllChatChannels:2,getChannelMembers:3,updateChatChannel:4},lO={getUserPresets:0,updateUserPreset:1};function Bn(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function Lf(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const F=Bn(ZM,nO),Ae=Bn(eO,aO),G=Bn(tO,oO),lr=Bn(sO,cO),Ri=Bn(rO,dO),Br=Lf(Vf,16777216),_s=Lf(Vf,50331648),Yd=Bn(iO,lO);var uO=Object.defineProperty,hO=Object.getOwnPropertyDescriptor,kh=(s,t,e,r)=>{for(var i=r>1?void 0:r?hO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&uO(t,e,i),i};const Ih=(Qv=class{constructor(s,t){m(this,Yr,void 0);m(this,ra,void 0);f(this,Yr,t),f(this,ra,s)}get telemetry(){return a(this,ra).getValue("telemetry")}get logger(){return a(this,ra).getValue("logger")}async createChannel(s,t,e,r="public",i=!1){const n={displayName:s,targetUserIds:t,displayPictureUrl:e,visibility:r,isDirectMessage:i};i&&(n.visibility="private");const o=await a(this,Yr).sendMessagePromise(Ri.createChatChannel,D0.toBinary(n)),c=dr.fromBinary(o.payload).chatChannels;return Ih.formatChannel(c[0])}async updateChannel(s,t){const e=await a(this,Yr).sendMessagePromise(Ri.updateChatChannel,V0.toBinary({chatChannelId:s,targetUserIds:t.memberIds,displayName:t.displayName,displayPictureUrl:t.displayPictureUrl,visibility:t.visibility})),r=dr.fromBinary(e.payload).chatChannels;return Ih.formatChannel(r[0])}static formatChannel(s){var r;const{latestMessageAndUnreadCount:t}=s,e={...s,id:s.chatChannelId,memberIds:s.targetUserIds,unreadCount:(r=t==null?void 0:t.unreadCount)!=null?r:0};return t!=null&&t.message&&(e.latestMessage=ds.formatSocketPeerMessage(t.message)),delete e.chatChannelId,delete e.targetUserIds,delete e.latestMessageAndUnreadCount,e}async getChannelMembers(s){try{const t=await a(this,Yr).sendMessagePromise(Ri.getChannelMembers,U0.toBinary({chatChannelId:s}));return J0.fromBinary(t.payload).channelMembers.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}on(s,t){let e,r;switch(s){case Ri.createChatChannel:{e=dr.fromBinary.bind(dr),r=dr.create();break}case Ri.updateChatChannel:{e=dr.fromBinary.bind(dr),r=dr.create();break}}if(!e){this.logger.warn(`ChatChannelSocketHandler::Event ${s} is not recognized`);return}a(this,Yr).on(s,({payload:i})=>{let n=r;try{n=e(i)}catch(o){this.logger.error("ChatChannelSocketHandler::on::binary_decode_error",{error:o})}return t(n)})}},Yr=new WeakMap,ra=new WeakMap,Qv);let ki=Ih;kh([T.trace("ChatChannelHandler.createChannel")],ki.prototype,"createChannel",1),kh([T.trace("ChatChannelHandler.updateChannel")],ki.prototype,"updateChannel",1),kh([T.trace("ChatChannelHandler.getChannelMembers")],ki.prototype,"getChannelMembers",1);var pO=Object.defineProperty,gO=Object.getOwnPropertyDescriptor,Cs=(s,t,e,r)=>{for(var i=r>1?void 0:r?gO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&pO(t,e,i),i},Pt=(s=>(s[s.TEXT=0]="TEXT",s[s.IMAGE=1]="IMAGE",s[s.FILE=2]="FILE",s[s.CUSTOM=3]="CUSTOM",s))(Pt||{});class os{constructor(t,e){m(this,ft,void 0);m(this,ia,void 0);f(this,ft,e),f(this,ia,t)}get telemetry(){return a(this,ia).getValue("telemetry")}get logger(){return a(this,ia).getValue("logger")}getChatMessages(){return a(this,ft).sendMessagePromise(Ae.getMessages)}async getChatMessagesPaginated(t,e,r,i=0,n=""){const o={timeStamp:t,size:e,from:i,reversed:r,channelId:n},c=await a(this,ft).sendMessagePromise(Ae.getPaginatedMessages,i0.toBinary(o));return c.payload?a0.fromBinary(c.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};a(this,ft).sendMessage(Ae.sendMessageToRoom,d0.toBinary(r))}sendMessageToPeers(t,e,r){const i={payloadType:e,peerIds:r,payload:t};a(this,ft).sendMessage(Ae.sendMessageToPeers,h0.toBinary(i))}sendMessageToChannel(t,e,r){const i={payloadType:e,channelId:r,payload:t};a(this,ft).sendMessage(Ae.sendMessageToChannel,m0.toBinary(i))}sendMessage(t,e,r,i){if(i&&this.sendMessageToChannel(t,e,i),r&&r.length>0){this.sendMessageToPeers(t,e,r);return}this.sendMessageToRoom(t,e)}async editMessage(t,e,r,i,n){const o={chatId:t,payloadType:r,payload:e};i&&(o.channelId=i),n!==void 0&&(o.pinned=n);const c=await a(this,ft).sendMessagePromise(Ae.editMessage,S0.toBinary(o));return Kd.fromBinary(c.payload).message}async deleteMessage(t,e){const r={chatId:t};e&&(r.channelId=e);const i=await a(this,ft).sendMessagePromise(Ae.deleteMessage,P0.toBinary(r)),n=zd.fromBinary(i.payload);return{id:n.chatId,...n.channelId?{channelId:n.channelId}:{}}}async searchMessages(t,e){var i,n,o,c;const r={searchTerm:t,timeStamp:(i=e.timestamp)!=null?i:Date.now(),size:(n=e.limit)!=null?n:75,from:(o=e.offset)!=null?o:0,reversed:(c=e.reversed)!=null?c:!0};e.channelId&&(r.channelId=e.channelId);try{const d=await a(this,ft).sendMessagePromise(Ae.searchChannelMessages,R0.toBinary(r));return _f.fromBinary(d.payload).messages}catch(d){return[]}}async getAllChannels(){try{const t=await a(this,ft).sendMessagePromise(Ae.getAllChatChannels);return dr.fromBinary(t.payload).chatChannels.map(ki.formatChannel)}catch(t){return[]}}async markLastReadMessage(t,e){const r=await a(this,ft).sendMessagePromise(Ae.markChannelIndexAsRead,I0.toBinary({channelId:t,userId:e.userId,channelIndex:e.channelIndex}));return M0.fromBinary(r.payload).channelIndex}async setPinState(t,e){const r={chatId:t.id,pinned:e,channelId:t.channelId},i=await a(this,ft).sendMessagePromise(Ae.pinMessage,T0.toBinary(r));return Jd.fromBinary(i.payload)}on(t,e){let r,i;switch(t){case Ae.sendMessageToRoom:{r=Eh.fromBinary.bind(Eh),i=Eh.create();break}case Ae.sendMessageToPeers:{r=bh.fromBinary.bind(bh),i=bh.create();break}case Ae.editMessage:{r=Kd.fromBinary.bind(Kd),i=Kd.create();break}case Ae.pinMessage:{r=Jd.fromBinary.bind(Jd),i=Jd.create();break}case Ae.deleteMessage:{r=zd.fromBinary.bind(zd),i=zd.create();break}}if(!r){this.logger.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}a(this,ft).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}ft=new WeakMap,ia=new WeakMap,Cs([T.trace("SocketService.getChatMessages")],os.prototype,"getChatMessages",1),Cs([T.trace("SocketService.getChatMessagesPaginated")],os.prototype,"getChatMessagesPaginated",1),Cs([T.trace("SocketService.sendMessageToRoom")],os.prototype,"sendMessageToRoom",1),Cs([T.trace("SocketService.sendMessageToPeers")],os.prototype,"sendMessageToPeers",1),Cs([T.trace("SocketService.sendMessageToChannel")],os.prototype,"sendMessageToChannel",1),Cs([T.trace("SocketService.sendMessage")],os.prototype,"sendMessage",1),Cs([T.trace("SocketService.editMessage")],os.prototype,"editMessage",1),Cs([T.trace("SocketService.deleteMessage")],os.prototype,"deleteMessage",1),Cs([T.trace("SocketService.searchMessages")],os.prototype,"searchMessages",1),Cs([T.trace("SocketService.getAllChannels")],os.prototype,"getAllChannels",1),Cs([T.trace("SocketService.markLastReadMessage")],os.prototype,"markLastReadMessage",1);function mO(s){return s.replace(/([-_]\w)/g,t=>t[1].toUpperCase())}function Rs(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Rs(e));const t={};return Object.keys(s).forEach(e=>{const r=Cu(e)?e:mO(e);t[r]=Rs(s[e])}),t}function fO(s){return s.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function xf(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>xf(e));const t={};return Object.keys(s).forEach(e=>{const r=Cu(e)?e:fO(e);t[r]=s[e]}),t}function Qd(s,t={}){return s==null?{}:(Object.getOwnPropertyNames(s).forEach(e=>{if(typeof s[e]!="function"){if(typeof s[e]=="object"){Qd(s[e],t[e]={});return}t[e]=s[e]}}),t)}class Uf{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 n=new URLSearchParams;return Object.entries(e).forEach(([o,c])=>{n.append(o,c)}),`${i}${i.includes("?")?"&":"?"}${n.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 g=new AbortController,v=setTimeout(()=>g.abort(),d);c.signal=g.signal;const E=await fetch(r,c);clearTimeout(v);let b=null;const P=E.headers.get("content-type");P&&P.includes("application/json")?b=await E.json():b=await E.text();const w={};E.headers.forEach(($,N)=>{w[N]=$});const L={data:b,status:E.status,statusText:E.statusText,headers:w,config:t};if(!E.ok)throw L;return L}catch(g){if(g instanceof Error&&l>0)return await new Promise(v=>setTimeout(v,u)),this.defaults.baseURL===Pi.apiBase.prod?this.defaults.baseURL=Pi.apiBase.prodAlternate:this.defaults.baseURL===Pi.apiBase.prodAlternate&&(this.defaults.baseURL=Pi.apiBase.prod),this.request({...t,retry:l-1});throw g}}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 vO=3,SO=30,yO=8e3;class TO{constructor(t,e){p(this,"ipInfo");p(this,"fetchClient");p(this,"requests");p(this,"roomName");p(this,"roomUUID");p(this,"authToken");p(this,"organizationId");p(this,"iceServers");p(this,"pluginInformation");p(this,"userDetails");p(this,"roomDetails");p(this,"context");this.context=t;const{timeout:r=yO,retry:i=vO,retryDelay:n=SO,baseURL:o=Pi.apiBase.prod,authToken:c,cachedUserDetails:d}=e||{};this.iceServers=d==null?void 0:d.iceServers,this.pluginInformation=d==null?void 0:d.pluginInformation,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=new Uf({baseURL:o,timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.fetchClient=new Uf({baseURL:"",timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.setAuthToken(c,{bearer:!0});const l=this.requests.request.bind(this.requests);this.requests.request=async u=>{var g,v,E,b,P;const h=t.getValue("telemetry");try{h.injectContext(this.requests.defaults.headers.common);const w=await l(u);return u.url!==h.logsEndpoint&&this.logger.debug("xhr::fetch",{networkCall:{status:w.status,statusText:w.statusText,baseURL:u.baseURL||this.requests.defaults.baseURL,url:u.url,method:u.method}}),w}catch(w){throw w?(((g=w.config)==null?void 0:g.url)!==h.logsEndpoint&&this.logger.error("xhr::fetch",{error:w,networkCall:{status:w.status,statusText:w.statusText,baseURL:((v=w.config)==null?void 0:v.baseURL)||this.requests.defaults.baseURL,url:(E=w.config)==null?void 0:E.url,retries:(b=w.config)==null?void 0:b.retry,method:(P=w.config)==null?void 0:P.method,isOnline:navigator.onLine?"online":"offline"}}),new C(w.message||"Network request failed","0011")):new C("Unknown network error occurred","0011")}}}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 EO=Object.defineProperty,bO=Object.getOwnPropertyDescriptor,cs=(s,t,e,r)=>{for(var i=r>1?void 0:r?bO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&EO(t,e,i),i};class Wt extends TO{constructor(e,r){super(e,r);p(this,"telemetry");this.telemetry=e.getValue("telemetry"),this.setHeader("x-realtimekit-version",e.getValue("sdkVersion"))}async getIPDetails(){var r;const{peerId:e}=this;try{const i=await Au.getIPDetails({peerId:e,apiHostnames:Mm(this.context),logger:fm});if(this.logger.log("ipInfo",{ipInfo:i}),((r=i==null?void 0:i.loc)==null?void 0:r.length)>5)return i;throw Error("Insufficient data")}catch(i){this.logger.warn("APIClient.getIPDetails Failed to get ip details",{error:{name:i.name,message:i.message}});return}}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 getPlugins(){var n,o,c,d,l,u,h;if(this.pluginInformation)return this.pluginInformation;const{plugins:e}=(await this.requests.get("/v2/plugins/user")).data.data,r=((o=(n=this.context.getValue("flagsmith").getValue(Z.V1_PLUGINS))==null?void 0:n.toString())==null?void 0:o.split(","))||[],i=e.reduce((g,v)=>(g[r.includes(v.id)?"v1":"v2"].push({...v,name:v.name.replace("v2","")}),g),{v1:[],v2:[]});return(l=(d=(c=this.context.getValue("modules"))==null?void 0:c.devTools)==null?void 0:d.plugins)!=null&&l.length&&((h=(u=this.context.getValue("modules"))==null?void 0:u.devTools)==null||h.plugins.forEach(g=>{var E,b,P;const v={...yo,tags:[...yo.tags],baseUrl:`http://localhost:${g.port}`,name:g.name,picture:(E=g.picture)!=null?E:yo.picture,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),id:g.id,organizationId:this.organizationId,description:(b=g.description)!=null?b:yo.description,staggered:(P=g.staggered)!=null?P:yo.staggered};i.v2.push(v)})),i.v2}async getPluginDetails(e){const{plugin:r}=(await this.requests.get(`/v2/plugins/view/${e}`)).data.data;return r}async getPluginConfig(e){return(await this.fetchClient.get(`${e}/dyte-config.json`)).data}async authorizePlugin(e){const r={peerId:this.peerId},{token:i}=(await this.requests.post(`/v2/plugins/authorize/${e}`,r)).data.data;return i}async getPresignedUrls(e,r){const i=Un(this.context,"chat_upload_expiry"),n={roomUUID:this.roomUUID,filename:e,expiry:typeof i=="number"?i:void 0};this.context.getValue("flagsmith").hasFeature(Z.FEAT_CHAT_SDK)&&(n.viewType=r);const{getLocation:o,putLocation:c}=(await this.requests.post("/v1/meetings/genPreSignedUploadUrl",n)).data.data;return{getLocation:o,putLocation:c}}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=Rs(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=Rs((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 Rs(e)}async startRecording(e,r){return(await this.requests.post("/v2/recordings",{...xf(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")}}async getRoomNodeData(){const e=await this.getIPDetails();if(this.ipInfo=e,this.roomDetails)return this.roomDetails;const{title:r}=Rs((await this.requests.post("v2/internals/rooms",{ip_information:e})).data.data);return{meetingTitle:r}}}cs([T.trace("APIClient.getIPDetails")],Wt.prototype,"getIPDetails",1),cs([T.trace("APIClient.getICEServers")],Wt.prototype,"getICEServers",1),cs([T.trace("APIClient.getPlugins")],Wt.prototype,"getPlugins",1),cs([T.trace("APIClient.startLivestreaming")],Wt.prototype,"startLivestreaming",1),cs([T.trace("APIClient.stopLivestreaming")],Wt.prototype,"stopLivestreaming",1),cs([T.trace("APIClient.getActiveLivestream")],Wt.prototype,"getActiveLivestream",1),cs([T.trace("APIClient.getUserDetails")],Wt.prototype,"getUserDetails",1),cs([T.trace("APIClient.startRecording")],Wt.prototype,"startRecording",1),cs([T.trace("APIClient.stopRecording")],Wt.prototype,"updateRecording",1),cs([T.trace("APIClient.getActiveRecording")],Wt.prototype,"getActiveRecording",1),cs([T.trace("APIClient.getActiveTranscript")],Wt.prototype,"getActiveTranscript",1),cs([T.trace("APIClient.getRoomNodeData")],Wt.prototype,"getRoomNodeData",1);let Ah;function wO(s,t){return Ah=new Wt(s,t),Ah}function pt(){return Ah}function PO(s,t){return`<blockquote>${t.replace(/<blockquote>[.\s\S]*<\/blockquote>\n\n/m,"")}</blockquote>
12
12
 
13
- ${s}`}const Hn={maxInvocations:5,period:1};function Lt(s,t){return function(e,r,i){const n=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,n.apply(this,d)},i}}var _O=Object.defineProperty,CO=Object.getOwnPropertyDescriptor,gt=(s,t,e,r)=>{for(var i=r>1?void 0:r?CO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&_O(t,e,i),i};const RO=["text","image","file","custom","poll"],Xd={maxInvocations:180,period:60};let et=(Xv=class extends Gt{constructor(t,e,r,i,n){const o=t.getValue("logger");super(o);m(this,Il);m(this,Bo);p(this,"messages");p(this,"channels",[]);m(this,X,void 0);m(this,qi,void 0);m(this,Be,void 0);m(this,ji,void 0);m(this,na,void 0);p(this,"maxTextLimit",2e3);f(this,na,t),f(this,Be,e),f(this,ji,r),f(this,X,i),f(this,qi,n),this.messages=[]}get telemetry(){return a(this,na).getValue("telemetry")}setMaxTextLimit(t){this.maxTextLimit=t}async sendMessageInternal(t,e,r,i={}){switch(t.type){case"text":{const n=i.replyTo&&i.replyTo.type==="text"?PO(t.message,i.replyTo.message):t.message;await this.sendTextMessageInternal(n,e,r);break}case"image":await this.sendImageMessageInternal(t.image,e,r);break;case"file":await this.sendFileMessageInternal(t.file,e,r);break;default:this.logger.error("sendMessage::message_type_not_supported",{chat:{messageType:t.type}});break}}async sendTextMessageInternal(t,e,r){var n,o,c,d,l,u;if(t.length>this.maxTextLimit)throw new C("Max character limit breached","0503");if(e&&e.length>0){if(!((n=a(this,X).permissions)!=null&&n.chatPrivate.canSend)||!((o=a(this,X).permissions)!=null&&o.chatPrivate.text))throw this.logger.error("sendTextMessage::private_chat_permission_denied"),new C("Could not send message to private chat.","0501")}else if(!((d=(c=a(this,X).permissions)==null?void 0:c.chatPublic)!=null&&d.canSend)||!((u=(l=a(this,X).permissions)==null?void 0:l.chatPublic)!=null&&u.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");if(r){a(this,Be).sendMessageToChannel(t,Pt.TEXT,r);return}let i=[];e&&e.length>0&&(e.push(a(this,X).id),i=a(this,qi).joined.toArray().filter(h=>e.includes(h.id)).map(h=>h.userId),i.push(a(this,X).userId)),a(this,Be).sendMessage(t,Pt.TEXT,e)}async sendImageMessageInternal(t,e,r){var n,o,c,d,l,u;if(e&&e.length>0){if(!((n=a(this,X).permissions)!=null&&n.chatPrivate.canSend)||!((o=a(this,X).permissions)!=null&&o.chatPrivate.files)){this.logger.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((d=(c=a(this,X).permissions)==null?void 0:c.chatPublic)!=null&&d.canSend)||!((u=(l=a(this,X).permissions)==null?void 0:l.chatPublic)!=null&&u.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 h=pt(),{getLocation:g,putLocation:v}=await h.getPresignedUrls(t.name,a(this,X).config.viewType);if(await h.uploadFile(t,v),r){a(this,Be).sendMessageToChannel(g,Pt.IMAGE,r);return}let E=[];e&&e.length>0&&(e.push(a(this,X).id),E=a(this,qi).joined.toArray().filter(b=>e.includes(b.id)).map(b=>b.userId),E.push(a(this,X).userId)),a(this,Be).sendMessage(g,Pt.IMAGE,e)}catch(h){throw new C("Error sending image message.","0500",this.logger)}}async sendFileMessageInternal(t,e,r){var i,n,o,c,d,l;if(e&&e.length>0){if(!((i=a(this,X).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,X).permissions)!=null&&n.chatPrivate.files)){this.logger.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((c=(o=a(this,X).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,X).permissions)==null?void 0:d.chatPublic)!=null&&l.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!t){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const u=pt(),{getLocation:h,putLocation:g}=await u.getPresignedUrls(t.name,a(this,X).config.viewType);if(await u.uploadFile(t,g),r){a(this,Be).sendMessageToChannel(JSON.stringify({link:h,name:t.name,size:"size"in t?t.size:0}),Pt.FILE,r);return}let v=[];e&&e.length>0&&(e.push(a(this,X).id),v=a(this,qi).joined.toArray().filter(b=>e.includes(b.id)).map(b=>b.userId),v.push(a(this,X).userId));const E=JSON.stringify({link:h,name:t.name,size:"size"in t?t.size:0});a(this,Be).sendMessage(E,Pt.FILE,e)}catch(u){throw new C("Error sending file message.","0500",this.logger)}}get rateLimits(){return Xd}updateRateLimits(t,e){Xd.maxInvocations=t,Xd.period=e}async sendTextMessage(t,e){return this.sendTextMessageInternal(t,e)}async sendCustomMessage(t,e){var n,o,c,d,l,u,h,g,v,E,b,P,w,L,$;if(e&&e.length>0){if(!((n=a(this,X).permissions)!=null&&n.chatPrivate.canSend)||!((o=a(this,X).permissions)!=null&&o.chatPrivate.files)||!((c=a(this,X).permissions)!=null&&c.chatPrivate.text)){this.logger.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((l=(d=a(this,X).permissions)==null?void 0:d.chatPublic)!=null&&l.canSend)||!((h=(u=a(this,X).permissions)==null?void 0:u.chatPublic)!=null&&h.files)||!((v=(g=a(this,X).permissions)==null?void 0:g.chatPublic)!=null&&v.text)){this.logger.error("sendCustomMessage::permission_denied");return}const r=async N=>{try{if(typeof N=="string")return{link:N};const B=pt(),{getLocation:Y,putLocation:ae}=await B.getPresignedUrls(N.name,a(this,X).config.viewType);return await B.uploadFile(N,ae),{link:Y,type:N.type,name:N.name,size:N.size}}catch(B){throw new C("Error sending image message.","0500",this.logger)}},i={...t,files:await Promise.all((b=(E=t.files)!=null?E:[])==null?void 0:b.map(async N=>r(N))),images:await Promise.all((w=(P=t.images)!=null?P:[])==null?void 0:w.map(async N=>r(N))),videos:await Promise.all(($=(L=t.videos)!=null?L:[])==null?void 0:$.map(async N=>r(N)))};a(this,Be).sendMessage(JSON.stringify(i),Pt.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,r){var i,n,o,c,d,l;if(((n=(i=a(this,X).permissions)==null?void 0:i.chatMessage)==null?void 0:n.canEdit)==="NONE")throw new C("Not permitted to edit messages","0501");if(!((c=(o=a(this,X).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,X).permissions)==null?void 0:d.chatPublic)!=null&&l.text)){this.logger.error("editTextMessage::permission_denied");return}if(!e){this.logger.error("editTextMessage::message_can_not_be_empty");return}a(this,Be).editMessage(t,e,Pt.TEXT,r)}async editImageMessage(t,e,r){var n,o,c,d;if(!((o=(n=a(this,X).permissions)==null?void 0:n.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,X).permissions)==null?void 0:c.chatPublic)!=null&&d.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 l=pt(),{getLocation:u,putLocation:h}=await l.getPresignedUrls(e.name,a(this,X).config.viewType);await l.uploadFile(e,h),a(this,Be).editMessage(t,u,Pt.IMAGE,r)}catch(l){throw new C("Error editing image message.","0500",this.logger)}}async editFileMessage(t,e,r){var i,n,o,c;if(!((n=(i=a(this,X).permissions)==null?void 0:i.chatPublic)!=null&&n.canSend)||!((c=(o=a(this,X).permissions)==null?void 0:o.chatPublic)!=null&&c.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!e){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const d=pt(),{getLocation:l,putLocation:u}=await d.getPresignedUrls(e.name,a(this,X).config.viewType);await d.uploadFile(e,u),a(this,Be).editMessage(t,JSON.stringify({link:l,name:e.name,size:"size"in e?e.size:0}),Pt.FILE,r)}catch(d){throw new C("Error editing file message.","0500",this.logger)}}async editMessage(t,e,r){switch(e.type){case"text":{this.editTextMessage(t,e.message,r);break}case"image":{this.editImageMessage(t,e.image,r);break}case"file":{this.editFileMessage(t,e.file,r);break}default:{this.logger.error("editMessage::message_type_not_supported",{chat:{messageType:e.type}});break}}}async deleteMessage(t,e){var r,i;if(((i=(r=a(this,X).permissions)==null?void 0:r.chatMessage)==null?void 0:i.canDelete)==="NONE")throw new C("Not permitted to delete messages","0501");a(this,Be).deleteMessage(t,e)}getMessagesByUser(t){return this.messages.filter(e=>e.userId===t)}getMessagesByType(t){return this.messages.filter(e=>e.type===t)}async pin(t){if(!a(this,Bo,gp))throw new C("Can`t pin message without joining room","0505");if(!a(this,X).permissions.pinParticipant)throw new C("You do not have permission to pin messages.","0501");const e=this.messages.find(r=>r.id===t);if(e){a(this,Be).setPinState(e,!0);return}throw new C(`No message found with id: ${t}`,"0504")}async unpin(t){if(!a(this,Bo,gp))throw new C("Can`t unpin message without joining room","0505");if(!a(this,X).permissions.pinParticipant)throw new C("You do not have permission to unpin messages.","0501");const e=this.messages.find(r=>r.id===t);if(e){a(this,Be).setPinState(e,!1);return}throw new C(`No message found with id: ${t}`,"0504")}async fetchMessages({timestamp:t=0,offset:e,limit:r,direction:i="after",searchQuery:n="",type:o,userId:c}){let d=[];return n?d=(await a(this,Be).searchMessages(n,{offset:e,limit:r,timestamp:t,reversed:i==="before"})).map(ds.formatSocketPeerMessage):d=(await a(this,Be).getChatMessagesPaginated(t,r,i==="before",e)).messages.map(u=>ds.formatSocketPeerMessage(u)),o&&(d=d.filter(l=>l.type===o)),c&&(d=d.filter(l=>l.userId===c)),d}async getMessages(t,e,r,i=0,n=void 0){const o=await a(this,Be).getChatMessagesPaginated(t,e,r,i,n);return{messages:o.messages.map(c=>ds.formatSocketPeerMessage(c)),next:o.next}}async createChannel(t,e,r={}){var c;const i=(c=a(this,X).permissions)==null?void 0:c.chatChannel;if(i){if(i.canCreate==="NONE")throw new C("Not permitted to create channels","0501");if(r.visibility==="public"&&!(i.canCreate==="PUBLIC"||i.canCreate==="ALL"))throw new C("Not permitted to create public channels","0501");if(r.visibility==="private"&&!(i.canCreate==="PRIVATE"||i.canCreate==="ALL"))throw new C("Not permitted to create private channels","0501")}if(!t||t.trim().length===0)throw new C("channel name cannot be empty.","0510");const n=[...new Set([...e,a(this,X).userId])];return await a(this,ji).createChannel(t.trim(),n,r.displayPictureUrl,r.visibility,r.isDirectMessage)}updateChannel(t,e){var o,c,d,l,u;const r=this.channels.find(h=>h.id===t),i=(o=a(this,X).permissions)==null?void 0:o.chatChannel;if(i){if(i.canUpdate==="NONE")throw new C("Not permitted to update channels","0501");if(r.visibility==="public"&&!(i.canUpdate==="PUBLIC"||i.canUpdate==="ALL"))throw new C("Not permitted to update public channels","0501");if(r.visibility==="private"&&!(i.canUpdate==="PRIVATE"||i.canUpdate==="ALL"))throw new C("Not permitted to update private channels","0501")}const n={memberIds:(c=e.memberIds)!=null?c:r.memberIds,displayName:(d=e.displayName)!=null?d:r.displayName,displayPictureUrl:(l=e.displayPictureUrl)!=null?l:r.displayPictureUrl,visibility:(u=e.visibility)!=null?u:r.visibility};return a(this,ji).updateChannel(t,n)}async sendMessageToChannel(t,e,r={}){return this.sendMessageInternal(t,null,e,r)}async getChannelMembers(t){return a(this,ji).getChannelMembers(t)}async searchMessages(t,e){throw new C("searchMessages is disabled! Please use `fetchMessages` method instead.","0506")}async markLastReadMessage(t,e){await a(this,Be).markLastReadMessage(t,e);const r=this.channels.find(i=>i.id===t);if(r){const i={...r,unreadCount:0};this.channels=this.channels.map(n=>n.id===t?i:n),this.emit("channelMessageUpdate",i)}}get pinned(){return this.messages.filter(t=>t.pinned)}},X=new WeakMap,qi=new WeakMap,Be=new WeakMap,ji=new WeakMap,na=new WeakMap,Il=new WeakSet,vS=function(){return a(this,na).getValue("connectionHandler")},Bo=new WeakSet,gp=function(){return a(this,Il,vS).socketJoined===!0},Xv);gt([T.trace("Chat.sendTextMessage"),Lt(Xd)],et.prototype,"sendTextMessage",1),gt([T.trace("Chat.sendImageMessage"),Lt({maxInvocations:20,period:60})],et.prototype,"sendImageMessage",1),gt([T.trace("Chat.sendFileMessage"),Lt({maxInvocations:20,period:60})],et.prototype,"sendFileMessage",1),gt([T.trace("Chat.sendMessage"),Lt({maxInvocations:180,period:60})],et.prototype,"sendMessage",1),gt([T.trace("Chat.editTextMessage")],et.prototype,"editTextMessage",1),gt([T.trace("Chat.editImageMessage")],et.prototype,"editImageMessage",1),gt([T.trace("Chat.editFileMessage")],et.prototype,"editFileMessage",1),gt([T.trace("Chat.editMessage")],et.prototype,"editMessage",1),gt([T.trace("Chat.deleteMessage")],et.prototype,"deleteMessage",1),gt([T.trace("Chat.createChannel")],et.prototype,"createChannel",1),gt([T.trace("Chat.updateChannel")],et.prototype,"updateChannel",1),gt([T.trace("Chat.sendMessageToChannel")],et.prototype,"sendMessageToChannel",1),gt([T.trace("Chat.getChannelMembers")],et.prototype,"getChannelMembers",1),gt([T.trace("Chat.searchMessages")],et.prototype,"searchMessages",1),gt([T.trace("Chat.markLastReadMessage")],et.prototype,"markLastReadMessage",1),et=gt([ut("0500")],et);var kO=Object.defineProperty,IO=Object.getOwnPropertyDescriptor,AO=(s,t,e,r)=>{for(var i=r>1?void 0:r?IO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&kO(t,e,i),i};const Ii=(Zv=class{constructor(s,t,e,r,i){p(this,"chat");p(this,"chatSocketHandler");p(this,"chatChannelSocketHandler");p(this,"self");m(this,Gi,void 0);f(this,Gi,s),this.chatSocketHandler=t,this.chatChannelSocketHandler=e,this.chat=new et(s,t,e,r,i),this.self=r,this.setupEvents()}get telemetry(){return a(this,Gi).getValue("telemetry")}get logger(){return a(this,Gi).getValue("logger")}static async init(s,t,e,r,i){return new Ii(s,t,e,r,i)}static formatMessage(s){return{...s,time:new Date(s.time),type:RO[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,channelId:s.channelId,channelIndex:s.channelIndex,message:"",link:"",name:"",html:"",images:[],videos:[],files:[],size:0,pinned:s.pinned};switch(e.type){case Pt.TEXT:{e.message=s.payload;break}case Pt.IMAGE:{e.link=s.payload;break}case Pt.FILE:{const{link:r,name:i,size:n}=JSON.parse(s.payload);e.link=r,e.name=i,e.size=n;break}case Pt.CUSTOM:{const{html:r,images:i,message:n,videos:o,files:c}=JSON.parse(s.payload);e.message=n,e.html=r,e.images=i,e.videos=o,e.files=c;break}}return Ii.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=_f.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>Ii.formatSocketPeerMessage(e))}setupEvents(){a(this,Gi).getValue("peerSessionStore").on(R.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(Ae.sendMessageToRoom,s=>{const t=Ii.formatSocketPeerMessage(s.message);if(!t.channelId)this.chat.messages=[...this.chat.messages,t];else{const e=this.chat.channels.find(r=>r.id===t.channelId);e&&(e.latestMessage=t,e.unreadCount+=1,this.chat.emit("channelMessageUpdate",e))}this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Ae.sendMessageToPeers,s=>{const t=Ii.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(Ae.editMessage,s=>{const t=Ii.formatSocketPeerMessage(s.message);if(t.channelId){this.chat.emit("chatUpdate",{action:"edit",message:t,messages:this.chat.messages});return}const 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(Ae.deleteMessage,s=>{if(s.channelId){this.chat.emit("chatUpdate",{action:"delete",message:{id:s.chatId,channelId:s.channelId},messages:this.chat.messages});return}const t=this.chat.messages.findIndex(r=>r.id===s.chatId);if(t===-1)return;const[e]=this.chat.messages.splice(t,1);this.chat.emit("chatUpdate",{action:"delete",message:e,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(Ri.createChatChannel,s=>{const[t]=s.chatChannels,e=ki.formatChannel(t);this.chat.channels.push(e),this.chat.emit("channelCreate",e)}),this.chatSocketHandler.on(Ae.pinMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId);if(t===-1)return;const e=this.chat.messages[t];e.pinned=s.pinned,this.chat.messages[t]=e,this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(Ri.updateChatChannel,s=>{const[t]=s.chatChannels,e=ki.formatChannel(t);this.chat.channels=this.chat.channels.map(r=>r.id===e.id?e:r),this.chat.emit("channelUpdate",e)})}},Gi=new WeakMap,Zv);let ds=Ii;AO([T.trace("ChatController.setupEvents")],ds.prototype,"setupEvents",1);var MO=Object.defineProperty,OO=Object.getOwnPropertyDescriptor,DO=(s,t,e,r)=>{for(var i=r>1?void 0:r?OO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&MO(t,e,i),i};let Mh=(eS=class extends Gt{constructor(t,e,r){const i=t.getValue("logger");super(i);m(this,Al);m(this,Ml);p(this,"items");m(this,aa,void 0);m(this,oa,void 0);m(this,Ho,void 0);f(this,Ho,t),f(this,aa,e),f(this,oa,r),this.items=[]}async create(t,e,r=!1,i=!1){if(!a(this,Ml,yS))throw new C("Can't create polls without joining room","0705");if(!a(this,aa).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 a(this,oa).createPoll(t,e,r,i)}async vote(t,e){if(!a(this,aa).permissions.polls.canVote){this.logger.error("Polls::vote::permission_denied");return}await a(this,oa).votePoll(t,e)}},Al=new WeakSet,SS=function(){return a(this,Ho).getValue("connectionHandler")},Ml=new WeakSet,yS=function(){var t;return((t=a(this,Al,SS))==null?void 0:t.socketJoined)===!0},aa=new WeakMap,oa=new WeakMap,Ho=new WeakMap,eS);Mh=DO([ut("0700")],Mh);var NO=Object.defineProperty,VO=Object.getOwnPropertyDescriptor,LO=(s,t,e,r)=>{for(var i=r>1?void 0:r?VO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&NO(t,e,i),i};const qn=(tS=class{constructor(s,t,e){p(this,"polls");m(this,Qr,void 0);m(this,ca,void 0);m(this,Wi,void 0);this.polls=new Mh(s,t,e),f(this,ca,t),f(this,Qr,s),f(this,Wi,e),this.setupEvents()}get telemetry(){return a(this,Qr).getValue("telemetry")}get logger(){return a(this,Qr).getValue("logger")}static async init(s,t,e){return new qn(s,t,e)}canViewPolls(){return a(this,ca).permissions.polls.canView}setupEvents(){const s={[lr.createPoll]:r=>{r.poll&&this.updatePoll(qn.formatSocketServicePoll(r.poll))},[lr.updatePoll]:r=>{r.poll&&this.updatePoll(qn.formatSocketServicePoll(r.poll))},[lr.votePoll]:r=>{r.poll&&this.updatePoll(qn.formatSocketServicePoll(r.poll))}},t=()=>{a(this,Qr).getValue("peerSessionStore").on(R.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,Wi).on(r,s[r])})},e=()=>{a(this,Qr).getValue("peerSessionStore").on(R.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,Wi).removeListeners(r)})};a(this,ca).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 a(this,Wi).getPolls();if(!(s!=null&&s.payload))return;const{polls:t}=JM.fromBinary(s.payload);this.polls.items=t.map(e=>qn.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}}},Qr=new WeakMap,ca=new WeakMap,Wi=new WeakMap,tS);let Ff=qn;LO([T.trace("PollController.setupEvents")],Ff.prototype,"setupEvents",1);var xO=Object.defineProperty,UO=Object.getOwnPropertyDescriptor,FO=(s,t,e,r)=>{for(var i=r>1?void 0:r?UO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&xO(t,e,i),i},$f=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))($f||{});let Oh=(sS=class extends Gt{constructor(t,e,r,i,n){const o=t.getValue("logger");super(o);m(this,qo);p(this,"selfActiveTab");p(this,"broadcastTabChanges");m(this,da,void 0);m(this,Ji,void 0);m(this,jo,void 0);p(this,"viewType");p(this,"meetingStartedTimestamp");p(this,"meetingTitle");p(this,"sessionId");f(this,da,t),f(this,Ji,e),this.viewType=r,f(this,jo,i),this.meetingTitle=n,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return a(this,qo,mp).socketState}get mediaState(){return a(this,qo,mp).mediaState}get meetingId(){return a(this,da).getValue("meetingId")}setBroadcastTabChanges(t){if(!a(this,Ji).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=a(this,Ji).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){a(this,jo).broadcastMessage("spotlight",{userId:a(this,Ji).userId,currentTab:this.selfActiveTab})}},da=new WeakMap,qo=new WeakSet,mp=function(){return a(this,da).getValue("connectionHandler")},Ji=new WeakMap,jo=new WeakMap,sS);Oh=FO([ut("0800")],Oh);function $O(s){let t="",e=[""];const r=[e];let i=0,n=0,o=!0,c;for(c of s)c==='"'?(o&&c===t&&(e[i]+=c),o=!o):c===","&&o?c=e[++i]="":c===`
13
+ ${s}`}const Hn={maxInvocations:5,period:1};function Lt(s,t){return function(e,r,i){const n=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,n.apply(this,d)},i}}var _O=Object.defineProperty,CO=Object.getOwnPropertyDescriptor,gt=(s,t,e,r)=>{for(var i=r>1?void 0:r?CO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&_O(t,e,i),i};const RO=["text","image","file","custom","poll"],Xd={maxInvocations:180,period:60};let et=(Xv=class extends Gt{constructor(t,e,r,i,n){const o=t.getValue("logger");super(o);m(this,Il);m(this,Bo);p(this,"messages");p(this,"channels",[]);m(this,X,void 0);m(this,qi,void 0);m(this,Be,void 0);m(this,ji,void 0);m(this,na,void 0);p(this,"maxTextLimit",2e3);f(this,na,t),f(this,Be,e),f(this,ji,r),f(this,X,i),f(this,qi,n),this.messages=[]}get telemetry(){return a(this,na).getValue("telemetry")}setMaxTextLimit(t){this.maxTextLimit=t}async sendMessageInternal(t,e,r,i={}){switch(t.type){case"text":{const n=i.replyTo&&i.replyTo.type==="text"?PO(t.message,i.replyTo.message):t.message;await this.sendTextMessageInternal(n,e,r);break}case"image":await this.sendImageMessageInternal(t.image,e,r);break;case"file":await this.sendFileMessageInternal(t.file,e,r);break;default:this.logger.error("sendMessage::message_type_not_supported",{chat:{messageType:t.type}});break}}async sendTextMessageInternal(t,e,r){var n,o,c,d,l,u;if(t.length>this.maxTextLimit)throw new C("Max character limit breached","0503");if(e&&e.length>0){if(!((n=a(this,X).permissions)!=null&&n.chatPrivate.canSend)||!((o=a(this,X).permissions)!=null&&o.chatPrivate.text))throw this.logger.error("sendTextMessage::private_chat_permission_denied"),new C("Could not send message to private chat.","0501")}else if(!((d=(c=a(this,X).permissions)==null?void 0:c.chatPublic)!=null&&d.canSend)||!((u=(l=a(this,X).permissions)==null?void 0:l.chatPublic)!=null&&u.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");if(r){a(this,Be).sendMessageToChannel(t,Pt.TEXT,r);return}let i=[];e&&e.length>0&&(e.push(a(this,X).id),i=a(this,qi).joined.toArray().filter(h=>e.includes(h.id)).map(h=>h.userId),i.push(a(this,X).userId)),a(this,Be).sendMessage(t,Pt.TEXT,e)}async sendImageMessageInternal(t,e,r){var n,o,c,d,l,u;if(e&&e.length>0){if(!((n=a(this,X).permissions)!=null&&n.chatPrivate.canSend)||!((o=a(this,X).permissions)!=null&&o.chatPrivate.files)){this.logger.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((d=(c=a(this,X).permissions)==null?void 0:c.chatPublic)!=null&&d.canSend)||!((u=(l=a(this,X).permissions)==null?void 0:l.chatPublic)!=null&&u.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 h=pt(),{getLocation:g,putLocation:v}=await h.getPresignedUrls(t.name,a(this,X).config.viewType);if(await h.uploadFile(t,v),r){a(this,Be).sendMessageToChannel(g,Pt.IMAGE,r);return}let E=[];e&&e.length>0&&(e.push(a(this,X).id),E=a(this,qi).joined.toArray().filter(b=>e.includes(b.id)).map(b=>b.userId),E.push(a(this,X).userId)),a(this,Be).sendMessage(g,Pt.IMAGE,e)}catch(h){throw new C("Error sending image message.","0500",this.logger)}}async sendFileMessageInternal(t,e,r){var i,n,o,c,d,l;if(e&&e.length>0){if(!((i=a(this,X).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,X).permissions)!=null&&n.chatPrivate.files)){this.logger.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((c=(o=a(this,X).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,X).permissions)==null?void 0:d.chatPublic)!=null&&l.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!t){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const u=pt(),{getLocation:h,putLocation:g}=await u.getPresignedUrls(t.name,a(this,X).config.viewType);if(await u.uploadFile(t,g),r){a(this,Be).sendMessageToChannel(JSON.stringify({link:h,name:t.name,size:"size"in t?t.size:0}),Pt.FILE,r);return}let v=[];e&&e.length>0&&(e.push(a(this,X).id),v=a(this,qi).joined.toArray().filter(b=>e.includes(b.id)).map(b=>b.userId),v.push(a(this,X).userId));const E=JSON.stringify({link:h,name:t.name,size:"size"in t?t.size:0});a(this,Be).sendMessage(E,Pt.FILE,e)}catch(u){throw new C("Error sending file message.","0500",this.logger)}}get rateLimits(){return Xd}updateRateLimits(t,e){Xd.maxInvocations=t,Xd.period=e}async sendTextMessage(t,e){return this.sendTextMessageInternal(t,e)}async sendCustomMessage(t,e){var n,o,c,d,l,u,h,g,v,E,b,P,w,L,$;if(e&&e.length>0){if(!((n=a(this,X).permissions)!=null&&n.chatPrivate.canSend)||!((o=a(this,X).permissions)!=null&&o.chatPrivate.files)||!((c=a(this,X).permissions)!=null&&c.chatPrivate.text)){this.logger.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((l=(d=a(this,X).permissions)==null?void 0:d.chatPublic)!=null&&l.canSend)||!((h=(u=a(this,X).permissions)==null?void 0:u.chatPublic)!=null&&h.files)||!((v=(g=a(this,X).permissions)==null?void 0:g.chatPublic)!=null&&v.text)){this.logger.error("sendCustomMessage::permission_denied");return}const r=async N=>{try{if(typeof N=="string")return{link:N};const B=pt(),{getLocation:Y,putLocation:ae}=await B.getPresignedUrls(N.name,a(this,X).config.viewType);return await B.uploadFile(N,ae),{link:Y,type:N.type,name:N.name,size:N.size}}catch(B){throw new C("Error sending image message.","0500",this.logger)}},i={...t,files:await Promise.all((b=(E=t.files)!=null?E:[])==null?void 0:b.map(async N=>r(N))),images:await Promise.all((w=(P=t.images)!=null?P:[])==null?void 0:w.map(async N=>r(N))),videos:await Promise.all(($=(L=t.videos)!=null?L:[])==null?void 0:$.map(async N=>r(N)))};a(this,Be).sendMessage(JSON.stringify(i),Pt.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,r){var i,n,o,c,d,l;if(((n=(i=a(this,X).permissions)==null?void 0:i.chatMessage)==null?void 0:n.canEdit)==="NONE")throw new C("Not permitted to edit messages","0501");if(!((c=(o=a(this,X).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,X).permissions)==null?void 0:d.chatPublic)!=null&&l.text)){this.logger.error("editTextMessage::permission_denied");return}if(!e){this.logger.error("editTextMessage::message_can_not_be_empty");return}a(this,Be).editMessage(t,e,Pt.TEXT,r)}async editImageMessage(t,e,r){var n,o,c,d;if(!((o=(n=a(this,X).permissions)==null?void 0:n.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,X).permissions)==null?void 0:c.chatPublic)!=null&&d.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 l=pt(),{getLocation:u,putLocation:h}=await l.getPresignedUrls(e.name,a(this,X).config.viewType);await l.uploadFile(e,h),a(this,Be).editMessage(t,u,Pt.IMAGE,r)}catch(l){throw new C("Error editing image message.","0500",this.logger)}}async editFileMessage(t,e,r){var i,n,o,c;if(!((n=(i=a(this,X).permissions)==null?void 0:i.chatPublic)!=null&&n.canSend)||!((c=(o=a(this,X).permissions)==null?void 0:o.chatPublic)!=null&&c.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!e){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const d=pt(),{getLocation:l,putLocation:u}=await d.getPresignedUrls(e.name,a(this,X).config.viewType);await d.uploadFile(e,u),a(this,Be).editMessage(t,JSON.stringify({link:l,name:e.name,size:"size"in e?e.size:0}),Pt.FILE,r)}catch(d){throw new C("Error editing file message.","0500",this.logger)}}async editMessage(t,e,r){switch(e.type){case"text":{this.editTextMessage(t,e.message,r);break}case"image":{this.editImageMessage(t,e.image,r);break}case"file":{this.editFileMessage(t,e.file,r);break}default:{this.logger.error("editMessage::message_type_not_supported",{chat:{messageType:e.type}});break}}}async deleteMessage(t,e){var r,i;if(((i=(r=a(this,X).permissions)==null?void 0:r.chatMessage)==null?void 0:i.canDelete)==="NONE")throw new C("Not permitted to delete messages","0501");a(this,Be).deleteMessage(t,e)}getMessagesByUser(t){return this.messages.filter(e=>e.userId===t)}getMessagesByType(t){return this.messages.filter(e=>e.type===t)}async pin(t){if(!a(this,Bo,gp))throw new C("Can`t pin message without joining room","0505");const e=this.messages.find(r=>r.id===t);if(e){a(this,Be).setPinState(e,!0);return}throw new C(`No message found with id: ${t}`,"0504")}async unpin(t){if(!a(this,Bo,gp))throw new C("Can`t unpin message without joining room","0505");if(!a(this,X).permissions.pinParticipant)throw new C("You do not have permission to unpin messages.","0501");const e=this.messages.find(r=>r.id===t);if(e){a(this,Be).setPinState(e,!1);return}throw new C(`No message found with id: ${t}`,"0504")}async fetchMessages({timestamp:t=0,offset:e,limit:r,direction:i="after",searchQuery:n="",type:o,userId:c}){let d=[];return n?d=(await a(this,Be).searchMessages(n,{offset:e,limit:r,timestamp:t,reversed:i==="before"})).map(ds.formatSocketPeerMessage):d=(await a(this,Be).getChatMessagesPaginated(t,r,i==="before",e)).messages.map(u=>ds.formatSocketPeerMessage(u)),o&&(d=d.filter(l=>l.type===o)),c&&(d=d.filter(l=>l.userId===c)),d}async getMessages(t,e,r,i=0,n=void 0){const o=await a(this,Be).getChatMessagesPaginated(t,e,r,i,n);return{messages:o.messages.map(c=>ds.formatSocketPeerMessage(c)),next:o.next}}async createChannel(t,e,r={}){var c;const i=(c=a(this,X).permissions)==null?void 0:c.chatChannel;if(i){if(i.canCreate==="NONE")throw new C("Not permitted to create channels","0501");if(r.visibility==="public"&&!(i.canCreate==="PUBLIC"||i.canCreate==="ALL"))throw new C("Not permitted to create public channels","0501");if(r.visibility==="private"&&!(i.canCreate==="PRIVATE"||i.canCreate==="ALL"))throw new C("Not permitted to create private channels","0501")}if(!t||t.trim().length===0)throw new C("channel name cannot be empty.","0510");const n=[...new Set([...e,a(this,X).userId])];return await a(this,ji).createChannel(t.trim(),n,r.displayPictureUrl,r.visibility,r.isDirectMessage)}updateChannel(t,e){var o,c,d,l,u;const r=this.channels.find(h=>h.id===t),i=(o=a(this,X).permissions)==null?void 0:o.chatChannel;if(i){if(i.canUpdate==="NONE")throw new C("Not permitted to update channels","0501");if(r.visibility==="public"&&!(i.canUpdate==="PUBLIC"||i.canUpdate==="ALL"))throw new C("Not permitted to update public channels","0501");if(r.visibility==="private"&&!(i.canUpdate==="PRIVATE"||i.canUpdate==="ALL"))throw new C("Not permitted to update private channels","0501")}const n={memberIds:(c=e.memberIds)!=null?c:r.memberIds,displayName:(d=e.displayName)!=null?d:r.displayName,displayPictureUrl:(l=e.displayPictureUrl)!=null?l:r.displayPictureUrl,visibility:(u=e.visibility)!=null?u:r.visibility};return a(this,ji).updateChannel(t,n)}async sendMessageToChannel(t,e,r={}){return this.sendMessageInternal(t,null,e,r)}async getChannelMembers(t){return a(this,ji).getChannelMembers(t)}async searchMessages(t,e){throw new C("searchMessages is disabled! Please use `fetchMessages` method instead.","0506")}async markLastReadMessage(t,e){await a(this,Be).markLastReadMessage(t,e);const r=this.channels.find(i=>i.id===t);if(r){const i={...r,unreadCount:0};this.channels=this.channels.map(n=>n.id===t?i:n),this.emit("channelMessageUpdate",i)}}get pinned(){return this.messages.filter(t=>t.pinned)}},X=new WeakMap,qi=new WeakMap,Be=new WeakMap,ji=new WeakMap,na=new WeakMap,Il=new WeakSet,vS=function(){return a(this,na).getValue("connectionHandler")},Bo=new WeakSet,gp=function(){return a(this,Il,vS).socketJoined===!0},Xv);gt([T.trace("Chat.sendTextMessage"),Lt(Xd)],et.prototype,"sendTextMessage",1),gt([T.trace("Chat.sendImageMessage"),Lt({maxInvocations:20,period:60})],et.prototype,"sendImageMessage",1),gt([T.trace("Chat.sendFileMessage"),Lt({maxInvocations:20,period:60})],et.prototype,"sendFileMessage",1),gt([T.trace("Chat.sendMessage"),Lt({maxInvocations:180,period:60})],et.prototype,"sendMessage",1),gt([T.trace("Chat.editTextMessage")],et.prototype,"editTextMessage",1),gt([T.trace("Chat.editImageMessage")],et.prototype,"editImageMessage",1),gt([T.trace("Chat.editFileMessage")],et.prototype,"editFileMessage",1),gt([T.trace("Chat.editMessage")],et.prototype,"editMessage",1),gt([T.trace("Chat.deleteMessage")],et.prototype,"deleteMessage",1),gt([T.trace("Chat.createChannel")],et.prototype,"createChannel",1),gt([T.trace("Chat.updateChannel")],et.prototype,"updateChannel",1),gt([T.trace("Chat.sendMessageToChannel")],et.prototype,"sendMessageToChannel",1),gt([T.trace("Chat.getChannelMembers")],et.prototype,"getChannelMembers",1),gt([T.trace("Chat.searchMessages")],et.prototype,"searchMessages",1),gt([T.trace("Chat.markLastReadMessage")],et.prototype,"markLastReadMessage",1),et=gt([ut("0500")],et);var kO=Object.defineProperty,IO=Object.getOwnPropertyDescriptor,AO=(s,t,e,r)=>{for(var i=r>1?void 0:r?IO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&kO(t,e,i),i};const Ii=(Zv=class{constructor(s,t,e,r,i){p(this,"chat");p(this,"chatSocketHandler");p(this,"chatChannelSocketHandler");p(this,"self");m(this,Gi,void 0);f(this,Gi,s),this.chatSocketHandler=t,this.chatChannelSocketHandler=e,this.chat=new et(s,t,e,r,i),this.self=r,this.setupEvents()}get telemetry(){return a(this,Gi).getValue("telemetry")}get logger(){return a(this,Gi).getValue("logger")}static async init(s,t,e,r,i){return new Ii(s,t,e,r,i)}static formatMessage(s){return{...s,time:new Date(s.time),type:RO[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,channelId:s.channelId,channelIndex:s.channelIndex,message:"",link:"",name:"",html:"",images:[],videos:[],files:[],size:0,pinned:s.pinned};switch(e.type){case Pt.TEXT:{e.message=s.payload;break}case Pt.IMAGE:{e.link=s.payload;break}case Pt.FILE:{const{link:r,name:i,size:n}=JSON.parse(s.payload);e.link=r,e.name=i,e.size=n;break}case Pt.CUSTOM:{const{html:r,images:i,message:n,videos:o,files:c}=JSON.parse(s.payload);e.message=n,e.html=r,e.images=i,e.videos=o,e.files=c;break}}return Ii.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=_f.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>Ii.formatSocketPeerMessage(e))}setupEvents(){a(this,Gi).getValue("peerSessionStore").on(R.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(Ae.sendMessageToRoom,s=>{const t=Ii.formatSocketPeerMessage(s.message);if(!t.channelId)this.chat.messages=[...this.chat.messages,t];else{const e=this.chat.channels.find(r=>r.id===t.channelId);e&&(e.latestMessage=t,e.unreadCount+=1,this.chat.emit("channelMessageUpdate",e))}this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Ae.sendMessageToPeers,s=>{const t=Ii.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(Ae.editMessage,s=>{const t=Ii.formatSocketPeerMessage(s.message);if(t.channelId){this.chat.emit("chatUpdate",{action:"edit",message:t,messages:this.chat.messages});return}const 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(Ae.deleteMessage,s=>{if(s.channelId){this.chat.emit("chatUpdate",{action:"delete",message:{id:s.chatId,channelId:s.channelId},messages:this.chat.messages});return}const t=this.chat.messages.findIndex(r=>r.id===s.chatId);if(t===-1)return;const[e]=this.chat.messages.splice(t,1);this.chat.emit("chatUpdate",{action:"delete",message:e,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(Ri.createChatChannel,s=>{const[t]=s.chatChannels,e=ki.formatChannel(t);this.chat.channels.push(e),this.chat.emit("channelCreate",e)}),this.chatSocketHandler.on(Ae.pinMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId);if(t===-1)return;const e=this.chat.messages[t];e.pinned=s.pinned,this.chat.messages[t]=e,this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(Ri.updateChatChannel,s=>{const[t]=s.chatChannels,e=ki.formatChannel(t);this.chat.channels=this.chat.channels.map(r=>r.id===e.id?e:r),this.chat.emit("channelUpdate",e)})}},Gi=new WeakMap,Zv);let ds=Ii;AO([T.trace("ChatController.setupEvents")],ds.prototype,"setupEvents",1);var MO=Object.defineProperty,OO=Object.getOwnPropertyDescriptor,DO=(s,t,e,r)=>{for(var i=r>1?void 0:r?OO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&MO(t,e,i),i};let Mh=(eS=class extends Gt{constructor(t,e,r){const i=t.getValue("logger");super(i);m(this,Al);m(this,Ml);p(this,"items");m(this,aa,void 0);m(this,oa,void 0);m(this,Ho,void 0);f(this,Ho,t),f(this,aa,e),f(this,oa,r),this.items=[]}async create(t,e,r=!1,i=!1){if(!a(this,Ml,yS))throw new C("Can't create polls without joining room","0705");if(!a(this,aa).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 a(this,oa).createPoll(t,e,r,i)}async vote(t,e){if(!a(this,aa).permissions.polls.canVote){this.logger.error("Polls::vote::permission_denied");return}await a(this,oa).votePoll(t,e)}},Al=new WeakSet,SS=function(){return a(this,Ho).getValue("connectionHandler")},Ml=new WeakSet,yS=function(){var t;return((t=a(this,Al,SS))==null?void 0:t.socketJoined)===!0},aa=new WeakMap,oa=new WeakMap,Ho=new WeakMap,eS);Mh=DO([ut("0700")],Mh);var NO=Object.defineProperty,VO=Object.getOwnPropertyDescriptor,LO=(s,t,e,r)=>{for(var i=r>1?void 0:r?VO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&NO(t,e,i),i};const qn=(tS=class{constructor(s,t,e){p(this,"polls");m(this,Qr,void 0);m(this,ca,void 0);m(this,Wi,void 0);this.polls=new Mh(s,t,e),f(this,ca,t),f(this,Qr,s),f(this,Wi,e),this.setupEvents()}get telemetry(){return a(this,Qr).getValue("telemetry")}get logger(){return a(this,Qr).getValue("logger")}static async init(s,t,e){return new qn(s,t,e)}canViewPolls(){return a(this,ca).permissions.polls.canView}setupEvents(){const s={[lr.createPoll]:r=>{r.poll&&this.updatePoll(qn.formatSocketServicePoll(r.poll))},[lr.updatePoll]:r=>{r.poll&&this.updatePoll(qn.formatSocketServicePoll(r.poll))},[lr.votePoll]:r=>{r.poll&&this.updatePoll(qn.formatSocketServicePoll(r.poll))}},t=()=>{a(this,Qr).getValue("peerSessionStore").on(R.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,Wi).on(r,s[r])})},e=()=>{a(this,Qr).getValue("peerSessionStore").on(R.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,Wi).removeListeners(r)})};a(this,ca).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 a(this,Wi).getPolls();if(!(s!=null&&s.payload))return;const{polls:t}=JM.fromBinary(s.payload);this.polls.items=t.map(e=>qn.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}}},Qr=new WeakMap,ca=new WeakMap,Wi=new WeakMap,tS);let Ff=qn;LO([T.trace("PollController.setupEvents")],Ff.prototype,"setupEvents",1);var xO=Object.defineProperty,UO=Object.getOwnPropertyDescriptor,FO=(s,t,e,r)=>{for(var i=r>1?void 0:r?UO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&xO(t,e,i),i},$f=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))($f||{});let Oh=(sS=class extends Gt{constructor(t,e,r,i,n){const o=t.getValue("logger");super(o);m(this,qo);p(this,"selfActiveTab");p(this,"broadcastTabChanges");m(this,da,void 0);m(this,Ji,void 0);m(this,jo,void 0);p(this,"viewType");p(this,"meetingStartedTimestamp");p(this,"meetingTitle");p(this,"sessionId");f(this,da,t),f(this,Ji,e),this.viewType=r,f(this,jo,i),this.meetingTitle=n,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return a(this,qo,mp).socketState}get mediaState(){return a(this,qo,mp).mediaState}get meetingId(){return a(this,da).getValue("meetingId")}setBroadcastTabChanges(t){if(!a(this,Ji).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=a(this,Ji).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){a(this,jo).broadcastMessage("spotlight",{userId:a(this,Ji).userId,currentTab:this.selfActiveTab})}},da=new WeakMap,qo=new WeakSet,mp=function(){return a(this,da).getValue("connectionHandler")},Ji=new WeakMap,jo=new WeakMap,sS);Oh=FO([ut("0800")],Oh);function $O(s){let t="",e=[""];const r=[e];let i=0,n=0,o=!0,c;for(c of s)c==='"'?(o&&c===t&&(e[i]+=c),o=!o):c===","&&o?c=e[++i]="":c===`
14
14
  `&&o?(t==="\r"&&(e[i]=e[i].slice(0,-1)),e=r[++n]=[c=""],i=0):e[i]+=c,t=c;return r}var BO=Object.defineProperty,HO=Object.getOwnPropertyDescriptor,Bf=(s,t,e,r)=>{for(var i=r>1?void 0:r?HO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&BO(t,e,i),i};let Hr=(rS=class extends Gt{constructor(t){const e=t.getValue("logger");super(e);p(this,"transcripts");m(this,Go,void 0);f(this,Go,t),this.transcripts=[]}get telemetry(){return a(this,Go).getValue("telemetry")}static async init(t,e){const r=new Hr(t),i=t.getValue("logger");try{e&&r.getActiveTranscript()}catch(n){i.error("Error fetching active transcriptions ",n)}return r}static parseTranscript(t,e=!1){if(!t)return;const[[r,i,n,o,c,d]]=$O(t);return{id:vi(),name:c,peerId:i,userId:n,customParticipantId:o,transcript:d,isPartialTranscript:e,date:new Date(parseInt(r,10)*1e3)}}static parseTranscripts(t){return t?t.split(`
15
15
  `).map(e=>Hr.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=pt(),{transcript:e}=await t.getActiveTranscript();this.transcripts=Hr.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)}},Go=new WeakMap,rS);Bf([T.trace("Ai.getActiveTranscript")],Hr.prototype,"getActiveTranscript",1),Hr=Bf([ut("0000")],Hr);var qO=Object.defineProperty,jO=Object.getOwnPropertyDescriptor,GO=(s,t,e,r)=>{for(var i=r>1?void 0:r?jO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&qO(t,e,i),i};const Hf=(iS=class{constructor(s,t,e,r,i,n){p(this,"meta");p(this,"ai");m(this,Xr,void 0);m(this,la,void 0);p(this,"aiSocketHandler");m(this,Qt,void 0);f(this,Qt,s),this.meta=new Oh(s,t,t.config.viewType,e,n),this.ai=r,f(this,Xr,t),f(this,la,e),this.aiSocketHandler=i,t.config.viewType!==Vt.Chat&&this.setupEvents()}get telemetry(){return a(this,Qt).getValue("telemetry")}get logger(){return a(this,Qt).getValue("logger")}static async init(s,t,e,r,i){const n=await Hr.init(s,t.permissions.transcriptionEnabled);return new Hf(s,t,e,n,r,i)}conditionallySetActiveTab(s){var t;s!=null&&s.currentTab&&((t=this.meta.selfActiveTab)==null?void 0:t.id)!==s.currentTab.id&&(this.meta.setSelfActiveTab(s.currentTab,$f.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){a(this,Qt).getValue("peerSessionStore").on(R.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),a(this,Qt).getValue("peerSessionStore").on(R.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),a(this,Qt).getValue("peerSessionStore").on(R.ROOM_STATE,({createdAt:s,roomUuid:t})=>{const e=this.meta.meetingStartedTimestamp;if(t&&(this.meta.sessionId=t),s&&!e){const r=new Date(s*1e3);this.meta.meetingStartedTimestamp=r,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),a(this,Qt).getValue("peerSessionStore").on(R.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),a(this,Xr).permissions.canSpotlight&&(this.logger.info("MetaController::Asserting Spotlight"),this.meta.selfActiveTab&&a(this,la).broadcastMessage("spotlight",{userId:a(this,Xr).userId,currentTab:this.meta.selfActiveTab})),a(this,Qt).getValue("peerSessionStore").on(R.PEER_JOINED_INTERNAL,async s=>{a(this,Xr).permissions.canSpotlight&&this.meta.selfActiveTab&&a(this,la).broadcastToPeers("spotlight",[s.id],{userId:a(this,Xr).userId,currentTab:this.meta.selfActiveTab})}),a(this,Qt).getValue("peerSessionStore").on(R.ROOM_MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),a(this,Qt).getValue("peerSessionStore").on(R.MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),this.aiSocketHandler.on(F.transcript,s=>{const{meetingId:t,transcript:e,isPartial:r}=s;let i;try{i=Hr.parseTranscript(e,r)}catch(d){this.logger.error(`Failed to parse transcript: ${e}`,d)}if(!i){this.logger.warn("Received empty transcript data");return}this.ai.onTranscript(i),this.meta.emit("transcript",i);const{peerId:n,name:o,transcript:c}=i;this.logger.debug(`${t} Received transcript for peer ${n} - ${o}: ${c}`)})}},Xr=new WeakMap,la=new WeakMap,Qt=new WeakMap,iS);let qf=Hf;GO([T.trace("MetaController.setupEvents")],qf.prototype,"setupEvents",1);const wo={},ur={executeWithLock({methodName:s,lockName:t,timeout:e}){return(r,i,n)=>{const o=n.value;return n.value=function(...d){var E,b;const l=(b=(this==null?void 0:this.peerId)||((E=d[0])==null?void 0:E.authToken))!=null?b:"",u=`${t}-${l}`,h=this==null?void 0:this.logger;if(wo[u]){const P=new Error(`Unsupported concurrent calls on method: ${s}.`);throw P.name="UnsupportedConcurrentMethodExecution",h==null||h.error("Locker::UnsupportedConcurrentMethodExecution",{error:{stack:P.stack},locker:{methodName:s,lockName:u}}),P}wo[u]=!0;const g=setTimeout(()=>delete wo[u],e),v=o.apply(this,d);return Promise.resolve(v).then(()=>{delete wo[u],clearTimeout(g)}).catch(()=>{delete wo[u],clearTimeout(g)}),v},n}}};var WO=Object.defineProperty,JO=Object.getOwnPropertyDescriptor,Ai=(s,t,e,r)=>{for(var i=r>1?void 0:r?JO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&WO(t,e,i),i};class qr extends Gt{constructor(e,r,i,n,o){const c=e.getValue("logger");super(c);m(this,Jo);m(this,ua);m(this,hs,void 0);m(this,Ol,void 0);m(this,ne,void 0);m(this,Wo,void 0);m(this,Js,void 0);m(this,rt,void 0);f(this,rt,e),f(this,hs,n),f(this,Ol,o),f(this,ne,r),f(this,Wo,i),f(this,Js,[]),this.setupEvents()}get telemetry(){return a(this,rt).getValue("telemetry")}get status(){return a(this,rt).getValue("stageStatus")}setupEvents(){const e={[R.GET_STAGE_REQUESTS]:async n=>{f(this,Js,n)},[R.UPDATE_STAGE_REQUESTS]:async({add:n})=>{const o=a(this,Js).length,{stageRequests:c}=this.getAccessRequests();(n||c.length>o)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)}},r=()=>{Object.entries(e).forEach(([n,o])=>{a(this,rt).getValue("peerSessionStore").onAsync(n,o)})},i=()=>{Object.entries(e).forEach(([n,o])=>{a(this,rt).getValue("peerSessionStore").removeListener(n,o)})};a(this,ne).permissions.on("permissionsUpdate",n=>{const{canAcceptProductionRequests:o}=n;o!==void 0&&(a(this,ne).permissions.acceptStageRequests?(r(),a(this,hs).getStageRequests()):(i(),f(this,Js,[]),this.emit("stageAccessRequestUpdate",a(this,Js))))}),a(this,ne).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!a(this,ne).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,ne).permissions.acceptStageRequests)throw this.logger.error("Stage::get_access_request::permission_denied"),new C("You do not have permission to perform this action","2001");const e=a(this,Wo).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return f(this,Js,e),{stageRequests:a(this,Js)}}async requestAccess(){if(!a(this,ne).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new C(`Unable to request access you are currently ${this.status}`,"2006");if(a(this,ne).permissions.stageAccess===H.Allowed){U(this,ua,Eu).call(this,"ACCEPTED_TO_JOIN_STAGE");return}a(this,hs).requestAccess(),U(this,ua,Eu).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!a(this,ne).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");a(this,hs).cancelRequestAccess(),U(this,ua,Eu).call(this,"OFF_STAGE")}grantAccess(e){if(!a(this,ne).roomJoined)throw new C("Can`t grant for participant without joining room");if(!a(this,ne).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,ne).permissions.acceptStageRequests)throw this.logger.error("Stage::grant_access::permission_denied"),new C("You do not have permission to perform this action","2001");return a(this,hs).grantAccess(e)}denyAccess(e){if(!a(this,ne).roomJoined)throw new C("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!a(this,ne).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,ne).permissions.acceptStageRequests)throw this.logger.error("Stage::deny_access::permission_denied"),new C("You do not have permission to perform this action","2001");return a(this,hs).denyAccess(e)}get peerId(){return a(this,rt).getValue("peerId")}async join(){const e=a(this,rt).getValue("viewType");if(this.status==="ON_STAGE")throw new C("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||a(this,ne).permissions.stageAccess===H.NotAllowed)throw new C(`Unable to join stage you are currently ${this.status}`,"2006");if(a(this,rt).setValue("stageStatus","ON_STAGE",!1),await a(this,hs).joinStage(),e===Vt.Livestream){await a(this,rt).getValue("selfController").joinRoom();return}a(this,rt).notify("stageStatus"),a(this,ne).audioEnabled&&a(this,Jo,fp).shareMic(a(this,ne).audioTrack),a(this,ne).videoEnabled&&a(this,Jo,fp).shareWebcam(a(this,ne).videoTrack)}async leave(){if(!a(this,ne).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new C(`Unable to leave stage you are currently ${this.status}`,"2006");a(this,ne).setIsPinned(!1),a(this,rt).setValue("stageStatus","OFF_STAGE",!1),await a(this,hs).leaveStage(a(this,ne).userId);try{await a(this,rt).getValue("peerSessionStore").emitAsync(R.LEAVE_MEDIA_ROOM,"stageLeft")}catch(e){this.logger.error("Stage::leave::emitAsync::failed",{error:e})}a(this,rt).notify("stageStatus")}async kick(e){if(!a(this,ne).roomJoined)throw new C("Can`t kick participant without joining room","2005");if(!a(this,ne).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,ne).permissions.acceptStageRequests)throw this.logger.error("Stage::kick::permission_denied"),new C("You do not have permissions for kick","2001");return a(this,hs).kick(e)}}hs=new WeakMap,Ol=new WeakMap,ne=new WeakMap,Wo=new WeakMap,Js=new WeakMap,rt=new WeakMap,Jo=new WeakSet,fp=function(){return a(this,rt).getValue("roomNodeClient")},ua=new WeakSet,Eu=async function(e){this.status!==e&&a(this,rt).setValue("stageStatus",e)},Ai([T.trace("Stage.getStageRequests")],qr.prototype,"getAccessRequests",1),Ai([T.trace("Stage.requestAccess")],qr.prototype,"requestAccess",1),Ai([T.trace("Stage.cancelRequestAccess")],qr.prototype,"cancelRequestAccess",1),Ai([T.trace("Stage.grantAccess")],qr.prototype,"grantAccess",1),Ai([T.trace("Stage.denyAccess")],qr.prototype,"denyAccess",1),Ai([ur.executeWithLock({methodName:"joinStage",lockName:"Stage.join",timeout:5e3}),T.trace("Stage.joinStage")],qr.prototype,"join",1),Ai([T.trace("Stage.leaveStage")],qr.prototype,"leave",1);function KO(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function Dh(s){switch(s){case cr.UNSPECIFIED:return"OFF_STAGE";case cr.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case cr.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case cr.OFF_STAGE:return"OFF_STAGE";case cr.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var zO=Object.defineProperty,YO=Object.getOwnPropertyDescriptor,QO=(s,t,e,r)=>{for(var i=r>1?void 0:r?YO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&zO(t,e,i),i};class jf{constructor(t,e,r,i,n){p(this,"stage");m(this,Zr,void 0);m(this,Ms,void 0);m(this,ei,void 0);m(this,Ko,0);m(this,kt,void 0);f(this,kt,t),this.stage=new qr(t,i,n,e,r),f(this,ei,e),f(this,Zr,i),f(this,Ms,n),this.setupEvents()}get telemetry(){return a(this,kt).getValue("telemetry")}get logger(){return a(this,kt).getValue("logger")}setupEvents(){a(this,kt).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),a(this,ei).on(F.grantStageAccess,()=>{a(this,Zr).permissions.stageAccess!==H.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),a(this,ei).on(F.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===a(this,Zr).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),a(this,ei).on(F.denyStageAccess,()=>{a(this,Zr).permissions.stageAccess!==H.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),a(this,ei).on(F.getStageRequests,async t=>{var r;if(a(this,Zr).permissions.stageAccess!==H.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await a(this,kt).getValue("peerSessionStore").emitAsync(R.GET_STAGE_REQUESTS,e),a(this,Ko)<e.length&&e.length>0&&this.stage.emit("newStageRequest",{count:e.length}),f(this,Ko,e.length),this.stage.emit("stageAccessRequestUpdate",e)})}getCurrentStageRequests(){return a(this,Ms).joined.toArray().filter(e=>e.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(e=>({displayName:e.name,userId:e.userId,peerId:e.id}))}async setStageStatus(t){this.stage.status!==t&&a(this,kt).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=Dh(t.stageType),r=a(this,kt).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:a(this,kt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(r);break;case 0:case 4:default:a(this,kt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}async peerStageStatusHandler(t){const e=a(this,Ms).joined.get(t.peerId),r=a(this,Ms).viewMode==="ACTIVE_GRID";if(!e){this.logger.warn("err::peerStageStatusUpdate: participant not found");return}switch(t.stageType){case 1:e.setStageStatus("ON_STAGE"),r&&a(this,kt).getValue("peerSessionStore").emit(R.UPDATE_ACTIVE,{viewMode:a(this,Ms).viewMode,page:a(this,Ms).currentPage});break;case 2:e.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:e.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:e.setStageStatus("OFF_STAGE"),r&&a(this,kt).getValue("peerSessionStore").emit(R.UPDATE_ACTIVE,{viewMode:a(this,Ms).viewMode,page:a(this,Ms).currentPage});break}a(this,kt).getValue("peerSessionStore").emit(R.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}Zr=new WeakMap,Ms=new WeakMap,ei=new WeakMap,Ko=new WeakMap,kt=new WeakMap,QO([T.trace("Stage.setupEvents")],jf.prototype,"setupEvents",1);var XO=Object.defineProperty,ZO=Object.getOwnPropertyDescriptor,Zd=(s,t,e,r)=>{for(var i=r>1?void 0:r?ZO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&XO(t,e,i),i};const De={getPeer:14,getPeers:15,chatMessage:16,getRoomName:17,getDisplayTitle:18,getPluginInitiator:19,customPluginEventToParent:20,peerJoined:22,peerLeft:23,sendData:24,stageStatusUpdate:25,peerStageStatusUpdate:26};let jn=(nS=class extends Fn{constructor(t,{baseURL:e,createdAt:r,description:i,id:n,name:o,organizationId:c,picture:d,private:l,published:u,staggered:h,tags:g,type:v,updatedAt:E},b,P,w,L,$){const N=t.getValue("logger");super(N);m(this,vt,void 0);p(this,"baseURL");p(this,"createdAt");p(this,"description");p(this,"id");p(this,"name");m(this,Xt,void 0);m(this,ha,void 0);m(this,pa,void 0);p(this,"organizationId");p(this,"picture");p(this,"private");p(this,"published");p(this,"staggered");p(this,"tags");p(this,"type");p(this,"updatedAt");m(this,Tr,void 0);p(this,"config");m(this,ga,void 0);p(this,"active");p(this,"iframes");p(this,"enabledBy");m(this,ti,void 0);m(this,ma,void 0);f(this,ti,t),this.baseURL=e,this.createdAt=new Date(r),this.description=i,this.id=n,this.name=o,f(this,Xt,P),this.organizationId=c,this.picture=d,this.private=l,this.published=u,this.staggered=h,this.tags=g,this.type=v,this.updatedAt=new Date(E),this.active=!1,this.iframes=new Map,f(this,vt,b),f(this,ha,w),f(this,pa,L),this.enabledBy="",f(this,ma,$)}get telemetry(){return a(this,ti).getValue("telemetry")}sendIframeEvent(t){this.iframes.size&&this.iframes.forEach(e=>{const{iframe:r}=e;r&&(navigator.isReactNative?r.postMessage(JSON.stringify(t)):r.contentWindow.postMessage(t,"*"))})}async handleIframeMessage(t){var o;if(!this.active)return;const e=t,{payload:r,uuid:i,type:n}=e;switch(n){case G.customPluginEventToRoom:{a(this,vt).customPluginEventToRoom(this.id,r,i);break}case G.customPluginEventToPeers:{a(this,vt).customPluginEventToPeers(this.id,r.peerIds,r,i);break}case G.enablePluginForRoom:{a(this,vt).enablePluginForRoom(this.id,i);break}case G.enablePluginForPeers:{a(this,vt).enablePluginForPeers(this.id,r.peerIds,i);break}case G.disablePluginForRoom:{a(this,vt).disablePluginForRoom(this.id,i);break}case G.disablePluginForPeers:{a(this,vt).disablePluginForPeers(this.id,r.peerIds,i);break}case G.storeInsertKeys:{a(this,vt).storeInsertKeys(this.id,r.store,r.insertKeys,i);break}case G.storeGetKeys:{a(this,vt).storeGetKeys(this.id,r.store,r.getKeys,i);break}case G.storeDeleteKeys:{a(this,vt).storeDeleteKeys(this.id,r.store,r.deleteKeys,i);break}case G.storeDelete:{a(this,vt).storeDelete(this.id,r.store,i);break}case De.chatMessage:{const{messagePayload:c,peerIds:d}=r;if(!a(this,pa)){this.sendIframeEvent({type:De.chatMessage,uuid:e.uuid,payload:{error:"Chat is disabled for this room."}});return}try{await a(this,pa).sendMessage(c,d),this.sendIframeEvent({type:De.chatMessage,uuid:e.uuid,payload:{success:!0}})}catch(l){this.sendIframeEvent({type:De.chatMessage,uuid:e.uuid,payload:{error:l}})}break}case De.getPeer:{let c;const{peerId:d}=r,l={...a(this,Xt),id:a(this,Xt).id,isRecorder:(o=a(this,Xt).permissions)==null?void 0:o.isRecorder,isHidden:a(this,Xt).permissions.hiddenParticipant,stageStatus:a(this,Xt).stageStatus};d?(c=a(this,ha).joined.get(r.peerId),a(this,Xt).id===d&&(c=l)):c=l,this.sendIframeEvent({type:De.getPeer,payload:{peer:c&&Qd(c)},uuid:e.uuid});break}case De.getPeers:{const c=a(this,ha).joined.toArray().map(d=>Qd(d));this.sendIframeEvent({type:De.getPeers,payload:{peers:c},uuid:e.uuid});break}case De.getPluginInitiator:{this.sendIframeEvent({type:De.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:e.uuid});break}case De.getDisplayTitle:{this.sendIframeEvent({type:De.getDisplayTitle,payload:{displayTitle:a(this,ma)},uuid:e.uuid});break}case De.getRoomName:{this.sendIframeEvent({type:De.getRoomName,payload:{roomName:a(this,ti).getValue("meetingId")},uuid:e.uuid});break}case De.customPluginEventToParent:{this.emit(e.payload.eventName,e.payload.data);break}}}sendData(t){this.active&&(this.logger.info("Plugin::SendData",{plugin:{id:this.id,name:this.name,data:{eventName:t.eventName}}}),this.sendIframeEvent({type:De.sendData,uuid:"",payload:t}))}removePluginView(t="default"){var i;const{iframe:e,listener:r}=(i=this.iframes.get(t))!=null?i:{};(e||r)&&(navigator.isReactNative?e.props.onMessage=void 0:window.removeEventListener("message",r),this.iframes.delete(t))}addPluginView(t,e="default"){var o;if(!a(this,ga))throw this.logger.error("Plugin::addPluginView::no_auth_token_set_for_plugin"),new C("No auth token set for plugin.","0602");if(!t)throw this.logger.error("Plugin::addPluginView::iframe_was_not_provided"),new C("Iframe was not provided.","0603");this.removePluginView(e);const r=t,i=new URL(this.baseURL),n={auth:a(this,ga),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:a(this,ti).getValue("apiBase"),pluginId:this.id,roomName:(o=a(this,ti).getValue("meetingId"))!=null?o:"",displayTitle:a(this,ma)};if(Object.keys(n).forEach(c=>{i.searchParams.set(c,n[c])}),r.src=i.href,r.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",r.title=e,navigator.isReactNative)r.props.onMessage=c=>{this.handleIframeMessage(JSON.parse(c.nativeEvent.data))},this.iframes.set(e,{iframe:r});else{const c=async d=>{d.source===t.contentWindow&&await this.handleIframeMessage(d.data)};window.addEventListener("message",c),this.iframes.set(e,{iframe:r,listener:c})}}setActive(t){var e,r;if(this.active=t,t){this.emit("stateUpdate",{active:this.active,pluginId:this.id,bind:this.addPluginView.bind(this),views:(e=this.config)==null?void 0:e.views});return}this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id,views:(r=this.config)==null?void 0:r.views})}async activateForSelf(){const t=pt(),e=await t.authorizePlugin(this.id);f(this,ga,e),f(this,Tr,new Date);try{const r=await t.getPluginConfig(this.baseURL);this.config=r}catch(r){this.logger.error("Plugin::activateForSelf",{error:r})}this.setActive(!0),this.emit("enabled")}deactivateForSelf(){Array.from(this.iframes.keys()).forEach(t=>{this.removePluginView(t)}),f(this,Tr,void 0),this.iframes.clear(),this.setActive(!1),this.emit("closed")}async enable(){return this.activateForSelf()}disable(){return this.deactivateForSelf()}async activate(){var t,e;this.active||(e=(t=a(this,Xt).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(a(this,vt).addPlugin(this.id,this.staggered),f(this,Tr,new Date),this.logger.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}}))}async deactivate(){var t,e;this.active&&(!((e=(t=a(this,Xt).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==a(this,Xt).id||(a(this,vt).removePlugin(this.id),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:a(this,Tr)?new Date().getTime()-a(this,Tr).getTime():0}}),f(this,Tr,void 0)))}},vt=new WeakMap,Xt=new WeakMap,ha=new WeakMap,pa=new WeakMap,Tr=new WeakMap,ga=new WeakMap,ti=new WeakMap,ma=new WeakMap,nS);Zd([Lt({maxInvocations:5,period:1})],jn.prototype,"sendData",1),Zd([T.trace("Plugin.activatePlugin")],jn.prototype,"activate",1),Zd([T.trace("Plugin.deactivatePlugin")],jn.prototype,"deactivate",1),jn=Zd([ut("0600")],jn);class Gf extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:n,onClearEvent:o}=e;super();m(this,He,void 0);m(this,Ki,void 0);p(this,"onAddEvent");p(this,"onDeleteEvent");p(this,"onClearEvent");f(this,He,new Fn(r)),this.onAddEvent=i,this.onDeleteEvent=n,this.onClearEvent=o,f(this,Ki,new Map)}emit(e,...r){return a(this,He).emit(e,...r)}on(e,r){return a(this,He).on(e,r)}addListener(e,r){return a(this,He).addListener(e,r)}off(e,r){return a(this,He).off(e,r)}once(e,r){return a(this,He).once(e,r)}prependListener(e,r){return a(this,He).prependListener(e,r)}prependOnceListener(e,r){return a(this,He).prependOnceListener(e,r)}removeListener(e,r){return a(this,He).removeListener(e,r)}removeAllListeners(e){return a(this,He).removeAllListeners(e)}listeners(e){return a(this,He).listeners(e)}listenerCount(e){return a(this,He).listenerCount(e)}getMaxListeners(){return a(this,He).getMaxListeners()}setMaxListeners(e){return a(this,He).setMaxListeners(e)}eventNames(){return a(this,He).eventNames()}add(e,r=!0){return this.set(e.id,e,r)}set(e,r,i=!0){const n=super.set(e,r),o=(c,...d)=>{this.emit(c,r,...d)};return a(this,Ki).set(e,o),r.on("*",o),i&&a(this,He).emit(this.onAddEvent,r),n}delete(e,r=!0,i=!1){const n=this.get(e);if(!n)return!1;n.removeListener("*",a(this,Ki).get(e));const o=super.delete(e);return i&&n.removeAllListeners(),r&&a(this,He).emit(this.onDeleteEvent,n),o}clear(e=!0,r=!1){this.forEach(n=>{n.removeListener("*",a(this,Ki).get(n.id)),r&&n.removeAllListeners()});const i=super.clear();return e&&a(this,He).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}He=new WeakMap,Ki=new WeakMap;class Wf extends Gf{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 eD=Object.defineProperty,tD=Object.getOwnPropertyDescriptor,sD=(s,t,e,r)=>{for(var i=r>1?void 0:r?tD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&eD(t,e,i),i};let Nh=class{constructor(s){p(this,"all");p(this,"active");this.all=new Wf(s),this.active=new Wf(s)}};Nh=sD([ut("0600")],Nh);var rD=Object.defineProperty,iD=Object.getOwnPropertyDescriptor,el=(s,t,e,r)=>{for(var i=r>1?void 0:r?iD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&rD(t,e,i),i};const Jf=(aS=class{constructor(s,t,e,r){p(this,"plugins");m(this,ps,void 0);m(this,fa,void 0);m(this,Os,void 0);f(this,ps,t),f(this,fa,e),f(this,Os,s),this.plugins=r,this.setupEvents()}get telemetry(){return a(this,Os).getValue("telemetry")}get logger(){return a(this,Os).getValue("logger")}static async init(s,t,e,r,i,n,o,c){const d=s.getValue("logger"),l=new Nh(d);return t.forEach(u=>{const h=new jn(s,u,e,n,o,i,c);l.all.add(h)}),new Jf(s,e,r,l)}async getRoomPlugins(){var t;const{plugins:s}=await a(this,ps).getActivePlugins();(t=this.plugins.active)==null||t.toArray().forEach(e=>{this.disablePlugin({id:e.id})}),await Promise.all(s.map(e=>this.enablePlugin({id:e.pluginId,enabledBy:e.enabledBy})))}async enablePlugin({id:s,enabledBy:t}){const e=this.plugins.all.get(s);e&&(await e.activateForSelf(),e.enabledBy=t)}async disablePlugin({id:s}){const t=this.plugins.all.get(s);t&&t.deactivateForSelf()}sendIframeEvent(s,t,e,r){const i=this.plugins.all.get(t);i&&i.sendIframeEvent({type:s,uuid:e,payload:r})}broadcastIframeEvent(s,t){this.plugins.active.forEach(e=>{this.sendIframeEvent(s,e.id,"",t)})}setupEvents(){this.plugins.all.on("stateUpdate",({active:s,id:t})=>{if(s){this.plugins.active.add(this.plugins.all.get(t));return}this.plugins.active.delete(t)}),a(this,Os).getValue("peerSessionStore").onAsync(R.SOCKET_SERVICE_ROOM_JOINED,async()=>{await this.getRoomPlugins(),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")}),a(this,ps).on(G.addPlugin,async s=>{var e;const t=s.pluginId;(e=this.plugins.all.get(t))!=null&&e.active||await this.enablePlugin({id:t,enabledBy:s.enabledBy})}),a(this,ps).on(G.removePlugin,async s=>{var e;const t=s.pluginId;(e=this.plugins.all.get(t))!=null&&e.active&&await this.disablePlugin({id:t})}),[G.enablePluginForPeers,G.enablePluginForRoom].forEach(s=>{a(this,ps).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{enabledBy:t.enabledBy})})}),[G.disablePluginForPeers,G.disablePluginForRoom].forEach(s=>{a(this,ps).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{disabledBy:t.disabledBy})})}),[G.customPluginEventToPeers,G.customPluginEventToRoom].forEach(s=>{a(this,ps).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{data:JSON.parse(new TextDecoder().decode(t.pluginData))})})}),[G.storeInsertKeys,G.storeGetKeys,G.storeDeleteKeys].forEach(s=>{a(this,ps).on(s,async(t,e)=>{var i;const r=(i=t.storeItems)==null?void 0:i.map(n=>{var o;return{timestamp:n.timestamp,peerId:n.peerId,payload:JSON.parse((o=n.payload)!=null&&o.length?new TextDecoder().decode(n.payload):"{}"),key:n.storeKey}});this.sendIframeEvent(s,t.pluginId,e,{storeName:t.storeName,storeItems:r})})}),a(this,ps).on(G.storeDelete,async(s,t)=>{this.sendIframeEvent(G.storeDelete,s.pluginId,t,{storeName:s.storeName})}),a(this,fa).on(Ae.sendMessageToPeers,s=>{const t=ds==null?void 0:ds.formatSocketPeerMessage(s.message);this.broadcastIframeEvent(De.chatMessage,{message:t})}),a(this,fa).on(Ae.sendMessageToRoom,s=>{const t=ds==null?void 0:ds.formatSocketPeerMessage(s.message);this.broadcastIframeEvent(De.chatMessage,{message:t})}),a(this,Os).getValue("peerSessionStore").on(R.PEER_JOINED_INTERNAL,s=>{const t=Qd(s);this.broadcastIframeEvent(De.peerJoined,t)}),a(this,Os).getValue("peerSessionStore").on(R.PEER_CLOSED,s=>{this.broadcastIframeEvent(De.peerLeft,s)}),a(this,Os).getValue("peerSessionStore").on(R.UPDATE_PEER_STAGE_STATUS,s=>{this.broadcastIframeEvent(De.peerStageStatusUpdate,s)}),a(this,Os).subscribe("stageStatus",s=>{this.broadcastIframeEvent(De.stageStatusUpdate,s)})}},ps=new WeakMap,fa=new WeakMap,Os=new WeakMap,aS);let Po=Jf;el([T.trace("PluginController.getRoomPlugins")],Po.prototype,"getRoomPlugins",1),el([T.trace("PluginController.enableForSelf")],Po.prototype,"enablePlugin",1),el([T.trace("PluginController.disableForSelf")],Po.prototype,"disablePlugin",1),el([T.trace("PluginController.setupEvents")],Po.prototype,"setupEvents",1);class nD{constructor(t){p(this,"mediaJoined");p(this,"socketJoined");p(this,"socketJoinAttempted");p(this,"mediaJoinAttempted");p(this,"socketState");p(this,"mediaState");m(this,zo,void 0);this.mediaJoined=!1,this.socketJoined=!1,this.socketJoinAttempted=!1,this.mediaJoinAttempted=!1,this.socketState={state:void 0,reconnected:!1,reconnectionAttempt:void 0},this.mediaState={recv:void 0,send:void 0},f(this,zo,t)}get joinAttempted(){return this.mediaJoinAttempted||this.socketJoinAttempted}get roomJoined(){return this.mediaJoined&&this.socketJoined}updateSocketConnectionState(t,e){let r;const{reconnected:i}=this.socketState;switch(t){case"connected":r={state:"connected",reconnected:i,reconnectionAttempt:void 0};break;case"disconnected":r={state:"disconnected",reconnected:!1,reconnectionAttempt:0},this.socketJoined=!1;break;case"reconnected":r={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":r={state:"reconnecting",reconnected:i,reconnectionAttempt:0};break;case"reconnectAttempt":r={state:"reconnecting",reconnected:i,reconnectionAttempt:e};break;case"failed":r={state:"failed",reconnected:i,reconnectionAttempt:void 0},this.socketJoined=!1;break}r&&(a(this,zo).getValue("peerSessionStore").emit(R.SOCKET_STATE_UPDATE,r),this.socketState=r)}}zo=new WeakMap;var aD=Object.defineProperty,oD=Object.getOwnPropertyDescriptor,_o=(s,t,e,r)=>{for(var i=r>1?void 0:r?oD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&aD(t,e,i),i};let Mi=(oS=class extends Gt{constructor(t,e){const r=t.getValue("logger");super(r);m(this,ya);m(this,va,void 0);m(this,Sa,void 0);p(this,"recordingPeerIds",[]);p(this,"recordings",[]);f(this,Sa,t),f(this,va,e)}get recordingState(){return this.recordings.some(t=>t.state==="RECORDING")?"RECORDING":this.recordings.some(t=>t.state==="PAUSED")?"PAUSED":this.recordings.some(t=>t.state==="STARTING")?"STARTING":this.recordings.some(t=>t.state==="STOPPING")?"STOPPING":"IDLE"}get telemetry(){return a(this,Sa).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!a(this,va).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(`Cant start recording, recordingState irregular: ${this.recordingState}`,"1005");try{const e=pt(),{recording:r={}}=a(this,Sa).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::stop::recording_failed_to_start",{error:e}),new C("Error while starting recording","1000",this.logger)}}async stop(t){await U(this,ya,bu).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await U(this,ya,bu).call(this,"pause",["RECORDING"],t)}async resume(t){await U(this,ya,bu).call(this,"resume",["PAUSED"],t)}},va=new WeakMap,Sa=new WeakMap,ya=new WeakSet,bu=async function(t,e,r){if(!a(this,va).permissions.canRecord)throw this.logger.error("Recording::stop::permission_denied"),new C("User does not have permission to stop recording","1001");let i=[];if(r!==void 0){const n=this.recordings.find(o=>o.id===r);if(n===void 0)throw new C("Could not find the specified recording","1004");if(e.includes(n.state)){this.logger.error("Recording::stop::recording_not_in_expected_state",{recording:{state:n.state}});return}i.push(n)}else i=this.recordings.filter(n=>e.includes(n.state));i.forEach(async n=>{const o=n.state;t==="stop"&&(n.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{await pt().updateRecording(n.id,t)}catch(c){throw this.logger.error("Recording::stop::recording_failed_to_stop",{error:c}),n.state!==o&&(n.state=o,this.emit("recordingUpdate",o)),new C("Error while stopping recording","1000",this.logger)}})},oS);_o([T.trace("Recording.start")],Mi.prototype,"start",1),_o([T.trace("Recording.stop")],Mi.prototype,"stop",1),_o([T.trace("Recording.stop")],Mi.prototype,"pause",1),_o([T.trace("Recording.stop")],Mi.prototype,"resume",1),Mi=_o([ut("1000")],Mi);var cD=Object.defineProperty,dD=Object.getOwnPropertyDescriptor,lD=(s,t,e,r)=>{for(var i=r>1?void 0:r?dD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&cD(t,e,i),i};class Kf{constructor(t,e,r){p(this,"recording");p(this,"room");m(this,zi,void 0);f(this,zi,t),this.recording=new Mi(t,e),this.room=r,this.setupEvents()}get telemetry(){return a(this,zi).getValue("telemetry")}get logger(){return a(this,zi).getValue("logger")}getRecordingTypeFromProtoType(t){let e;switch(t){case _i.BROWSER:e="BROWSER";break;case _i.COMPOSITE:e="COMPOSITE";break;case _i.TRACK:e="TRACK";break;default:e="BROWSER"}return e}setupEvents(){a(this,zi).getValue("peerSessionStore").on(R.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(F.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(F.recordingPaused,t=>{const e=[...this.recording.recordings];e.forEach(r=>{r.id===t.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(e)}),this.room.on(F.recordingStopped,t=>{const e=[...this.recording.recordings.filter(r=>r.id!==t.recordingId)];this.recording.updateRecordings(e)})}}zi=new WeakMap,lD([T.trace("RecordingController.setupEvents")],Kf.prototype,"setupEvents",1);class uD{constructor(t){m(this,Yi,void 0);f(this,Yi,t)}hasFeature(t){var e;return(e=a(this,Yi).getValue("flagsmith").hasFeature(t))!=null?e:!1}getFeatureValue(t){return a(this,Yi).getValue("flagsmith").getValue(t)}getAllFeatures(){return a(this,Yi).getValue("flagsmith").getAllFlags()}}Yi=new WeakMap;class Vh{constructor(t,e,r){p(this,"logger");p(this,"features");p(this,"browserSpecs");p(this,"callStats");this.logger=t,this.features=e,this.browserSpecs=ye,this.callStats=r}static init(t){return new Vh(t.getValue("logger"),new uD(t),t.getValue("callstats"))}}class Lh{constructor(t){p(this,"internals");this.internals=t}static async init(t){const e=Vh.init(t);return new Lh(e)}}var hD=Object.defineProperty,pD=Object.getOwnPropertyDescriptor,Jt=(s,t,e,r)=>{for(var i=r>1?void 0:r?pD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&hD(t,e,i),i};class xt extends Fn{constructor(e,r,i=sl,n=!0){const o=e.getValue("logger");super(o);m(this,ze,void 0);m(this,be,void 0);m(this,ve,void 0);m(this,Er,void 0);m(this,gs,void 0);m(this,Yo,void 0);m(this,Le,void 0);p(this,"audioUpdateInProgress");p(this,"videoUpdateInProgress");f(this,Le,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,f(this,ze,new rv(e,r)),f(this,be,new BD(e,a(this,ze),void 0,i)),f(this,ve,new KD(e,a(this,ze),void 0,i)),f(this,gs,new GD(a(this,Le),a(this,ze))),f(this,Er,new qD(e,a(this,ze))),f(this,Yo,n),a(this,be).on("trackMuted",this.onAudioTrackMuted.bind(this)),a(this,be).on("trackChanged",this.onAudioTrackChanged.bind(this)),a(this,ve).on("trackChanged",this.onVideoTrackChanged.bind(this)),a(this,ve).on("trackEnded",this.onVideoTrackEnded.bind(this)),a(this,gs).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return a(this,Le).getValue("telemetry")}set context(e){f(this,Le,e)}async onVisibilityChange(){a(this,Le).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?a(this,Le).getValue("callstats").browserBackgrounded():(a(this,Le).getValue("callstats").browserForegrounded(),await this.setupSpeaker())}async repopulateAvailableDevices(){return!0}async setupStreams({audio:e,video:r}){var o;e?a(this,Le).getValue("callstats").audioOn():a(this,Le).getValue("callstats").audioOff(),r?a(this,Le).getValue("callstats").videoOn():a(this,Le).getValue("callstats").videoOff();let i,n;if(e&&r)try{const c=await a(this,ze).getAudioAndVideoTrack(a(this,be).userSelectedDevice,a(this,ve).userSelectedDevice);i=c.audioTrack,n=c.videoTrack}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!i&&e)try{i=await a(this,ze).getAudioTrack(!1,a(this,be).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!n&&r)try{n=await a(this,ze).getVideoTrack(a(this,ve).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}e&&!i&&a(this,Le).getValue("callstats").audioOff(),r&&!n&&a(this,Le).getValue("callstats").videoOff(),await a(this,be).setMediaTrack(i),await a(this,ve).setMediaTrack(n);try{await this.setupSpeaker()}catch(c){}if(n){const c=await this.getDeviceById(n.getSettings().deviceId);a(this,Le).getValue("callstats").selectedDevice("VIDEO",c)}if(i){const c=await this.getDeviceById(i.getSettings().deviceId);a(this,Le).getValue("callstats").selectedDevice("AUDIO",c)}(o=a(this,Er).currentDevice)!=null&&o.deviceId&&a(this,Le).getValue("callstats").selectedDevice("SPEAKER",a(this,Er).currentDevice),a(this,ze).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})}getCurrentDevices(){return{audio:a(this,be).currentDevice,video:a(this,ve).currentDevice,speaker:a(this,Er).currentDevice}}get permissions(){return a(this,ze).permissions}getAllDevices(){return a(this,ze).getAvailableDevices()}getDeviceById(e,r){return a(this,ze).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return a(this,be).mediaTrack}get audioTrack(){return a(this,be).transformedMediaTrack}get audioEnabled(){return a(this,be).trackEnabled}async enableAudio(e){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?await a(this,be).enableTrack(!1,e):await a(this,be).unmuteTrack()}catch(r){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){a(this,be).mediaTrack&&!a(this,be).isCustomTrack?a(this,be).muteTrack():a(this,be).disableTrack()}getAudioDevices(e){return a(this,ze).getAudioInputDevices(e)}async setAudioDevice(e,{saveDevicePreference:r}){await a(this,be).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Le).getValue("callstats").selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async setupSpeaker(){const{speaker:e}=this.getCurrentDevices();await a(this,Er).setPreferredSpeaker();const{speaker:r}=this.getCurrentDevices();(e==null?void 0:e.deviceId)!==(r==null?void 0:r.deviceId)&&r&&this.emit("DEVICE_CHANGE",{device:r})}async setSpeakerDevice(e,{saveDevicePreference:r}){await a(this,Er).setupSpeaker(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Le).getValue("callstats").selectedDevice("SPEAKER",e),this.emit("DEVICE_CHANGE",{device:e})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return a(this,ve).mediaTrack}get videoTrack(){return a(this,ve).transformedMediaTrack}get videoEnabled(){return a(this,ve).trackEnabled}async enableVideo(e){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?await a(this,ve).enableTrack(!1,e):await a(this,ve).unmuteTrack()}catch(r){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){a(this,ve).disableTrack()}getVideoDevices(e){return a(this,ze).getVideoInputDevices(e)}async setVideoDevice(e,{saveDevicePreference:r}){await a(this,ve).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Le).getValue("callstats").selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async updateVideoConstraints(e){await a(this,ve).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:a(this,gs).audioMediaTrack,video:a(this,gs).videoMediaTrack}}get screenShareEnabled(){return a(this,gs).trackEnabled}async enableScreenShare(){await a(this,gs).enableScreenShare()}async disableScreenShare(){a(this,gs).disableScreenShare()}async updateScreenshareConstraints(e){await a(this,gs).updateConstraints(e)}getSpeakerDevices(e){return a(this,ze).getAudioOutputDevices(e)}addAudioMiddleware(e){return a(this,be).addMiddleware(e)}removeAudioMiddleware(e){return a(this,be).removeMiddleware(e)}removeAllAudioMiddlewares(){return a(this,be).removeAllMiddlewares()}addVideoMiddleware(e){return a(this,ve).addMiddleware(e)}removeVideoMiddleware(e){return a(this,ve).removeMiddleware(e)}removeAllVideoMiddlewares(){return a(this,ve).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return a(this,ve).setVideoMiddlewareGlobalConfig(e)}destruct(){a(this,be).disableTrack(),a(this,ve).disableTrack(),a(this,ve).terminateMiddlewareWebWorker(),a(this,gs).disableScreenShare(),a(this,ze).destruct()}async onDeviceChange(e,r){var n,o;if(this.emit("DEVICE_LIST_UPDATED",e),r||!a(this,Yo))return;let i=!1;(n=e==null?void 0:e.added)==null||n.reverse().forEach(async c=>{var d;c&&!sl(c)&&(c.kind==="audioinput"&&((d=this.audioTrack)==null?void 0:d.enabled)===!0?await this.setAudioDevice(c,{saveDevicePreference:!1}):c.kind==="audiooutput"&&(i=!0,await this.setSpeakerDevice(c,{saveDevicePreference:!1})))}),i||(o=e==null?void 0:e.removed)==null||o.forEach(async c=>{var d;if(c.kind==="audiooutput"&&((d=this.getCurrentDevices().speaker)==null?void 0:d.deviceId)===c.deviceId){const l=await this.getSpeakerDevices();(l==null?void 0:l.length)>0&&await this.setSpeakerDevice(l[0],{saveDevicePreference:!1})}})}removeAllTracks(){this.destruct()}removeAudioTrack(){a(this,be).disableTrack()}removeVideoTrack(){a(this,ve).disableTrack(),a(this,ve).terminateMiddlewareWebWorker()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}ze=new WeakMap,be=new WeakMap,ve=new WeakMap,Er=new WeakMap,gs=new WeakMap,Yo=new WeakMap,Le=new WeakMap,Jt([T.trace("MediaHandler.setupStreams")],xt.prototype,"setupStreams",1),Jt([T.trace("MediaHandler.enableAudio")],xt.prototype,"enableAudio",1),Jt([T.trace("MediaHandler.disableAudio")],xt.prototype,"disableAudio",1),Jt([T.trace("MediaHandler.setAudioDevice")],xt.prototype,"setAudioDevice",1),Jt([T.trace("MediaHandler.enableVideo")],xt.prototype,"enableVideo",1),Jt([T.trace("MediaHandler.disableVideo")],xt.prototype,"disableVideo",1),Jt([T.trace("MediaHandler.setVideoDevice")],xt.prototype,"setVideoDevice",1),Jt([T.trace("MediaHandler.updateVideoConstraints")],xt.prototype,"updateVideoConstraints",1),Jt([T.trace("MediaHandler.enableScreenShare")],xt.prototype,"enableScreenShare",1),Jt([T.trace("MediaHandler.disableScreenShare")],xt.prototype,"disableScreenShare",1),Jt([T.trace("MediaHandler.updateScreenshareConstraints")],xt.prototype,"updateScreenshareConstraints",1),Jt([T.trace("MediaHandler.destruct")],xt.prototype,"destruct",1),Jt([T.trace("MediaHandler.onDeviceChange")],xt.prototype,"onDeviceChange",1);function tl(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 gD=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function sl(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:gD.some(i=>t==null?void 0:t.includes(i))}async function mD(s,t,e){if(!(t!=null&&t.length))return e;const r=s.getValue("logger"),i=new AudioContext,n=await Promise.all(t==null?void 0:t.map(d=>d(i))),o=i.createMediaStreamSource(new MediaStream([e])),c=i.createMediaStreamDestination();try{let d=o;for(let l=0;l<n.length;l+=1)d.connect(n[l]),d=n[l];d.connect(c)}catch(d){return r.error("getTransformedAudioTrack::middleware_execution_failed",{error:d}),e}return c.stream.getAudioTracks()[0]}const fD=s=>(t,e)=>(s.set(t,e),e),zf=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Yf=536870912,Qf=Yf*2,vD=(s,t)=>e=>{const r=t.get(e);let i=r===void 0?e.size:r<Qf?r+1:0;if(!e.has(i))return s(e,i);if(e.size<Yf){for(;e.has(i);)i=Math.floor(Math.random()*Qf);return s(e,i)}if(e.size>zf)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;e.has(i);)i=Math.floor(Math.random()*zf);return s(e,i)},Xf=new WeakMap,SD=fD(Xf),rl=vD(SD,Xf),yD=s=>s.method!==void 0&&s.method==="call",TD=s=>s.error===null&&typeof s.id=="number",il=((s,t)=>{let e=null;return()=>{if(e!==null)return e;const r=new Blob([t],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(r);return e=s(i),setTimeout(()=>URL.revokeObjectURL(i)),e}})(s=>{const t=new Map([[0,()=>{}]]),e=new Map([[0,()=>{}]]),r=new Map,i=new Worker(s);return i.addEventListener("message",({data:l})=>{if(yD(l)){const{params:{timerId:u,timerType:h}}=l;if(h==="interval"){const g=t.get(u);if(typeof g=="number"){const v=r.get(g);if(v===void 0||v.timerId!==u||v.timerType!==h)throw new Error("The timer is in an undefined state.")}else if(typeof g!="undefined")g();else throw new Error("The timer is in an undefined state.")}else if(h==="timeout"){const g=e.get(u);if(typeof g=="number"){const v=r.get(g);if(v===void 0||v.timerId!==u||v.timerType!==h)throw new Error("The timer is in an undefined state.")}else if(typeof g!="undefined")g(),e.delete(u);else throw new Error("The timer is in an undefined state.")}}else if(TD(l)){const{id:u}=l,h=r.get(u);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:g,timerType:v}=h;r.delete(u),v==="interval"?t.delete(g):e.delete(g)}else{const{error:{message:u}}=l;throw new Error(u)}}),{clearInterval:l=>{const u=rl(r);r.set(u,{timerId:l,timerType:"interval"}),t.set(l,u),i.postMessage({id:u,method:"clear",params:{timerId:l,timerType:"interval"}})},clearTimeout:l=>{const u=rl(r);r.set(u,{timerId:l,timerType:"timeout"}),e.set(l,u),i.postMessage({id:u,method:"clear",params:{timerId:l,timerType:"timeout"}})},setInterval:(l,u=0)=>{const h=rl(t);return t.set(h,()=>{l(),typeof t.get(h)=="function"&&i.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:h,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:h,timerType:"interval"}}),h},setTimeout:(l,u=0)=>{const h=rl(e);return e.set(h,l),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:h,timerType:"timeout"}}),h}}},`(()=>{"use strict";const e=new Map,t=new Map,r=(e,t)=>{let r,o;const i=performance.now();r=i,o=e-Math.max(0,i-t);return{expected:r+o,remainingDelay:o}},o=(e,t,r,i)=>{const s=performance.now();s>r?postMessage({id:null,method:"call",params:{timerId:t,timerType:i}}):e.set(t,setTimeout(o,r-s,e,t,r,i))};addEventListener("message",(i=>{let{data:s}=i;try{if("clear"===s.method){const{id:r,params:{timerId:o,timerType:i}}=s;if("interval"===i)(t=>{const r=e.get(t);if(void 0===r)throw new Error('There is no interval scheduled with the given id "'.concat(t,'".'));clearTimeout(r),e.delete(t)})(o),postMessage({error:null,id:r});else{if("timeout"!==i)throw new Error('The given type "'.concat(i,'" is not supported'));(e=>{const r=t.get(e);if(void 0===r)throw new Error('There is no timeout scheduled with the given id "'.concat(e,'".'));clearTimeout(r),t.delete(e)})(o),postMessage({error:null,id:r})}}else{if("set"!==s.method)throw new Error('The given method "'.concat(s.method,'" is not supported'));{const{params:{delay:i,now:n,timerId:a,timerType:d}}=s;if("interval"===d)((t,i,s)=>{const{expected:n,remainingDelay:a}=r(t,s);e.set(i,setTimeout(o,a,e,i,n,"interval"))})(i,a,n);else{if("timeout"!==d)throw new Error('The given type "'.concat(d,'" is not supported'));((e,i,s)=>{const{expected:n,remainingDelay:a}=r(e,s);t.set(i,setTimeout(o,a,t,i,n,"timeout"))})(i,a,n)}}}}catch(e){postMessage({error:{message:e.message},id:s.id,result:null})}}))})();`),Zf=s=>il().clearInterval(s),ED=s=>il().clearTimeout(s),ev=(s,t)=>il().setInterval(s,t),tv=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:Zf,clearTimeout:ED,setInterval:ev,setTimeout:(s,t)=>il().setTimeout(s,t)},Symbol.toStringTag,{value:"Module"}));class bD{constructor(t){m(this,Qi,void 0);m(this,Qo,void 0);f(this,Qo,t)}get logger(){return a(this,Qo).getValue("logger")}terminateMiddlewareWebWorker(){if(a(this,Qi))try{Zf(a(this,Qi)),f(this,Qi,void 0)}catch(t){this.logger.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}async getTransformedVideoTrack(t,e,r){if(!(t!=null&&t.length))return e;const i=document.createElement("canvas"),n=await Promise.all(t==null?void 0:t.map(g=>g({canvas:i,WorkerTimers:tv})));if(r.disablePerFrameCanvasRendering){const v=i.captureStream().getVideoTracks()[0];return Object.defineProperty(v,"originalSettings",{value:e.getSettings()}),v}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 g=0;g<n.length;g+=1)typeof n[g]=="function"&&await n[g](i,d)}catch(g){this.logger.error("getTransformedVideoTrack::middleware_execution_failed",{error:g})}};try{o.play()}catch(g){}o.addEventListener("play",()=>{i.width=o.width||e.getSettings().width,i.height=o.width||e.getSettings().height,f(this,Qi,ev(l,50))},!1);const h=i.captureStream().getVideoTracks()[0];return Object.defineProperty(h,"originalSettings",{value:e.getSettings()}),h}}Qi=new WeakMap,Qo=new WeakMap;const sv={gross:{width:{ideal:192},height:{ideal:144}},qvga:{width:{ideal:384},height:{ideal:288}},pvga:{width:{ideal:480},height:{ideal:360}},vga:{width:{ideal:640},height:{ideal:480}},hd:{width:{ideal:1280},height:{ideal:720}},hd_cropped:{width:{ideal:900},height:{ideal:720}},fhd:{width:{ideal:1920},height:{ideal:1080}}},wD=[[320,[{rid:"q",maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"}]],[640,[{rid:"q",scaleResolutionDownBy:2,maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:7e5,maxFramerate:30,scalabilityMode:"L1T1"}]],[1280,[{rid:"q",scaleResolutionDownBy:2,maxBitrate:5e5,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:13e5,maxFramerate:30,scalabilityMode:"L1T1"}]],[1920,[{rid:"q",scaleResolutionDownBy:2,maxBitrate:9e5,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:15e5,maxFramerate:30,scalabilityMode:"L1T1"}]]],PD=(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);let i=wD;s.getValue("flagsmith").hasFeature(Z.OVERRIDE_SIMULCAST_DYNAMIC)&&(i=JSON.parse(s.getValue("flagsmith").getValue(Z.OVERRIDE_SIMULCAST_DYNAMIC)));const n=i.map(([h])=>h).sort((h,g)=>h-g);let o=Number.MAX_VALUE,c=0;return n.forEach((h,g)=>{Math.abs(h-r)<o&&(o=Math.abs(h-r),c=g)}),i[c][1]};var fe=(s=>(s.WEBCAM="webcam",s.WEBCAM_BACKUP="webcam_backup",s.MIC="mic",s.SCREENSHARE_VIDEO="screenshare_video",s.SCREENSHARE_AUDIO="screenshare_audio",s))(fe||{});const _D=pP(),Gn=Rs(_D.config.media);function CD(s){var e,r;const t={};return s.audio&&(t.audio={enableStereo:(e=s.audio.enableStereo)!=null?e:!1,enableHighBitrate:(r=s.audio.enableHighBitrate)!=null?r:!1}),t.video=s.video.quality,t}class RD{constructor(t,e){m(this,Xi,void 0);m(this,Ks,void 0);p(this,"getScreenShareConstraints",()=>{var l,u,h,g,v,E,b,P,w,L,$;const t=(l=a(this,Xi))==null?void 0:l.screenshare,e=(h=(u=t==null?void 0:t.width)==null?void 0:u.max)!=null?h:1920,r=(v=(g=t==null?void 0:t.height)==null?void 0:g.max)!=null?v:1080,i=(b=(E=t==null?void 0:t.frameRate)==null?void 0:E.max)!=null?b:5;let n=(w=(P=t==null?void 0:t.frameRate)==null?void 0:P.ideal)!=null?w:5;const o=t==null?void 0:t.displaySurface,c=t==null?void 0:t.selfBrowserSurface;a(this,Ks).getValue("flagsmith").getValue(Z.VAL_MIN_FRAMERATE)&&(n=parseInt((L=a(this,Ks).getValue("flagsmith").getValue(Z.VAL_MIN_FRAMERATE))==null?void 0:L.toString(),10));let d={width:{max:e},height:{max:r},frameRate:{ideal:n,max:i}};if(a(this,Ks).getValue("flagsmith").hasFeature(Z.SCREENSHARE_CONSTRAINTS)){const N=($=a(this,Ks).getValue("flagsmith").getValue(Z.SCREENSHARE_CONSTRAINTS))==null?void 0:$.toString();d=JSON.parse(N)}return o!==void 0&&["monitor","browser","window"].includes(o)&&(d={...d,displaySurface:o}),c!==void 0&&(d={...d,selfBrowserSurface:c}),{audio:!0,video:d}});p(this,"getAudioConstraints",t=>{var n,o,c,d,l,u,h;const e={},r=(n=a(this,Xi))==null?void 0:n.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 n,o,c,d;const e={},r=(n=a(this,Xi))==null?void 0:n.video;let i=sv.vga;if(typeof r=="string"?i=sv[r]:r!==void 0&&(i.height.ideal=r.height.ideal,i.width.ideal=r.width.ideal),i.frameRate={ideal:(c=(o=i.frameRate)==null?void 0:o.ideal)!=null?c:24},ye.isChromiumBased()&&(i.frameRate.max=30),a(this,Ks).getValue("flagsmith").hasFeature(Z.VIDEO_CONSTRAINTS)){const l=(d=a(this,Ks).getValue("flagsmith").getValue(Z.VIDEO_CONSTRAINTS))==null?void 0:d.toString();i=JSON.parse(l)}return e.video=i,typeof e.video=="boolean"||(t?e.video.deviceId={exact:t}:e.video.facingMode="user"),e});f(this,Ks,t),f(this,Xi,e)}getUpdatedVideoConstraints(t){return t}}Xi=new WeakMap,Ks=new WeakMap;class xh extends Error{constructor(e,r,i){super(r);p(this,"constraints");p(this,"name");this.name=e,this.constraints=i}}class kD{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 ID=Object.defineProperty,AD=Object.getOwnPropertyDescriptor,ks=(s,t,e,r)=>{for(var i=r>1?void 0:r?AD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ID(t,e,i),i};let Kt=(cS=class extends kD{constructor(t,e){super();m(this,Ta,void 0);m(this,ms,void 0);m(this,qe,void 0);f(this,qe,t),f(this,ms,new RD(t,e)),f(this,Ta,new AbortController)}get telemetry(){return a(this,qe).getValue("telemetry")}get logger(){return a(this,qe).getValue("logger")}get constraintsBuilder(){return a(this,ms)}async destruct(){var t;(t=a(this,Ta))==null||t.abort()}handlePermissionErrors(t,e){const r=tl(t,e.name,e.message);return this.permissions[t]=r,a(this,qe).getValue("peerSessionStore").emit(R.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}async getAudioAndVideoTrack(t,e){var r,i,n,o;try{const c=await this.getAudioInputDevices(),d=await this.getVideoInputDevices(),l=!!(c!=null&&c.find(L=>L.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(L=>L.deviceId===e));let g;e&&h?g=e:d&&((n=d[0])!=null&&n.deviceId)&&(g=(o=d[0])==null?void 0:o.deviceId);const v={audio:a(this,ms).getAudioConstraints(u).audio,video:a(this,ms).getVideoConstraints(g).video};this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(v)});const E=await navigator.mediaDevices.getUserMedia(v);this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(v)});const b=E.getAudioTracks()[0];let P=E.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",a(this,qe).getValue("flagsmith").hasFeature(Z.OBS_QUALITY)&&P.label.includes("OBS Virtual")){const $=(await this.getVideoInputDevices()).find(N=>N.label.includes("OBS Virtual"));P=await this.getVideoTrack($.deviceId)}return a(this,qe).getValue("peerSessionStore").emit(R.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),a(this,qe).getValue("peerSessionStore").emit(R.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:b,videoTrack:P}}catch(c){throw this.logger.error("WebMediaInterface.getAudioAndVideoTrack",{error:c}),new C("Couldnt fetch audio and video track","1605")}}async getAudioTrack(t,e){var c,d;let r=await this.getAudioInputDevices();if(!(r!=null&&r.length))throw this.permissions.audio="NO_DEVICES_AVAILABLE",a(this,qe).getValue("peerSessionStore").emit(R.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new C("No audio devices available","1606");const i=!!(r!=null&&r.find(l=>l.deviceId===e));let n;e&&i?n=e:(c=r[0])!=null&&c.deviceId&&(n=(d=r[0])==null?void 0:d.deviceId);const o=async l=>{let u;try{r=r.filter(g=>g.deviceId!==l),u=a(this,ms).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 g=tl("audio",h.name,h.message),v=new xh(h.name,h.message,u);if(g==="COULD_NOT_START"){const E=r.shift();if(!E)throw v;this.logger.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(u),error:h});const b=a(this,ms).getAudioConstraints(E.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(b)}),o(E.deviceId)}throw v}};try{const l=await o(n);return l.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",a(this,qe).getValue("peerSessionStore").emit(R.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 l,u,h;const e=a(this,qe).getValue("flagsmith").hasFeature(Z.OBS_QUALITY),r=(l=await this.getCurrentDeviceLabel(t))==null?void 0:l.includes("OBS Virtual"),i=e&&r,n=await this.getVideoInputDevices();if(!(n!=null&&n.length))throw this.permissions.video="NO_DEVICES_AVAILABLE",a(this,qe).getValue("peerSessionStore").emit(R.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new C("No video devices available","1607");const o=!!(n!=null&&n.find(g=>g.deviceId===t));let c;t&&o?c=t:(u=n[0])!=null&&u.deviceId&&(c=(h=n[0])==null?void 0:h.deviceId);const d=async g=>{try{let v=g;const{video:E}=v;i&&typeof E!="boolean"&&(v={video:{deviceId:E.deviceId}}),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(v)});const[b]=(await navigator.mediaDevices.getUserMedia(v)).getVideoTracks();if(i&&typeof E!="boolean"&&typeof E.width=="object"){const{width:P,height:w}=b.getSettings(),{ideal:L}=E.width;b.applyConstraints({width:{ideal:L},height:{ideal:Math.floor(w*L/P)},frameRate:E.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(v)}),b}catch(v){const E=tl("video",v.name,v.message),b=new xh(v.name,v.message,g);if(E==="COULD_NOT_START"){const P=n.shift();if(!P)throw b;this.logger.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(g),error:v});const w=a(this,ms).getVideoConstraints(P.deviceId);return this.logger.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(w)}),d({video:w.video})}throw b}};try{const g=a(this,ms).getVideoConstraints(c),v=await d(g);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",a(this,qe).getValue("peerSessionStore").emit(R.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),v}catch(g){throw g.constraints&&this.handlePermissionErrors("video",g),new C(g.message,"1602")}}async getScreenShareTracks(){const t=async e=>{try{this.logger.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),a(this,qe).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=tl("video",r.name,r.message),n=new xh(r.name,r.message,e),o={video:!0};if(Z_(e,o)||!a(this,qe).getValue("flagsmith").hasFeature(Z.SCREEENSHARE_CONSTRAINTS_RETRY))throw n;if(i==="COULD_NOT_START")return t(o);throw n}};try{const e=a(this,ms).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",a(this,qe).getValue("peerSessionStore").emit(R.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:r.getAudioTracks()[0],videoTrack:r.getVideoTracks()[0]}}catch(e){throw e.constraints&&this.handlePermissionErrors("screenshare",e),new C(e.message,"1612")}}async getCurrentDeviceLabel(t){const e=await this.getDevice(t||"default");return e==null?void 0:e.label}async enumerateDevicesWithExternalFirst(){const t=await navigator.mediaDevices.enumerateDevices(),e=i=>{var o;const n=((o=i.label)==null?void 0:o.toLowerCase())||"";return sl(i)?4:n.includes("airpods")||n.includes("airdopes")||n.includes("bluetooth")||n.includes("wireless")||n.includes("headphones")||n.includes("headset")||n.includes("earbuds")||n.includes("usb")||n.includes("external")?0:i.deviceId==="default"||n.includes("default")?1:n.includes("built-in")||n.includes("internal")?2:3},r=i=>{var o;if(i.kind!=="videoinput")return!1;const n=((o=i.label)==null?void 0:o.toLowerCase())||"";return n.includes("front")||n.includes("user")||n.includes("selfie")?!0:!(n.includes("back")||n.includes("rear")||n.includes("environment"))};return t.sort((i,n)=>{var u,h;const o=e(i),c=e(n);if(o!==c)return o-c;const d=i.deviceId==="default"||((u=i.label)==null?void 0:u.toLowerCase().includes("default")),l=n.deviceId==="default"||((h=n.label)==null?void 0:h.toLowerCase().includes("default"));if(d&&!l)return-1;if(!d&&l)return 1;if(i.kind==="videoinput"&&n.kind==="videoinput"){const g=r(i),v=r(n);if(g&&!v)return-1;if(!g&&v)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}`,n=new Set(e.map(h=>i(h))),o=await this.getAvailableDevices(),c=new Set(o.map(h=>i(h))),d={added:o.filter(h=>!n.has(i(h))),removed:e.filter(h=>!c.has(i(h))),devices:o};if(e=o,(l=d.added)!=null&&l.length||(u=d.removed)!=null&&u.length){this.logger.info("repopulated_full_device_list",{devices:JSON.stringify(o)});const h=[...d.added,...d.removed];h.some(g=>g.kind==="audioinput")&&a(this,qe).getValue("callstats").devices("AUDIO",o==null?void 0:o.filter(g=>g.kind==="audioinput")),h.some(g=>g.kind==="videoinput")&&a(this,qe).getValue("callstats").devices("VIDEO",o==null?void 0:o.filter(g=>g.kind==="videoinput")),h.some(g=>g.kind==="audiooutput")&&a(this,qe).getValue("callstats").devices("SPEAKER",o==null?void 0:o.filter(g=>g.kind==="audiooutput")),t(r,d,!1)}},{signal:a(this,Ta).signal})}}},Ta=new WeakMap,ms=new WeakMap,qe=new WeakMap,cS);ks([T.trace("WebMediaInterface.destruct")],Kt.prototype,"destruct",1),ks([T.trace("WebMediaInterface.handlePermissionErrors")],Kt.prototype,"handlePermissionErrors",1),ks([T.trace("WebMediaInterface.getAudioAndVideoTrack")],Kt.prototype,"getAudioAndVideoTrack",1),ks([T.trace("WebMediaInterface.getAudioTrack")],Kt.prototype,"getAudioTrack",1),ks([T.trace("WebMediaInterface.getVideoTrack")],Kt.prototype,"getVideoTrack",1),ks([T.trace("WebMediaInterface.getScreenShareTracks")],Kt.prototype,"getScreenShareTracks",1),ks([T.trace("WebMediaInterface.getAvailableDevices")],Kt.prototype,"getAvailableDevices",1),ks([T.trace("WebMediaInterface.getAvailableDevicesByKind")],Kt.prototype,"getAvailableDevicesByKind",1),ks([T.trace("WebMediaInterface.getDevice")],Kt.prototype,"getDevice",1),ks([T.trace("WebMediaInterface.onDeviceChange")],Kt.prototype,"onDeviceChange",1),Kt=ks([ut("1600")],Kt);const rv=Kt,Oi={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}},MD=(s=0)=>new Promise(t=>setTimeout(t,s)),OD=(s,t,e)=>{const r=typeof e=="number"?e:250,i=s.createMediaStreamSource(t),n=s.createAnalyser();n.fftSize=2048,i.connect(n);const o=new Uint8Array(n.fftSize);let c=!1;setTimeout(()=>{c=!0},r);function d(){return c?Promise.resolve(!0):(n.getByteTimeDomainData(o),o.some(l=>l!==128&&l!==0)?Promise.resolve(!1):MD().then(d))}return d().then(l=>(i.disconnect(),l),l=>{throw i.disconnect(),l})},DD=typeof AudioContext!="undefined"?AudioContext:null;class Uh{constructor(t){p(this,"_AudioContext");p(this,"audioContext");p(this,"_audioContextRefContainers");const e={AudioContext:DD,...t};Object.defineProperties(this,{_AudioContext:{value:e.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:Uh}})}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 iv=new Uh,ND=3,VD=250;function LD(s){const t={},e=iv.getOrCreate(t);let r=ND;function i(){return r-=1,OD(e,s.srcObject,VD).then(n=>n?r>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{iv.release(t)})}async function nv(s,t){const e=new Audio,r=new MediaStream;r.addTrack(t),e.srcObject=r;let i=!1;try{const n=e.play();n&&await n,i=await LD(e),i&&s.info("checkIfAudioTrackIsSilent::silence_detected")}catch(n){s.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:n})}finally{e.pause(),e.remove()}return i}var xD=Object.defineProperty,UD=Object.getOwnPropertyDescriptor,av=(s,t,e,r)=>{for(var i=r>1?void 0:r?UD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&xD(t,e,i),i};let nl=class extends Fn{constructor(t,e,r,i){var o;const n=t.getValue("logger");super(n);p(this,"constructorName",this.constructor.name);p(this,"userSelectedDevice");p(this,"mediaInterface");p(this,"isNonPreferredDevice");p(this,"_mediaTrack");p(this,"transformedMediaTrack");p(this,"middlewares",[]);p(this,"currentDevice");p(this,"userPreferredDeviceKey",`Realtimekit::${this.constructorName}::UserDeviceID`);p(this,"setUserPreferredDevice",t=>Oi.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>Oi.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()&&!sP.hasFeature(Z.ALLOW_SAFARI_MEDIA_MIDDLEWARES))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))}};av([T.trace("BaseMediaHandler.unmuteTrack")],nl.prototype,"unmuteTrack",1),nl=av([ut("1600")],nl);const ov=nl;var FD=Object.defineProperty,$D=Object.getOwnPropertyDescriptor,Fh=(s,t,e,r)=>{for(var i=r>1?void 0:r?$D(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&FD(t,e,i),i};const $h="[Realtimekit]nonSilentDeviceLabels";class al extends ov{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 mD(this.context,this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(r){this.logger.error("AudioMediaHandler.setTransformedTrack",{error:r}),this.transformedMediaTrack=this.mediaTrack}}async onTrackEnded(){this.logger.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const t=this.mediaTrack.enabled;this.disableTrack(),await this.enableTrack(!t),await this.setTransformedTrack(),this.emit("trackChanged")}onTrackMuted(){this.logger.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(t,e=!1){var d;if(!t||this.userSelectedDevice||e)return t;let r=t;const i=await this.mediaInterface.getAudioInputDevices(),n=this.isNonPreferredDevice?i.filter(l=>l&&!this.isNonPreferredDevice(l)):i;if(!(n!=null&&n.length))return r;n.find(l=>l.deviceId===t.getSettings().deviceId)||(r.stop(),this.logger.info("localmediahandler::setupstreams::found_audio_non_preferred"),r=await this.mediaInterface.getAudioTrack(!1,n[0].deviceId));const o=JSON.parse(Oi.getItem($h,this.logger));if(o!=null&&o.devices.some(l=>l.label===r.label))return r;if(!await nv(this.logger,r)){const l=(d=o==null?void 0:o.devices.concat({label:r.label}))!=null?d:[{label:r.label}];return Oi.setItem($h,JSON.stringify({devices:l}),this.logger),r}this.logger.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const c=r.getSettings().deviceId;return n.filter(l=>l.deviceId!==c).some(async l=>{var u;if(r=await this.mediaInterface.getAudioTrack(!1,l.deviceId),!await nv(this.logger,r)){const h=(u=o==null?void 0:o.devices.concat({label:r.label}))!=null?u:[{label:r.label}];return Oi.setItem($h,JSON.stringify({devices:h}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),r}}Fh([T.trace("AudioMediaHandler.setTransformedTrack")],al.prototype,"setTransformedTrack",1),Fh([T.trace("AudioMediaHandler.onTrackEnded")],al.prototype,"onTrackEnded",1),Fh([T.trace("AudioMediaHandler.conditionallyChangeTrack")],al.prototype,"conditionallyChangeTrack",1);const BD=al;class HD{constructor(t,e){m(this,Zi,void 0);p(this,"currentDevice");p(this,"userPreferredDeviceKey","Realtimekit::speaker::UserDeviceID");p(this,"logger");p(this,"setUserPreferredDevice",t=>Oi.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>Oi.getItem(this.userPreferredDeviceKey,this.logger));f(this,Zi,e),this.logger=t.getValue("logger")}async setPreferredSpeaker(){const t=this.getUserPreferredDevice(),e=await a(this,Zi).getAudioOutputDevices(),r=e==null?void 0:e.find(i=>i.deviceId===t);await this.setupSpeaker(r,{saveDevicePreference:!1})}async setupSpeaker(t,{saveDevicePreference:e}){var n,o;if(!(a(this,Zi)instanceof rv))return;let r=t;if(t||([r]=(await a(this,Zi).getAvailableDevicesByKind("audiooutput")).filter(d=>!sl(d))),!r)throw new C("No speaker found","1608");if(((n=this.currentDevice)==null?void 0:n.deviceId)===r.deviceId)return;e&&this.setUserPreferredDevice(r.deviceId),this.currentDevice=r;const i=document.querySelectorAll("audio");(o=i[0])!=null&&o.setSinkId&&i.forEach(async c=>{if(typeof c.sinkId!="undefined"&&this.currentDevice.deviceId&&c.sinkId!==this.currentDevice.deviceId)try{await c.setSinkId(this.currentDevice.deviceId)}catch(d){}})}}Zi=new WeakMap;const qD=HD;class jD extends Fn{constructor(e,r){const i=e.getValue("logger");super(i);p(this,"mediaInterface");p(this,"audioMediaTrack");p(this,"videoMediaTrack");m(this,Xo,void 0);f(this,Xo,e),this.mediaInterface=r}get trackEnabled(){return!!this.videoMediaTrack}async enableScreenShare(){var e,r;try{const{audioTrack:i,videoTrack:n}=await this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=i,this.videoMediaTrack=n,this.addMediaTrackListeners(),((r=(e=this.mediaInterface)==null?void 0:e.permissions)==null?void 0:r.screenshare)==="ACCEPTED")return;this.mediaInterface.permissions&&(this.mediaInterface.permissions.screenshare="ACCEPTED",a(this,Xo).getValue("peerSessionStore").emit(R.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch(i){}}disableScreenShare(){var e,r;this.removeMediaTrackListeners(),(e=this.audioMediaTrack)==null||e.stop(),(r=this.videoMediaTrack)==null||r.stop(),this.videoMediaTrack=void 0,this.audioMediaTrack=void 0}async updateConstraints(e){if(!this.videoMediaTrack)throw new C("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100",this.logger);try{this.videoMediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(i){this.logger.error("ScreenShareHandler.updateConstraints.error",{error:i})}}addMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this)),ye.isWebKitBased()&&((r=this.videoMediaTrack)==null||r.addEventListener("mute",this.onTrackEnded.bind(this)))}removeMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(r=this.videoMediaTrack)==null||r.removeEventListener("mute",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}Xo=new WeakMap;const GD=jD;var WD=Object.defineProperty,JD=Object.getOwnPropertyDescriptor,ol=(s,t,e,r)=>{for(var i=r>1?void 0:r?JD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&WD(t,e,i),i};class Co extends ov{constructor(e,r,i,n){super(e,r,i,n);m(this,Ea,void 0);m(this,Zo,{disablePerFrameCanvasRendering:!1});f(this,Ea,new bD(e))}async onSetDevice(e){if(!e)throw this.logger.warn("VideoMediaHandler.setDevice No device received"),new C("No device received!","1603");if(e.kind!=="videoinput")throw this.logger.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new C("Non video device received while setting video device!","1603");if(!(this.mediaTrack&&this.mediaTrack.enabled)){this.logger.warn("VideoMediaHandler.setDevice Tried switching device with video disabled",{devices:[e]}),this.currentDevice=e;return}try{this.disableTrack(),await this.setMediaTrack(await this.mediaInterface.getVideoTrack(this.userSelectedDevice))}catch(r){throw this.logger.error("VideoMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new C("Failed to change device","1600",this.logger)}}async enableTrack(e,r){if(this.trackEnabled){this.logger.warn("VideoMediaHandler.enableTrack Track already enabled!");return}if(r){this.isCustomTrack=!0,await this.setMediaTrack(r,!0);return}this.isCustomTrack=!1;const i=await this.mediaInterface.getVideoTrack(this.userSelectedDevice);await this.setMediaTrack(i)}async setTransformedTrack(e){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await a(this,Ea).getTransformedVideoTrack(this.middlewares,this.mediaTrack,a(this,Zo)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){f(this,Zo,e)}async updateConstraints(e){if(!this._mediaTrack)throw new C("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100",this.logger);try{this._mediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),await this.setTransformedTrack(),this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(i){this.logger.error("VideoMediaHandler.updateConstraints.error",{error:i})}}terminateMiddlewareWebWorker(){a(this,Ea).terminateMiddlewareWebWorker()}async onTrackEnded(){this.logger.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")}onTrackMuted(){this.logger.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(e,r=!1){if(!e||this.userSelectedDevice||r)return e;let i=e;const n=await this.mediaInterface.getVideoInputDevices(),o=this.isNonPreferredDevice?n.filter(c=>!this.isNonPreferredDevice(c)):n;return!(o!=null&&o.length)||window.FAST_RTK||o.find(c=>c.deviceId===e.getSettings().deviceId)||(i.stop(),this.logger.info("localmediahandler::setupstreams::found_video_non_preferred"),i=await this.mediaInterface.getVideoTrack(o[0].deviceId)),i}}Ea=new WeakMap,Zo=new WeakMap,ol([T.trace("VideoMediaHandler.setTransformedTrack")],Co.prototype,"setTransformedTrack",1),ol([T.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],Co.prototype,"setVideoMiddlewareGlobalConfig",1),ol([T.trace("VideoMediaHandler.onTrackEnded")],Co.prototype,"onTrackEnded",1),ol([T.trace("VideoMediaHandler.conditionallyChangeTrack")],Co.prototype,"conditionallyChangeTrack",1);const KD=Co,cv=Rs(Ku()),wa=class{constructor(t){m(this,Ft,void 0);m(this,en,void 0);m(this,ec,void 0);m(this,ba,void 0);if(!t)throw new C("Could not load preset.","0904");f(this,Ft,t.config),f(this,ec,t.name),f(this,en,t.ui||Rs(Ku().ui)),f(this,ba,t.permissions.plugins.config)}static fromResponse(t){return new wa(t)}static default(){return new wa(cv)}static init(t,e=!0){return!t||e?new wa(cv):new wa(t)}get setupScreen(){return{isEnabled:!0}}get waitingRoom(){return{isEnabled:!0}}get controlBar(){return{isEnabled:!0,elements:{chat:!0,fullscreen:!0,invite:!1,layout:!1,participants:!0,plugins:!0,polls:!0,reactions:!1,screenshare:!0}}}get header(){return{isEnabled:!0,elements:{logo:a(this,en).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return a(this,Ft).viewType}get livestreamViewerQualities(){return a(this,Ft).livestreamViewerQualities||[]}get maxVideoStreams(){return a(this,Ft).maxVideoStreams}get maxScreenShareCount(){return a(this,Ft).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(a(this,ba)).filter(t=>a(this,ba)[t].disabled)}get designTokens(){return a(this,en).designTokens}get configDiff(){return a(this,en).configDiff}get mediaConstraints(){var t,e,r,i,n,o,c,d,l,u,h,g,v,E,b,P,w,L,$,N,B,Y,ae,bt;return{audio:{enableStereo:(i=(r=(e=(t=a(this,Ft))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:Gn.audio.enableStereo,enableHighBitrate:(d=(c=(o=(n=a(this,Ft))==null?void 0:n.media)==null?void 0:o.audio)==null?void 0:c.enableHighBitrate)!=null?d:Gn.audio.enableHighBitrate},video:{quality:(g=(h=(u=(l=a(this,Ft))==null?void 0:l.media)==null?void 0:u.video)==null?void 0:h.quality)!=null?g:Gn.video.quality,frameRate:(P=(b=(E=(v=a(this,Ft))==null?void 0:v.media)==null?void 0:E.video)==null?void 0:b.frameRate)!=null?P:Gn.video.frameRate},screenshare:{quality:(N=($=(L=(w=a(this,Ft))==null?void 0:w.media)==null?void 0:L.screenshare)==null?void 0:$.quality)!=null?N:Gn.screenshare.quality,frameRate:(bt=(ae=(Y=(B=a(this,Ft))==null?void 0:B.media)==null?void 0:Y.screenshare)==null?void 0:ae.frameRate)!=null?bt:Gn.screenshare.frameRate}}}get name(){return a(this,ec)}};let Bh=wa;Ft=new WeakMap,en=new WeakMap,ec=new WeakMap,ba=new WeakMap;var zD=Object.defineProperty,YD=Object.getOwnPropertyDescriptor,dv=(s,t,e,r)=>{for(var i=r>1?void 0:r?YD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&zD(t,e,i),i};class Hh extends Gt{constructor(e,r){const i=e.getValue("logger");super(i);m(this,Pa,void 0);p(this,"state","IDLE");p(this,"playbackUrl");p(this,"ingestionCredentials");p(this,"viewerCount");m(this,tc,void 0);f(this,Pa,r),f(this,tc,e),this.viewerCount=0}get telemetry(){return a(this,tc).getValue("telemetry")}setLivestreamState(e){const r=this.state;this.state=e,r!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}async start(e={manualIngestion:!1}){if(!a(this,Pa).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=pt(),{playbackUrl:i,ingestionCredentials:n}=await r.startLivestreaming(e);this.playbackUrl=i,this.ingestionCredentials=n,e!=null&&e.manualIngestion&&this.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}catch(r){throw this.logger.error("Recording::stop::livestream_failed_to_start",{error:r}),this.setLivestreamState("IDLE"),new C("Error while starting livestream","1900",this.logger)}}async stop(){if(!a(this,Pa).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 pt().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)}}}Pa=new WeakMap,tc=new WeakMap,dv([T.trace("livestream.start")],Hh.prototype,"start",1),dv([T.trace("livestream.stop")],Hh.prototype,"stop",1);var QD=Object.defineProperty,XD=Object.getOwnPropertyDescriptor,ZD=(s,t,e,r)=>{for(var i=r>1?void 0:r?XD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&QD(t,e,i),i};class lv{constructor(t,e,r){p(this,"livestream");m(this,_a,void 0);m(this,Ca,void 0);m(this,br,void 0);m(this,zs,void 0);f(this,zs,t),f(this,Ca,e),this.livestream=new Hh(t,e),f(this,br,r),this.setupEvents()}get logger(){return a(this,zs).getValue("logger")}get telemetry(){return a(this,zs).getValue("telemetry")}async fetchInitialLivestreamingState(){const t=pt(),{status:e,playbackUrl:r,manualIngest:i,ingestionCredentials:n}=await t.getActiveLivestream();this.livestream.playbackUrl=r,this.livestream.ingestionCredentials=n,e==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),e==="INVOKED"&&i&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}setupEvents(){a(this,br).on(F.startedLivestream,async t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{a(this,Ca).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}}),a(this,br).on(F.livestreamingInvoked,async t=>{if(t.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{a(this,Ca).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}}),a(this,br).on(F.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),a(this,br).on(F.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),a(this,br).on(F.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),a(this,zs).getValue("peerSessionStore").on(R.PEER_JOINED_INTERNAL,async t=>{var e;((e=t.flags)==null?void 0:e.hiddenParticipant)===!0&&t.recorderType==="LIVESTREAMER"&&(f(this,_a,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),a(this,zs).getValue("peerSessionStore").on(R.PEER_CLOSED,t=>{t.id===a(this,_a)&&(f(this,_a,void 0),this.livestream.setLivestreamState("IDLE"))}),a(this,zs).getValue("peerSessionStore").onAsync(R.LEAVE_MEDIA_ROOM,async()=>{if(!this.livestream.playbackUrl){this.logger.info("Fetching livestreaming state on leave stage");try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Failed to fetch livestreaming state on leave stage",{error:t})}}}),a(this,zs).getValue("peerSessionStore").on(R.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Error: LivestreamController.fetchLivestream")}})}}_a=new WeakMap,Ca=new WeakMap,br=new WeakMap,zs=new WeakMap,ZD([T.trace("LivestreamController.setupEvents")],lv.prototype,"setupEvents",1);var e1=Object.defineProperty,t1=Object.getOwnPropertyDescriptor,Ro=(s,t,e,r)=>{for(var i=r>1?void 0:r?t1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&e1(t,e,i),i};class Wn{constructor({name:t,socketHandler:e,meetingId:r}){m(this,Dl);p(this,"name","");m(this,St,{});m(this,si,"");m(this,ri,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"bulkRateLimitConfig",{maxInvocations:5,period:1});p(this,"listeners",{});this.name=t,f(this,ri,e),f(this,si,r)}async set(t,e,r=!0,i=!1){a(this,St)[t]=e,r&&this.remoteSet(t,e),i&&(this.listeners[t]&&this.listeners[t].forEach(n=>n({[t]:a(this,St)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(n=>n({[t]:a(this,St)[t]})))}remoteSet(t,e){a(this,ri).storeInsertKeys(a(this,si),this.name,[{key:t,payload:e}])}async bulkSet(t){t.forEach(({key:e,payload:r})=>{a(this,St)[e]=r}),a(this,ri).storeInsertKeys(a(this,si),this.name,t)}async update(t,e,r=!0){U(this,Dl,TS).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(a(this,St)[t]&&delete a(this,St)[t],e)return a(this,ri).storeDeleteKeys(a(this,si),this.name,[{key:t}]);r&&(this.listeners[t]&&(this.listeners[t].forEach(i=>i({[t]:void 0})),delete this.listeners[t]),this.listeners["*"]&&this.listeners["*"].forEach(i=>i({[t]:void 0})))}async bulkDelete(t){return t.forEach(({key:e})=>{a(this,St)[e]&&delete a(this,St)[e]}),a(this,ri).storeDeleteKeys(a(this,si),this.name,t)}get(t){if(a(this,St)[t])return a(this,St)[t]}getAll(){return a(this,St)}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){f(this,St,t)}}St=new WeakMap,si=new WeakMap,ri=new WeakMap,Dl=new WeakSet,TS=function(t,e,r=!0){let i;const n=a(this,St)[t],o=Object.prototype.toString.call(e),c=Object.prototype.toString.call(n);if(o!==c){this.set(t,e);return}switch(c){case"[object Array]":i=[...n,...e];break;case"[object Object]":i={...n,...e};break;case"[object Map]":i=new Map([...n,...e]);break;case"[object Set]":i=new Set([...n,...e]);break;default:i=e;break}this.set(t,i,r)},Ro([Lt(Hn,"rateLimitConfig")],Wn.prototype,"remoteSet",1),Ro([Lt(Hn,"bulkRateLimitConfig")],Wn.prototype,"bulkSet",1),Ro([Lt(Hn,"rateLimitConfig")],Wn.prototype,"update",1),Ro([Lt(Hn,"rateLimitConfig")],Wn.prototype,"delete",1),Ro([Lt(Hn,"bulkRateLimitConfig")],Wn.prototype,"bulkDelete",1);class s1{constructor(t,e){m(this,sc);m(this,Nl);p(this,"stores",new Map);m(this,tn,void 0);m(this,sn,"");m(this,rc,void 0);m(this,ii,new Map);f(this,tn,e),f(this,sn,t.getValue("meetingId")),f(this,rc,t),U(this,Nl,ES).call(this)}create(t){const e=new Wn({name:t,socketHandler:a(this,tn),meetingId:a(this,sn)});return a(this,tn).storeGetKeys(a(this,sn),t,[]),new Promise((i,n)=>{const o=setTimeout(()=>n(Error("Failed")),3e3);a(this,ii).set(t,{rejectTimeout:o,resolve:i,store:e})})}}tn=new WeakMap,sn=new WeakMap,sc=new WeakSet,vp=function(){return a(this,rc).getValue("peerId")},rc=new WeakMap,ii=new WeakMap,Nl=new WeakSet,ES=function(){[G.storeInsertKeys,G.storeGetKeys,G.storeDeleteKeys].forEach(t=>{a(this,tn).on(t,async e=>{var n,o;if(e.pluginId!==a(this,sn))return;const r=(n=e.storeItems)==null?void 0:n.map(c=>{var d;return{timestamp:c.timestamp,peerId:c.peerId,payload:JSON.parse((d=c.payload)!=null&&d.length?new TextDecoder().decode(c.payload):"{}"),key:c.storeKey}});if(t===G.storeGetKeys){const c=a(this,ii).get(e.storeName),d=this.stores.get(e.storeName)||(c==null?void 0:c.store);a(this,ii).get(e.storeName)&&(this.stores.set(e.storeName,c.store),c.resolve(d),clearTimeout(c.rejectTimeout),a(this,ii).delete(e.storeName)),r.forEach(l=>{d.set(l.key,l.payload,!1,!1)});return}const i=this.stores.get(e.storeName)||((o=a(this,ii).get(e.storeName))==null?void 0:o.store);i!==void 0&&(t===G.storeInsertKeys&&r.forEach(({key:c,peerId:d,payload:l})=>{d!==a(this,sc,vp)&&i.set(c,l,!1,!0)}),t===G.storeDeleteKeys&&r.forEach(({key:c,peerId:d})=>{d!==a(this,sc,vp)&&i.delete(c,!1,!0)}))})})};function Di(s){var t,e,r,i,n,o,c,d,l,u,h,g,v;return s?{media:{audio:{enabled:s.audioEnabled,trackId:(t=s.audioTrack)==null?void 0:t.id,permission:"mediaPermissions"in s?(e=s.mediaPermissions)==null?void 0:e.audio:null},video:{enabled:s.videoEnabled,trackId:(r=s.videoTrack)==null?void 0:r.id,permission:"mediaPermissions"in s?(i=s.mediaPermissions)==null?void 0:i.video:null},screenshare:{enabled:s.screenShareEnabled,permission:"mediaPermissions"in s?(n=s.mediaPermissions)==null?void 0:n.screenshare:null,audio:{enabled:(c=(o=s.screenShareTracks)==null?void 0:o.audio)==null?void 0:c.enabled,trackId:(l=(d=s.screenShareTracks)==null?void 0:d.audio)==null?void 0:l.id},video:{enabled:(h=(u=s.screenShareTracks)==null?void 0:u.video)==null?void 0:h.enabled,trackId:(v=(g=s.screenShareTracks)==null?void 0:g.video)==null?void 0:v.id}}}}:{}}var r1=Object.defineProperty,i1=Object.getOwnPropertyDescriptor,Jn=(s,t,e,r)=>{for(var i=r>1?void 0:r?i1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&r1(t,e,i),i};const n1=.8,a1=1.2;let hr=(dS=class extends Gt{constructor(t,e,r,i){const n=t.getValue("logger");super(n);m(this,rn);m(this,ni);m(this,nn);m(this,Vl);m(this,an);m(this,nc);m(this,xl);m(this,Ul);p(this,"id");p(this,"userId");p(this,"name");p(this,"picture");p(this,"isHost");p(this,"customParticipantId");p(this,"flags");p(this,"device");p(this,"videoTrack");p(this,"audioTrack");p(this,"screenShareTracks");p(this,"videoEnabled");p(this,"audioEnabled");p(this,"screenShareEnabled");p(this,"producers");p(this,"manualProducerConfig");m(this,Ra,void 0);p(this,"supportsRemoteControl",!1);m(this,ka,void 0);p(this,"presetName");m(this,Zt,void 0);m(this,wr,void 0);m(this,ic,void 0);m(this,ai,new Map);m(this,Pr,1);m(this,Ll,Zu(t=>{if(!this.videoTrack)return;const{clientWidth:e,clientHeight:r}=t,{width:i,height:n}=this.videoTrack.getSettings();if(!i||!n)return;const o=n/r,c=i/e,d=Math.max(o,c);d>a1&&a(this,Pr)===1?(f(this,Pr,0),a(this,Zt).getValue("peerSessionStore").emit(R.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,Pr)})):d<n1&&a(this,Pr)===0&&(f(this,Pr,1),a(this,Zt).getValue("peerSessionStore").emit(R.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,Pr)}))},2e3));f(this,Zt,t);const{id:o,userId:c,displayName:d,device:l,picture:u,isHost:h,flags:g,clientSpecificId:v,stageStatus:E,customParticipantId:b,audioMuted:P,audioTrack:w,videoEnabled:L=!1,videoTrack:$,producers:N,metadata:B}=e;this.id=o,this.userId=c,this.name=d,this.device=l,this.picture=u,this.isHost=h,this.flags=g,this.manualProducerConfig=oC,f(this,ka,E!=null?E:"ON_STAGE"),this.customParticipantId=b!=null?b:v,this.audioEnabled=!P,this.audioTrack=w,this.videoEnabled=L,this.videoTrack=$,this.screenShareTracks={audio:void 0,video:void 0},this.producers=N!=null?N:[],this.presetName=B==null?void 0:B.preset_name,f(this,Ra,!1),f(this,wr,r),f(this,ic,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),U(this,nc,Sp).call(this)}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return a(this,ka)}get telemetry(){return a(this,Zt).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("Participant::setVideoEnabled::videoUpdate",{...Di(this)}),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(this.logger.info("Participant::setAudioEnabled::audioUpdate",{...Di(this)}),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}))}setScreenShareEnabled(t,e=!0){this.screenShareEnabled=t,e&&this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}setupEvents(){this.on("videoUpdate",U(this,nc,Sp)),a(this,ni,io)&&(this.on("audioUpdate",U(this,xl,wS)),this.on("screenShareUpdate",U(this,Ul,PS)))}async pin(){if(!a(this,nn,ad))throw new C("Can`t pin participant without joining room","1205");if(!a(this,wr).permissions.pinParticipant)throw new C("You do not have permission to pin participants.","1201");return a(this,rn,nd).pinPeer(this.id)}async unpin(){if(!a(this,nn,ad))throw new C("Can`t unpin participant without joining room","1205");if(!a(this,wr).permissions.pinParticipant)throw new C("You do not have permission to unpin participants.","1201");return a(this,rn,nd).pinPeer(null)}setIsPinned(t,e=!0){var i;f(this,Ra,t);const r=t?"pinned":"unpinned";(i=a(this,an,od))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}async disableAudio(){const t=this.id;if(this.logger.info("Participant::disable_audio",{participant:{id:t}}),!a(this,nn,ad))throw new C("Can`t disable participant audio without joining room","1205");if(a(this,wr).permissions.canDisableParticipantAudio)return a(this,rn,nd).disableAudio(t);throw this.logger.error("Participant::unauthorized_disable_audio",{participant:{id:t}}),new C("Unauthorized: User does not have permission to disable participant audio.","1201")}async kick(){const t=this.id;if(this.logger.info("Participant::kick",{participant:{id:t}}),!a(this,Vl,bS))throw new C("Can`t kick participant without joining room","1205");if(a(this,wr).permissions.kickParticipant){await a(this,Zt).getValue("peerSessionStore").emitAsync(R.KICK_PEER,{peerId:t});return}throw this.logger.error("Participant::unauthorized_kick",{participant:{id:t}}),new C("Unauthorized: User does not have permission to kick participants.","1201")}async disableVideo(){const t=this.id;if(this.logger.info("Participant::disable_video",{participant:{id:t}}),!a(this,nn,ad))throw new C("Can`t disable participant video without joining room","1205");if(a(this,wr).permissions.canDisableParticipantVideo)return a(this,rn,nd).disableVideo(t);throw this.logger.error("Participant::unauthorized_disable_video",{participant:{id:t}}),new C("Unauthorized: User does not have permission to disable participant video.","1201")}async getPermissions(){return a(this,ic).getUserPermissions(this.userId)}setStageStatus(t){f(this,ka,t),this.emit("stageStatusUpdate",this)}get isPinned(){return a(this,Ra)}registerVideoElement(t){var r,i,n,o;if(!t)return;let e;(i=(r=a(this,ai).get(t))==null?void 0:r.observer)==null||i.disconnect(),"ResizeObserver"in window&&(e=new ResizeObserver(()=>a(this,Ll).call(this,t)),e.observe(t)),a(this,ai).set(t,{observer:e}),this.updateVideo(t),(o=a(this,an,od))==null||o.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(n=this.raised)!=null?n:!1)}deregisterVideoElement(t){var e,r,i,n;if(!t){(e=a(this,an,od))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=a(this,ai).get(t))==null?void 0:r.observer)==null||i.disconnect(),a(this,ai).delete(t),(n=a(this,an,od))==null||n.removeSource(this.id)}updateVideo(t){var e;if(this.videoEnabled){if(this.videoTrack==null)return;const r=(e=t.srcObject)==null?void 0:e.getTracks()[0];if((r==null?void 0:r.id)===this.videoTrack.id)return;const i=new MediaStream;i.addTrack(this.videoTrack),t.srcObject=i}else t.srcObject=void 0;t.style.display=this.videoEnabled?"block":"none"}},Ra=new WeakMap,ka=new WeakMap,Zt=new WeakMap,rn=new WeakSet,nd=function(){return a(this,Zt).getValue("roomNodeClient")},ni=new WeakSet,io=function(){return a(this,Zt).getValue("audioPlayback")},nn=new WeakSet,ad=function(){return a(this,Zt).getValue("connectionHandler").mediaJoined},Vl=new WeakSet,bS=function(){return a(this,Zt).getValue("connectionHandler").socketJoined},wr=new WeakMap,ic=new WeakMap,ai=new WeakMap,an=new WeakSet,od=function(){return a(this,Zt).getValue("pip")},Pr=new WeakMap,Ll=new WeakMap,nc=new WeakSet,Sp=function(){Array.from(a(this,ai).keys()).forEach(this.updateVideo)},xl=new WeakSet,wS=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=a(this,ni,io))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=a(this,ni,io))==null||e.removeParticipantTrack(this.id)},Ul=new WeakSet,PS=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=a(this,ni,io))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=a(this,ni,io))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},dS);Jn([T.trace("Participant.disableAudio")],hr.prototype,"disableAudio",1),Jn([T.trace("Participant.kick")],hr.prototype,"kick",1),Jn([T.trace("Participant.disableVideo")],hr.prototype,"disableVideo",1),Jn([T.trace("Participant.getPermissions")],hr.prototype,"getPermissions",1),Jn([T.trace("Participant.setStageStatus")],hr.prototype,"setStageStatus",1),hr=Jn([ut("1200")],hr);class ko extends Gf{constructor(t,e){const{onAddEvent:r="participantJoined",onDeleteEvent:i="participantLeft",onClearEvent:n="participantsCleared"}=e!=null?e:{};super({onAddEvent:r,onDeleteEvent:i,onClearEvent:n},t)}add(t,e=!0){return this.has(t.id)&&Object.is(this.get(t.id),t)===!1&&this.delete(t.id),super.add(t,e)}clear(t=!0,e=!1){return super.clear(t,e)}delete(t,e=!0,r=!1){return super.delete(t,e,r)}}class o1 extends Fn{constructor(e){super(e);m(this,oi,void 0);f(this,oi,new Map)}__set(e,r){return a(this,oi).set(e,r)}__clear(){return a(this,oi).clear()}get(e){return a(this,oi).get(e)}toArray(){return Array.from(a(this,oi).values())}}oi=new WeakMap;class c1{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 d1{constructor(){p(this,"_activeSpeakerPeers");p(this,"_compulsoryPeers");this._activeSpeakerPeers=new c1,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)}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 uv=new d1;var l1=Object.defineProperty,u1=Object.getOwnPropertyDescriptor,zt=(s,t,e,r)=>{for(var i=r>1?void 0:r?u1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&l1(t,e,i),i};const h1=["ACTIVE_GRID","PAGINATED","MANUAL"];let _t=(lS=class extends Gt{constructor(t,e,r){const i=t.getValue("logger");super(i);m(this,ac);m(this,on);m(this,Ia);p(this,"waitlisted");p(this,"joined");p(this,"active");p(this,"videoSubscribed");p(this,"audioSubscribed");p(this,"pinned");p(this,"all");m(this,Re,void 0);m(this,cn,void 0);m(this,$t,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"viewMode");p(this,"currentPage");p(this,"lastActiveSpeaker");p(this,"selectedPeers",uv);f(this,Re,t),f(this,cn,e),f(this,$t,r),this.waitlisted=new ko(i),this.joined=new ko(i),this.videoSubscribed=new ko(i),this.audioSubscribed=new ko(i),this.active=this.videoSubscribed,this.pinned=new ko(i),this.all=new o1(i),this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return a(this,Re).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return a(this,Re).getValue("telemetry")}setupEvents(){a(this,Re).getValue("peerSessionStore").on(R.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=a(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=a(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=a(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");a(this,Re).setValue("maxPreferredStreams",t),a(this,Ia,wu)&&a(this,Re).getValue("peerSessionStore").emit(R.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.selectedPeers.compulsoryPeers.length,e=this.joined.toArray().filter(r=>r.stageStatus==="ON_STAGE");return Math.ceil((e.length-t)/Math.max(this.maxActiveParticipantsCount-t,1))}return 0}acceptWaitingRoomRequest(t){var r,i;if(!a(this,on,cd))throw new C("Can`t accept waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;return a(this,$t).acceptWaitingRoomRequest([e])}async acceptAllWaitingRoomRequest(t){const e=t.map(r=>{var i,n;return(n=(i=this.waitlisted.get(r))==null?void 0:i.userId)!=null?n:r});return a(this,$t).acceptWaitingRoomRequest(e)}async rejectWaitingRoomRequest(t){var r,i;if(!a(this,on,cd))throw new C("Can`t reject waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;a(this,$t).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=>h1.includes(r))(t))throw this.logger.error("Participants::setViewMode::invalid_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),new C(`Invalid view mode: ${t}. Try ACTIVE_GRID, PAGINATED or MANUAL.`,"1207");if(this.viewMode===t){this.logger.info("Participants::setViewMode::view_mode_same_as_previous");return}this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,a(this,Re).getValue("peerSessionStore").emit(R.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,a(this,Re).getValue("peerSessionStore").emit(R.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,a(this,Re).getValue("peerSessionStore").emit(R.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})}async subscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new C("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)))}),a(this,Re).getValue("peerSessionStore").emit(R.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}async unsubscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new C("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!1},i.manualProducerConfig.screenshareAudio||this.audioSubscribed.delete(i.id)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!1},i.manualProducerConfig.screenshareVideo||this.videoSubscribed.delete(i.id)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!1},i.manualProducerConfig.audio||this.audioSubscribed.delete(i.id)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!1},i.manualProducerConfig.video||this.videoSubscribed.delete(i.id)))}),a(this,Re).getValue("peerSessionStore").emit(R.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}getPeerIdsForCurrentPage(){this.logger.info("Participants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(c=>this.joined.has(c)),r=Array.from(this.pinned.keys()).filter(c=>!e.includes(c)),i=Array.from(this.joined.toArray().filter(c=>c.stageStatus==="ON_STAGE").map(c=>c.id)),n=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),o=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,i.slice(n,o))}async setPage(t){if(this.logger.info("Participants::set_page",{pageNavigation:{settingPage:t,viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),this.viewMode==="PAGINATED"){if(!Number.isInteger(t))throw this.logger.error("Participants::invalid_page_number"),new C(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`,"1202");this.currentPage=t,a(this,Re).getValue("peerSessionStore").emit(R.UPDATE_ACTIVE,{viewMode:this.viewMode,page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}}async disableAllAudio(t){if(this.logger.info("Participants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!a(this,Ia,wu))throw new C("Can`t disable all audio without joining room","1205");if(a(this,cn).permissions.canAllowParticipantAudio)return a(this,ac,yp).muteAll(t);throw this.logger.error("Participants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new C("Unauthorized: User does not have permission to disable peer audio.","1201")}async disableAllVideo(){if(this.logger.info("Participants::disable_all_video"),!a(this,Ia,wu))throw new C("Can`t disable all video without joining room","1205");if(a(this,cn).permissions.canAllowParticipantVideo)return a(this,ac,yp).muteAllVideo();throw this.logger.error("Participants::unauthorized_disable_all_video"),new C("Unauthorized: User does not have permission to disable peer video.","1201")}async disableAudio(t){this.joined.get(t).disableAudio()}async disableVideo(t){this.joined.get(t).disableVideo()}async kick(t){await a(this,Re).getValue("peerSessionStore").emitAsync(R.KICK_PEER,{peerId:t})}async kickAll(){if(this.logger.info("Participants::kick_all"),a(this,Re).getValue("viewType")!=="LIVESTREAM"&&!a(this,on,cd))throw new C("Can`t kick all without joining room","1205");if(!a(this,cn).permissions.kickParticipant)throw this.logger.error("Participants::unauthorized_kick_all"),new C("Unauthorized: User does not have permission to kick peers.","1201");const e=a(this,Re).getValue("flagsmith").hasFeature(Z.PROPAGATE_KICK_ALL);a(this,$t).kickAll(e)}async broadcastMessage(t,e,r){if(this.logger.info("Participants::broadcastMessage"),!a(this,on,cd))throw new C("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new C("`type` must be a non-empty string.","1209");if(r)if("meetingIds"in r)await a(this,$t).broadcastToMeetings(t,r.meetingIds,e);else{let i=[];"participantIds"in r?i=r.participantIds:i=this.joined.toArray().filter(n=>{var o;return(o=r.presetNames)==null?void 0:o.includes(n.presetName)}).map(n=>n.id),await a(this,$t).broadcastToPeers(t,i,e)}else await a(this,$t).broadcastMessage(t,e)}async getAllJoinedPeers(t,e,r){return(await a(this,$t).getRoomPeers(t,e,r)).peers.map(pr.formatSocketPeerMessage)}async updatePermissions(t,e){const r=this.joined.toArray().filter(n=>t.includes(n.id)).map(n=>n.userId),i=[...new Set(r)];if(!i.length)throw new C("Cannot update permissions, no valid userIDs found","1204");a(this,$t).updatePermissions(i,e)}async getParticipantsInMeetingPreJoin(){return a(this,$t).getRoomPeersNonPaginated()}},Re=new WeakMap,ac=new WeakSet,yp=function(){return a(this,Re).getValue("roomNodeClient")},on=new WeakSet,cd=function(){var t;return((t=a(this,Re).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},Ia=new WeakSet,wu=function(){var t;return((t=a(this,Re).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},cn=new WeakMap,$t=new WeakMap,lS);zt([T.trace("Participants.setViewMode")],_t.prototype,"setViewMode",1),zt([T.trace("Participants.setPage")],_t.prototype,"setPage",1),zt([T.trace("Participants.disableAllAudio")],_t.prototype,"disableAllAudio",1),zt([T.trace("Participants.disableAllVideo")],_t.prototype,"disableAllVideo",1),zt([T.trace("Participants.disablePeerAudio")],_t.prototype,"disableAudio",1),zt([T.trace("Participants.disablePeerVideo")],_t.prototype,"disableVideo",1),zt([T.trace("Participants.kickPeer")],_t.prototype,"kick",1),zt([T.trace("Participants.kickAll")],_t.prototype,"kickAll",1),zt([T.trace("Participants.broadcastMessage"),Lt(Hn,"rateLimitConfig")],_t.prototype,"broadcastMessage",1),zt([T.trace("Participants.getAllJoinedPeers"),Lt({maxInvocations:10,period:60})],_t.prototype,"getAllJoinedPeers",1),zt([T.trace("Participant.updatePermissions"),Lt({maxInvocations:1e3,period:60})],_t.prototype,"updatePermissions",1),zt([T.trace("Participants.getParticipantsInMeetingPreJoin")],_t.prototype,"getParticipantsInMeetingPreJoin",1),_t=zt([ut("1200")],_t);var p1=Object.defineProperty,g1=Object.getOwnPropertyDescriptor,Ni=(s,t,e,r)=>{for(var i=r>1?void 0:r?g1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&p1(t,e,i),i};const hv=(uS=class{constructor(s,t,e){p(this,"participants");p(this,"self");p(this,"selectedPeers",uv);p(this,"maxSpatialLayerUpdates",new Map);p(this,"consumerPeerMap");p(this,"events");p(this,"roomSocketHandler");p(this,"context");p(this,"videoPeerConsumerMap",new Map);m(this,fs,{mode:"ACTIVE_GRID",page:0});m(this,Ds,!1);m(this,Aa,!1);p(this,"updateConsumerSpatialLayers",Zu(()=>{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 consumer updates - AddProducers: ${s.length}, RemoveProducers: ${t.length}, ConsumersSyncing: ${a(this,Ds)}`);try{s.length!==0&&(this.logger.info(`updateConsumers: Creating consumers for ${s.length} producers: [${s.map(e=>e.producerId).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 for ${t.length} producers: [${t.map(e=>e.producerId).join(", ")}]`),await this.roomNodeClient.closeConsumers(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 _t(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,this.events=_s,t.config.viewType!=="CHAT"&&this.setupEventsGlobal(),this.setupEvents()}get roomNodeClient(){return this.context.getValue("roomNodeClient")}get mediaJoined(){var s;return((s=this.roomNodeClient)==null?void 0:s.mediaJoined)===!0}get pip(){return this.context.getValue("pip")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}setupEvents(){this.roomSocketHandler.on(F.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),this.context.getValue("peerSessionStore").on(R.SOCKET_PEERS,async s=>{const t=this.context.getValue("flagsmith").hasFeature(Z.DEBUG_SOCKET_JOIN);if(t){const e=s&&(s==null?void 0:s.length)<20?{peers:JSON.stringify(s.map(r=>r.peerId))}:void 0;this.logger.info("Processing socket peers",e)}s==null||s.forEach(e=>{e.waitlisted||this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(e))}),t&&this.logger.info("Processed socket peers")}),this.roomSocketHandler.on(this.events.peerJoinedBroadcast,({participant:s})=>{this.logger.info("PEER_INFO:::MEDIA_JOIN",{participant:{id:s.peerId,maskedName:[...(s==null?void 0:s.displayName)||""].map((t,e)=>e%2?"*":t).join("")}}),this.logger.info("events.peerJoinedBroadcast",{peers:s.peerId}),this.onParticipantMediaJoined(s.peerId,s.producerStates,s.capabilities)}),this.roomSocketHandler.on(this.events.selfJoinComplete,({participants:s,selectedPeers:t,roomState:e})=>{if(this.context.getValue("flagsmith").hasFeature(Z.DEBUG_SOCKET_JOIN)){const n=s&&(s==null?void 0:s.length)<20?{peers:JSON.stringify(s.map(o=>o.peerId))}:void 0;this.logger.info("events.selfJoinComplete",n)}s.forEach(({peerId:n,producerStates:o,capabilities:c})=>this.onParticipantMediaJoined(n,o,c));const{audioPeers:r,compulsoryPeers:i}=t!=null?t:{};e.pinnedPeerIds.length!==0&&this.onParticipantPinned(e.pinnedPeerIds[0]),this.computeActivateParticipants(r!=null?r:[],i),this.logger.info("selfJoinComplete: Emitting UPDATE_ACTIVE with createAllConsumers=true"),this.context.getValue("peerSessionStore").emit(R.UPDATE_ACTIVE,{createAllConsumers:!0})}),this.context.getValue("peerSessionStore").on(R.MAX_SPATIAL_LAYER_CHANGE,({peerId:s,maxSpatialLayer:t})=>{const e=this.videoPeerConsumerMap.get(s);e&&(this.context.getValue("flagsmith").hasFeature(Z.DISABLE_LAYER_SWITCH)||(this.maxSpatialLayerUpdates.set(e,t),this.updateConsumerSpatialLayers()))}),this.context.getValue("peerSessionStore").on(R.NEW_PRODUCER,({peerId:s,producer:t})=>{const e=this.participants.joined.get(s);if(!e){this.logger.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:t==null?void 0:t.producerId,kind:t==null?void 0:t.kind,status:"not_initialized",appData:{screenShare:t==null?void 0:t.screenShare}},participant:{id:s}});return}e.producers.push(t),this.logger.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:t==null?void 0:t.producerId,peerId:s,kind:t==null?void 0:t.kind,status:"not_initialized",appData:{screenShare:t==null?void 0:t.screenShare}}}),(t==null?void 0:t.kind)==="audio"&&this.participants.audioSubscribed.get(s)||(t==null?void 0:t.kind)==="video"&&this.participants.videoSubscribed.get(s)||t!=null&&t.screenShare?(this.logger.info(`NEW_PRODUCER: scheduling syncConsumer (AUTO mode) - Producer: ${t.producerId}, Peer: ${s}, Kind: ${t.kind}, ScreenShare: ${t.screenShare}, ConsumersSyncing: ${a(this,Ds)}, VideoSub: ${t.kind==="video"?this.participants.videoSubscribed.has(s):"N/A"}, AudioSub: ${t.kind==="audio"?this.participants.audioSubscribed.has(s):"N/A"}`),this.scheduleSyncConsumers({source:"NEW_PRODUCER_AUTO"})):this.logger.info("ParticipantController::NEW_PRODUCER::not_consuming_producer_auto",{producer:{id:t==null?void 0:t.producerId,peerId:s,kind:t==null?void 0:t.kind,status:"UNKNOWN",appData:{screenShare:t==null?void 0:t.screenShare}}})}),this.context.getValue("peerSessionStore").on(R.PRODUCER_CLOSED,({peerId:s,producerId:t})=>{const e=this.participants.joined.get(s);if(!e){this.logger.warn("ParticipantController::NEW_PRODUCER::participant not found",{participant:{id:s}});return}e.producers=e.producers.filter(r=>r.producerId!==t)}),this.context.getValue("peerSessionStore").on(R.PRODUCER_TOGGLE,({peerId:s,producerId:t,paused:e,kind:r})=>{const i=this.participants.joined.get(s);if(i){r==="audio"&&i.setAudioEnabled(!e);const n=i.producers.find(o=>o.producerId===t);n&&(n.pause=e),r==="video"&&this.context.getValue("peerSessionStore").emit(R.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}}),this.roomSocketHandler.on(this.events.globalPeerPinBroadcast,s=>{let t;if(s&&(t=s.participantId),!this.mediaJoined)return;const e=t;this.onParticipantPinned(e);const r=this.participants.joined.get(e);r&&(this.logger.info(`globalPeerPinBroadcast: Scheduling audio/video consumer sync for pinned participant ${e} - ProducerCount: ${r.producers.length}, ConsumersSyncing: ${a(this,Ds)}, 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){const t=s.requests.filter(r=>!this.participants.waitlisted.toArray().find(i=>i.userId===r.userId)),e=this.participants.waitlisted.toArray().filter(r=>!s.requests.find(i=>i.userId===r.userId));t.forEach(r=>this.participants.waitlisted.add(new hr(this.context,{id:r.peerId,displayName:r.displayName,audioMuted:!0,videoEnabled:!1,audioTrack:void 0,videoTrack:void 0,stageStatus:"OFF_STAGE",userId:r.userId,flags:{},isHost:!1,customParticipantId:r.customParticipantId,picture:r.picture,metadata:{preset_name:r.presetName}},this.self,this.roomSocketHandler))),e.forEach(r=>this.participants.waitlisted.delete(r.id))}get maxPreferredStreams(){return this.participants.maxActiveParticipantsCount}selectPagePeers(s){const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(d=>this.participants.joined.has(d)),r=Array.from(this.participants.pinned.keys()).filter(d=>!e.includes(d)),i=Array.from(this.participants.joined.toArray().filter(d=>d.stageStatus==="ON_STAGE").map(d=>d.id)),n=Math.max((s-1)*(this.maxPreferredStreams-e.length-r.length)),o=s*(this.maxPreferredStreams-e.length-r.length);return e.concat(r,i.slice(n,o))}selectActivePeers(s){const t=new Map,e=Array.from(this.participants.joined.toArray().filter(u=>u.stageStatus==="ON_STAGE").map(u=>(t.set(u.id,!0),u.id))),r=this.selectedPeers.peers,i=this.participants.pinned.toArray().reduce((u,h)=>(h.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(h.id):u.push(h.id),u),[]),n=this.self.stageStatus==="ON_STAGE"?1:0,o=s-n,c=new Set(r.concat(i).filter(u=>u!==this.self.id&&t.has(u)));let d=Array.from(c);const l=o-c.size;if(l>=0){const u=e.filter(h=>!c.has(h)&&h!==this.self.id).slice(0,l);d=Array.from(c).concat(u)}else d=d.slice(0,o);return d}updateMediaSubscribedMaps(s,t){const{page:e}=t!=null?t:{};s&&a(this,fs).mode!==s&&(a(this,fs).mode=s),e&&a(this,fs).page!==e&&(a(this,fs).page=e);const{mode:r,page:i}=a(this,fs);switch(r){case"PAGINATED":{if(!i)return;const n=this.selectPagePeers(i),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMap(this.participants.videoSubscribed,n),this.updateParticipantsMap(this.participants.audioSubscribed,o),this.logger.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:n});break}case"ACTIVE_GRID":{const n=this.selectActivePeers(this.participants.maxActiveParticipantsCount),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMapMinReplacement(this.participants.videoSubscribed,n),this.updateParticipantsMap(this.participants.audioSubscribed,o);break}case"MANUAL":break;default:throw new Error(`View mode ${s} not supported`)}}async scheduleSyncConsumers({source:s}){var e,r,i;const t=((e=a(this,fs))==null?void 0:e.mode)==="PAGINATED"&&!a(this,Ds)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${s}, ViewMode: ${(r=a(this,fs))==null?void 0:r.mode}, ConsumersSyncing: ${a(this,Ds)}, Delay: ${t}, Page: ${(i=a(this,fs))==null?void 0:i.page}`),setTimeout(()=>this.syncConsumers(),t)}async syncConsumers(){var o,c,d,l,u;if(((d=(c=(o=this.context.getValue("connectionHandler"))==null?void 0:o.mediaState)==null?void 0:c.recv)==null?void 0:d.state)!=="connected"){this.logger.info("syncConsumers: Connection not ready, exiting.");return}if(a(this,Ds)){f(this,Aa,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),f(this,Ds,!0),f(this,Aa,!1);let s=[];this.participants.videoSubscribed.forEach(h=>{var E,b;const g=this.participants.joined.get(h.id),v=(b=(E=h.producers)==null?void 0:E.filter(P=>P.kind==="video"))!=null?b:[];g&&(v!=null&&v.length)&&v.forEach(P=>{var $,N,B,Y;const w=((N=($=g.manualProducerConfig)==null?void 0:$.video)!=null?N:!0)&&P.kind==="video"&&!P.screenShare,L=((Y=(B=g.manualProducerConfig)==null?void 0:B.screenshareVideo)!=null?Y:!0)&&P.kind==="video"&&P.screenShare;(w||L)&&(P.pause||s.push(P))})}),this.participants.audioSubscribed.forEach(h=>{var E,b;const g=this.participants.joined.get(h.id),v=(b=(E=h.producers)==null?void 0:E.filter(P=>P.kind==="audio"))!=null?b:[];g&&(v!=null&&v.length)&&v.forEach(P=>{var $,N,B,Y;const w=((N=($=g.manualProducerConfig)==null?void 0:$.audio)!=null?N:!0)&&P.kind==="audio"&&!P.screenShare,L=((Y=(B=g.manualProducerConfig)==null?void 0:B.screenshareAudio)!=null?Y:!0)&&P.kind==="audio"&&P.screenShare;(w||L)&&s.push(P)})}),s=aC(s,h=>h.producerId);const t=new Map;s.forEach(h=>{t.set(h.producerId,h)});const e=(l=this.roomNodeClient)==null?void 0:l.getConsumers(),r=s.filter(h=>!(e!=null&&e.has(h.producerId))),i=[];let n=Array.from((u=e==null?void 0:e.values())!=null?u:[]).map(h=>h.peerId);n=nC(n),n==null||n.forEach(h=>{var v;const g=this.participants.joined.get(h);if(!g){this.logger.warn(`Peer with ${h} doesn't exist in joined list but producers of it are being consumed.`);return}(v=g.producers)!=null&&v.length&&g.producers.forEach(E=>{const b=E.consumer&&e.has(E.consumer.id);!t.has(E.producerId)&&(e.has(E.producerId)||b)&&i.push(E)})}),this.logger.info(`syncConsumers: Computed changes - AddProducers: ${r.length} [${r.map(h=>h.producerId).join(", ")}], RemoveProducers: ${i.length} [${i.map(h=>h.producerId).join(", ")}]`.substring(0,5e3));try{r.length>0||i.length>0?(this.logger.info(`syncConsumers: Calling updateConsumers with changes. Adding ${r.length} and removing ${i.length}.`),await this.updateConsumers(r,i),this.logger.info("syncConsumers: updateConsumers completed successfully.")):this.logger.info("syncConsumers: No changes needed, skipping updateConsumers.")}catch(h){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:h})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),f(this,Ds,!1)}a(this,Aa)&&(this.logger.info("syncConsumers: Resync required, calling syncConsumers again."),this.syncConsumers())}computeActivateParticipants(s,t){const e=s.map((i,n)=>({peerId:i,priority:n+1})),r=t==null?void 0:t.map((i,n)=>({peerId:i,priority:-(n+1)}));e.push(...r!=null?r:[]),e.length>0&&this.updateActiveParticipantsWithPriorities(e)}createParticipantObjFromSocketPeer(s){const t=hv.formatSocketPeerMessage(s);return new hr(this.context,{...t,isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0},this.self,this.roomSocketHandler)}updatePipSource(s,t){var e,r;t?(e=this.pip)==null||e.enableSource(s):(r=this.pip)==null||r.disableSource(s)}onParticipantMediaJoined(s,t,e){if(!this.mediaJoined||s===this.self.id)return;const r=this.participants.joined.get(s);if(!r){this.logger.warn(`Received media.peerJoinedBroadcast for non-existent peer ${s}`);return}this.logger.info("PEER_INFO:::SOCKET_ON_MEDIA_JOIN",{participant:{id:r.id,maskedName:[...(r==null?void 0:r.name)||""].map((i,n)=>n%2?"*":i).join("")}}),this.logger.info(`onParticipantMediaJoined: peer ${s} has joined media room. Processing.`),t.forEach(i=>{i.kind===Ws.AUDIO&&!i.screenShare?r.setAudioEnabled(!i.pause):i.kind===Ws.VIDEO&&!i.screenShare&&(r.setVideoEnabled(!i.pause),this.updatePipSource(r.id,!i.pause)),r.producers.push({...i,producingTransportId:i.producingTransportId,kind:i.kind===Ws.AUDIO?"audio":"video",producingPeerId:s,mimeType:i.mimeType})}),this.roomNodeClient.handlePeerCapabilities(s,e),this.context.getValue("flagsmith").hasFeature(Z.FORCE_VIDEO_CODEC)||this.roomNodeClient.shareWebcam(this.self.videoTrack),this.logger.info(`onParticipantMediaJoined: Emitting UPDATE_ACTIVE for peer ${s}`),this.context.getValue("peerSessionStore").emit(R.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}updateParticipantsMapMinReplacement(s,t){const e=Array.from(s.keys()),r=new Map(s),i=new Set(t),n=[];e.forEach((o,c)=>{(!i.has(o)||!this.participants.joined.get(o))&&n.push(c)}),t.forEach(o=>{if(s.get(o))return;if(e.length<t.length){e.push(o);return}const c=n.shift();e[c]=o}),n.forEach(o=>{e.splice(o,1)}),Array.from(s.keys()).forEach(o=>{s.delete(o,!i.has(o))}),e.forEach(o=>{if(!this.participants.joined.get(o)){this.logger.warn("updateActiveParticipants::participant_not_in_joined_list",{participant:{id:o}});return}s.add(this.participants.joined.get(o),!r.get(o))}),s.emit("participantsUpdate")}updateParticipantsMap(s,t){Array.from(s.keys()).forEach(r=>{t.includes(r)||s.delete(r,!0)}),t.forEach(r=>{s.get(r)||s.add(this.participants.joined.get(r),!0)}),s.emit("participantsUpdate")}updatePinnedParticipants(){this.participants.pinned.forEach(s=>{s.setIsPinned(!1),this.participants.pinned.delete(s.id)})}setupEventsGlobal(){this.roomSocketHandler.on(F.joinRoom,({peer:s})=>{if(!s.waitlisted){const t=this.context.getValue("flagsmith").hasFeature(Z.DEBUG_SOCKET_JOIN);t&&this.logger.info("Processing socket join",{peers:s.peerId}),this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(s)),t&&this.logger.info("Processed socket join",{peers:s.peerId})}}),this.roomSocketHandler.on(F.leaveRoom,s=>{const{peerId:t}=s.peer;this.selectedPeers.delete(t,this.context),this.onParticipantLeave(t)}),this.context.getValue("peerSessionStore").on(R.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(R.SOCKET_SERVICE_DISCONNECTED,()=>{this.participants.joined.clear(),this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear(),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount})}),this.context.getValue("peerSessionStore").on(R.CONSUMER_PAUSED,({id:s})=>{this.processConsumerPaused(s)}),this.context.getValue("peerSessionStore").on(R.CONSUMER_RESUMED,({id:s})=>{this.processConsumerResumed(s)}),this.context.getValue("peerSessionStore").on(R.NEW_CONSUMER,({id:s})=>{this.processNewConsumer(s)}),this.context.getValue("peerSessionStore").on(R.CONSUMER_CLOSED,({id:s})=>{this.processConsumerClosed(s)}),this.context.getValue("peerSessionStore").on(R.ROOM_MESSAGE,async({payload:s,type:t,timestamp:e})=>{this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(R.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(R.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(R.CONSUMER_SCORE_UPDATE,({score:s,kind:t,appData:e,peerId:r,scoreStats:i})=>{var c;const n=t==="video"&&((c=e==null?void 0:e.screenShare)!=null?c:!1),o=this.participants.joined.get(r);o&&(o.emit("mediaScoreUpdate",{kind:t,isScreenshare:n,score:s,participantId:r,scoreStats:i}),this.participants.emit("mediaScoreUpdate",{kind:t,isScreenshare:n,score:s,participantId:r,scoreStats:i}))}),this.context.getValue("peerSessionStore").onAsync(R.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(R.UPDATE_ACTIVE,async({viewMode:s,page:t,createAllConsumers:e}={viewMode:"ACTIVE_GRID",page:0,createAllConsumers:!1})=>{this.logger.info(`UPDATE_ACTIVE event received - viewMode: ${a(this,fs).mode}, page: ${t}, CreateAllConsumers: ${e}`),e&&(this.logger.info(`UPDATE_ACTIVE viewMode: ${s}, Page: ${t}, Removing existing subscriptions.`),this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear()),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.logger.info(`onParticipantSocketJoined: peer ${s.id} has joined socket edge. Processing.`),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.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(R.UPDATE_STAGE_REQUESTS,{request:{displayName:s.name,userId:s.userId,peerId:s.id},add:!0})),this.context.getValue("peerSessionStore").emit(R.PEER_JOINED_INTERNAL,s)}async onParticipantLeave(s){const t=this.participants.joined.get(s);this.participants.joined.delete(s,!0,!0),this.participants.pinned.delete(s,!0,!0),this.participants.waitlisted.delete(s,!0,!0),this.roomNodeClient&&(this.roomNodeClient.handlePeerLeaving(s),this.roomNodeClient.closeConsumers(t==null?void 0:t.producers)),t&&t.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&this.context.getValue("peerSessionStore").emit(R.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!1});const{currentPage:e}=this.participants,r=this.maxPreferredStreams*(e-1),i=this.participants.videoSubscribed.get(s);this.participants.viewMode==="MANUAL"?this.context.getValue("peerSessionStore").emit(R.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:e}):r===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=r?e===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(e-1):i&&this.context.getValue("peerSessionStore").emit(R.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:e})}processMedia(s){var h;const t=this.roomNodeClient.getConsumers(),{peerId:e,kind:r,appData:i,track:n,producerId:o,rtpReceiver:c,paused:d,localId:l}=(h=t.get(s))!=null?h:{};if(!e)return this.logger.warn("processMedia::Peer ID is undefined",{consumer:{id:s,kind:r,peerId:e,appData:{supportsRemoteControl:!!(i!=null&&i.supportsRemoteControl),screenShare:!!(i!=null&&i.screenShare)},remotelyPaused:d,producerId:o}}),{};const u=i;return r==="video"&&u.screenShare!==!0&&this.videoPeerConsumerMap.set(e,s),this.logger.info("ParticipantController::processMedia",{consumer:{id:s,peerId:e,kind:r,appData:u,remotelyPaused:d,producerId:o}}),this.consumerPeerMap.set(s,{type:r,peerId:e,appData:u,remotelyPaused:d,producerId:o}),{peerId:e,kind:r,appData:u,remotelyPaused:d,track:n,producerId:o,rtpReceiver:c,localId:l}}processConsumerClosed(s){const{peerId:t,type:e,appData:r,remotelyPaused:i,producerId:n}=this.consumerPeerMap.get(s)||{},o=this.participants.joined.get(t);if(this.logger.info("ParticipantController::processConsumerClosed",{consumer:{id:s,peerId:t,appData:r,kind:e,remotelyPaused:i,producerId:n}}),this.consumerPeerMap.delete(s),e==="video"&&r.screenShare!==!0&&this.videoPeerConsumerMap.delete(t),!o)return;const c=o.producers.find(l=>l.producerId===n);c&&(c.consumer={id:s,peerId:t,kind:void 0,appData:r,paused:i,producerId:n,rtpReceiver:void 0,localId:void 0});const d=[];r&&r.screenShare?(o.setScreenShareEnabled(!1),this.context.getValue("callstats").consumerSharedMediaState(s,{screen:!1}),o.screenShareTracks.video&&d.push(o.screenShareTracks.video.id),o.screenShareTracks.audio&&d.push(o.screenShareTracks.audio.id),o.screenShareTracks={audio:void 0,video:void 0}):e==="audio"?(o.setAudioEnabled(!1),o.audioTrack&&d.push(o.audioTrack.id),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!1}),o.audioTrack=void 0):e==="video"&&(o.setVideoEnabled(!1),this.updatePipSource(o.id,!1),o.videoTrack&&d.push(o.videoTrack.id),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1}),o.videoTrack=void 0),r.e2ee&&d.forEach(l=>{this.context.getValue("peerSessionStore").emit(R.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:l})})}processConsumerResumed(s){var g;const t=this.processMedia(s),{peerId:e,kind:r,appData:i,track:n,remotelyPaused:o,producerId:c,rtpReceiver:d,localId:l}=t;if(!e)return;this.logger.info("ParticipantController::processConsumerResumed",{consumer:{id:s,peerId:e,kind:r,appData:i,remotelyPaused:o,producerId:c}});const u=this.participants.joined.get(e);if(!u)return;const h=u.producers.find(v=>v.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(R.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:d,track:n}),i.screenShare){r==="video"?u.screenShareTracks.video=n:r==="audio"&&(u.screenShareTracks.audio=n),u.setScreenShareEnabled(!0),(g=this.context)==null||g.getValue("callstats").consumerSharedMediaState(s,{screen:!0});return}r==="video"?(u.videoTrack=n,u.setVideoEnabled(!0),this.updatePipSource(u.id,!0),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!0})):r==="audio"&&(u.audioTrack=n,u.setAudioEnabled(u.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:u.audioEnabled}))}processConsumerPaused(s){this.logger.info(`ParticipantController::processConsumerPaused called for consumerId: ${s}`);const{peerId:t,kind:e,track:r,appData:i,remotelyPaused:n,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processConsumerPaused",{consumer:{id:s,peerId:t,kind:e,appData:i,remotelyPaused:n,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(h=>h.producerId===o);u&&(u.consumer={id:s,peerId:t,kind:e,appData:i,paused:n,producerId:o,rtpReceiver:c,localId:d}),r&&i.e2ee&&this.context.getValue("peerSessionStore").emit(R.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:r.id}),e==="video"?(l.videoTrack=r,l.setVideoEnabled(!1),this.updatePipSource(l.id,!1),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1})):e==="audio"&&(l.audioTrack=r,l.setAudioEnabled(l.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:l.audioEnabled}))}processNewConsumer(s){const{peerId:t,kind:e,remotelyPaused:r,track:i,appData:n,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processNewConsumer",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:n,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(h=>h.producerId===o);if(u&&(u.consumer={id:s,peerId:t,kind:e,appData:n,paused:r,producerId:o,rtpReceiver:c,localId:d}),n.screenShare){e==="video"?l.screenShareTracks.video=i:e==="audio"&&(l.screenShareTracks.audio=i),(!r||this.self.permissions.isRecorder||this.context.getValue("flagsmith").hasFeature(Z.SCREEENSHARE_ERR_HACK))&&l.setScreenShareEnabled(!0),n.supportsRemoteControl&&(l.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:o,peerId:t,screenShare:!0,consumerId:s,consumerPeerId:this.self.id}),this.logger.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:n,producerId:o}});return}e==="video"?(l.videoTrack=i,r||(l.setVideoEnabled(!0),this.updatePipSource(l.id,!0)),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!r})):e==="audio"&&(l.audioTrack=i,r||l.setAudioEnabled(!0),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!r})),!r&&n.e2ee&&this.context.getValue("peerSessionStore").emit(R.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:c,track:i})}static formatSocketPeerMessage(s){var e,r,i,n,o,c;if(!s)return;const t=Dh(s.stageType);return{id:s.peerId,userId:s.userId,name:s.displayName,displayName:s.displayName,stageType:t,customParticipantId:s.customParticipantId,presetId:s.presetId,picture:s.displayPictureUrl,waitlisted:s.waitlisted,stageStatus:t,metadata:{preset_name:(e=s.flags)==null?void 0:e.presetName},recorderType:(r=s.flags)==null?void 0:r.recorderType,flags:{hiddenParticipant:(i=s.flags)==null?void 0:i.hiddenParticipant,hidden_participant:(n=s.flags)==null?void 0:n.hiddenParticipant,recorder:((o=s.flags)==null?void 0:o.recorderType)!==void 0&&((c=s.flags)==null?void 0:c.recorderType)!=="NONE"}}}async onSelectedPeers(s,t){this.participants.viewMode==="ACTIVE_GRID"&&this.computeActivateParticipants(s,t)}updateActiveParticipantsWithPriorities(s,t=!1){if(this.participants.viewMode==="MANUAL")return;if(!this.mediaJoined){this.logger.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.mediaJoined});return}s.forEach(r=>{this.selectedPeers.add(r.peerId,r.priority,this.context)});const e=this.selectedPeers.activeSpeakerPeers.at(0);e!==void 0&&e!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=e,this.participants.emit("activeSpeaker",{peerId:e,volume:1})),t&&this.context.getValue("peerSessionStore").emit(R.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}},fs=new WeakMap,Ds=new WeakMap,Aa=new WeakMap,uS);let pr=hv;Ni([T.trace("ParticipantController.setupEvents")],pr.prototype,"setupEvents",1),Ni([T.trace("ParticipantController.setupEvents")],pr.prototype,"setupEventsGlobal",1),Ni([T.trace("ParticipantController.processMedia")],pr.prototype,"processMedia",1),Ni([T.trace("ParticipantController.processConsumerClosed")],pr.prototype,"processConsumerClosed",1),Ni([T.trace("ParticipantController.processConsumerResumed")],pr.prototype,"processConsumerResumed",1),Ni([T.trace("ParticipantController.processConsumerPaused")],pr.prototype,"processConsumerPaused",1),Ni([T.trace("ParticipantController.processNewConsumer")],pr.prototype,"processNewConsumer",1);const he=Rs(Ku().permissions),Da=class extends Gt{constructor(e,r,i,n=!1){const o=e.getValue("logger");super(o);m(this,It);m(this,q,void 0);m(this,Ma,void 0);m(this,Oa,void 0);m(this,Fl,e=>{var l,u,h;const{chat:r,connectedMeetings:i,plugins:n,polls:o,media:c,...d}=e;if(r&&(r.private&&Fr(a(this,q).chat.private,r.private),r.public&&Fr(a(this,q).chat.public,r.public),this.emit("chatUpdate")),i&&Fr(a(this,q).connectedMeetings,i),c){const g=E=>{switch(E){case $r.NONE:return H.Allowed;case $r.ALLOWED:return H.Allowed;case $r.NOT_ALLOWED:return H.NotAllowed;case $r.CAN_REQUEST:return H.CanRequest;default:return}},v={audio:void 0,video:void 0,screenshare:void 0};(l=c.audio)!=null&&l.canProduce&&(v.audio={canProduce:g(c.audio.canProduce)}),(u=c.video)!=null&&u.canProduce&&(v.video={canProduce:g(c.video.canProduce)}),(h=c.screenshare)!=null&&h.canProduce&&(v.screenshare={canProduce:g(c.screenshare.canProduce)}),Fr(a(this,q).media,v)}n&&(Fr(a(this,q).plugins,n),this.emit("pluginsUpdate")),o&&(Fr(a(this,q).polls,o),this.emit("pollsUpdate")),Object.keys(d).length!==0&&Fr(a(this,q),d),this.emit("permissionsUpdate",e)});if(!r)throw this.logger.error("PermissionPreset::load_preset_permissions_failed"),new C("Could not load preset permissions.","0904");f(this,Oa,e),f(this,Ma,i),f(this,q,r),n&&this.setupEvents()}setupEvents(){a(this,Oa).getValue("peerSessionStore").on(R.UPDATE_PERMISSIONS,a(this,Fl))}static fromResponse(e,r,i){return new Da(i,e,r,!0)}static default(e,r){return new Da(e,he,r)}static init(e,r,i){let n;return i?n=new Da(e,i,r,!0):n=new Da(e,he,r),n}get mediaRoomType(){return"CF"}get stageEnabled(){var e;return((e=a(this,q))==null?void 0:e.stageEnabled)||a(this,Ma)===Vt.Webinar||a(this,Ma)===Vt.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=a(this,q))==null?void 0:e.acceptStageRequests)||((r=a(this,q))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,i;return((e=a(this,q))==null?void 0:e.stageAccess)===H.NotAllowed?H.NotAllowed:((r=a(this,q))==null?void 0:r.stageAccess)===H.CanRequest?H.CanRequest:((i=a(this,q))==null?void 0:i.stageAccess)===H.Allowed||a(this,q).media.audio.canProduce===H.Allowed||a(this,q).media.video.canProduce===H.Allowed||a(this,q).media.screenshare.canProduce===H.Allowed?H.Allowed:a(this,q).media.audio.canProduce===H.CanRequest||a(this,q).media.video.canProduce===H.CanRequest||a(this,q).media.screenshare.canProduce===H.CanRequest?H.CanRequest:H.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=a(this,q))==null?void 0:e.acceptWaitingRequests)!=null?r:he.acceptWaitingRequests}get requestProduceVideo(){var e,r,i;return((i=(r=(e=a(this,q))==null?void 0:e.media)==null?void 0:r.video)==null?void 0:i.canProduce)===H.CanRequest}get requestProduceAudio(){var e,r,i;return((i=(r=(e=a(this,q))==null?void 0:e.media)==null?void 0:r.audio)==null?void 0:i.canProduce)===H.CanRequest}get requestProduceScreenshare(){var e,r,i;return((i=(r=(e=a(this,q))==null?void 0:e.media)==null?void 0:r.screenshare)==null?void 0:i.canProduce)===H.CanRequest}get canAllowParticipantAudio(){var e,r;return(r=(e=a(this,q))==null?void 0:e.disableParticipantAudio)!=null?r:he.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=a(this,q))==null?void 0:e.canAcceptProductionRequests)!=null?r:he.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=a(this,q))==null?void 0:e.disableParticipantVideo)!=null?r:he.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var e,r;return(r=(e=a(this,q))==null?void 0:e.kickParticipant)!=null?r:he.kickParticipant}get pinParticipant(){var e,r;return(r=(e=a(this,q))==null?void 0:e.pinParticipant)!=null?r:he.pinParticipant}get canRecord(){var e,r;return(r=(e=a(this,q))==null?void 0:e.canRecord)!=null?r:he.canRecord}get waitingRoomType(){var e,r;return(r=(e=a(this,q))==null?void 0:e.waitingRoomType)!=null?r:he.waitingRoomType}get waitingRoomBehaviour(){var e,r;return(r=(e=a(this,q))==null?void 0:e.waitingRoomType)!=null?r:he.waitingRoomType}get plugins(){var e,r;return(r=(e=a(this,q))==null?void 0:e.plugins)!=null?r:he.plugins}get polls(){var e,r;return(r=(e=a(this,q))==null?void 0:e.polls)!=null?r:he.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return a(this,q).media.audio.canProduce===H.CanRequest||a(this,q).media.video.canProduce===H.CanRequest||a(this,q).media.screenshare.canProduce===H.CanRequest}get canProduceVideo(){var r;const e=(r=a(this,q).media.video.canProduce)!=null?r:he.media.video.canProduce;return this.stageEnabled&&(a(this,It,rs)==="ACCEPTED_TO_JOIN_STAGE"||a(this,It,rs)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(a(this,It,rs)==="OFF_STAGE"||a(this,It,rs)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var r;const e=(r=a(this,q).media.screenshare.canProduce)!=null?r:he.media.screenshare.canProduce;return this.stageEnabled&&(a(this,It,rs)==="ACCEPTED_TO_JOIN_STAGE"||a(this,It,rs)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(a(this,It,rs)==="OFF_STAGE"||a(this,It,rs)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var r;const e=(r=a(this,q).media.audio.canProduce)!=null?r:he.media.audio.canProduce;return this.stageEnabled&&(a(this,It,rs)==="ACCEPTED_TO_JOIN_STAGE"||a(this,It,rs)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(a(this,It,rs)==="OFF_STAGE"||a(this,It,rs)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get chatPublic(){var e,r,i;return(i=(r=(e=a(this,q))==null?void 0:e.chat)==null?void 0:r.public)!=null?i:he.chat.public}get chatPrivate(){var e,r,i;return(i=(r=(e=a(this,q))==null?void 0:e.chat)==null?void 0:r.private)!=null?i:he.chat.private}get chatChannel(){var e,r,i;return(i=(r=(e=a(this,q))==null?void 0:e.chat)==null?void 0:r.channel)!=null?i:he.chat.channel}get chatMessage(){var e,r,i;return(i=(r=(e=a(this,q))==null?void 0:e.chat)==null?void 0:r.message)!=null?i:he.chat.message}get connectedMeetings(){var e,r;return(r=(e=a(this,q))==null?void 0:e.connectedMeetings)!=null?r:he==null?void 0:he.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=a(this,q))==null?void 0:e.hiddenParticipant)!=null?r:he.hiddenParticipant}get showParticipantList(){var e;return(e=a(this,q).showParticipantList)!=null?e:he.showParticipantList}get canChangeParticipantRole(){var e,r;return(r=(e=a(this,q))==null?void 0:e.canChangeParticipantPermissions)!=null?r:he.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var e,r;return(r=(e=a(this,q))==null?void 0:e.canChangeParticipantPermissions)!=null?r:he.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return a(this,q).media.audio.canProduce===H.Allowed||a(this,q).media.video.canProduce===H.Allowed||a(this,q).media.screenshare.canProduce===H.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var e;return(e=a(this,q).canEditDisplayName)!=null?e:!1}get maxScreenShareCount(){return 1}get isRecorder(){return a(this,q).isRecorder}get canSpotlight(){return a(this,q).canSpotlight}get canLivestream(){return a(this,q).canLivestream}get transcriptionEnabled(){return a(this,q).transcriptionEnabled}};let qh=Da;q=new WeakMap,Ma=new WeakMap,Oa=new WeakMap,Fl=new WeakMap,It=new WeakSet,rs=function(){return a(this,Oa).getValue("stageStatus")};class pv extends Gt{constructor(e,r){super(r);p(this,"localMediaHandler");m(this,es,void 0);f(this,es,e)}async updatePermission(){var d,l;const e=(u,h)=>{this.mediaPermissions[u]=h;const g={message:this.mediaPermissions[u],kind:u};h==="DENIED"?a(this,es).getValue("peerSessionStore").emit(R.MEDIA_PERMISSION_ERROR,g):a(this,es).getValue("peerSessionStore").emit(R.MEDIA_PERMISSION_UPDATE,g)};if(ye.getName()==="firefox")return;const r="microphone",i="camera",n=await((d=navigator==null?void 0:navigator.permissions)==null?void 0:d.query({name:r})),o=await((l=navigator==null?void 0:navigator.permissions)==null?void 0:l.query({name:i})),c=(u,h)=>{switch(h){case"granted":e(u,"ACCEPTED");break;case"denied":e(u,"DENIED");break;case"prompt":e(u,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};n&&(n.onchange=()=>c("audio",n.state)),o&&(o.onchange=()=>c("video",o.state))}async populateMediaPermissionsInCallstats({message:e,kind:r}){var i,n,o,c;switch(r){case"audio":{(i=a(this,es))==null||i.getValue("callstats").mediaPermission("AUDIO",e),(n=a(this,es))==null||n.getValue("callstats").mediaPermission("SPEAKER",e);break}case"video":{(o=a(this,es))==null||o.getValue("callstats").mediaPermission("VIDEO",e);break}case"screenshare":{(c=a(this,es))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",e);break}}}get peerId(){var e;return(e=a(this,es))==null?void 0:e.getValue("peerId")}async init(e={},r=!1,i=null){var n,o,c,d,l,u,h;if(ye.init(),i&&f(this,es,i),!this.localMediaHandler)try{let g=!0;if((n=i==null?void 0:i.getValue("defaults"))!=null&&n.mediaHandler)g=!1,this.localMediaHandler=i.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:v}=navigator;this.localMediaHandler=await v.init(e)}else this.localMediaHandler=new xt(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(R.MEDIA_PERMISSION_UPDATE,async v=>{if(this.populateMediaPermissionsInCallstats({message:v.message,kind:v.kind}),v.message==="NOT_REQUESTED")switch(v==null?void 0:v.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",v)}),i==null||i.getValue("peerSessionStore").on(R.MEDIA_PERMISSION_ERROR,async v=>{const{kind:E,message:b,constraints:P}=v;this.populateMediaPermissionsInCallstats({message:b,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:b},constraints:P,mediaPermissionsErrors:{kind:E,message:b}}),this.emit("mediaPermissionError",v),this.emit("mediaPermissionUpdate",{message:b,kind:E})}),g){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 v=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 v}}catch(g){this.logger.error("Self::init::Failed To Setup Streams",{error:{name:g.name,message:g.message}})}}set context(e){f(this,es,e),this.localMediaHandler.context=e}get audioTrack(){return this.localMediaHandler.audioTrack}get rawAudioTrack(){return this.localMediaHandler.rawAudioTrack}get mediaPermissions(){return this.localMediaHandler.permissions}async addAudioMiddleware(e){return this.localMediaHandler.addAudioMiddleware(e)}async removeAudioMiddleware(e){return this.localMediaHandler.removeAudioMiddleware(e)}async removeAllAudioMiddlewares(){return this.localMediaHandler.removeAllAudioMiddlewares()}get videoTrack(){return this.localMediaHandler.videoTrack}get rawVideoTrack(){return this.localMediaHandler.rawVideoTrack}async addVideoMiddleware(e){return this.localMediaHandler.addVideoMiddleware(e)}async setVideoMiddlewareGlobalConfig(e={disablePerFrameCanvasRendering:!1}){return this.localMediaHandler.setVideoMiddlewareGlobalConfig(e)}async removeVideoMiddleware(e){return this.localMediaHandler.removeVideoMiddleware(e)}async removeAllVideoMiddlewares(){return this.localMediaHandler.removeAllVideoMiddlewares()}get screenShareTracks(){return this.localMediaHandler.screenShareTracks}get audioEnabled(){return this.localMediaHandler.audioEnabled}get videoEnabled(){return this.localMediaHandler.videoEnabled}get screenShareEnabled(){return this.localMediaHandler.screenShareEnabled}async enableAudio(){await this.localMediaHandler.enableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableVideo(){await this.localMediaHandler.enableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}async disableAudio(){this.localMediaHandler.disableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableScreenShare(){await this.localMediaHandler.enableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableScreenShare(){await this.localMediaHandler.disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableVideo(){await this.localMediaHandler.disableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}getCurrentDevices(){return this.localMediaHandler.getCurrentDevices()}async getAudioDevices(){return await this.localMediaHandler.getAudioDevices()}async getVideoDevices(){return await this.localMediaHandler.getVideoDevices()}async getSpeakerDevices(){return await this.localMediaHandler.getSpeakerDevices()}getDeviceById(e,r){let i;return r==="audio"?i="audioinput":r==="video"?i="videoinput":r==="speaker"&&(i="audiooutput"),this.localMediaHandler.getDeviceById(e,i)}async setDevice(e){switch(e.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(e,{saveDevicePreference:!0})}catch(r){}finally{this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":await this.localMediaHandler.setSpeakerDevice(e,{saveDevicePreference:!0});break;case"videoinput":try{await this.localMediaHandler.setVideoDevice(e,{saveDevicePreference:!0})}catch(r){}finally{this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})}}es=new WeakMap;var m1=Object.defineProperty,f1=Object.getOwnPropertyDescriptor,Ct=(s,t,e,r)=>{for(var i=r>1?void 0:r?f1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&m1(t,e,i),i};let tt=(hS=class extends pv{constructor(t,e,r,i,n){var c;const o=t.getValue("logger");super(t,o);m(this,_r);m(this,Ye);m(this,La);m(this,je);m(this,oc);p(this,"name");p(this,"picture");p(this,"customParticipantId");p(this,"waitlistStatus");m(this,Na,void 0);m(this,At,void 0);m(this,Va,void 0);p(this,"role");p(this,"userId");p(this,"organizationId");p(this,"supportsRemoteControl",!1);p(this,"device");m(this,We,void 0);p(this,"hidden",!1);p(this,"presetName");p(this,"roomState","init");m(this,xa,new Set);m(this,Ua,new Set);f(this,We,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=(c=e.customParticipantId)!=null?c:e.clientSpecificId,this.waitlistStatus="none",f(this,At,r),f(this,Na,i),this.hidden=!1,f(this,Va,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=ye.isElectron(),this.device=ye.getDeviceInfo(),this.presetName=n,i.viewType!==Vt.Chat&&this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),U(this,oc,Tp).call(this)}get telemetry(){return a(this,We).getValue("telemetry")}get stageStatus(){return a(this,We).getValue("stageStatus")}get producers(){var t,e;return Array.from((e=(t=a(this,Ye,dt).getProducers())==null?void 0:t.values())!=null?e:[])}get id(){return this.peerId}get peerId(){return a(this,We).getValue("peerId")}static async __init__(t,e,r,i,n,o=!1){var g,v,E,b,P,w;let c=(v=(g=t.getValue("defaults"))==null?void 0:g.audio)!=null?v:!0,d=(b=(E=t.getValue("defaults"))==null?void 0:E.video)!=null?b:!0;r.canProduceAudio!=="ALLOWED"&&(c=!1),r.canProduceVideo!=="ALLOWED"&&(d=!1);const l=new tt(t,e,r,i,n);if(i.viewType===Vt.Chat)return l;const u=CD(i.mediaConstraints);Fr(u,(P=t.getValue("defaults"))==null?void 0:P.mediaConfiguration);const h=(w=t.getValue("defaults"))==null?void 0:w.mediaHandler;return h&&(h.context=t),await l.init({audio:c,video:d,constraints:u},o,t),l.setupEvents(),l}cleanupEvents(){this.removeAllListeners("videoUpdate"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("VIDEO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_LIST_UPDATED"),this.localMediaHandler.removeAllListeners("SCREENSHARE_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("SCREENSHARE_ENDED"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_SILENT"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_AUDIO"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_VIDEO"),a(this,At).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",U(this,oc,Tp));const t=a(this,La,Pu);t&&t.onError(e=>{this.emit("autoplayError",e)}),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::AUDIO_TRACK_CHANGE",{...Di(this)}),a(this,je,Ze)&&this.audioEnabled)try{await a(this,Ye,dt).shareMic(this.audioTrack)}catch(e){this.logger.error("Self::setupEvents::Error while sharing mic",{error:e}),this.localMediaHandler.disableAudio()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}),this.localMediaHandler.on("VIDEO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::VIDEO_TRACK_CHANGE",{...Di(this)}),a(this,je,Ze)&&this.rawVideoTrack===void 0)this.logger.info("Self::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&a(this,je,Ze))try{const e=await a(this,Ye,dt).shareWebcam(this.videoTrack);e&&e.id!==this.videoTrack.id&&a(this,We).getValue("flagsmith").hasFeature(Z.EXP_RESHARE)&&await a(this,Ye,dt).shareWebcam(this.videoTrack)}catch(e){this.logger.error("Self::setupEvents::failed shareWebcam",{error:e}),this.videoEnabled&&await this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}),this.localMediaHandler.on("DEVICE_CHANGE",async({device:e})=>{var r;this.emit("deviceUpdate",{device:e}),e.kind==="audiooutput"&&typeof HTMLAudioElement.prototype.setSinkId=="function"&&((r=a(this,La,Pu))==null||r.setSpeakerDevice(e.deviceId))}),this.localMediaHandler.on("DEVICE_LIST_UPDATED",e=>{this.emit("deviceListUpdate",e)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",async()=>{if(!a(this,je,Ze)){this.logger.error("Self.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await a(this,Ye,dt).shareScreen(this.screenShareTracks)}catch(e){this.logger.error("Self::setupEvents::Error while sharing screen",{error:e}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.logger.info("Self::setupEvents::SCREENSHARE_TRACK_CHANGE",{...Di(this)}),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}),this.localMediaHandler.on("SCREENSHARE_ENDED",async()=>{this.logger.log("Disabling screenshare due to SCREENSHARE_ENDED"),await this.disableScreenShare(),this.logger.info("Self::setupEvents::SCREENSHARE_ENDED",{...Di(this)})}),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{var e;(e=a(this,We))==null||e.getValue("callstats").mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",async()=>{var e;a(this,je,Ze)&&await a(this,Ye,dt).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(e=a(this,We))==null||e.getValue("callstats").videoOff()}),a(this,At).on("permissionsUpdate",e=>{var r,i,n;(r=e==null?void 0:e.media)!=null&&r.audio&&a(this,At).canProduceAudio!==H.Allowed&&(this.disableAudio(),this.logger.info(`Disabled audio due to dynamic preset change: canProduceAudio: ${this.permissions.canProduceAudio}`)),(i=e==null?void 0:e.media)!=null&&i.video&&a(this,At).canProduceVideo!==H.Allowed&&(this.disableVideo(),this.logger.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(n=e==null?void 0:e.media)!=null&&n.screenshare&&a(this,At).canProduceScreenshare!==H.Allowed&&(this.disableScreenShare(),this.logger.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return a(this,At)}get config(){return a(this,Na)}get roomJoined(){var t;return a(this,Na).viewType===Vt.Livestream&&this.stageStatus!=="ON_STAGE"?((t=a(this,We).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:a(this,je,Ze)}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!==H.NotAllowed&&!(a(this,At).canProduceAudio===H.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if((e=a(this,We))==null||e.getValue("callstats").audioOn(),await this.localMediaHandler.enableAudio(t),a(this,je,Ze)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await a(this,Ye,dt).shareMic(this.audioTrack)}catch(r){this.logger.error("Self::enableAudio::Error while sharing mic",{error:r}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}}async enableVideo(t){var e;if(a(this,At).canProduceVideo!==H.NotAllowed&&!(a(this,At).canProduceVideo===H.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if((e=a(this,We))==null||e.getValue("callstats").videoOn(),await this.localMediaHandler.enableVideo(t),a(this,je,Ze)&&this.stageStatus==="ON_STAGE")try{await a(this,Ye,dt).shareWebcam(this.videoTrack)}catch(r){this.logger.error("Self::enableVideo::Error while sharing video",{error:r}),this.videoEnabled&&this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),this.logger.info("Self.enableVideo",{...Di(this)})}}async updateVideoConstraints(t){if(!this.localMediaHandler.updateVideoConstraints)throw new C("Unsupported","1102");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){if(!a(this,je,Ze))throw new C("Can`t enable screenshare without joining room","1105");if(a(this,At).canProduceScreenshare!==H.NotAllowed&&!(a(this,At).canProduceScreenshare===H.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.screenShareEnabled&&(await this.localMediaHandler.enableScreenShare(),this.screenShareTracks.audio||this.screenShareTracks.video)){try{await a(this,Ye,dt).shareScreen(this.screenShareTracks)}catch(t){this.logger.error("Self::enableScreenShare::Error while sharing screen",{error:t}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}}async updateScreenshareConstraints(t){if(!this.localMediaHandler.updateScreenshareConstraints)throw new C("Unsupported","1102");await this.localMediaHandler.updateScreenshareConstraints(t)}async disableAudio(){var t;this.audioEnabled&&(this.localMediaHandler.disableAudio(),a(this,je,Ze)&&a(this,Ye,dt).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),(t=a(this,We))==null||t.getValue("callstats").audioOff())}async disableVideo(){var t;this.videoEnabled&&(await this.localMediaHandler.disableVideo(),a(this,je,Ze)&&await a(this,Ye,dt).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(t=a(this,We))==null||t.getValue("callstats").videoOff())}async disableScreenShare(){this.screenShareEnabled&&(await this.localMediaHandler.disableScreenShare(),a(this,je,Ze)&&await a(this,Ye,dt).disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var i;f(this,Va,t);const r=t?"pinned":"unpinned";(i=a(this,_r,On))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return a(this,Va)}async pin(){if(!a(this,je,Ze))throw new C("Can`t pin participants without joining room","1105");return this.show(),a(this,Ye,dt).pinPeer(this.id)}async unpin(){if(!a(this,je,Ze))throw new C("Can`t unpin participants without joining room","1105");return a(this,Ye,dt).pinPeer(null)}async hide(){if(!a(this,je,Ze))throw new C("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})}show(){if(!a(this,je,Ze))throw new C("Can`t toggle participant tile without joining room","1105");this.hidden=!1,this.emit("toggleTile",{hidden:this.hidden})}async setDevice(t){var r,i,n;if(!t)throw new C("No device selected","1104");const e=this.getCurrentDevices();if(t.deviceId&&(((r=e==null?void 0:e.audio)==null?void 0:r.deviceId)===t.deviceId||((i=e==null?void 0:e.video)==null?void 0:i.deviceId)===t.deviceId||((n=e==null?void 0:e.speaker)==null?void 0:n.deviceId)===t.deviceId)&&(this.logger.warn("Self.setDevice.setting_to_in_use_device",{devices:[t]}),a(this,We).getValue("flagsmith").hasFeature(Z.SKIP_SETTING_IN_USE_DEVICE)))throw new C("Cannot set device currently in use","1106");switch(t.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(t,{saveDevicePreference:!0})}catch(o){a(this,je,Ze)&&await a(this,Ye,dt).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":await this.localMediaHandler.setSpeakerDevice(t,{saveDevicePreference:!0});break;case"videoinput":try{await this.localMediaHandler.setVideoDevice(t,{saveDevicePreference:!0})}catch(o){a(this,je,Ze)&&await a(this,Ye,dt).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}}cleanUpTracks(){var t,e,r,i;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(r=this.videoTrack)==null||r.stop(),(i=this.rawVideoTrack)==null||i.stop()}playAudio(){var t;return(t=a(this,La,Pu))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?a(this,xa).add(t):a(this,Ua).add(t),this.updateVideo(t),e||(i=a(this,_r,On))==null||i.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(r=this.raised)!=null?r:!1))}deregisterVideoElement(t,e=!1){if(!t){a(this,_r,On).removeSource(this.id);return}t.srcObject=void 0,e?a(this,xa).delete(t):(a(this,Ua).delete(t),a(this,_r,On).removeSource(this.id))}updateVideo(t,e=!1){var r,i,n;if(this.videoEnabled){if(this.videoTrack==null)return;const o=(r=t.srcObject)==null?void 0:r.getTracks()[0];if((o==null?void 0:o.id)===this.videoTrack.id)return;const c=new MediaStream;c.addTrack(this.videoTrack),t.srcObject=c,e||(i=a(this,_r,On))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(n=a(this,_r,On))==null||n.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},Na=new WeakMap,At=new WeakMap,Va=new WeakMap,We=new WeakMap,_r=new WeakSet,On=function(){return a(this,We).getValue("pip")},Ye=new WeakSet,dt=function(){return a(this,We).getValue("roomNodeClient")},La=new WeakSet,Pu=function(){return a(this,We).getValue("audioPlayback")},je=new WeakSet,Ze=function(){var t;return((t=a(this,We).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},xa=new WeakMap,Ua=new WeakMap,oc=new WeakSet,Tp=function(){Array.from(a(this,Ua)).forEach(t=>this.updateVideo(t,!1)),Array.from(a(this,xa)).forEach(t=>this.updateVideo(t,!0))},hS);Ct([T.trace("Self.cleanupEvents")],tt.prototype,"cleanupEvents",1),Ct([T.trace("Self.setupEvents")],tt.prototype,"setupEvents",1),Ct([T.trace("Self.setupTracks")],tt.prototype,"setupTracks",1),Ct([T.trace("Self.destructMediaHandler")],tt.prototype,"destructMediaHandler",1),Ct([T.trace("Self.removeDocumentEventListeners")],tt.prototype,"removeDocumentEventListeners",1),Ct([ur.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"Self.toggleAudio",timeout:3e3}),T.trace("Self.enableAudio")],tt.prototype,"enableAudio",1),Ct([ur.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"Self.toggleVideo",timeout:3e3}),T.trace("Self.enableVideo")],tt.prototype,"enableVideo",1),Ct([T.trace("Self.updateVideoConstraints")],tt.prototype,"updateVideoConstraints",1),Ct([T.trace("Self.enableScreenShare"),ur.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3})],tt.prototype,"enableScreenShare",1),Ct([T.trace("Self.updateScreenshareConstraints")],tt.prototype,"updateScreenshareConstraints",1),Ct([ur.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"Self.toggleAudio",timeout:3e3}),T.trace("Self.disableAudio")],tt.prototype,"disableAudio",1),Ct([ur.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"Self.toggleVideo",timeout:3e3}),T.trace("Self.disableVideo")],tt.prototype,"disableVideo",1),Ct([ur.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3}),T.trace("Self.disableScreenShare")],tt.prototype,"disableScreenShare",1),Ct([T.trace("Self.setDevice")],tt.prototype,"setDevice",1),tt=Ct([ut("1100")],tt);class jh extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,jh)}}class Gh extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Gh)}}class Wh{constructor(t,e=!1){p(this,"pendingTasks",new Map);p(this,"nextTaskId",0);p(this,"stopping",!1);m(this,cc,void 0);this.log=e,f(this,cc,{info:e&&t?t.info:()=>{}})}get size(){return this.pendingTasks.size}async push(t,e,r){if(e=e!=null?e:t.name,typeof t!="function")throw new TypeError("given task is not a function");if(e)try{Object.defineProperty(t,"name",{value:e})}catch(i){}return new Promise((i,n)=>{const o={id:this.nextTaskId++,task:t,metadata:r,name:e,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:c=>{if(o.completed)return;o.completed=!0,this.pendingTasks.delete(o.id),i(c);const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)},reject:c=>{if(!o.completed&&(o.completed=!0,this.pendingTasks.delete(o.id),n(c),!this.stopping)){const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)}}};this.pendingTasks.set(o.id,o),this.pendingTasks.size===1&&this.execute(o)})}stop(){this.stopping=!0;for(const t of this.pendingTasks.values())t.reject(new jh);this.stopping=!1}remove(t){const e=Array.from(this.pendingTasks.values())[t];e&&e.reject(new Gh)}get(t){return Array.from(this.pendingTasks.values())[t]}dump(){const t=Date.now();let e=0;return Array.from(this.pendingTasks.values()).map(r=>({idx:e++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:t-r.enqueuedAt,executionTime:r.executedAt?t-r.executedAt:0}))}async execute(t){if(t.executedAt)throw new Error("task already being executed");t.executedAt=Date.now();try{const e=this.pendingTasks.size,r=await t.task(),i=Date.now();a(this,cc).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)}}}cc=new WeakMap;function v1(s,t){const e=new Error(t);return e.name=s,e}class Io extends C{constructor(t){super(t),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Io):this.stack=new Error(t).stack}}class Ut extends C{constructor(t){super(t),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ut):this.stack=new Error(t).stack}}class Vi extends C{constructor(t){super(t),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ut):this.stack=new Error(t).stack}}const gv=s=>new Promise(t=>setTimeout(t,s));async function mv(s,t){return new Promise(async(e,r)=>{const{strategy:i,maxRetryCount:n,delayTime:o}={strategy:"linear",maxRetryCount:3,delayTime:10,...t};let c=0,d,l=!1;const u=h=>{l=!0,r(h)};for(;c<n;){try{const h=await s(c,u);return e(h)}catch(h){if(d=h,l)break;if(c<n)i==="linear"?await gv(o*(c+1)):i==="exponential"&&await gv(o*(c+Math.max(0,c-1)));else break}c+=1}return r(d)})}function S1(s){return s.map(t=>({channels:t.channels,clockRate:t.clockRate,mimeType:t.mimeType,sdpFmtpLine:t.sdpFmtpLine}))}function y1(s){return s.map(t=>({uri:t.uri}))}function cl(s){return{codecs:S1(s.codecs),headerExtensions:y1(s.headerExtensions?s.headerExtensions:[])}}function T1(s){const t=RTCRtpReceiver.getCapabilities("audio"),e=RTCRtpReceiver.getCapabilities("video"),r=RTCRtpSender.getCapabilities("audio"),i=RTCRtpSender.getCapabilities("video");s&&(e.codecs=e.codecs.filter(({mimeType:d})=>s===d),i.codecs=i.codecs.filter(({mimeType:d})=>s===d));const n={audio:cl(t),video:cl(e)};return{sender:{audio:cl(r),video:cl(i)},receiver:n}}class E1{constructor(t){m(this,it,void 0);p(this,"events");f(this,it,t),this.events=_s}async joinRoom(t,e,r,i=!1,n=null){const o={roomUuid:t,displayName:e,prejoined:i,capabilities:r};return n&&(o.location=n),(await a(this,it).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:IR.toBinary(o),timeout:5e3})).payload}async connectTransport(t){const e=(await a(this,it).sendMessagePromise(this.events.createWebRTCTransport,rR.toBinary(t))).payload,{transportId:r,description:i,producerIds:n}=Xm.fromBinary(e),o={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:r,answer:o,producerIds:n}}async produce(t){var n,o;const e=(await a(this,it).sendMessagePromise(this.events.produce,jR.toBinary(t))).payload,r=Ck.fromBinary(e);return{answer:{sdp:(n=r==null?void 0:r.description)==null?void 0:n.sdp,type:(o=r==null?void 0:r.description)==null?void 0:o.type},producerId:r.producerId}}async consume(t){const e=(await a(this,it).sendMessagePromise(this.events.consume,UR.toBinary(t))).payload,{consumerIdsMap:{map:r},description:i}=Pk.fromBinary(e);return{consumerStateMap:r,sessionDescription:i}}async closeProducer(t){const e=(await a(this,it).sendMessagePromise(this.events.closeProducer,QR.toBinary(t))).payload,{description:r}=Dk.fromBinary(e);return r}async closeConsumer(t){return(await a(this,it).sendMessagePromise(this.events.closeConsumer,ZR.toBinary(t))).payload}async updateConsumersSimulcastConfig(t){return(await a(this,it).sendMessagePromise(this.events.updateConsumersSimulcastConfig,HR.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},i=(await a(this,it).sendMessagePromise(this.events.hostControlPeer,nk.toBinary(r))).payload;if(!i)return!1;const{status:n}=$k.fromBinary(i);return n==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await a(this,it).sendMessagePromise(this.events.hostControlAllPeers,ok.toBinary(e))).payload;if(!r)return!1;const{status:i}=Hk.fromBinary(r);return i==="success"}async kickAll(){const t={propagateKickAcrossRooms:!1};a(this,it).sendMessagePromise(F.kickAll,nf.toBinary(t))}async kickPeer(t){a(this,it).sendMessagePromise(F.kick,Tf.toBinary(t))}async changeDisplayName(t){const e=(await a(this,it).sendMessagePromise(this.events.changeDisplayName,rk.toBinary(t))).payload;if(!e)return!1;const{status:r}=jk.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await a(this,it).sendMessagePromise(this.events.selfJoinComplete,MR.toBinary(t))).payload;return uh.fromBinary(e)}async audioActivity(t){a(this,it).sendMessage(this.events.audioActivity,nR.toBinary(t))}}it=new WeakMap;var Kn=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s.CLOSED="closed",s))(Kn||{});class dl extends lt.EventEmitter{constructor(e){super();m(this,dc,void 0);f(this,dc,e),this.setMaxListeners(1/0)}get logger(){return a(this,dc).getValue("logger")}safeEmit(e,...r){const i=this.listenerCount(e);try{return this.emit(e,...r)}catch(n){return this.logger.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:n}),Boolean(i)}}async safeEmitAsPromise(e,...r){const i={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,i,...r)}async safeEmitAsPromiseWithTimeout(e,r,...i){return new Promise((n,o)=>{setTimeout(o,r,"event request timeout");try{this.emit(e.toString(),...i,n,o)}catch(c){this.logger.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:c}),o(c)}})}}dc=new WeakMap;class Jh extends dl{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(`${this.name}::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:async i=>{this.logger.info(`${this.name}::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this.pc.setRemoteDescription(i)}}}init({direction:e,iceServers:r,iceTransportPolicy:i,additionalSettings:n,proprietaryConstraints:o,onTrackHandler:c}){this.logger.debug("HandlerInterface::init()"),this._direction=e,this.pc=new RTCPeerConnection({iceServers:r||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...n},o),c&&this.pc.addEventListener("track",d=>{c(d)}),this._addEventListeners()}async connect(){this.pc.addTransceiver("audio",{direction:"sendonly"}),this.pc.addTransceiver("video",{direction:"sendonly"});const e=await this.pc.createOffer();return await this.pc.setLocalDescription(e),this.logger.info(`connect offer: ${JSON.stringify(e)}`),{offerSdp:e,callback:async i=>{this.logger.debug(`${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(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(i)}]`),await this.pc.setLocalDescription(i),{offerSdp:i,callback:async o=>{this.logger.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(o)}]`),await this.pc.setRemoteDescription(o),this.midTransceiverMap.delete(e)}}}async replaceTrack(e,r){this._assertSendDirection(),r?this.logger.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):this.logger.debug(`replaceTrack() [localId:${e}, no track]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");await i.sender.replaceTrack(r)}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters();n.encodings.forEach((o,c)=>{c<=r?o.active=!0:o.active=!1}),await i.sender.setParameters(n)}async setRtpEncodingParameters(e,r){this._assertSendDirection(),this.logger.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters();n.encodings.forEach((o,c)=>{n.encodings[c]={...o,...r}}),await i.sender.setParameters(n)}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}_addEventListeners(){this.pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this.pc.addEventListener("iceconnectionstatechange",()=>{switch(this.pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),this.logger.debug("negotiationneeded")}),this.pc.addEventListener("icegatheringstatechange",()=>{switch(this.pc.iceGatheringState){case"gathering":this.logger.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":this.logger.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("icecandidateerror",e=>{this.logger.warn("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this.pc.addEventListener("datachannel",e=>{this.logger.info("data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{this.logger.info("data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{this.logger.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{this.logger.error("data channel error: ",{rtcChannel:{label:e.channel.label}})}}),this.addCustomEventListeners()}addCustomEventListeners(){}}class Kh extends Jh{static createFactory(t){return()=>new Kh(t)}get name(){return"Chrome74"}init({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:i,proprietaryConstraints:n,onTrackHandler:o}){this._direction=t,this.pc=new RTCPeerConnection({iceServers:e||[],iceTransportPolicy:r||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...i},n),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection();const n=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e});if(!navigator.isReactNative){this.logger.debug("creating new transceiver");const d=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`senders available params: ${JSON.stringify(d)}`);const l=[];r&&r.length&&r.forEach(u=>{var g;const h=d.codecs.find(v=>v.mimeType.includes(u.name));if(u.parameters){this.logger.debug(`codecOption.parameters:${JSON.stringify(u.parameters)}`);const v=((g=h.sdpFmtpLine)==null?void 0:g.split(";"))||[];v.push(...u.parameters);const E=Array.from(new Set(v).values());h.sdpFmtpLine=E.join(";")}l.push(h)}),this.logger.info(`selected codecs: ${JSON.stringify(l)}`),n.setCodecPreferences(l)}const o=await this.pc.createOffer();if(await this.pc.setLocalDescription(o),r&&r.findIndex(({name:d})=>d==="opus")>=0){const{enableDtx:d,enableStereo:l}=this,u=this.enableHighBitrate?l?128e3:64e3:l?64e3:32e3;o.sdp=o.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${d?"usedtx=1;":""}${l?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${u}`),o.sdp+=`a=rtcp-fb:111 nack\r
16
16
  `}this.midTransceiverMap.set(n.mid,n);const c=async d=>(this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),await this.pc.setRemoteDescription(d),n.mid);return this.logger.debug(`send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(o,void 0,2)}]`),{offerSdp:o,callback:c,sender:n.sender,mid:n.mid}}addCustomEventListeners(){this.pc.addEventListener("datachannel",t=>{const{channel:e}=t;e.onmessage=r=>{this.safeEmit("datachannel",t.channel,String.fromCharCode(...new Uint8Array(r.data)))}})}}var fv={},ll={},b1={get exports(){return ll},set exports(s){ll=s}},vv=b1.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(s){return s.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(s){return s.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(s){var t="candidate:%s %d %s %d %s %d typ %s";return t+=s.raddr!=null?" raddr %s rport %d":"%v%v",t+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(t+=" generation %d"),t+=s["network-id"]!=null?" network-id %d":"%v",t+=s["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(s){var t="ssrc:%d";return s.attribute!=null&&(t+=" %s",s.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(s){return s.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(s){return s.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(s){return"imageattr:%s %s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(s){return"simulcast:%s %s"+(s.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var t="mediaclk:";return t+=s.id!=null?"id=%s %s":"%v%s",t+=s.mediaClockValue!=null?"=%s":"",t+=s.rateNumerator!=null?" rate=%s":"",t+=s.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(vv).forEach(function(s){var t=vv[s];t.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})}),function(s){var t=function(c){return String(Number(c))===c?Number(c):c},e=function(c,d,l,u){if(u&&!l)d[u]=t(c[1]);else for(var h=0;h<l.length;h+=1)c[h+1]!=null&&(d[l[h]]=t(c[h+1]))},r=function(c,d,l){var u=c.name&&c.names;c.push&&!d[c.push]?d[c.push]=[]:u&&!d[c.name]&&(d[c.name]={});var h=c.push?{}:u?d[c.name]:d;e(l.match(c.reg),h,c.names,c.name),c.push&&d[c.push].push(h)},i=ll,n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);s.parse=function(c){var d={},l=[],u=d;return c.split(/(\r\n|\r|\n)/).filter(n).forEach(function(h){var g=h[0],v=h.slice(2);g==="m"&&(l.push({rtp:[],fmtp:[]}),u=l[l.length-1]);for(var E=0;E<(i[g]||[]).length;E+=1){var b=i[g][E];if(b.reg.test(v))return r(b,u,v)}}),d.media=l,d};var o=function(c,d){var l=d.split(/=(.+)/,2);return l.length===2?c[l[0]]=t(l[1]):l.length===1&&d.length>1&&(c[l[0]]=void 0),c};s.parseParams=function(c){return c.split(/;\s?/).reduce(o,{})},s.parseFmtpConfig=s.parseParams,s.parsePayloads=function(c){return c.toString().split(" ").map(Number)},s.parseRemoteCandidates=function(c){for(var d=[],l=c.split(" ").map(t),u=0;u<l.length;u+=3)d.push({component:l[u],ip:l[u+1],port:l[u+2]});return d},s.parseImageAttributes=function(c){return c.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(o,{})})},s.parseSimulcastStreamList=function(c){return c.split(";").map(function(d){return d.split(",").map(function(l){var u,h=!1;return l[0]!=="~"?u=t(l):(u=t(l.substring(1,l.length)),h=!0),{scid:u,paused:h}})})}}(fv);var zh=ll,w1=/%[sdv%]/g,P1=function(s){var t=1,e=arguments,r=e.length;return s.replace(w1,function(i){if(t>=r)return i;var n=e[t];switch(t+=1,i){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}})},Ao=function(s,t,e){var r=t.format instanceof Function?t.format(t.push?e:e[t.name]):t.format,i=[s+"="+r];if(t.names)for(var n=0;n<t.names.length;n+=1){var o=t.names[n];t.name?i.push(e[t.name][o]):i.push(e[t.names[n]])}else i.push(e[t.name]);return P1.apply(null,i)},_1=["v","o","s","i","u","e","p","c","b","t","r","z","a"],C1=["i","c","b","a"],R1=function(s,t){t=t||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(n){n.payloads==null&&(n.payloads="")});var e=t.outerOrder||_1,r=t.innerOrder||C1,i=[];return e.forEach(function(n){zh[n].forEach(function(o){o.name in s&&s[o.name]!=null?i.push(Ao(n,o,s)):o.push in s&&s[o.push]!=null&&s[o.push].forEach(function(c){i.push(Ao(n,o,c))})})}),s.media.forEach(function(n){i.push(Ao("m",zh.m[0],n)),r.forEach(function(o){zh[o].forEach(function(c){c.name in n&&n[c.name]!=null?i.push(Ao(o,c,n)):c.push in n&&n[c.push]!=null&&n[c.push].forEach(function(d){i.push(Ao(o,c,d))})})})}),i.join(`\r
@@ -20,4 +20,4 @@ slogScale: ${i}, isVoice: ${r}, minEnergy: ${a(this,Mr)},
20
20
  maxEnergy: ${a(this,ui)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,Mr)||i<a(this,Mr))&&f(this,Mr,i),(!a(this,ui)||i>a(this,ui))&&f(this,ui,i),{energy:(i-a(this,Mr))/(a(this,ui)-a(this,Mr))*10||0,isVoice:r})},Mc=new WeakSet,Rp=function(t){return t<5},cu=new WeakSet,HS=function(t=a(this,yn)){var r;if(!a(this,xs)||!t){a(this,Or).getValue("flagsmith").hasFeature(Z.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,xs)}`);return}const e={producerId:a(this,xs),energy:Math.round(t),silent:U(r=Oc,Mc,Rp).call(r,t)};f(this,to,e.silent),this.reportRequest(e)},du=new WeakSet,qS=function(t){const e=Math.log10(t);return Math.round(e)},m(Oo,Mc),m(Oo,du);const q1=(s=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const e=new window.MediaStreamTrackGenerator({kind:"audio"}),r=e.writable.getWriter(),i=48e3,n=128,o=1;let c=0,d=null;const l=async()=>{try{const g=new Float32Array(n*o),v=new window.AudioData({format:"f32",sampleRate:i,numberOfFrames:n,numberOfChannels:o,timestamp:c,data:g});c+=n/i*1e6,await r.ready,await r.write(v)}catch(g){d&&clearInterval(d),r.releaseLock(),e.writable.abort()}};d=window.setInterval(l,100);const h=new MediaStream([e]).getAudioTracks()[0];return h.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),e.writable.abort()}),Object.assign(h,{fakeTracks:"fakeTracks:fakeAudioTrack"}),h.enabled=s,h}catch(e){}const t=window.AudioContext||window.webkitAudioContext;if(t)try{const e=new t;if(!e||e.state!=="running"||!e.destination)return;const r=e.createOscillator();r.frequency.value=0,r.type="sine";const i=e.createGain();i.gain.value=0,r.connect(i);const n=e.createMediaStreamDestination();i.connect(n),r.start();const o=n.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=s,o):void 0}catch(e){return}},j1=(s=!1)=>{var n,o;const t=new MediaStream().getVideoTracks()[0],e=document.createElement("canvas");e.height=(n=t==null?void 0:t.getSettings().height)!=null?n:720,e.width=(o=t==null?void 0:t.getSettings().width)!=null?o:1280;const r=e.getContext("2d");r.fillStyle="black",r.fillRect(0,0,e.width,e.height),setInterval(()=>{r.fillStyle="black",r.fillRect(0,0,e.width,e.height)},1e3);const i=e.captureStream().getVideoTracks()[0];return Object.assign(i,{fakeTracks:"fakeTracks:fakeVideoTrack"}),i.enabled=s,i};var G1=Object.defineProperty,W1=Object.getOwnPropertyDescriptor,ce=(s,t,e,r)=>{for(var i=r>1?void 0:r?W1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&G1(t,e,i),i};const Yt=["video/VP9","video/VP8"],bv=(up=class{constructor(s,t){m(this,hi);m(this,lu);m(this,uu);m(this,hu);m(this,xc);m(this,gu);m(this,mu);m(this,fu);m(this,ot);m(this,_n);m(this,vu);m(this,Su);m(this,yu);p(this,"context");p(this,"authToken");p(this,"e2ee");m(this,Dc,void 0);m(this,Nc,void 0);m(this,Et,void 0);m(this,j,void 0);m(this,so,void 0);m(this,Mt,void 0);m(this,Tn,void 0);m(this,En,void 0);m(this,bn,void 0);m(this,Vc,void 0);m(this,ys,null);m(this,Nr,void 0);m(this,Lc,void 0);m(this,wn,void 0);m(this,Pn,void 0);m(this,Ot,void 0);m(this,Ht,void 0);var r,i;this.context=s;const{socket:e}=t;this.mediaJoined=!1,f(this,wn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,Pn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,Et,e),f(this,Tn,!1),f(this,j,new F1(s,e)),f(this,Mt,a(this,j).events),f(this,Nr,new Set),f(this,Ot,new Map),f(this,En,!1),f(this,bn,new Wh(s.getValue("logger"))),f(this,Ht,new Oo(this.context,a(this,j).socketHandler.audioActivity.bind(a(this,j).socketHandler))),this.e2ee=(i=(r=s.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?i:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,Vc,Zu(async()=>{if(!a(this,hi,no).mediaJoinAttempted)return;const{roomJoined:n}=await this.joinRoom(a(this,Nc),a(this,Dc),!0,!0);n&&(this.context.getValue("peerSessionStore").emit(R.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(R.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return a(this,hi,no).mediaJoined}set mediaJoined(s){a(this,hi,no).mediaJoined=s}reset(){a(this,j).closeAllProducers(),a(this,j).closeAllConsumers(),a(this,Ot).clear(),a(this,Nr).clear(),f(this,ys,null),a(this,bn).stop(),a(this,j).stopAllTransports(),a(this,j).reset(),f(this,bn,new Wh)}async joinRoom(s,t,e=!1,r=!1,i={}){a(this,hi,no).mediaJoinAttempted=!0,f(this,Tn,!0),e&&this.reset();try{return await a(this,bn).push(()=>U(this,lu,jS).call(this,s,t,r,i),"joinRoom")}catch(n){return this.logger.error("Error in room joining process",{error:n}),this.context.getValue("peerSessionStore").emit(R.ROOM_NODE_FAILED),{roomJoined:!1}}}async initializeConnection(s,t,e=!1,r={}){return a(this,ys)?a(this,ys):(f(this,ys,(async()=>{try{await U(this,xc,kp).call(this,s,t,e,r)}catch(i){throw f(this,ys,null),i}})()),a(this,ys))}getConsumers(){return a(this,j).consumers}getProducers(){return a(this,j).producers}async leaveRoom(){a(this,j).stopAllTransports(),f(this,En,!1),a(this,hi,no).mediaJoinAttempted=!1;const s={closeRoom:!1};a(this,Et).sendMessagePromise(a(this,Mt).leaveRoom,DR.toBinary(s)).then(e=>{var r;(r=Ek.fromBinary(e.payload))!=null&&r.closed&&this.logger.warn("Weird state on peer closed and should not happen")}).catch(e=>{this.logger.error("error on sending leave room request",{error:e})}),this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct()}async activatePeers(s){return this.createConsumers(s)}async createConsumers(s){return s.length===0?Promise.resolve():a(this,j).createConsumers(s)}async closeConsumers(s){if(!s.length)return;const t=s.reduce((e,r)=>{const i=a(this,j).producerIdToConsumerIdMap.get(r.producerId);return i?(e.push(i),e):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),e)},[]);await a(this,j).closeConsumers(t)}async _shareWebcam(s,t){var h,g;const e=t==="video/VP9"?fe.WEBCAM:fe.WEBCAM_BACKUP,r=U(this,ot,Nt).call(this,e);if(r){const v=await r;if(a(this,j).producers.has(v)){const E=a(this,j).producers.get(v);if(!E.closed)return await E.replaceTrack({track:s}),await this.resumeWebcam(e),s;await this.disableWebcam(t)}return this._shareWebcam(s,t)}const i=[t].concat(Yt.filter(v=>v!==t)),n=U(this,yu,ZS).call(this,s,i),o=Un(this.context,"disableSimulcast"),c=(g=(h=this.context)==null?void 0:h.getValue("overrides"))==null?void 0:g.simulcastConfig;!(o||c&&c.disable)&&this.context.getValue("flagsmith").hasFeature(Z.ENABLE_CF_SIMULCAST)?(this.logger.info("Simulcast enabled for SFU: CF"),n.encodings=PD(this.context,s)):this.logger.info("Simulcast disabled for webcam producer, SFU: CF"),this.context.getValue("flagsmith").hasFeature(Z.TRACK_HINT)&&(n.track.contentHint=this.context.getValue("flagsmith").getValue(Z.TRACK_HINT));const l=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,Ot).delete(e)},u=a(this,j).createProducer(n,l);return U(this,_n,dd).call(this,e,u.then(v=>v.id)),u.then(v=>v.track)}async shareWebcam(s){var r;if(s===void 0)return null;const t=(r=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:r.toString();if(t)return this.logger.debug(`Calling _shareWebcam with forced video codec: ${t}`),this._shareWebcam(s,t);const e=Yt.filter(i=>{var n,o;return((o=(n=a(this,so).sender)==null?void 0:n.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===i))>=0&&a(this,Pn).get(i).size>0});return e.length===0&&e.push(Yt[0]),await Promise.all(e.map(i=>(this.logger.debug(`Calling _shareWebcam with video codec: ${i}`),this._shareWebcam(s,i)))),s}async shareScreen(s){const{video:t,audio:e}=s;if(t===void 0)return;const r={track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ye.isElectron()},stopTracks:!1},i=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Ot).delete(fe.SCREENSHARE_VIDEO),a(this,Ot).delete(fe.SCREENSHARE_AUDIO)},n=a(this,j).createProducer(r,i);U(this,_n,dd).call(this,fe.SCREENSHARE_VIDEO,n.then(c=>c.id));let o;if(e){const c={track:e,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ye.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},d=()=>{};o=a(this,j).createProducer(c,d),U(this,_n,dd).call(this,fe.SCREENSHARE_AUDIO,o.then(l=>l.id))}await Promise.all([n,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()}async shareMic(s){try{if(s===void 0)throw new Ut("track undefined");const t=U(this,ot,Nt).call(this,fe.MIC);if(t){const n=await t;if(a(this,j).producers.has(n)){const o=a(this,j).producers.get(n);if(!o.closed){await o.replaceTrack({track:s}),await this.resumeMic(),a(this,Ht)&&(a(this,Ht).audioTrack=s,a(this,Ht).producerId=n,a(this,Ht).start());return}await a(this,j).closeProducer(n,{stopTrack:!1})}await this.shareMic(s);return}const e=U(this,Su,XS).call(this,s),r=()=>{a(this,Ot).delete(fe.MIC)},i=a(this,j).createProducer(e,r);U(this,_n,dd).call(this,fe.MIC,i.then(n=>n.id)),await i.then(n=>{a(this,Ht)&&(a(this,Ht).audioTrack=n.track,a(this,Ht).producerId=n.id,a(this,Ht).start())})}catch(t){throw new C(t)}}async pauseMic(){var r;const s=await U(this,ot,Nt).call(this,fe.MIC),t=a(this,j).producers.get(s);if(!t){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}t.pause(),(r=a(this,Ht))==null||r.stop();const e={producerId:t.id,pause:!0};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(e))}async pauseWebcam(){const s=await U(this,ot,Nt).call(this,fe.WEBCAM),t=await U(this,ot,Nt).call(this,fe.WEBCAM_BACKUP),e=a(this,j).producers.get(s),r=a(this,j).producers.get(t);if(!e&&!r){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const i=n=>{const o={producerId:n.id,pause:!0};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(o))};e&&(e.pause(),i(e)),r&&(r.pause(),i(r))}async resumeMic(){const s=await U(this,ot,Nt).call(this,fe.MIC),t=a(this,j).producers.get(s);if(!t){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&this.context.getValue("peerSessionStore").emit(R.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(e))}async resumeWebcam(s=fe.WEBCAM){const t=await U(this,ot,Nt).call(this,s),e=a(this,j).producers.get(t);if(!e){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!e.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(R.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(r))}async disableWebcam(s){const t=s==="video/VP9"?fe.WEBCAM:fe.WEBCAM_BACKUP,e=await U(this,ot,Nt).call(this,t);U(this,vu,QS).call(this,t),e&&await a(this,j).closeProducer(e)}async disableMic(){var t;const s=await U(this,ot,Nt).call(this,fe.MIC);s&&await a(this,j).closeProducer(s),(t=a(this,Ht))==null||t.stop(),a(this,Ot).delete(fe.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=await U(this,ot,Nt).call(this,fe.SCREENSHARE_VIDEO),t=await U(this,ot,Nt).call(this,fe.SCREENSHARE_AUDIO);s&&await a(this,j).closeProducer(s),t&&await a(this,j).closeProducer(t),a(this,Nr).clear(),a(this,Ot).delete(fe.SCREENSHARE_VIDEO),a(this,Ot).delete(fe.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(s,t){if(s){const e=await U(this,ot,Nt).call(this,fe.WEBCAM),r=await U(this,ot,Nt).call(this,fe.WEBCAM_BACKUP);await a(this,j).closeProducer(e,{stopTrack:!1}),await a(this,j).closeProducer(r,{stopTrack:!1}),this.shareWebcam(s)}if(t){const e=await U(this,ot,Nt).call(this,fe.SCREENSHARE_VIDEO);await a(this,j).closeProducer(e,{stopTrack:!1}),this.shareScreen({video:t})}}async changeDisplayName(s,t){const e={displayName:s,participantId:t!=null?t:this.peerId};if(!await a(this,j).socketHandler.changeDisplayName(e))throw new Error("failed to change display name!")}kick(s){const t={peerIds:[s]};a(this,j).socketHandler.kickPeer(t)}kickAll(){a(this,j).socketHandler.kickAll()}async muteAll(s){if(!await a(this,j).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,j).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(s){if(!await a(this,j).socketHandler.hostControlForPeer(s,"audio"))throw new Error("failed to mute given participant")}async disableVideo(s){if(!await a(this,j).socketHandler.hostControlForPeer(s,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(s){const t={participantId:s!=null?s:""};try{await a(this,Et).sendMessagePromise(a(this,Mt).globalPinPeer,JR.toBinary(t))}catch(e){this.logger.error("Error in pinning peer:",{error:e})}}validateScreenShare(s){return this.peerId===s.peerId&&a(this,j).producers.get(s.producerId)&&a(this,Nr).add(s.consumerPeerId),a(this,Nr).size}async switchConsumersToLayer(s,t){const e=s.map(r=>this.getConsumers().get(r));a(this,j).switchConsumersToLayer(e,t)}async handleSocketEvents(){a(this,Et).on(a(this,Mt).peerProducerCreateBroadcast,({payload:s})=>{var t,e;if(this.mediaJoined)try{const{participantId:r,producerState:i}=Qk.fromBinary(s);if(r===this.peerId)return;if(i!=null&&i.mimeType||(i.mimeType=i.kind===Ws.AUDIO?"audio/opus":"video/VP8"),i.kind===Ws.VIDEO&&!i.screenShare&&((e=(t=a(this,so).receiver)==null?void 0:t.video)==null?void 0:e.codecs.findIndex(n=>n.mimeType===Yt[0]))>=0&&a(this,wn).get(Yt[0]).has(r)&&i.mimeType!==Yt[0]){this.logger.warn(`Ignoring producer: ${i.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${i}`),this.context.getValue("peerSessionStore").emit(R.NEW_PRODUCER,{peerId:r,producer:{...i,kind:i.kind===Ws.AUDIO?"audio":"video",producingPeerId:r}})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),a(this,Et).on(a(this,Mt).peerProducerToggleBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,initiatorParticipantId:e,producerState:{kind:r,pause:i,producerId:n,screenShare:o}}=lf.fromBinary(s);if(o)return;const c=r===Ws.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${t}, producerId: ${n}, kind:${c}, paused:${i} payload: ${JSON.stringify(lf.fromBinary(s))}`),t===this.peerId&&e!==this.peerId&&i&&this.context.getValue("peerSessionStore").emit(c==="audio"?R.MUTE_SELF:R.MUTE_SELF_VIDEO),t===this.peerId)return;this.context.getValue("peerSessionStore").emit(R.PRODUCER_TOGGLE,{peerId:t,producerId:n,paused:i,kind:c}),Array.from(this.getConsumers().values()).filter(l=>l.producerId===n).forEach(l=>{l.kind==="video"&&i||l.paused!==i&&(this.logger.debug(`consumer state mismatched for ${l.id}. updating consumer pause state ${l.paused} to ${i}`),i?(l.pause(),this.context.getValue("peerSessionStore").emit(R.CONSUMER_PAUSED,{id:l.id})):(l.resume(),this.context.getValue("peerSessionStore").emit(R.CONSUMER_RESUMED,{id:l.id})))})}catch(t){this.logger.error("error in producer toggle broadcast handler",{error:t})}}),a(this,Et).on(a(this,Mt).peerLeaveBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t}=hh.fromBinary(s);if(t===this.peerId)return;this.logger.info(`peer left broadcast:${t}`),a(this,Nr).delete(t),a(this,j).consumers.forEach(e=>{e.peerId===t&&e.close()}),this.context.getValue("peerSessionStore").emit(R.PEER_CLOSED,{id:t})}catch(t){this.logger.error("error in peer left broadcast",{error:t})}}),a(this,Et).on(a(this,Mt).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=eI.fromBinary(s);if(t===this.peerId)return;this.logger.info(`producer closed broadcast:${t}`),this.context.getValue("peerSessionStore").emit(R.PRODUCER_CLOSED,{peerId:t,producerId:e});const r=a(this,j).producerIdToConsumerIdMap.get(e);if(!r){this.logger.warn(`no consumer found for producer:${e}`);return}this.logger.info(`closing consumer ${r}, producer id: ${e}`),a(this,j).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),a(this,j).producerIdToConsumerIdMap.delete(e),this.context.getValue("peerSessionStore").emit(R.CONSUMER_CLOSED,{id:r})}).catch(i=>{this.logger.error("error closing consumer",{error:i})})}catch(t){this.logger.error("error on producer close broadcast",{error:t})}}),a(this,Et).on(a(this,Mt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,Tn)&&!a(this,En)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(R.ROOM_NODE_DISCONNECTED),a(this,Vc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(s=>{s.forEach((t,e)=>{const r=a(this,j).consumers.get(e);r&&this.context.getValue("peerSessionStore").emit(R.CONSUMER_SCORE_UPDATE,{id:e,kind:r.kind,peerId:r.peerId,score:t.score,scoreStats:t})})}),this.context.getValue("callstats").onProducerScore(s=>{s.forEach((t,e)=>{const r=Array.from(a(this,j).producers.values()).find(i=>i.id===e);r&&this.context.getValue("peerSessionStore").emit(R.PRODUCER_SCORE_UPDATE,{id:e,kind:r.kind,appData:r.appData,score:t.score,scoreStats:t})})})}handlePeerCapabilities(s,t){var e,r,i,n;for(let o=0;o<=Yt.length;o+=1){const c=Yt[o];if(((r=(e=t==null?void 0:t.receiver)==null?void 0:e.video)==null?void 0:r.codecs.findIndex(d=>d.mimeType===c))>=0||o===Yt.length-1){a(this,Pn).get(c).add(s);break}}for(let o=0;o<=Yt.length;o+=1){const c=Yt[o];if(((n=(i=t==null?void 0:t.sender)==null?void 0:i.video)==null?void 0:n.codecs.findIndex(d=>d.mimeType===c))>=0||o===Yt.length-1){a(this,wn).get(c).add(s);break}}}handlePeerLeaving(s){this.context.getValue("flagsmith").hasFeature(Z.FORCE_VIDEO_CODEC)||(a(this,wn).forEach(t=>t.delete(s)),a(this,Pn).forEach((t,e)=>{t.delete(s),!(t.size!==0||e===Yt[0])&&this.disableWebcam(e)}))}},Dc=new WeakMap,Nc=new WeakMap,Et=new WeakMap,j=new WeakMap,so=new WeakMap,Mt=new WeakMap,Tn=new WeakMap,En=new WeakMap,bn=new WeakMap,Vc=new WeakMap,ys=new WeakMap,Nr=new WeakMap,Lc=new WeakMap,wn=new WeakMap,Pn=new WeakMap,Ot=new WeakMap,Ht=new WeakMap,hi=new WeakSet,no=function(){return this.context.getValue("connectionHandler")},lu=new WeakSet,jS=async function(s,t,e,r){f(this,Nc,s);try{return a(this,ys)?await a(this,ys):await U(this,xc,kp).call(this,s,t,e,r),U(this,hu,WS).call(this,t),{roomJoined:await U(this,uu,GS).call(this)}}catch(i){return this.logger.error("Failed to complete room join",{error:i}),{roomJoined:!1}}finally{f(this,ys,null)}},uu=new WeakSet,GS=async function(){try{this.mediaJoined=!0;const{roomState:s}=await a(this,j).socketHandler.notifySelfJoinComplete();return f(this,Dc,s.roomUuid),f(this,En,!0),f(this,Tn,!1),!0}catch(s){return this.logger.error("Error completing room join",{error:s}),this.mediaJoined=!1,!1}},hu=new WeakSet,WS=function(s){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:{...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(e)}catch(t){this.logger.error("Error reporting room joined analytics",{error:t})}},0)},xc=new WeakSet,kp=async function(s,t,e,r){var i,n;try{(n=a(this,Lc))!=null||f(this,Lc,U(i=bv,pu,JS).call(i));const o=U(this,gu,KS).call(this);await U(this,mu,zS).call(this,s,t,e,o),await a(this,j).setupTransports({send:!0,recv:!0}),await U(this,fu,YS).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},pu=new WeakSet,JS=function(){const{ipInfo:s}=pt();if(!(s!=null&&s.loc))return;const[t,e]=s.loc.split(",").map(parseFloat);return{latitude:t,longitude:e}},gu=new WeakSet,KS=function(){var e;const s=(e=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:e.toString(),t=T1(s);return f(this,so,t),t},mu=new WeakSet,zS=async function(s,t,e,r){await mv(async(i,n)=>{if(!a(this,Et).isConnected){n(new Error("Socket is not connected"));return}i>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${i}`});try{await a(this,j).socketHandler.joinRoom(t,s,r,e,a(this,Lc))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}},{delayTime:1e3,strategy:"exponential",maxRetryCount:1/0})},fu=new WeakSet,YS=async function(s){if(!(!this.context.getValue("flagsmith").hasFeature(Z.PRECREATE_PRODUCERS)||!s))try{const e=[];if(s.canProduceVideo===H.Allowed&&e.push(this.shareWebcam(j1(!1))),s.canProduceAudio===H.Allowed){const r=q1(!1);r&&e.push(this.shareMic(r))}e.length>0&&await Promise.all(e)}catch(e){this.logger.warn("Failed to precreate producers",{error:e})}},ot=new WeakSet,Nt=function(s){return a(this,Ot).get(s)},_n=new WeakSet,dd=function(s,t){return a(this,Ot).set(s,t)},vu=new WeakSet,QS=function(s){return a(this,Ot).delete(s)},Su=new WeakSet,XS=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},yu=new WeakSet,ZS=function(s,t){return{track:s,codecOptions:t?t.map(e=>({name:e.split("/")[1]})):[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},m(up,pu),up);let re=bv;ce([T.trace("MediaNodeClient.reset",{country:T.location.country})],re.prototype,"reset",1),ce([T.trace("MediaNodeClient.joinRoom")],re.prototype,"joinRoom",1),ce([T.trace("MediaNodeClient.leaveRoom")],re.prototype,"leaveRoom",1),ce([T.trace("MediaNodeClient.activatePeers")],re.prototype,"activatePeers",1),ce([T.trace("MediaNodeClient.createConsumers")],re.prototype,"createConsumers",1),ce([T.trace("MediaNodeClient.closeConsumers")],re.prototype,"closeConsumers",1),ce([T.trace("MediaNodeClient._shareWebcam")],re.prototype,"_shareWebcam",1),ce([T.trace("MediaNodeClient.shareWebcam")],re.prototype,"shareWebcam",1),ce([T.trace("MediaNodeClient.shareScreen")],re.prototype,"shareScreen",1),ce([T.trace("MediaNodeClient.shareMic")],re.prototype,"shareMic",1),ce([T.trace("MediaNodeClient.pauseMic")],re.prototype,"pauseMic",1),ce([T.trace("MediaNodeClient.pauseWebcam")],re.prototype,"pauseWebcam",1),ce([T.trace("MediaNodeClient.resumeMic")],re.prototype,"resumeMic",1),ce([T.trace("MediaNodeClient.resumeWebcam")],re.prototype,"resumeWebcam",1),ce([T.trace("MediaNodeClient.disableWebcam")],re.prototype,"disableWebcam",1),ce([T.trace("MediaNodeClient.disableMic")],re.prototype,"disableMic",1),ce([T.trace("MediaNodeClient.disableScreenShare")],re.prototype,"disableScreenShare",1),ce([T.trace("MediaNodeClient.muteSelf")],re.prototype,"muteSelf",1),ce([T.trace("MediaNodeClient.resetVideoProducers")],re.prototype,"resetVideoProducers",1),ce([T.trace("MediaNodeClient.changeDisplayName")],re.prototype,"changeDisplayName",1),ce([T.trace("MediaNodeClient.kickPeer")],re.prototype,"kick",1),ce([T.trace("MediaNodeClient.kickAllPeers")],re.prototype,"kickAll",1),ce([T.trace("MediaNodeClient.muteAll")],re.prototype,"muteAll",1),ce([T.trace("MediaNodeClient.muteAllVideo")],re.prototype,"muteAllVideo",1),ce([T.trace("MediaNodeClient.disableAudio")],re.prototype,"disableAudio",1),ce([T.trace("MediaNodeClient.disableVideo")],re.prototype,"disableVideo",1),ce([T.trace("MediaNodeClient.pinPeer")],re.prototype,"pinPeer",1),ce([T.trace("MediaNodeClient.validateScreenShare")],re.prototype,"validateScreenShare",1);function wv(s,t){const e=s.getValue("roomNodeClient");if(e){if(e)return e;throw new Error("Room node client already set up.")}const r=new re(s,t);return s.setValue("roomNodeClient",r),r}function Pv(s){const t=s.getValue("roomNodeClient");try{t==null||t.leaveRoom()}catch(e){s.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}s.setValue("roomNodeClient",void 0)}var J1=Object.defineProperty,K1=Object.getOwnPropertyDescriptor,Fi=(s,t,e,r)=>{for(var i=r>1?void 0:r?K1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&J1(t,e,i),i};const _v=(pS=class{constructor(s,t,e,r){m(this,Dt);p(this,"self");p(this,"authToken");m(this,Cn,void 0);p(this,"viewType");m(this,Us,void 0);m(this,ee,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,ee,s),this.viewType=r,this.authToken=n,f(this,Cn,i),f(this,Us,e),t.config.viewType!==Vt.Chat&&this.setupEvents()}get peerId(){return a(this,ee).getValue("peerId")}get telemetry(){return a(this,ee).getValue("telemetry")}get logger(){return a(this,ee).getValue("logger")}get mediaJoined(){return a(this,ee).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=pt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await tt.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");if(navigator.product!=="ReactNative"){const u=!s.getValue("flagsmith").hasFeature(Z.PRECALL_BANDWIDTH_TEST);setTimeout(async()=>{const h=await d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(h)}),s.getValue("callstats").devices("AUDIO",h==null?void 0:h.filter(g=>g.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",h==null?void 0:h.filter(g=>g.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",h==null?void 0:h.filter(g=>g.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:ye.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:Mm(s),skipConnectivityChecks:u}),l.info("Callstats:: initialized")}catch(g){l.error("Callstats:: initialization failed",{error:g})}},0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new _v(s,d,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:n,screenShareTracks:o}=this.self;if(e.canProduceAudio===H.Allowed&&r)try{await a(this,Dt,is).shareMic(s),this.self.audioEnabled||a(this,Dt,is).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===H.Allowed&&i)try{const d=await a(this,Dt,is).shareWebcam(t);d&&d.id!==t.id&&a(this,ee).getValue("flagsmith").hasFeature(Z.EXP_RESHARE)&&await a(this,Dt,is).shareWebcam(d),this.self.videoEnabled||a(this,Dt,is).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===H.Allowed&&n)try{await((c=a(this,Dt,is))==null?void 0:c.shareScreen({video:o.video,audio:o.audio}))}catch(d){this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){a(this,ee).getValue("callstats").callEnded(),a(this,Dt,is).reset(),s&&await this.joinRoom(s)}setupEvents(){a(this,ee).getValue("peerSessionStore").on(R.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,ee).getValue("peerSessionStore").on(R.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,ee).getValue("peerSessionStore").on(R.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,ee).getValue("peerSessionStore").on(R.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,ee).getValue("peerSessionStore").on(R.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,ee).getValue("peerSessionStore").on(R.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&a(this,ee).getValue("flagsmith").hasFeature(Z.REFRESH_ID_ON_DISCONNECTION)&&(t=vi()),a(this,Cn).updateURL(t),a(this,ee).getValue("telemetry").resetPeerId(t),pt().setHeader("tracing-id",t),nr.remapContext(t,a(this,ee)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,ee).getValue("peerSessionStore").on(R.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Us).on(F.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Us).on(Yd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,ee).getValue("peerSessionStore").emit(R.UPDATE_PERMISSIONS,t.patch)})}),a(this,Us).on(F.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Us).on(F.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Us).on(F.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,ee).getValue("peerSessionStore").onAsync(R.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,ee).getValue("peerSessionStore").on(R.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var n;const i=(n=e==null?void 0:e.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),a(this,ee).getValue("peerSessionStore").on(R.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,ee).getValue("callstats").audioOff())}),a(this,ee).getValue("peerSessionStore").on(R.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,ee).getValue("callstats").videoOff())}),a(this,ee).getValue("peerSessionStore").onAsync(R.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,ee).getValue("peerSessionStore").on(R.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await a(this,Us).joinRoom(this.self);a(this,Us).socket.flush();const e=Dh(t.stageType);if(a(this,ee).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}await this.joinMediaRoom(s),a(this,ee).notify("stageStatus")}catch(t){throw this.logger.error("Error in joinRoom",{error:t}),t}}async leaveRoom(s="left"){var t,e;if(this.logger.info(`Leaving room with state: ${s}`),(t=a(this,ee).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),a(this,ee).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,ee).notify("stageStatus");try{(e=a(this,Cn))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}Pv(a(this,ee)),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var n,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,ee).getAllValues();try{if(e===Vt.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}wv(a(this,ee),{socket:a(this,Cn),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u}=(o=await((n=a(this,Dt,is))==null?void 0:n.joinRoom(this.self.name,r,s,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)return;i==="ON_STAGE"&&await this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:c}),new C("Error: could not join media room","0002")}}async leaveMediaRoom(s){const t=a(this,ee).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===Vt.Webinar)&&a(this,Dt,is)&&(a(this,Dt,is).mediaJoined&&s!=="disconnected"&&await a(this,Dt,is).leaveRoom(),!(s==="stageLeft"&&t===Vt.Livestream)&&(a(this,Dt,is).mediaJoined=!1))}async cleanupSelf(){await this.self.disableAudio(),await this.self.disableVideo(),await this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()}},Cn=new WeakMap,Us=new WeakMap,ee=new WeakMap,Dt=new WeakSet,is=function(){return a(this,ee).getValue("roomNodeClient")},pS);let jr=_v;Fi([T.trace("SelfController.resetSelf")],jr.prototype,"resetSelf",1),Fi([T.trace("SelfController.setupEvents")],jr.prototype,"setupEvents",1),Fi([T.trace("SelfController.joinRoom")],jr.prototype,"joinRoom",1),Fi([T.trace("SelfController.leaveRoom")],jr.prototype,"leaveRoom",1),Fi([T.trace("SelfController.joinMediaRoom")],jr.prototype,"joinMediaRoom",1),Fi([T.trace("SelfController.leaveMediaRoom")],jr.prototype,"leaveMediaRoom",1),Fi([T.trace("SelfController.init")],jr,"init",1);class z1{constructor(t){m(this,Uc,void 0);f(this,Uc,t)}on(t,e){let r;t===F.roomPeerCount?r=pf.fromBinary.bind(pf):r=Af.fromBinary.bind(Af),a(this,Uc).on(t,({payload:i})=>{if(t===F.roomPeerCount&&!i)return;const n=r(i);e(n)})}}Uc=new WeakMap;class Y1{constructor(t,e){m(this,Fc,void 0);m(this,$c,void 0);f(this,Fc,e),f(this,$c,t)}get logger(){return a(this,$c).getValue("logger")}on(t,e){let r,i;switch(t){case F.transcript:{r=ph.fromBinary.bind(ph),i=ph.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Fc).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}Fc=new WeakMap,$c=new WeakMap;var Q1=Object.defineProperty,X1=Object.getOwnPropertyDescriptor,ep=(s,t,e,r)=>{for(var i=r>1?void 0:r?X1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&Q1(t,e,i),i};class ml{constructor(t,e){m(this,Vr,void 0);m(this,ro,void 0);f(this,Vr,e),f(this,ro,t)}get logger(){return a(this,ro).getValue("logger")}get telemetry(){return a(this,ro).getValue("telemetry")}getPolls(){return a(this,Vr).sendMessagePromise(lr.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Vr).sendMessage(lr.createPoll,HM.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Vr).sendMessage(lr.votePoll,jM.toBinary(r))}on(t,e){let r,i;switch(t){case lr.updatePoll:case lr.createPoll:case lr.votePoll:{r=Ch.fromBinary.bind(Ch),i=Ch.create();break}}a(this,Vr).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){a(this,Vr).removeListeners(t)}}Vr=new WeakMap,ro=new WeakMap,ep([T.trace("PollSocketHandler.getPolls")],ml.prototype,"getPolls",1),ep([T.trace("PollSocketHandler.createPoll")],ml.prototype,"createPoll",1),ep([T.trace("PollSocketHandler.votePoll")],ml.prototype,"votePoll",1);var Z1=Object.defineProperty,eN=Object.getOwnPropertyDescriptor,tN=(s,t,e,r)=>{for(var i=r>1?void 0:r?eN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&Z1(t,e,i),i};class Cv{constructor(t,e){p(this,"socket");m(this,ss,void 0);f(this,ss,t),this.socket=e,this.handleSocketEvents(),a(this,ss).setValue("roomSocketHandler",this)}get telemetry(){return a(this,ss).getValue("telemetry")}get logger(){return a(this,ss).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}async joinRoom(t){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(F.joinRoom,II.toBinary(e));try{const{peer:n}=$n.fromBinary((await r).payload);a(this,ss).getValue("connectionHandler").socketJoined=!0,a(this,ss).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_ROOM_JOINED,{peer:n});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return a(this,ss).getValue("peerSessionStore").emit(R.ROOM_STATE,d),a(this,ss).getValue("peerSessionStore").emit(R.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),new C("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,n)}}async getAllAddedParticipants(){try{return pA.fromBinary((await this.socket.sendMessagePromise(F.getAllAddedParticipants)).payload).participants.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}async getRoomPeers(t,e,r){let i;try{const n={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise(F.getRoomPeersInfo,yI.toBinary(n));i=fh.fromBinary(o.payload)}catch(n){this.logger.error("getRoomPeers::binary_decode_error",{error:n})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise(F.getRoomPeersInfo);t=fh.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getStagePeers(){let t;try{const e=await this.socket.sendMessagePromise(F.getRoomPeersInfo);t=fh.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getPeerInfo(t){let e;try{const r=await this.socket.sendMessagePromise(F.getPeerInfo,ff.toBinary({peerId:t}));e=$n.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=mf.create();try{const e=await this.socket.sendMessagePromise(F.getRoomInfo);t=mf.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=bf.create();try{const e=await this.socket.sendMessagePromise(F.getRoomStageState);t=bf.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t}async broadcastMessage(t,e){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(F.broadcastMessage,bo.toBinary(r))}async broadcastToMeetings(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(F.broadcastToEntity,bo.toBinary(i))}async broadcastToPeers(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(F.broadcastToEntity,bo.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(F.leaveRoom,MI.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(F.kick,Tf.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(F.kickAll,nf.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(F.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(F.acceptWaitingRoomRequests,yA.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(F.denyWaitingRoomRequests,EA.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Yd.updateUserPreset,YA.toBinary(r))}handleSocketEvents(){this.socket.on(F.broadcastMessage,({payload:t})=>{try{const e=bo.fromBinary(t);a(this,ss).getValue("peerSessionStore").emit(R.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on(F.broadcastToEntity,({payload:t})=>{try{const e=bo.fromBinary(t);a(this,ss).getValue("peerSessionStore").emit(R.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case F.joinRoom:case F.leaveRoom:case F.kick:case F.kickAll:{r=$n.fromBinary.bind($n),i=$n.create();break}case F.getWaitingRoomRequests:{r=(n,o)=>n?Ef.fromBinary(n,o):{requests:[]},i=Ef.create();break}case F.recordingPaused:case F.recordingStarted:case F.recordingStopped:{r=Nf.fromBinary.bind(Nf);break}case Yd.updateUserPreset:{r=Pf.fromBinary.bind(Pf);break}case _s.peerJoinedBroadcast:case Br.peerJoinedBroadcast:{r=cf.fromBinary.bind(cf);break}case _s.selfJoinComplete:case Br.selfJoinComplete:{r=uh.fromBinary.bind(uh);break}case _s.globalPeerPinBroadcast:case Br.globalPeerPinBroadcast:{r=uf.fromBinary.bind(uf);break}case _s.selectedPeer:case Br.selectedPeer:{r=lh.fromBinary.bind(lh);break}case _s.selectedPeerDiff:case Br.selectedPeerDiff:{r=of.fromBinary.bind(of);break}case _s.leaveRoom:case Br.leaveRoom:{r=hh.fromBinary.bind(hh);break}}this.socket.on(t,({payload:n})=>{let o=i;if(!r)return e(void 0);try{o=r(n)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}async getUserPermissions(t){const e={userIds:[t]};try{const r=await this.socket.sendMessagePromise(Yd.getUserPresets,qA.toBinary(e)),i=JA.fromBinary(r.payload).peerPresets[0],n=new TextDecoder().decode(i.preset),o=JSON.parse(n).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}}}ss=new WeakMap,tN([T.trace("RoomSocketHandler.joinRoom")],Cv.prototype,"joinRoom",1);class sN{constructor(t){m(this,qt,void 0);f(this,qt,t)}async getStageRequests(){const{payload:t}=await a(this,qt).sendMessagePromise(F.getStageRequests);return t?_h.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,qt).sendMessage(F.requestStageAccess)}cancelRequestAccess(){a(this,qt).sendMessage(F.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,qt).sendMessage(F.grantStageAccess,OM.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,qt).sendMessage(F.denyStageAccess,NM.toBinary(e))}joinStage(){return a(this,qt).sendMessagePromise(F.joinStage,void 0,void 0,F.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,qt).sendMessagePromise(F.leaveStage,Of.toBinary(e),void 0,F.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,qt).sendMessagePromise(F.leaveStage,Of.toBinary(e))}on(t,e){let r;switch(t){case F.grantStageAccess:case F.denyStageAccess:{r=void 0;break}case F.getStagePeers:{r=Mf.fromBinary.bind(Mf);break}case F.getStageRequests:case F.requestStageAccess:case F.cancelStageRequest:{r=_h.fromBinary.bind(_h);break}case F.peerStageStatusUpdate:{r=hf.fromBinary.bind(hf);break}}a(this,qt).on(t,({payload:i,id:n})=>{if(!i||!r)return e(void 0,n);const o=r(i);return e(o,n)})}async getPeerInfo(t){const e=await a(this,qt).sendMessagePromise(F.getPeerInfo,ff.toBinary({peerId:t}));return $n.fromBinary(e.payload)}}qt=new WeakMap;class rN{constructor(t,e){m(this,Qe,void 0);m(this,Bc,void 0);f(this,Qe,e),f(this,Bc,t)}get logger(){return a(this,Bc).getValue("logger")}addPlugin(t,e){a(this,Qe).sendMessage(G.addPlugin,z0.toBinary({pluginId:t,staggered:e}))}removePlugin(t){a(this,Qe).sendMessage(G.removePlugin,Q0.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await a(this,Qe).sendMessagePromise(G.getPlugins);return t?TM.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};a(this,Qe).sendMessage(G.customPluginEventToRoom,oM.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const n={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,Qe).sendMessage(G.customPluginEventToPeers,dM.toBinary(n),i)}enablePluginForRoom(t,e){a(this,Qe).sendMessage(G.enablePluginForRoom,Z0.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){a(this,Qe).sendMessage(G.enablePluginForPeers,rM.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){a(this,Qe).sendMessage(G.disablePluginForRoom,tM.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){a(this,Qe).sendMessage(G.disablePluginForPeers,nM.toBinary({pluginId:t,peerIds:e}),r)}storeInsertKeys(t,e,r,i){const n={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,Qe).sendMessage(G.storeInsertKeys,Cf.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,Qe).sendMessage(G.storeGetKeys,pM.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,Qe).sendMessage(G.storeDeleteKeys,mM.toBinary(n),i)}storeDelete(t,e,r){a(this,Qe).sendMessage(G.storeDelete,vM.toBinary({pluginId:t,storeName:e}),r)}getPluginDataOld(t,e){this.logger.info("getPluginDataOld",{plugin:{id:t,storeName:e}})}storePluginDataOld(t,e,r){const i={pluginId:t,storeName:e,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};a(this,Qe).sendMessage(G.storeInsertKeys,Cf.toBinary(i))}on(t,e){let r;switch(t){case G.addPlugin:case G.enablePluginForPeers:case G.enablePluginForRoom:{r=Ph.fromBinary.bind(Ph);break}case G.removePlugin:case G.disablePluginForPeers:case G.disablePluginForRoom:{r=Rf.fromBinary.bind(Rf);break}case G.customPluginEventToPeers:case G.customPluginEventToRoom:{r=If.fromBinary.bind(If);break}case G.storeInsertKeys:case G.storeGetKeys:case G.storeDeleteKeys:case G.storeDelete:{r=kf.fromBinary.bind(kf);break}}a(this,Qe).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}Qe=new WeakMap,Bc=new WeakMap;var iN=Object.defineProperty,nN=(s,t,e)=>t in s?iN(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,aN=(s,t,e)=>(nN(s,typeof t!="symbol"?t+"":t,e),e),tp=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},O=(s,t,e)=>(tp(s,t,"read from private field"),e?e.call(s):t.get(s)),Ee=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},ie=(s,t,e,r)=>(tp(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),_e=(s,t,e)=>(tp(s,t,"access private method"),e),fl={},oN={get exports(){return fl},set exports(s){fl=s}},zn=typeof Reflect=="object"?Reflect:null,Rv=zn&&typeof zn.apply=="function"?zn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},vl;zn&&typeof zn.ownKeys=="function"?vl=zn.ownKeys:Object.getOwnPropertySymbols?vl=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:vl=function(s){return Object.getOwnPropertyNames(s)};function cN(s){console&&console.warn&&console.warn(s)}var kv=Number.isNaN||function(s){return s!==s};function de(){de.init.call(this)}oN.exports=de,fl.once=hN,de.EventEmitter=de,de.prototype._events=void 0,de.prototype._eventsCount=0,de.prototype._maxListeners=void 0;var Iv=10;function Sl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(de,"defaultMaxListeners",{enumerable:!0,get:function(){return Iv},set:function(s){if(typeof s!="number"||s<0||kv(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Iv=s}}),de.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},de.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||kv(s))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+s+".");return this._maxListeners=s,this};function Av(s){return s._maxListeners===void 0?de.defaultMaxListeners:s._maxListeners}de.prototype.getMaxListeners=function(){return Av(this)},de.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var n;if(t.length>0&&(n=t[0]),n instanceof Error)throw n;var o=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw o.context=n,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")Rv(c,this,t);else for(var d=c.length,l=Vv(c,d),e=0;e<d;++e)Rv(l[e],this,t);return!0};function Mv(s,t,e,r){var i,n,o;if(Sl(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=Av(s),i>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=s,c.type=t,c.count=o.length,cN(c)}return s}de.prototype.addListener=function(s,t){return Mv(this,s,t,!1)},de.prototype.on=de.prototype.addListener,de.prototype.prependListener=function(s,t){return Mv(this,s,t,!0)};function dN(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Ov(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=dN.bind(r);return i.listener=e,r.wrapFn=i,i}de.prototype.once=function(s,t){return Sl(t),this.on(s,Ov(this,s,t)),this},de.prototype.prependOnceListener=function(s,t){return Sl(t),this.prependListener(s,Ov(this,s,t)),this},de.prototype.removeListener=function(s,t){var e,r,i,n,o;if(Sl(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,n=e.length-1;n>=0;n--)if(e[n]===t||e[n].listener===t){o=e[n].listener,i=n;break}if(i<0)return this;i===0?e.shift():lN(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this},de.prototype.off=de.prototype.removeListener,de.prototype.removeAllListeners=function(s){var t,e,r;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[s]),this;if(arguments.length===0){var i=Object.keys(e),n;for(r=0;r<i.length;++r)n=i[r],n!=="removeListener"&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=e[s],typeof t=="function")this.removeListener(s,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(s,t[r]);return this};function Dv(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?uN(i):Vv(i,i.length)}de.prototype.listeners=function(s){return Dv(this,s,!0)},de.prototype.rawListeners=function(s){return Dv(this,s,!1)},de.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):Nv.call(s,t)},de.prototype.listenerCount=Nv;function Nv(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}de.prototype.eventNames=function(){return this._eventsCount>0?vl(this._events):[]};function Vv(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function lN(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function uN(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function hN(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,n),r(o)}function n(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}Lv(s,t,n,{once:!0}),t!=="error"&&pN(s,i,{once:!0})})}function pN(s,t,e){typeof s.on=="function"&&Lv(s,"error",t,e)}function Lv(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(n){r.once&&s.removeEventListener(t,i),e(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class gN extends S{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const xv=new gN;class Uv{static encode(t){return xv.toBinary(t)}static decode(t){return xv.fromBinary(new Uint8Array(t))}}function mN(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Gr;class fN{constructor(t={}){aN(this,"opts"),Ee(this,Gr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ie(this,Gr,0)}async wait(){ie(this,Gr,O(this,Gr)+1);const t=mN(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**O(this,Gr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return O(this,Gr)}reset(){ie(this,Gr,0)}}Gr=new WeakMap;const Wr={debug:0,info:1,warn:2,error:3};var $i,Bi;class vN{constructor(t){Ee(this,$i,void 0),Ee(this,Bi,void 0),ie(this,$i,console),ie(this,Bi,t)}debug(...t){Wr[O(this,Bi)]>Wr.debug||O(this,$i).debug("[Sockrates]:",...t)}info(...t){Wr[O(this,Bi)]>Wr.info||O(this,$i).info("[Sockrates]:",...t)}warn(...t){Wr[O(this,Bi)]>Wr.warn||O(this,$i).warn("[Sockrates]:",...t)}error(...t){Wr[O(this,Bi)]>Wr.error||O(this,$i).error("[Sockrates]:",...t)}}$i=new WeakMap,Bi=new WeakMap;var Fv=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(Fv||{});const SN="2",yN="3";var Ne,Yn,Ce,Fe,Jr,st,gr,Kr,Is,Qn,mr,sp,$v,Do,yl,rp,Bv,ip,Hv,Tl,np,ap,qv,No,El,Vo,bl,wl,op,Xn,Lo,xo,Pl;class TN{constructor(t,e){var g,v,E,b,P,w,L,$,N,B;Ee(this,sp),Ee(this,Do),Ee(this,rp),Ee(this,ip),Ee(this,Tl),Ee(this,ap),Ee(this,No),Ee(this,Vo),Ee(this,wl),Ee(this,Xn),Ee(this,xo),Ee(this,Ne,void 0),Ee(this,Yn,void 0),Ee(this,Ce,void 0),Ee(this,Fe,void 0),Ee(this,Jr,void 0),Ee(this,st,void 0),Ee(this,gr,void 0),Ee(this,Kr,void 0),Ee(this,Is,void 0),Ee(this,Qn,void 0),Ee(this,mr,void 0);var r,i,n,o,c,d,l,u,h;ie(this,Yn,t),ie(this,Jr,[]),ie(this,st,new fl),ie(this,gr,!0),ie(this,Is,!1),ie(this,Ce,e!=null?e:{}),(g=(r=O(this,Ce)).autoReconnect)!=null||(r.autoReconnect=!0),(v=(i=O(this,Ce)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(E=(n=O(this,Ce)).pingTimeout)!=null||(n.pingTimeout=3e4),(b=(o=O(this,Ce)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(P=(c=O(this,Ce)).debug)!=null||(c.debug=!0),(w=(d=O(this,Ce)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(L=(l=O(this,Ce)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),($=(u=O(this,Ce)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(N=(h=O(this,Ce)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),ie(this,Kr,{code:void 0,reason:void 0}),ie(this,Fe,(B=O(this,Ce).logger)!=null?B:new vN(O(this,Ce).debug?"debug":"info")),ie(this,mr,new fN)}get readyState(){var t;return(t=O(this,Ne))==null?void 0:t.readyState}get url(){return O(this,Yn)}updateURL(t){ie(this,Yn,t),_e(this,ap,qv).call(this)}get config(){return O(this,Ce)}get sendQueue(){return O(this,Jr)}flush(){if(!O(this,Ce).queueOnDisconnect)return!1;const t=[];return O(this,Jr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ie(this,Jr,t),O(this,Jr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){O(this,Fe).debug("Websocket was already connecting or connected.");return}if(O(this,gr)!==!1)return new Promise((e,r)=>{_e(this,Xn,Lo).call(this),_e(this,xo,Pl).call(this);try{ie(this,Ne,new WebSocket(_e(this,sp,$v).call(this,O(this,Yn)))),O(this,Ne).binaryType="arraybuffer",O(this,Fe).debug("Connecting");const i=setTimeout(()=>{O(this,Fe).debug("Connection timeout. Closing socket"),ie(this,gr,!0),_e(this,xo,Pl).call(this),O(this,Ne).close(3001,"Connection Timeout"),O(this,Ce).autoReconnect&&!O(this,Is)&&(O(this,st).emit("reconnecting"),_e(this,No,El).call(this)),r(new Error("Connection timed out!"))},O(this,Ce).connectionTimeout);O(this,Ne).onopen=()=>{O(this,Fe).debug(`Ready State: ${Fv[O(this,Ne).readyState]}`),i&&clearTimeout(i),_e(this,wl,op).call(this),ie(this,Kr,{code:void 0,reason:void 0}),O(this,st).emit("connected"),O(this,Ce).flushOnReconnect&&this.flush(),e()},O(this,Ne).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),O(this,Fe).debug("Socket closed. Close event:",{event:n}),O(this,Fe).debug(`Connection closed code: ${o}`),O(this,Fe).debug(`Connection closed reason: ${c}`),O(this,Is)||_e(this,Tl,np).call(this,o,c)}catch(o){_e(this,Do,yl).call(this,o)}},O(this,Ne).onerror=n=>{_e(this,Do,yl).call(this,n)},O(this,Ne).onmessage=n=>_e(this,rp,Bv).call(this,n)}catch(i){_e(this,Do,yl).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(O(this,Ce).queueOnDisconnect&&(!O(this,Ne)||O(this,Ne).readyState!==1))return O(this,Fe).debug("Queuing message since socket is not connected!",n),O(this,Jr).push(n),!1;const o=Uv.encode(n);return _e(this,Vo,bl).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return _e(this,Vo,bl).call(this,t)}receive(t,e){return O(this,st).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){O(this,st).on(t,e);return}this.receive(t,e)}removeAllListeners(){O(this,st).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){O(this,st).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){O(this,st).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ie(this,gr,!1),_e(this,Xn,Lo).call(this),this.removeAllListeners(),ie(this,Kr,{code:1e3,reason:"Sockrates disconnect method called"}),O(this,Ne).close(1e3,"Sockrates disconnect method called.")}}Ne=new WeakMap,Yn=new WeakMap,Ce=new WeakMap,Fe=new WeakMap,Jr=new WeakMap,st=new WeakMap,gr=new WeakMap,Kr=new WeakMap,Is=new WeakMap,Qn=new WeakMap,mr=new WeakMap,sp=new WeakSet,$v=function(s){if(s.startsWith("ws://")||s.startsWith("wss://"))return s;if(s.startsWith("https://"))return`wss://${s.substring(8)}`;if(s.startsWith("http://"))return`ws://${s.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},Do=new WeakSet,yl=function(s,t){O(this,Fe).error("Error:",{error:s}),O(this,st).emit("errored",{error:s}),t==null||t(s)},rp=new WeakSet,Bv=function(s){if(_e(this,wl,op).call(this),s.data===SN){O(this,Fe).debug("Received ping from server"),_e(this,Vo,bl).call(this,yN);return}const t=Uv.decode(s.data),{id:e,payload:r}=t;O(this,Fe).debug("Received message",{event:t.event,messageID:e}),O(this,st).emit(t.event.toString(),{id:e,payload:r})},ip=new WeakSet,Hv=function(){return O(this,Ne).readyState===1},Tl=new WeakSet,np=function(s,t){ie(this,Kr,{reason:t,code:s}),O(this,st).emit("disconnected",{code:s,reason:t})},ap=new WeakSet,qv=function(){const{reason:s,code:t}=O(this,Kr);t&&t!==1e3&&O(this,gr)&&O(this,Ce).autoReconnect&&!O(this,Is)&&(O(this,Fe).debug(`Triggering reconnection due to ${s}.`),O(this,st).emit("reconnecting"),_e(this,No,El).call(this))},No=new WeakSet,El=async function(s=!0){if(s&&O(this,Is)){O(this,Fe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(O(this,Is)||O(this,mr).reset(),O(this,Ce).maxReconnectionAttempts!==null&&O(this,mr).getAttempts()>=O(this,Ce).maxReconnectionAttempts){O(this,st).emit("failed"),ie(this,Is,!1);return}ie(this,Is,!0),_e(this,xo,Pl).call(this),_e(this,Xn,Lo).call(this);try{if(await O(this,mr).wait(),O(this,gr)===!1)return;if(O(this,Fe).debug(`Reconnection attempt ${O(this,mr).getAttempts()}`),O(this,st).emit("reconnectAttempt",{attempt:O(this,mr).getAttempts()}),await this.connect(),!_e(this,ip,Hv).call(this))throw Error("Reconnect Failed");ie(this,Is,!1),ie(this,Kr,{code:void 0,reason:void 0}),O(this,st).emit("reconnected")}catch(t){O(this,Fe).debug("Failed to reconnect."),O(this,st).emit("reconnectFailure",{attempt:O(this,mr).getAttempts()}),_e(this,No,El).call(this,!1)}},Vo=new WeakSet,bl=function(s){try{return O(this,Ne).send(s),!0}catch(t){return O(this,Fe).error(t.message),!1}},wl=new WeakSet,op=function(){this.config.disconnectOnPingTimeout&&(O(this,Fe).debug("Resetting ping timeout"),_e(this,Xn,Lo).call(this),ie(this,Qn,setTimeout(()=>{var s;O(this,Fe).debug("Disconnecting the socket due to ping timeout"),ie(this,gr,!0);const t=3002,e="Ping timeout";(s=O(this,Ne))==null||s.close(t,e),_e(this,Tl,np).call(this,t,e)},O(this,Ce).pingTimeout)))},Xn=new WeakSet,Lo=function(){O(this,Qn)&&(clearTimeout(O(this,Qn)),ie(this,Qn,void 0))},xo=new WeakSet,Pl=function(){O(this,Ne)&&(O(this,Ne).onopen=void 0,O(this,Ne).onerror=void 0,O(this,Ne).onmessage=void 0,O(this,Ne).onclose=void 0)};var EN=Object.defineProperty,bN=Object.getOwnPropertyDescriptor,_l=(s,t,e,r)=>{for(var i=r>1?void 0:r?bN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&EN(t,e,i),i};const jv=65535,wN=3e3,Gv=(gS=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,Oe);m(this,Hc);m(this,qc);m(this,pi,void 0);m(this,Me,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");m(this,Ts,void 0);m(this,ct,void 0);var n;if(!t||!e||!r)throw new C("peerId, meetingId, or authToken can not be empty","0404");f(this,Ts,void 0),f(this,ct,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,pi,U(this,Hc,Ip).call(this,t)),f(this,Me,new TN(a(this,pi),{autoReconnect:!0,disconnectOnPingTimeout:(n=i.includes("PING"))!=null?n:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Oe,Ge).socketJoinAttempted}set joinAttempted(s){a(this,Oe,Ge).socketJoinAttempted=s}get telemetry(){return a(this,ct).getValue("telemetry")}get logger(){return a(this,ct).getValue("logger")}get peerId(){return a(this,ct).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,pi,U(this,Hc,Ip).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Me).updateURL(a(this,pi))}static getSocketEdgeDomain(s){return wi({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,pi)}async connect(){a(this,Oe,Ge).socketJoinAttempted=!0,await a(this,Me).connect(),a(this,Oe,Ge).socketJoinAttempted=!0,a(this,Oe,Ge).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){a(this,Oe,Ge).socketJoinAttempted=!1,a(this,Me).disconnect(),a(this,Oe,Ge).socketJoinAttempted=!0,a(this,Oe,Ge).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Me).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,ct).getValue("telemetry").injectContext(r),a(this,Me).send(s,e!=null?e:U(this,qc,Ap).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:i,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:i}){const n=i!=null?i:s;return new Promise((o,c)=>{const d=(E,b)=>{a(this,Me).removeListener(n,E),a(this,Me).removeListener(jv,b),a(this,Me).removeListener(Br.errorResponse,b),a(this,Me).removeListener(_s.errorResponse,b)},l=r!=null?r:U(this,qc,Ap).call(this),u={};a(this,ct).getValue("telemetry").injectContext(u);const g=({id:E,payload:b})=>{if(l===E){let P;try{const w=uk.fromBinary(b);P=new Error(w.errorMessage)}catch(w){P=new Error("failed to parse error message",{cause:w});try{const L=hI.fromBinary(b);P=new Error(L.message)}catch(L){P=new Error("failed to parse error message",{cause:L})}}c(P),d(v,g)}},v=({id:E,payload:b})=>{l===E&&(o({id:E,payload:b}),d(v,g))};a(this,Me).on(n,v),a(this,Me).on(jv,g),a(this,Me).on(Br.errorResponse,g),a(this,Me).on(_s.errorResponse,g),setTimeout(()=>{d(v,g),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Me).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){a(this,Me).on(s,t)}onStateEvent(s,t){a(this,Me).on(s,t)}removeListener(s,t){a(this,Me).removeListener(s,t)}removeListeners(s){a(this,Me).removeListeners(s)}flush(){return a(this,Me).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),a(this,Ts)&&(clearTimeout(a(this,Ts)),f(this,Ts,void 0)),a(this,Oe,Ge).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t},country:T.location.country});const{recv:e,send:r}=(i=a(this,Oe,Ge).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Kn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Kn.CONNECTED?a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Oe,Ge).joinAttempted}):f(this,Ts,setTimeout(()=>{a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Oe,Ge).joinAttempted}),f(this,Ts,void 0)},wN)),a(this,Oe,Ge).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge",{country:T.location.country}),a(this,Oe,Ge).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,Oe,Ge).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,Oe,Ge).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Oe,Ge).mediaJoinAttempted}}),a(this,Ts)&&(clearTimeout(a(this,Ts)),f(this,Ts,void 0)),a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Oe,Ge).mediaJoinAttempted}),a(this,Oe,Ge).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge",{country:T.location.country}),a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_FAILED),a(this,Oe,Ge).updateSocketConnectionState("failed")})}},pi=new WeakMap,Me=new WeakMap,Oe=new WeakSet,Ge=function(){return a(this,ct).getValue("connectionHandler")},Ts=new WeakMap,ct=new WeakMap,Hc=new WeakSet,Ip=function(s){let t=Gv.getSocketEdgeDomain(a(this,ct).getValue("baseURI"));typeof Un(a(this,ct),"socket_server_base")=="string"&&(t=Un(a(this,ct),"socket_server_base"));const e=`wss://${t}`,r=new URL(`${e}/ws`),i=this.peerId,n={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...i!==s&&{oldPeerID:i},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>Gd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(n).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},qc=new WeakSet,Ap=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},gS);let Uo=Gv;_l([T.trace("SocketService.connect")],Uo.prototype,"connect",1),_l([T.trace("SocketService.disconnect")],Uo.prototype,"disconnect",1),_l([T.trace("SocketService.sendMessagePromise")],Uo.prototype,"sendMessagePromise",1),_l([T.trace("SocketService.sendMessagePromiseWithTimeout")],Uo.prototype,"sendMessagePromiseWithTimeout",1);class PN{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=FI.fromBinary(t),r=e.meetings.map(o=>{var c;return{id:o.id,title:o.title,participants:(c=o.participants)!=null?c:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(n=e.parentMeeting.participants)!=null?n:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=uA.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=yf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return Sf.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return tA.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(F.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(F.createConnectedRooms,qI.toBinary({payloads:t}));return Sf.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}async updateConnectedRooms(t){}async disableConnectedRooms(t){const e=t.map(i=>({id:i})),r=await this.socketService.sendMessagePromise(F.deleteConnectedRooms,ZI.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(F.movePeers,oA.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}}}var _N=Object.defineProperty,CN=Object.getOwnPropertyDescriptor,RN=(s,t,e,r)=>{for(var i=r>1?void 0:r?CN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&_N(t,e,i),i};class Wv extends Gt{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);m(this,Fs,void 0);f(this,Fs,e)}get supportsConnectedMeetings(){return a(this,Fs).getValue("self").id!==""}get isActive(){return this.meetings.length!==0}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
21
21
  Please connect with our support team to enable connected meetings.`)}async getConnectedMeetings(){this.validateConnectedMeetingsAction(),this.logger.info("Getting connected meetings dump");const e=await a(this,Fs).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await a(this,Fs).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await a(this,Fs).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)}async deleteMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),await Promise.all(r);const i=await a(this,Fs).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,Fs).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return n.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),n}async moveParticipantsWithCustomPreset(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,Fs).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return n.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),n}moveSuccessHandler(e,r,i){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>n.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>n.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>n.get(d)));return{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}Fs=new WeakMap,RN([Lt({maxInvocations:60,period:60})],Wv.prototype,"getConnectedMeetings",1);var kN=Object.defineProperty,IN=Object.getOwnPropertyDescriptor,cp=(s,t,e,r)=>{for(var i=r>1?void 0:r?IN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&kN(t,e,i),i};const Jv=(mS=class{constructor(s){p(this,"connectedMeetings");m(this,Se,void 0);f(this,Se,s),this.connectedMeetings=new Wv(s)}get telemetry(){return a(this,Se).getValue("telemetry")}get logger(){return a(this,Se).getValue("logger")}static init(s){const t=new Jv(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(F.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(F.transferPeer,this.handleTransferPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(F.movedPeer,this.handleMovedPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(F.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(F.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,n,o,c;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
22
22
  Please connect with our support team to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:a(this,Se).getValue("self").videoEnabled,audio:a(this,Se).getValue("self").audioEnabled};try{a(this,Se).getValue("self").cleanupEvents(),await a(this,Se).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,Se).getValue("meeting"))==null?void 0:i.meta)==null?void 0:n.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await zv.init({...a(this,Se).getValue("options"),cachedUserDetails:null,defaults:{...a(this,Se).getValue("options").defaults,...e,mediaHandler:a(this,Se).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=a(this,Se).getValue("self");r.self.setName(a(this,Se).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return a(this,Se).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s),e=new Map;this.connectedMeetings.meetings.forEach(r=>{e.set(r.id,r)}),t.forEach(r=>{e.has(r.id)?e.get(r.id).title=r.title:e.set(r.id,{...r,participants:[]})}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Se=new WeakMap,mS);let Cl=Jv;cp([T.trace("ConnectedMeetingsController.getConnectedMeetings")],Cl.prototype,"getConnectedMeetings",1),cp([T.trace("ConnectedMeetingsController.setupEvents")],Cl.prototype,"setupEvents",1),cp([T.trace("ConnectedMeetingsController.switchMeeting")],Cl.prototype,"switchMeeting",1);var AN=Object.defineProperty,MN=Object.getOwnPropertyDescriptor,Rl=(s,t,e,r)=>{for(var i=r>1?void 0:r?MN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&AN(t,e,i),i};const Zn=class{constructor(s,t,e){p(this,"apiBase");p(this,"selfController");p(this,"pollController");p(this,"chatController");p(this,"metaController");p(this,"storesManager");p(this,"stageController");p(this,"pluginController");p(this,"internalsController");p(this,"recordingController");p(this,"livestreamController");p(this,"participantController");p(this,"connectedMeetingsController");p(this,"telemetry");p(this,"logger");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController,this.connectedMeetingsController=t.connectedMeetingsController,this.telemetry=e.getValue("telemetry"),this.logger=e.getValue("logger")}static async init(s){var N,B;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(Pv(s),ye.isSupported()===!1)throw new C("Browser not supported","0010",c,!0);const d=wO(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(n),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new nD(s);s.setValue("connectionHandler",l);const u=Zn.createSocketService(s),h=u.connect(),g=d.getUserDetails(),v=d.getPlugins();let E,b="";try{await Zn.setupFlagsmith(s)}catch(Y){c.error("Failed to setup flagsmith",{error:Y})}try{await h}catch(Y){c.error("[Controller]: Failed to connect to socket server:",{error:Y})}try{({meetingTitle:b}=await d.getRoomNodeData()),E=await g,c.info("CF SFU is being used."),s.setValue("presetName",E.preset.name)}catch(Y){c.error("Failed to get room metadata",{error:Y})}const P=Bh.init(E.preset,!s.getValue("modules").theme),w=qh.init(s,P.viewType,E.preset.permissions),L=Zn.setupControllers(u,s,E,v,b,P,w);KO(P)&&((N=Zn.createRoomNodeClient(s,u).initializeConnection(E.participant.name,i,!1,w))==null||N.catch(ae=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:ae})})),T.location.country=(B=d.ipInfo)==null?void 0:B.country;const{controllers:$}=await L;return yC(),new Zn(e,$,s)}static async setupFlagsmith(s){var l;const{peerId:t,baseURI:e,overrides:r,meetingId:i,organizationId:n,logger:o}=s.getAllValues(),c=SC(i),d={entity:sh.PEER,clientId:n,isAnonUser:!n,sdkVersion:s.getValue("sdkVersion"),presetName:s.getValue("presetName"),meetingHash:c,roomName:i,...ye.getDeviceInfo(),isReactNative:navigator.isReactNative};try{const u=(l=r==null?void 0:r.whitelabelled_flags_endpoint)==null||l?wi({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";await s.getValue("flagsmith").identify(`${sh.PEER}_${t}`,JSON.parse(JSON.stringify(d)),!1,5e3,u,o),o.info("flagsmith::allFlags",{flags:JSON.stringify(s.getValue("flagsmith").getAllFlags())},!0)}catch(u){o.error("Failed to fetch flagsmith flags")}}static async setupControllers(s,t,e,r,i,n,o){var k,Ke,mi;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),u=t.getValue("logger"),{viewType:h,mediaConstraints:{audio:g}}=n;t.setValue("viewType",h),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(k=g.enableHighBitrate)!=null?k:!1,enableStereo:(Ke=g.enableStereo)!=null?Ke:!1}},...l}),t.setValue("maxPreferredStreams",ye.isMobile()?n.maxVideoStreams.mobile:n.maxVideoStreams.desktop);let v,E,b,P,w,L,$,N,B;const Y=new Y1(t,s),ae=new PN(s);t.setValue("connectedMeetingsSocketHandler",ae);const bt=new ml(t,s),$s=new os(t,s),Mn=new sN(s),Bs=new Cv(t,s),I=new rN(t,s),y=new z1(s),_=new ki(t,s),x=await jr.init(t,Bs,d,o,n);t.setValue("selfController",x);const we=await qf.init(t,x.self,Bs,Y,i);if(c.participant&&(N=new pr(t,x.self,Bs)),(mi=c.e2ee)!=null&&mi.enabled&&c.e2ee.manager.init(u,t.getValue("peerSessionStore")),c.chat&&(E=await ds.init(t,$s,_,x.self,N.participants)),c.internals&&(w=await Lh.init(t)),c.livestream&&n.viewType===Vt.Livestream&&t.getValue("flagsmith").hasFeature(Z.LIVESTREAM)&&($=new lv(t,x.self,y)),n.viewType!==Vt.Chat){if(c.poll&&(v=await Ff.init(t,x.self,bt)),c.recording&&(L=new Kf(t,x.self,Bs)),c.stage&&(b=new jf(t,Mn,Bs,x.self,N.participants)),c.plugin){if(!N)throw new C("The plugin module cannot be initialized without the `participant` module","0102");const Lr=await r;P=await Po.init(t,Lr,I,$s,E==null?void 0:E.chat,x.self,N.participants,i)}if(c.connectedMeetings&&(B=await Cl.init(t)),c.pip){const Lr=await rh._init(t,x.self);t.setValue("pip",Lr)}}const V={storesManager:new s1(t,I),pollController:v,selfController:x,metaController:we,chatController:E,stageController:b,pluginController:P,recordingController:L,internalsController:w,livestreamController:$,participantController:N,connectedMeetingsController:B};return{theme:n,permissions:o,controllers:V}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return wv(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=["PING"];return new Uo(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Fo=Zn;Rl([T.trace("Controller.init")],Fo,"init",1),Rl([T.trace("setupFlagsmith")],Fo,"setupFlagsmith",1),Rl([T.trace("Controller.createRoomNodeClient")],Fo,"createRoomNodeClient",1),Rl([T.trace("Controller.createSocketService")],Fo,"createSocketService",1);class ON{constructor(){p(this,"battery");p(this,"logger");p(this,"init",async t=>{this.logger=t;try{"getBattery"in navigator&&(this.battery=await navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){t.error("Error getting battery",e)}});p(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});p(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});p(this,"cleanup",()=>{var t,e;"getBattery"in navigator&&((t=this.battery)==null||t.removeEventListener("chargingchange",this.updateChargeInfo),(e=this.battery)==null||e.removeEventListener("levelchange",this.updateLevelInfo))})}}const Kv=new ON;function DN(s,t){s.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c — not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.realtime.cloudflare.com/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:e,orgId:r,participantId:i}=JSON.parse(atob(s.split(".")[1]));if(!e)throw Error(`Received V1 auth token ${s}`);let n=Pi.baseURI.prod;t&&(n=t);const o=`https://${wi({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new C("Invalid auth token","0004")}}class NN{constructor(){m(this,Tu);m(this,gi,new Audio);m(this,Rn,new MediaStream);m(this,kn,new Map);m(this,jc,void 0);a(this,gi).srcObject=a(this,Rn),a(this,gi).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,kn).has(e.id)||(a(this,Rn).addTrack(e),a(this,kn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,gi).setSinkId(t)}removeTrack(t){const e=a(this,kn).get(t);e&&(a(this,Rn).removeTrack(e),a(this,kn).delete(t))}async play(){return a(this,gi).srcObject=a(this,Rn),a(this,gi).play().catch(t=>{U(this,Tu,ey).call(this,t)})}onError(t){f(this,jc,t)}}gi=new WeakMap,Rn=new WeakMap,kn=new WeakMap,jc=new WeakMap,Tu=new WeakSet,ey=function(t){var e;(e=a(this,jc))==null||e.call(this,t)};class VN extends NN{constructor(){super();m(this,In,void 0);f(this,In,new Map)}addParticipantTrack(e,r){a(this,In).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,In).get(e);r&&this.removeTrack(r),a(this,In).delete(e)}}In=new WeakMap;var LN=Object.defineProperty,xN=Object.getOwnPropertyDescriptor,kl=(s,t,e,r)=>{for(var i=r>1?void 0:r?xN(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&LN(t,e,i),i};let zr=(fS=class{constructor(t,e){m(this,Xe,void 0);m(this,An,void 0);f(this,An,t),f(this,Xe,e)}get peerId(){return a(this,An).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:vi(),n=nr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new pv(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var v,E,b,P,w,L,$;ye.init();const{mediaHandler:e}=(v=t.defaults)!=null?v:{},r=(e==null?void 0:e.peerId)||((b=(E=t==null?void 0:t.cachedUserDetails)==null?void 0:E.peerId)!=null?b:vi()),{authToken:i,baseURI:n}=t,{meetingId:o,...c}=DN(i,n);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const d=zr.setupContext(r,t,o,c),l=d.getValue("telemetry"),u=d.getValue("logger");iy(u),Kv.init(u),l.init(d,{roomName:o,userId:c.participantId,organizationId:c.orgId,peerId:r},(w=(P=t.modules)==null?void 0:P.tracing)!=null?w:!0),u.init(d),u.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(L=t.authToken)==null?void 0:L.slice(0,10)}...
23
- ${($=t.authToken)==null?void 0:$.slice(-10)}`}});const h=await Fo.init(d),g=new zr(d,h);return d.setValue("meeting",g),g}static setupContext(t,e,r,i){var d,l;const n=nr.createContext(t,e),o={...cC,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return n.setValue("options",e),n.setValue("peerId",t),n.setValue("modules",o),n.setValue("sdkName","web-core"),n.setValue("meetingId",r),n.setValue("apiBase",i.apiBase),n.setValue("baseURI",i.baseURI),n.setValue("userId",i.participantId),n.setValue("organizationId",i.orgId),n.setValue("authToken",e.authToken),n.setValue("overrides",(d=e.overrides)!=null?d:{}),n.setValue("env",dC({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Rs(e.cachedUserDetails)),n.setValue("sdkVersion","1.2.4-staging.4"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new VN),n}async join(){const{selfController:t}=a(this,Xe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){Kv.cleanup(),a(this,An).getValue("peerSessionStore").reset();const{selfController:e}=a(this,Xe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,Xe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Xe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Xe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Xe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Xe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Xe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Xe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Xe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Xe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Xe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Xe).stageController)==null?void 0:t.stage}get stores(){return a(this,Xe).storesManager}get audio(){return a(this,An).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Xe).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Xe=new WeakMap,An=new WeakMap,fS);kl([ut("0002"),ur.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],zr.prototype,"join",1),kl([ut("0003")],zr.prototype,"leave",1),kl([ut("0001"),ur.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],zr,"init",1),zr=kl([ut("0000")],zr);const zv=zr;return zv}();
23
+ ${($=t.authToken)==null?void 0:$.slice(-10)}`}});const h=await Fo.init(d),g=new zr(d,h);return d.setValue("meeting",g),g}static setupContext(t,e,r,i){var d,l;const n=nr.createContext(t,e),o={...cC,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return n.setValue("options",e),n.setValue("peerId",t),n.setValue("modules",o),n.setValue("sdkName","web-core"),n.setValue("meetingId",r),n.setValue("apiBase",i.apiBase),n.setValue("baseURI",i.baseURI),n.setValue("userId",i.participantId),n.setValue("organizationId",i.orgId),n.setValue("authToken",e.authToken),n.setValue("overrides",(d=e.overrides)!=null?d:{}),n.setValue("env",dC({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Rs(e.cachedUserDetails)),n.setValue("sdkVersion","1.2.4-staging.5"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new VN),n}async join(){const{selfController:t}=a(this,Xe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){Kv.cleanup(),a(this,An).getValue("peerSessionStore").reset();const{selfController:e}=a(this,Xe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,Xe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Xe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Xe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Xe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Xe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Xe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Xe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Xe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Xe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Xe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Xe).stageController)==null?void 0:t.stage}get stores(){return a(this,Xe).storesManager}get audio(){return a(this,An).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Xe).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Xe=new WeakMap,An=new WeakMap,fS);kl([ut("0002"),ur.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],zr.prototype,"join",1),kl([ut("0003")],zr.prototype,"leave",1),kl([ut("0001"),ur.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],zr,"init",1),zr=kl([ut("0000")],zr);const zv=zr;return zv}();