@cloudflare/realtimekit 1.2.5 → 1.2.6-staging.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.js +2 -2
- package/dist/dependencies.txt +1 -1
- package/dist/index.cjs.js +2 -2
- package/dist/index.es.js +2 -6
- package/dist/index.es5.js +1 -8
- package/dist/index.rn.js +2 -2
- package/package.json +2 -3
package/dist/index.rn.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";var NT=Object.defineProperty;var VT=(s,t,e)=>t in s?NT(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var u=(s,t,e)=>(VT(s,typeof t!="symbol"?t+"":t,e),e),Hl=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)};var n=(s,t,e)=>(Hl(s,t,"read from private field"),e?e.call(s):t.get(s)),g=(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)},m=(s,t,e,r)=>(Hl(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e);var V=(s,t,e)=>(Hl(s,t,"access private method"),e);const ur=require("uuid"),bg=require("bowser"),v=require("@protobuf-ts/runtime"),LT=require("worker-timers"),xT=require("sdp-transform");function kg(s){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const e in s)if(e!=="default"){const r=Object.getOwnPropertyDescriptor(s,e);Object.defineProperty(t,e,r.get?r:{enumerable:!0,get:()=>s[e]})}}return t.default=s,Object.freeze(t)}const Jc=kg(LT),os=kg(xT);function UT(s){const{length:t}=this,e=s>=0?s:t+s;return e<0||e>=t?void 0:this[e]}Array.prototype.at||Object.assign(Array.prototype,{at:UT});function $T(s){const{length:t}=this,e=s>=0?s:t+s;return e<0||e>=t?void 0:this[e]}String.prototype.at||Object.assign(String.prototype,{at:$T});const FT=s=>{!navigator.isReactNative&&typeof window!="undefined"&&(window.addEventListener("error",t=>{var e;!((e=t.filename)!=null&&e.includes("localhost"))&&t.lineno!==0&&s.error("window::error",{error:t.error},!0)}),window.addEventListener("unhandledrejection",t=>{var e,r,i,a,o,c,d,l;s.error("window::unhandledrejection",{error:t==null?void 0:t.reason,networkCall:{url:(r=(e=t==null?void 0:t.reason)==null?void 0:e.config)==null?void 0:r.url,baseURL:(a=(i=t==null?void 0:t.reason)==null?void 0:i.config)==null?void 0:a.baseURL,method:(c=(o=t==null?void 0:t.reason)==null?void 0:o.config)==null?void 0:c.method,status:(d=t==null?void 0:t.reason)==null?void 0:d.status,statusText:(l=t==null?void 0:t.reason)==null?void 0:l.statusText}},!0)}),window.addEventListener("offline",()=>{s.info("window::offline")}),window.addEventListener("online",()=>{s.info("window::online")}))},mo="chrome",Ig="opera",Ag="firefox",Mg="iexplorer",Dg="safari",Og="nwjs",Ng="electron",Vg="react-native",Qu="unknown",cd={Chrome:mo,Chromium:mo,Opera:Ig,Firefox:Ag,"Internet Explorer":Mg,Safari:Dg};function BT(){const{userAgent:s}=navigator,t={name:Qu,version:void 0};if(s.match(/Chrome/)&&!s.match(/Edge/))if(s.match(/Edg(A?)/)){const e=s.match(/Chrome\/([\d.]+)/)[1];Number.parseInt(e,10)>72&&(t.name=mo,t.version=e)}else t.name=mo,t.version=s.match(/Chrome\/([\d.]+)/)[1];return t}function HT(){const{userAgent:s}=navigator;if(s.match(/Electron/)){const t=s.match(/Electron\/([\d.]+)/)[1];return{name:Ng,version:t}}return null}function qT(){const{userAgent:s}=navigator;if(s.match(/JitsiMeetNW/)){const t=s.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:Og,version:t}}}function jT(){const s=navigator.userAgent.match(/\b(react[ \t_-]*native)(?:\/(\S+))?/i);let t;if(s||navigator.product==="ReactNative")return s&&s.length>2&&(s[1],t=s[2]),t||(t="unknown"),{name:Vg,version:t}}function GT(s){let t;const e=[jT,HT,qT];for(let i=0;i<e.length;i+=1)if(t=e[i](),t)return t;const r=s.getBrowserName();return r in cd?{name:cd[r],version:s.getBrowserVersion()}:(t=BT(),t||{name:Qu,version:void 0})}class WT{constructor(){u(this,"_bowser");u(this,"_name");u(this,"_version");u(this,"getDeviceInfo",()=>({isMobile:this.isMobile(),browserName:this._bowser.getBrowserName(),osName:this._bowser.getOSName(),browserVersion:this._bowser.getBrowserVersion(),osVersionName:this._bowser.getOSVersion(),engineName:this._bowser.getEngineName()}))}init(t){let e,r;if(this._bowser=bg.getParser(navigator.userAgent),typeof t=="undefined"){const i=GT(this._bowser);e=i.name,r=i.version}else t.name in cd?(e=cd[t.name],r=t.version):(e=Qu,r=void 0);this._name=e,this._version=r}getName(){return this._name}isChrome(){return this._name===mo}isOpera(){return this._name===Ig}isFirefox(){return this._name===Ag}isIExplorer(){return this._name===Mg}isSafari(){return this._name===Dg}isNWJS(){return this._name===Og}isElectron(){return this._name===Ng}isReactNative(){return this._name===Vg||navigator.isReactNative===!0}getVersion(){return this._version}isMobile(){return this._bowser.getPlatformType()==="mobile"}_checkCondition(t){if(this._version)return this._bowser.satisfies(t)}isVersionGreaterThan(t){return this._checkCondition({[this._name]:`>${t}`})}isVersionLessThan(t){return this._checkCondition({[this._name]:`<${t}`})}isVersionEqualTo(t){return this._checkCondition({[this._name]:`~${t}`})}}class JT extends WT{doesVideoMuteByStreamRemove(){return this.isChromiumBased()||this.isWebKitBased()}supportsP2P(){return!this.usesUnifiedPlan()}isChromiumBased(){return this.isChrome()||this.isElectron()||this.isNWJS()||this.isOpera()}isWebKitBased(){return this._bowser.isEngine("webkit")&&typeof navigator.mediaDevices!="undefined"&&typeof navigator.mediaDevices.getUserMedia!="undefined"&&typeof window.RTCRtpTransceiver!="undefined"&&Object.keys(RTCRtpTransceiver.prototype).indexOf("currentDirection")>-1}isSupported(){return typeof RTCPeerConnection!="undefined"}isUserInteractionRequiredForUnmute(){return this.isFirefox()&&this.isVersionLessThan("68")}supportsVideoMuteOnConnInterrupted(){return this.isChromiumBased()||this.isReactNative()||this.isWebKitBased()}supportsBandwidthStatistics(){return!this.isFirefox()&&!this.isWebKitBased()}supportsCodecPreferences(){return this.usesUnifiedPlan()&&typeof window.RTCRtpTransceiver!="undefined"&&Object.keys(window.RTCRtpTransceiver.prototype).indexOf("setCodecPreferences")>-1&&Object.keys(RTCRtpSender.prototype).indexOf("getCapabilities")>-1&&!this.isWebKitBased()}supportsDeviceChangeEvent(){return navigator.mediaDevices&&typeof navigator.mediaDevices.ondevicechange!="undefined"&&typeof navigator.mediaDevices.addEventListener!="undefined"}supportsLocalCandidateRttStatistics(){return this.isChromiumBased()||this.isReactNative()||this.isWebKitBased()}supportsPerformanceObserver(){return typeof window.PerformanceObserver!="undefined"&&PerformanceObserver.supportedEntryTypes.indexOf("longtask")>-1}supportsReceiverStats(){return typeof window.RTCRtpReceiver!="undefined"&&Object.keys(RTCRtpReceiver.prototype).indexOf("getSynchronizationSources")>-1}supportsRTTStatistics(){return!this.isFirefox()}usesPlanB(){return!this.usesUnifiedPlan()}usesSdpMungingForSimulcast(){return this.isChromiumBased()||this.isReactNative()||this.isWebKitBased()}usesUnifiedPlan(){return!!(this.isFirefox()||this.isWebKitBased())}usesNewGumFlow(){return!!(this.isChromiumBased()||this.isFirefox()||this.isWebKitBased())}usesAdapter(){return this.usesNewGumFlow()}usesRidsForSimulcast(){return!1}supportsGetDisplayMedia(){return typeof navigator.getDisplayMedia!="undefined"||typeof navigator.mediaDevices!="undefined"&&typeof navigator.mediaDevices.getDisplayMedia!="undefined"}supportsInsertableStreams(){if(!(typeof window.RTCRtpSender!="undefined"&&(window.RTCRtpSender.prototype.createEncodedStreams||window.RTCRtpSender.prototype.createEncodedVideoStreams)))return!1;const t=new ReadableStream;try{return window.postMessage(t,"*",[t]),!0}catch(e){return!1}}supportsAudioRed(){return Boolean(window.RTCRtpSender&&window.RTCRtpSender.getCapabilities&&window.RTCRtpSender.getCapabilities("audio").codecs.some(t=>t.mimeType==="audio/red")&&window.RTCRtpReceiver&&window.RTCRtpReceiver.getCapabilities&&window.RTCRtpReceiver.getCapabilities("audio").codecs.some(t=>t.mimeType==="audio/red"))}supportsSdpSemantics(){return this.isChromiumBased()}_getChromiumBasedVersion(){if(this.isChromiumBased()){if(this.isNWJS())return Number.parseInt(process.versions.chromium,10);const t=navigator.userAgent;if(t.match(/Chrome/))return Number.parseInt(t.match(/Chrome\/([\d.]+)/)[1],10)}return-1}isIOSMobile(){return this.isMobile&&this._bowser.getOSName()==="iOS"}}const fe=new JT;var nt={},KT={get exports(){return nt},set exports(s){nt=s}},yn=typeof Reflect=="object"?Reflect:null,Vh=yn&&typeof yn.apply=="function"?yn.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Kc;yn&&typeof yn.ownKeys=="function"?Kc=yn.ownKeys:Object.getOwnPropertySymbols?Kc=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Kc=function(t){return Object.getOwnPropertyNames(t)};function zT(s){console&&console.warn&&console.warn(s)}var Lg=Number.isNaN||function(t){return t!==t};function ie(){ie.init.call(this)}KT.exports=ie;nt.once=ZT;ie.EventEmitter=ie;ie.prototype._events=void 0;ie.prototype._eventsCount=0;ie.prototype._maxListeners=void 0;var Lh=10;function Tl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ie,"defaultMaxListeners",{enumerable:!0,get:function(){return Lh},set:function(s){if(typeof s!="number"||s<0||Lg(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Lh=s}});ie.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};ie.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Lg(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function xg(s){return s._maxListeners===void 0?ie.defaultMaxListeners:s._maxListeners}ie.prototype.getMaxListeners=function(){return xg(this)};ie.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var i=t==="error",a=this._events;if(a!==void 0)i=i&&a.error===void 0;else if(!i)return!1;if(i){var o;if(e.length>0&&(o=e[0]),o instanceof Error)throw o;var c=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw c.context=o,c}var d=a[t];if(d===void 0)return!1;if(typeof d=="function")Vh(d,this,e);else for(var l=d.length,h=Hg(d,l),r=0;r<l;++r)Vh(h[r],this,e);return!0};function Ug(s,t,e,r){var i,a,o;if(Tl(e),a=s._events,a===void 0?(a=s._events=Object.create(null),s._eventsCount=0):(a.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),a=s._events),o=a[t]),o===void 0)o=a[t]=e,++s._eventsCount;else if(typeof o=="function"?o=a[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=xg(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,zT(c)}return s}ie.prototype.addListener=function(t,e){return Ug(this,t,e,!1)};ie.prototype.on=ie.prototype.addListener;ie.prototype.prependListener=function(t,e){return Ug(this,t,e,!0)};function YT(){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 $g(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=YT.bind(r);return i.listener=e,r.wrapFn=i,i}ie.prototype.once=function(t,e){return Tl(e),this.on(t,$g(this,t,e)),this};ie.prototype.prependOnceListener=function(t,e){return Tl(e),this.prependListener(t,$g(this,t,e)),this};ie.prototype.removeListener=function(t,e){var r,i,a,o,c;if(Tl(e),i=this._events,i===void 0)return this;if(r=i[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(a=-1,o=r.length-1;o>=0;o--)if(r[o]===e||r[o].listener===e){c=r[o].listener,a=o;break}if(a<0)return this;a===0?r.shift():QT(r,a),r.length===1&&(i[t]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",t,c||e)}return this};ie.prototype.off=ie.prototype.removeListener;ie.prototype.removeAllListeners=function(t){var e,r,i;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[t]),this;if(arguments.length===0){var a=Object.keys(r),o;for(i=0;i<a.length;++i)o=a[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=r[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(i=e.length-1;i>=0;i--)this.removeListener(t,e[i]);return this};function Fg(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?XT(i):Hg(i,i.length)}ie.prototype.listeners=function(t){return Fg(this,t,!0)};ie.prototype.rawListeners=function(t){return Fg(this,t,!1)};ie.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):Bg.call(s,t)};ie.prototype.listenerCount=Bg;function Bg(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}ie.prototype.eventNames=function(){return this._eventsCount>0?Kc(this._events):[]};function Hg(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function QT(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function XT(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function ZT(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,a),r(o)}function a(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}qg(s,t,a,{once:!0}),t!=="error"&&ev(s,i,{once:!0})})}function ev(s,t,e){typeof s.on=="function"&&qg(s,"error",t,e)}function qg(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(a){r.once&&s.removeEventListener(t,i),e(a)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}var W;(function(s){s[s.MAJOR_EVENT=0]="MAJOR_EVENT",s[s.MINOR_EVENT=1]="MINOR_EVENT"})(W||(W={}));var D;(function(s){s.PRECALL_TEST_BEGIN="precall_begin",s.PRECALL_TEST_COMPLETE="precall_end",s.CALL_JOIN_BEGIN="call_join",s.NET_QUALITY_TEST_BEGIN="net_quality_test_begin",s.NET_QUALITY_TEST_END="net_quality_test_end",s.WEBSOCKET_CONNECTED="websocket_connected",s.TRANSPORT_CONNECTED="transport_connected",s.AUDIO_ON="audio_on",s.AUDIO_OFF="audio_off",s.VIDEO_ON="video_on",s.VIDEO_OFF="video_off",s.PARTICIPANT_ROLE="participant_role",s.PING_STAT="ping_stat",s.DISCONNECT="disconnect",s.RECONNECT_ATTEMPT="reconnect_attempt",s.SCREENSHARE_START_REQUESTED="screenshare_start_requested",s.SCREENSHARE_STARTED="screenshare_started",s.SCREENSHARE_STOPPED="screenshare_stopped",s.TAB_CHANGE="tab_change",s.BROWSER_BACKGROUNDED="browser_backgrounded",s.BROWSER_FOREGROUNDED="browser_foregrounded",s.DOMINANT_SPEAKER="dominant_speaker",s.AUDIO_DEVICES_UPDATES="audio_devices_updates",s.VIDEO_DEVICES_UPDATES="video_devices_updates",s.SPEAKER_DEVICES_UPDATES="speaker_devices_updates",s.SELECTED_MICROHPONE_UPDATE="selected_microphone_update",s.SELECTED_CAMERA_UPDATE="selected_camera_update",s.SELECTED_SPEAKER_UPDATE="selected_speaker_update",s.EXPECTED_VIDEO_RESOLUTION="expected_video_resolution",s.EXPECTED_SCREENSHARE_RESOLUTION="expected_screenshare_resolution",s.MEDIA_PERMISSION="media_permission",s.LEGACY_SWITCH="legacy_switch",s.AUDIO_PLAY_FAILED="audio_play_failed",s.VIDEO_PLAY_FAILED="video_play_failed",s.AUDIO_TRACK_MUTED="audio_track_muted",s.VIDEO_TRACK_MUTED="video_track_muted",s.IVS_PLAYER_REBUFFERING="ivs_player_rebuffering",s.IVS_PLAYER_AUDIO_BLOCKED="ivs_player_audio_blocked",s.IVS_PLAYER_PLAYBACK_BLOCKED="ivs_player_playback_blocked",s.IVS_PLAYER_ERROR="ivs_player_error",s.IVS_PLAYER_RECOVERABLE_ERROR="ivs_player_recoverable_error",s.IVS_PLAYER_WORKER_ERROR="ivs_player_worker_error",s.IVS_PLAYER_NETWORK_UNAVAILABLE="ivs_player_network_unavailable",s.LIVESTREAM_LATENCY="livestream_latency",s.IVS_PLAYER_ANALYTICS_EVENT="ivs_player_analytics_event",s.IVS_PLAYER_PLAYBACK_RATE_CHANGED="ivs_player_playback_rate_changed",s.IVS_PLAYER_QUALITY_CHANGED="ivs_player_quality_changed",s.IVS_PLAYER_INITIALIZED="ivs_player_initialized"})(D||(D={}));const tv=new Map([[D.PRECALL_TEST_BEGIN,W.MINOR_EVENT],[D.PRECALL_TEST_COMPLETE,W.MINOR_EVENT],[D.CALL_JOIN_BEGIN,W.MAJOR_EVENT],[D.NET_QUALITY_TEST_BEGIN,W.MINOR_EVENT],[D.NET_QUALITY_TEST_END,W.MINOR_EVENT],[D.WEBSOCKET_CONNECTED,W.MINOR_EVENT],[D.TRANSPORT_CONNECTED,W.MAJOR_EVENT],[D.AUDIO_ON,W.MINOR_EVENT],[D.AUDIO_OFF,W.MINOR_EVENT],[D.VIDEO_ON,W.MINOR_EVENT],[D.VIDEO_OFF,W.MINOR_EVENT],[D.PARTICIPANT_ROLE,W.MINOR_EVENT],[D.PING_STAT,W.MAJOR_EVENT],[D.DISCONNECT,W.MAJOR_EVENT],[D.RECONNECT_ATTEMPT,W.MAJOR_EVENT],[D.SCREENSHARE_START_REQUESTED,W.MINOR_EVENT],[D.SCREENSHARE_STARTED,W.MINOR_EVENT],[D.SCREENSHARE_STOPPED,W.MINOR_EVENT],[D.TAB_CHANGE,W.MINOR_EVENT],[D.BROWSER_BACKGROUNDED,W.MINOR_EVENT],[D.BROWSER_FOREGROUNDED,W.MINOR_EVENT],[D.DOMINANT_SPEAKER,W.MINOR_EVENT],[D.AUDIO_DEVICES_UPDATES,W.MINOR_EVENT],[D.VIDEO_DEVICES_UPDATES,W.MINOR_EVENT],[D.SPEAKER_DEVICES_UPDATES,W.MINOR_EVENT],[D.SELECTED_MICROHPONE_UPDATE,W.MINOR_EVENT],[D.SELECTED_CAMERA_UPDATE,W.MINOR_EVENT],[D.SELECTED_SPEAKER_UPDATE,W.MINOR_EVENT],[D.MEDIA_PERMISSION,W.MINOR_EVENT],[D.LEGACY_SWITCH,W.MINOR_EVENT],[D.AUDIO_PLAY_FAILED,W.MINOR_EVENT],[D.VIDEO_PLAY_FAILED,W.MINOR_EVENT],[D.AUDIO_TRACK_MUTED,W.MINOR_EVENT],[D.VIDEO_TRACK_MUTED,W.MINOR_EVENT],[D.IVS_PLAYER_REBUFFERING,W.MAJOR_EVENT],[D.IVS_PLAYER_AUDIO_BLOCKED,W.MAJOR_EVENT],[D.IVS_PLAYER_PLAYBACK_BLOCKED,W.MAJOR_EVENT],[D.IVS_PLAYER_ERROR,W.MAJOR_EVENT],[D.IVS_PLAYER_RECOVERABLE_ERROR,W.MAJOR_EVENT],[D.IVS_PLAYER_WORKER_ERROR,W.MAJOR_EVENT],[D.IVS_PLAYER_NETWORK_UNAVAILABLE,W.MAJOR_EVENT],[D.LIVESTREAM_LATENCY,W.MAJOR_EVENT],[D.IVS_PLAYER_ANALYTICS_EVENT,W.MINOR_EVENT],[D.IVS_PLAYER_PLAYBACK_RATE_CHANGED,W.MINOR_EVENT],[D.IVS_PLAYER_QUALITY_CHANGED,W.MINOR_EVENT],[D.IVS_PLAYER_INITIALIZED,W.MINOR_EVENT],[D.EXPECTED_VIDEO_RESOLUTION,W.MINOR_EVENT],[D.EXPECTED_SCREENSHARE_RESOLUTION,W.MINOR_EVENT]]);class sv{constructor(){u(this,"events");this.events=[]}add(t){this.events.push(t)}flush(){return{entries:this.events.splice(0,25)}}}class rv extends nt{constructor({logger:e,peerId:r,apiHostnames:i}){super();u(this,"logger");u(this,"peerId");u(this,"eventStore");u(this,"apiEndpoint");this.logger=e,this.peerId=r,this.apiEndpoint=`https://${i.daCollector}/api/v1/message`,this.eventStore=new sv}async sendEventsChunkToServer(e){var i;const r={payload:e,peerId:this.peerId};try{return await fetch(this.apiEndpoint,{method:"POST",body:JSON.stringify(r)}),!0}catch(a){return this.logger.error("callStats::sendEventsChunkToServer::catch",{error:a}),(i=e.entries)==null||i.forEach(o=>{this.eventStore.add(o)}),!1}}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),tv.get(e.event)===W.MAJOR_EVENT&&this.flush()}async flush(){var r;const e=this.eventStore.flush();return(r=e==null?void 0:e.entries)!=null&&r.length?(await this.sendEventsChunkToServer(e),!0):!1}}var xh;(function(s){s.CHROMIUM="chromum",s.FIREFOX="firefox",s.SAFARI="safari"})(xh||(xh={}));const oo={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var Ht;(function(s){s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.SPEAKER="SPEAKER",s.SCREENSHARE="SCREENSHARE"})(Ht||(Ht={}));var Uh;(function(s){s[s.INIT=0]="INIT",s[s.ACCEPTED=1]="ACCEPTED",s[s.DENIED=2]="DENIED",s[s.SYS_DENIED=3]="SYS_DENIED",s[s.FAILED=4]="FAILED",s[s.NOTFOUND=5]="NOTFOUND",s[s.NOT_APPLICABLE=6]="NOT_APPLICABLE"})(Uh||(Uh={}));function Jr(s){return s?s.split(".").slice(0,2).concat(["0","0"]).join("."):""}function dd({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function ld({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}const jg=240,Gg=720,Wg=8,Jg=3,vl=10,Sl=.02,yl=.03;function dr({stat:s,weight:t,rangeMin:e,rangeMax:r,rangeRankingDirection:i}){return s==null?t:e===r?i==="UP"?s<=e?t:0:s>=r?t:0:i==="UP"?(1-Math.max(Math.min(r,Math.abs(s))-e,0)/(r-e))*t:i==="DOWN"?Math.max(Math.min(r,Math.abs(s))-e,0)/(r-e)*t:t}function Kg({isLowQualityVideo:s,isVideoStuck:t,isVideoLagging:e,jitterQuality:r,packetsLostQuality:i}){const a=.8*((s?.85:1)*(e?.7:1)*(t?.5:1))+.2*(r*i);return Math.round((a+Number.EPSILON)*100)/100}function zg({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function Yg({packetsLost:s,packetsSent:t,jitter:e}){const i=dr({stat:zg({packetsLost:s,packetsSent:t}),weight:.7,rangeMin:0,rangeMax:vl,rangeRankingDirection:"UP"}),o=dr({stat:e,weight:.3,rangeMin:Sl,rangeMax:yl,rangeRankingDirection:"UP"});return i+o}function iv({frameWidth:s,isScreenShare:t}){return s<(t?Gg:jg)}function nv({framesPerSecond:s,isScreenShare:t}){return s<(t?Jg:Wg)}function av({framesEncoded:s}){return s===0}function Qg({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsSent:r,jitter:i,isScreenShare:a,framesEncoded:o}){const c=dr({stat:zg({packetsLost:e,packetsSent:r}),weight:1,rangeMin:0,rangeMax:vl,rangeRankingDirection:"UP"}),d=dr({stat:i,weight:1,rangeMin:Sl,rangeMax:yl,rangeRankingDirection:"UP"}),l=iv({frameWidth:s,isScreenShare:a}),h=nv({framesPerSecond:t,isScreenShare:a}),p=av({framesEncoded:o,isScreenShare:a});return Kg({isLowQualityVideo:l,isVideoLagging:h,isVideoStuck:p,jitterQuality:d,packetsLostQuality:c})}function Xg({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}function Zg({concealmentEvents:s,packetsLost:t,packetsReceived:e,jitter:r}){const a=dr({stat:s,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),o=.5,c=dr({stat:Xg({packetsLost:t,packetsReceived:e}),weight:o,rangeMin:0,rangeMax:vl,rangeRankingDirection:"UP"}),l=dr({stat:r,weight:.3,rangeMin:Sl,rangeMax:yl,rangeRankingDirection:"UP"});return a+c+l}function ov({framesDecoded:s}){return s===0}function cv({framesPerSecond:s,isScreenShare:t}){return s<(t?Jg:Wg)}function dv({frameWidth:s,isScreenShare:t}){return s<(t?Gg:jg)}function em({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsReceived:r,jitter:i,isScreenShare:a,framesDecoded:o}){const c=dr({stat:Xg({packetsLost:e,packetsReceived:r}),weight:1,rangeMin:0,rangeMax:vl,rangeRankingDirection:"UP"}),d=dr({stat:i,weight:1,rangeMin:Sl,rangeMax:yl,rangeRankingDirection:"UP"}),l=dv({frameWidth:s,isScreenShare:a}),h=cv({framesPerSecond:t,isScreenShare:a}),p=ov({framesDecoded:o,isScreenShare:a});return Kg({isLowQualityVideo:l,isVideoLagging:h,isVideoStuck:p,jitterQuality:d,packetsLostQuality:c})}class hr{constructor(t){u(this,"pc1");u(this,"pc2");u(this,"constrainVideoBitrateKbps");u(this,"constrainOfferToRemoveVideoFec",!1);u(this,"iceCandidateFilter");const e=new RTCPeerConnection(t),r=new RTCPeerConnection(t);this.pc1=e,this.pc2=r,this.iceCandidateFilter=hr.noFilter,this.pc1.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc2)),this.pc2.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc1))}static parseCandidate(t){const e="candidate:",r=t.indexOf(e)+e.length,i=t.substr(r).split(" ");return{type:i[7],protocol:i[2],address:i[4]}}static isNotHostCandidate(t){return t.type!=="host"}static isHost(t){return t.type==="host"}static isRelay(t){return t.type==="relay"}static isReflexive(t){return t.type==="srflx"}static noFilter(t){return!0}onIceCandidate(t,e){if(e.candidate){const r=hr.parseCandidate(e.candidate.candidate);this.iceCandidateFilter(r)&&t.addIceCandidate(e.candidate)}}setIceCandidateFilter(t){this.iceCandidateFilter=t}constrainVideoBitrate(t){this.constrainVideoBitrateKbps=t}disableVideoFec(){this.constrainOfferToRemoveVideoFec=!0}gotOffer(t){this.constrainOfferToRemoveVideoFec&&(t.sdp=t.sdp.replace(/(m=video 1 [^\r]+)(116 117)(\r\n)/g,`$1\r
|
|
2
2
|
`),t.sdp=t.sdp.replace(/a=rtpmap:116 red\/90000\r\n/g,""),t.sdp=t.sdp.replace(/a=rtpmap:117 ulpfec\/90000\r\n/g,""),t.sdp=t.sdp.replace(/a=rtpmap:98 rtx\/90000\r\n/g,""),t.sdp=t.sdp.replace(/a=fmtp:98 apt=116\r\n/g,"")),this.pc1.setLocalDescription(t),this.pc2.setRemoteDescription(t),this.pc2.createAnswer().then(this.gotAnswer.bind(this),this.reportFatal.bind(this))}gotAnswer(t){this.constrainVideoBitrateKbps&&(t.sdp=t.sdp.replace(/a=mid:video\r\n/g,`a=mid:video\r
|
|
3
3
|
b=AS:${this.constrainVideoBitrateKbps}\r
|
|
4
|
-
`)),this.pc2.setLocalDescription(t),this.pc1.setRemoteDescription(t)}establishConnection(){this.pc1.createOffer().then(this.gotOffer.bind(this),this.reportFatal.bind(this))}reportFatal(t){console.error("Error:",t)}async getRoundTripTime(){const[t,e]=await Promise.all([this.pc1.getStats(),this.pc2.getStats()]);let r,i;if(t.forEach(a=>{a.type==="candidate-pair"&&a.nominated===!0&&a.bytesSent>0&&(r=a)}),e.forEach(a=>{a.type==="candidate-pair"&&a.nominated===!0&&a.bytesReceived>0&&(i=a)}),r&&i)try{if(r.currentRoundTripTime&&i.currentRoundTripTime)return{rtt:r.currentRoundTripTime,backendRTT:i.currentRoundTripTime};const a=(i.lastPacketReceivedTimestamp-r.lastPacketSentTimestamp)/1e3;return{rtt:a,backendRTT:a}}catch(a){return}}close(){this.pc1.close(),this.pc2.close()}}class tm extends nt{constructor(e){super();u(this,"call");u(this,"timeOut");this.call=new hr(e)}start(e=1e4){this.call.establishConnection(),this.timeOut=setTimeout(this.testFailed.bind(this),e)}testComplete(e){clearTimeout(this.timeOut),this.call.close(),this.emit("done",e)}testFailed(e){this.call.close(),this.emit("failed",e)}}const lv=8,uv=1/1e3;class hv extends tm{constructor(e){super(e);u(this,"senderChannel");u(this,"recieveChannel");u(this,"startTime");u(this,"lastBitrateMeasureTime");u(this,"sentPayloadBytes",0);u(this,"recievedPayloadBytes",0);u(this,"lastReceivedPayloadBytes",0);u(this,"stopSending",!1);u(this,"testProgress",0);u(this,"samplePacket","");u(this,"finalBitrateSum",0);u(this,"bitRateSampels",0);u(this,"maxNumberOfPacketsToSend",0);u(this,"bytesToKeepBuffered",0);u(this,"testDurationSeconds",5);this.call.setIceCandidateFilter(hr.isNotHostCandidate),this.senderChannel=this.call.pc1.createDataChannel(null);for(let r=0;r<1024*256;r+=1)this.samplePacket+="h";this.maxNumberOfPacketsToSend=1,this.bytesToKeepBuffered=1024*this.maxNumberOfPacketsToSend,this.testDurationSeconds=4,this.senderChannel.addEventListener("open",this.sendingStep.bind(this)),this.call.pc2.addEventListener("datachannel",this.onRecieverChannel.bind(this))}sendingStep(){const e=new Date;this.startTime||(this.startTime=e,this.lastBitrateMeasureTime=e);for(let i=0;i!==this.maxNumberOfPacketsToSend&&!(this.senderChannel.bufferedAmount>=this.bytesToKeepBuffered);i+=1){this.sentPayloadBytes+=this.samplePacket.length;try{this.senderChannel.send(this.samplePacket)}catch(a){}}const r=e.getTime()-this.startTime.getTime();r>=1e3*this.testDurationSeconds?(this.stopSending=!0,this.testProgress=100):(this.testProgress=r/(10*this.testDurationSeconds),setTimeout(this.sendingStep.bind(this),1))}onMessageRecieved(e){this.recievedPayloadBytes+=e.data.length;const r=new Date,i=r.getTime()-this.lastBitrateMeasureTime.getTime();if(i>=1e3){const o=(this.recievedPayloadBytes-this.lastReceivedPayloadBytes)*lv/(i/1e3);this.finalBitrateSum+=o,this.bitRateSampels+=1,this.lastReceivedPayloadBytes=this.recievedPayloadBytes,this.lastBitrateMeasureTime=r}if(this.stopSending&&this.sentPayloadBytes===this.recievedPayloadBytes){const a=this.finalBitrateSum/this.bitRateSampels;this.testComplete({throughput:Math.round(a*uv)})}}testComplete(e){this.call.getRoundTripTime().then(({rtt:r,backendRTT:i})=>super.testComplete({RTT:r,backendRTT:i,throughput:e.throughput}))}onRecieverChannel(e){this.recieveChannel=e.channel,this.recieveChannel.addEventListener("message",this.onMessageRecieved.bind(this))}}class Xu extends tm{constructor(e,r=hr.noFilter){super(e);u(this,"ch1");u(this,"ch2");this.call.setIceCandidateFilter(r);const i=this.call.pc1.createDataChannel(null);this.ch1=i,i.addEventListener("open",()=>{i.send("hello")}),i.addEventListener("message",this.onCh1Recieve.bind(this)),this.call.pc2.addEventListener("datachannel",this.dataChannelHandler.bind(this))}onCh1Recieve(e){e.data!=="world"?this.hangup("Invalid data transmitted."):this.testComplete({connectivity:!0})}onCh2Recieve(e){if(e.data!=="hello")this.hangup("Invalid data transmitted.");else try{this.ch2.send("world")}catch(r){}}dataChannelHandler(e){const r=e.channel;this.ch2=r,r.addEventListener("message",this.onCh2Recieve.bind(this))}hangup(e){this.testFailed(e)}}class pv extends Xu{constructor(t){super(t,hr.isHost)}}class gv extends Xu{constructor(t){super(t,hr.isRelay)}}class mv extends Xu{constructor(t){super(t,hr.isReflexive)}}class fv{constructor(){u(this,"ipInformation",null)}async getIPDetails({peerId:t,apiHostnames:e,logger:r}){var i,a,o;if(!this.ipInformation){try{const c=`https://${e.location}`,l=await(await fetch(c)).json();if(((i=l.loc)==null?void 0:i.length)>5)return this.ipInformation=l,(a=this.ipInformation)!=null&&a.ip&&(this.ipInformation.ip=Jr(this.ipInformation.ip)),l;throw Error("Insufficient data")}catch(c){r.error("callstats::ipDetails:: failed to fetch ip using location service",{error:c})}try{const c=await fetch(`https://${e.locationLegacy}/?token=3c493932b0624c&peerId=${t}`,{method:"POST"});this.ipInformation=await c.json(),(o=this.ipInformation)!=null&&o.ip&&(this.ipInformation.ip=Jr(this.ipInformation.ip))}catch(c){r.error("callstats::ipDetails:: failed to fetch ip using legacy location service",{error:c})}}return this.ipInformation}resetCache(){this.ipInformation=null}}const Zu=new fv,$h=[{urls:"turn:turn.dyte.in:443?transport=tcp",username:"dyte",credential:"dytein",credentialType:"password"},{urls:"turn:turn.dyte.in:3478?transport=udp",username:"dyte",credential:"dytein",credentialType:"password"}];function Fh(s){const[t,e]=s.split(",");return{coords:{latitude:Number(t),longitude:Number(e)}}}class sm{constructor(){u(this,"transport");u(this,"candidatePair");u(this,"outboundVideoRtp",new Map);u(this,"inboundVideoRtp",new Map);u(this,"outboundAudioRtp",new Map);u(this,"inboundAudioRtp",new Map);u(this,"remoteInboundRtp",new Map);u(this,"producerStreamMap",new Map);u(this,"consumerStreamMap",new Map);u(this,"staleProducerStreamMap",!1);u(this,"staleConsumerStreamMap",!1)}}class rm extends nt{constructor(){super();u(this,"observer");u(this,"outboundProducerMap",new Map);u(this,"inboundConsumerMap",new Map);u(this,"consumerPeerIdMap",new Map);u(this,"pausedConsumerMap",new Map);u(this,"pausedProducerMap",new Map);u(this,"overallProducingTransportsStatsMap",{});u(this,"overallConsumingTransportsStatsMap",{});u(this,"overallConsumersStatsMap",{});u(this,"overallProducersStatsMap",{});u(this,"videoProducerToStatsMap",new Map);u(this,"audioProducerToStatsMap",new Map);u(this,"videoConsumerToStatsMap",new Map);u(this,"audioConsumerToStatsMap",new Map);u(this,"consumerIdsWithFreezedVideo",new Set);u(this,"consumerIdsWithFreezedAudio",new Set);u(this,"producerIdsWithFreezedVideo",new Set);u(this,"producerIdsWithFreezedAudio",new Set);u(this,"freezedProducingTransportIds",new Set);u(this,"freezedConsumingTransportIds",new Set);u(this,"screenShareProducers",new Set);u(this,"screenShareConsumers",new Set);u(this,"ipDetails");u(this,"callStatsInstance");this.observer=new nt}async registerProducer(e){await this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}pauseProducer(e){this.pausedProducerMap.set(e,{lastReportCalculated:!1})}resumeProducer(e){this.pausedProducerMap.delete(e)}processInboundConsumerVideoStats(e,r,i){var o,c;const a=((c=(o=this==null?void 0:this.callStatsInstance)==null?void 0:o.consumerSharedMediaStatesMap)==null?void 0:c.get(e))||{};r.totalVideoPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedVideo.add(e),this.callStatsInstance&&a.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","pause",e))):(r.totalVideoPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedVideo.has(e)&&(this.consumerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&a.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","resume",e))))}processInboundConsumerAudioStats(e,r,i){var o,c;const a=((c=(o=this==null?void 0:this.callStatsInstance)==null?void 0:o.consumerSharedMediaStatesMap)==null?void 0:c.get(e))||{};r.totalAudioPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedAudio.add(e),this.callStatsInstance&&a.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","pause",e))):(r.totalAudioPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedAudio.has(e)&&(this.consumerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&a.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","resume",e))))}processOutboundProducerVideoStats(e,r,i){var o;const a=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalVideoPacketsSent===i.packetsSent?(this.producerIdsWithFreezedVideo.add(e),this.callStatsInstance&&a.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","pause",e))):(r.totalVideoPacketsSent=i.packetsSent,this.producerIdsWithFreezedVideo.has(e)&&(this.producerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&a.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","resume",e))))}processOutboundProducerAudioStats(e,r,i){var o;const a=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalAudioPacketsSent===i.packetsSent?(this.producerIdsWithFreezedAudio.add(e),this.callStatsInstance&&a.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","pause",e))):(r.totalAudioPacketsSent=i.packetsSent,this.producerIdsWithFreezedAudio.has(e)&&(this.producerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&a.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","resume",e))))}processProducingTransportStats(e,r,i){var h;const a=((h=this==null?void 0:this.callStatsInstance)==null?void 0:h.currentUserMediaStates)||{},{audio:o,video:c,screen:d}=a,l=o||c||d;r.totalPacketsSent===i.packetsSent?(this.freezedProducingTransportIds.add(e),this.callStatsInstance&&l&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","pause",e))):(r.totalPacketsSent=i.packetsSent,this.freezedProducingTransportIds.has(e)&&(this.freezedProducingTransportIds.delete(e),this.callStatsInstance&&l&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","resume",e))))}processConsumingTransportStats(e,r,i){var c,d;const o=!!Array.from(((d=(c=this==null?void 0:this.callStatsInstance)==null?void 0:c.consumerSharedMediaStatesMap)==null?void 0:d.values())||[]).reduce((l,h)=>l||h.audio||h.video||h.screen,!1);r.totalPacketsReceived===i.packetsSent?(this.freezedConsumingTransportIds.add(e),this.callStatsInstance&&o&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","pause",e))):(r.totalPacketsReceived=i.packetsSent,this.freezedConsumingTransportIds.has(e)&&(this.freezedConsumingTransportIds.delete(e),this.callStatsInstance&&o&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","resume",e))))}async registerConsumer(e){await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}pauseConsumer(e){this.pausedConsumerMap.set(e,{lastReportCalculated:!1})}resumeConsumer(e){this.pausedConsumerMap.delete(e)}async generateProducerStreamMap(e,r=!1){const i=await e.getStats(),a=r?this.getProducerStatsFromReport(this.parseRTCReport(i,["outbound-rtp","remote-inbound-rtp"],!1,e.id))[0]:void 0;for(const o of i.values())switch(o.type){case"outbound-rtp":{this.outboundProducerMap.set(o.id,e.id);break}}return a}async generateConsumerStreamMap(e,r=!1){const i=await e.getStats(),a=r?this.getConsumerStatsFromReport(this.parseRTCReport(i,["inbound-rtp"],!1,e.id))[0]:void 0;for(const o of i.values())switch(o.type){case"inbound-rtp":{this.inboundConsumerMap.set(o.id,e.id);break}}return a}deregisterProducer(e){this.outboundProducerMap.forEach((r,i)=>{r===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.inboundConsumerMap.forEach((r,i)=>{r===e.id&&this.inboundConsumerMap.delete(i)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}getWorkingSimulcastVideoStats(e){return e.find(i=>{const a=i.framesEncoded>0,o=i.packetsSent>0,c=i.frameWidth&&i.frameHeight;return a&&o&&!!c})||e[e.length-1]}parseRTCReport(e,r=[],i=!1,a=void 0,o=void 0){var C,_,I,M,x,N,$,q,ee,Qe,is,ei,ns;const c=e,d=new sm,l=r.length?new Set(r):void 0,h=[],p=[],f=[],T=new Map,E=new Map;for(const k of c.values()){if(l){if(l.size===0)break;if(l.has(k.type))i&&l.delete(k.type);else continue}switch(k.type){case"local-candidate":{h.push(this.getIceCandidateStats(k));break}case"remote-candidate":{p.push(this.getIceCandidateStats(k));break}case"candidate-pair":{const{nominated:S}=k,{selected:P}=k,U=k,Te={nominated:S!=null?S:P,currentRoundTripTime:U.currentRoundTripTime,totalRoundTripTime:U.totalRoundTripTime,bytesReceived:U.bytesReceived,bytesSent:U.bytesSent,availableOutgoingBitrate:U.availableOutgoingBitrate,availableIncomingBitrate:U.availableIncomingBitrate,lastPacketReceivedTimestamp:U.lastPacketReceivedTimestamp,lastPacketSentTimestamp:U.lastPacketSentTimestamp,localCandidateId:U.localCandidateId,remoteCandidateId:U.remoteCandidateId,bytesDiscardedOnSend:U.bytesDiscardedOnSend,packetsSent:U.packetsSent,packetsReceived:U.packetsReceived,packetsDiscardedOnSend:U.packetsDiscardedOnSend};f.push(Te),(k.nominated===!0||k.selected===!0)&&(d.candidatePair=Te);break}case"transport":{const S=k;o&&(o.producing&&(this.overallProducingTransportsStatsMap[o.id]||(this.overallProducingTransportsStatsMap[o.id]={totalPacketsSent:0})),o.consuming&&(this.overallConsumingTransportsStatsMap[o.id]||(this.overallConsumingTransportsStatsMap[o.id]={totalPacketsReceived:0})));const P={bytesReceived:S.bytesReceived,bytesSent:S.bytesSent,packetsSent:S.packetsSent,packetsReceived:S.packetsReceived,dtlsCipher:S.dtlsCipher,dtlsState:S.dtlsState,iceRole:S.iceRole};if(d.transport=P,o){if(o.producing){const U=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,U,P)}if(o.consuming){const U=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,U,P)}}break}case"remote-inbound-rtp":{const S=k,P={jitter:S.jitter,fractionLost:S.fractionLost,roundTripTime:S.roundTripTime,roundTripTimeMeasurements:S.roundTripTimeMeasurements,totalRoundTripTime:S.totalRoundTripTime,packetsLost:S.packetsLost};d.remoteInboundRtp.set(S.localId,P);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(k.id))break;const S=k,P=a||this.outboundProducerMap.get(k.id),U=this.pausedProducerMap.get(P);if(U){if(U.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const Te=this.overallProducersStatsMap[P];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.outboundProducerMap.has(k.id)){d.staleProducerStreamMap=!0;break}const be=this.callStatsInstance.producers.get(P);if(((C=be==null?void 0:be.track)==null?void 0:C.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const O={bytesSent:S.bytesSent,packetsSent:S.packetsSent,nackCount:S.nackCount,ssrc:S.ssrc,mid:S.mid,active:S.active,codecId:S.codecId,headerBytesSent:S.headerBytesSent||0,totalPacketSendDelay:S.totalPacketSendDelay||0};if(S.mediaType==="video"||S.kind==="video"){const R=S,Ne={frameHeight:R.frameHeight,frameWidth:R.frameWidth,framesEncoded:R.framesEncoded,framesDropped:R.framesDropped,framesPerSecond:R.framesPerSecond,framesSent:R.framesSent,keyFramesEncoded:R.keyFramesEncoded,firCount:R.firCount,encoderImplementation:R.encoderImplementation,hugeFramesSent:R.hugeFramesSent,pliCount:R.pliCount,qpSum:R.qpSum,qualityLimitationDurations:R.qualityLimitationDurations,qualityLimitationReason:R.qualityLimitationReason,qualityLimitationResolutionChanges:R.qualityLimitationResolutionChanges,totalEncodeTime:R.targetBitrate,totalPacketSendDelay:R.totalPacketSendDelay,retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,scalabilityMode:R.scalabilityMode,powerEfficientEncoder:R.powerEfficientEncoder,...O};d.outboundVideoRtp.set(k.id,Ne),d.producerStreamMap.get(P).outboundVideoRtpId.push(k.id),this.processOutboundProducerVideoStats(P,Te,Ne)}else if(S.mediaType==="audio"||S.kind==="audio"){const R=S,Ne={retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,...O};d.outboundAudioRtp.set(k.id,Ne),d.producerStreamMap.get(P).outboundAudioRtpId.push(k.id),this.processOutboundProducerAudioStats(P,Te,Ne)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(k.id))break;const S=k,P=a||this.inboundConsumerMap.get(k.id),U=this.pausedConsumerMap.get(P);if(U){if(U.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(S.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const Te=this.overallConsumersStatsMap[P];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.inboundConsumerMap.has(k.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(P)||d.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const be={bytesReceived:S.bytesReceived,packetsReceived:S.packetsReceived,packetsLost:S.packetsLost>=0?S.packetsLost:0,jitter:S.jitter,nackCount:S.nackCount,jitterBufferDelay:S.jitterBufferDelay,jitterBufferEmittedCount:S.jitterBufferEmittedCount,lastPacketReceivedTimestamp:S.lastPacketReceivedTimestamp,ssrc:S.ssrc,mid:S.mid,codecId:S.codecId,headerBytesReceived:S.headerBytesReceived||0,packetsDiscarded:S.packetsDiscarded||0,jitterBufferMinimumDelay:S.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:S.jitterBufferTargetDelay||0};if(S.mediaType==="video"||S.kind==="video"){const O=S,R={frameHeight:O.frameHeight,frameWidth:O.frameWidth,framesDecoded:O.framesDecoded,framesDropped:O.framesDropped,framesPerSecond:O.framesPerSecond,framesReceived:O.framesReceived,keyFramesDecoded:O.keyFramesDecoded,firCount:O.firCount,decoderImplementation:O.decoderImplementation,pliCount:O.pliCount,totalProcessingDelay:O.totalProcessingDelay,qpSum:O.qpSum||0,totalAssemblyTime:O.totalAssemblyTime||0,totalDecodeTime:O.totalDecodeTime||0,totalFreezesDuration:O.totalFreezesDuration||0,totalInterFrameDelay:O.totalInterFrameDelay||0,totalPausesDuration:O.totalPausesDuration||0,totalSquaredInterFrameDelay:O.totalSquaredInterFrameDelay||0,freezeCount:O.freezeCount||0,pauseCount:O.pauseCount||0,powerEfficientDecoder:O.powerEfficientDecoder,...be};R.score=em({frameWidth:R.frameWidth||0,framesDecoded:(R.framesDecoded||0)-(((_=this.videoConsumerToStatsMap.get(P))==null?void 0:_.framesDecoded)||0),framesPerSecond:R.framesPerSecond||0,packetsLost:(R.packetsLost||0)-(((I=this.videoConsumerToStatsMap.get(P))==null?void 0:I.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((M=this.videoConsumerToStatsMap.get(P))==null?void 0:M.packetsReceived)||0),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),E.set(P,{score:+(R.score*10).toFixed(),frameWidth:R.frameWidth||0,frameHeight:R.frameHeight||0,framesPerSecond:R.framesPerSecond||0,packetsLostPercentage:ld({packetsLost:(R.packetsLost||0)-(((x=this.videoConsumerToStatsMap.get(P))==null?void 0:x.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((N=this.videoConsumerToStatsMap.get(P))==null?void 0:N.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((R.bytesReceived||0)-((($=this.videoConsumerToStatsMap.get(P))==null?void 0:$.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,R),d.inboundVideoRtp.set(k.id,R),d.consumerStreamMap.get(P).inboundVideoRtpId.push(k.id),this.processInboundConsumerVideoStats(P,Te,R)}else if(S.mediaType==="audio"||S.kind==="audio"){const O=S,R={audioLevel:O.audioLevel,concealedSamples:O.concealedSamples,concealmentEvents:O.concealmentEvents,totalAudioEnergy:O.totalAudioEnergy,totalSamplesDuration:O.totalSamplesDuration,totalSamplesReceived:O.totalSamplesReceived,fecPacketsDiscarded:O.fecPacketsDiscarded||0,fecPacketsReceived:O.fecPacketsReceived||0,insertedSamplesForDeceleration:O.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:O.removedSamplesForAcceleration||0,silentConcealedSamples:O.silentConcealedSamples||0,playoutId:O.playoutId,...be};R.score=Zg({concealmentEvents:(R.concealmentEvents||0)-(((q=this.audioConsumerToStatsMap.get(P))==null?void 0:q.concealmentEvents)||0),packetsLost:(R.packetsLost||0)-(((ee=this.audioConsumerToStatsMap.get(P))==null?void 0:ee.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((Qe=this.audioConsumerToStatsMap.get(P))==null?void 0:Qe.packetsReceived)||0),jitter:R.jitter||0}),E.set(P,{score:+(R.score*10).toFixed(),packetsLostPercentage:ld({packetsLost:(R.packetsLost||0)-(((is=this.audioConsumerToStatsMap.get(P))==null?void 0:is.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((ei=this.audioConsumerToStatsMap.get(P))==null?void 0:ei.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((R.bytesReceived||0)-(((ns=this.audioConsumerToStatsMap.get(P))==null?void 0:ns.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,R),d.inboundAudioRtp.set(k.id,R),d.consumerStreamMap.get(P).inboundAudioRtpId.push(k.id),this.processInboundConsumerAudioStats(P,Te,R)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}}}if(d.producerStreamMap.forEach((k,S)=>{var P,U,Te,be,O,R,Ne,xs,Oa,Na,Va,La,xa,Ua,$a,Fa,Ba,Ha,qa,ja,Ga,Wa,Ja;if(k.outboundVideoRtpId.length>0){const oe=[];k.outboundVideoRtpId.forEach(Bl=>{oe.push(d.outboundVideoRtp.get(Bl))});const X=this.getWorkingSimulcastVideoStats(oe);X.score=Qg({frameWidth:X.frameWidth||0,framesPerSecond:X.framesPerSecond||0,jitter:((P=X.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsSent:(X.packetsSent||0)-(((U=this.videoProducerToStatsMap.get(S))==null?void 0:U.packetsSent)||0),packetsLost:(((Te=X.remoteData)==null?void 0:Te.packetsLost)||0)-(((O=(be=this.videoProducerToStatsMap.get(S))==null?void 0:be.remoteData)==null?void 0:O.packetsLost)||0),framesEncoded:(X.framesEncoded||0)-(((R=this.videoProducerToStatsMap.get(S))==null?void 0:R.framesEncoded)||0)}),T.set(S,{score:+(X.score*10).toFixed(),frameWidth:X.frameWidth||0,frameHeight:X.frameHeight||0,framesPerSecond:X.framesPerSecond||0,jitter:((Ne=X.remoteData)==null?void 0:Ne.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsLostPercentage:dd({packetsSent:(X.packetsSent||0)-(((xs=this.videoProducerToStatsMap.get(S))==null?void 0:xs.packetsSent)||0),packetsLost:(((Oa=X.remoteData)==null?void 0:Oa.packetsLost)||0)-(((Va=(Na=this.videoProducerToStatsMap.get(S))==null?void 0:Na.remoteData)==null?void 0:Va.packetsLost)||0)}),bitrate:((X.bytesSent||0)-(((La=this.videoProducerToStatsMap.get(S))==null?void 0:La.bytesSent)||0))*8/7,cpuLimitations:X.qualityLimitationReason==="cpu",bandwidthLimitations:X.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(S,X)}else if(k.outboundAudioRtpId.length>0){const oe=d.outboundAudioRtp.get(k.outboundAudioRtpId[0]);oe.score=Yg({packetsSent:(oe.packetsSent||0)-(((xa=this.audioProducerToStatsMap.get(S))==null?void 0:xa.packetsSent)||0),packetsLost:(((Ua=oe.remoteData)==null?void 0:Ua.packetsLost)||0)-(((Fa=($a=this.audioProducerToStatsMap.get(S))==null?void 0:$a.remoteData)==null?void 0:Fa.packetsLost)||0),jitter:((Ba=oe.remoteData)==null?void 0:Ba.jitter)||0}),T.set(S,{score:+(oe.score*10).toFixed(),bitrate:((oe.bytesSent||0)-(((Ha=this.audioProducerToStatsMap.get(S))==null?void 0:Ha.bytesSent)||0))*8/7,packetsLostPercentage:dd({packetsSent:(oe.packetsSent||0)-(((qa=this.audioProducerToStatsMap.get(S))==null?void 0:qa.packetsSent)||0),packetsLost:(((ja=oe.remoteData)==null?void 0:ja.packetsLost)||0)-(((Wa=(Ga=this.audioProducerToStatsMap.get(S))==null?void 0:Ga.remoteData)==null?void 0:Wa.packetsLost)||0)}),jitter:((Ja=oe.remoteData)==null?void 0:Ja.jitter)||0,isScreenShare:this.screenShareProducers.has(S)}),this.audioProducerToStatsMap.set(S,oe)}}),f.forEach(k=>{const S=h.find(U=>U.id===k.localCandidateId?(k.localCandidateId=U.id,U):null),P=p.find(U=>U.id===k.remoteCandidateId?(k.remoteCandidateId=U.id,U):null);S&&(k.localCandidateType=S.type,k.localCandidateAddress=Jr(S.address),k.localCandidatePort=S.port,k.localCandidateProtocol=S.protocol,k.localCandidateUrl=S.url,k.localCandidateNetworkType=S.networkType,k.localCandidateRelatedAddress=Jr(S.relatedAddress),k.localCandidateRelatedPort=S.relatedPort),P&&(k.remoteCandidateType=P.type,k.remoteCandidateAddress=Jr(P.address),k.remoteCandidatePort=P.port,k.remoteCandidateProtocol=P.protocol,k.remoteCandidateUrl=P.url)}),d.candidatePair&&(d.transport?(d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=f),d.transport&&!d.transport.roundTripTime){let k=0,S=0;d.remoteInboundRtp.forEach((P,U)=>{P.roundTripTime&&P.roundTripTime>k&&(k=P.roundTripTime,S=P.totalRoundTripTime)}),d.transport.roundTripTime=k,d.transport.totalRoundTripTime=S}if(E.size>0)try{this.observer.emit("consumer_score",E)}catch(k){}if(T.size>0)try{this.observer.emit("producer_score",T)}catch(k){}return d}async getProducersReport(e){const r=e.map(i=>this.generateProducerStreamMap(i,!0));return r.length>0?Promise.all(r):void 0}async getConsumersReport(e){const r=e.map(i=>this.generateConsumerStreamMap(i,!0));return r.length>0?Promise.all(r):void 0}async getTransportReport(e){return e.getStats()}async getProcessedStats(e,r,i){const a=await this.getTransportReport(e),o={producing:i,consuming:r,id:e.id},c=a,d=this.parseRTCReport(c,["transport","candidate-pair","inbound-rtp","outbound-rtp","remote-inbound-rtp","local-candidate","remote-candidate"],!1,void 0,o);if(!d)return;const l={stats:d.transport,transportId:e.id,consuming:r,producing:i},h=d.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(d),p=d.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(d);return{transportReport:l,producerReport:h,consumerReport:p}}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,a)=>{var o,c;r.push({producerId:a,videoStats:i.outboundVideoRtpId.map(d=>e.outboundVideoRtp.get(d)),audioStats:i.outboundAudioRtpId.map(d=>e.outboundAudioRtp.get(d)),appData:((c=(o=this.callStatsInstance.producers)==null?void 0:o.get(a))==null?void 0:c.appData)||null})})}catch(i){this.callStatsInstance.logger.error("callStats::measurements::getProducerStatsFromReport",{error:{reason:i.reason,message:i.message}})}return r}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((i,a)=>{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(a);r.push({consumerId:a,peerId:o,producerId:c,appData:d,videoStats:i.inboundVideoRtpId.map(l=>e.inboundVideoRtp.get(l)),audioStats:i.inboundAudioRtpId.map(l=>e.inboundAudioRtp.get(l))})})}catch(i){console.error("getConsumersReport: ",i,e)}return r}async getUserLocation(){return new Promise((e,r)=>{try{navigator.geolocation?navigator.geolocation.getCurrentPosition(i=>{e(i)}):r()}catch(i){r(i)}})}async getConnectivity(e){try{const r={iceServers:e||$h},i=new Promise((h,p)=>{try{const f=new pv(r);f.addListener("done",h),f.addListener("failed",()=>{h({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),a=new Promise((h,p)=>{try{const f=new gv(r);f.addListener("done",h),f.addListener("failed",()=>{h({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),o=new Promise((h,p)=>{try{const f=new mv(r);f.addListener("done",h),f.addListener("failed",()=>{h({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),[c,d,l]=await Promise.all([i,a,o]);return{host:c==null?void 0:c.connectivity,relay:d==null?void 0:d.connectivity,reflexive:l==null?void 0:l.connectivity}}catch(r){return{host:!1,relay:!1,reflexive:!1}}}async getThroughput(e){try{const i=await new Promise((a,o)=>{try{const c={iceServers:e||$h},d=new hv(c);d.addListener("done",a),d.addListener("failed",o),d.start(1e4)}catch(c){o(c)}});return{throughput:i.throughput,fractionalLoss:0,RTT:i.RTT,jitter:0,backendRTT:i.backendRTT}}catch(r){return}}async getIPDetails(){var e,r;try{return this.ipDetails||(this.ipDetails=await Zu.getIPDetails({peerId:(e=this.callStatsInstance)==null?void 0:e.peerId,apiHostnames:(r=this.callStatsInstance)==null?void 0:r.apiHostnames,logger:this.callStatsInstance.logger})),this.ipDetails}catch(i){return}}async getNetworkQuality(e){const[r,i]=await Promise.all([this.getConnectivity(e),this.getThroughput(e)]);return{connectivity:r,throughput:i==null?void 0:i.throughput,fractionalLoss:i==null?void 0:i.fractionalLoss,RTT:i==null?void 0:i.RTT,jitter:i==null?void 0:i.jitter,backendRTT:i==null?void 0:i.backendRTT}}async getNetworkInfo(e,r=!1){var c,d;if(r){const l=await this.getIPDetails();return{ipDetails:l,effectiveNetworkType:(c=navigator.connection)==null?void 0:c.effectiveType,location:l!=null&&l.loc?Fh(l==null?void 0:l.loc):void 0}}const[i,a,o]=await Promise.all([this.getConnectivity(e),this.getThroughput(e),this.getIPDetails()]);return{ipDetails:o,effectiveNetworkType:(d=navigator.connection)==null?void 0:d.effectiveType,location:o!=null&&o.loc?Fh(o==null?void 0:o.loc):void 0,turnConnectivity:i?i.host||i.relay||i.reflexive:!1,connectivity:i,throughput:a==null?void 0:a.throughput,fractionalLoss:a==null?void 0:a.fractionalLoss,RTT:a==null?void 0:a.RTT,jitter:a==null?void 0:a.jitter,backendRTT:a==null?void 0:a.backendRTT}}}class Tv extends rm{}class im extends rm{constructor(){super(...arguments);u(this,"producerMap",new Map);u(this,"consumerMap",new Map)}async registerProducer(e){this.producerMap.set(e.id,e),await this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}async registerConsumer(e){this.consumerMap.set(e.id,e),await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}async generateConsumerStreamMap(e,r=!1){const i=await e.getStats(),a=this.parseRTCReport(i,["inbound-rtp"],!1,e.id),o=[...a.consumerStreamMap.values()][0],c=r?this.getConsumerStatsFromParsedConsumerStats(a,o,e.id):void 0;for(const d of i.values())switch(d.type){case"inbound-rtp":{this.inboundConsumerMap.set(d.id,e.id);break}}return c}deregisterProducer(e){this.producerMap.delete(e.id),this.outboundProducerMap.forEach((r,i)=>{r===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.consumerMap.delete(e.id),this.inboundConsumerMap.forEach((r,i)=>{r===e.id&&this.inboundConsumerMap.delete(i)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}parseRTCReport(e,r=[],i=!1,a=void 0,o=void 0){var C,_,I,M,x,N,$,q,ee,Qe,is,ei,ns;const c=e,d=new sm,l=r.length?new Set(r):void 0,h=[],p=[],f=[],T=new Map,E=new Map;for(const k of c.values()){if(l){if(l.size===0)break;if(l.has(k.type))i&&l.delete(k.type);else continue}switch(k.type){case"local-candidate":{h.push(this.getIceCandidateStats(k));break}case"remote-candidate":{p.push(this.getIceCandidateStats(k));break}case"candidate-pair":{const{nominated:S}=k,{selected:P}=k,U=k,Te={nominated:S!=null?S:P,currentRoundTripTime:U.currentRoundTripTime,totalRoundTripTime:U.totalRoundTripTime,bytesReceived:U.bytesReceived,bytesSent:U.bytesSent,availableOutgoingBitrate:U.availableOutgoingBitrate,availableIncomingBitrate:U.availableIncomingBitrate,lastPacketReceivedTimestamp:U.lastPacketReceivedTimestamp,lastPacketSentTimestamp:U.lastPacketSentTimestamp,localCandidateId:U.localCandidateId,remoteCandidateId:U.remoteCandidateId,bytesDiscardedOnSend:U.bytesDiscardedOnSend,packetsSent:U.packetsSent,packetsReceived:U.packetsReceived,packetsDiscardedOnSend:U.packetsDiscardedOnSend};f.push(Te),(k.nominated===!0||k.selected===!0)&&(d.candidatePair=Te);break}case"transport":{const S=k;o&&(o.producing&&(this.overallProducingTransportsStatsMap[o.id]||(this.overallProducingTransportsStatsMap[o.id]={totalPacketsSent:0})),o.consuming&&(this.overallConsumingTransportsStatsMap[o.id]||(this.overallConsumingTransportsStatsMap[o.id]={totalPacketsReceived:0})));const P={bytesReceived:S.bytesReceived,bytesSent:S.bytesSent,packetsSent:S.packetsSent,packetsReceived:S.packetsReceived,dtlsCipher:S.dtlsCipher,dtlsState:S.dtlsState,iceRole:S.iceRole};if(d.transport=P,o){if(o.producing){const U=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,U,P)}if(o.consuming){const U=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,U,P)}}break}case"remote-inbound-rtp":{const S=k,P={jitter:S.jitter,fractionLost:S.fractionLost,roundTripTime:S.roundTripTime,roundTripTimeMeasurements:S.roundTripTimeMeasurements,totalRoundTripTime:S.totalRoundTripTime,packetsLost:S.packetsLost};d.remoteInboundRtp.set(S.localId,P);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(k.id))break;const S=k,P=a||this.outboundProducerMap.get(k.id),U=this.pausedProducerMap.get(P);if(U){if(U.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const Te=this.overallProducersStatsMap[P];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.outboundProducerMap.has(k.id)){d.staleProducerStreamMap=!0;break}const be=this.callStatsInstance.producers.get(P);if(((C=be==null?void 0:be.track)==null?void 0:C.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const O={bytesSent:S.bytesSent,packetsSent:S.packetsSent,nackCount:S.nackCount,ssrc:S.ssrc,mid:S.mid,active:S.active,codecId:S.codecId,headerBytesSent:S.headerBytesSent||0,totalPacketSendDelay:S.totalPacketSendDelay||0};if(S.mediaType==="video"||S.kind==="video"){const R=S,Ne={frameHeight:R.frameHeight,frameWidth:R.frameWidth,framesEncoded:R.framesEncoded,framesDropped:R.framesDropped?R.framesDropped:R.droppedFrames,framesPerSecond:R.framesPerSecond?R.framesPerSecond:R.framerateMean,framesSent:R.framesSent,keyFramesEncoded:R.keyFramesEncoded,firCount:R.firCount,encoderImplementation:R.encoderImplementation,hugeFramesSent:R.hugeFramesSent,pliCount:R.pliCount,qpSum:R.qpSum,qualityLimitationReason:R.qualityLimitationReason,qualityLimitationDurations:R.qualityLimitationDurations,qualityLimitationResolutionChanges:R.qualityLimitationResolutionChanges,totalEncodeTime:R.totalEncodeTime,totalPacketSendDelay:R.totalEncodeTime,retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,scalabilityMode:R.scalabilityMode,powerEfficientEncoder:R.powerEfficientEncoder,...O};d.outboundVideoRtp.set(k.id,Ne),d.producerStreamMap.get(P).outboundVideoRtpId.push(k.id),this.processOutboundProducerVideoStats(P,Te,Ne)}else if(S.mediaType==="audio"||S.kind==="audio"){const R=S,Ne={retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,...O};d.outboundAudioRtp.set(k.id,Ne),d.producerStreamMap.get(P).outboundAudioRtpId.push(k.id),this.processOutboundProducerAudioStats(P,Te,Ne)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(k.id))break;const S=k,P=a||this.inboundConsumerMap.get(k.id),U=this.pausedConsumerMap.get(P);if(U){if(U.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(S.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const Te=this.overallConsumersStatsMap[P];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.inboundConsumerMap.has(k.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(P)||d.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const be={bytesReceived:S.bytesReceived,packetsReceived:S.packetsReceived,packetsLost:S.packetsLost>=0?S.packetsLost:0,jitter:S.jitter,nackCount:S.nackCount,jitterBufferDelay:S.jitterBufferDelay,jitterBufferEmittedCount:S.jitterBufferEmittedCount,lastPacketReceivedTimestamp:S.lastPacketReceivedTimestamp,ssrc:S.ssrc,mid:S.mid,codecId:S.codecId,headerBytesReceived:S.headerBytesReceived||0,packetsDiscarded:S.packetsDiscarded||0,jitterBufferMinimumDelay:S.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:S.jitterBufferTargetDelay||0};if(S.mediaType==="video"||S.kind==="video"){const O=S,R={frameHeight:O.frameHeight,frameWidth:O.frameWidth,framesDecoded:O.framesDecoded,framesDropped:O.framesDropped?O.framesDropped:O.droppedFrames,framesPerSecond:O.framesPerSecond?O.framesPerSecond:O.framerateMean,framesReceived:O.framesReceived,keyFramesDecoded:O.keyFramesDecoded,firCount:O.firCount,decoderImplementation:O.decoderImplementation,pliCount:O.pliCount,totalProcessingDelay:O.totalProcessingDelay,qpSum:O.qpSum||0,totalAssemblyTime:O.totalAssemblyTime||0,totalDecodeTime:O.totalDecodeTime||0,totalFreezesDuration:O.totalFreezesDuration||0,totalInterFrameDelay:O.totalInterFrameDelay||0,totalPausesDuration:O.totalPausesDuration||0,totalSquaredInterFrameDelay:O.totalSquaredInterFrameDelay||0,freezeCount:O.freezeCount||0,pauseCount:O.pauseCount||0,powerEfficientDecoder:O.powerEfficientDecoder,...be};R.score=em({frameWidth:R.frameWidth||0,framesDecoded:(R.framesDecoded||0)-(((_=this.videoConsumerToStatsMap.get(P))==null?void 0:_.framesDecoded)||0),framesPerSecond:R.framesPerSecond||0,packetsLost:(R.packetsLost||0)-(((I=this.videoConsumerToStatsMap.get(P))==null?void 0:I.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((M=this.videoConsumerToStatsMap.get(P))==null?void 0:M.packetsReceived)||0),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),E.set(P,{score:+(R.score*10).toFixed(),frameWidth:R.frameWidth||0,frameHeight:R.frameHeight||0,framesPerSecond:R.framesPerSecond||0,packetsLostPercentage:ld({packetsLost:(R.packetsLost||0)-(((x=this.videoConsumerToStatsMap.get(P))==null?void 0:x.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((N=this.videoConsumerToStatsMap.get(P))==null?void 0:N.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((R.bytesReceived||0)-((($=this.videoConsumerToStatsMap.get(P))==null?void 0:$.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,R),d.inboundVideoRtp.set(k.id,R),d.consumerStreamMap.get(P).inboundVideoRtpId.push(k.id),this.processInboundConsumerVideoStats(P,Te,R)}else if(S.mediaType==="audio"||S.kind==="audio"){const O=S,R={audioLevel:O.audioLevel,concealedSamples:O.concealedSamples,concealmentEvents:O.concealmentEvents,totalAudioEnergy:O.totalAudioEnergy,totalSamplesDuration:O.totalSamplesDuration,totalSamplesReceived:O.totalSamplesReceived,fecPacketsDiscarded:O.fecPacketsDiscarded||0,fecPacketsReceived:O.fecPacketsReceived||0,insertedSamplesForDeceleration:O.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:O.removedSamplesForAcceleration||0,silentConcealedSamples:O.silentConcealedSamples||0,playoutId:O.playoutId,...be};R.score=Zg({concealmentEvents:(R.concealmentEvents||0)-(((q=this.audioConsumerToStatsMap.get(P))==null?void 0:q.concealmentEvents)||0),packetsLost:(R.packetsLost||0)-(((ee=this.audioConsumerToStatsMap.get(P))==null?void 0:ee.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((Qe=this.audioConsumerToStatsMap.get(P))==null?void 0:Qe.packetsReceived)||0),jitter:R.jitter||0}),E.set(P,{score:+(R.score*10).toFixed(),packetsLostPercentage:ld({packetsLost:(R.packetsLost||0)-(((is=this.audioConsumerToStatsMap.get(P))==null?void 0:is.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((ei=this.audioConsumerToStatsMap.get(P))==null?void 0:ei.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((R.bytesReceived||0)-(((ns=this.audioConsumerToStatsMap.get(P))==null?void 0:ns.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,R),d.inboundAudioRtp.set(k.id,R),d.consumerStreamMap.get(P).inboundAudioRtpId.push(k.id),this.processInboundConsumerAudioStats(P,Te,R)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}}}if(d.producerStreamMap.forEach((k,S)=>{var P,U,Te,be,O,R,Ne,xs,Oa,Na,Va,La,xa,Ua,$a,Fa,Ba,Ha,qa,ja,Ga,Wa,Ja;if(k.outboundVideoRtpId.length>0){const oe=[];k.outboundVideoRtpId.forEach(Bl=>{oe.push(d.outboundVideoRtp.get(Bl))});const X=this.getWorkingSimulcastVideoStats(oe);X.score=Qg({frameWidth:X.frameWidth||0,framesPerSecond:X.framesPerSecond||0,jitter:((P=X.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsSent:(X.packetsSent||0)-(((U=this.videoProducerToStatsMap.get(S))==null?void 0:U.packetsSent)||0),packetsLost:(((Te=X.remoteData)==null?void 0:Te.packetsLost)||0)-(((O=(be=this.videoProducerToStatsMap.get(S))==null?void 0:be.remoteData)==null?void 0:O.packetsLost)||0),framesEncoded:(X.framesEncoded||0)-(((R=this.videoProducerToStatsMap.get(S))==null?void 0:R.framesEncoded)||0)}),T.set(S,{score:+(X.score*10).toFixed(),frameWidth:X.frameWidth||0,frameHeight:X.frameHeight||0,framesPerSecond:X.framesPerSecond||0,jitter:((Ne=X.remoteData)==null?void 0:Ne.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsLostPercentage:dd({packetsSent:(X.packetsSent||0)-(((xs=this.videoProducerToStatsMap.get(S))==null?void 0:xs.packetsSent)||0),packetsLost:(((Oa=X.remoteData)==null?void 0:Oa.packetsLost)||0)-(((Va=(Na=this.videoProducerToStatsMap.get(S))==null?void 0:Na.remoteData)==null?void 0:Va.packetsLost)||0)}),bitrate:((X.bytesSent||0)-(((La=this.videoProducerToStatsMap.get(S))==null?void 0:La.bytesSent)||0))*8/7,cpuLimitations:X.qualityLimitationReason==="cpu",bandwidthLimitations:X.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(S,X)}else if(k.outboundAudioRtpId.length>0){const oe=d.outboundAudioRtp.get(k.outboundAudioRtpId[0]);oe.score=Yg({packetsSent:(oe.packetsSent||0)-(((xa=this.audioProducerToStatsMap.get(S))==null?void 0:xa.packetsSent)||0),packetsLost:(((Ua=oe.remoteData)==null?void 0:Ua.packetsLost)||0)-(((Fa=($a=this.audioProducerToStatsMap.get(S))==null?void 0:$a.remoteData)==null?void 0:Fa.packetsLost)||0),jitter:((Ba=oe.remoteData)==null?void 0:Ba.jitter)||0}),T.set(S,{score:+(oe.score*10).toFixed(),bitrate:((oe.bytesSent||0)-(((Ha=this.audioProducerToStatsMap.get(S))==null?void 0:Ha.bytesSent)||0))*8/7,packetsLostPercentage:dd({packetsSent:(oe.packetsSent||0)-(((qa=this.audioProducerToStatsMap.get(S))==null?void 0:qa.packetsSent)||0),packetsLost:(((ja=oe.remoteData)==null?void 0:ja.packetsLost)||0)-(((Wa=(Ga=this.audioProducerToStatsMap.get(S))==null?void 0:Ga.remoteData)==null?void 0:Wa.packetsLost)||0)}),jitter:((Ja=oe.remoteData)==null?void 0:Ja.jitter)||0,isScreenShare:this.screenShareProducers.has(S)}),this.audioProducerToStatsMap.set(S,oe)}}),f.forEach(k=>{const S=h.find(U=>U.id===k.localCandidateId?(k.localCandidateId=U.id,U):null),P=p.find(U=>U.id===k.remoteCandidateId?(k.remoteCandidateId=U.id,U):null);S&&(k.localCandidateType=S.type,k.localCandidateAddress=Jr(S.address),k.localCandidatePort=S.port,k.localCandidateProtocol=S.protocol,k.localCandidateUrl=S.url,k.localCandidateNetworkType=S.networkType,k.localCandidateRelatedAddress=Jr(S.relatedAddress),k.localCandidateRelatedPort=S.relatedPort),P&&(k.remoteCandidateType=P.type,k.remoteCandidateAddress=Jr(P.address),k.remoteCandidatePort=P.port,k.remoteCandidateProtocol=P.protocol,k.remoteCandidateUrl=P.url)}),d.candidatePair&&(d.transport?(d.transport.bytesReceived=d.candidatePair.bytesReceived,d.transport.bytesSent=d.candidatePair.bytesSent,d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=f),d.transport&&!d.transport.roundTripTime){let k=0,S=0;d.remoteInboundRtp.forEach((P,U)=>{P.roundTripTime&&P.roundTripTime>k&&(k=P.roundTripTime,S=P.totalRoundTripTime)}),d.transport.roundTripTime=k,d.transport.totalRoundTripTime=S}if(E.size>0)try{this.observer.emit("consumer_score",E)}catch(k){}if(T.size>0)try{this.observer.emit("producer_score",T)}catch(k){}return d}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,a)=>{const o=this.producerMap.get(a),c=o.track.getSettings(),d=i.outboundVideoRtpId.map(h=>{const p=e.outboundVideoRtp.get(h);return p.frameHeight||(p.frameHeight=c.height,p.frameWidth=c.width,p.framesPerSecond=c.frameRate),p}),l={producerId:a,appData:o.appData,videoStats:d,audioStats:i.outboundAudioRtpId.map(h=>e.outboundAudioRtp.get(h))};r.push(l)})}catch(i){console.error("getProducersReport: ",i,e)}return r}getConsumerStatsFromParsedConsumerStats(e,r,i){let a;try{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(i),l=r==null?void 0:r.inboundVideoRtpId.map(h=>{const f=this.consumerMap.get(i).track.getSettings(),T=e.inboundVideoRtp.get(h);return T.frameHeight||(T.frameHeight=f.height,T.frameWidth=f.width,T.framesPerSecond=f.frameRate),T});a={consumerId:i,peerId:o,producerId:c,appData:d,videoStats:l,audioStats:r==null?void 0:r.inboundAudioRtpId.map(h=>e.inboundAudioRtp.get(h))}}catch(o){console.error("getConsumerStatsFromParsedConsumerStats: ",o,e)}return a}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((i,a)=>{r.push(this.getConsumerStatsFromParsedConsumerStats(e,i,a))})}catch(i){console.error("getConsumerStatsFromReport: ",i,e)}return r}}class vv extends im{}function ud(s,t,e,r){if(s!=null&&s.logger&&s.logger.error("Callstats::handleError",{error:r}),typeof e=="function"&&r instanceof t)e.call(null,r,s);else throw r}function Bh(s,t,e){const r=s.value;return s.value=function(...i){try{const a=r.apply(this,i);return a&&a instanceof Promise?a.catch(o=>{ud(this,t,e,o)}):a}catch(a){ud(this,t,e,a)}return null},s}const z=(s,t)=>(e,r,i)=>{const a=i.value;return i.value=function(...o){try{const c=a.apply(this,o);return c&&c instanceof Promise?c.catch(d=>{ud(this,s,t,d)}):c}catch(c){ud(this,s,t,c)}return null},i},Sv=(s,t)=>(e,r,i)=>{if(i)return Bh(i,s,t);for(const a of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,a);o.value instanceof Function&&Object.defineProperty(e.prototype,a,Bh(o,s,t))}};var J=globalThis&&globalThis.__decorate||function(s,t,e,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(s,t,e,r);else for(var c=s.length-1;c>=0;c--)(o=s[c])&&(a=(i<3?o(a):i>3?o(t,e,a):o(t,e))||a);return i>3&&a&&Object.defineProperty(t,e,a),a};const K=console;let G=class extends nt{constructor(e="https://api.testingv3.dyte.in",r="Blink",i=oo.PROD,a,o,c,d){super();u(this,"observer");u(this,"eventHandler");u(this,"measurements");u(this,"producingTransport");u(this,"consumingTransport");u(this,"producers",new Map);u(this,"consumers",new Map);u(this,"iceServers");u(this,"connectionInfoPromise");u(this,"pingStatsTimeout");u(this,"logger");u(this,"env");u(this,"apiHostnames");u(this,"peerId");u(this,"consumerSharedMediaStatesMap",new Map);u(this,"currentUserMediaStates",{});switch(this.env=i,this.apiHostnames=d,this.logger=o,this.peerId=c,this.eventHandler=new rv({logger:o,peerId:c,apiHostnames:d}),this.logger.debug("callStats::engineName: ",{engineName:r}),r){case"Blink":this.measurements=new Tv;break;case"Gecko":this.measurements=new im;break;case"WebKit":this.measurements=new vv;break;default:throw Error(`Unknown engineName! ${r}`)}this.measurements.callStatsInstance=this,this.registerProducer=this.registerProducer.bind(this),this.registerConsumer=this.registerConsumer.bind(this),this.observer=new nt,this.measurements.observer.on("consumer_score",l=>{o.debug(`callStats::consumer_score ${[...l.entries()]}`),this.eventHandler.emit("consumer_score",l)}),this.measurements.observer.on("producer_score",l=>{o.debug(`callStats::producer_score ${[...l.entries()]}`),this.eventHandler.emit("producer_score",l)})}registerIceServers(e){this.iceServers=e}registerConsumer(e){var r;this.consumerSharedMediaStatesMap.has(e.id)||this.consumerSharedMediaStatesMap.set(e.id,{}),this.consumers.set(e.id,e),this.measurements.registerConsumer(e),this.logger.debug("callStats::registerConsumer",{consumerId:e.id,consumerkind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.on("close",this.deRegisterConsumer.bind(this,e))}registerProducer(e){var r;this.producers.set(e.id,e),this.measurements.registerProducer(e),this.logger.debug("callStats::registerProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.on("close",this.deRegisterProducer.bind(this,e))}sendConsumerSharedMediaStateEvent(e,r){this.consumerSharedMediaStatesMap.has(e)||this.consumerSharedMediaStatesMap.set(e,{});const i=this.consumerSharedMediaStatesMap.get(e);this.consumerSharedMediaStatesMap.set(e,Object.assign(i,r))}registerProducingTransport(e){var i;this.producingTransport=e,e.on("close",this.disconnectProducingTransport.bind(this,e)),e.on("disconnect",this.disconnectProducingTransport.bind(this,e)),Array.from(((i=e._producers)==null?void 0:i.values())||[]).forEach(a=>{this.registerProducer(a)}),e.on("newproducer",this.registerProducer)}registerConsumingTransport(e){var i;this.consumingTransport=e,e.on("close",this.disconnectConsumingTransport.bind(this,e)),e.on("disconnect",this.disconnectConsumingTransport.bind(this,e)),Array.from(((i=e._consumers)==null?void 0:i.values())||[]).forEach(a=>{this.registerConsumer(a)}),e.on("newconsumer",this.registerConsumer)}deRegisterConsumer(e){this.consumers.delete(e.id)}deRegisterProducer(e){var r;this.producers.delete(e.id),this.logger.debug("callStats::deRegisterProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)})}disconnectConsumingTransport(){this.consumingTransport=void 0}disconnectProducingTransport(){this.producingTransport=void 0}callEvent(e){this.eventHandler.callEvent(e)}sendPreCallTestBeginEvent(e=!1,r){this.connectionInfoPromise=this.measurements.getNetworkInfo(this.iceServers,e),this.eventHandler.callEvent({event:D.PRECALL_TEST_BEGIN,timestamp:r}),this.connectionInfoPromise&&this.connectionInfoPromise.then(i=>{this.eventHandler.callEvent({event:D.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:i},timestamp:r})})}sendScreenShareToggleEvent(e,r=null,i){this.currentUserMediaStates.screen=e,this.eventHandler.callEvent({event:e?D.SCREENSHARE_STARTED:D.SCREENSHARE_STOPPED,metaData:{ssrc:r},timestamp:i})}sendScreenShareRequestedEvent(e){this.eventHandler.callEvent({event:D.SCREENSHARE_START_REQUESTED,timestamp:e})}sendActiveSpeakerEvent(e,r){this.eventHandler.callEvent({event:D.DOMINANT_SPEAKER,metaData:{peerId:e},timestamp:r})}devices(e,r,i){this.eventHandler.callEvent({event:e===Ht.AUDIO&&D.AUDIO_DEVICES_UPDATES||e===Ht.VIDEO&&D.VIDEO_DEVICES_UPDATES||e===Ht.SPEAKER&&D.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:r},timestamp:i})}selectedDevice(e,r,i){this.eventHandler.callEvent({event:e===Ht.AUDIO&&D.SELECTED_MICROHPONE_UPDATE||e===Ht.VIDEO&&D.SELECTED_CAMERA_UPDATE||e===Ht.SPEAKER&&D.SELECTED_SPEAKER_UPDATE,metaData:{device:r},timestamp:i})}mediaPermission(e,r,i){this.eventHandler.callEvent({event:D.MEDIA_PERMISSION,metaData:{deviceType:e,permission:r},timestamp:i})}mediaPlaybackFailed(e,r){this.eventHandler.callEvent({event:e===Ht.AUDIO&&D.AUDIO_PLAY_FAILED||e===Ht.VIDEO&&D.VIDEO_PLAY_FAILED,metaData:{deviceType:e},timestamp:r})}mediaTrackMuted(e,r){this.eventHandler.callEvent({event:e===Ht.AUDIO&&D.AUDIO_TRACK_MUTED||e===Ht.VIDEO&&D.VIDEO_TRACK_MUTED,metaData:{deviceType:e},timestamp:r})}tabChanged(e,r){this.eventHandler.callEvent({event:D.TAB_CHANGE,metaData:{isMeetingsTabActive:e},timestamp:r})}browserBackgrounded(e){this.eventHandler.callEvent({event:D.BROWSER_BACKGROUNDED,timestamp:e})}browserForegrounded(e){this.eventHandler.callEvent({event:D.BROWSER_FOREGROUNDED,timestamp:e})}legacySwitch(e,r){this.eventHandler.callEvent({event:D.LEGACY_SWITCH,metadata:{on:e},timestamp:r})}async getPreCallTestResults(){return this.connectionInfoPromise}sendCallJoinBeginEvent(e,r){e={...e,meetingEnv:this.env},e.deviceInfo={...e.deviceInfo,userAgent:navigator.userAgent,cpus:navigator.hardwareConcurrency,memory:navigator.deviceMemory},this.eventHandler.callEvent({event:D.CALL_JOIN_BEGIN,metaData:{peerMetaData:e},timestamp:r})}sendNetworkQualityTestBeginEvent(e,r){this.eventHandler.callEvent({event:D.NET_QUALITY_TEST_BEGIN,timestamp:r}),new Promise(async(a,o)=>{const c=[];try{for(const d of e)try{if(d.iceServers&&d.iceServers.length>0){const l=await this.measurements.getNetworkQuality(d.iceServers);c.push({...d,networkResults:l})}}catch(l){console.warn("Error handling ",l)}a({regionData:c})}catch(d){console.warn("Error in callstats, ",d),o(d)}}).then(a=>{this.eventHandler.callEvent({event:D.NET_QUALITY_TEST_END,timestamp:r,metaData:a})})}sendWebSocketConnectedEvent(e){this.eventHandler.callEvent({event:D.WEBSOCKET_CONNECTED,timestamp:e})}sendTransportConnectedEvent(e){this.eventHandler.callEvent({event:D.TRANSPORT_CONNECTED,timestamp:e})}sendAudioToggleEvent(e,r){this.currentUserMediaStates.audio=e;let i;e?i=D.AUDIO_ON:i=D.AUDIO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendVideoToggleEvent(e,r){this.currentUserMediaStates.video=e;let i;e?i=D.VIDEO_ON:i=D.VIDEO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendParticipantRoleToggleEvent(e,r){this.eventHandler.callEvent({event:D.PARTICIPANT_ROLE,timestamp:r,metaData:e})}startPingStats(e=7e3){this.sendPingStatsEvent(!1,new Date),this.pingStatsTimeout=setInterval(this.sendPingStatsEvent.bind(this),e)}stopPingStats(){clearInterval(this.pingStatsTimeout)}async sendPingStatsEvent(e=!0,r){var c,d;let i,a;if(this.producingTransport&&(i=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),!i||!((c=i==null?void 0:i.producerReport)!=null&&c.length))){this.logger.debug("callStats::sendPingStatsEvent::staleProducingTransport",{disclaimer:"Stale producer? Regenerating Stream Maps!"});const l=await this.measurements.getProducersReport([...this.producers.values()]);i&&l?i.producerReport=l:(i=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),(!i||!(i!=null&&i.producerReport))&&this.logger.debug("callStats::sendPingStatsEvent::noProducingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}if(this.consumingTransport&&(a=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),!a||!((d=a.consumerReport)!=null&&d.length))){this.logger.debug("callStats::sendPingStatsEvent::staleConsumingTransport",{disclaimer:"Stale consumer? Regenerating Stream Maps!"});const l=await this.measurements.getConsumersReport([...this.consumers.values()]);a&&l?a.consumerReport=l:(a=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),(!a||!a.consumerReport)&&this.logger.debug("callStats::sendPingStatsEvent::noConsumingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}const o={producingTransportStats:i?i==null?void 0:i.transportReport:void 0,consumingTransportStats:a?a==null?void 0:a.transportReport:void 0,producerStats:[].concat((i==null?void 0:i.producerReport)||[]).concat((a==null?void 0:a.producerReport)||[]),consumerStats:[].concat((a==null?void 0:a.consumerReport)||[]).concat((i==null?void 0:i.consumerReport)||[])};if(e&&o.producerStats.length===0&&o.consumerStats.length===0){await this.eventHandler.flush();return}this.eventHandler.callEvent({event:D.PING_STAT,metaData:o,timestamp:r})}sendIVSPlayerRebufferEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_REBUFFERING,timestamp:e})}sendIVSPlayerAudioBlockEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_AUDIO_BLOCKED,timestamp:e})}sendIVSPlayerPlaybackBlockedEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:e})}sendIVSPlayerNetworkUnavailableEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:e})}sendIVSPlayerInitializedEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_INITIALIZED,timestamp:e})}sendIVSPlayerWorkerErrorEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_WORKER_ERROR,timestamp:e})}sendIVSPlayerErrorEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_ERROR,timestamp:r,metaData:e})}sendIVSPlayerRecoverableErrorEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:r,metaData:e})}sendIVSPlayerAnalyticsEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_ANALYTICS_EVENT,timestamp:r,metaData:e})}sendIVSPlayerPlaybackRateChangedEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:r,metaData:{updatedPlaybackRate:e}})}sendIVSPlayerQualityChanged(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_QUALITY_CHANGED,timestamp:r,metaData:e})}sendPlayerLiveLatency(e,r){this.eventHandler.callEvent({event:D.LIVESTREAM_LATENCY,timestamp:r,metaData:{latency:e}})}sendDisconnectEvent(e){this.eventHandler.callEvent({event:D.DISCONNECT,timestamp:e})}sendReconnectEvent(e){this.eventHandler.callEvent({event:D.RECONNECT_ATTEMPT,timestamp:e})}expectedVideoResolution(e,r,i){this.eventHandler.callEvent({event:D.EXPECTED_VIDEO_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}expectedScreenshareResolution(e,r,i){this.eventHandler.callEvent({event:D.EXPECTED_SCREENSHARE_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}};J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"registerIceServers",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"registerConsumer",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"registerProducer",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendConsumerSharedMediaStateEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"registerProducingTransport",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"registerConsumingTransport",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"deRegisterConsumer",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"deRegisterProducer",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"disconnectConsumingTransport",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"disconnectProducingTransport",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendPreCallTestBeginEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendScreenShareToggleEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendScreenShareRequestedEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendActiveSpeakerEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"devices",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"selectedDevice",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"mediaPermission",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"mediaPlaybackFailed",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"mediaTrackMuted",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"tabChanged",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"browserBackgrounded",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"browserForegrounded",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"legacySwitch",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"getPreCallTestResults",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendCallJoinBeginEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendNetworkQualityTestBeginEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendWebSocketConnectedEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendTransportConnectedEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendAudioToggleEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendVideoToggleEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendParticipantRoleToggleEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"startPingStats",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"stopPingStats",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendPingStatsEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerRebufferEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerAudioBlockEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerPlaybackBlockedEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerNetworkUnavailableEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerInitializedEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerWorkerErrorEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerErrorEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerRecoverableErrorEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerAnalyticsEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerQualityChanged",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendPlayerLiveLatency",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendDisconnectEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendReconnectEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"expectedVideoResolution",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"expectedScreenshareResolution",null);G=J([Sv(TypeError,(s,t)=>K.error(t,s))],G);const yv=G;class nm extends nt{constructor(){super(...arguments);u(this,"stats");u(this,"peerId");u(this,"backend");u(this,"iceServers");u(this,"initialized",!1);u(this,"stalled",!1);u(this,"ipInformation");u(this,"logger")}async initialize({peerId:e,engineName:r,env:i=oo.PROD,iceServers:a,apiBase:o="https://api.cluster.dyte.in",flags:c,logger:d=console,apiHostnames:l,skipConnectivityChecks:h=!1}){var p,f,T;try{this.peerId=e,this.logger=d,this.ipInformation=await Zu.getIPDetails({peerId:e,apiHostnames:l,logger:d}),this.backend=new yv(o,r,i,c,d,e,l),this.iceServers=a,(p=this.backend)==null||p.registerIceServers(this.iceServers),this.initialized=!0,(T=(f=this.backend)==null?void 0:f.eventHandler)==null||T.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(h)}catch(E){this.logger.error("callStats::CallStatsIntegration: ",{error:E}),this.stallCallStats()}}configureSendTransport(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.registerProducingTransport(e)})}configureRecvTransport(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.registerConsumingTransport(e)})}async candidateRegionalNetworkQualityTest(e){const r=new Date;this.onSafeInitialization(()=>{var i;try{(i=this.backend)==null||i.sendNetworkQualityTestBeginEvent(e,r)}catch(a){this.logger.error("callStats::sendNetworkQualityTestBeginEvent",{error:{reason:a.reason}})}})}async roomJoined(e){const r=new Date;this.onSafeInitialization(()=>{var i,a;(i=this.backend)==null||i.sendCallJoinBeginEvent(e,r),this.backend,(a=this.backend)==null||a.startPingStats()})}audioOff(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendAudioToggleEvent(!1,e)})}audioOn(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendAudioToggleEvent(!0,e)})}videoOff(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendVideoToggleEvent(!1,e)})}videoOn(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendVideoToggleEvent(!0,e)})}callEnded(){const e=new Date;this.onSafeInitialization(()=>{var r,i;(r=this.backend)==null||r.stopPingStats(),(i=this.backend)==null||i.sendDisconnectEvent(e)})}screenShareStart(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendScreenShareToggleEvent(!0,e,r)})}consumerSharedMediaState(e,r){this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendConsumerSharedMediaStateEvent(e,r)})}screenShareStop(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendScreenShareToggleEvent(!1,e,r)})}screenShareRequested(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendScreenShareRequestedEvent(e)})}activeSpeaker(e){if(e!==this.peerId)return;const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendActiveSpeakerEvent(e,r)})}devices(e,r){const i=new Date;this.onSafeInitialization(()=>{var a;(a=this.backend)==null||a.devices(e,r,i)})}selectedDevice(e,r){const i=new Date;this.onSafeInitialization(()=>{var a;(a=this.backend)==null||a.selectedDevice(e,r,i)})}mediaPermission(e,r){const i=new Date;this.onSafeInitialization(()=>{var a;(a=this.backend)==null||a.mediaPermission(e,r,i)})}mediaPlaybackFailed(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaPlaybackFailed(e,r)})}mediaTrackMuted(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaTrackMuted(e,r)})}tabChanged(e=!1){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.tabChanged(e,r)})}browserBackgrounded(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.browserBackgrounded(e)})}browserForegrounded(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.browserForegrounded(e)})}legacySwitch(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.legacySwitch(e,r)})}async startPreCallTest(e=!1){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPreCallTestBeginEvent(e,r)})}onPreCallTestResults(e){return this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.once("precall_end",e)}),e}onReceivingConsumerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_audio_status",e)})}onReceivingConsumerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_video_status",e)})}onReceivingProducerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_audio_status",e)})}onReceivingProducerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_video_status",e)})}onReceivingProducingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producing_transport_status",e)})}onReceivingConsumingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consuming_transport_status",e)})}onProducerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_score",e)})}onConsumerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_score",e)})}onSafeInitialization(e){if(this.initialized)e(this.ipInformation,!1);else if(!this.stalled){const r=i=>{e(i,!0)};return this.once("initialized",r),r}return()=>{}}removeInitializationListener(e){this.removeListener("initialized",e)}stallCallStats(){this.stalled=!0,this.removeAllListeners("initialized")}ivsPlayerEvent(e,r){const i=new Date;this.onSafeInitialization(()=>{var a,o,c,d,l,h,p,f,T,E,C;switch(e){case"PlayerRebuffering":(a=this.backend)==null||a.sendIVSPlayerRebufferEvent(i);break;case"PlayerAudioBlocked":(o=this.backend)==null||o.sendIVSPlayerAudioBlockEvent(i);break;case"PlayerPlaybackBlocked":(c=this.backend)==null||c.sendIVSPlayerPlaybackBlockedEvent(i);break;case"PlayerNetworkUnavailable":(d=this.backend)==null||d.sendIVSPlayerNetworkUnavailableEvent(i);break;case"PlayerInitialized":(l=this.backend)==null||l.sendIVSPlayerInitializedEvent(i);break;case"PlayerWorkerError":(h=this.backend)==null||h.sendIVSPlayerWorkerErrorEvent(i);break;case"PlayerError":(p=this.backend)==null||p.sendIVSPlayerErrorEvent(r,i);break;case"PlayerRecoverableError":(f=this.backend)==null||f.sendIVSPlayerRecoverableErrorEvent(r,i);break;case"PlayerAnalyticsEvent":(T=this.backend)==null||T.sendIVSPlayerAnalyticsEvent(r,i);break;case"PlayerPlaybackRateChanged":(E=this.backend)==null||E.sendIVSPlayerPlaybackRateChangedEvent(r,i);break;case"PlayerQualityChanged":(C=this.backend)==null||C.sendIVSPlayerQualityChanged(r,i);break}})}livestreamLatency(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPlayerLiveLatency(e,r)})}expectedVideoResolution(e,r){const i=new Date;this.onSafeInitialization(()=>{var a;(a=this.backend)==null||a.expectedVideoResolution(e,r,i)})}expectedScreenshareResolution(e,r){const i=new Date;this.onSafeInitialization(()=>{var a;(a=this.backend)==null||a.expectedScreenshareResolution(e,r,i)})}}const Ev=new nm;Ev.setMaxListeners(30);function Pv(){this.__data__=[],this.size=0}function wc(s,t){return s===t||s!==s&&t!==t}function El(s,t){for(var e=s.length;e--;)if(wc(s[e][0],t))return e;return-1}var _v=Array.prototype,Cv=_v.splice;function wv(s){var t=this.__data__,e=El(t,s);if(e<0)return!1;var r=t.length-1;return e==r?t.pop():Cv.call(t,e,1),--this.size,!0}function Rv(s){var t=this.__data__,e=El(t,s);return e<0?void 0:t[e][1]}function bv(s){return El(this.__data__,s)>-1}function kv(s,t){var e=this.__data__,r=El(e,s);return r<0?(++this.size,e.push([s,t])):e[r][1]=t,this}function mr(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}mr.prototype.clear=Pv;mr.prototype.delete=wv;mr.prototype.get=Rv;mr.prototype.has=bv;mr.prototype.set=kv;function Iv(){this.__data__=new mr,this.size=0}function Av(s){var t=this.__data__,e=t.delete(s);return this.size=t.size,e}function Mv(s){return this.__data__.get(s)}function Dv(s){return this.__data__.has(s)}var Ov=typeof global=="object"&&global&&global.Object===Object&&global;const am=Ov;var Nv=typeof self=="object"&&self&&self.Object===Object&&self,Vv=am||Nv||Function("return this")();const Ps=Vv;var Lv=Ps.Symbol;const Vs=Lv;var om=Object.prototype,xv=om.hasOwnProperty,Uv=om.toString,Ka=Vs?Vs.toStringTag:void 0;function $v(s){var t=xv.call(s,Ka),e=s[Ka];try{s[Ka]=void 0;var r=!0}catch(a){}var i=Uv.call(s);return r&&(t?s[Ka]=e:delete s[Ka]),i}var Fv=Object.prototype,Bv=Fv.toString;function Hv(s){return Bv.call(s)}var qv="[object Null]",jv="[object Undefined]",Hh=Vs?Vs.toStringTag:void 0;function tn(s){return s==null?s===void 0?jv:qv:Hh&&Hh in Object(s)?$v(s):Hv(s)}function ss(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var Gv="[object AsyncFunction]",Wv="[object Function]",Jv="[object GeneratorFunction]",Kv="[object Proxy]";function eh(s){if(!ss(s))return!1;var t=tn(s);return t==Wv||t==Jv||t==Gv||t==Kv}var zv=Ps["__core-js_shared__"];const ql=zv;var qh=function(){var s=/[^.]+$/.exec(ql&&ql.keys&&ql.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function Yv(s){return!!qh&&qh in s}var Qv=Function.prototype,Xv=Qv.toString;function sn(s){if(s!=null){try{return Xv.call(s)}catch(t){}try{return s+""}catch(t){}}return""}var Zv=/[\\^$.*+?()[\]{}|]/g,eS=/^\[object .+?Constructor\]$/,tS=Function.prototype,sS=Object.prototype,rS=tS.toString,iS=sS.hasOwnProperty,nS=RegExp("^"+rS.call(iS).replace(Zv,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function aS(s){if(!ss(s)||Yv(s))return!1;var t=eh(s)?nS:eS;return t.test(sn(s))}function oS(s,t){return s==null?void 0:s[t]}function rn(s,t){var e=oS(s,t);return aS(e)?e:void 0}var cS=rn(Ps,"Map");const fo=cS;var dS=rn(Object,"create");const To=dS;function lS(){this.__data__=To?To(null):{},this.size=0}function uS(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var hS="__lodash_hash_undefined__",pS=Object.prototype,gS=pS.hasOwnProperty;function mS(s){var t=this.__data__;if(To){var e=t[s];return e===hS?void 0:e}return gS.call(t,s)?t[s]:void 0}var fS=Object.prototype,TS=fS.hasOwnProperty;function vS(s){var t=this.__data__;return To?t[s]!==void 0:TS.call(t,s)}var SS="__lodash_hash_undefined__";function yS(s,t){var e=this.__data__;return this.size+=this.has(s)?0:1,e[s]=To&&t===void 0?SS:t,this}function Zi(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}Zi.prototype.clear=lS;Zi.prototype.delete=uS;Zi.prototype.get=mS;Zi.prototype.has=vS;Zi.prototype.set=yS;function ES(){this.size=0,this.__data__={hash:new Zi,map:new(fo||mr),string:new Zi}}function PS(s){var t=typeof s;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?s!=="__proto__":s===null}function Pl(s,t){var e=s.__data__;return PS(t)?e[typeof t=="string"?"string":"hash"]:e.map}function _S(s){var t=Pl(this,s).delete(s);return this.size-=t?1:0,t}function CS(s){return Pl(this,s).get(s)}function wS(s){return Pl(this,s).has(s)}function RS(s,t){var e=Pl(this,s),r=e.size;return e.set(s,t),this.size+=e.size==r?0:1,this}function fr(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}fr.prototype.clear=ES;fr.prototype.delete=_S;fr.prototype.get=CS;fr.prototype.has=wS;fr.prototype.set=RS;var bS=200;function kS(s,t){var e=this.__data__;if(e instanceof mr){var r=e.__data__;if(!fo||r.length<bS-1)return r.push([s,t]),this.size=++e.size,this;e=this.__data__=new fr(r)}return e.set(s,t),this.size=e.size,this}function Es(s){var t=this.__data__=new mr(s);this.size=t.size}Es.prototype.clear=Iv;Es.prototype.delete=Av;Es.prototype.get=Mv;Es.prototype.has=Dv;Es.prototype.set=kS;function IS(s,t){for(var e=-1,r=s==null?0:s.length;++e<r&&t(s[e],e,s)!==!1;);return s}var AS=function(){try{var s=rn(Object,"defineProperty");return s({},"",{}),s}catch(t){}}();const hd=AS;function th(s,t,e){t=="__proto__"&&hd?hd(s,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):s[t]=e}var MS=Object.prototype,DS=MS.hasOwnProperty;function cm(s,t,e){var r=s[t];(!(DS.call(s,t)&&wc(r,e))||e===void 0&&!(t in s))&&th(s,t,e)}function Rc(s,t,e,r){var i=!e;e||(e={});for(var a=-1,o=t.length;++a<o;){var c=t[a],d=r?r(e[c],s[c],c,e,s):void 0;d===void 0&&(d=s[c]),i?th(e,c,d):cm(e,c,d)}return e}function OS(s,t){for(var e=-1,r=Array(s);++e<s;)r[e]=t(e);return r}function Ls(s){return s!=null&&typeof s=="object"}var NS="[object Arguments]";function jh(s){return Ls(s)&&tn(s)==NS}var dm=Object.prototype,VS=dm.hasOwnProperty,LS=dm.propertyIsEnumerable,xS=jh(function(){return arguments}())?jh:function(s){return Ls(s)&&VS.call(s,"callee")&&!LS.call(s,"callee")};const vo=xS;var US=Array.isArray;const Vt=US;function $S(){return!1}var lm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Gh=lm&&typeof module=="object"&&module&&!module.nodeType&&module,FS=Gh&&Gh.exports===lm,Wh=FS?Ps.Buffer:void 0,BS=Wh?Wh.isBuffer:void 0,HS=BS||$S;const Ca=HS;var qS=9007199254740991,jS=/^(?:0|[1-9]\d*)$/;function sh(s,t){var e=typeof s;return t=t==null?qS:t,!!t&&(e=="number"||e!="symbol"&&jS.test(s))&&s>-1&&s%1==0&&s<t}var GS=9007199254740991;function rh(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=GS}var WS="[object Arguments]",JS="[object Array]",KS="[object Boolean]",zS="[object Date]",YS="[object Error]",QS="[object Function]",XS="[object Map]",ZS="[object Number]",ey="[object Object]",ty="[object RegExp]",sy="[object Set]",ry="[object String]",iy="[object WeakMap]",ny="[object ArrayBuffer]",ay="[object DataView]",oy="[object Float32Array]",cy="[object Float64Array]",dy="[object Int8Array]",ly="[object Int16Array]",uy="[object Int32Array]",hy="[object Uint8Array]",py="[object Uint8ClampedArray]",gy="[object Uint16Array]",my="[object Uint32Array]",me={};me[oy]=me[cy]=me[dy]=me[ly]=me[uy]=me[hy]=me[py]=me[gy]=me[my]=!0;me[WS]=me[JS]=me[ny]=me[KS]=me[ay]=me[zS]=me[YS]=me[QS]=me[XS]=me[ZS]=me[ey]=me[ty]=me[sy]=me[ry]=me[iy]=!1;function fy(s){return Ls(s)&&rh(s.length)&&!!me[tn(s)]}function ih(s){return function(t){return s(t)}}var um=typeof exports=="object"&&exports&&!exports.nodeType&&exports,co=um&&typeof module=="object"&&module&&!module.nodeType&&module,Ty=co&&co.exports===um,jl=Ty&&am.process,vy=function(){try{var s=co&&co.require&&co.require("util").types;return s||jl&&jl.binding&&jl.binding("util")}catch(t){}}();const wa=vy;var Jh=wa&&wa.isTypedArray,Sy=Jh?ih(Jh):fy;const _l=Sy;var yy=Object.prototype,Ey=yy.hasOwnProperty;function hm(s,t){var e=Vt(s),r=!e&&vo(s),i=!e&&!r&&Ca(s),a=!e&&!r&&!i&&_l(s),o=e||r||i||a,c=o?OS(s.length,String):[],d=c.length;for(var l in s)(t||Ey.call(s,l))&&!(o&&(l=="length"||i&&(l=="offset"||l=="parent")||a&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||sh(l,d)))&&c.push(l);return c}var Py=Object.prototype;function Cl(s){var t=s&&s.constructor,e=typeof t=="function"&&t.prototype||Py;return s===e}function pm(s,t){return function(e){return s(t(e))}}var _y=pm(Object.keys,Object);const Cy=_y;var wy=Object.prototype,Ry=wy.hasOwnProperty;function gm(s){if(!Cl(s))return Cy(s);var t=[];for(var e in Object(s))Ry.call(s,e)&&e!="constructor"&&t.push(e);return t}function bc(s){return s!=null&&rh(s.length)&&!eh(s)}function wl(s){return bc(s)?hm(s):gm(s)}function by(s,t){return s&&Rc(t,wl(t),s)}function ky(s){var t=[];if(s!=null)for(var e in Object(s))t.push(e);return t}var Iy=Object.prototype,Ay=Iy.hasOwnProperty;function My(s){if(!ss(s))return ky(s);var t=Cl(s),e=[];for(var r in s)r=="constructor"&&(t||!Ay.call(s,r))||e.push(r);return e}function kc(s){return bc(s)?hm(s,!0):My(s)}function Dy(s,t){return s&&Rc(t,kc(t),s)}var mm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Kh=mm&&typeof module=="object"&&module&&!module.nodeType&&module,Oy=Kh&&Kh.exports===mm,zh=Oy?Ps.Buffer:void 0,Yh=zh?zh.allocUnsafe:void 0;function fm(s,t){if(t)return s.slice();var e=s.length,r=Yh?Yh(e):new s.constructor(e);return s.copy(r),r}function Tm(s,t){var e=-1,r=s.length;for(t||(t=Array(r));++e<r;)t[e]=s[e];return t}function Ny(s,t){for(var e=-1,r=s==null?0:s.length,i=0,a=[];++e<r;){var o=s[e];t(o,e,s)&&(a[i++]=o)}return a}function vm(){return[]}var Vy=Object.prototype,Ly=Vy.propertyIsEnumerable,Qh=Object.getOwnPropertySymbols,xy=Qh?function(s){return s==null?[]:(s=Object(s),Ny(Qh(s),function(t){return Ly.call(s,t)}))}:vm;const nh=xy;function Uy(s,t){return Rc(s,nh(s),t)}function Sm(s,t){for(var e=-1,r=t.length,i=s.length;++e<r;)s[i+e]=t[e];return s}var $y=pm(Object.getPrototypeOf,Object);const ah=$y;var Fy=Object.getOwnPropertySymbols,By=Fy?function(s){for(var t=[];s;)Sm(t,nh(s)),s=ah(s);return t}:vm;const ym=By;function Hy(s,t){return Rc(s,ym(s),t)}function Em(s,t,e){var r=t(s);return Vt(s)?r:Sm(r,e(s))}function iu(s){return Em(s,wl,nh)}function qy(s){return Em(s,kc,ym)}var jy=rn(Ps,"DataView");const nu=jy;var Gy=rn(Ps,"Promise");const au=Gy;var Wy=rn(Ps,"Set");const En=Wy;var Jy=rn(Ps,"WeakMap");const ou=Jy;var Xh="[object Map]",Ky="[object Object]",Zh="[object Promise]",ep="[object Set]",tp="[object WeakMap]",sp="[object DataView]",zy=sn(nu),Yy=sn(fo),Qy=sn(au),Xy=sn(En),Zy=sn(ou),ti=tn;(nu&&ti(new nu(new ArrayBuffer(1)))!=sp||fo&&ti(new fo)!=Xh||au&&ti(au.resolve())!=Zh||En&&ti(new En)!=ep||ou&&ti(new ou)!=tp)&&(ti=function(s){var t=tn(s),e=t==Ky?s.constructor:void 0,r=e?sn(e):"";if(r)switch(r){case zy:return sp;case Yy:return Xh;case Qy:return Zh;case Xy:return ep;case Zy:return tp}return t});const Ra=ti;var eE=Object.prototype,tE=eE.hasOwnProperty;function sE(s){var t=s.length,e=new s.constructor(t);return t&&typeof s[0]=="string"&&tE.call(s,"index")&&(e.index=s.index,e.input=s.input),e}var rE=Ps.Uint8Array;const pd=rE;function oh(s){var t=new s.constructor(s.byteLength);return new pd(t).set(new pd(s)),t}function iE(s,t){var e=t?oh(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.byteLength)}var nE=/\w*$/;function aE(s){var t=new s.constructor(s.source,nE.exec(s));return t.lastIndex=s.lastIndex,t}var rp=Vs?Vs.prototype:void 0,ip=rp?rp.valueOf:void 0;function oE(s){return ip?Object(ip.call(s)):{}}function Pm(s,t){var e=t?oh(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.length)}var cE="[object Boolean]",dE="[object Date]",lE="[object Map]",uE="[object Number]",hE="[object RegExp]",pE="[object Set]",gE="[object String]",mE="[object Symbol]",fE="[object ArrayBuffer]",TE="[object DataView]",vE="[object Float32Array]",SE="[object Float64Array]",yE="[object Int8Array]",EE="[object Int16Array]",PE="[object Int32Array]",_E="[object Uint8Array]",CE="[object Uint8ClampedArray]",wE="[object Uint16Array]",RE="[object Uint32Array]";function bE(s,t,e){var r=s.constructor;switch(t){case fE:return oh(s);case cE:case dE:return new r(+s);case TE:return iE(s,e);case vE:case SE:case yE:case EE:case PE:case _E:case CE:case wE:case RE:return Pm(s,e);case lE:return new r;case uE:case gE:return new r(s);case hE:return aE(s);case pE:return new r;case mE:return oE(s)}}var np=Object.create,kE=function(){function s(){}return function(t){if(!ss(t))return{};if(np)return np(t);s.prototype=t;var e=new s;return s.prototype=void 0,e}}();const IE=kE;function _m(s){return typeof s.constructor=="function"&&!Cl(s)?IE(ah(s)):{}}var AE="[object Map]";function ME(s){return Ls(s)&&Ra(s)==AE}var ap=wa&&wa.isMap,DE=ap?ih(ap):ME;const OE=DE;var NE="[object Set]";function VE(s){return Ls(s)&&Ra(s)==NE}var op=wa&&wa.isSet,LE=op?ih(op):VE;const xE=LE;var UE=1,$E=2,FE=4,Cm="[object Arguments]",BE="[object Array]",HE="[object Boolean]",qE="[object Date]",jE="[object Error]",wm="[object Function]",GE="[object GeneratorFunction]",WE="[object Map]",JE="[object Number]",Rm="[object Object]",KE="[object RegExp]",zE="[object Set]",YE="[object String]",QE="[object Symbol]",XE="[object WeakMap]",ZE="[object ArrayBuffer]",eP="[object DataView]",tP="[object Float32Array]",sP="[object Float64Array]",rP="[object Int8Array]",iP="[object Int16Array]",nP="[object Int32Array]",aP="[object Uint8Array]",oP="[object Uint8ClampedArray]",cP="[object Uint16Array]",dP="[object Uint32Array]",ue={};ue[Cm]=ue[BE]=ue[ZE]=ue[eP]=ue[HE]=ue[qE]=ue[tP]=ue[sP]=ue[rP]=ue[iP]=ue[nP]=ue[WE]=ue[JE]=ue[Rm]=ue[KE]=ue[zE]=ue[YE]=ue[QE]=ue[aP]=ue[oP]=ue[cP]=ue[dP]=!0;ue[jE]=ue[wm]=ue[XE]=!1;function zc(s,t,e,r,i,a){var o,c=t&UE,d=t&$E,l=t&FE;if(e&&(o=i?e(s,r,i,a):e(s)),o!==void 0)return o;if(!ss(s))return s;var h=Vt(s);if(h){if(o=sE(s),!c)return Tm(s,o)}else{var p=Ra(s),f=p==wm||p==GE;if(Ca(s))return fm(s,c);if(p==Rm||p==Cm||f&&!i){if(o=d||f?{}:_m(s),!c)return d?Hy(s,Dy(o,s)):Uy(s,by(o,s))}else{if(!ue[p])return i?s:{};o=bE(s,p,c)}}a||(a=new Es);var T=a.get(s);if(T)return T;a.set(s,o),xE(s)?s.forEach(function(_){o.add(zc(_,t,e,_,s,a))}):OE(s)&&s.forEach(function(_,I){o.set(I,zc(_,t,e,I,s,a))});var E=l?d?qy:iu:d?kc:wl,C=h?void 0:E(s);return IS(C||s,function(_,I){C&&(I=_,_=s[I]),cm(o,I,zc(_,t,e,I,s,a))}),o}var lP=1,uP=4;function ch(s){return zc(s,lP|uP)}var hP="[object Symbol]";function Rl(s){return typeof s=="symbol"||Ls(s)&&tn(s)==hP}var pP=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,gP=/^\w*$/;function dh(s,t){if(Vt(s))return!1;var e=typeof s;return e=="number"||e=="symbol"||e=="boolean"||s==null||Rl(s)?!0:gP.test(s)||!pP.test(s)||t!=null&&s in Object(t)}var mP="Expected a function";function lh(s,t){if(typeof s!="function"||t!=null&&typeof t!="function")throw new TypeError(mP);var e=function(){var r=arguments,i=t?t.apply(this,r):r[0],a=e.cache;if(a.has(i))return a.get(i);var o=s.apply(this,r);return e.cache=a.set(i,o)||a,o};return e.cache=new(lh.Cache||fr),e}lh.Cache=fr;var fP=500;function TP(s){var t=lh(s,function(r){return e.size===fP&&e.clear(),r}),e=t.cache;return t}var vP=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,SP=/\\(\\)?/g,yP=TP(function(s){var t=[];return s.charCodeAt(0)===46&&t.push(""),s.replace(vP,function(e,r,i,a){t.push(i?a.replace(SP,"$1"):r||e)}),t});const EP=yP;function PP(s,t){for(var e=-1,r=s==null?0:s.length,i=Array(r);++e<r;)i[e]=t(s[e],e,s);return i}var _P=1/0,cp=Vs?Vs.prototype:void 0,dp=cp?cp.toString:void 0;function bm(s){if(typeof s=="string")return s;if(Vt(s))return PP(s,bm)+"";if(Rl(s))return dp?dp.call(s):"";var t=s+"";return t=="0"&&1/s==-_P?"-0":t}function CP(s){return s==null?"":bm(s)}function km(s,t){return Vt(s)?s:dh(s,t)?[s]:EP(CP(s))}var wP=1/0;function bl(s){if(typeof s=="string"||Rl(s))return s;var t=s+"";return t=="0"&&1/s==-wP?"-0":t}function Im(s,t){t=km(t,s);for(var e=0,r=t.length;s!=null&&e<r;)s=s[bl(t[e++])];return e&&e==r?s:void 0}function RP(s,t,e){var r=s==null?void 0:Im(s,t);return r===void 0?e:r}function bP(s,t,e){t=km(t,s);for(var r=-1,i=t.length,a=!1;++r<i;){var o=bl(t[r]);if(!(a=s!=null&&e(s,o)))break;s=s[o]}return a||++r!=i?a:(i=s==null?0:s.length,!!i&&rh(i)&&sh(o,i)&&(Vt(s)||vo(s)))}var kP=Object.defineProperty,IP=(s,t)=>{for(var e in t)kP(s,e,{get:t[e],enumerable:!0})},AP={};IP(AP,{permissions:()=>MP,theme:()=>DP});var lr=(s=>(s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT",s))(lr||{}),F=(s=>(s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST",s))(F||{}),MP={view_type:"GROUP_CALL",accept_waiting_requests:!1,accept_present_requests:!1,request_produce:!1,can_allow_participant_audio:!1,can_allow_participant_screensharing:!1,can_allow_participant_video:!1,can_spotlight:!1,request_kick_participant:!1,kick_participant:!1,pin_participant:!1,can_edit_display_name:!1,can_record:!1,can_livestream:!1,can_present:!0,waiting_room_type:"SKIP_ON_ACCEPT",recorder_type:"NONE",plugins:{can_close:!0,can_start:!0},polls:{can_create:!0,can_vote:!0,can_view:!0},produce:{video:{allow:!0,quality:"vga",frame_rate:24},audio:!0,screenshare:{allow:!0,quality:"hd",frame_rate:5}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1}},connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},reactions:!1,hidden_participant:!1,is_recorder:!1,show_participant_list:!0,can_change_participant_role:!1,can_change_theme:!1,max_screenshare_count:1},DP={setup_screen:{is_enabled:!0},alone_here:{is_enabled:!0},waiting_room:{is_enabled:!1,enable_preview:!0},control_bar:{is_enabled:!0,elements:{plugins:!0,screenshare:!0,invite:!0,participants:!0,chat:!0,reactions:!1,polls:!0,fullscreen:!0,layout:!0}},header:{is_enabled:!0,elements:{timer:!0,title:!0,participant_count:!0,change_layout:!0}},pip_mode:!0,auto_tune:!0,grid:{multi:{maxVideoCount:6,videoFit:"cover"},single:{maxVideoCount:6,videoFit:"cover"},defaultView:"multi"},controls:{pip_toggle:!1}},Am="hXgU8Wc8pwuGNq9ms5q9Hh",og;typeof process!="undefined"&&(og=process==null?void 0:process.env)!=null&&og.FLAGSMITH_ENVIRONMENT_KEY&&(Am=process.env.FLAGSMITH_ENVIRONMENT_KEY);function OP(s=[]){const t={};return s.forEach(e=>{t[e.feature.name]={enabled:e.enabled,value:e.feature_state_value}}),t}var Mm=class{constructor(s=Am){u(this,"flags",{});u(this,"environmentKey",null);this.environmentKey=s}async identifyAndFetchFlagsWithRetry({primaryEndpoint:s,secondaryEndpoint:t,forceEvaluate:e,timeout:r,uniqueIdentifier:i,traitsObj:a,logger:o}){const c=JSON.parse(JSON.stringify(a)),d=Object.entries(c).map(h=>({trait_key:h[0],trait_value:h[1]})),l=[s,t,t];for(const h of l)try{const p=new AbortController,f=setTimeout(()=>p.abort(),r),T=`_${(Math.random()+1).toString(36).substring(2)}`,E=await fetch(`https://${h}/api/v1/identities/`,{method:"POST",headers:{"Content-Type":"application/json","X-Environment-Key":this.environmentKey},body:JSON.stringify({identifier:i+(e?T:""),traits:d}),signal:p.signal});if(clearTimeout(f),!E.ok)throw new Error(`Request failed with status ${E.status}`);const C=await E.json();return OP(C.flags||[])}catch(p){o.error("Flagsmith identify failed!!",{error:p,url:h})}return{}}async identify(s,t={},e=!1,r=5e3,i="edge.api.flagsmith.com",a=console){return this.flags=await this.identifyAndFetchFlagsWithRetry({traitsObj:t,uniqueIdentifier:s,forceEvaluate:e,timeout:r,primaryEndpoint:i,secondaryEndpoint:"edge.api.flagsmith.com",logger:a}),this.flags}getValue(s){return this.flags&&this.flags[s]&&this.flags[s].value}hasFeature(s){return this.flags&&this.flags[s]&&this.flags[s].enabled}getAllFlags(){return this.flags}},NP=new Mm;function VP(s){return new Mm(s)}var Dm=[-2,-1,0,1,2],LP=[0,1,2,3,4];function xP(s){s=s.trim();let t="0",e="0",r="0";return s.length==4?(t=`0x${s[1]}${s[1]}`,e=`0x${s[2]}${s[2]}`,r=`0x${s[3]}${s[3]}`):s.length>6&&(t=`0x${s[1]}${s[2]}`,e=`0x${s[3]}${s[4]}`,r=`0x${s[5]}${s[6]}`),[+t,+e,+r]}var UP=(s,t,e)=>{let r,i,a;if(t==0)r=i=a=e;else{const o=(l,h,p)=>(p<0&&(p+=1),p>1&&(p-=1),p<.16666666666666666?l+(h-l)*6*p:p<.5?h:p<.6666666666666666?l+(h-l)*(.6666666666666666-p)*6:l),c=e<.5?e*(1+t):e+t-e*t,d=2*e-c;r=o(d,c,s+1/3),i=o(d,c,s),a=o(d,c,s-1/3)}return[Math.round(r*255),Math.round(i*255),Math.round(a*255)]},$P=(s,t,e)=>{s/=255,t/=255,e/=255;const r=Math.max(s,t,e),i=Math.min(s,t,e);let a,o;const c=(r+i)/2;if(r==i)a=o=0;else{const d=r-i;switch(o=c>.5?d/(2-r-i):d/(r+i),r){case s:a=(t-e)/d+(t<e?6:0);break;case t:a=(e-s)/d+2;break;case e:a=(s-t)/d+4;break}a/=6}return[a,o,c]},FP=(s,t,e)=>{const r=i=>i.toString(16).padStart(2,"0");return`#${r(s)}${r(t)}${r(e)}`},Om=(s,t=Dm,e=.4)=>{const r=[],[i,a,o]=xP(s),[c,d,l]=$P(i,a,o),h=Math.round(l*100);h>70?e=.8:h>60?e=.9:h<10?e=.075:h<42&&(e=.3);const p=t.findIndex(_=>_===0);if(p===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const f=5-p,T=p+1,E=(100-h)/f,C=h/T;for(const _ of t){let I;_<0?I=h+_*C*e:_>0?I=h+_*E*e:I=h;const[M,x,N]=UP(c,d,I/100);r.push(FP(M,x,N))}return r},lp={dark:{background:{1e3:"#252525",900:"#2F2F2F",800:"#323232",700:"#3E3E3E",600:"#4A4A4A"},text:"#F5F5F5","video-bg":"#1C1C1C"},light:{background:{1e3:"#FFFFFF",900:"#F5F5F5",800:"#EBEBEB",700:"#E0E0E0",600:"#D6D6D6"},text:"#111111","text-on-brand":"#ffffff","video-bg":"#DADADA"}},BP=s=>{const[t,e,r,i,a]=Om(s,Dm);return{300:t,400:e,500:r,600:i,700:a}},HP=s=>{if(s==="#FFFFFF")return lp.light.background;if(s==="#000000")return lp.dark.background;const[t,e,r,i,a]=Om(s,LP);return{1e3:t,900:e,800:r,700:i,600:a}},qP={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:BP("#2160FD"),background:HP("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function Nm(){return ch(qP)}var jP={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED",can_consume:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED",can_consume:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1},channel:{can_create:"ALL",can_delete:"ALL",can_update:"ALL",can_read_all:!1},message:{can_delete:"ALL",can_edit:"ALL",delete_cutoff_time_seconds:0,edit_cutoff_time_seconds:0}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{oldTheme:{setup_screen:{is_enabled:!1},alone_here:{is_enabled:!1},waiting_room:{is_enabled:!1,enable_preview:!0},control_bar:{is_enabled:!0,elements:{plugins:!0,screenshare:!0,invite:!1,participants:!0,chat:!0,reactions:!1,polls:!0,fullscreen:!0,layout:!0}},header:{is_enabled:!0,elements:{timer:!0,title:!0,participant_count:!0,change_layout:!0}},pip_mode:!0,auto_tune:!0,colors:{primary:"#2160FD",secondary:"#1A1A1A",text:"#EEEEEE",background:"#1A1A1A",textPrimary:"#EEEEEE",videoBackground:"#1A1A1A"},dimensions:{mode:"fillParent"},grid:{multi:{maxVideoCount:6,videoFit:"cover"},single:{maxVideoCount:6,videoFit:"cover"},defaultView:"MULTI"},controls:{pip_toggle:!1},plugins:[]},design_tokens:Nm(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:24},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"hybrid"};function GP(){return ch(jP)}var WP={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{design_tokens:Nm(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:24},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"2.0.0"};function uh(){return ch(WP)}var Eo;class Vm{constructor(){g(this,Eo,void 0)}get telemetry(){var t;return(t=n(this,Eo))==null?void 0:t.getValue("telemetry")}init(t){m(this,Eo,t)}info(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("info",t,e,r)}error(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("error",t,e,r)}debug(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("debug",t,e,r)}log(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("log",t,e,r)}warn(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("warn",t,e,r)}}Eo=new WeakMap;var Fs,Bs;class JP extends nt.EventEmitter{constructor(e){super();g(this,Fs,void 0);g(this,Bs,void 0);u(this,"asyncPromiseTimeout");u(this,"logger");this.logger=e,m(this,Fs,new Map),m(this,Bs,new Map),this.asyncPromiseTimeout=8e3}async emitAsync(e,...r){n(this,Fs).set(e,[]);const i=n(this,Bs).get(e).map(()=>new Promise(a=>{n(this,Fs).get(e).push(a)}));super.emit(e,...r),await Promise.race([Promise.all(i),new Promise((a,o)=>setTimeout(()=>o(new Error(`emitAsync failed to resolve for event ${e}.`)),this.asyncPromiseTimeout))]),n(this,Fs).delete(e)}onAsync(e,r){const i=n(this,Fs),a=async(...o)=>{var d;try{await r(...o)}catch(l){this.logger.error("[onAsync]",{error:l})}const c=(d=i.get(e))==null?void 0:d.shift();c==null||c()};return n(this,Bs).get(e)||n(this,Bs).set(e,[]),n(this,Bs).get(e).push(a),super.on(e,a)}reset(){m(this,Fs,new Map),m(this,Bs,new Map),super.removeAllListeners()}}Fs=new WeakMap,Bs=new WeakMap;var KP=/\s/;function zP(s){for(var t=s.length;t--&&KP.test(s.charAt(t)););return t}var YP=/^\s+/;function QP(s){return s&&s.slice(0,zP(s)+1).replace(YP,"")}var up=0/0,XP=/^[-+]0x[0-9a-f]+$/i,ZP=/^0b[01]+$/i,e_=/^0o[0-7]+$/i,t_=parseInt;function hp(s){if(typeof s=="number")return s;if(Rl(s))return up;if(ss(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=ss(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=QP(s);var e=ZP.test(s);return e||e_.test(s)?t_(s.slice(2),e?2:8):XP.test(s)?up:+s}function hh(s){return s}function s_(s,t,e){switch(e.length){case 0:return s.call(t);case 1:return s.call(t,e[0]);case 2:return s.call(t,e[0],e[1]);case 3:return s.call(t,e[0],e[1],e[2])}return s.apply(t,e)}function r_(){}var i_=800,n_=16,a_=Date.now;function o_(s){var t=0,e=0;return function(){var r=a_(),i=n_-(r-e);if(e=r,i>0){if(++t>=i_)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}function c_(s){return function(){return s}}var d_=hd?function(s,t){return hd(s,"toString",{configurable:!0,enumerable:!1,value:c_(t),writable:!0})}:hh;const l_=d_;var u_=o_(l_);const h_=u_;function p_(s,t,e,r){for(var i=s.length,a=e+(r?1:-1);r?a--:++a<i;)if(t(s[a],a,s))return a;return-1}function g_(s){return s!==s}function m_(s,t,e){for(var r=e-1,i=s.length;++r<i;)if(s[r]===t)return r;return-1}function f_(s,t,e){return t===t?m_(s,t,e):p_(s,g_,e)}function T_(s,t){var e=s==null?0:s.length;return!!e&&f_(s,t,0)>-1}var pp=Math.max;function v_(s,t,e){return t=pp(t===void 0?s.length-1:t,0),function(){for(var r=arguments,i=-1,a=pp(r.length-t,0),o=Array(a);++i<a;)o[i]=r[t+i];i=-1;for(var c=Array(t+1);++i<t;)c[i]=r[i];return c[t]=e(o),s_(s,this,c)}}function S_(s,t){return h_(v_(s,t,hh),s+"")}function y_(s,t,e){if(!ss(e))return!1;var r=typeof t;return(r=="number"?bc(e)&&sh(t,e.length):r=="string"&&t in e)?wc(e[t],s):!1}function E_(s){return S_(function(t,e){var r=-1,i=e.length,a=i>1?e[i-1]:void 0,o=i>2?e[2]:void 0;for(a=s.length>3&&typeof a=="function"?(i--,a):void 0,o&&y_(e[0],e[1],o)&&(a=i<3?void 0:a,i=1),t=Object(t);++r<i;){var c=e[r];c&&s(t,c,r,a)}return t})}var P_="[object Object]",__=Function.prototype,C_=Object.prototype,Lm=__.toString,w_=C_.hasOwnProperty,R_=Lm.call(Object);function b_(s){if(!Ls(s)||tn(s)!=P_)return!1;var t=ah(s);if(t===null)return!0;var e=w_.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Lm.call(e)==R_}var k_="__lodash_hash_undefined__";function I_(s){return this.__data__.set(s,k_),this}function A_(s){return this.__data__.has(s)}function So(s){var t=-1,e=s==null?0:s.length;for(this.__data__=new fr;++t<e;)this.add(s[t])}So.prototype.add=So.prototype.push=I_;So.prototype.has=A_;function M_(s,t){for(var e=-1,r=s==null?0:s.length;++e<r;)if(t(s[e],e,s))return!0;return!1}function xm(s,t){return s.has(t)}var D_=1,O_=2;function Um(s,t,e,r,i,a){var o=e&D_,c=s.length,d=t.length;if(c!=d&&!(o&&d>c))return!1;var l=a.get(s),h=a.get(t);if(l&&h)return l==t&&h==s;var p=-1,f=!0,T=e&O_?new So:void 0;for(a.set(s,t),a.set(t,s);++p<c;){var E=s[p],C=t[p];if(r)var _=o?r(C,E,p,t,s,a):r(E,C,p,s,t,a);if(_!==void 0){if(_)continue;f=!1;break}if(T){if(!M_(t,function(I,M){if(!xm(T,M)&&(E===I||i(E,I,e,r,a)))return T.push(M)})){f=!1;break}}else if(!(E===C||i(E,C,e,r,a))){f=!1;break}}return a.delete(s),a.delete(t),f}function N_(s){var t=-1,e=Array(s.size);return s.forEach(function(r,i){e[++t]=[i,r]}),e}function ph(s){var t=-1,e=Array(s.size);return s.forEach(function(r){e[++t]=r}),e}var V_=1,L_=2,x_="[object Boolean]",U_="[object Date]",$_="[object Error]",F_="[object Map]",B_="[object Number]",H_="[object RegExp]",q_="[object Set]",j_="[object String]",G_="[object Symbol]",W_="[object ArrayBuffer]",J_="[object DataView]",gp=Vs?Vs.prototype:void 0,Gl=gp?gp.valueOf:void 0;function K_(s,t,e,r,i,a,o){switch(e){case J_:if(s.byteLength!=t.byteLength||s.byteOffset!=t.byteOffset)return!1;s=s.buffer,t=t.buffer;case W_:return!(s.byteLength!=t.byteLength||!a(new pd(s),new pd(t)));case x_:case U_:case B_:return wc(+s,+t);case $_:return s.name==t.name&&s.message==t.message;case H_:case j_:return s==t+"";case F_:var c=N_;case q_:var d=r&V_;if(c||(c=ph),s.size!=t.size&&!d)return!1;var l=o.get(s);if(l)return l==t;r|=L_,o.set(s,t);var h=Um(c(s),c(t),r,i,a,o);return o.delete(s),h;case G_:if(Gl)return Gl.call(s)==Gl.call(t)}return!1}var z_=1,Y_=Object.prototype,Q_=Y_.hasOwnProperty;function X_(s,t,e,r,i,a){var o=e&z_,c=iu(s),d=c.length,l=iu(t),h=l.length;if(d!=h&&!o)return!1;for(var p=d;p--;){var f=c[p];if(!(o?f in t:Q_.call(t,f)))return!1}var T=a.get(s),E=a.get(t);if(T&&E)return T==t&&E==s;var C=!0;a.set(s,t),a.set(t,s);for(var _=o;++p<d;){f=c[p];var I=s[f],M=t[f];if(r)var x=o?r(M,I,f,t,s,a):r(I,M,f,s,t,a);if(!(x===void 0?I===M||i(I,M,e,r,a):x)){C=!1;break}_||(_=f=="constructor")}if(C&&!_){var N=s.constructor,$=t.constructor;N!=$&&"constructor"in s&&"constructor"in t&&!(typeof N=="function"&&N instanceof N&&typeof $=="function"&&$ instanceof $)&&(C=!1)}return a.delete(s),a.delete(t),C}var Z_=1,mp="[object Arguments]",fp="[object Array]",xc="[object Object]",eC=Object.prototype,Tp=eC.hasOwnProperty;function tC(s,t,e,r,i,a){var o=Vt(s),c=Vt(t),d=o?fp:Ra(s),l=c?fp:Ra(t);d=d==mp?xc:d,l=l==mp?xc:l;var h=d==xc,p=l==xc,f=d==l;if(f&&Ca(s)){if(!Ca(t))return!1;o=!0,h=!1}if(f&&!h)return a||(a=new Es),o||_l(s)?Um(s,t,e,r,i,a):K_(s,t,d,e,r,i,a);if(!(e&Z_)){var T=h&&Tp.call(s,"__wrapped__"),E=p&&Tp.call(t,"__wrapped__");if(T||E){var C=T?s.value():s,_=E?t.value():t;return a||(a=new Es),i(C,_,e,r,a)}}return f?(a||(a=new Es),X_(s,t,e,r,i,a)):!1}function kl(s,t,e,r,i){return s===t?!0:s==null||t==null||!Ls(s)&&!Ls(t)?s!==s&&t!==t:tC(s,t,e,r,kl,i)}var sC=1,rC=2;function iC(s,t,e,r){var i=e.length,a=i,o=!r;if(s==null)return!a;for(s=Object(s);i--;){var c=e[i];if(o&&c[2]?c[1]!==s[c[0]]:!(c[0]in s))return!1}for(;++i<a;){c=e[i];var d=c[0],l=s[d],h=c[1];if(o&&c[2]){if(l===void 0&&!(d in s))return!1}else{var p=new Es;if(r)var f=r(l,h,d,s,t,p);if(!(f===void 0?kl(h,l,sC|rC,r,p):f))return!1}}return!0}function $m(s){return s===s&&!ss(s)}function nC(s){for(var t=wl(s),e=t.length;e--;){var r=t[e],i=s[r];t[e]=[r,i,$m(i)]}return t}function Fm(s,t){return function(e){return e==null?!1:e[s]===t&&(t!==void 0||s in Object(e))}}function aC(s){var t=nC(s);return t.length==1&&t[0][2]?Fm(t[0][0],t[0][1]):function(e){return e===s||iC(e,s,t)}}function oC(s,t){return s!=null&&t in Object(s)}function cC(s,t){return s!=null&&bP(s,t,oC)}var dC=1,lC=2;function uC(s,t){return dh(s)&&$m(t)?Fm(bl(s),t):function(e){var r=RP(e,s);return r===void 0&&r===t?cC(e,s):kl(t,r,dC|lC)}}function hC(s){return function(t){return t==null?void 0:t[s]}}function pC(s){return function(t){return Im(t,s)}}function gC(s){return dh(s)?hC(bl(s)):pC(s)}function mC(s){return typeof s=="function"?s:s==null?hh:typeof s=="object"?Vt(s)?uC(s[0],s[1]):aC(s):gC(s)}function fC(s){return function(t,e,r){for(var i=-1,a=Object(t),o=r(t),c=o.length;c--;){var d=o[s?c:++i];if(e(a[d],d,a)===!1)break}return t}}var TC=fC();const vC=TC;var SC=function(){return Ps.Date.now()};const Wl=SC;var yC="Expected a function",EC=Math.max,PC=Math.min;function gh(s,t,e){var r,i,a,o,c,d,l=0,h=!1,p=!1,f=!0;if(typeof s!="function")throw new TypeError(yC);t=hp(t)||0,ss(e)&&(h=!!e.leading,p="maxWait"in e,a=p?EC(hp(e.maxWait)||0,t):a,f="trailing"in e?!!e.trailing:f);function T(q){var ee=r,Qe=i;return r=i=void 0,l=q,o=s.apply(Qe,ee),o}function E(q){return l=q,c=setTimeout(I,t),h?T(q):o}function C(q){var ee=q-d,Qe=q-l,is=t-ee;return p?PC(is,a-Qe):is}function _(q){var ee=q-d,Qe=q-l;return d===void 0||ee>=t||ee<0||p&&Qe>=a}function I(){var q=Wl();if(_(q))return M(q);c=setTimeout(I,C(q))}function M(q){return c=void 0,f&&r?T(q):(r=i=void 0,o)}function x(){c!==void 0&&clearTimeout(c),l=0,r=d=i=c=void 0}function N(){return c===void 0?o:M(Wl())}function $(){var q=Wl(),ee=_(q);if(r=arguments,i=this,d=q,ee){if(c===void 0)return E(d);if(p)return clearTimeout(c),c=setTimeout(I,t),T(d)}return c===void 0&&(c=setTimeout(I,t)),o}return $.cancel=x,$.flush=N,$}function cu(s,t,e){(e!==void 0&&!wc(s[t],e)||e===void 0&&!(t in s))&&th(s,t,e)}function _C(s){return Ls(s)&&bc(s)}function du(s,t){if(!(t==="constructor"&&typeof s[t]=="function")&&t!="__proto__")return s[t]}function CC(s){return Rc(s,kc(s))}function wC(s,t,e,r,i,a,o){var c=du(s,e),d=du(t,e),l=o.get(d);if(l){cu(s,e,l);return}var h=a?a(c,d,e+"",s,t,o):void 0,p=h===void 0;if(p){var f=Vt(d),T=!f&&Ca(d),E=!f&&!T&&_l(d);h=d,f||T||E?Vt(c)?h=c:_C(c)?h=Tm(c):T?(p=!1,h=fm(d,!0)):E?(p=!1,h=Pm(d,!0)):h=[]:b_(d)||vo(d)?(h=c,vo(c)?h=CC(c):(!ss(c)||eh(c))&&(h=_m(d))):p=!1}p&&(o.set(d,h),i(h,d,r,a,o),o.delete(d)),cu(s,e,h)}function Bm(s,t,e,r,i){s!==t&&vC(t,function(a,o){if(i||(i=new Es),ss(a))wC(s,t,o,e,Bm,r,i);else{var c=r?r(du(s,o),a,o+"",s,t,i):void 0;c===void 0&&(c=a),cu(s,o,c)}},kc)}function RC(s,t,e){for(var r=-1,i=s==null?0:s.length;++r<i;)if(e(t,s[r]))return!0;return!1}var bC="[object Map]",kC="[object Set]",IC=Object.prototype,AC=IC.hasOwnProperty;function MC(s){if(s==null)return!0;if(bc(s)&&(Vt(s)||typeof s=="string"||typeof s.splice=="function"||Ca(s)||_l(s)||vo(s)))return!s.length;var t=Ra(s);if(t==bC||t==kC)return!s.size;if(Cl(s))return!gm(s).length;for(var e in s)if(AC.call(s,e))return!1;return!0}function DC(s,t){return kl(s,t)}var OC=E_(function(s,t,e){Bm(s,t,e)});const Er=OC;var NC=1/0,VC=En&&1/ph(new En([,-0]))[1]==NC?function(s){return new En(s)}:r_;const LC=VC;var xC=200;function Hm(s,t,e){var r=-1,i=T_,a=s.length,o=!0,c=[],d=c;if(e)o=!1,i=RC;else if(a>=xC){var l=t?null:LC(s);if(l)return ph(l);o=!1,i=xm,d=new So}else d=t?[]:c;e:for(;++r<a;){var h=s[r],p=t?t(h):h;if(h=e||h!==0?h:0,o&&p===p){for(var f=d.length;f--;)if(d[f]===p)continue e;t&&d.push(p),c.push(h)}else i(d,p,e)||(d!==c&&d.push(p),c.push(h))}return c}function UC(s){return s&&s.length?Hm(s):[]}function $C(s,t){return s&&s.length?Hm(s,mC(t)):[]}var lu=(s=>(s.PARTICIPANT="PARTICIPANT",s.PEER="PEER",s.CLIENT="CLIENT",s))(lu||{});const Y={PROPAGATE_KICK_ALL:"propagate_kick_across_rooms",REFRESH_ID_ON_DISCONNECTION:"refresh_id_on_disconnection",SKIP_OTEL_TRACES:"skip_otel_traces",ENABLE_CF_SIMULCAST:"enable_cf_simulcast",CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED:"cf_transport_force_relay_on_ice_failed",LOG_LEVEL:"log_level",V1_PLUGINS:"v1_plugins",LIVESTREAM:"feat_livestream",VAL_MIN_FRAMERATE:"val_min_framerate",SCREEENSHARE_ERR_HACK:"screenshare_err_hack",SCREEENSHARE_CONSTRAINTS_RETRY:"screenshare_constraints_retry",VIDEO_CONSTRAINTS:"video_constraints",SCREENSHARE_CONSTRAINTS:"screenshare_constraints",OBS_QUALITY:"obs_quality",ALLOW_SAFARI_MEDIA_MIDDLEWARES:"allow_safari_media_middlewares",EXP_RESHARE:"exp_reshare",SKIP_SETTING_IN_USE_DEVICE:"skip_setting_in_use_device",PRECALL_BANDWIDTH_TEST:"precall_bandwidth_test",DEBUG_SOCKET_JOIN:"debug_socket_join",FORCE_RELAY:"force_relay",FORCE_VIDEO_CODEC:"force_video_codec",TRACK_HINT:"track_hint",OVERRIDE_SIMULCAST_DYNAMIC:"override_simulcast_dynamic",PRECREATE_PRODUCERS:"precreate_producers",DISABLE_OPUS_DTX_CF:"disable_opus_dtx_cf",ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS:"enable_audio_activity_debug_logs",DISABLE_LAYER_SWITCH:"disable_layer_switch"};function Yc(s){const t={};return typeof(s==null?void 0:s.code)=="number"&&(t.code=s.code),typeof(s==null?void 0:s.code)=="string"&&(t.code=s.code.substring(0,100)),typeof(s==null?void 0:s.name)=="string"&&(t.name=s.name.substring(0,500)),typeof(s==null?void 0:s.message)=="string"&&(t.message=s.message.substring(0,500)),typeof(s==null?void 0:s.reason)=="string"&&(t.reason=s.reason.substring(0,500)),typeof(s==null?void 0:s.stack)=="string"&&(t.stack=s.stack.substring(0,500)),t}const FC={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},za={baseURL:"http://localhost:5000",createdAt:"2021-08-05T10:49:56.602Z",description:"Develop plugins locally",id:"09259e3b-7be8-46f6-9801-106bf1866e1c",name:"Localhost Dev",organizationId:"4ad15a19-80e2-4105-bf43-48039fd2963e",picture:"https://dyte-uploads.s3.ap-south-1.amazonaws.com/dyte.png",private:!1,published:!0,staggered:!1,tags:["#localhost","#dev"],type:"self_hosted",updatedAt:"2021-08-05T10:50:07.681Z"},BC={pip:!0,poll:!0,chat:!0,stage:!0,theme:!0,plugin:!0,tracing:!0,internals:!0,recording:!0,livestream:!0,participant:!0,connectedMeetings:!0,devTools:{logs:!1}};function ba(s,t){const e=s.getValue("overrides");return e&&e[t]?e[t]:!1}function HC({baseURI:s}){return s.includes("preprod.dyte")||s.includes("preprod.realtime")?oo.PREPROD:s.includes("devel.dyte")||s.includes("devel.realtime")?oo.DEVEL:oo.PROD}function Yi({servicePrefix:s,baseURI:t}){return`${s}.${t}`}function qm(s){const t=s.getValue("baseURI");return{location:Yi({servicePrefix:"location",baseURI:t}),locationLegacy:Yi({servicePrefix:"location-legacy",baseURI:t}),daCollector:Yi({servicePrefix:"da-collector",baseURI:t.replace("realtime.cloudflare.com","dyte.io")})}}const qC='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="m16.242 2.932 4.826 4.826a2.75 2.75 0 0 1-.715 4.404l-4.87 2.435a.75.75 0 0 0-.374.426l-1.44 4.166a1.25 1.25 0 0 1-2.065.476L8.5 16.561 4.06 21H3v-1.06l4.44-4.44-3.105-3.104a1.25 1.25 0 0 1 .476-2.066l4.166-1.44a.75.75 0 0 0 .426-.373l2.435-4.87a2.75 2.75 0 0 1 4.405-.715Zm3.766 5.886-4.826-4.826a1.25 1.25 0 0 0-2.002.325l-2.435 4.871a2.25 2.25 0 0 1-1.278 1.12l-3.789 1.31 6.705 6.704 1.308-3.789a2.25 2.25 0 0 1 1.12-1.277l4.872-2.436a1.25 1.25 0 0 0 .325-2.002Z" fill="currentColor"/></svg>',jC='<svg viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M4 12.02c0 1.06.2 2.1.6 3.08l.6 1.42c.22.55.64 1.01 1.17 1.29.27.14.56.21.86.21h2.55c.77 0 1.49-.41 1.87-1.08.5-.87 1.02-1.7 1.72-2.43l1.32-1.39c.44-.46.97-.84 1.49-1.23l.59-.45a.6.6 0 0 0 .23-.47c0-.75-.54-1.57-1.22-1.79a3.34 3.34 0 0 0-2.78.29V4.5a1.5 1.5 0 0 0-2.05-1.4 1.5 1.5 0 0 0-2.9 0A1.5 1.5 0 0 0 6 4.5v.09A1.5 1.5 0 0 0 4 6v6.02ZM8 4.5v4a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0v5a.5.5 0 0 0 1 0v-4a.5.5 0 0 1 1 0v6a.5.5 0 0 0 .85.37h.01c.22-.22.44-.44.72-.58.7-.35 2.22-.57 2.4.5l-.53.4c-.52.4-1.04.78-1.48 1.24l-1.33 1.38c-.75.79-1.31 1.7-1.85 2.63-.21.36-.6.58-1.01.58H7.23a.87.87 0 0 1-.4-.1 1.55 1.55 0 0 1-.71-.78l-.59-1.42a7.09 7.09 0 0 1-.53-2.7V6a.5.5 0 0 1 1 0v3.5a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0Z" fill="currentColor"></path></svg>',Uc=s=>{if(!s)return;if(!s.startsWith("<svg"))return new Promise(a=>{a(s)});const e=new Blob([s],{type:"image/svg+xml"}),r=new Image,i=window.URL.createObjectURL(e);return new Promise((a,o)=>{r.onload=()=>{a(r),window.URL.revokeObjectURL(i)},r.onerror=()=>{o(),window.URL.revokeObjectURL(i)},r.src=i})},ci={logs:"https://api-silos.dyte.io/otel/logs",mock:{url:"https://mock.dyte.io",domain:"mock.dyte.io",app:"https://app.dyte.io/v2/meeting",stagingApp:"https://app.devel.dyte.io/v2/meeting"},apiBase:{prod:"https://api.dyte.io",staging:"https://api.devel.dyte.io",prodAlternate:"https://api.cluster.dyte.in"},baseURI:{prod:"dyte.io",staging:"devel.dyte.io"}};function GC(s){var r,i,a;const t=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((r=window.location.host)==null?void 0:r.includes(ci.baseURI.staging)),e=!!((a=(i=s==null?void 0:s.getValue("modules"))==null?void 0:i.devTools)!=null&&a.logs);return t||e}function WC(s,t){var e;if(s!=null&&s.getValue("flagsmith").hasFeature(Y.LOG_LEVEL)){let r=((e=s.getValue("flagsmith").getValue(Y.LOG_LEVEL))==null?void 0:e.toString())||"all";if(r=r.toLowerCase().trim(),r==="off")return!1;if(r!=="all"){const i=["debug","log","info","warn","error"],a=i.indexOf(t),o=i.indexOf(r);if(a<o)return!1}}return!0}function jm(s,t,e={}){return Object.getOwnPropertyNames(s).forEach(r=>{var a;if([null,void 0,NaN].includes(s[r])||t&&(((a=t.match(/\./g))==null?void 0:a.length)||0)>=10)return;const i=t?`${t}.${r}`:r;typeof s[r]=="object"?jm(s[r],i,e):["number","string","boolean"].includes(typeof s[r])&&(e[i]=s[r])}),e}function vp(s,t,e={},r=""){const i={};try{const a=JSON.stringify(e),o=JSON.parse(a),c=jm(o,r),d=JSON.stringify(c);return JSON.parse(d)}catch(a){const o=Yc(a);i[`${r}.error.message`]=o.message||"",i[`${r}.error.stack`]=o.stack||"",i[`${r}.error.reason`]=o.reason||"",i[`${r}.error.source`]="safelyFlattenObjForOpenTelemetry"}return i}const Oh=class{constructor(){u(this,"logsCache",[]);u(this,"logsProcessorTimer");u(this,"tracingEnabled",!0);u(this,"initialized",!1);u(this,"logsProcessingInterval",7e3);u(this,"logExclusionList",["message","websocket/message","roomMessage","websocket/room-message","websocket/room-legacy-mode","chatMessage","websocket/new-chat-message","websocket/no-active-speaker","websocket/selected-peers","websocket/active-speaker","ping","websocket/new-consumer","websocket/producer-score","websocket/consumer-score","websocket/plugin-event","websocket/plugin-data","websocket/plugin-internal-data"]);u(this,"meetingMetadata",{})}get logsEndpoint(){const t=cr.getContext(this.meetingMetadata.peerId);return`https://${Yi({servicePrefix:"api-silos",baseURI:t.getValue("baseURI")})}/otel/logs`}resetPeerId(t){this.meetingMetadata.peerId=t}init(t,e,r){this.tracingEnabled=!0,this.initialized=!1,this.logsCache=[];const i=t.getValue("peerId");this.meetingMetadata=e,this.tracingEnabled=r,this.meetingMetadata.peerId=i,this.meetingMetadata.sdkVersion=t.getValue("sdkVersion");const{RNDeviceInfoImpl:a}=navigator;this.meetingMetadata.deviceInfo=navigator.isReactNative?a==null?void 0:a.getDeviceInfo():fe.getDeviceInfo(),this.meetingMetadata.visitedUrl=!navigator.isReactNative&&typeof window!="undefined"&&window.location.href,this.logsProcessorTimer=setInterval(this.processCachedLogs.bind(this),this.logsProcessingInterval),r&&(this.initialized=!0)}static trace(t,e=void 0){return(r,i,a)=>{const o=a.value;return a.value=function(...d){var f;const l=this==null?void 0:this.telemetry;if(!l||!l.initialized||navigator.isReactNative||!l.tracingEnabled||(f=cr.getContext(l.meetingMetadata.peerId))!=null&&f.getValue("flagsmith").hasFeature(Y.SKIP_OTEL_TRACES))return o.apply(this,d);l.addLogInCurrentSpan("info",t,e);const h=performance.now(),p=o.apply(this,d);return Promise.resolve(p).then(()=>{const T=performance.now();T-h>10&&l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:T-h,country:Oh.location.country})}).catch(()=>{const T=performance.now();l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:T-h})}),p},a}}injectContext(t){var i;const e=ur.v4().replace(/-/g,"").substring(0,16),r=(i=this.meetingMetadata.peerId)==null?void 0:i.replace(/-/g,"");t.TRACEPARENT=`00-${r}-${e}-01`}addLogInCurrentSpan(t,e,r={},i=!1){r!=null&&r.error&&Object.assign(r,{error:Yc(r.error)});const a=cr.getContext(this.meetingMetadata.peerId);if(GC(a)&&(MC(r)?console[t]("InternalLogs:: ",t,e):console[t]("InternalLogs:: ",t,e,r)),!!WC(a,t))try{const c=vp(a,e,r,"metadata"),d=new Date,l={message:e,level:t,...c,loggedAt:d.toISOString(),loggedAtTzOffset:d.getTimezoneOffset()};i?this.sendOtelLogsToNewRelic([l]):this.logsCache.push(l)}catch(c){this.addLogInCurrentSpan("error","opentelemetry::addLogInCurrentSpan_failed",{error:Yc(c)})}}sendOtelLogsToNewRelic(t){const e=cr.getContext(this.meetingMetadata.peerId);fetch(this.logsEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({meetingMetadata:vp(e,"sendOtelLogsToNewRelic",this.meetingMetadata,"meetingMetadata"),serviceName:e.getValue("sdkName"),logs:t})}).catch(r=>{this.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:Yc(r)}),this.logsCache.push(...t)})}processCachedLogs(){const t=this.logsCache.splice(0,25);t!=null&&t.length&&this.sendOtelLogsToNewRelic(t)}destruct(){clearInterval(this.logsProcessorTimer),this.processCachedLogs()}};let y=Oh;u(y,"location",{country:void 0});function JC(s){const t={...s},e=new Map,r=(l,h)=>(e.has(l)||e.set(l,new Set),e.get(l).add(h),()=>{var p;return(p=e.get(l))==null?void 0:p.delete(h)}),i=(l,h)=>{var p;(p=e.get(l))==null||p.delete(h)},a=l=>{var h;(h=e.get(l))==null||h.forEach(p=>{try{p(t[l])}catch(f){}})};return{subscribe:r,unsubscribe:i,notify:a,setValue:(l,h,p=!0)=>{t[l]=h,p&&a(l)},getValue:l=>t[l],getAllValues:()=>t}}class KC{constructor(){u(this,"contexts",new Map);u(this,"mostRecentPeerId",null)}createContext(t,e){if(this.contexts.has(t))return this.contexts.get(t);const r=new y,i=new Vm;this.contexts.set(t,JC(e)),this.contexts.get(t).setValue("peerSessionStore",new JP(i));const a=new nm;return a.setMaxListeners(50),this.contexts.get(t).setValue("logger",i),this.contexts.get(t).setValue("telemetry",r),this.contexts.get(t).setValue("callstats",a),this.contexts.get(t).setValue("flagsmith",VP()),this.mostRecentPeerId=t,this.contexts.get(t)}remapContext(t,e){const r=e.getValue("peerId");r!==t&&(e.setValue("peerId",t),this.mostRecentPeerId=t,this.contexts.set(t,e),this.contexts.delete(r))}getContext(t){return this.contexts.get(t)}getMostRecentPeerId(){return this.mostRecentPeerId}}const cr=new KC,zC={"00":"Client","01":"Controller","02":"RoomNodeClient","03":"HiveNodeClient","04":"SocketService","05":"Chat","06":"Plugin","07":"Polls","08":"Meta","09":"Preset",10:"Recording",11:"Self",12:"Participant",13:"Spotlight",14:"Remote Request",15:"Webinar",16:"LocalMediaHandler",17:"End-End Encryption",18:"AI",19:"Livestream",20:"Stage"},Qc={"0000":"Internal exception.","0001":"Failed to initialize.","0002":"Failed to join room.","0003":"Failed to leave room.","0004":"Invalid auth token","0010":"Browser not supported","0011":"HTTP Network Error","0012":"Websocket Network Error","0013":"Rate Limited","0100":"Internal exception","0101":"Permission denied","0102":"Prerequisite module missing","0200":"Internal exception.","0300":"Internal exception","0400":"Internal exception","0404":"Missing prerequisites to establish a websocket connection","0500":"Internal exception","0501":"Permission denied.","0502":"Invalid message body.","0503":"Text Message is too large","0504":"Message not found by the given id","0505":"Action not permitted without joining room","0506":"Message search is disabled","0600":"Internal exception","0601":"Permission denied.","0602":"Auth token not set for plugin","0603":"Iframe was not provided","0700":"Internal exception","0705":"Action not permitted without joining room","0800":"Internal exception","0801":"Permission denied","0900":"Internal exception","0904":"Could not load preset",1e3:"Internal exception",1001:"Permission denied",1004:"Could not find specified recording",1005:"Action not permitted in given recording state",1100:"Internal exception",1101:"Permission denied",1102:"Unsupported",1103:"Name cannot be empty",1104:"No device selected while calling meeting.self.setDevice",1105:"Action not permitted without joining room",1106:"Can't set currently used device",1200:"Internal exception",1201:"Permission denied",1202:"Invalid page number was requested",1203:"Invalid participant count per page was requested",1204:"No participants exists with the given UserIds",1205:"Action not permitted without joining room",1206:"Manual Subscription Mode was not ACTIVATED",1207:"Invalid view mode",1208:"Manual Subscription not enabled for organization",1209:"Broadcast message type must be a non-empty string",1300:"Internal exception",1400:"Internal exception",1402:"No existing remote requests",1403:"No peer exists with given id",1500:"Internal exception",1600:"Internal exception",1601:"Failed to get audio track",1602:"Failed to get video track",1603:"Incorrect device",1604:"Failed to change device",1605:"Failed to get audio & video track",1606:"No audio input devices are available",1607:"No video input devices are available",1608:"No audio output devices (speakers) are available",1609:"Failed to fetch list of media devices",1610:"No media track exists",1611:"Failed to unmute track",1612:"Failed to get screenshare tracks",1701:"Crypto error",1800:"Internal exception",1801:"Can't fetch transcript file",1900:"Internal exception",1901:"Permission denied.",1902:"Livestream that has not yet started, can't be stopped",2e3:"Internal exception",2001:"Permission denied",2002:"Unsupported",2003:"Stage is disabled",2004:"Method not implemented",2005:"Action not permitted without joining room",2006:"Action not permitted in current stage status",9900:"Internal exception"};Object.keys(Qc).forEach(s=>{Qc[s]=`{${zC[s.slice(0,2)]}} ${Qc[s]}`});class b extends Error{constructor(e,r,i=void 0,a=!1){super(e);u(this,"code");this.code=r,this.name="ClientError";const o=this.code?`[ERR${this.code}]`:"[ERR]",c=this.code?Qc[this.code]:"";this.message=`${o}: ${c}
|
|
4
|
+
`)),this.pc2.setLocalDescription(t),this.pc1.setRemoteDescription(t)}establishConnection(){this.pc1.createOffer().then(this.gotOffer.bind(this),this.reportFatal.bind(this))}reportFatal(t){console.error("Error:",t)}async getRoundTripTime(){const[t,e]=await Promise.all([this.pc1.getStats(),this.pc2.getStats()]);let r,i;if(t.forEach(a=>{a.type==="candidate-pair"&&a.nominated===!0&&a.bytesSent>0&&(r=a)}),e.forEach(a=>{a.type==="candidate-pair"&&a.nominated===!0&&a.bytesReceived>0&&(i=a)}),r&&i)try{if(r.currentRoundTripTime&&i.currentRoundTripTime)return{rtt:r.currentRoundTripTime,backendRTT:i.currentRoundTripTime};const a=(i.lastPacketReceivedTimestamp-r.lastPacketSentTimestamp)/1e3;return{rtt:a,backendRTT:a}}catch(a){return}}close(){this.pc1.close(),this.pc2.close()}}class tm extends nt{constructor(e){super();u(this,"call");u(this,"timeOut");this.call=new hr(e)}start(e=1e4){this.call.establishConnection(),this.timeOut=setTimeout(this.testFailed.bind(this),e)}testComplete(e){clearTimeout(this.timeOut),this.call.close(),this.emit("done",e)}testFailed(e){this.call.close(),this.emit("failed",e)}}const lv=8,uv=1/1e3;class hv extends tm{constructor(e){super(e);u(this,"senderChannel");u(this,"recieveChannel");u(this,"startTime");u(this,"lastBitrateMeasureTime");u(this,"sentPayloadBytes",0);u(this,"recievedPayloadBytes",0);u(this,"lastReceivedPayloadBytes",0);u(this,"stopSending",!1);u(this,"testProgress",0);u(this,"samplePacket","");u(this,"finalBitrateSum",0);u(this,"bitRateSampels",0);u(this,"maxNumberOfPacketsToSend",0);u(this,"bytesToKeepBuffered",0);u(this,"testDurationSeconds",5);this.call.setIceCandidateFilter(hr.isNotHostCandidate),this.senderChannel=this.call.pc1.createDataChannel(null);for(let r=0;r<1024*256;r+=1)this.samplePacket+="h";this.maxNumberOfPacketsToSend=1,this.bytesToKeepBuffered=1024*this.maxNumberOfPacketsToSend,this.testDurationSeconds=4,this.senderChannel.addEventListener("open",this.sendingStep.bind(this)),this.call.pc2.addEventListener("datachannel",this.onRecieverChannel.bind(this))}sendingStep(){const e=new Date;this.startTime||(this.startTime=e,this.lastBitrateMeasureTime=e);for(let i=0;i!==this.maxNumberOfPacketsToSend&&!(this.senderChannel.bufferedAmount>=this.bytesToKeepBuffered);i+=1){this.sentPayloadBytes+=this.samplePacket.length;try{this.senderChannel.send(this.samplePacket)}catch(a){}}const r=e.getTime()-this.startTime.getTime();r>=1e3*this.testDurationSeconds?(this.stopSending=!0,this.testProgress=100):(this.testProgress=r/(10*this.testDurationSeconds),setTimeout(this.sendingStep.bind(this),1))}onMessageRecieved(e){this.recievedPayloadBytes+=e.data.length;const r=new Date,i=r.getTime()-this.lastBitrateMeasureTime.getTime();if(i>=1e3){const o=(this.recievedPayloadBytes-this.lastReceivedPayloadBytes)*lv/(i/1e3);this.finalBitrateSum+=o,this.bitRateSampels+=1,this.lastReceivedPayloadBytes=this.recievedPayloadBytes,this.lastBitrateMeasureTime=r}if(this.stopSending&&this.sentPayloadBytes===this.recievedPayloadBytes){const a=this.finalBitrateSum/this.bitRateSampels;this.testComplete({throughput:Math.round(a*uv)})}}testComplete(e){this.call.getRoundTripTime().then(({rtt:r,backendRTT:i})=>super.testComplete({RTT:r,backendRTT:i,throughput:e.throughput}))}onRecieverChannel(e){this.recieveChannel=e.channel,this.recieveChannel.addEventListener("message",this.onMessageRecieved.bind(this))}}class Xu extends tm{constructor(e,r=hr.noFilter){super(e);u(this,"ch1");u(this,"ch2");this.call.setIceCandidateFilter(r);const i=this.call.pc1.createDataChannel(null);this.ch1=i,i.addEventListener("open",()=>{i.send("hello")}),i.addEventListener("message",this.onCh1Recieve.bind(this)),this.call.pc2.addEventListener("datachannel",this.dataChannelHandler.bind(this))}onCh1Recieve(e){e.data!=="world"?this.hangup("Invalid data transmitted."):this.testComplete({connectivity:!0})}onCh2Recieve(e){if(e.data!=="hello")this.hangup("Invalid data transmitted.");else try{this.ch2.send("world")}catch(r){}}dataChannelHandler(e){const r=e.channel;this.ch2=r,r.addEventListener("message",this.onCh2Recieve.bind(this))}hangup(e){this.testFailed(e)}}class pv extends Xu{constructor(t){super(t,hr.isHost)}}class gv extends Xu{constructor(t){super(t,hr.isRelay)}}class mv extends Xu{constructor(t){super(t,hr.isReflexive)}}class fv{constructor(){u(this,"ipInformation",null)}async getIPDetails({peerId:t,apiHostnames:e,logger:r}){var i,a,o;if(!this.ipInformation){try{const c=`https://${e.location}`,l=await(await fetch(c)).json();if(((i=l.loc)==null?void 0:i.length)>5)return this.ipInformation=l,(a=this.ipInformation)!=null&&a.ip&&(this.ipInformation.ip=Jr(this.ipInformation.ip)),l;throw Error("Insufficient data")}catch(c){r.error("callstats::ipDetails:: failed to fetch ip using location service",{error:c})}try{const c=await fetch(`https://${e.locationLegacy}/?token=3c493932b0624c&peerId=${t}`,{method:"POST"});this.ipInformation=await c.json(),(o=this.ipInformation)!=null&&o.ip&&(this.ipInformation.ip=Jr(this.ipInformation.ip))}catch(c){r.error("callstats::ipDetails:: failed to fetch ip using legacy location service",{error:c})}}return this.ipInformation}resetCache(){this.ipInformation=null}}const Zu=new fv,$h=[{urls:"turn:turn.dyte.in:443?transport=tcp",username:"dyte",credential:"dytein",credentialType:"password"},{urls:"turn:turn.dyte.in:3478?transport=udp",username:"dyte",credential:"dytein",credentialType:"password"}];function Fh(s){const[t,e]=s.split(",");return{coords:{latitude:Number(t),longitude:Number(e)}}}class sm{constructor(){u(this,"transport");u(this,"candidatePair");u(this,"outboundVideoRtp",new Map);u(this,"inboundVideoRtp",new Map);u(this,"outboundAudioRtp",new Map);u(this,"inboundAudioRtp",new Map);u(this,"remoteInboundRtp",new Map);u(this,"producerStreamMap",new Map);u(this,"consumerStreamMap",new Map);u(this,"staleProducerStreamMap",!1);u(this,"staleConsumerStreamMap",!1)}}class rm extends nt{constructor(){super();u(this,"observer");u(this,"outboundProducerMap",new Map);u(this,"inboundConsumerMap",new Map);u(this,"consumerPeerIdMap",new Map);u(this,"pausedConsumerMap",new Map);u(this,"pausedProducerMap",new Map);u(this,"overallProducingTransportsStatsMap",{});u(this,"overallConsumingTransportsStatsMap",{});u(this,"overallConsumersStatsMap",{});u(this,"overallProducersStatsMap",{});u(this,"videoProducerToStatsMap",new Map);u(this,"audioProducerToStatsMap",new Map);u(this,"videoConsumerToStatsMap",new Map);u(this,"audioConsumerToStatsMap",new Map);u(this,"consumerIdsWithFreezedVideo",new Set);u(this,"consumerIdsWithFreezedAudio",new Set);u(this,"producerIdsWithFreezedVideo",new Set);u(this,"producerIdsWithFreezedAudio",new Set);u(this,"freezedProducingTransportIds",new Set);u(this,"freezedConsumingTransportIds",new Set);u(this,"screenShareProducers",new Set);u(this,"screenShareConsumers",new Set);u(this,"ipDetails");u(this,"callStatsInstance");this.observer=new nt}async registerProducer(e){await this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}pauseProducer(e){this.pausedProducerMap.set(e,{lastReportCalculated:!1})}resumeProducer(e){this.pausedProducerMap.delete(e)}processInboundConsumerVideoStats(e,r,i){var o,c;const a=((c=(o=this==null?void 0:this.callStatsInstance)==null?void 0:o.consumerSharedMediaStatesMap)==null?void 0:c.get(e))||{};r.totalVideoPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedVideo.add(e),this.callStatsInstance&&a.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","pause",e))):(r.totalVideoPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedVideo.has(e)&&(this.consumerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&a.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","resume",e))))}processInboundConsumerAudioStats(e,r,i){var o,c;const a=((c=(o=this==null?void 0:this.callStatsInstance)==null?void 0:o.consumerSharedMediaStatesMap)==null?void 0:c.get(e))||{};r.totalAudioPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedAudio.add(e),this.callStatsInstance&&a.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","pause",e))):(r.totalAudioPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedAudio.has(e)&&(this.consumerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&a.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","resume",e))))}processOutboundProducerVideoStats(e,r,i){var o;const a=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalVideoPacketsSent===i.packetsSent?(this.producerIdsWithFreezedVideo.add(e),this.callStatsInstance&&a.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","pause",e))):(r.totalVideoPacketsSent=i.packetsSent,this.producerIdsWithFreezedVideo.has(e)&&(this.producerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&a.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","resume",e))))}processOutboundProducerAudioStats(e,r,i){var o;const a=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalAudioPacketsSent===i.packetsSent?(this.producerIdsWithFreezedAudio.add(e),this.callStatsInstance&&a.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","pause",e))):(r.totalAudioPacketsSent=i.packetsSent,this.producerIdsWithFreezedAudio.has(e)&&(this.producerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&a.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","resume",e))))}processProducingTransportStats(e,r,i){var h;const a=((h=this==null?void 0:this.callStatsInstance)==null?void 0:h.currentUserMediaStates)||{},{audio:o,video:c,screen:d}=a,l=o||c||d;r.totalPacketsSent===i.packetsSent?(this.freezedProducingTransportIds.add(e),this.callStatsInstance&&l&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","pause",e))):(r.totalPacketsSent=i.packetsSent,this.freezedProducingTransportIds.has(e)&&(this.freezedProducingTransportIds.delete(e),this.callStatsInstance&&l&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","resume",e))))}processConsumingTransportStats(e,r,i){var c,d;const o=!!Array.from(((d=(c=this==null?void 0:this.callStatsInstance)==null?void 0:c.consumerSharedMediaStatesMap)==null?void 0:d.values())||[]).reduce((l,h)=>l||h.audio||h.video||h.screen,!1);r.totalPacketsReceived===i.packetsSent?(this.freezedConsumingTransportIds.add(e),this.callStatsInstance&&o&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","pause",e))):(r.totalPacketsReceived=i.packetsSent,this.freezedConsumingTransportIds.has(e)&&(this.freezedConsumingTransportIds.delete(e),this.callStatsInstance&&o&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","resume",e))))}async registerConsumer(e){await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}pauseConsumer(e){this.pausedConsumerMap.set(e,{lastReportCalculated:!1})}resumeConsumer(e){this.pausedConsumerMap.delete(e)}async generateProducerStreamMap(e,r=!1){const i=await e.getStats(),a=r?this.getProducerStatsFromReport(this.parseRTCReport(i,["outbound-rtp","remote-inbound-rtp"],!1,e.id))[0]:void 0;for(const o of i.values())switch(o.type){case"outbound-rtp":{this.outboundProducerMap.set(o.id,e.id);break}}return a}async generateConsumerStreamMap(e,r=!1){const i=await e.getStats(),a=r?this.getConsumerStatsFromReport(this.parseRTCReport(i,["inbound-rtp"],!1,e.id))[0]:void 0;for(const o of i.values())switch(o.type){case"inbound-rtp":{this.inboundConsumerMap.set(o.id,e.id);break}}return a}deregisterProducer(e){this.outboundProducerMap.forEach((r,i)=>{r===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.inboundConsumerMap.forEach((r,i)=>{r===e.id&&this.inboundConsumerMap.delete(i)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}getWorkingSimulcastVideoStats(e){return e.find(i=>{const a=i.framesEncoded>0,o=i.packetsSent>0,c=i.frameWidth&&i.frameHeight;return a&&o&&!!c})||e[e.length-1]}parseRTCReport(e,r=[],i=!1,a=void 0,o=void 0){var C,_,I,M,x,N,$,q,ee,Qe,is,ei,ns;const c=e,d=new sm,l=r.length?new Set(r):void 0,h=[],p=[],f=[],T=new Map,E=new Map;for(const k of c.values()){if(l){if(l.size===0)break;if(l.has(k.type))i&&l.delete(k.type);else continue}switch(k.type){case"local-candidate":{h.push(this.getIceCandidateStats(k));break}case"remote-candidate":{p.push(this.getIceCandidateStats(k));break}case"candidate-pair":{const{nominated:S}=k,{selected:P}=k,U=k,Te={nominated:S!=null?S:P,currentRoundTripTime:U.currentRoundTripTime,totalRoundTripTime:U.totalRoundTripTime,bytesReceived:U.bytesReceived,bytesSent:U.bytesSent,availableOutgoingBitrate:U.availableOutgoingBitrate,availableIncomingBitrate:U.availableIncomingBitrate,lastPacketReceivedTimestamp:U.lastPacketReceivedTimestamp,lastPacketSentTimestamp:U.lastPacketSentTimestamp,localCandidateId:U.localCandidateId,remoteCandidateId:U.remoteCandidateId,bytesDiscardedOnSend:U.bytesDiscardedOnSend,packetsSent:U.packetsSent,packetsReceived:U.packetsReceived,packetsDiscardedOnSend:U.packetsDiscardedOnSend};f.push(Te),(k.nominated===!0||k.selected===!0)&&(d.candidatePair=Te);break}case"transport":{const S=k;o&&(o.producing&&(this.overallProducingTransportsStatsMap[o.id]||(this.overallProducingTransportsStatsMap[o.id]={totalPacketsSent:0})),o.consuming&&(this.overallConsumingTransportsStatsMap[o.id]||(this.overallConsumingTransportsStatsMap[o.id]={totalPacketsReceived:0})));const P={bytesReceived:S.bytesReceived,bytesSent:S.bytesSent,packetsSent:S.packetsSent,packetsReceived:S.packetsReceived,dtlsCipher:S.dtlsCipher,dtlsState:S.dtlsState,iceRole:S.iceRole};if(d.transport=P,o){if(o.producing){const U=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,U,P)}if(o.consuming){const U=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,U,P)}}break}case"remote-inbound-rtp":{const S=k,P={jitter:S.jitter,fractionLost:S.fractionLost,roundTripTime:S.roundTripTime,roundTripTimeMeasurements:S.roundTripTimeMeasurements,totalRoundTripTime:S.totalRoundTripTime,packetsLost:S.packetsLost};d.remoteInboundRtp.set(S.localId,P);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(k.id))break;const S=k,P=a||this.outboundProducerMap.get(k.id),U=this.pausedProducerMap.get(P);if(U){if(U.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const Te=this.overallProducersStatsMap[P];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.outboundProducerMap.has(k.id)){d.staleProducerStreamMap=!0;break}const be=this.callStatsInstance.producers.get(P);if(((C=be==null?void 0:be.track)==null?void 0:C.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const O={bytesSent:S.bytesSent,packetsSent:S.packetsSent,nackCount:S.nackCount,ssrc:S.ssrc,mid:S.mid,active:S.active,codecId:S.codecId,headerBytesSent:S.headerBytesSent||0,totalPacketSendDelay:S.totalPacketSendDelay||0};if(S.mediaType==="video"||S.kind==="video"){const R=S,Ne={frameHeight:R.frameHeight,frameWidth:R.frameWidth,framesEncoded:R.framesEncoded,framesDropped:R.framesDropped,framesPerSecond:R.framesPerSecond,framesSent:R.framesSent,keyFramesEncoded:R.keyFramesEncoded,firCount:R.firCount,encoderImplementation:R.encoderImplementation,hugeFramesSent:R.hugeFramesSent,pliCount:R.pliCount,qpSum:R.qpSum,qualityLimitationDurations:R.qualityLimitationDurations,qualityLimitationReason:R.qualityLimitationReason,qualityLimitationResolutionChanges:R.qualityLimitationResolutionChanges,totalEncodeTime:R.targetBitrate,totalPacketSendDelay:R.totalPacketSendDelay,retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,scalabilityMode:R.scalabilityMode,powerEfficientEncoder:R.powerEfficientEncoder,...O};d.outboundVideoRtp.set(k.id,Ne),d.producerStreamMap.get(P).outboundVideoRtpId.push(k.id),this.processOutboundProducerVideoStats(P,Te,Ne)}else if(S.mediaType==="audio"||S.kind==="audio"){const R=S,Ne={retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,...O};d.outboundAudioRtp.set(k.id,Ne),d.producerStreamMap.get(P).outboundAudioRtpId.push(k.id),this.processOutboundProducerAudioStats(P,Te,Ne)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(k.id))break;const S=k,P=a||this.inboundConsumerMap.get(k.id),U=this.pausedConsumerMap.get(P);if(U){if(U.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(S.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const Te=this.overallConsumersStatsMap[P];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.inboundConsumerMap.has(k.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(P)||d.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const be={bytesReceived:S.bytesReceived,packetsReceived:S.packetsReceived,packetsLost:S.packetsLost>=0?S.packetsLost:0,jitter:S.jitter,nackCount:S.nackCount,jitterBufferDelay:S.jitterBufferDelay,jitterBufferEmittedCount:S.jitterBufferEmittedCount,lastPacketReceivedTimestamp:S.lastPacketReceivedTimestamp,ssrc:S.ssrc,mid:S.mid,codecId:S.codecId,headerBytesReceived:S.headerBytesReceived||0,packetsDiscarded:S.packetsDiscarded||0,jitterBufferMinimumDelay:S.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:S.jitterBufferTargetDelay||0};if(S.mediaType==="video"||S.kind==="video"){const O=S,R={frameHeight:O.frameHeight,frameWidth:O.frameWidth,framesDecoded:O.framesDecoded,framesDropped:O.framesDropped,framesPerSecond:O.framesPerSecond,framesReceived:O.framesReceived,keyFramesDecoded:O.keyFramesDecoded,firCount:O.firCount,decoderImplementation:O.decoderImplementation,pliCount:O.pliCount,totalProcessingDelay:O.totalProcessingDelay,qpSum:O.qpSum||0,totalAssemblyTime:O.totalAssemblyTime||0,totalDecodeTime:O.totalDecodeTime||0,totalFreezesDuration:O.totalFreezesDuration||0,totalInterFrameDelay:O.totalInterFrameDelay||0,totalPausesDuration:O.totalPausesDuration||0,totalSquaredInterFrameDelay:O.totalSquaredInterFrameDelay||0,freezeCount:O.freezeCount||0,pauseCount:O.pauseCount||0,powerEfficientDecoder:O.powerEfficientDecoder,...be};R.score=em({frameWidth:R.frameWidth||0,framesDecoded:(R.framesDecoded||0)-(((_=this.videoConsumerToStatsMap.get(P))==null?void 0:_.framesDecoded)||0),framesPerSecond:R.framesPerSecond||0,packetsLost:(R.packetsLost||0)-(((I=this.videoConsumerToStatsMap.get(P))==null?void 0:I.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((M=this.videoConsumerToStatsMap.get(P))==null?void 0:M.packetsReceived)||0),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),E.set(P,{score:+(R.score*10).toFixed(),frameWidth:R.frameWidth||0,frameHeight:R.frameHeight||0,framesPerSecond:R.framesPerSecond||0,packetsLostPercentage:ld({packetsLost:(R.packetsLost||0)-(((x=this.videoConsumerToStatsMap.get(P))==null?void 0:x.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((N=this.videoConsumerToStatsMap.get(P))==null?void 0:N.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((R.bytesReceived||0)-((($=this.videoConsumerToStatsMap.get(P))==null?void 0:$.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,R),d.inboundVideoRtp.set(k.id,R),d.consumerStreamMap.get(P).inboundVideoRtpId.push(k.id),this.processInboundConsumerVideoStats(P,Te,R)}else if(S.mediaType==="audio"||S.kind==="audio"){const O=S,R={audioLevel:O.audioLevel,concealedSamples:O.concealedSamples,concealmentEvents:O.concealmentEvents,totalAudioEnergy:O.totalAudioEnergy,totalSamplesDuration:O.totalSamplesDuration,totalSamplesReceived:O.totalSamplesReceived,fecPacketsDiscarded:O.fecPacketsDiscarded||0,fecPacketsReceived:O.fecPacketsReceived||0,insertedSamplesForDeceleration:O.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:O.removedSamplesForAcceleration||0,silentConcealedSamples:O.silentConcealedSamples||0,playoutId:O.playoutId,...be};R.score=Zg({concealmentEvents:(R.concealmentEvents||0)-(((q=this.audioConsumerToStatsMap.get(P))==null?void 0:q.concealmentEvents)||0),packetsLost:(R.packetsLost||0)-(((ee=this.audioConsumerToStatsMap.get(P))==null?void 0:ee.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((Qe=this.audioConsumerToStatsMap.get(P))==null?void 0:Qe.packetsReceived)||0),jitter:R.jitter||0}),E.set(P,{score:+(R.score*10).toFixed(),packetsLostPercentage:ld({packetsLost:(R.packetsLost||0)-(((is=this.audioConsumerToStatsMap.get(P))==null?void 0:is.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((ei=this.audioConsumerToStatsMap.get(P))==null?void 0:ei.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((R.bytesReceived||0)-(((ns=this.audioConsumerToStatsMap.get(P))==null?void 0:ns.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,R),d.inboundAudioRtp.set(k.id,R),d.consumerStreamMap.get(P).inboundAudioRtpId.push(k.id),this.processInboundConsumerAudioStats(P,Te,R)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}}}if(d.producerStreamMap.forEach((k,S)=>{var P,U,Te,be,O,R,Ne,xs,Oa,Na,Va,La,xa,Ua,$a,Fa,Ba,Ha,qa,ja,Ga,Wa,Ja;if(k.outboundVideoRtpId.length>0){const oe=[];k.outboundVideoRtpId.forEach(Bl=>{oe.push(d.outboundVideoRtp.get(Bl))});const X=this.getWorkingSimulcastVideoStats(oe);X.score=Qg({frameWidth:X.frameWidth||0,framesPerSecond:X.framesPerSecond||0,jitter:((P=X.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsSent:(X.packetsSent||0)-(((U=this.videoProducerToStatsMap.get(S))==null?void 0:U.packetsSent)||0),packetsLost:(((Te=X.remoteData)==null?void 0:Te.packetsLost)||0)-(((O=(be=this.videoProducerToStatsMap.get(S))==null?void 0:be.remoteData)==null?void 0:O.packetsLost)||0),framesEncoded:(X.framesEncoded||0)-(((R=this.videoProducerToStatsMap.get(S))==null?void 0:R.framesEncoded)||0)}),T.set(S,{score:+(X.score*10).toFixed(),frameWidth:X.frameWidth||0,frameHeight:X.frameHeight||0,framesPerSecond:X.framesPerSecond||0,jitter:((Ne=X.remoteData)==null?void 0:Ne.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsLostPercentage:dd({packetsSent:(X.packetsSent||0)-(((xs=this.videoProducerToStatsMap.get(S))==null?void 0:xs.packetsSent)||0),packetsLost:(((Oa=X.remoteData)==null?void 0:Oa.packetsLost)||0)-(((Va=(Na=this.videoProducerToStatsMap.get(S))==null?void 0:Na.remoteData)==null?void 0:Va.packetsLost)||0)}),bitrate:((X.bytesSent||0)-(((La=this.videoProducerToStatsMap.get(S))==null?void 0:La.bytesSent)||0))*8/7,cpuLimitations:X.qualityLimitationReason==="cpu",bandwidthLimitations:X.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(S,X)}else if(k.outboundAudioRtpId.length>0){const oe=d.outboundAudioRtp.get(k.outboundAudioRtpId[0]);oe.score=Yg({packetsSent:(oe.packetsSent||0)-(((xa=this.audioProducerToStatsMap.get(S))==null?void 0:xa.packetsSent)||0),packetsLost:(((Ua=oe.remoteData)==null?void 0:Ua.packetsLost)||0)-(((Fa=($a=this.audioProducerToStatsMap.get(S))==null?void 0:$a.remoteData)==null?void 0:Fa.packetsLost)||0),jitter:((Ba=oe.remoteData)==null?void 0:Ba.jitter)||0}),T.set(S,{score:+(oe.score*10).toFixed(),bitrate:((oe.bytesSent||0)-(((Ha=this.audioProducerToStatsMap.get(S))==null?void 0:Ha.bytesSent)||0))*8/7,packetsLostPercentage:dd({packetsSent:(oe.packetsSent||0)-(((qa=this.audioProducerToStatsMap.get(S))==null?void 0:qa.packetsSent)||0),packetsLost:(((ja=oe.remoteData)==null?void 0:ja.packetsLost)||0)-(((Wa=(Ga=this.audioProducerToStatsMap.get(S))==null?void 0:Ga.remoteData)==null?void 0:Wa.packetsLost)||0)}),jitter:((Ja=oe.remoteData)==null?void 0:Ja.jitter)||0,isScreenShare:this.screenShareProducers.has(S)}),this.audioProducerToStatsMap.set(S,oe)}}),f.forEach(k=>{const S=h.find(U=>U.id===k.localCandidateId?(k.localCandidateId=U.id,U):null),P=p.find(U=>U.id===k.remoteCandidateId?(k.remoteCandidateId=U.id,U):null);S&&(k.localCandidateType=S.type,k.localCandidateAddress=Jr(S.address),k.localCandidatePort=S.port,k.localCandidateProtocol=S.protocol,k.localCandidateUrl=S.url,k.localCandidateNetworkType=S.networkType,k.localCandidateRelatedAddress=Jr(S.relatedAddress),k.localCandidateRelatedPort=S.relatedPort),P&&(k.remoteCandidateType=P.type,k.remoteCandidateAddress=Jr(P.address),k.remoteCandidatePort=P.port,k.remoteCandidateProtocol=P.protocol,k.remoteCandidateUrl=P.url)}),d.candidatePair&&(d.transport?(d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=f),d.transport&&!d.transport.roundTripTime){let k=0,S=0;d.remoteInboundRtp.forEach((P,U)=>{P.roundTripTime&&P.roundTripTime>k&&(k=P.roundTripTime,S=P.totalRoundTripTime)}),d.transport.roundTripTime=k,d.transport.totalRoundTripTime=S}if(E.size>0)try{this.observer.emit("consumer_score",E)}catch(k){}if(T.size>0)try{this.observer.emit("producer_score",T)}catch(k){}return d}async getProducersReport(e){const r=e.map(i=>this.generateProducerStreamMap(i,!0));return r.length>0?Promise.all(r):void 0}async getConsumersReport(e){const r=e.map(i=>this.generateConsumerStreamMap(i,!0));return r.length>0?Promise.all(r):void 0}async getTransportReport(e){return e.getStats()}async getProcessedStats(e,r,i){const a=await this.getTransportReport(e),o={producing:i,consuming:r,id:e.id},c=a,d=this.parseRTCReport(c,["transport","candidate-pair","inbound-rtp","outbound-rtp","remote-inbound-rtp","local-candidate","remote-candidate"],!1,void 0,o);if(!d)return;const l={stats:d.transport,transportId:e.id,consuming:r,producing:i},h=d.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(d),p=d.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(d);return{transportReport:l,producerReport:h,consumerReport:p}}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,a)=>{var o,c;r.push({producerId:a,videoStats:i.outboundVideoRtpId.map(d=>e.outboundVideoRtp.get(d)),audioStats:i.outboundAudioRtpId.map(d=>e.outboundAudioRtp.get(d)),appData:((c=(o=this.callStatsInstance.producers)==null?void 0:o.get(a))==null?void 0:c.appData)||null})})}catch(i){this.callStatsInstance.logger.error("callStats::measurements::getProducerStatsFromReport",{error:{reason:i.reason,message:i.message}})}return r}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((i,a)=>{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(a);r.push({consumerId:a,peerId:o,producerId:c,appData:d,videoStats:i.inboundVideoRtpId.map(l=>e.inboundVideoRtp.get(l)),audioStats:i.inboundAudioRtpId.map(l=>e.inboundAudioRtp.get(l))})})}catch(i){console.error("getConsumersReport: ",i,e)}return r}async getUserLocation(){return new Promise((e,r)=>{try{navigator.geolocation?navigator.geolocation.getCurrentPosition(i=>{e(i)}):r()}catch(i){r(i)}})}async getConnectivity(e){try{const r={iceServers:e||$h},i=new Promise((h,p)=>{try{const f=new pv(r);f.addListener("done",h),f.addListener("failed",()=>{h({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),a=new Promise((h,p)=>{try{const f=new gv(r);f.addListener("done",h),f.addListener("failed",()=>{h({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),o=new Promise((h,p)=>{try{const f=new mv(r);f.addListener("done",h),f.addListener("failed",()=>{h({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),[c,d,l]=await Promise.all([i,a,o]);return{host:c==null?void 0:c.connectivity,relay:d==null?void 0:d.connectivity,reflexive:l==null?void 0:l.connectivity}}catch(r){return{host:!1,relay:!1,reflexive:!1}}}async getThroughput(e){try{const i=await new Promise((a,o)=>{try{const c={iceServers:e||$h},d=new hv(c);d.addListener("done",a),d.addListener("failed",o),d.start(1e4)}catch(c){o(c)}});return{throughput:i.throughput,fractionalLoss:0,RTT:i.RTT,jitter:0,backendRTT:i.backendRTT}}catch(r){return}}async getIPDetails(){var e,r;try{return this.ipDetails||(this.ipDetails=await Zu.getIPDetails({peerId:(e=this.callStatsInstance)==null?void 0:e.peerId,apiHostnames:(r=this.callStatsInstance)==null?void 0:r.apiHostnames,logger:this.callStatsInstance.logger})),this.ipDetails}catch(i){return}}async getNetworkQuality(e){const[r,i]=await Promise.all([this.getConnectivity(e),this.getThroughput(e)]);return{connectivity:r,throughput:i==null?void 0:i.throughput,fractionalLoss:i==null?void 0:i.fractionalLoss,RTT:i==null?void 0:i.RTT,jitter:i==null?void 0:i.jitter,backendRTT:i==null?void 0:i.backendRTT}}async getNetworkInfo(e,r=!1){var c,d;if(r){const l=await this.getIPDetails();return{ipDetails:l,effectiveNetworkType:(c=navigator.connection)==null?void 0:c.effectiveType,location:l!=null&&l.loc?Fh(l==null?void 0:l.loc):void 0}}const[i,a,o]=await Promise.all([this.getConnectivity(e),this.getThroughput(e),this.getIPDetails()]);return{ipDetails:o,effectiveNetworkType:(d=navigator.connection)==null?void 0:d.effectiveType,location:o!=null&&o.loc?Fh(o==null?void 0:o.loc):void 0,turnConnectivity:i?i.host||i.relay||i.reflexive:!1,connectivity:i,throughput:a==null?void 0:a.throughput,fractionalLoss:a==null?void 0:a.fractionalLoss,RTT:a==null?void 0:a.RTT,jitter:a==null?void 0:a.jitter,backendRTT:a==null?void 0:a.backendRTT}}}class Tv extends rm{}class im extends rm{constructor(){super(...arguments);u(this,"producerMap",new Map);u(this,"consumerMap",new Map)}async registerProducer(e){this.producerMap.set(e.id,e),await this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}async registerConsumer(e){this.consumerMap.set(e.id,e),await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}async generateConsumerStreamMap(e,r=!1){const i=await e.getStats(),a=this.parseRTCReport(i,["inbound-rtp"],!1,e.id),o=[...a.consumerStreamMap.values()][0],c=r?this.getConsumerStatsFromParsedConsumerStats(a,o,e.id):void 0;for(const d of i.values())switch(d.type){case"inbound-rtp":{this.inboundConsumerMap.set(d.id,e.id);break}}return c}deregisterProducer(e){this.producerMap.delete(e.id),this.outboundProducerMap.forEach((r,i)=>{r===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.consumerMap.delete(e.id),this.inboundConsumerMap.forEach((r,i)=>{r===e.id&&this.inboundConsumerMap.delete(i)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}parseRTCReport(e,r=[],i=!1,a=void 0,o=void 0){var C,_,I,M,x,N,$,q,ee,Qe,is,ei,ns;const c=e,d=new sm,l=r.length?new Set(r):void 0,h=[],p=[],f=[],T=new Map,E=new Map;for(const k of c.values()){if(l){if(l.size===0)break;if(l.has(k.type))i&&l.delete(k.type);else continue}switch(k.type){case"local-candidate":{h.push(this.getIceCandidateStats(k));break}case"remote-candidate":{p.push(this.getIceCandidateStats(k));break}case"candidate-pair":{const{nominated:S}=k,{selected:P}=k,U=k,Te={nominated:S!=null?S:P,currentRoundTripTime:U.currentRoundTripTime,totalRoundTripTime:U.totalRoundTripTime,bytesReceived:U.bytesReceived,bytesSent:U.bytesSent,availableOutgoingBitrate:U.availableOutgoingBitrate,availableIncomingBitrate:U.availableIncomingBitrate,lastPacketReceivedTimestamp:U.lastPacketReceivedTimestamp,lastPacketSentTimestamp:U.lastPacketSentTimestamp,localCandidateId:U.localCandidateId,remoteCandidateId:U.remoteCandidateId,bytesDiscardedOnSend:U.bytesDiscardedOnSend,packetsSent:U.packetsSent,packetsReceived:U.packetsReceived,packetsDiscardedOnSend:U.packetsDiscardedOnSend};f.push(Te),(k.nominated===!0||k.selected===!0)&&(d.candidatePair=Te);break}case"transport":{const S=k;o&&(o.producing&&(this.overallProducingTransportsStatsMap[o.id]||(this.overallProducingTransportsStatsMap[o.id]={totalPacketsSent:0})),o.consuming&&(this.overallConsumingTransportsStatsMap[o.id]||(this.overallConsumingTransportsStatsMap[o.id]={totalPacketsReceived:0})));const P={bytesReceived:S.bytesReceived,bytesSent:S.bytesSent,packetsSent:S.packetsSent,packetsReceived:S.packetsReceived,dtlsCipher:S.dtlsCipher,dtlsState:S.dtlsState,iceRole:S.iceRole};if(d.transport=P,o){if(o.producing){const U=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,U,P)}if(o.consuming){const U=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,U,P)}}break}case"remote-inbound-rtp":{const S=k,P={jitter:S.jitter,fractionLost:S.fractionLost,roundTripTime:S.roundTripTime,roundTripTimeMeasurements:S.roundTripTimeMeasurements,totalRoundTripTime:S.totalRoundTripTime,packetsLost:S.packetsLost};d.remoteInboundRtp.set(S.localId,P);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(k.id))break;const S=k,P=a||this.outboundProducerMap.get(k.id),U=this.pausedProducerMap.get(P);if(U){if(U.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const Te=this.overallProducersStatsMap[P];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.outboundProducerMap.has(k.id)){d.staleProducerStreamMap=!0;break}const be=this.callStatsInstance.producers.get(P);if(((C=be==null?void 0:be.track)==null?void 0:C.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const O={bytesSent:S.bytesSent,packetsSent:S.packetsSent,nackCount:S.nackCount,ssrc:S.ssrc,mid:S.mid,active:S.active,codecId:S.codecId,headerBytesSent:S.headerBytesSent||0,totalPacketSendDelay:S.totalPacketSendDelay||0};if(S.mediaType==="video"||S.kind==="video"){const R=S,Ne={frameHeight:R.frameHeight,frameWidth:R.frameWidth,framesEncoded:R.framesEncoded,framesDropped:R.framesDropped?R.framesDropped:R.droppedFrames,framesPerSecond:R.framesPerSecond?R.framesPerSecond:R.framerateMean,framesSent:R.framesSent,keyFramesEncoded:R.keyFramesEncoded,firCount:R.firCount,encoderImplementation:R.encoderImplementation,hugeFramesSent:R.hugeFramesSent,pliCount:R.pliCount,qpSum:R.qpSum,qualityLimitationReason:R.qualityLimitationReason,qualityLimitationDurations:R.qualityLimitationDurations,qualityLimitationResolutionChanges:R.qualityLimitationResolutionChanges,totalEncodeTime:R.totalEncodeTime,totalPacketSendDelay:R.totalEncodeTime,retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,scalabilityMode:R.scalabilityMode,powerEfficientEncoder:R.powerEfficientEncoder,...O};d.outboundVideoRtp.set(k.id,Ne),d.producerStreamMap.get(P).outboundVideoRtpId.push(k.id),this.processOutboundProducerVideoStats(P,Te,Ne)}else if(S.mediaType==="audio"||S.kind==="audio"){const R=S,Ne={retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,...O};d.outboundAudioRtp.set(k.id,Ne),d.producerStreamMap.get(P).outboundAudioRtpId.push(k.id),this.processOutboundProducerAudioStats(P,Te,Ne)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(k.id))break;const S=k,P=a||this.inboundConsumerMap.get(k.id),U=this.pausedConsumerMap.get(P);if(U){if(U.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(S.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const Te=this.overallConsumersStatsMap[P];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.inboundConsumerMap.has(k.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(P)||d.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const be={bytesReceived:S.bytesReceived,packetsReceived:S.packetsReceived,packetsLost:S.packetsLost>=0?S.packetsLost:0,jitter:S.jitter,nackCount:S.nackCount,jitterBufferDelay:S.jitterBufferDelay,jitterBufferEmittedCount:S.jitterBufferEmittedCount,lastPacketReceivedTimestamp:S.lastPacketReceivedTimestamp,ssrc:S.ssrc,mid:S.mid,codecId:S.codecId,headerBytesReceived:S.headerBytesReceived||0,packetsDiscarded:S.packetsDiscarded||0,jitterBufferMinimumDelay:S.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:S.jitterBufferTargetDelay||0};if(S.mediaType==="video"||S.kind==="video"){const O=S,R={frameHeight:O.frameHeight,frameWidth:O.frameWidth,framesDecoded:O.framesDecoded,framesDropped:O.framesDropped?O.framesDropped:O.droppedFrames,framesPerSecond:O.framesPerSecond?O.framesPerSecond:O.framerateMean,framesReceived:O.framesReceived,keyFramesDecoded:O.keyFramesDecoded,firCount:O.firCount,decoderImplementation:O.decoderImplementation,pliCount:O.pliCount,totalProcessingDelay:O.totalProcessingDelay,qpSum:O.qpSum||0,totalAssemblyTime:O.totalAssemblyTime||0,totalDecodeTime:O.totalDecodeTime||0,totalFreezesDuration:O.totalFreezesDuration||0,totalInterFrameDelay:O.totalInterFrameDelay||0,totalPausesDuration:O.totalPausesDuration||0,totalSquaredInterFrameDelay:O.totalSquaredInterFrameDelay||0,freezeCount:O.freezeCount||0,pauseCount:O.pauseCount||0,powerEfficientDecoder:O.powerEfficientDecoder,...be};R.score=em({frameWidth:R.frameWidth||0,framesDecoded:(R.framesDecoded||0)-(((_=this.videoConsumerToStatsMap.get(P))==null?void 0:_.framesDecoded)||0),framesPerSecond:R.framesPerSecond||0,packetsLost:(R.packetsLost||0)-(((I=this.videoConsumerToStatsMap.get(P))==null?void 0:I.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((M=this.videoConsumerToStatsMap.get(P))==null?void 0:M.packetsReceived)||0),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),E.set(P,{score:+(R.score*10).toFixed(),frameWidth:R.frameWidth||0,frameHeight:R.frameHeight||0,framesPerSecond:R.framesPerSecond||0,packetsLostPercentage:ld({packetsLost:(R.packetsLost||0)-(((x=this.videoConsumerToStatsMap.get(P))==null?void 0:x.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((N=this.videoConsumerToStatsMap.get(P))==null?void 0:N.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((R.bytesReceived||0)-((($=this.videoConsumerToStatsMap.get(P))==null?void 0:$.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,R),d.inboundVideoRtp.set(k.id,R),d.consumerStreamMap.get(P).inboundVideoRtpId.push(k.id),this.processInboundConsumerVideoStats(P,Te,R)}else if(S.mediaType==="audio"||S.kind==="audio"){const O=S,R={audioLevel:O.audioLevel,concealedSamples:O.concealedSamples,concealmentEvents:O.concealmentEvents,totalAudioEnergy:O.totalAudioEnergy,totalSamplesDuration:O.totalSamplesDuration,totalSamplesReceived:O.totalSamplesReceived,fecPacketsDiscarded:O.fecPacketsDiscarded||0,fecPacketsReceived:O.fecPacketsReceived||0,insertedSamplesForDeceleration:O.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:O.removedSamplesForAcceleration||0,silentConcealedSamples:O.silentConcealedSamples||0,playoutId:O.playoutId,...be};R.score=Zg({concealmentEvents:(R.concealmentEvents||0)-(((q=this.audioConsumerToStatsMap.get(P))==null?void 0:q.concealmentEvents)||0),packetsLost:(R.packetsLost||0)-(((ee=this.audioConsumerToStatsMap.get(P))==null?void 0:ee.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((Qe=this.audioConsumerToStatsMap.get(P))==null?void 0:Qe.packetsReceived)||0),jitter:R.jitter||0}),E.set(P,{score:+(R.score*10).toFixed(),packetsLostPercentage:ld({packetsLost:(R.packetsLost||0)-(((is=this.audioConsumerToStatsMap.get(P))==null?void 0:is.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((ei=this.audioConsumerToStatsMap.get(P))==null?void 0:ei.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((R.bytesReceived||0)-(((ns=this.audioConsumerToStatsMap.get(P))==null?void 0:ns.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,R),d.inboundAudioRtp.set(k.id,R),d.consumerStreamMap.get(P).inboundAudioRtpId.push(k.id),this.processInboundConsumerAudioStats(P,Te,R)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}}}if(d.producerStreamMap.forEach((k,S)=>{var P,U,Te,be,O,R,Ne,xs,Oa,Na,Va,La,xa,Ua,$a,Fa,Ba,Ha,qa,ja,Ga,Wa,Ja;if(k.outboundVideoRtpId.length>0){const oe=[];k.outboundVideoRtpId.forEach(Bl=>{oe.push(d.outboundVideoRtp.get(Bl))});const X=this.getWorkingSimulcastVideoStats(oe);X.score=Qg({frameWidth:X.frameWidth||0,framesPerSecond:X.framesPerSecond||0,jitter:((P=X.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsSent:(X.packetsSent||0)-(((U=this.videoProducerToStatsMap.get(S))==null?void 0:U.packetsSent)||0),packetsLost:(((Te=X.remoteData)==null?void 0:Te.packetsLost)||0)-(((O=(be=this.videoProducerToStatsMap.get(S))==null?void 0:be.remoteData)==null?void 0:O.packetsLost)||0),framesEncoded:(X.framesEncoded||0)-(((R=this.videoProducerToStatsMap.get(S))==null?void 0:R.framesEncoded)||0)}),T.set(S,{score:+(X.score*10).toFixed(),frameWidth:X.frameWidth||0,frameHeight:X.frameHeight||0,framesPerSecond:X.framesPerSecond||0,jitter:((Ne=X.remoteData)==null?void 0:Ne.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsLostPercentage:dd({packetsSent:(X.packetsSent||0)-(((xs=this.videoProducerToStatsMap.get(S))==null?void 0:xs.packetsSent)||0),packetsLost:(((Oa=X.remoteData)==null?void 0:Oa.packetsLost)||0)-(((Va=(Na=this.videoProducerToStatsMap.get(S))==null?void 0:Na.remoteData)==null?void 0:Va.packetsLost)||0)}),bitrate:((X.bytesSent||0)-(((La=this.videoProducerToStatsMap.get(S))==null?void 0:La.bytesSent)||0))*8/7,cpuLimitations:X.qualityLimitationReason==="cpu",bandwidthLimitations:X.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(S,X)}else if(k.outboundAudioRtpId.length>0){const oe=d.outboundAudioRtp.get(k.outboundAudioRtpId[0]);oe.score=Yg({packetsSent:(oe.packetsSent||0)-(((xa=this.audioProducerToStatsMap.get(S))==null?void 0:xa.packetsSent)||0),packetsLost:(((Ua=oe.remoteData)==null?void 0:Ua.packetsLost)||0)-(((Fa=($a=this.audioProducerToStatsMap.get(S))==null?void 0:$a.remoteData)==null?void 0:Fa.packetsLost)||0),jitter:((Ba=oe.remoteData)==null?void 0:Ba.jitter)||0}),T.set(S,{score:+(oe.score*10).toFixed(),bitrate:((oe.bytesSent||0)-(((Ha=this.audioProducerToStatsMap.get(S))==null?void 0:Ha.bytesSent)||0))*8/7,packetsLostPercentage:dd({packetsSent:(oe.packetsSent||0)-(((qa=this.audioProducerToStatsMap.get(S))==null?void 0:qa.packetsSent)||0),packetsLost:(((ja=oe.remoteData)==null?void 0:ja.packetsLost)||0)-(((Wa=(Ga=this.audioProducerToStatsMap.get(S))==null?void 0:Ga.remoteData)==null?void 0:Wa.packetsLost)||0)}),jitter:((Ja=oe.remoteData)==null?void 0:Ja.jitter)||0,isScreenShare:this.screenShareProducers.has(S)}),this.audioProducerToStatsMap.set(S,oe)}}),f.forEach(k=>{const S=h.find(U=>U.id===k.localCandidateId?(k.localCandidateId=U.id,U):null),P=p.find(U=>U.id===k.remoteCandidateId?(k.remoteCandidateId=U.id,U):null);S&&(k.localCandidateType=S.type,k.localCandidateAddress=Jr(S.address),k.localCandidatePort=S.port,k.localCandidateProtocol=S.protocol,k.localCandidateUrl=S.url,k.localCandidateNetworkType=S.networkType,k.localCandidateRelatedAddress=Jr(S.relatedAddress),k.localCandidateRelatedPort=S.relatedPort),P&&(k.remoteCandidateType=P.type,k.remoteCandidateAddress=Jr(P.address),k.remoteCandidatePort=P.port,k.remoteCandidateProtocol=P.protocol,k.remoteCandidateUrl=P.url)}),d.candidatePair&&(d.transport?(d.transport.bytesReceived=d.candidatePair.bytesReceived,d.transport.bytesSent=d.candidatePair.bytesSent,d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=f),d.transport&&!d.transport.roundTripTime){let k=0,S=0;d.remoteInboundRtp.forEach((P,U)=>{P.roundTripTime&&P.roundTripTime>k&&(k=P.roundTripTime,S=P.totalRoundTripTime)}),d.transport.roundTripTime=k,d.transport.totalRoundTripTime=S}if(E.size>0)try{this.observer.emit("consumer_score",E)}catch(k){}if(T.size>0)try{this.observer.emit("producer_score",T)}catch(k){}return d}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,a)=>{const o=this.producerMap.get(a),c=o.track.getSettings(),d=i.outboundVideoRtpId.map(h=>{const p=e.outboundVideoRtp.get(h);return p.frameHeight||(p.frameHeight=c.height,p.frameWidth=c.width,p.framesPerSecond=c.frameRate),p}),l={producerId:a,appData:o.appData,videoStats:d,audioStats:i.outboundAudioRtpId.map(h=>e.outboundAudioRtp.get(h))};r.push(l)})}catch(i){console.error("getProducersReport: ",i,e)}return r}getConsumerStatsFromParsedConsumerStats(e,r,i){let a;try{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(i),l=r==null?void 0:r.inboundVideoRtpId.map(h=>{const f=this.consumerMap.get(i).track.getSettings(),T=e.inboundVideoRtp.get(h);return T.frameHeight||(T.frameHeight=f.height,T.frameWidth=f.width,T.framesPerSecond=f.frameRate),T});a={consumerId:i,peerId:o,producerId:c,appData:d,videoStats:l,audioStats:r==null?void 0:r.inboundAudioRtpId.map(h=>e.inboundAudioRtp.get(h))}}catch(o){console.error("getConsumerStatsFromParsedConsumerStats: ",o,e)}return a}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((i,a)=>{r.push(this.getConsumerStatsFromParsedConsumerStats(e,i,a))})}catch(i){console.error("getConsumerStatsFromReport: ",i,e)}return r}}class vv extends im{}function ud(s,t,e,r){if(s!=null&&s.logger&&s.logger.error("Callstats::handleError",{error:r}),typeof e=="function"&&r instanceof t)e.call(null,r,s);else throw r}function Bh(s,t,e){const r=s.value;return s.value=function(...i){try{const a=r.apply(this,i);return a&&a instanceof Promise?a.catch(o=>{ud(this,t,e,o)}):a}catch(a){ud(this,t,e,a)}return null},s}const z=(s,t)=>(e,r,i)=>{const a=i.value;return i.value=function(...o){try{const c=a.apply(this,o);return c&&c instanceof Promise?c.catch(d=>{ud(this,s,t,d)}):c}catch(c){ud(this,s,t,c)}return null},i},Sv=(s,t)=>(e,r,i)=>{if(i)return Bh(i,s,t);for(const a of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,a);o.value instanceof Function&&Object.defineProperty(e.prototype,a,Bh(o,s,t))}};var J=globalThis&&globalThis.__decorate||function(s,t,e,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(s,t,e,r);else for(var c=s.length-1;c>=0;c--)(o=s[c])&&(a=(i<3?o(a):i>3?o(t,e,a):o(t,e))||a);return i>3&&a&&Object.defineProperty(t,e,a),a};const K=console;let G=class extends nt{constructor(e="https://api.testingv3.dyte.in",r="Blink",i=oo.PROD,a,o,c,d){super();u(this,"observer");u(this,"eventHandler");u(this,"measurements");u(this,"producingTransport");u(this,"consumingTransport");u(this,"producers",new Map);u(this,"consumers",new Map);u(this,"iceServers");u(this,"connectionInfoPromise");u(this,"pingStatsTimeout");u(this,"logger");u(this,"env");u(this,"apiHostnames");u(this,"peerId");u(this,"consumerSharedMediaStatesMap",new Map);u(this,"currentUserMediaStates",{});switch(this.env=i,this.apiHostnames=d,this.logger=o,this.peerId=c,this.eventHandler=new rv({logger:o,peerId:c,apiHostnames:d}),this.logger.debug("callStats::engineName: ",{engineName:r}),r){case"Blink":this.measurements=new Tv;break;case"Gecko":this.measurements=new im;break;case"WebKit":this.measurements=new vv;break;default:throw Error(`Unknown engineName! ${r}`)}this.measurements.callStatsInstance=this,this.registerProducer=this.registerProducer.bind(this),this.registerConsumer=this.registerConsumer.bind(this),this.observer=new nt,this.measurements.observer.on("consumer_score",l=>{o.debug(`callStats::consumer_score ${[...l.entries()]}`),this.eventHandler.emit("consumer_score",l)}),this.measurements.observer.on("producer_score",l=>{o.debug(`callStats::producer_score ${[...l.entries()]}`),this.eventHandler.emit("producer_score",l)})}registerIceServers(e){this.iceServers=e}registerConsumer(e){var r;this.consumerSharedMediaStatesMap.has(e.id)||this.consumerSharedMediaStatesMap.set(e.id,{}),this.consumers.set(e.id,e),this.measurements.registerConsumer(e),this.logger.debug("callStats::registerConsumer",{consumerId:e.id,consumerkind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.on("close",this.deRegisterConsumer.bind(this,e))}registerProducer(e){var r;this.producers.set(e.id,e),this.measurements.registerProducer(e),this.logger.debug("callStats::registerProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.on("close",this.deRegisterProducer.bind(this,e))}sendConsumerSharedMediaStateEvent(e,r){this.consumerSharedMediaStatesMap.has(e)||this.consumerSharedMediaStatesMap.set(e,{});const i=this.consumerSharedMediaStatesMap.get(e);this.consumerSharedMediaStatesMap.set(e,Object.assign(i,r))}registerProducingTransport(e){var i;this.producingTransport=e,e.on("close",this.disconnectProducingTransport.bind(this,e)),e.on("disconnect",this.disconnectProducingTransport.bind(this,e)),Array.from(((i=e._producers)==null?void 0:i.values())||[]).forEach(a=>{this.registerProducer(a)}),e.on("newproducer",this.registerProducer)}registerConsumingTransport(e){var i;this.consumingTransport=e,e.on("close",this.disconnectConsumingTransport.bind(this,e)),e.on("disconnect",this.disconnectConsumingTransport.bind(this,e)),Array.from(((i=e._consumers)==null?void 0:i.values())||[]).forEach(a=>{this.registerConsumer(a)}),e.on("newconsumer",this.registerConsumer)}deRegisterConsumer(e){this.consumers.delete(e.id)}deRegisterProducer(e){var r;this.producers.delete(e.id),this.logger.debug("callStats::deRegisterProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)})}disconnectConsumingTransport(){this.consumingTransport=void 0}disconnectProducingTransport(){this.producingTransport=void 0}callEvent(e){this.eventHandler.callEvent(e)}sendPreCallTestBeginEvent(e=!1,r){this.connectionInfoPromise=this.measurements.getNetworkInfo(this.iceServers,e),this.eventHandler.callEvent({event:D.PRECALL_TEST_BEGIN,timestamp:r}),this.connectionInfoPromise&&this.connectionInfoPromise.then(i=>{this.eventHandler.callEvent({event:D.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:i},timestamp:r})})}sendScreenShareToggleEvent(e,r=null,i){this.currentUserMediaStates.screen=e,this.eventHandler.callEvent({event:e?D.SCREENSHARE_STARTED:D.SCREENSHARE_STOPPED,metaData:{ssrc:r},timestamp:i})}sendScreenShareRequestedEvent(e){this.eventHandler.callEvent({event:D.SCREENSHARE_START_REQUESTED,timestamp:e})}sendActiveSpeakerEvent(e,r){this.eventHandler.callEvent({event:D.DOMINANT_SPEAKER,metaData:{peerId:e},timestamp:r})}devices(e,r,i){this.eventHandler.callEvent({event:e===Ht.AUDIO&&D.AUDIO_DEVICES_UPDATES||e===Ht.VIDEO&&D.VIDEO_DEVICES_UPDATES||e===Ht.SPEAKER&&D.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:r},timestamp:i})}selectedDevice(e,r,i){this.eventHandler.callEvent({event:e===Ht.AUDIO&&D.SELECTED_MICROHPONE_UPDATE||e===Ht.VIDEO&&D.SELECTED_CAMERA_UPDATE||e===Ht.SPEAKER&&D.SELECTED_SPEAKER_UPDATE,metaData:{device:r},timestamp:i})}mediaPermission(e,r,i){this.eventHandler.callEvent({event:D.MEDIA_PERMISSION,metaData:{deviceType:e,permission:r},timestamp:i})}mediaPlaybackFailed(e,r){this.eventHandler.callEvent({event:e===Ht.AUDIO&&D.AUDIO_PLAY_FAILED||e===Ht.VIDEO&&D.VIDEO_PLAY_FAILED,metaData:{deviceType:e},timestamp:r})}mediaTrackMuted(e,r){this.eventHandler.callEvent({event:e===Ht.AUDIO&&D.AUDIO_TRACK_MUTED||e===Ht.VIDEO&&D.VIDEO_TRACK_MUTED,metaData:{deviceType:e},timestamp:r})}tabChanged(e,r){this.eventHandler.callEvent({event:D.TAB_CHANGE,metaData:{isMeetingsTabActive:e},timestamp:r})}browserBackgrounded(e){this.eventHandler.callEvent({event:D.BROWSER_BACKGROUNDED,timestamp:e})}browserForegrounded(e){this.eventHandler.callEvent({event:D.BROWSER_FOREGROUNDED,timestamp:e})}legacySwitch(e,r){this.eventHandler.callEvent({event:D.LEGACY_SWITCH,metadata:{on:e},timestamp:r})}async getPreCallTestResults(){return this.connectionInfoPromise}sendCallJoinBeginEvent(e,r){e={...e,meetingEnv:this.env},e.deviceInfo={...e.deviceInfo,userAgent:navigator.userAgent,cpus:navigator.hardwareConcurrency,memory:navigator.deviceMemory},this.eventHandler.callEvent({event:D.CALL_JOIN_BEGIN,metaData:{peerMetaData:e},timestamp:r})}sendNetworkQualityTestBeginEvent(e,r){this.eventHandler.callEvent({event:D.NET_QUALITY_TEST_BEGIN,timestamp:r}),new Promise(async(a,o)=>{const c=[];try{for(const d of e)try{if(d.iceServers&&d.iceServers.length>0){const l=await this.measurements.getNetworkQuality(d.iceServers);c.push({...d,networkResults:l})}}catch(l){console.warn("Error handling ",l)}a({regionData:c})}catch(d){console.warn("Error in callstats, ",d),o(d)}}).then(a=>{this.eventHandler.callEvent({event:D.NET_QUALITY_TEST_END,timestamp:r,metaData:a})})}sendWebSocketConnectedEvent(e){this.eventHandler.callEvent({event:D.WEBSOCKET_CONNECTED,timestamp:e})}sendTransportConnectedEvent(e){this.eventHandler.callEvent({event:D.TRANSPORT_CONNECTED,timestamp:e})}sendAudioToggleEvent(e,r){this.currentUserMediaStates.audio=e;let i;e?i=D.AUDIO_ON:i=D.AUDIO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendVideoToggleEvent(e,r){this.currentUserMediaStates.video=e;let i;e?i=D.VIDEO_ON:i=D.VIDEO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendParticipantRoleToggleEvent(e,r){this.eventHandler.callEvent({event:D.PARTICIPANT_ROLE,timestamp:r,metaData:e})}startPingStats(e=7e3){this.sendPingStatsEvent(!1,new Date),this.pingStatsTimeout=setInterval(this.sendPingStatsEvent.bind(this),e)}stopPingStats(){clearInterval(this.pingStatsTimeout)}async sendPingStatsEvent(e=!0,r){var c,d;let i,a;if(this.producingTransport&&(i=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),!i||!((c=i==null?void 0:i.producerReport)!=null&&c.length))){this.logger.debug("callStats::sendPingStatsEvent::staleProducingTransport",{disclaimer:"Stale producer? Regenerating Stream Maps!"});const l=await this.measurements.getProducersReport([...this.producers.values()]);i&&l?i.producerReport=l:(i=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),(!i||!(i!=null&&i.producerReport))&&this.logger.debug("callStats::sendPingStatsEvent::noProducingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}if(this.consumingTransport&&(a=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),!a||!((d=a.consumerReport)!=null&&d.length))){this.logger.debug("callStats::sendPingStatsEvent::staleConsumingTransport",{disclaimer:"Stale consumer? Regenerating Stream Maps!"});const l=await this.measurements.getConsumersReport([...this.consumers.values()]);a&&l?a.consumerReport=l:(a=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),(!a||!a.consumerReport)&&this.logger.debug("callStats::sendPingStatsEvent::noConsumingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}const o={producingTransportStats:i?i==null?void 0:i.transportReport:void 0,consumingTransportStats:a?a==null?void 0:a.transportReport:void 0,producerStats:[].concat((i==null?void 0:i.producerReport)||[]).concat((a==null?void 0:a.producerReport)||[]),consumerStats:[].concat((a==null?void 0:a.consumerReport)||[]).concat((i==null?void 0:i.consumerReport)||[])};if(e&&o.producerStats.length===0&&o.consumerStats.length===0){await this.eventHandler.flush();return}this.eventHandler.callEvent({event:D.PING_STAT,metaData:o,timestamp:r})}sendIVSPlayerRebufferEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_REBUFFERING,timestamp:e})}sendIVSPlayerAudioBlockEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_AUDIO_BLOCKED,timestamp:e})}sendIVSPlayerPlaybackBlockedEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:e})}sendIVSPlayerNetworkUnavailableEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:e})}sendIVSPlayerInitializedEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_INITIALIZED,timestamp:e})}sendIVSPlayerWorkerErrorEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_WORKER_ERROR,timestamp:e})}sendIVSPlayerErrorEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_ERROR,timestamp:r,metaData:e})}sendIVSPlayerRecoverableErrorEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:r,metaData:e})}sendIVSPlayerAnalyticsEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_ANALYTICS_EVENT,timestamp:r,metaData:e})}sendIVSPlayerPlaybackRateChangedEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:r,metaData:{updatedPlaybackRate:e}})}sendIVSPlayerQualityChanged(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_QUALITY_CHANGED,timestamp:r,metaData:e})}sendPlayerLiveLatency(e,r){this.eventHandler.callEvent({event:D.LIVESTREAM_LATENCY,timestamp:r,metaData:{latency:e}})}sendDisconnectEvent(e){this.eventHandler.callEvent({event:D.DISCONNECT,timestamp:e})}sendReconnectEvent(e){this.eventHandler.callEvent({event:D.RECONNECT_ATTEMPT,timestamp:e})}expectedVideoResolution(e,r,i){this.eventHandler.callEvent({event:D.EXPECTED_VIDEO_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}expectedScreenshareResolution(e,r,i){this.eventHandler.callEvent({event:D.EXPECTED_SCREENSHARE_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}};J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"registerIceServers",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"registerConsumer",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"registerProducer",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendConsumerSharedMediaStateEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"registerProducingTransport",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"registerConsumingTransport",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"deRegisterConsumer",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"deRegisterProducer",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"disconnectConsumingTransport",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"disconnectProducingTransport",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendPreCallTestBeginEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendScreenShareToggleEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendScreenShareRequestedEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendActiveSpeakerEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"devices",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"selectedDevice",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"mediaPermission",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"mediaPlaybackFailed",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"mediaTrackMuted",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"tabChanged",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"browserBackgrounded",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"browserForegrounded",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"legacySwitch",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"getPreCallTestResults",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendCallJoinBeginEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendNetworkQualityTestBeginEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendWebSocketConnectedEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendTransportConnectedEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendAudioToggleEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendVideoToggleEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendParticipantRoleToggleEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"startPingStats",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"stopPingStats",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendPingStatsEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerRebufferEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerAudioBlockEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerPlaybackBlockedEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerNetworkUnavailableEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerInitializedEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerWorkerErrorEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerErrorEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerRecoverableErrorEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerAnalyticsEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendIVSPlayerQualityChanged",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendPlayerLiveLatency",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendDisconnectEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"sendReconnectEvent",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"expectedVideoResolution",null);J([z(TypeError,(s,t)=>K.error(t,s))],G.prototype,"expectedScreenshareResolution",null);G=J([Sv(TypeError,(s,t)=>K.error(t,s))],G);const yv=G;class nm extends nt{constructor(){super(...arguments);u(this,"stats");u(this,"peerId");u(this,"backend");u(this,"iceServers");u(this,"initialized",!1);u(this,"stalled",!1);u(this,"ipInformation");u(this,"logger")}async initialize({peerId:e,engineName:r,env:i=oo.PROD,iceServers:a,apiBase:o="https://api.cluster.dyte.in",flags:c,logger:d=console,apiHostnames:l,skipConnectivityChecks:h=!1}){var p,f,T;try{this.peerId=e,this.logger=d,this.ipInformation=await Zu.getIPDetails({peerId:e,apiHostnames:l,logger:d}),this.backend=new yv(o,r,i,c,d,e,l),this.iceServers=a,(p=this.backend)==null||p.registerIceServers(this.iceServers),this.initialized=!0,(T=(f=this.backend)==null?void 0:f.eventHandler)==null||T.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(h)}catch(E){this.logger.error("callStats::CallStatsIntegration: ",{error:E}),this.stallCallStats()}}configureSendTransport(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.registerProducingTransport(e)})}configureRecvTransport(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.registerConsumingTransport(e)})}async candidateRegionalNetworkQualityTest(e){const r=new Date;this.onSafeInitialization(()=>{var i;try{(i=this.backend)==null||i.sendNetworkQualityTestBeginEvent(e,r)}catch(a){this.logger.error("callStats::sendNetworkQualityTestBeginEvent",{error:{reason:a.reason}})}})}async roomJoined(e){const r=new Date;this.onSafeInitialization(()=>{var i,a;(i=this.backend)==null||i.sendCallJoinBeginEvent(e,r),this.backend,(a=this.backend)==null||a.startPingStats()})}audioOff(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendAudioToggleEvent(!1,e)})}audioOn(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendAudioToggleEvent(!0,e)})}videoOff(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendVideoToggleEvent(!1,e)})}videoOn(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendVideoToggleEvent(!0,e)})}callEnded(){const e=new Date;this.onSafeInitialization(()=>{var r,i;(r=this.backend)==null||r.stopPingStats(),(i=this.backend)==null||i.sendDisconnectEvent(e)})}screenShareStart(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendScreenShareToggleEvent(!0,e,r)})}consumerSharedMediaState(e,r){this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendConsumerSharedMediaStateEvent(e,r)})}screenShareStop(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendScreenShareToggleEvent(!1,e,r)})}screenShareRequested(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendScreenShareRequestedEvent(e)})}activeSpeaker(e){if(e!==this.peerId)return;const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendActiveSpeakerEvent(e,r)})}devices(e,r){const i=new Date;this.onSafeInitialization(()=>{var a;(a=this.backend)==null||a.devices(e,r,i)})}selectedDevice(e,r){const i=new Date;this.onSafeInitialization(()=>{var a;(a=this.backend)==null||a.selectedDevice(e,r,i)})}mediaPermission(e,r){const i=new Date;this.onSafeInitialization(()=>{var a;(a=this.backend)==null||a.mediaPermission(e,r,i)})}mediaPlaybackFailed(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaPlaybackFailed(e,r)})}mediaTrackMuted(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaTrackMuted(e,r)})}tabChanged(e=!1){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.tabChanged(e,r)})}browserBackgrounded(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.browserBackgrounded(e)})}browserForegrounded(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.browserForegrounded(e)})}legacySwitch(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.legacySwitch(e,r)})}async startPreCallTest(e=!1){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPreCallTestBeginEvent(e,r)})}onPreCallTestResults(e){return this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.once("precall_end",e)}),e}onReceivingConsumerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_audio_status",e)})}onReceivingConsumerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_video_status",e)})}onReceivingProducerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_audio_status",e)})}onReceivingProducerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_video_status",e)})}onReceivingProducingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producing_transport_status",e)})}onReceivingConsumingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consuming_transport_status",e)})}onProducerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_score",e)})}onConsumerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_score",e)})}onSafeInitialization(e){if(this.initialized)e(this.ipInformation,!1);else if(!this.stalled){const r=i=>{e(i,!0)};return this.once("initialized",r),r}return()=>{}}removeInitializationListener(e){this.removeListener("initialized",e)}stallCallStats(){this.stalled=!0,this.removeAllListeners("initialized")}ivsPlayerEvent(e,r){const i=new Date;this.onSafeInitialization(()=>{var a,o,c,d,l,h,p,f,T,E,C;switch(e){case"PlayerRebuffering":(a=this.backend)==null||a.sendIVSPlayerRebufferEvent(i);break;case"PlayerAudioBlocked":(o=this.backend)==null||o.sendIVSPlayerAudioBlockEvent(i);break;case"PlayerPlaybackBlocked":(c=this.backend)==null||c.sendIVSPlayerPlaybackBlockedEvent(i);break;case"PlayerNetworkUnavailable":(d=this.backend)==null||d.sendIVSPlayerNetworkUnavailableEvent(i);break;case"PlayerInitialized":(l=this.backend)==null||l.sendIVSPlayerInitializedEvent(i);break;case"PlayerWorkerError":(h=this.backend)==null||h.sendIVSPlayerWorkerErrorEvent(i);break;case"PlayerError":(p=this.backend)==null||p.sendIVSPlayerErrorEvent(r,i);break;case"PlayerRecoverableError":(f=this.backend)==null||f.sendIVSPlayerRecoverableErrorEvent(r,i);break;case"PlayerAnalyticsEvent":(T=this.backend)==null||T.sendIVSPlayerAnalyticsEvent(r,i);break;case"PlayerPlaybackRateChanged":(E=this.backend)==null||E.sendIVSPlayerPlaybackRateChangedEvent(r,i);break;case"PlayerQualityChanged":(C=this.backend)==null||C.sendIVSPlayerQualityChanged(r,i);break}})}livestreamLatency(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPlayerLiveLatency(e,r)})}expectedVideoResolution(e,r){const i=new Date;this.onSafeInitialization(()=>{var a;(a=this.backend)==null||a.expectedVideoResolution(e,r,i)})}expectedScreenshareResolution(e,r){const i=new Date;this.onSafeInitialization(()=>{var a;(a=this.backend)==null||a.expectedScreenshareResolution(e,r,i)})}}const Ev=new nm;Ev.setMaxListeners(30);function Pv(){this.__data__=[],this.size=0}function wc(s,t){return s===t||s!==s&&t!==t}function El(s,t){for(var e=s.length;e--;)if(wc(s[e][0],t))return e;return-1}var _v=Array.prototype,Cv=_v.splice;function wv(s){var t=this.__data__,e=El(t,s);if(e<0)return!1;var r=t.length-1;return e==r?t.pop():Cv.call(t,e,1),--this.size,!0}function Rv(s){var t=this.__data__,e=El(t,s);return e<0?void 0:t[e][1]}function bv(s){return El(this.__data__,s)>-1}function kv(s,t){var e=this.__data__,r=El(e,s);return r<0?(++this.size,e.push([s,t])):e[r][1]=t,this}function mr(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}mr.prototype.clear=Pv;mr.prototype.delete=wv;mr.prototype.get=Rv;mr.prototype.has=bv;mr.prototype.set=kv;function Iv(){this.__data__=new mr,this.size=0}function Av(s){var t=this.__data__,e=t.delete(s);return this.size=t.size,e}function Mv(s){return this.__data__.get(s)}function Dv(s){return this.__data__.has(s)}var Ov=typeof global=="object"&&global&&global.Object===Object&&global;const am=Ov;var Nv=typeof self=="object"&&self&&self.Object===Object&&self,Vv=am||Nv||Function("return this")();const Ps=Vv;var Lv=Ps.Symbol;const Vs=Lv;var om=Object.prototype,xv=om.hasOwnProperty,Uv=om.toString,Ka=Vs?Vs.toStringTag:void 0;function $v(s){var t=xv.call(s,Ka),e=s[Ka];try{s[Ka]=void 0;var r=!0}catch(a){}var i=Uv.call(s);return r&&(t?s[Ka]=e:delete s[Ka]),i}var Fv=Object.prototype,Bv=Fv.toString;function Hv(s){return Bv.call(s)}var qv="[object Null]",jv="[object Undefined]",Hh=Vs?Vs.toStringTag:void 0;function tn(s){return s==null?s===void 0?jv:qv:Hh&&Hh in Object(s)?$v(s):Hv(s)}function ss(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var Gv="[object AsyncFunction]",Wv="[object Function]",Jv="[object GeneratorFunction]",Kv="[object Proxy]";function eh(s){if(!ss(s))return!1;var t=tn(s);return t==Wv||t==Jv||t==Gv||t==Kv}var zv=Ps["__core-js_shared__"];const ql=zv;var qh=function(){var s=/[^.]+$/.exec(ql&&ql.keys&&ql.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function Yv(s){return!!qh&&qh in s}var Qv=Function.prototype,Xv=Qv.toString;function sn(s){if(s!=null){try{return Xv.call(s)}catch(t){}try{return s+""}catch(t){}}return""}var Zv=/[\\^$.*+?()[\]{}|]/g,eS=/^\[object .+?Constructor\]$/,tS=Function.prototype,sS=Object.prototype,rS=tS.toString,iS=sS.hasOwnProperty,nS=RegExp("^"+rS.call(iS).replace(Zv,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function aS(s){if(!ss(s)||Yv(s))return!1;var t=eh(s)?nS:eS;return t.test(sn(s))}function oS(s,t){return s==null?void 0:s[t]}function rn(s,t){var e=oS(s,t);return aS(e)?e:void 0}var cS=rn(Ps,"Map");const fo=cS;var dS=rn(Object,"create");const To=dS;function lS(){this.__data__=To?To(null):{},this.size=0}function uS(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var hS="__lodash_hash_undefined__",pS=Object.prototype,gS=pS.hasOwnProperty;function mS(s){var t=this.__data__;if(To){var e=t[s];return e===hS?void 0:e}return gS.call(t,s)?t[s]:void 0}var fS=Object.prototype,TS=fS.hasOwnProperty;function vS(s){var t=this.__data__;return To?t[s]!==void 0:TS.call(t,s)}var SS="__lodash_hash_undefined__";function yS(s,t){var e=this.__data__;return this.size+=this.has(s)?0:1,e[s]=To&&t===void 0?SS:t,this}function Zi(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}Zi.prototype.clear=lS;Zi.prototype.delete=uS;Zi.prototype.get=mS;Zi.prototype.has=vS;Zi.prototype.set=yS;function ES(){this.size=0,this.__data__={hash:new Zi,map:new(fo||mr),string:new Zi}}function PS(s){var t=typeof s;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?s!=="__proto__":s===null}function Pl(s,t){var e=s.__data__;return PS(t)?e[typeof t=="string"?"string":"hash"]:e.map}function _S(s){var t=Pl(this,s).delete(s);return this.size-=t?1:0,t}function CS(s){return Pl(this,s).get(s)}function wS(s){return Pl(this,s).has(s)}function RS(s,t){var e=Pl(this,s),r=e.size;return e.set(s,t),this.size+=e.size==r?0:1,this}function fr(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}fr.prototype.clear=ES;fr.prototype.delete=_S;fr.prototype.get=CS;fr.prototype.has=wS;fr.prototype.set=RS;var bS=200;function kS(s,t){var e=this.__data__;if(e instanceof mr){var r=e.__data__;if(!fo||r.length<bS-1)return r.push([s,t]),this.size=++e.size,this;e=this.__data__=new fr(r)}return e.set(s,t),this.size=e.size,this}function Es(s){var t=this.__data__=new mr(s);this.size=t.size}Es.prototype.clear=Iv;Es.prototype.delete=Av;Es.prototype.get=Mv;Es.prototype.has=Dv;Es.prototype.set=kS;function IS(s,t){for(var e=-1,r=s==null?0:s.length;++e<r&&t(s[e],e,s)!==!1;);return s}var AS=function(){try{var s=rn(Object,"defineProperty");return s({},"",{}),s}catch(t){}}();const hd=AS;function th(s,t,e){t=="__proto__"&&hd?hd(s,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):s[t]=e}var MS=Object.prototype,DS=MS.hasOwnProperty;function cm(s,t,e){var r=s[t];(!(DS.call(s,t)&&wc(r,e))||e===void 0&&!(t in s))&&th(s,t,e)}function Rc(s,t,e,r){var i=!e;e||(e={});for(var a=-1,o=t.length;++a<o;){var c=t[a],d=r?r(e[c],s[c],c,e,s):void 0;d===void 0&&(d=s[c]),i?th(e,c,d):cm(e,c,d)}return e}function OS(s,t){for(var e=-1,r=Array(s);++e<s;)r[e]=t(e);return r}function Ls(s){return s!=null&&typeof s=="object"}var NS="[object Arguments]";function jh(s){return Ls(s)&&tn(s)==NS}var dm=Object.prototype,VS=dm.hasOwnProperty,LS=dm.propertyIsEnumerable,xS=jh(function(){return arguments}())?jh:function(s){return Ls(s)&&VS.call(s,"callee")&&!LS.call(s,"callee")};const vo=xS;var US=Array.isArray;const Vt=US;function $S(){return!1}var lm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Gh=lm&&typeof module=="object"&&module&&!module.nodeType&&module,FS=Gh&&Gh.exports===lm,Wh=FS?Ps.Buffer:void 0,BS=Wh?Wh.isBuffer:void 0,HS=BS||$S;const Ca=HS;var qS=9007199254740991,jS=/^(?:0|[1-9]\d*)$/;function sh(s,t){var e=typeof s;return t=t==null?qS:t,!!t&&(e=="number"||e!="symbol"&&jS.test(s))&&s>-1&&s%1==0&&s<t}var GS=9007199254740991;function rh(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=GS}var WS="[object Arguments]",JS="[object Array]",KS="[object Boolean]",zS="[object Date]",YS="[object Error]",QS="[object Function]",XS="[object Map]",ZS="[object Number]",ey="[object Object]",ty="[object RegExp]",sy="[object Set]",ry="[object String]",iy="[object WeakMap]",ny="[object ArrayBuffer]",ay="[object DataView]",oy="[object Float32Array]",cy="[object Float64Array]",dy="[object Int8Array]",ly="[object Int16Array]",uy="[object Int32Array]",hy="[object Uint8Array]",py="[object Uint8ClampedArray]",gy="[object Uint16Array]",my="[object Uint32Array]",me={};me[oy]=me[cy]=me[dy]=me[ly]=me[uy]=me[hy]=me[py]=me[gy]=me[my]=!0;me[WS]=me[JS]=me[ny]=me[KS]=me[ay]=me[zS]=me[YS]=me[QS]=me[XS]=me[ZS]=me[ey]=me[ty]=me[sy]=me[ry]=me[iy]=!1;function fy(s){return Ls(s)&&rh(s.length)&&!!me[tn(s)]}function ih(s){return function(t){return s(t)}}var um=typeof exports=="object"&&exports&&!exports.nodeType&&exports,co=um&&typeof module=="object"&&module&&!module.nodeType&&module,Ty=co&&co.exports===um,jl=Ty&&am.process,vy=function(){try{var s=co&&co.require&&co.require("util").types;return s||jl&&jl.binding&&jl.binding("util")}catch(t){}}();const wa=vy;var Jh=wa&&wa.isTypedArray,Sy=Jh?ih(Jh):fy;const _l=Sy;var yy=Object.prototype,Ey=yy.hasOwnProperty;function hm(s,t){var e=Vt(s),r=!e&&vo(s),i=!e&&!r&&Ca(s),a=!e&&!r&&!i&&_l(s),o=e||r||i||a,c=o?OS(s.length,String):[],d=c.length;for(var l in s)(t||Ey.call(s,l))&&!(o&&(l=="length"||i&&(l=="offset"||l=="parent")||a&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||sh(l,d)))&&c.push(l);return c}var Py=Object.prototype;function Cl(s){var t=s&&s.constructor,e=typeof t=="function"&&t.prototype||Py;return s===e}function pm(s,t){return function(e){return s(t(e))}}var _y=pm(Object.keys,Object);const Cy=_y;var wy=Object.prototype,Ry=wy.hasOwnProperty;function gm(s){if(!Cl(s))return Cy(s);var t=[];for(var e in Object(s))Ry.call(s,e)&&e!="constructor"&&t.push(e);return t}function bc(s){return s!=null&&rh(s.length)&&!eh(s)}function wl(s){return bc(s)?hm(s):gm(s)}function by(s,t){return s&&Rc(t,wl(t),s)}function ky(s){var t=[];if(s!=null)for(var e in Object(s))t.push(e);return t}var Iy=Object.prototype,Ay=Iy.hasOwnProperty;function My(s){if(!ss(s))return ky(s);var t=Cl(s),e=[];for(var r in s)r=="constructor"&&(t||!Ay.call(s,r))||e.push(r);return e}function kc(s){return bc(s)?hm(s,!0):My(s)}function Dy(s,t){return s&&Rc(t,kc(t),s)}var mm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Kh=mm&&typeof module=="object"&&module&&!module.nodeType&&module,Oy=Kh&&Kh.exports===mm,zh=Oy?Ps.Buffer:void 0,Yh=zh?zh.allocUnsafe:void 0;function fm(s,t){if(t)return s.slice();var e=s.length,r=Yh?Yh(e):new s.constructor(e);return s.copy(r),r}function Tm(s,t){var e=-1,r=s.length;for(t||(t=Array(r));++e<r;)t[e]=s[e];return t}function Ny(s,t){for(var e=-1,r=s==null?0:s.length,i=0,a=[];++e<r;){var o=s[e];t(o,e,s)&&(a[i++]=o)}return a}function vm(){return[]}var Vy=Object.prototype,Ly=Vy.propertyIsEnumerable,Qh=Object.getOwnPropertySymbols,xy=Qh?function(s){return s==null?[]:(s=Object(s),Ny(Qh(s),function(t){return Ly.call(s,t)}))}:vm;const nh=xy;function Uy(s,t){return Rc(s,nh(s),t)}function Sm(s,t){for(var e=-1,r=t.length,i=s.length;++e<r;)s[i+e]=t[e];return s}var $y=pm(Object.getPrototypeOf,Object);const ah=$y;var Fy=Object.getOwnPropertySymbols,By=Fy?function(s){for(var t=[];s;)Sm(t,nh(s)),s=ah(s);return t}:vm;const ym=By;function Hy(s,t){return Rc(s,ym(s),t)}function Em(s,t,e){var r=t(s);return Vt(s)?r:Sm(r,e(s))}function iu(s){return Em(s,wl,nh)}function qy(s){return Em(s,kc,ym)}var jy=rn(Ps,"DataView");const nu=jy;var Gy=rn(Ps,"Promise");const au=Gy;var Wy=rn(Ps,"Set");const En=Wy;var Jy=rn(Ps,"WeakMap");const ou=Jy;var Xh="[object Map]",Ky="[object Object]",Zh="[object Promise]",ep="[object Set]",tp="[object WeakMap]",sp="[object DataView]",zy=sn(nu),Yy=sn(fo),Qy=sn(au),Xy=sn(En),Zy=sn(ou),ti=tn;(nu&&ti(new nu(new ArrayBuffer(1)))!=sp||fo&&ti(new fo)!=Xh||au&&ti(au.resolve())!=Zh||En&&ti(new En)!=ep||ou&&ti(new ou)!=tp)&&(ti=function(s){var t=tn(s),e=t==Ky?s.constructor:void 0,r=e?sn(e):"";if(r)switch(r){case zy:return sp;case Yy:return Xh;case Qy:return Zh;case Xy:return ep;case Zy:return tp}return t});const Ra=ti;var eE=Object.prototype,tE=eE.hasOwnProperty;function sE(s){var t=s.length,e=new s.constructor(t);return t&&typeof s[0]=="string"&&tE.call(s,"index")&&(e.index=s.index,e.input=s.input),e}var rE=Ps.Uint8Array;const pd=rE;function oh(s){var t=new s.constructor(s.byteLength);return new pd(t).set(new pd(s)),t}function iE(s,t){var e=t?oh(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.byteLength)}var nE=/\w*$/;function aE(s){var t=new s.constructor(s.source,nE.exec(s));return t.lastIndex=s.lastIndex,t}var rp=Vs?Vs.prototype:void 0,ip=rp?rp.valueOf:void 0;function oE(s){return ip?Object(ip.call(s)):{}}function Pm(s,t){var e=t?oh(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.length)}var cE="[object Boolean]",dE="[object Date]",lE="[object Map]",uE="[object Number]",hE="[object RegExp]",pE="[object Set]",gE="[object String]",mE="[object Symbol]",fE="[object ArrayBuffer]",TE="[object DataView]",vE="[object Float32Array]",SE="[object Float64Array]",yE="[object Int8Array]",EE="[object Int16Array]",PE="[object Int32Array]",_E="[object Uint8Array]",CE="[object Uint8ClampedArray]",wE="[object Uint16Array]",RE="[object Uint32Array]";function bE(s,t,e){var r=s.constructor;switch(t){case fE:return oh(s);case cE:case dE:return new r(+s);case TE:return iE(s,e);case vE:case SE:case yE:case EE:case PE:case _E:case CE:case wE:case RE:return Pm(s,e);case lE:return new r;case uE:case gE:return new r(s);case hE:return aE(s);case pE:return new r;case mE:return oE(s)}}var np=Object.create,kE=function(){function s(){}return function(t){if(!ss(t))return{};if(np)return np(t);s.prototype=t;var e=new s;return s.prototype=void 0,e}}();const IE=kE;function _m(s){return typeof s.constructor=="function"&&!Cl(s)?IE(ah(s)):{}}var AE="[object Map]";function ME(s){return Ls(s)&&Ra(s)==AE}var ap=wa&&wa.isMap,DE=ap?ih(ap):ME;const OE=DE;var NE="[object Set]";function VE(s){return Ls(s)&&Ra(s)==NE}var op=wa&&wa.isSet,LE=op?ih(op):VE;const xE=LE;var UE=1,$E=2,FE=4,Cm="[object Arguments]",BE="[object Array]",HE="[object Boolean]",qE="[object Date]",jE="[object Error]",wm="[object Function]",GE="[object GeneratorFunction]",WE="[object Map]",JE="[object Number]",Rm="[object Object]",KE="[object RegExp]",zE="[object Set]",YE="[object String]",QE="[object Symbol]",XE="[object WeakMap]",ZE="[object ArrayBuffer]",eP="[object DataView]",tP="[object Float32Array]",sP="[object Float64Array]",rP="[object Int8Array]",iP="[object Int16Array]",nP="[object Int32Array]",aP="[object Uint8Array]",oP="[object Uint8ClampedArray]",cP="[object Uint16Array]",dP="[object Uint32Array]",ue={};ue[Cm]=ue[BE]=ue[ZE]=ue[eP]=ue[HE]=ue[qE]=ue[tP]=ue[sP]=ue[rP]=ue[iP]=ue[nP]=ue[WE]=ue[JE]=ue[Rm]=ue[KE]=ue[zE]=ue[YE]=ue[QE]=ue[aP]=ue[oP]=ue[cP]=ue[dP]=!0;ue[jE]=ue[wm]=ue[XE]=!1;function zc(s,t,e,r,i,a){var o,c=t&UE,d=t&$E,l=t&FE;if(e&&(o=i?e(s,r,i,a):e(s)),o!==void 0)return o;if(!ss(s))return s;var h=Vt(s);if(h){if(o=sE(s),!c)return Tm(s,o)}else{var p=Ra(s),f=p==wm||p==GE;if(Ca(s))return fm(s,c);if(p==Rm||p==Cm||f&&!i){if(o=d||f?{}:_m(s),!c)return d?Hy(s,Dy(o,s)):Uy(s,by(o,s))}else{if(!ue[p])return i?s:{};o=bE(s,p,c)}}a||(a=new Es);var T=a.get(s);if(T)return T;a.set(s,o),xE(s)?s.forEach(function(_){o.add(zc(_,t,e,_,s,a))}):OE(s)&&s.forEach(function(_,I){o.set(I,zc(_,t,e,I,s,a))});var E=l?d?qy:iu:d?kc:wl,C=h?void 0:E(s);return IS(C||s,function(_,I){C&&(I=_,_=s[I]),cm(o,I,zc(_,t,e,I,s,a))}),o}var lP=1,uP=4;function ch(s){return zc(s,lP|uP)}var hP="[object Symbol]";function Rl(s){return typeof s=="symbol"||Ls(s)&&tn(s)==hP}var pP=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,gP=/^\w*$/;function dh(s,t){if(Vt(s))return!1;var e=typeof s;return e=="number"||e=="symbol"||e=="boolean"||s==null||Rl(s)?!0:gP.test(s)||!pP.test(s)||t!=null&&s in Object(t)}var mP="Expected a function";function lh(s,t){if(typeof s!="function"||t!=null&&typeof t!="function")throw new TypeError(mP);var e=function(){var r=arguments,i=t?t.apply(this,r):r[0],a=e.cache;if(a.has(i))return a.get(i);var o=s.apply(this,r);return e.cache=a.set(i,o)||a,o};return e.cache=new(lh.Cache||fr),e}lh.Cache=fr;var fP=500;function TP(s){var t=lh(s,function(r){return e.size===fP&&e.clear(),r}),e=t.cache;return t}var vP=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,SP=/\\(\\)?/g,yP=TP(function(s){var t=[];return s.charCodeAt(0)===46&&t.push(""),s.replace(vP,function(e,r,i,a){t.push(i?a.replace(SP,"$1"):r||e)}),t});const EP=yP;function PP(s,t){for(var e=-1,r=s==null?0:s.length,i=Array(r);++e<r;)i[e]=t(s[e],e,s);return i}var _P=1/0,cp=Vs?Vs.prototype:void 0,dp=cp?cp.toString:void 0;function bm(s){if(typeof s=="string")return s;if(Vt(s))return PP(s,bm)+"";if(Rl(s))return dp?dp.call(s):"";var t=s+"";return t=="0"&&1/s==-_P?"-0":t}function CP(s){return s==null?"":bm(s)}function km(s,t){return Vt(s)?s:dh(s,t)?[s]:EP(CP(s))}var wP=1/0;function bl(s){if(typeof s=="string"||Rl(s))return s;var t=s+"";return t=="0"&&1/s==-wP?"-0":t}function Im(s,t){t=km(t,s);for(var e=0,r=t.length;s!=null&&e<r;)s=s[bl(t[e++])];return e&&e==r?s:void 0}function RP(s,t,e){var r=s==null?void 0:Im(s,t);return r===void 0?e:r}function bP(s,t,e){t=km(t,s);for(var r=-1,i=t.length,a=!1;++r<i;){var o=bl(t[r]);if(!(a=s!=null&&e(s,o)))break;s=s[o]}return a||++r!=i?a:(i=s==null?0:s.length,!!i&&rh(i)&&sh(o,i)&&(Vt(s)||vo(s)))}var kP=Object.defineProperty,IP=(s,t)=>{for(var e in t)kP(s,e,{get:t[e],enumerable:!0})},AP={};IP(AP,{permissions:()=>MP,theme:()=>DP});var lr=(s=>(s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT",s))(lr||{}),F=(s=>(s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST",s))(F||{}),MP={view_type:"GROUP_CALL",accept_waiting_requests:!1,accept_present_requests:!1,request_produce:!1,can_allow_participant_audio:!1,can_allow_participant_screensharing:!1,can_allow_participant_video:!1,can_spotlight:!1,request_kick_participant:!1,kick_participant:!1,pin_participant:!1,can_edit_display_name:!1,can_record:!1,can_livestream:!1,can_present:!0,waiting_room_type:"SKIP_ON_ACCEPT",recorder_type:"NONE",plugins:{can_close:!0,can_start:!0},polls:{can_create:!0,can_vote:!0,can_view:!0},produce:{video:{allow:!0,quality:"vga",frame_rate:24},audio:!0,screenshare:{allow:!0,quality:"hd",frame_rate:5}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1}},connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},reactions:!1,hidden_participant:!1,is_recorder:!1,show_participant_list:!0,can_change_participant_role:!1,can_change_theme:!1,max_screenshare_count:1},DP={setup_screen:{is_enabled:!0},alone_here:{is_enabled:!0},waiting_room:{is_enabled:!1,enable_preview:!0},control_bar:{is_enabled:!0,elements:{plugins:!0,screenshare:!0,invite:!0,participants:!0,chat:!0,reactions:!1,polls:!0,fullscreen:!0,layout:!0}},header:{is_enabled:!0,elements:{timer:!0,title:!0,participant_count:!0,change_layout:!0}},pip_mode:!0,auto_tune:!0,grid:{multi:{maxVideoCount:6,videoFit:"cover"},single:{maxVideoCount:6,videoFit:"cover"},defaultView:"multi"},controls:{pip_toggle:!1}},Am="hXgU8Wc8pwuGNq9ms5q9Hh",og;typeof process!="undefined"&&(og=process==null?void 0:process.env)!=null&&og.FLAGSMITH_ENVIRONMENT_KEY&&(Am=process.env.FLAGSMITH_ENVIRONMENT_KEY);function OP(s=[]){const t={};return s.forEach(e=>{t[e.feature.name]={enabled:e.enabled,value:e.feature_state_value}}),t}var Mm=class{constructor(s=Am){u(this,"flags",{});u(this,"environmentKey",null);this.environmentKey=s}async identifyAndFetchFlagsWithRetry({primaryEndpoint:s,secondaryEndpoint:t,forceEvaluate:e,timeout:r,uniqueIdentifier:i,traitsObj:a,logger:o}){const c=JSON.parse(JSON.stringify(a)),d=Object.entries(c).map(h=>({trait_key:h[0],trait_value:h[1]})),l=[s,t,t];for(const h of l)try{const p=new AbortController,f=setTimeout(()=>p.abort(),r),T=`_${(Math.random()+1).toString(36).substring(2)}`,E=await fetch(`https://${h}/api/v1/identities/`,{method:"POST",headers:{"Content-Type":"application/json","X-Environment-Key":this.environmentKey},body:JSON.stringify({identifier:i+(e?T:""),traits:d}),signal:p.signal});if(clearTimeout(f),!E.ok)throw new Error(`Request failed with status ${E.status}`);const C=await E.json();return OP(C.flags||[])}catch(p){o.error("Flagsmith identify failed!!",{error:p,url:h})}return{}}async identify(s,t={},e=!1,r=5e3,i="edge.api.flagsmith.com",a=console){return this.flags=await this.identifyAndFetchFlagsWithRetry({traitsObj:t,uniqueIdentifier:s,forceEvaluate:e,timeout:r,primaryEndpoint:i,secondaryEndpoint:"edge.api.flagsmith.com",logger:a}),this.flags}getValue(s){return this.flags&&this.flags[s]&&this.flags[s].value}hasFeature(s){return this.flags&&this.flags[s]&&this.flags[s].enabled}getAllFlags(){return this.flags}},NP=new Mm;function VP(s){return new Mm(s)}var Dm=[-2,-1,0,1,2],LP=[0,1,2,3,4];function xP(s){s=s.trim();let t="0",e="0",r="0";return s.length==4?(t=`0x${s[1]}${s[1]}`,e=`0x${s[2]}${s[2]}`,r=`0x${s[3]}${s[3]}`):s.length>6&&(t=`0x${s[1]}${s[2]}`,e=`0x${s[3]}${s[4]}`,r=`0x${s[5]}${s[6]}`),[+t,+e,+r]}var UP=(s,t,e)=>{let r,i,a;if(t==0)r=i=a=e;else{const o=(l,h,p)=>(p<0&&(p+=1),p>1&&(p-=1),p<.16666666666666666?l+(h-l)*6*p:p<.5?h:p<.6666666666666666?l+(h-l)*(.6666666666666666-p)*6:l),c=e<.5?e*(1+t):e+t-e*t,d=2*e-c;r=o(d,c,s+1/3),i=o(d,c,s),a=o(d,c,s-1/3)}return[Math.round(r*255),Math.round(i*255),Math.round(a*255)]},$P=(s,t,e)=>{s/=255,t/=255,e/=255;const r=Math.max(s,t,e),i=Math.min(s,t,e);let a,o;const c=(r+i)/2;if(r==i)a=o=0;else{const d=r-i;switch(o=c>.5?d/(2-r-i):d/(r+i),r){case s:a=(t-e)/d+(t<e?6:0);break;case t:a=(e-s)/d+2;break;case e:a=(s-t)/d+4;break}a/=6}return[a,o,c]},FP=(s,t,e)=>{const r=i=>i.toString(16).padStart(2,"0");return`#${r(s)}${r(t)}${r(e)}`},Om=(s,t=Dm,e=.4)=>{const r=[],[i,a,o]=xP(s),[c,d,l]=$P(i,a,o),h=Math.round(l*100);h>70?e=.8:h>60?e=.9:h<10?e=.075:h<42&&(e=.3);const p=t.findIndex(_=>_===0);if(p===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const f=5-p,T=p+1,E=(100-h)/f,C=h/T;for(const _ of t){let I;_<0?I=h+_*C*e:_>0?I=h+_*E*e:I=h;const[M,x,N]=UP(c,d,I/100);r.push(FP(M,x,N))}return r},lp={dark:{background:{1e3:"#252525",900:"#2F2F2F",800:"#323232",700:"#3E3E3E",600:"#4A4A4A"},text:"#F5F5F5","video-bg":"#1C1C1C"},light:{background:{1e3:"#FFFFFF",900:"#F5F5F5",800:"#EBEBEB",700:"#E0E0E0",600:"#D6D6D6"},text:"#111111","text-on-brand":"#ffffff","video-bg":"#DADADA"}},BP=s=>{const[t,e,r,i,a]=Om(s,Dm);return{300:t,400:e,500:r,600:i,700:a}},HP=s=>{if(s==="#FFFFFF")return lp.light.background;if(s==="#000000")return lp.dark.background;const[t,e,r,i,a]=Om(s,LP);return{1e3:t,900:e,800:r,700:i,600:a}},qP={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:BP("#2160FD"),background:HP("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function Nm(){return ch(qP)}var jP={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED",can_consume:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED",can_consume:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1},channel:{can_create:"ALL",can_delete:"ALL",can_update:"ALL",can_read_all:!1},message:{can_delete:"ALL",can_edit:"ALL",delete_cutoff_time_seconds:0,edit_cutoff_time_seconds:0}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{oldTheme:{setup_screen:{is_enabled:!1},alone_here:{is_enabled:!1},waiting_room:{is_enabled:!1,enable_preview:!0},control_bar:{is_enabled:!0,elements:{plugins:!0,screenshare:!0,invite:!1,participants:!0,chat:!0,reactions:!1,polls:!0,fullscreen:!0,layout:!0}},header:{is_enabled:!0,elements:{timer:!0,title:!0,participant_count:!0,change_layout:!0}},pip_mode:!0,auto_tune:!0,colors:{primary:"#2160FD",secondary:"#1A1A1A",text:"#EEEEEE",background:"#1A1A1A",textPrimary:"#EEEEEE",videoBackground:"#1A1A1A"},dimensions:{mode:"fillParent"},grid:{multi:{maxVideoCount:6,videoFit:"cover"},single:{maxVideoCount:6,videoFit:"cover"},defaultView:"MULTI"},controls:{pip_toggle:!1},plugins:[]},design_tokens:Nm(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:24},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"hybrid"};function GP(){return ch(jP)}var WP={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{design_tokens:Nm(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:24},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"2.0.0"};function uh(){return ch(WP)}var Eo;class Vm{constructor(){g(this,Eo,void 0)}get telemetry(){var t;return(t=n(this,Eo))==null?void 0:t.getValue("telemetry")}init(t){m(this,Eo,t)}info(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("info",t,e,r)}error(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("error",t,e,r)}debug(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("debug",t,e,r)}log(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("log",t,e,r)}warn(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("warn",t,e,r)}}Eo=new WeakMap;var Fs,Bs;class JP extends nt.EventEmitter{constructor(e){super();g(this,Fs,void 0);g(this,Bs,void 0);u(this,"asyncPromiseTimeout");u(this,"logger");this.logger=e,m(this,Fs,new Map),m(this,Bs,new Map),this.asyncPromiseTimeout=8e3}async emitAsync(e,...r){n(this,Fs).set(e,[]);const i=n(this,Bs).get(e).map(()=>new Promise(a=>{n(this,Fs).get(e).push(a)}));super.emit(e,...r),await Promise.race([Promise.all(i),new Promise((a,o)=>setTimeout(()=>o(new Error(`emitAsync failed to resolve for event ${e}.`)),this.asyncPromiseTimeout))]),n(this,Fs).delete(e)}onAsync(e,r){const i=n(this,Fs),a=async(...o)=>{var d;try{await r(...o)}catch(l){this.logger.error("[onAsync]",{error:l})}const c=(d=i.get(e))==null?void 0:d.shift();c==null||c()};return n(this,Bs).get(e)||n(this,Bs).set(e,[]),n(this,Bs).get(e).push(a),super.on(e,a)}reset(){m(this,Fs,new Map),m(this,Bs,new Map),super.removeAllListeners()}}Fs=new WeakMap,Bs=new WeakMap;var KP=/\s/;function zP(s){for(var t=s.length;t--&&KP.test(s.charAt(t)););return t}var YP=/^\s+/;function QP(s){return s&&s.slice(0,zP(s)+1).replace(YP,"")}var up=0/0,XP=/^[-+]0x[0-9a-f]+$/i,ZP=/^0b[01]+$/i,e_=/^0o[0-7]+$/i,t_=parseInt;function hp(s){if(typeof s=="number")return s;if(Rl(s))return up;if(ss(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=ss(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=QP(s);var e=ZP.test(s);return e||e_.test(s)?t_(s.slice(2),e?2:8):XP.test(s)?up:+s}function hh(s){return s}function s_(s,t,e){switch(e.length){case 0:return s.call(t);case 1:return s.call(t,e[0]);case 2:return s.call(t,e[0],e[1]);case 3:return s.call(t,e[0],e[1],e[2])}return s.apply(t,e)}function r_(){}var i_=800,n_=16,a_=Date.now;function o_(s){var t=0,e=0;return function(){var r=a_(),i=n_-(r-e);if(e=r,i>0){if(++t>=i_)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}function c_(s){return function(){return s}}var d_=hd?function(s,t){return hd(s,"toString",{configurable:!0,enumerable:!1,value:c_(t),writable:!0})}:hh;const l_=d_;var u_=o_(l_);const h_=u_;function p_(s,t,e,r){for(var i=s.length,a=e+(r?1:-1);r?a--:++a<i;)if(t(s[a],a,s))return a;return-1}function g_(s){return s!==s}function m_(s,t,e){for(var r=e-1,i=s.length;++r<i;)if(s[r]===t)return r;return-1}function f_(s,t,e){return t===t?m_(s,t,e):p_(s,g_,e)}function T_(s,t){var e=s==null?0:s.length;return!!e&&f_(s,t,0)>-1}var pp=Math.max;function v_(s,t,e){return t=pp(t===void 0?s.length-1:t,0),function(){for(var r=arguments,i=-1,a=pp(r.length-t,0),o=Array(a);++i<a;)o[i]=r[t+i];i=-1;for(var c=Array(t+1);++i<t;)c[i]=r[i];return c[t]=e(o),s_(s,this,c)}}function S_(s,t){return h_(v_(s,t,hh),s+"")}function y_(s,t,e){if(!ss(e))return!1;var r=typeof t;return(r=="number"?bc(e)&&sh(t,e.length):r=="string"&&t in e)?wc(e[t],s):!1}function E_(s){return S_(function(t,e){var r=-1,i=e.length,a=i>1?e[i-1]:void 0,o=i>2?e[2]:void 0;for(a=s.length>3&&typeof a=="function"?(i--,a):void 0,o&&y_(e[0],e[1],o)&&(a=i<3?void 0:a,i=1),t=Object(t);++r<i;){var c=e[r];c&&s(t,c,r,a)}return t})}var P_="[object Object]",__=Function.prototype,C_=Object.prototype,Lm=__.toString,w_=C_.hasOwnProperty,R_=Lm.call(Object);function b_(s){if(!Ls(s)||tn(s)!=P_)return!1;var t=ah(s);if(t===null)return!0;var e=w_.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Lm.call(e)==R_}var k_="__lodash_hash_undefined__";function I_(s){return this.__data__.set(s,k_),this}function A_(s){return this.__data__.has(s)}function So(s){var t=-1,e=s==null?0:s.length;for(this.__data__=new fr;++t<e;)this.add(s[t])}So.prototype.add=So.prototype.push=I_;So.prototype.has=A_;function M_(s,t){for(var e=-1,r=s==null?0:s.length;++e<r;)if(t(s[e],e,s))return!0;return!1}function xm(s,t){return s.has(t)}var D_=1,O_=2;function Um(s,t,e,r,i,a){var o=e&D_,c=s.length,d=t.length;if(c!=d&&!(o&&d>c))return!1;var l=a.get(s),h=a.get(t);if(l&&h)return l==t&&h==s;var p=-1,f=!0,T=e&O_?new So:void 0;for(a.set(s,t),a.set(t,s);++p<c;){var E=s[p],C=t[p];if(r)var _=o?r(C,E,p,t,s,a):r(E,C,p,s,t,a);if(_!==void 0){if(_)continue;f=!1;break}if(T){if(!M_(t,function(I,M){if(!xm(T,M)&&(E===I||i(E,I,e,r,a)))return T.push(M)})){f=!1;break}}else if(!(E===C||i(E,C,e,r,a))){f=!1;break}}return a.delete(s),a.delete(t),f}function N_(s){var t=-1,e=Array(s.size);return s.forEach(function(r,i){e[++t]=[i,r]}),e}function ph(s){var t=-1,e=Array(s.size);return s.forEach(function(r){e[++t]=r}),e}var V_=1,L_=2,x_="[object Boolean]",U_="[object Date]",$_="[object Error]",F_="[object Map]",B_="[object Number]",H_="[object RegExp]",q_="[object Set]",j_="[object String]",G_="[object Symbol]",W_="[object ArrayBuffer]",J_="[object DataView]",gp=Vs?Vs.prototype:void 0,Gl=gp?gp.valueOf:void 0;function K_(s,t,e,r,i,a,o){switch(e){case J_:if(s.byteLength!=t.byteLength||s.byteOffset!=t.byteOffset)return!1;s=s.buffer,t=t.buffer;case W_:return!(s.byteLength!=t.byteLength||!a(new pd(s),new pd(t)));case x_:case U_:case B_:return wc(+s,+t);case $_:return s.name==t.name&&s.message==t.message;case H_:case j_:return s==t+"";case F_:var c=N_;case q_:var d=r&V_;if(c||(c=ph),s.size!=t.size&&!d)return!1;var l=o.get(s);if(l)return l==t;r|=L_,o.set(s,t);var h=Um(c(s),c(t),r,i,a,o);return o.delete(s),h;case G_:if(Gl)return Gl.call(s)==Gl.call(t)}return!1}var z_=1,Y_=Object.prototype,Q_=Y_.hasOwnProperty;function X_(s,t,e,r,i,a){var o=e&z_,c=iu(s),d=c.length,l=iu(t),h=l.length;if(d!=h&&!o)return!1;for(var p=d;p--;){var f=c[p];if(!(o?f in t:Q_.call(t,f)))return!1}var T=a.get(s),E=a.get(t);if(T&&E)return T==t&&E==s;var C=!0;a.set(s,t),a.set(t,s);for(var _=o;++p<d;){f=c[p];var I=s[f],M=t[f];if(r)var x=o?r(M,I,f,t,s,a):r(I,M,f,s,t,a);if(!(x===void 0?I===M||i(I,M,e,r,a):x)){C=!1;break}_||(_=f=="constructor")}if(C&&!_){var N=s.constructor,$=t.constructor;N!=$&&"constructor"in s&&"constructor"in t&&!(typeof N=="function"&&N instanceof N&&typeof $=="function"&&$ instanceof $)&&(C=!1)}return a.delete(s),a.delete(t),C}var Z_=1,mp="[object Arguments]",fp="[object Array]",xc="[object Object]",eC=Object.prototype,Tp=eC.hasOwnProperty;function tC(s,t,e,r,i,a){var o=Vt(s),c=Vt(t),d=o?fp:Ra(s),l=c?fp:Ra(t);d=d==mp?xc:d,l=l==mp?xc:l;var h=d==xc,p=l==xc,f=d==l;if(f&&Ca(s)){if(!Ca(t))return!1;o=!0,h=!1}if(f&&!h)return a||(a=new Es),o||_l(s)?Um(s,t,e,r,i,a):K_(s,t,d,e,r,i,a);if(!(e&Z_)){var T=h&&Tp.call(s,"__wrapped__"),E=p&&Tp.call(t,"__wrapped__");if(T||E){var C=T?s.value():s,_=E?t.value():t;return a||(a=new Es),i(C,_,e,r,a)}}return f?(a||(a=new Es),X_(s,t,e,r,i,a)):!1}function kl(s,t,e,r,i){return s===t?!0:s==null||t==null||!Ls(s)&&!Ls(t)?s!==s&&t!==t:tC(s,t,e,r,kl,i)}var sC=1,rC=2;function iC(s,t,e,r){var i=e.length,a=i,o=!r;if(s==null)return!a;for(s=Object(s);i--;){var c=e[i];if(o&&c[2]?c[1]!==s[c[0]]:!(c[0]in s))return!1}for(;++i<a;){c=e[i];var d=c[0],l=s[d],h=c[1];if(o&&c[2]){if(l===void 0&&!(d in s))return!1}else{var p=new Es;if(r)var f=r(l,h,d,s,t,p);if(!(f===void 0?kl(h,l,sC|rC,r,p):f))return!1}}return!0}function $m(s){return s===s&&!ss(s)}function nC(s){for(var t=wl(s),e=t.length;e--;){var r=t[e],i=s[r];t[e]=[r,i,$m(i)]}return t}function Fm(s,t){return function(e){return e==null?!1:e[s]===t&&(t!==void 0||s in Object(e))}}function aC(s){var t=nC(s);return t.length==1&&t[0][2]?Fm(t[0][0],t[0][1]):function(e){return e===s||iC(e,s,t)}}function oC(s,t){return s!=null&&t in Object(s)}function cC(s,t){return s!=null&&bP(s,t,oC)}var dC=1,lC=2;function uC(s,t){return dh(s)&&$m(t)?Fm(bl(s),t):function(e){var r=RP(e,s);return r===void 0&&r===t?cC(e,s):kl(t,r,dC|lC)}}function hC(s){return function(t){return t==null?void 0:t[s]}}function pC(s){return function(t){return Im(t,s)}}function gC(s){return dh(s)?hC(bl(s)):pC(s)}function mC(s){return typeof s=="function"?s:s==null?hh:typeof s=="object"?Vt(s)?uC(s[0],s[1]):aC(s):gC(s)}function fC(s){return function(t,e,r){for(var i=-1,a=Object(t),o=r(t),c=o.length;c--;){var d=o[s?c:++i];if(e(a[d],d,a)===!1)break}return t}}var TC=fC();const vC=TC;var SC=function(){return Ps.Date.now()};const Wl=SC;var yC="Expected a function",EC=Math.max,PC=Math.min;function gh(s,t,e){var r,i,a,o,c,d,l=0,h=!1,p=!1,f=!0;if(typeof s!="function")throw new TypeError(yC);t=hp(t)||0,ss(e)&&(h=!!e.leading,p="maxWait"in e,a=p?EC(hp(e.maxWait)||0,t):a,f="trailing"in e?!!e.trailing:f);function T(q){var ee=r,Qe=i;return r=i=void 0,l=q,o=s.apply(Qe,ee),o}function E(q){return l=q,c=setTimeout(I,t),h?T(q):o}function C(q){var ee=q-d,Qe=q-l,is=t-ee;return p?PC(is,a-Qe):is}function _(q){var ee=q-d,Qe=q-l;return d===void 0||ee>=t||ee<0||p&&Qe>=a}function I(){var q=Wl();if(_(q))return M(q);c=setTimeout(I,C(q))}function M(q){return c=void 0,f&&r?T(q):(r=i=void 0,o)}function x(){c!==void 0&&clearTimeout(c),l=0,r=d=i=c=void 0}function N(){return c===void 0?o:M(Wl())}function $(){var q=Wl(),ee=_(q);if(r=arguments,i=this,d=q,ee){if(c===void 0)return E(d);if(p)return clearTimeout(c),c=setTimeout(I,t),T(d)}return c===void 0&&(c=setTimeout(I,t)),o}return $.cancel=x,$.flush=N,$}function cu(s,t,e){(e!==void 0&&!wc(s[t],e)||e===void 0&&!(t in s))&&th(s,t,e)}function _C(s){return Ls(s)&&bc(s)}function du(s,t){if(!(t==="constructor"&&typeof s[t]=="function")&&t!="__proto__")return s[t]}function CC(s){return Rc(s,kc(s))}function wC(s,t,e,r,i,a,o){var c=du(s,e),d=du(t,e),l=o.get(d);if(l){cu(s,e,l);return}var h=a?a(c,d,e+"",s,t,o):void 0,p=h===void 0;if(p){var f=Vt(d),T=!f&&Ca(d),E=!f&&!T&&_l(d);h=d,f||T||E?Vt(c)?h=c:_C(c)?h=Tm(c):T?(p=!1,h=fm(d,!0)):E?(p=!1,h=Pm(d,!0)):h=[]:b_(d)||vo(d)?(h=c,vo(c)?h=CC(c):(!ss(c)||eh(c))&&(h=_m(d))):p=!1}p&&(o.set(d,h),i(h,d,r,a,o),o.delete(d)),cu(s,e,h)}function Bm(s,t,e,r,i){s!==t&&vC(t,function(a,o){if(i||(i=new Es),ss(a))wC(s,t,o,e,Bm,r,i);else{var c=r?r(du(s,o),a,o+"",s,t,i):void 0;c===void 0&&(c=a),cu(s,o,c)}},kc)}function RC(s,t,e){for(var r=-1,i=s==null?0:s.length;++r<i;)if(e(t,s[r]))return!0;return!1}var bC="[object Map]",kC="[object Set]",IC=Object.prototype,AC=IC.hasOwnProperty;function MC(s){if(s==null)return!0;if(bc(s)&&(Vt(s)||typeof s=="string"||typeof s.splice=="function"||Ca(s)||_l(s)||vo(s)))return!s.length;var t=Ra(s);if(t==bC||t==kC)return!s.size;if(Cl(s))return!gm(s).length;for(var e in s)if(AC.call(s,e))return!1;return!0}function DC(s,t){return kl(s,t)}var OC=E_(function(s,t,e){Bm(s,t,e)});const Er=OC;var NC=1/0,VC=En&&1/ph(new En([,-0]))[1]==NC?function(s){return new En(s)}:r_;const LC=VC;var xC=200;function Hm(s,t,e){var r=-1,i=T_,a=s.length,o=!0,c=[],d=c;if(e)o=!1,i=RC;else if(a>=xC){var l=t?null:LC(s);if(l)return ph(l);o=!1,i=xm,d=new So}else d=t?[]:c;e:for(;++r<a;){var h=s[r],p=t?t(h):h;if(h=e||h!==0?h:0,o&&p===p){for(var f=d.length;f--;)if(d[f]===p)continue e;t&&d.push(p),c.push(h)}else i(d,p,e)||(d!==c&&d.push(p),c.push(h))}return c}function UC(s){return s&&s.length?Hm(s):[]}function $C(s,t){return s&&s.length?Hm(s,mC(t)):[]}var lu=(s=>(s.PARTICIPANT="PARTICIPANT",s.PEER="PEER",s.CLIENT="CLIENT",s))(lu||{});const Y={PROPAGATE_KICK_ALL:"propagate_kick_across_rooms",REFRESH_ID_ON_DISCONNECTION:"refresh_id_on_disconnection",SKIP_OTEL_TRACES:"skip_otel_traces",ENABLE_CF_SIMULCAST:"enable_cf_simulcast",CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED:"cf_transport_force_relay_on_ice_failed",LOG_LEVEL:"log_level",V1_PLUGINS:"v1_plugins",LIVESTREAM:"feat_livestream",VAL_MIN_FRAMERATE:"val_min_framerate",SCREEENSHARE_ERR_HACK:"screenshare_err_hack",SCREEENSHARE_CONSTRAINTS_RETRY:"screenshare_constraints_retry",VIDEO_CONSTRAINTS:"video_constraints",SCREENSHARE_CONSTRAINTS:"screenshare_constraints",OBS_QUALITY:"obs_quality",ALLOW_SAFARI_MEDIA_MIDDLEWARES:"allow_safari_media_middlewares",EXP_RESHARE:"exp_reshare",SKIP_SETTING_IN_USE_DEVICE:"skip_setting_in_use_device",PRECALL_BANDWIDTH_TEST:"precall_bandwidth_test",DEBUG_SOCKET_JOIN:"debug_socket_join",FORCE_RELAY:"force_relay",FORCE_VIDEO_CODEC:"force_video_codec",TRACK_HINT:"track_hint",OVERRIDE_SIMULCAST_DYNAMIC:"override_simulcast_dynamic",PRECREATE_PRODUCERS:"precreate_producers",DISABLE_OPUS_DTX_CF:"disable_opus_dtx_cf",ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS:"enable_audio_activity_debug_logs",DISABLE_LAYER_SWITCH:"disable_layer_switch"};function Yc(s){const t={};return typeof(s==null?void 0:s.code)=="number"&&(t.code=s.code),typeof(s==null?void 0:s.code)=="string"&&(t.code=s.code.substring(0,100)),typeof(s==null?void 0:s.name)=="string"&&(t.name=s.name.substring(0,500)),typeof(s==null?void 0:s.message)=="string"&&(t.message=s.message.substring(0,500)),typeof(s==null?void 0:s.reason)=="string"&&(t.reason=s.reason.substring(0,500)),typeof(s==null?void 0:s.stack)=="string"&&(t.stack=s.stack.substring(0,500)),t}const FC={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},za={baseURL:"http://localhost:5000",createdAt:"2021-08-05T10:49:56.602Z",description:"Develop plugins locally",id:"09259e3b-7be8-46f6-9801-106bf1866e1c",name:"Localhost Dev",organizationId:"4ad15a19-80e2-4105-bf43-48039fd2963e",picture:"https://dyte-uploads.s3.ap-south-1.amazonaws.com/dyte.png",private:!1,published:!0,staggered:!1,tags:["#localhost","#dev"],type:"self_hosted",updatedAt:"2021-08-05T10:50:07.681Z"},BC={pip:!0,poll:!0,chat:!0,stage:!0,theme:!0,plugin:!0,tracing:!0,internals:!0,recording:!0,livestream:!0,participant:!0,connectedMeetings:!0,devTools:{logs:!1}};function ba(s,t){const e=s.getValue("overrides");return e&&e[t]?e[t]:!1}function HC({baseURI:s}){return s.includes("preprod.dyte")||s.includes("preprod.realtime")?oo.PREPROD:s.includes("devel.dyte")||s.includes("devel.realtime")?oo.DEVEL:oo.PROD}function Yi({servicePrefix:s,baseURI:t}){return`${s}.${t}`}function qm(s){const t=s.getValue("baseURI");return{location:Yi({servicePrefix:"location",baseURI:t}),locationLegacy:Yi({servicePrefix:"location-legacy",baseURI:t}),daCollector:Yi({servicePrefix:"da-collector",baseURI:t})}}const qC='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="m16.242 2.932 4.826 4.826a2.75 2.75 0 0 1-.715 4.404l-4.87 2.435a.75.75 0 0 0-.374.426l-1.44 4.166a1.25 1.25 0 0 1-2.065.476L8.5 16.561 4.06 21H3v-1.06l4.44-4.44-3.105-3.104a1.25 1.25 0 0 1 .476-2.066l4.166-1.44a.75.75 0 0 0 .426-.373l2.435-4.87a2.75 2.75 0 0 1 4.405-.715Zm3.766 5.886-4.826-4.826a1.25 1.25 0 0 0-2.002.325l-2.435 4.871a2.25 2.25 0 0 1-1.278 1.12l-3.789 1.31 6.705 6.704 1.308-3.789a2.25 2.25 0 0 1 1.12-1.277l4.872-2.436a1.25 1.25 0 0 0 .325-2.002Z" fill="currentColor"/></svg>',jC='<svg viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M4 12.02c0 1.06.2 2.1.6 3.08l.6 1.42c.22.55.64 1.01 1.17 1.29.27.14.56.21.86.21h2.55c.77 0 1.49-.41 1.87-1.08.5-.87 1.02-1.7 1.72-2.43l1.32-1.39c.44-.46.97-.84 1.49-1.23l.59-.45a.6.6 0 0 0 .23-.47c0-.75-.54-1.57-1.22-1.79a3.34 3.34 0 0 0-2.78.29V4.5a1.5 1.5 0 0 0-2.05-1.4 1.5 1.5 0 0 0-2.9 0A1.5 1.5 0 0 0 6 4.5v.09A1.5 1.5 0 0 0 4 6v6.02ZM8 4.5v4a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0v5a.5.5 0 0 0 1 0v-4a.5.5 0 0 1 1 0v6a.5.5 0 0 0 .85.37h.01c.22-.22.44-.44.72-.58.7-.35 2.22-.57 2.4.5l-.53.4c-.52.4-1.04.78-1.48 1.24l-1.33 1.38c-.75.79-1.31 1.7-1.85 2.63-.21.36-.6.58-1.01.58H7.23a.87.87 0 0 1-.4-.1 1.55 1.55 0 0 1-.71-.78l-.59-1.42a7.09 7.09 0 0 1-.53-2.7V6a.5.5 0 0 1 1 0v3.5a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0Z" fill="currentColor"></path></svg>',Uc=s=>{if(!s)return;if(!s.startsWith("<svg"))return new Promise(a=>{a(s)});const e=new Blob([s],{type:"image/svg+xml"}),r=new Image,i=window.URL.createObjectURL(e);return new Promise((a,o)=>{r.onload=()=>{a(r),window.URL.revokeObjectURL(i)},r.onerror=()=>{o(),window.URL.revokeObjectURL(i)},r.src=i})},ci={logs:"https://api-silos.dyte.io/otel/logs",mock:{url:"https://mock.dyte.io",domain:"mock.dyte.io",app:"https://app.dyte.io/v2/meeting",stagingApp:"https://app.devel.dyte.io/v2/meeting"},apiBase:{prod:"https://api.dyte.io",staging:"https://api.devel.dyte.io",prodAlternate:"https://api.cluster.dyte.in"},baseURI:{prod:"dyte.io",staging:"devel.dyte.io"}};function GC(s){var r,i,a;const t=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((r=window.location.host)==null?void 0:r.includes(ci.baseURI.staging)),e=!!((a=(i=s==null?void 0:s.getValue("modules"))==null?void 0:i.devTools)!=null&&a.logs);return t||e}function WC(s,t){var e;if(s!=null&&s.getValue("flagsmith").hasFeature(Y.LOG_LEVEL)){let r=((e=s.getValue("flagsmith").getValue(Y.LOG_LEVEL))==null?void 0:e.toString())||"all";if(r=r.toLowerCase().trim(),r==="off")return!1;if(r!=="all"){const i=["debug","log","info","warn","error"],a=i.indexOf(t),o=i.indexOf(r);if(a<o)return!1}}return!0}function jm(s,t,e={}){return Object.getOwnPropertyNames(s).forEach(r=>{var a;if([null,void 0,NaN].includes(s[r])||t&&(((a=t.match(/\./g))==null?void 0:a.length)||0)>=10)return;const i=t?`${t}.${r}`:r;typeof s[r]=="object"?jm(s[r],i,e):["number","string","boolean"].includes(typeof s[r])&&(e[i]=s[r])}),e}function vp(s,t,e={},r=""){const i={};try{const a=JSON.stringify(e),o=JSON.parse(a),c=jm(o,r),d=JSON.stringify(c);return JSON.parse(d)}catch(a){const o=Yc(a);i[`${r}.error.message`]=o.message||"",i[`${r}.error.stack`]=o.stack||"",i[`${r}.error.reason`]=o.reason||"",i[`${r}.error.source`]="safelyFlattenObjForOpenTelemetry"}return i}const Oh=class{constructor(){u(this,"logsCache",[]);u(this,"logsProcessorTimer");u(this,"tracingEnabled",!0);u(this,"initialized",!1);u(this,"logsProcessingInterval",7e3);u(this,"logExclusionList",["message","websocket/message","roomMessage","websocket/room-message","websocket/room-legacy-mode","chatMessage","websocket/new-chat-message","websocket/no-active-speaker","websocket/selected-peers","websocket/active-speaker","ping","websocket/new-consumer","websocket/producer-score","websocket/consumer-score","websocket/plugin-event","websocket/plugin-data","websocket/plugin-internal-data"]);u(this,"meetingMetadata",{})}get logsEndpoint(){const t=cr.getContext(this.meetingMetadata.peerId);return`https://${Yi({servicePrefix:"api-silos",baseURI:t.getValue("baseURI")})}/otel/logs`}resetPeerId(t){this.meetingMetadata.peerId=t}init(t,e,r){this.tracingEnabled=!0,this.initialized=!1,this.logsCache=[];const i=t.getValue("peerId");this.meetingMetadata=e,this.tracingEnabled=r,this.meetingMetadata.peerId=i,this.meetingMetadata.sdkVersion=t.getValue("sdkVersion");const{RNDeviceInfoImpl:a}=navigator;this.meetingMetadata.deviceInfo=navigator.isReactNative?a==null?void 0:a.getDeviceInfo():fe.getDeviceInfo(),this.meetingMetadata.visitedUrl=!navigator.isReactNative&&typeof window!="undefined"&&window.location.href,this.logsProcessorTimer=setInterval(this.processCachedLogs.bind(this),this.logsProcessingInterval),r&&(this.initialized=!0)}static trace(t,e=void 0){return(r,i,a)=>{const o=a.value;return a.value=function(...d){var f;const l=this==null?void 0:this.telemetry;if(!l||!l.initialized||navigator.isReactNative||!l.tracingEnabled||(f=cr.getContext(l.meetingMetadata.peerId))!=null&&f.getValue("flagsmith").hasFeature(Y.SKIP_OTEL_TRACES))return o.apply(this,d);l.addLogInCurrentSpan("info",t,e);const h=performance.now(),p=o.apply(this,d);return Promise.resolve(p).then(()=>{const T=performance.now();T-h>10&&l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:T-h,country:Oh.location.country})}).catch(()=>{const T=performance.now();l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:T-h})}),p},a}}injectContext(t){var i;const e=ur.v4().replace(/-/g,"").substring(0,16),r=(i=this.meetingMetadata.peerId)==null?void 0:i.replace(/-/g,"");t.TRACEPARENT=`00-${r}-${e}-01`}addLogInCurrentSpan(t,e,r={},i=!1){r!=null&&r.error&&Object.assign(r,{error:Yc(r.error)});const a=cr.getContext(this.meetingMetadata.peerId);if(GC(a)&&(MC(r)?console[t]("InternalLogs:: ",t,e):console[t]("InternalLogs:: ",t,e,r)),!!WC(a,t))try{const c=vp(a,e,r,"metadata"),d=new Date,l={message:e,level:t,...c,loggedAt:d.toISOString(),loggedAtTzOffset:d.getTimezoneOffset()};i?this.sendOtelLogsToNewRelic([l]):this.logsCache.push(l)}catch(c){this.addLogInCurrentSpan("error","opentelemetry::addLogInCurrentSpan_failed",{error:Yc(c)})}}sendOtelLogsToNewRelic(t){const e=cr.getContext(this.meetingMetadata.peerId);fetch(this.logsEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({meetingMetadata:vp(e,"sendOtelLogsToNewRelic",this.meetingMetadata,"meetingMetadata"),serviceName:e.getValue("sdkName"),logs:t})}).catch(r=>{this.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:Yc(r)}),this.logsCache.push(...t)})}processCachedLogs(){const t=this.logsCache.splice(0,25);t!=null&&t.length&&this.sendOtelLogsToNewRelic(t)}destruct(){clearInterval(this.logsProcessorTimer),this.processCachedLogs()}};let y=Oh;u(y,"location",{country:void 0});function JC(s){const t={...s},e=new Map,r=(l,h)=>(e.has(l)||e.set(l,new Set),e.get(l).add(h),()=>{var p;return(p=e.get(l))==null?void 0:p.delete(h)}),i=(l,h)=>{var p;(p=e.get(l))==null||p.delete(h)},a=l=>{var h;(h=e.get(l))==null||h.forEach(p=>{try{p(t[l])}catch(f){}})};return{subscribe:r,unsubscribe:i,notify:a,setValue:(l,h,p=!0)=>{t[l]=h,p&&a(l)},getValue:l=>t[l],getAllValues:()=>t}}class KC{constructor(){u(this,"contexts",new Map);u(this,"mostRecentPeerId",null)}createContext(t,e){if(this.contexts.has(t))return this.contexts.get(t);const r=new y,i=new Vm;this.contexts.set(t,JC(e)),this.contexts.get(t).setValue("peerSessionStore",new JP(i));const a=new nm;return a.setMaxListeners(50),this.contexts.get(t).setValue("logger",i),this.contexts.get(t).setValue("telemetry",r),this.contexts.get(t).setValue("callstats",a),this.contexts.get(t).setValue("flagsmith",VP()),this.mostRecentPeerId=t,this.contexts.get(t)}remapContext(t,e){const r=e.getValue("peerId");r!==t&&(e.setValue("peerId",t),this.mostRecentPeerId=t,this.contexts.set(t,e),this.contexts.delete(r))}getContext(t){return this.contexts.get(t)}getMostRecentPeerId(){return this.mostRecentPeerId}}const cr=new KC,zC={"00":"Client","01":"Controller","02":"RoomNodeClient","03":"HiveNodeClient","04":"SocketService","05":"Chat","06":"Plugin","07":"Polls","08":"Meta","09":"Preset",10:"Recording",11:"Self",12:"Participant",13:"Spotlight",14:"Remote Request",15:"Webinar",16:"LocalMediaHandler",17:"End-End Encryption",18:"AI",19:"Livestream",20:"Stage"},Qc={"0000":"Internal exception.","0001":"Failed to initialize.","0002":"Failed to join room.","0003":"Failed to leave room.","0004":"Invalid auth token","0010":"Browser not supported","0011":"HTTP Network Error","0012":"Websocket Network Error","0013":"Rate Limited","0100":"Internal exception","0101":"Permission denied","0102":"Prerequisite module missing","0200":"Internal exception.","0300":"Internal exception","0400":"Internal exception","0404":"Missing prerequisites to establish a websocket connection","0500":"Internal exception","0501":"Permission denied.","0502":"Invalid message body.","0503":"Text Message is too large","0504":"Message not found by the given id","0505":"Action not permitted without joining room","0506":"Message search is disabled","0600":"Internal exception","0601":"Permission denied.","0602":"Auth token not set for plugin","0603":"Iframe was not provided","0700":"Internal exception","0705":"Action not permitted without joining room","0800":"Internal exception","0801":"Permission denied","0900":"Internal exception","0904":"Could not load preset",1e3:"Internal exception",1001:"Permission denied",1004:"Could not find specified recording",1005:"Action not permitted in given recording state",1100:"Internal exception",1101:"Permission denied",1102:"Unsupported",1103:"Name cannot be empty",1104:"No device selected while calling meeting.self.setDevice",1105:"Action not permitted without joining room",1106:"Can't set currently used device",1200:"Internal exception",1201:"Permission denied",1202:"Invalid page number was requested",1203:"Invalid participant count per page was requested",1204:"No participants exists with the given UserIds",1205:"Action not permitted without joining room",1206:"Manual Subscription Mode was not ACTIVATED",1207:"Invalid view mode",1208:"Manual Subscription not enabled for organization",1209:"Broadcast message type must be a non-empty string",1300:"Internal exception",1400:"Internal exception",1402:"No existing remote requests",1403:"No peer exists with given id",1500:"Internal exception",1600:"Internal exception",1601:"Failed to get audio track",1602:"Failed to get video track",1603:"Incorrect device",1604:"Failed to change device",1605:"Failed to get audio & video track",1606:"No audio input devices are available",1607:"No video input devices are available",1608:"No audio output devices (speakers) are available",1609:"Failed to fetch list of media devices",1610:"No media track exists",1611:"Failed to unmute track",1612:"Failed to get screenshare tracks",1701:"Crypto error",1800:"Internal exception",1801:"Can't fetch transcript file",1900:"Internal exception",1901:"Permission denied.",1902:"Livestream that has not yet started, can't be stopped",2e3:"Internal exception",2001:"Permission denied",2002:"Unsupported",2003:"Stage is disabled",2004:"Method not implemented",2005:"Action not permitted without joining room",2006:"Action not permitted in current stage status",9900:"Internal exception"};Object.keys(Qc).forEach(s=>{Qc[s]=`{${zC[s.slice(0,2)]}} ${Qc[s]}`});class b extends Error{constructor(e,r,i=void 0,a=!1){super(e);u(this,"code");this.code=r,this.name="ClientError";const o=this.code?`[ERR${this.code}]`:"[ERR]",c=this.code?Qc[this.code]:"";this.message=`${o}: ${c}
|
|
5
5
|
${this.message}`;try{let d=a&&!!i;r&&r.endsWith("00")&&i&&(d=!0),d&&i.error("ClientError",{error:{message:this.message,name:this.name,code:r}});const l=cr.getContext(cr.getMostRecentPeerId());if(l){const h=l.getValue("onError");try{h(this)}catch(p){}}typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("ClientError",{detail:this}))}catch(d){}}}function $c(s,t,e,r){if(r instanceof b)throw r;if(r instanceof t){const i=new b(r.message,e);throw i.stack=r.stack,i}else throw r}function Sp(s,t,e){if(!s.value){const i=s.get,a=s.set;return i&&(s.get=function(){try{return i.apply(this)}catch(o){$c(this,t,e,o)}}),a&&(s.set=function(o){try{return a.apply(this,[o])}catch(c){$c(this,t,e,c)}}),s}const r=s.value;return s.value=function(...i){try{const a=r.apply(this,i);return a&&a instanceof Promise?a.catch(o=>{$c(this,t,e,o)}):a}catch(a){$c(this,t,e,a)}},s}function YC(s,t){return(e,r,i)=>{if(i)return Sp(i,s,t);for(const a of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,a);(o.value instanceof Function||o.get instanceof Function||o.set instanceof Function)&&Object.defineProperty(e.prototype,a,Sp(o,s,t))}}}const at=s=>YC(Error,s);function QC(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 XC(){fe.isElectron()&&window.electronGetDisplayMediaSource&&(navigator.mediaDevices.getDisplayMedia=async()=>{const s=await window.electronGetDisplayMediaSource({types:["window","screen"]});let t=[];if(s&&(Array.isArray(s)?t=s:t=[s]),!(t!=null&&t.length))throw new Error("Couldn't find any media source for screen share.");let e=t.find(a=>{var o;return(o=a.id)==null?void 0:o.includes("screen")});e=e!=null?e:t[0];const r={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e.id}}};return await navigator.mediaDevices.getUserMedia(r)})}var w=(s=>(s.NEW_PRODUCER="NEW_PRODUCER",s.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))(w||{});class Ia extends nt.EventEmitter{constructor(e){super();u(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 a=this.listenerCount(e);a>25&&a%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(a){}return super.on(e,r)}addListener(e,r){var i;try{const a=this.listenerCount(e);a>25&&a%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(a){}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 Ut extends nt.EventEmitter{constructor(e){super();u(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 a=this.listenerCount(e);a>25&&a%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(a){}return super.on(e,r)}addListener(e,r){var i;try{const a=this.listenerCount(e);a>25&&a%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(a){}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 ZC(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 yp=1080,Ep=1920,ew=(s,t,e,r,i,a)=>{let o=.5,c=.5;const d=i,l=a,h=Math.min(e/d,r/l);let p=d*h,f=l*h,T,E,C,_,I=1;return p<e&&(I=e/p),Math.abs(I-1)<1e-14&&f<r&&(I=r/f),p*=I,f*=I,C=d/(p/e),_=l/(f/r),T=(d-C)*o,E=(l-_)*c,T<0&&(T=0),E<0&&(E=0),C>d&&(C=d),_>l&&(_=l),[T,E,C,_,s,t,e,r]};var qt,di,Xe,jt,_e,cs,Hs,ct,Ie,wn,Rn,qs,bn;const Nh=class extends Ut{constructor(e,r,i,a){const o=e.getValue("logger");super(o);g(this,qt,void 0);g(this,di,void 0);g(this,Xe,void 0);g(this,jt,void 0);g(this,_e,{height:yp,width:Ep});g(this,cs,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});g(this,Hs,void 0);g(this,ct,{});g(this,Ie,void 0);g(this,wn,void 0);g(this,Rn,void 0);g(this,qs,void 0);g(this,bn,!1);u(this,"cleanupEventListeners",()=>{n(this,di).unsubscribe("stageStatus",this.handlePipMediaControls),n(this,Ie).removeListener("videoUpdate",this.onSelfVideoUpdateListener),n(this,Ie).removeListener("audioUpdate",this.onSelfAudioUpdateListener),n(this,Ie).removeListener("roomLeft",()=>this.disable())});u(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()});u(this,"onSelfVideoUpdateListener",({videoEnabled:e})=>{this.updateMediaSession("CAMERA",e)});u(this,"onSelfAudioUpdateListener",({audioEnabled:e})=>{this.updateMediaSession("MIC",e)});u(this,"handlePipMediaControls",e=>{e==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()});u(this,"eventCallback",e=>{e==="CAMERA"&&(n(this,Ie).videoEnabled?n(this,Ie).disableVideo():n(this,Ie).enableVideo(),this.emit("cameraToggled")),e==="MIC"&&(n(this,Ie).audioEnabled?n(this,Ie).disableAudio():n(this,Ie).enableAudio(),this.emit("micToggled")),e==="END"&&(n(this,di).getValue("peerSessionStore").emit(w.PIP_HANGUP),this.cleanupEventListeners(),this.emit("hangup"),this.cleanup())});u(this,"unmountEvents",()=>{navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("togglemicrophone",void 0),navigator.mediaSession.setActionHandler("togglecamera",void 0))});u(this,"animate",()=>{if(!this.isActive&&n(this,qs)==="active"){this.disable(!0);return}n(this,ct)!==void 0&&this.paintCanvas(),n(this,Hs)!==void 0&&m(this,Hs,requestAnimationFrame(()=>this.animate()))});u(this,"disable",(e=!1)=>{m(this,qs,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(n(this,Hs)),e!==!0&&document.body.removeChild(n(this,Xe)),m(this,Hs,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});m(this,di,e),m(this,qs,"idle"),m(this,Ie,r),m(this,cs,{brand:r.config.designTokens.colors.brand[500],background:r.config.designTokens.colors.background[1e3],text:r.config.designTokens.colors.text,videoBackground:r.config.designTokens.colors.videoBg,textOnBrand:r.config.designTokens.colors.textOnBrand}),i&&this.setupIcon("pin",i),a&&this.setupIcon("handRaise",a)}static async _init(e,r){let i,a;try{i=await Uc(qC),a=await Uc(jC)}catch(o){}return new Nh(e,r,i,a)}async setupIcon(e,r){switch(e){case"handRaise":m(this,Rn,r);break;case"pin":m(this,wn,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":m(this,Rn,await Uc(r));break;case"pin":m(this,wn,await Uc(r));break}}constructImage(e){const r=new Image,i=new Blob([e],{type:"image/svg+xml"}),a=window.URL.createObjectURL(i);return new Promise(o=>{r.onload=()=>{o(r),window.URL.revokeObjectURL(a)},r.src=a})}createVideoContainer(){m(this,Xe,document.createElement("div")),n(this,Xe).style.width="0.1px",n(this,Xe).style.height="0.1px",n(this,Xe).style.overflow="hidden",n(this,Xe).style.position="absolute",n(this,Xe).style.bottom="0",n(this,Xe).style.right="0",n(this,Xe).style.opacity="0",n(this,Xe).appendChild(n(this,jt))}setupEventListeners(){n(this,di).subscribe("stageStatus",this.handlePipMediaControls),n(this,Ie).addListener("videoUpdate",this.onSelfVideoUpdateListener),n(this,Ie).addListener("audioUpdate",this.onSelfAudioUpdateListener),n(this,Ie).addListener("roomLeft",()=>this.disable())}createCanvas(){const e=document.createElement("canvas");e.height=n(this,_e).height,e.width=n(this,_e).width,m(this,qt,e)}setupMediaSessionEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("hangup",()=>{this.eventCallback("END")}),this.mountAudioEvents(),this.mountVideoEvents())}mountAudioEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setMicrophoneActive===void 0||n(this,Ie).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||n(this,Ie).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const r=Object.values(n(this,ct)).reduce((i,a)=>(i[a.pinned?"pinned":"regular"].push(a),i),{pinned:[],regular:[]});return[...r.pinned,...r.regular]}drawEmptyTile(e,r,i,a){if(n(this,qt)===void 0)return;const o=n(this,qt).getContext("2d"),c=n(this,qt).width,d=0,l=0,h=r-d*2,p=i-d*2,f=Math.floor(c/h),T=Math.floor(e/f),C=e%f*(h+d)+d,_=T*(p+d)+d,{displayText:I,image:M}=a!=null?a:{};o.fillStyle=I||M?n(this,cs).videoBackground:n(this,cs).background,o.strokeStyle=n(this,cs).brand,o.beginPath(),o.moveTo(C+l,_),o.arcTo(C+h,_,C+h,_+l,l),o.arcTo(C+h,_+p,C+h-l,_+p,l),o.arcTo(C,_+p,C,_+p-l,l),o.arcTo(C,_,C+l,_,l),o.closePath(),o.fill(),o.stroke();const x=h/6,N=h/2+C,$=p/2+_;o.save(),(I||M)&&(o.beginPath(),o.arc(N,$,x,0,Math.PI*2),o.fillStyle=n(this,cs).brand,o.fill(),M?(o.clip(),o.drawImage(M,N-x,$-x,x*2,x*2),o.restore()):I&&(o.fillStyle=n(this,cs).textOnBrand,o.font=`${x/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(I,N,$)),this.drawIcons(a,C,_,Math.max(h,p)))}drawIcons(e,r,i,a){const o=Math.min(Math.max(a*.15,100),200),c=o*.2,d=o*.2;let l=r+c;const h=i+c,p=f=>{const T=n(this,qt).getContext("2d");T.save(),T.fillStyle=n(this,cs).background,T.beginPath(),T.moveTo(l+d,h),T.arcTo(l+o,h,l+o,h+d,d),T.arcTo(l+o,h+o,l+o-d,h+o,d),T.arcTo(l,h+o,l,h+o-d,d),T.arcTo(l,h,l+d,h,d),T.closePath(),T.fill(),typeof f=="string"?(T.font=`${o/1.5}px sans-serif`,T.fillStyle=n(this,cs).text,T.textAlign="center",T.textBaseline="top",T.fillText(f,o/2+l,h+c)):T.drawImage(f,l+c,h+c,o-c*2,o-c*2),l+=o+c,T.restore()};e.pinned&&p(n(this,wn)),e.handRaised&&p(n(this,Rn)),e.reaction&&p(e.reaction)}drawTile(e,r,i){var l,h;if(n(this,qt)===void 0)return;const a=n(this,qt).getContext("2d"),o=this.getSources();let c=0,d=0;for(;c<n(this,_e).height-5;){let p=0;for(;p<n(this,_e).width-5&&d<i;){if((l=o[d])!=null&&l.enabled){const f=o[d].element,[T,E,C,_,I,M,x,N]=ew(p,c,e,r,f.videoWidth,f.videoHeight);((h=f==null?void 0:f.classList)==null?void 0:h.contains("mirror"))?(a.save(),a.scale(-1,1),a.drawImage(f,T,E,C,_,-1*I,M,-1*x,N),a.restore()):a.drawImage(f,T,E,C,_,I,M,x,N),this.drawIcons(o[d],I,M,Math.max(x,N))}else this.drawEmptyTile(d,e,r,o[d]);d+=1,p+=e}c+=r}}calcGridElemSize(e){switch(e){case 0:case 1:return[n(this,_e).width,n(this,_e).height];case 2:return[Math.floor(n(this,_e).width/2),n(this,_e).height];case 3:case 4:return[Math.floor(n(this,_e).width/2),Math.floor(n(this,_e).height/2)];case 5:case 6:return[Math.floor(n(this,_e).width/3),Math.floor(n(this,_e).height/2)];case 7:case 8:case 9:return[Math.floor(n(this,_e).width/3),Math.floor(n(this,_e).height/3)];default:return[Math.floor(n(this,_e).width/3),Math.floor(n(this,_e).height/2)]}}paintCanvas(){let e=this.getSources().length;e!==1&&(e=e%2>0?e+1:e);const[r,i]=this.calcGridElemSize(e);this.drawTile(r,i,e)}isSupported(){var e;return!!window.chrome&&document.pictureInPictureEnabled&&((e=n(this,Ie).config)==null?void 0:e.viewType)!=="LIVESTREAM"}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(m(this,bn,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),n(this,Xe))try{document.body.removeChild(n(this,Xe))}catch(e){}this.removeAllSources(),m(this,qt,void 0),m(this,jt,void 0),m(this,Hs,void 0)}init({height:e,width:r}={}){if(!this.isSupported())throw this.logger.error("Pip.unsupported"),new Error("Picture-in-picture is not available in this environment");if(n(this,bn))return;m(this,bn,!0),this.createCanvas(),this.setupMediaSessionEvents();const i=document.createElement("video");m(this,_e,{height:e!=null?e:yp,width:r!=null?r:Ep}),i.height=n(this,_e).height,i.width=n(this,_e).width,i.autoplay=!0,i.muted=!0,i.srcObject=n(this,qt).captureStream(24),m(this,jt,i),n(this,jt).onloadedmetadata=()=>{try{this.emit("pipStarted"),n(this,jt).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(a){this.emit("pipEnded")}},this.createVideoContainer(),this.paintCanvas()}updateMediaSession(e,r){navigator.mediaSession!==void 0&&(e==="CAMERA"&&navigator.mediaSession.setCameraActive!==void 0&&navigator.mediaSession.setCameraActive(r),e==="MIC"&&navigator.mediaSession.setMicrophoneActive!==void 0&&navigator.mediaSession.setMicrophoneActive(r))}enableSource(e){n(this,ct)[e]!==void 0&&(n(this,ct)[e].enabled=!0)}disableSource(e){n(this,ct)[e]!==void 0&&(n(this,ct)[e].enabled=!1)}async generateAvatar(e,r){if(!r)return;const i=new Image;try{const a=await(await fetch(r)).blob(),o=window.URL.createObjectURL(a);i.onload=()=>{this.updateSource(e,{image:i}),window.URL.revokeObjectURL(o)},i.src=o}catch(a){this.logger.error("Pip::GenerateAvatar",{error:a})}}addSource(e,r,i,a=!1,o=void 0,c=void 0,d=!1){this.logger.debug("Pip::AddSource",{pip:{id:e,handRaised:d}}),n(this,ct)[e]={id:e,element:r,enabled:i,pinned:a,displayText:o?ZC(o):void 0,imageUrl:c,handRaised:d},c&&this.generateAvatar(e,c)}updateSource(e,r){this.logger.info("Pip::UpdateSource",{pip:{id:e,handRaised:r.handRaised,reaction:r.reaction}});const i=n(this,ct)[e];i&&(n(this,ct)[e]={...i,...r})}removeSource(e){delete n(this,ct)[e]}removePinnedSource(){Object.values(n(this,ct)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){m(this,ct,{})}enable(){m(this,qs,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",n(this,Ie).videoEnabled),this.updateMediaSession("MIC",n(this,Ie).audioEnabled),document.body.appendChild(n(this,Xe)),m(this,Hs,requestAnimationFrame(()=>this.animate())),n(this,jt).onloadedmetadata=()=>{n(this,jt).requestPictureInPicture().then(()=>{m(this,qs,"active")})},n(this,jt).readyState===4&&n(this,jt).requestPictureInPicture().then(()=>{m(this,qs,"active")})}};let uu=Nh;qt=new WeakMap,di=new WeakMap,Xe=new WeakMap,jt=new WeakMap,_e=new WeakMap,cs=new WeakMap,Hs=new WeakMap,ct=new WeakMap,Ie=new WeakMap,wn=new WeakMap,Rn=new WeakMap,qs=new WeakMap,bn=new WeakMap;var pr;(function(s){s[s.PUBLISHER=0]="PUBLISHER",s[s.SUBSCRIBER=1]="SUBSCRIBER"})(pr||(pr={}));var Ns;(function(s){s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO"})(Ns||(Ns={}));class tw extends v.MessageType{constructor(){super("media.Codec",[{no:1,name:"channels",kind:"scalar",opt:!0,T:5},{no:2,name:"clock_rate",kind:"scalar",T:5},{no:3,name:"mime_type",kind:"scalar",T:9},{no:4,name:"sdp_fmtp_line",kind:"scalar",opt:!0,T:9},{no:5,name:"payload_type",kind:"scalar",opt:!0,T:13}])}}const Gm=new tw;class sw extends v.MessageType{constructor(){super("media.HeaderExtension",[{no:1,name:"direction",kind:"scalar",opt:!0,T:9},{no:2,name:"uri",kind:"scalar",T:9}])}}const rw=new sw;class iw extends v.MessageType{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new iw;class nw extends v.MessageType{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",pr]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const _s=new nw;class aw extends v.MessageType{constructor(){super("media.ProducerPayload",[{no:1,name:"kind",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"msid",kind:"scalar",T:9},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"mime_type",kind:"scalar",opt:!0,T:9}])}}const ow=new aw;class cw extends v.MessageType{constructor(){super("media.CreateTransportRequest",[{no:1,name:"consuming",kind:"scalar",T:8},{no:2,name:"force_tcp",kind:"scalar",opt:!0,T:8},{no:3,name:"description",kind:"message",T:()=>_s},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>ow}])}}const dw=new cw;class lw extends v.MessageType{constructor(){super("media.AudioActivityRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"energy",kind:"scalar",T:5},{no:3,name:"silent",kind:"scalar",T:8}])}}const uw=new lw;class hw extends v.MessageType{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>_s},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const Wm=new hw;class pw extends v.MessageType{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>_s}])}}const gw=new pw;class mw extends v.MessageType{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>_s}])}}new mw;class fw extends v.MessageType{constructor(){super("media.NestedScore",[{no:1,name:"encoding_idx",kind:"scalar",T:5},{no:2,name:"rid",kind:"scalar",T:9},{no:3,name:"score",kind:"scalar",T:5},{no:4,name:"ssrc",kind:"scalar",T:3,L:0}])}}const Tw=new fw;class vw extends v.MessageType{constructor(){super("media.ProducerTrack",[{no:1,name:"track_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9},{no:3,name:"stream_id",kind:"scalar",T:9}])}}const Sw=new vw;class yw extends v.MessageType{constructor(){super("media.ProducerEntry",[{no:1,name:"producing_transport_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9}])}}new yw;class Ew extends v.MessageType{constructor(){super("media.ConsumerEntry",[{no:1,name:"consuming_transport_id",kind:"scalar",T:9},{no:2,name:"consumer_id",kind:"scalar",T:9}])}}new Ew;class Pw extends v.MessageType{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",Ns]},{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:()=>Gm}])}}const Ic=new Pw;class _w extends v.MessageType{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Ic},{no:3,name:"producer_track",kind:"message",T:()=>Sw},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const Cw=new _w;class ww extends v.MessageType{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>Cw}}])}}const Jm=new ww;class Rw extends v.MessageType{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>_p},{no:2,name:"receiver",kind:"message",T:()=>_p}])}}const Km=new Rw;class bw extends v.MessageType{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>Gm},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>rw}])}}const Pp=new bw;class kw extends v.MessageType{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>Pp},{no:2,name:"video",kind:"message",T:()=>Pp}])}}const _p=new kw;class Iw extends v.MessageType{constructor(){super("media.PreferredCodec",[{no:1,name:"audio",kind:"scalar",opt:!0,T:9},{no:2,name:"video",kind:"scalar",opt:!0,T:9}])}}const Aw=new Iw;class Mw extends v.MessageType{constructor(){super("media.Simulcast",[{no:1,name:"preferred_rid",kind:"scalar",opt:!0,T:9},{no:2,name:"priority_ordering",kind:"scalar",opt:!0,T:9},{no:3,name:"rid_not_available",kind:"scalar",opt:!0,T:9}])}}const zm=new Mw;class Dw extends v.MessageType{constructor(){super("media.edge.GeoLocation",[{no:1,name:"latitude",kind:"scalar",T:2},{no:2,name:"longitude",kind:"scalar",T:2},{no:3,name:"region",kind:"scalar",opt:!0,T:9}])}}const Ow=new Dw;class Nw extends v.MessageType{constructor(){super("media.edge.PeerJoinRequest",[{no:1,name:"display_name",kind:"scalar",opt:!0,T:9},{no:2,name:"prejoined",kind:"scalar",T:8},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:5,name:"preset",kind:"scalar",opt:!0,T:12},{no:6,name:"user_id",kind:"scalar",opt:!0,T:9},{no:7,name:"organization_id",kind:"scalar",opt:!0,T:9},{no:8,name:"location",kind:"message",T:()=>Ow},{no:9,name:"capabilities",kind:"message",T:()=>Km}])}}const Vw=new Nw;class Lw extends v.MessageType{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const xw=new Lw;class Uw extends v.MessageType{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const $w=new Uw;class Fw extends v.MessageType{constructor(){super("media.edge.ConsumeMultipleProducerRequest",[{no:1,name:"producer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8}])}}new Fw;class Bw extends v.MessageType{constructor(){super("media.edge.ConsumePeerRequest",[{no:1,name:"producing_peer_id",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8},{no:3,name:"producer_id",kind:"scalar",opt:!0,T:9},{no:4,name:"preferred_codec",kind:"message",T:()=>Aw},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:6,name:"simulcast",kind:"message",T:()=>zm}])}}const Hw=new Bw;class qw extends v.MessageType{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>Hw},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const jw=new qw;class Gw extends v.MessageType{constructor(){super("media.edge.UpdateConsumerSimulcastConfigRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"simulcast",kind:"message",T:()=>zm},{no:3,name:"producing_transport_id",kind:"scalar",T:9},{no:4,name:"mid",kind:"scalar",T:9}])}}const Ww=new Gw;class Jw extends v.MessageType{constructor(){super("media.edge.UpdateConsumersSimulcastConfigRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>Ww},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const Kw=new Jw;class zw extends v.MessageType{constructor(){super("media.edge.ProducerCreateRequest",[{no:1,name:"kind",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"description",kind:"message",T:()=>_s},{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 Yw=new zw;class Qw extends v.MessageType{constructor(){super("media.edge.SelectedPeersRequest",[])}}new Qw;class Xw extends v.MessageType{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Zw=new Xw;class eR extends v.MessageType{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const Fc=new eR;class tR extends v.MessageType{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}new tR;class sR extends v.MessageType{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>_s},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const rR=new sR;class iR extends v.MessageType{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>_s},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const nR=new iR;class aR extends v.MessageType{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new aR;class oR extends v.MessageType{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const Ym=new oR;class cR extends v.MessageType{constructor(){super("media.edge.PeerDisplayNameEditRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}const dR=new cR;class lR extends v.MessageType{constructor(){super("media.edge.HostMediaControlForPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"audio",kind:"scalar",T:8},{no:3,name:"video",kind:"scalar",T:8},{no:4,name:"scree_share",kind:"scalar",T:8}])}}const uR=new lR;class hR extends v.MessageType{constructor(){super("media.edge.HostMediaControlForAllPeerRequest",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8}])}}const pR=new hR;class gR extends v.MessageType{constructor(){super("media.edge.GetRoomStateResponse",[{no:1,name:"display_title",kind:"scalar",T:9},{no:2,name:"locked_mode",kind:"scalar",T:8},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"room_name",kind:"scalar",T:9},{no:5,name:"current_peer_id",kind:"scalar",T:9},{no:6,name:"is_recording",kind:"scalar",opt:!0,T:8},{no:7,name:"recorder_participant_id",kind:"scalar",opt:!0,T:9},{no:8,name:"pinned_peer_ids",kind:"scalar",repeat:2,T:9}])}}const mR=new gR;class fR extends v.MessageType{constructor(){super("media.edge.ErrorResponse",[{no:1,name:"error_message",kind:"scalar",T:9},{no:2,name:"event_id",kind:"scalar",T:5}])}}const TR=new fR;class vR extends v.MessageType{constructor(){super("media.edge.EmptyResponse",[])}}new vR;class SR extends v.MessageType{constructor(){super("media.edge.RoomParticipants",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"producer_states",kind:"message",repeat:1,T:()=>Ic},{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:()=>Km}])}}const Qm=new SR;class yR extends v.MessageType{constructor(){super("media.edge.SelectedPeersResponse",[{no:1,name:"audio_peers",kind:"scalar",repeat:2,T:9},{no:2,name:"compulsory_peers",kind:"scalar",repeat:2,T:9}])}}const hu=new yR;class ER extends v.MessageType{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const PR=new ER;class _R extends v.MessageType{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>PR}])}}const Cp=new _R;class CR extends v.MessageType{constructor(){super("media.edge.PeerJoinResponse",[])}}new CR;class wR extends v.MessageType{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>mR},{no:2,name:"participants",kind:"message",repeat:1,T:()=>Qm},{no:3,name:"selected_peers",kind:"message",T:()=>hu},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const pu=new wR;class RR extends v.MessageType{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const bR=new RR;class kR extends v.MessageType{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Jm}])}}new kR;class IR extends v.MessageType{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Jm},{no:3,name:"description",kind:"message",T:()=>_s}])}}const AR=new IR;class MR extends v.MessageType{constructor(){super("media.edge.ProducerCreateResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"producer_id",kind:"scalar",T:9},{no:4,name:"description",kind:"message",T:()=>_s}])}}const DR=new MR;class OR extends v.MessageType{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>Tw}])}}new OR;class NR extends v.MessageType{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new NR;class VR extends v.MessageType{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new VR;class LR extends v.MessageType{constructor(){super("media.edge.ProducerToggleResponse",[])}}new LR;class xR extends v.MessageType{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new xR;class UR extends v.MessageType{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>_s}])}}const $R=new UR;class FR extends v.MessageType{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>_s}])}}const BR=new FR;class HR extends v.MessageType{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new HR;class qR extends v.MessageType{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new qR;class jR extends v.MessageType{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new jR;class GR extends v.MessageType{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const WR=new GR;class JR extends v.MessageType{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const KR=new JR;class zR extends v.MessageType{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const YR=new zR;class QR extends v.MessageType{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>Qm}])}}const wp=new QR;class XR extends v.MessageType{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const Rp=new XR;class ZR extends v.MessageType{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>Rp},{no:3,name:"screenshare",kind:"message",T:()=>Rp}])}}const eb=new ZR;class tb extends v.MessageType{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>Wm},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>eb}])}}new tb;class sb extends v.MessageType{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Ic}])}}const rb=new sb;class ib extends v.MessageType{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Ic},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const bp=new ib;class nb extends v.MessageType{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Ic}])}}const ab=new nb;class ob extends v.MessageType{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const gu=new ob;class cb extends v.MessageType{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const kp=new cb;class db extends v.MessageType{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new db;class lb extends v.MessageType{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new lb;class ub extends v.MessageType{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new ub;class hb extends v.MessageType{constructor(){super("media.edge.PeerDisplayNameEditBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}new hb;class pb extends v.MessageType{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new pb;class gb extends v.MessageType{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new gb;class mb extends v.MessageType{constructor(){super("socket.ai.MeetingTranscript",[{no:1,name:"meeting_id",kind:"scalar",T:9},{no:2,name:"transcript",kind:"scalar",T:9},{no:3,name:"is_partial",kind:"scalar",T:8}])}}const Jl=new mb;class fb extends v.MessageType{constructor(){super("socket.api.BaseSocketHubMessage",[{no:1,name:"event",kind:"scalar",T:5},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9},{no:4,name:"room_id",kind:"scalar",T:9},{no:5,name:"user_id",kind:"scalar",T:9},{no:6,name:"payload",kind:"scalar",T:12},{no:7,name:"error",kind:"scalar",opt:!0,T:8},{no:8,name:"sid",kind:"scalar",opt:!0,T:9}])}}new fb;class Tb extends v.MessageType{constructor(){super("socket.api.ErrorMessage",[{no:1,name:"code",kind:"scalar",opt:!0,T:5},{no:2,name:"message",kind:"scalar",T:9}])}}const vb=new Tb;var Qi;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(Qi||(Qi={}));var ar;(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"})(ar||(ar={}));var mu;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(mu||(mu={}));var fu;(function(s){s[s.PEERS=0]="PEERS",s[s.ROOMS=1]="ROOMS"})(fu||(fu={}));var gd;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(gd||(gd={}));class Sb extends v.MessageType{constructor(){super("socket.room.PeerFlags",[{no:1,name:"preset_name",kind:"scalar",T:9},{no:2,name:"recorder_type",kind:"scalar",T:9},{no:3,name:"hidden_participant",kind:"scalar",T:8}])}}const yb=new Sb;class Eb extends v.MessageType{constructor(){super("socket.room.Peer",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",ar,"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:()=>yb}])}}const Il=new Eb;class Pb extends v.MessageType{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>Il}])}}const dn=new Pb;class _b extends v.MessageType{constructor(){super("socket.room.PeerStatusUpdate",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",ar,"STAGE_TYPE_"]}])}}const Ip=new _b;class Cb extends v.MessageType{constructor(){super("socket.room.RoomPeersInfoRequest",[{no:1,name:"seach_query",kind:"scalar",T:9},{no:2,name:"limit",kind:"scalar",T:5},{no:3,name:"offset",kind:"scalar",T:5}])}}const wb=new Cb;class Rb extends v.MessageType{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>Il}])}}const Kl=new Rb;class bb extends v.MessageType{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const Ap=new bb;class kb extends v.MessageType{constructor(){super("socket.room.Room",[{no:1,name:"room_id",kind:"scalar",T:9},{no:2,name:"title",kind:"scalar",T:9},{no:4,name:"created_at",kind:"scalar",T:4,L:2},{no:5,name:"active_recordings",kind:"message",repeat:1,T:()=>Ab},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const Xm=new kb;class Ib extends v.MessageType{constructor(){super("socket.room.ActiveRecording",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",Qi]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const Ab=new Ib;class Mb extends v.MessageType{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>Xm}])}}const Mp=new Mb;class Db extends v.MessageType{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const Zm=new Db;class Ob extends v.MessageType{constructor(){super("socket.room.UpdatePeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9}])}}new Ob;class Nb extends v.MessageType{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Il},{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 Vb=new Nb;class Lb extends v.MessageType{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Il},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const xb=new Lb;class Ub extends v.MessageType{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>Xm}])}}new Ub;class $b extends v.MessageType{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new $b;class Fb extends v.MessageType{constructor(){super("socket.room.ServiceError",[{no:1,name:"message",kind:"scalar",opt:!0,T:9},{no:2,name:"code",kind:"scalar",opt:!0,T:9}])}}const mh=new Fb;class Bb extends v.MessageType{constructor(){super("socket.room.ConnectedMeetingPeer",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9},{no:3,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:4,name:"preset_id",kind:"scalar",opt:!0,T:9},{no:5,name:"display_picture_url",kind:"scalar",opt:!0,T:9}])}}const Hb=new Bb;class qb extends v.MessageType{constructor(){super("socket.room.ConnectedMeetingDump",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9},{no:3,name:"participants",kind:"message",repeat:1,T:()=>Hb}])}}const Dp=new qb;class jb extends v.MessageType{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>Dp},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>Dp}])}}const Gb=new jb;class Wb extends v.MessageType{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const Jb=new Wb;class Kb extends v.MessageType{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Jb}])}}const zb=new Kb;class Yb extends v.MessageType{constructor(){super("socket.room.CreateRoomResponsePayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9},{no:3,name:"error",kind:"message",T:()=>mh}])}}const Qb=new Yb;class Xb extends v.MessageType{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Qb}])}}const Op=new Xb;class Zb extends v.MessageType{constructor(){super("socket.room.UpdateRoomRequestPayload",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9}])}}const ek=new Zb;class tk extends v.MessageType{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>ek}])}}new tk;class sk extends v.MessageType{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const rk=new sk;class ik extends v.MessageType{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>rk}])}}const nk=new ik;class ak extends v.MessageType{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>dk}])}}const ok=new ak;class ck extends v.MessageType{constructor(){super("socket.room.DisableConnectedRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"status",kind:"scalar",opt:!0,T:9},{no:3,name:"title",kind:"scalar",opt:!0,T:9},{no:4,name:"error",kind:"message",T:()=>mh}])}}const dk=new ck;class lk extends v.MessageType{constructor(){super("socket.room.MovePeerPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"preset_id",kind:"scalar",opt:!0,T:9}])}}const uk=new lk;class hk extends v.MessageType{constructor(){super("socket.room.MovePeersBetweenRoomsRequest",[{no:1,name:"source_meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"destination_meeting_id",kind:"scalar",opt:!0,T:9},{no:3,name:"participants",kind:"message",repeat:1,T:()=>uk}])}}const pk=new hk;class gk extends v.MessageType{constructor(){super("socket.room.MovedPeer",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:3,name:"error",kind:"message",T:()=>mh}])}}const ef=new gk;class mk extends v.MessageType{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>ef}])}}new mk;class fk extends v.MessageType{constructor(){super("socket.room.TransferPeer",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"auth_token",kind:"scalar",opt:!0,T:9}])}}const Tk=new fk;class vk extends v.MessageType{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>Ek}])}}const Sk=new vk;class yk extends v.MessageType{constructor(){super("socket.room.AddedParticipant",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",opt:!0,T:9},{no:3,name:"picture",kind:"scalar",opt:!0,T:9},{no:4,name:"custom_participant_id",kind:"scalar",T:9}])}}const Ek=new yk;class Pk extends v.MessageType{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const tf=new Pk;class _k extends v.MessageType{constructor(){super("socket.room.BroadcastMessage",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"timestamp",kind:"scalar",T:4,L:2},{no:4,name:"ids",kind:"scalar",repeat:2,T:9},{no:5,name:"broadcast_type",kind:"enum",opt:!0,T:()=>["socket.room.BroadcastType",fu,"BROADCAST_TYPE_"]}])}}const Ya=new _k;class Ck extends v.MessageType{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const wk=new Ck;class Rk extends v.MessageType{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const bk=new Rk;class kk extends v.MessageType{constructor(){super("socket.room.WaitingRoomRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"picture",kind:"scalar",opt:!0,T:9},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_name",kind:"scalar",opt:!0,T:9}])}}const Ik=new kk;class Ak extends v.MessageType{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>Ik}])}}const Np=new Ak;class Mk extends v.MessageType{constructor(){super("socket.room.GetRoomStageStateResponse",[{no:1,name:"on_stage_peers",kind:"scalar",repeat:2,T:9},{no:2,name:"approved_stage_peers",kind:"scalar",repeat:2,T:9},{no:3,name:"requested_stage_peers",kind:"scalar",repeat:2,T:9}])}}const Vp=new Mk;var Tu;(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"})(Tu||(Tu={}));var Gr;(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"})(Gr||(Gr={}));class Dk extends v.MessageType{constructor(){super("socket.preset.PollsPermissionUpdate",[{no:1,name:"can_create",kind:"scalar",opt:!0,T:8},{no:2,name:"can_vote",kind:"scalar",opt:!0,T:8},{no:3,name:"can_view",kind:"scalar",opt:!0,T:8}])}}const Ok=new Dk;class Nk extends v.MessageType{constructor(){super("socket.preset.PluginsPermissionsUpdate",[{no:1,name:"can_close",kind:"scalar",opt:!0,T:8},{no:2,name:"can_start",kind:"scalar",opt:!0,T:8}])}}const Vk=new Nk;class Lk extends v.MessageType{constructor(){super("socket.preset.PublicChatPermission",[{no:1,name:"can_send",kind:"scalar",opt:!0,T:8},{no:2,name:"text",kind:"scalar",opt:!0,T:8},{no:3,name:"files",kind:"scalar",opt:!0,T:8}])}}const xk=new Lk;class Uk extends v.MessageType{constructor(){super("socket.preset.PrivateChatPermission",[{no:1,name:"can_send",kind:"scalar",opt:!0,T:8},{no:2,name:"can_receive",kind:"scalar",opt:!0,T:8},{no:3,name:"text",kind:"scalar",opt:!0,T:8},{no:4,name:"files",kind:"scalar",opt:!0,T:8}])}}const $k=new Uk;class Fk extends v.MessageType{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>xk},{no:2,name:"private",kind:"message",T:()=>$k}])}}const Bk=new Fk;class Hk extends v.MessageType{constructor(){super("socket.preset.ConnectedMeetingPermissionUpdate",[{no:1,name:"can_alter_connected_meetings",kind:"scalar",opt:!0,T:8},{no:2,name:"can_switch_to_parent_meeting",kind:"scalar",opt:!0,T:8},{no:3,name:"can_switch_connected_meetings",kind:"scalar",opt:!0,T:8}])}}const qk=new Hk;class jk extends v.MessageType{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Gr,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Gr,"STREAM_PERMISSION_TYPE_"]}])}}const zl=new jk;class Gk extends v.MessageType{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>zl},{no:2,name:"audio",kind:"message",T:()=>zl},{no:3,name:"screenshare",kind:"message",T:()=>zl}])}}const Wk=new Gk;class Jk extends v.MessageType{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>Ok},{no:2,name:"plugins",kind:"message",T:()=>Vk},{no:3,name:"chat",kind:"message",T:()=>Bk},{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",Tu,"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",mu,"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:()=>qk},{no:23,name:"media",kind:"message",T:()=>Wk}])}}const fh=new Jk;class Kk extends v.MessageType{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const zk=new Kk;class Yk extends v.MessageType{constructor(){super("socket.preset.PeerPreset",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"preset",kind:"scalar",T:12}])}}const Qk=new Yk;class Xk extends v.MessageType{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>Qk}])}}const Zk=new Xk;class eI extends v.MessageType{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>fh}])}}const sf=new eI;class tI extends v.MessageType{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>sf}])}}const sI=new tI;class rI extends v.MessageType{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>sf}])}}const Lp=new rI;class iI extends v.MessageType{constructor(){super("socket.preset.PeerUserIDMap",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9}])}}const nI=new iI;class aI extends v.MessageType{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>nI},{no:2,name:"patch",kind:"message",T:()=>fh}])}}new aI;class oI extends v.MessageType{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>fh}])}}new oI;class cI extends v.MessageType{constructor(){super("socket.chat.ChatMessage",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"user_id",kind:"scalar",T:9},{no:4,name:"display_name",kind:"scalar",T:9},{no:5,name:"pinned",kind:"scalar",T:8},{no:6,name:"is_edited",kind:"scalar",T:8},{no:7,name:"payload_type",kind:"scalar",T:5},{no:8,name:"payload",kind:"scalar",T:9},{no:10,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:11,name:"created_at",kind:"scalar",T:4,L:2},{no:12,name:"created_at_ms",kind:"scalar",opt:!0,T:4,L:2},{no:13,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:14,name:"channel_index",kind:"scalar",opt:!0,T:9}])}}const Yr=new cI;class dI extends v.MessageType{constructor(){super("socket.chat.GetPaginatedChatMessageFilters",[{no:1,name:"pinned",kind:"scalar",oneof:"filters",T:8},{no:2,name:"user_id",kind:"scalar",oneof:"filters",T:9}])}}const lI=new dI;class uI extends v.MessageType{constructor(){super("socket.chat.GetPaginatedChatMessageRoomRequest",[{no:1,name:"time_stamp",kind:"scalar",T:4,L:2},{no:2,name:"size",kind:"scalar",T:5},{no:3,name:"from",kind:"scalar",T:5},{no:4,name:"reversed",kind:"scalar",T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:6,name:"filters",kind:"message",T:()=>lI}])}}const hI=new uI;class pI extends v.MessageType{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Yr},{no:2,name:"next",kind:"scalar",T:8}])}}const gI=new pI;class mI extends v.MessageType{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Yr}])}}const rf=new mI;class fI extends v.MessageType{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const TI=new fI;class vI extends v.MessageType{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Yr}])}}const Yl=new vI;class SI extends v.MessageType{constructor(){super("socket.chat.SendChatMessageToPeersRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"payload_type",kind:"scalar",T:5},{no:3,name:"payload",kind:"scalar",T:9}])}}const yI=new SI;class EI extends v.MessageType{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Yr}])}}const Ql=new EI;class PI extends v.MessageType{constructor(){super("socket.chat.SendChatMessageToChannelRequest",[{no:1,name:"channel_id",kind:"scalar",T:9},{no:2,name:"payload_type",kind:"scalar",T:5},{no:3,name:"payload",kind:"scalar",T:9}])}}new PI;class _I extends v.MessageType{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Yr}])}}new _I;class CI extends v.MessageType{constructor(){super("socket.chat.EditChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"payload_type",kind:"scalar",opt:!0,T:5},{no:3,name:"payload",kind:"scalar",opt:!0,T:9},{no:4,name:"pinned",kind:"scalar",opt:!0,T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const wI=new CI;class RI extends v.MessageType{constructor(){super("socket.chat.PinChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"pinned",kind:"scalar",T:8},{no:3,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const bI=new RI;class kI extends v.MessageType{constructor(){super("socket.chat.PinChatMessageResponse",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"pinned",kind:"scalar",T:8},{no:3,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:4,name:"message",kind:"message",T:()=>Yr}])}}const Bc=new kI;class II extends v.MessageType{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Yr}])}}const Hc=new II;class AI extends v.MessageType{constructor(){super("socket.chat.DeleteChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const MI=new AI;class DI extends v.MessageType{constructor(){super("socket.chat.DeleteChatMessageResponse",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const qc=new DI;class OI extends v.MessageType{constructor(){super("socket.chat.SearchChatMessagesRequest",[{no:1,name:"time_stamp",kind:"scalar",T:4,L:2},{no:2,name:"size",kind:"scalar",T:5},{no:3,name:"from",kind:"scalar",T:5},{no:4,name:"reversed",kind:"scalar",T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:6,name:"search_term",kind:"scalar",T:9}])}}const NI=new OI;class VI extends v.MessageType{constructor(){super("socket.chat.MarkChannelIndexAsReadRequest",[{no:1,name:"channel_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"channel_index",kind:"scalar",T:9}])}}new VI;class LI extends v.MessageType{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}new LI;class xI extends v.MessageType{constructor(){super("socket.chat.CreateChatChannelRequest",[{no:1,name:"display_name",kind:"scalar",T:9},{no:2,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:4,name:"visibility",kind:"scalar",T:9},{no:5,name:"is_direct_message",kind:"scalar",T:8}])}}new xI;class UI extends v.MessageType{constructor(){super("socket.chat.UpdateChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9},{no:3,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:4,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:5,name:"visibility",kind:"scalar",opt:!0,T:9},{no:6,name:"is_direct_message",kind:"scalar",opt:!0,T:8}])}}new UI;class $I extends v.MessageType{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new $I;class FI extends v.MessageType{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new FI;class BI extends v.MessageType{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>Yr},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const HI=new BI;class qI extends v.MessageType{constructor(){super("socket.chat.ChatChannel",[{no:1,name:"chat_channel_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9},{no:3,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:4,name:"visibility",kind:"scalar",T:9},{no:5,name:"is_direct_message",kind:"scalar",T:8},{no:6,name:"latest_message_and_unread_count",kind:"message",T:()=>HI},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const jI=new qI;class GI extends v.MessageType{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>jI}])}}new GI;class WI extends v.MessageType{constructor(){super("socket.chat.ChannelMember",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",opt:!0,T:9},{no:3,name:"picture",kind:"scalar",opt:!0,T:9},{no:4,name:"custom_participant_id",kind:"scalar",T:9}])}}const JI=new WI;class KI extends v.MessageType{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>JI}])}}new KI;class zI extends v.MessageType{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const YI=new zI;class QI extends v.MessageType{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const XI=new QI;class ZI extends v.MessageType{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const eA=new ZI;class tA extends v.MessageType{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const sA=new tA;class rA extends v.MessageType{constructor(){super("socket.plugin.EnablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const iA=new rA;class nA extends v.MessageType{constructor(){super("socket.plugin.DisablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const aA=new nA;class oA extends v.MessageType{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const cA=new oA;class dA extends v.MessageType{constructor(){super("socket.plugin.PluginEventToPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"plugin_data",kind:"scalar",T:12}])}}const lA=new dA;class uA extends v.MessageType{constructor(){super("socket.plugin.StoreKeys",[{no:1,name:"store_key",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",opt:!0,T:12}])}}const Th=new uA;class hA extends v.MessageType{constructor(){super("socket.plugin.PluginStoreInsertKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"insert_keys",kind:"message",repeat:1,T:()=>Th}])}}const xp=new hA;class pA extends v.MessageType{constructor(){super("socket.plugin.PluginStoreGetKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"get_keys",kind:"message",repeat:1,T:()=>Th}])}}const gA=new pA;class mA extends v.MessageType{constructor(){super("socket.plugin.PluginStoreDeleteKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"delete_keys",kind:"message",repeat:1,T:()=>Th}])}}const fA=new mA;class TA extends v.MessageType{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}const vA=new TA;class SA extends v.MessageType{constructor(){super("socket.plugin.EnablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"enabled_by",kind:"scalar",T:9}])}}const vu=new SA;class yA extends v.MessageType{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>vu}])}}const EA=new yA;class PA extends v.MessageType{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}const Up=new PA;class _A extends v.MessageType{constructor(){super("socket.plugin.PluginStoreItem",[{no:1,name:"timestamp",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"store_key",kind:"scalar",T:9},{no:4,name:"payload",kind:"scalar",T:12}])}}const CA=new _A;class wA extends v.MessageType{constructor(){super("socket.plugin.PluginStoreResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"store_items",kind:"message",repeat:1,T:()=>CA}])}}const $p=new wA;class RA extends v.MessageType{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const Fp=new RA;class bA extends v.MessageType{constructor(){super("socket.livestreaming.LiveStreamingEvent",[{no:1,name:"livestream_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",T:9},{no:5,name:"playback_url",kind:"scalar",T:9},{no:6,name:"org_id",kind:"scalar",T:9},{no:7,name:"room_name",kind:"scalar",T:9},{no:8,name:"room_uuid",kind:"scalar",T:9},{no:9,name:"status",kind:"scalar",T:9},{no:10,name:"manual_ingest",kind:"scalar",opt:!0,T:8}])}}const Bp=new bA;class kA extends v.MessageType{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const Hp=new kA;class IA extends v.MessageType{constructor(){super("socket.livestreaming.StageRequest",[{no:1,name:"display_name",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9}])}}const AA=new IA;class MA extends v.MessageType{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>AA}])}}const Xl=new MA;class DA extends v.MessageType{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const OA=new DA;class NA extends v.MessageType{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const VA=new NA;class LA extends v.MessageType{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const qp=new LA;class xA extends v.MessageType{constructor(){super("socket.polls.Poll",[{no:1,name:"poll_id",kind:"scalar",T:9},{no:2,name:"created_by",kind:"scalar",T:9},{no:3,name:"created_by_user_id",kind:"scalar",T:9},{no:4,name:"question",kind:"scalar",T:9},{no:5,name:"options",kind:"message",repeat:1,T:()=>$A},{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 nf=new xA;class UA extends v.MessageType{constructor(){super("socket.polls.PollOption",[{no:1,name:"text",kind:"scalar",T:9},{no:2,name:"count",kind:"scalar",opt:!0,T:4,L:2},{no:3,name:"votes",kind:"message",repeat:1,T:()=>BA}])}}const $A=new UA;class FA extends v.MessageType{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const BA=new FA;class HA extends v.MessageType{constructor(){super("socket.polls.NewPollRequest",[{no:1,name:"question",kind:"scalar",T:9},{no:2,name:"options",kind:"scalar",repeat:2,T:9},{no:3,name:"anonymous",kind:"scalar",T:8},{no:4,name:"hide_votes",kind:"scalar",T:8},{no:5,name:"created_by",kind:"scalar",opt:!0,T:9},{no:6,name:"created_by_user_id",kind:"scalar",opt:!0,T:9}])}}const qA=new HA;class jA extends v.MessageType{constructor(){super("socket.polls.VotePollRequest",[{no:1,name:"poll_id",kind:"scalar",T:9},{no:2,name:"index",kind:"scalar",T:4,L:2}])}}const GA=new jA;class WA extends v.MessageType{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>nf}])}}const Zl=new WA;class JA extends v.MessageType{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>nf}])}}const KA=new JA;class zA extends v.MessageType{constructor(){super("socket.recording.RecordingEvent",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",Qi]}])}}const jp=new zA;class YA extends v.MessageType{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:0},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const t=this.create(),e=Date.now();return t.seconds=v.PbLong.from(Math.floor(e/1e3)).toBigInt(),t.nanos=e%1e3*1e6,t}toDate(t){return new Date(v.PbLong.from(t.seconds).toNumber()*1e3+Math.ceil(t.nanos/1e6))}fromDate(t){const e=this.create(),r=t.getTime();return e.seconds=v.PbLong.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}internalJsonWrite(t,e){let r=v.PbLong.from(t.seconds).toNumber()*1e3;if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(t.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let i="Z";if(t.nanos>0){let a=(t.nanos+1e9).toString().substring(1);a.substring(3)==="000000"?i="."+a.substring(0,3)+"Z":a.substring(6)==="000"?i="."+a.substring(0,6)+"Z":i="."+a+"Z"}return new Date(r).toISOString().replace(".000Z",i)}internalJsonRead(t,e,r){if(typeof t!="string")throw new Error("Unable to parse Timestamp from JSON "+v.typeofJsonValue(t)+".");let i=t.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let a=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(a))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(a<Date.parse("0001-01-01T00:00:00Z")||a>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return r||(r=this.create()),r.seconds=v.PbLong.from(a/1e3).toBigInt(),r.nanos=0,i[7]&&(r.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),r}}new YA;class QA extends v.MessageType{constructor(){super("common.BaseHubMessage",[{no:1,name:"event",kind:"scalar",T:5},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9},{no:4,name:"room_id",kind:"scalar",T:9},{no:5,name:"user_id",kind:"scalar",T:9},{no:6,name:"payload",kind:"scalar",T:12},{no:7,name:"error",kind:"scalar",opt:!0,T:8},{no:8,name:"sid",kind:"scalar",opt:!0,T:9},{no:9,name:"room_object_id",kind:"scalar",opt:!0,T:9},{no:10,name:"preset",kind:"scalar",opt:!0,T:9},{no:11,name:"use_start_session",kind:"scalar",opt:!0,T:8}])}}const Su=new QA;class XA extends v.MessageType{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Su}])}}new XA;class ZA extends v.MessageType{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>Su},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>Su}])}}new ZA;const eM=0,tM=1,sM=2,rM=3,iM=5,nM={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},aM={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,searchChannelMessages:7,pinMessage:10},oM={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},cM={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},af={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},dM={getUserPresets:0,updateUserPreset:1};function Ac(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function of(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const L=Ac(eM,nM),Le=Ac(tM,aM),j=Ac(sM,oM),$s=Ac(rM,cM),Rr=of(af,16777216),Ss=of(af,50331648),Xc=Ac(iM,dM);var lM=Object.defineProperty,uM=Object.getOwnPropertyDescriptor,Qr=(s,t,e,r)=>{for(var i=r>1?void 0:r?uM(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&lM(t,e,i),i},es=(s=>(s[s.TEXT=0]="TEXT",s[s.IMAGE=1]="IMAGE",s[s.FILE=2]="FILE",s[s.CUSTOM=3]="CUSTOM",s))(es||{}),kt,kn;class Tr{constructor(t,e){g(this,kt,void 0);g(this,kn,void 0);m(this,kt,e),m(this,kn,t)}get telemetry(){return n(this,kn).getValue("telemetry")}get logger(){return n(this,kn).getValue("logger")}getChatMessages(){return n(this,kt).sendMessagePromise(Le.getMessages)}async getChatMessagesPaginated(t,e,r,i){const a={timeStamp:t,size:e,from:0,reversed:r,...i&&{filters:{filters:i}}},o=await n(this,kt).sendMessagePromise(Le.getPaginatedMessages,hI.toBinary(a));return o.payload?gI.fromBinary(o.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};n(this,kt).sendMessage(Le.sendMessageToRoom,TI.toBinary(r))}sendMessageToPeers(t,e,r){const i={payloadType:e,peerIds:r,payload:t};n(this,kt).sendMessage(Le.sendMessageToPeers,yI.toBinary(i))}sendMessage(t,e,r){if(r&&r.length>0){this.sendMessageToPeers(t,e,r);return}this.sendMessageToRoom(t,e)}async editMessage(t,e,r,i){const a={chatId:t,payloadType:r,payload:e};i!==void 0&&(a.pinned=i);const o=await n(this,kt).sendMessagePromise(Le.editMessage,wI.toBinary(a));return Hc.fromBinary(o.payload).message}async deleteMessage(t){const e={chatId:t},r=await n(this,kt).sendMessagePromise(Le.deleteMessage,MI.toBinary(e));return{id:qc.fromBinary(r.payload).chatId}}async searchMessages(t,e){var i,a,o,c;const r={searchTerm:t,timeStamp:(i=e.timestamp)!=null?i:Date.now(),size:(a=e.limit)!=null?a:75,from:(o=e.offset)!=null?o:0,reversed:(c=e.reversed)!=null?c:!0};try{const d=await n(this,kt).sendMessagePromise(Le.searchChannelMessages,NI.toBinary(r));return rf.fromBinary(d.payload).messages}catch(d){return[]}}async setPinState(t,e){const r={chatId:t,pinned:e},i=await n(this,kt).sendMessagePromise(Le.pinMessage,bI.toBinary(r));return Bc.fromBinary(i.payload)}on(t,e){let r,i;switch(t){case Le.sendMessageToRoom:{r=Yl.fromBinary.bind(Yl),i=Yl.create();break}case Le.sendMessageToPeers:{r=Ql.fromBinary.bind(Ql),i=Ql.create();break}case Le.editMessage:{r=Hc.fromBinary.bind(Hc),i=Hc.create();break}case Le.pinMessage:{r=Bc.fromBinary.bind(Bc),i=Bc.create();break}case Le.deleteMessage:{r=qc.fromBinary.bind(qc),i=qc.create();break}}if(!r){this.logger.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}n(this,kt).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}kt=new WeakMap,kn=new WeakMap;Qr([y.trace("SocketService.getChatMessages")],Tr.prototype,"getChatMessages",1);Qr([y.trace("SocketService.getChatMessagesPaginated")],Tr.prototype,"getChatMessagesPaginated",1);Qr([y.trace("SocketService.sendMessageToRoom")],Tr.prototype,"sendMessageToRoom",1);Qr([y.trace("SocketService.sendMessageToPeers")],Tr.prototype,"sendMessageToPeers",1);Qr([y.trace("SocketService.sendMessage")],Tr.prototype,"sendMessage",1);Qr([y.trace("SocketService.editMessage")],Tr.prototype,"editMessage",1);Qr([y.trace("SocketService.deleteMessage")],Tr.prototype,"deleteMessage",1);Qr([y.trace("SocketService.searchMessages")],Tr.prototype,"searchMessages",1);function hM(s){return s.replace(/([-_]\w)/g,t=>t[1].toUpperCase())}function ys(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>ys(e));const t={};return Object.keys(s).forEach(e=>{const r=ur.validate(e)?e:hM(e);t[r]=ys(s[e])}),t}function pM(s){return s.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function cf(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>cf(e));const t={};return Object.keys(s).forEach(e=>{const r=ur.validate(e)?e:pM(e);t[r]=s[e]}),t}function md(s,t={}){return s==null?{}:(Object.getOwnPropertyNames(s).forEach(e=>{if(typeof s[e]!="function"){if(typeof s[e]=="object"){md(s[e],t[e]={});return}t[e]=s[e]}}),t)}class Gp{constructor(t){u(this,"defaults");this.defaults={baseURL:t.baseURL,headers:{common:{}},timeout:t.timeout,retry:t.retry,retryDelay:t.retryDelay}}buildURL(t,e){const{baseURL:r}=this.defaults,i=t.startsWith("http")?t:`${r}${t.startsWith("/")?t:`/${t}`}`;if(e){const a=new URLSearchParams;return Object.entries(e).forEach(([o,c])=>{a.append(o,c)}),`${i}${i.includes("?")?"&":"?"}${a.toString()}`}return i}async request(t){var p;const e=((p=t.method)==null?void 0:p.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,h=t.retryDelay||this.defaults.retryDelay;try{const f=new AbortController,T=setTimeout(()=>f.abort(),d);c.signal=f.signal;const E=await fetch(r,c);clearTimeout(T);let C=null;const _=E.headers.get("content-type");_&&_.includes("application/json")?C=await E.json():C=await E.text();const I={};E.headers.forEach((x,N)=>{I[N]=x});const M={data:C,status:E.status,statusText:E.statusText,headers:I,config:t};if(!E.ok)throw M;return M}catch(f){if(f instanceof Error&&l>0)return await new Promise(T=>setTimeout(T,h)),this.defaults.baseURL===ci.apiBase.prod?this.defaults.baseURL=ci.apiBase.prodAlternate:this.defaults.baseURL===ci.apiBase.prodAlternate&&(this.defaults.baseURL=ci.apiBase.prod),this.request({...t,retry:l-1});throw f}}async get(t,e={}){return this.request({...e,method:"GET",url:t})}async post(t,e,r={}){return this.request({...r,method:"POST",url:t,data:e})}async put(t,e,r={}){return this.request({...r,method:"PUT",url:t,data:e})}}const gM=3,mM=30,fM=8e3;class TM{constructor(t,e){u(this,"ipInfo");u(this,"fetchClient");u(this,"requests");u(this,"roomName");u(this,"roomUUID");u(this,"authToken");u(this,"organizationId");u(this,"iceServers");u(this,"pluginInformation");u(this,"userDetails");u(this,"roomDetails");u(this,"context");this.context=t;const{timeout:r=fM,retry:i=gM,retryDelay:a=mM,baseURL:o=ci.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 Gp({baseURL:o,timeout:r,retry:i,retryDelay:a,responseType:"json"}),this.fetchClient=new Gp({baseURL:"",timeout:r,retry:i,retryDelay:a,responseType:"json"}),this.setAuthToken(c,{bearer:!0});const l=this.requests.request.bind(this.requests);this.requests.request=async h=>{var f,T,E,C,_;const p=t.getValue("telemetry");try{p.injectContext(this.requests.defaults.headers.common);const I=await l(h);return h.url!==p.logsEndpoint&&this.logger.debug("xhr::fetch",{networkCall:{status:I.status,statusText:I.statusText,baseURL:h.baseURL||this.requests.defaults.baseURL,url:h.url,method:h.method}}),I}catch(I){throw I?(((f=I.config)==null?void 0:f.url)!==p.logsEndpoint&&this.logger.error("xhr::fetch",{error:I,networkCall:{status:I.status,statusText:I.statusText,baseURL:((T=I.config)==null?void 0:T.baseURL)||this.requests.defaults.baseURL,url:(E=I.config)==null?void 0:E.url,retries:(C=I.config)==null?void 0:C.retry,method:(_=I.config)==null?void 0:_.method,isOnline:navigator.onLine?"online":"offline"}}),new b(I.message||"Network request failed","0011")):new b("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 vM=Object.defineProperty,SM=Object.getOwnPropertyDescriptor,rs=(s,t,e,r)=>{for(var i=r>1?void 0:r?SM(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&vM(t,e,i),i};class $t extends TM{constructor(e,r){super(e,r);u(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 Zu.getIPDetails({peerId:e,apiHostnames:qm(this.context),logger:Vm});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 a,o,c,d,l,h,p;if(this.pluginInformation)return this.pluginInformation;const{plugins:e}=(await this.requests.get("/v2/plugins/user")).data.data,r=((o=(a=this.context.getValue("flagsmith").getValue(Y.V1_PLUGINS))==null?void 0:a.toString())==null?void 0:o.split(","))||[],i=e.reduce((f,T)=>(f[r.includes(T.id)?"v1":"v2"].push({...T,name:T.name.replace("v2","")}),f),{v1:[],v2:[]});return(l=(d=(c=this.context.getValue("modules"))==null?void 0:c.devTools)==null?void 0:d.plugins)!=null&&l.length&&((p=(h=this.context.getValue("modules"))==null?void 0:h.devTools)==null||p.plugins.forEach(f=>{var E,C,_;const T={...za,tags:[...za.tags],baseUrl:`http://localhost:${f.port}`,name:f.name,picture:(E=f.picture)!=null?E:za.picture,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),id:f.id,organizationId:this.organizationId,description:(C=f.description)!=null?C:za.description,staggered:(_=f.staggered)!=null?_:za.staggered};i.v2.push(T)})),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){const r=ba(this.context,"chat_upload_expiry"),i={roomUUID:this.roomUUID,filename:e,expiry:typeof r=="number"?r:void 0},{get_location:a,put_location:o}=(await this.requests.post("/v2/meetings/chat-upload",i)).data.data;return{getLocation:a,putLocation:o}}async uploadFile(e,r){if(navigator.isReactNative&&"uri"in e)try{await fetch(r,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:{uri:e.uri,name:e.name}})}catch(i){this.logger.error(`sendFileMessage::${i}`)}else await this.fetchClient.put(r,e,{headers:{"Content-Type":e.type}})}async startLivestreaming({manualIngestion:e}){const r=ys(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=ys((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 ys(e)}async startRecording(e,r){return(await this.requests.post("/v2/recordings",{...cf(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 b("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}=ys((await this.requests.post("v2/internals/rooms",{ip_information:e})).data.data);return{meetingTitle:r}}}rs([y.trace("APIClient.getIPDetails")],$t.prototype,"getIPDetails",1);rs([y.trace("APIClient.getICEServers")],$t.prototype,"getICEServers",1);rs([y.trace("APIClient.getPlugins")],$t.prototype,"getPlugins",1);rs([y.trace("APIClient.startLivestreaming")],$t.prototype,"startLivestreaming",1);rs([y.trace("APIClient.stopLivestreaming")],$t.prototype,"stopLivestreaming",1);rs([y.trace("APIClient.getActiveLivestream")],$t.prototype,"getActiveLivestream",1);rs([y.trace("APIClient.getUserDetails")],$t.prototype,"getUserDetails",1);rs([y.trace("APIClient.startRecording")],$t.prototype,"startRecording",1);rs([y.trace("APIClient.stopRecording")],$t.prototype,"updateRecording",1);rs([y.trace("APIClient.getActiveRecording")],$t.prototype,"getActiveRecording",1);rs([y.trace("APIClient.getActiveTranscript")],$t.prototype,"getActiveTranscript",1);rs([y.trace("APIClient.getRoomNodeData")],$t.prototype,"getRoomNodeData",1);let yu;function yM(s,t){return yu=new $t(s,t),yu}function it(){return yu}const Aa={maxInvocations:5,period:1};function _t(s,t){return function(e,r,i){const a=i.value;let o=0,c=Date.now();return i.value=function(...d){const l=Date.now(),h=t?this[t]:s;if(l-c>h.period*1e3&&(c=l,o=0),o>=h.maxInvocations)throw new b(`Method rate limit ${h.maxInvocations} invocations/${h.period}sec exceeded`,"0013");return o+=1,a.apply(this,d)},i}}var EM=Object.defineProperty,PM=Object.getOwnPropertyDescriptor,Cs=(s,t,e,r)=>{for(var i=r>1?void 0:r?PM(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&EM(t,e,i),i};const _M=["text","image","file","custom","poll"],Zc={maxInvocations:180,period:60};var Z,li,He,In,wd,df,Po,Eu,cg;let Lt=(cg=class extends Ut{constructor(t,e,r,i){const a=t.getValue("logger");super(a);g(this,wd);g(this,Po);u(this,"messages");g(this,Z,void 0);g(this,li,void 0);g(this,He,void 0);g(this,In,void 0);u(this,"maxTextLimit",2e3);m(this,In,t),m(this,He,e),m(this,Z,r),m(this,li,i),this.messages=[]}get telemetry(){return n(this,In).getValue("telemetry")}setMaxTextLimit(t){this.maxTextLimit=t}async sendMessageInternal(t,e){switch(t.type){case"text":{await this.sendTextMessageInternal(t.message,e);break}case"image":await this.sendImageMessageInternal(t.image,e);break;case"file":await this.sendFileMessageInternal(t.file,e);break;default:this.logger.error("sendMessage::message_type_not_supported",{chat:{messageType:t.type}});break}}async sendTextMessageInternal(t,e){var i,a,o,c,d,l;if(t.length>this.maxTextLimit)throw new b("Max character limit breached","0503");if(e&&e.length>0){if(!((i=n(this,Z).permissions)!=null&&i.chatPrivate.canSend)||!((a=n(this,Z).permissions)!=null&&a.chatPrivate.text))throw this.logger.error("sendTextMessage::private_chat_permission_denied"),new b("Could not send message to private chat.","0501")}else if(!((c=(o=n(this,Z).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=n(this,Z).permissions)==null?void 0:d.chatPublic)!=null&&l.text))throw this.logger.error("sendTextMessage::public_chat_permission_denied"),new b("Could not send message to public chat.","0501");if(!t)throw this.logger.error("sendTextMessage::message_can_not_be_empty"),new b("Message can not be empty.","0502");let r=[];e&&e.length>0&&(e.push(n(this,Z).id),r=n(this,li).joined.toArray().filter(h=>e.includes(h.id)).map(h=>h.userId),r.push(n(this,Z).userId)),n(this,He).sendMessage(t,es.TEXT,e)}async sendImageMessageInternal(t,e){var i,a,o,c,d,l;if(e&&e.length>0){if(!((i=n(this,Z).permissions)!=null&&i.chatPrivate.canSend)||!((a=n(this,Z).permissions)!=null&&a.chatPrivate.files)){this.logger.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((c=(o=n(this,Z).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=n(this,Z).permissions)==null?void 0:d.chatPublic)!=null&&l.files)){this.logger.error("sendImageMessage::permission_denied");return}if(!t){this.logger.error("sendImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(t.type)){this.logger.error("sendImageMessage::image_type_not_supported",{chat:{imageType:t.type}});return}try{const h=it(),{getLocation:p,putLocation:f}=await h.getPresignedUrls(t.name);await h.uploadFile(t,f);let T=[];e&&e.length>0&&(e.push(n(this,Z).id),T=n(this,li).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),T.push(n(this,Z).userId)),n(this,He).sendMessage(p,es.IMAGE,e)}catch(h){throw new b("Error sending image message.","0500",this.logger)}}async sendFileMessageInternal(t,e){var r,i,a,o,c,d;if(e&&e.length>0){if(!((r=n(this,Z).permissions)!=null&&r.chatPrivate.canSend)||!((i=n(this,Z).permissions)!=null&&i.chatPrivate.files)){this.logger.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(a=n(this,Z).permissions)==null?void 0:a.chatPublic)!=null&&o.canSend)||!((d=(c=n(this,Z).permissions)==null?void 0:c.chatPublic)!=null&&d.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!t){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const l=it(),{getLocation:h,putLocation:p}=await l.getPresignedUrls(t.name);await l.uploadFile(t,p);let f=[];e&&e.length>0&&(e.push(n(this,Z).id),f=n(this,li).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),f.push(n(this,Z).userId));const T=JSON.stringify({link:h,name:t.name,size:"size"in t?t.size:0});n(this,He).sendMessage(T,es.FILE,e)}catch(l){throw new b("Error sending file message.","0500",this.logger)}}get rateLimits(){return Zc}updateRateLimits(t,e){Zc.maxInvocations=t,Zc.period=e}async sendTextMessage(t,e){return this.sendTextMessageInternal(t,e)}async sendCustomMessage(t,e){var a,o,c,d,l,h,p,f,T,E,C,_,I,M,x;if(e&&e.length>0){if(!((a=n(this,Z).permissions)!=null&&a.chatPrivate.canSend)||!((o=n(this,Z).permissions)!=null&&o.chatPrivate.files)||!((c=n(this,Z).permissions)!=null&&c.chatPrivate.text)){this.logger.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((l=(d=n(this,Z).permissions)==null?void 0:d.chatPublic)!=null&&l.canSend)||!((p=(h=n(this,Z).permissions)==null?void 0:h.chatPublic)!=null&&p.files)||!((T=(f=n(this,Z).permissions)==null?void 0:f.chatPublic)!=null&&T.text)){this.logger.error("sendCustomMessage::permission_denied");return}const r=async N=>{try{if(typeof N=="string")return{link:N};const $=it(),{getLocation:q,putLocation:ee}=await $.getPresignedUrls(N.name);return await $.uploadFile(N,ee),{link:q,type:N.type,name:N.name,size:N.size}}catch($){throw new b("Error sending image message.","0500",this.logger)}},i={...t,files:await Promise.all((C=(E=t.files)!=null?E:[])==null?void 0:C.map(async N=>r(N))),images:await Promise.all((I=(_=t.images)!=null?_:[])==null?void 0:I.map(async N=>r(N))),videos:await Promise.all((x=(M=t.videos)!=null?M:[])==null?void 0:x.map(async N=>r(N)))};n(this,He).sendMessage(JSON.stringify(i),es.CUSTOM,e)}async sendImageMessage(t,e){return this.sendImageMessageInternal(t,e)}async sendFileMessage(t,e){return this.sendFileMessageInternal(t,e)}async sendMessage(t,e){return this.sendMessageInternal(t,e)}async editTextMessage(t,e){var r,i,a,o;if(!((i=(r=n(this,Z).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(a=n(this,Z).permissions)==null?void 0:a.chatPublic)!=null&&o.text)){this.logger.error("editTextMessage::permission_denied");return}if(!e){this.logger.error("editTextMessage::message_can_not_be_empty");return}n(this,He).editMessage(t,e,es.TEXT)}async editImageMessage(t,e){var i,a,o,c;if(!((a=(i=n(this,Z).permissions)==null?void 0:i.chatPublic)!=null&&a.canSend)||!((c=(o=n(this,Z).permissions)==null?void 0:o.chatPublic)!=null&&c.files)){this.logger.error("editImageMessage::permission_denied");return}if(!e){this.logger.error("editImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(e.type)){this.logger.error("sendImageMessage::image_type_not_supported",{chat:{imageType:e.type}});return}try{const d=it(),{getLocation:l,putLocation:h}=await d.getPresignedUrls(e.name);await d.uploadFile(e,h),n(this,He).editMessage(t,l,es.IMAGE)}catch(d){throw new b("Error editing image message.","0500",this.logger)}}async editFileMessage(t,e){var r,i,a,o;if(!((i=(r=n(this,Z).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(a=n(this,Z).permissions)==null?void 0:a.chatPublic)!=null&&o.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!e){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const c=it(),{getLocation:d,putLocation:l}=await c.getPresignedUrls(e.name);await c.uploadFile(e,l),n(this,He).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),es.FILE)}catch(c){throw new b("Error editing file message.","0500",this.logger)}}async editMessage(t,e){switch(e.type){case"text":{this.editTextMessage(t,e.message);break}case"image":{this.editImageMessage(t,e.image);break}case"file":{this.editFileMessage(t,e.file);break}default:{this.logger.error("editMessage::message_type_not_supported",{chat:{messageType:e.type}});break}}}async deleteMessage(t){n(this,He).deleteMessage(t)}getMessagesByUser(t){return this.messages.filter(e=>e.userId===t)}getMessagesByType(t){return this.messages.filter(e=>e.type===t)}async pin(t){if(!n(this,Po,Eu))throw new b("Can`t pin message without joining room","0505");try{await n(this,He).setPinState(t,!0)}catch(e){throw new b(`No message found with id: ${t}`,"0504")}}async unpin(t){if(!n(this,Po,Eu))throw new b("Can`t unpin message without joining room","0505");try{await n(this,He).setPinState(t,!1)}catch(e){throw new b(`No message found with id: ${t}`,"0504")}}async fetchPublicMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await n(this,He).getChatMessagesPaginated(t,e,r==="before")).messages.map(o=>ts.formatSocketPeerMessage(o))}async fetchPrivateMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after",userId:i}){return(await n(this,He).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"userId",userId:i})).messages.map(c=>ts.formatSocketPeerMessage(c))}async fetchPinnedMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await n(this,He).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"pinned",pinned:!0})).messages.map(o=>ts.formatSocketPeerMessage(o))}async getMessages(t,e,r,i=0){const a=await n(this,He).getChatMessagesPaginated(t,e,r);return{messages:a.messages.map(o=>ts.formatSocketPeerMessage(o)),next:a.next}}async searchMessages(t,e){throw new b("searchMessages is disabled! Please use `fetchPublicMessages` method instead.","0506")}get pinned(){return this.messages.filter(t=>t.pinned)}},Z=new WeakMap,li=new WeakMap,He=new WeakMap,In=new WeakMap,wd=new WeakSet,df=function(){return n(this,In).getValue("connectionHandler")},Po=new WeakSet,Eu=function(){return n(this,wd,df).socketJoined===!0},cg);Cs([y.trace("Chat.sendTextMessage"),_t(Zc)],Lt.prototype,"sendTextMessage",1);Cs([y.trace("Chat.sendImageMessage"),_t({maxInvocations:20,period:60})],Lt.prototype,"sendImageMessage",1);Cs([y.trace("Chat.sendFileMessage"),_t({maxInvocations:20,period:60})],Lt.prototype,"sendFileMessage",1);Cs([y.trace("Chat.sendMessage"),_t({maxInvocations:180,period:60})],Lt.prototype,"sendMessage",1);Cs([y.trace("Chat.editTextMessage")],Lt.prototype,"editTextMessage",1);Cs([y.trace("Chat.editImageMessage")],Lt.prototype,"editImageMessage",1);Cs([y.trace("Chat.editFileMessage")],Lt.prototype,"editFileMessage",1);Cs([y.trace("Chat.editMessage")],Lt.prototype,"editMessage",1);Cs([y.trace("Chat.deleteMessage")],Lt.prototype,"deleteMessage",1);Cs([y.trace("Chat.searchMessages")],Lt.prototype,"searchMessages",1);Lt=Cs([at("0500")],Lt);var CM=Object.defineProperty,wM=Object.getOwnPropertyDescriptor,RM=(s,t,e,r)=>{for(var i=r>1?void 0:r?wM(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&CM(t,e,i),i},ui,dg;const Pr=(dg=class{constructor(s,t,e,r){u(this,"chat");u(this,"chatSocketHandler");u(this,"self");g(this,ui,void 0);m(this,ui,s),this.chatSocketHandler=t,this.chat=new Lt(s,t,e,r),this.self=e,this.setupEvents()}get telemetry(){return n(this,ui).getValue("telemetry")}get logger(){return n(this,ui).getValue("logger")}static async init(s,t,e,r){return new Pr(s,t,e,r)}static formatMessage(s){return{...s,time:new Date(s.time),type:_M[s.type]}}static formatSocketPeerMessage(s){const t=s.createdAt*1e3,e={displayName:s.displayName,id:s.chatId,time:t,timeMs:s.createdAtMs,type:s.payloadType,isEdited:s.isEdited,userId:s.userId,targetUserIds:s.targetUserIds,message:"",link:"",name:"",html:"",images:[],videos:[],files:[],size:0,pinned:s.pinned};switch(e.type){case es.TEXT:{e.message=s.payload;break}case es.IMAGE:{e.link=s.payload;break}case es.FILE:{const{link:r,name:i,size:a}=JSON.parse(s.payload);e.link=r,e.name=i,e.size=a;break}case es.CUSTOM:{const{html:r,images:i,message:a,videos:o,files:c}=JSON.parse(s.payload);e.message=a,e.html=r,e.images=i,e.videos=o,e.files=c;break}}return Pr.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=rf.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>Pr.formatSocketPeerMessage(e))}setupEvents(){n(this,ui).getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(Le.sendMessageToRoom,s=>{if(!s.message)return;const t=Pr.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(Le.sendMessageToPeers,s=>{const t=Pr.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(Le.editMessage,s=>{if(!s.message)return;const t=Pr.formatSocketPeerMessage(s.message),e=this.chat.messages.findIndex(r=>r.id===t.id);e!==-1&&(this.chat.messages[e]=t),this.chat.emit("chatUpdate",{action:"edit",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Le.deleteMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId);let e={id:s.chatId};t!==-1&&([e]=this.chat.messages.splice(t,1)),this.chat.emit("chatUpdate",{action:"delete",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(Le.pinMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId),e=Pr.formatSocketPeerMessage(s.message);t!==-1&&(this.chat.messages[t]=e),this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages}),s.pinned?this.chat.emit("pinMessage",{message:e,messages:this.chat.messages}):this.chat.emit("unpinMessage",{message:e,messages:this.chat.messages})})}},ui=new WeakMap,dg);let ts=Pr;RM([y.trace("ChatController.setupEvents")],ts.prototype,"setupEvents",1);var bM=Object.defineProperty,kM=Object.getOwnPropertyDescriptor,IM=(s,t,e,r)=>{for(var i=r>1?void 0:r?kM(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&bM(t,e,i),i},Rd,lf,bd,uf,An,Mn,_o,lg;let Pu=(lg=class extends Ut{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,Rd);g(this,bd);u(this,"items");g(this,An,void 0);g(this,Mn,void 0);g(this,_o,void 0);m(this,_o,t),m(this,An,e),m(this,Mn,r),this.items=[]}async create(t,e,r=!1,i=!1){if(!n(this,bd,uf))throw new b("Can't create polls without joining room","0705");if(!n(this,An).permissions.polls.canCreate){this.logger.error("Polls::create::permission_denied");return}if(!t||!e){this.logger.error("Polls::question_and_options_can_not_be_empty",{polls:{hasQuestion:!!t,optionsLength:e==null?void 0:e.length}});return}if(e.length<2){this.logger.error("Polls::there_must_be_at_least_two_options",{polls:{hasQuestion:!!t,optionsLength:e.length}});return}await n(this,Mn).createPoll(t,e,r,i)}async vote(t,e){if(!n(this,An).permissions.polls.canVote){this.logger.error("Polls::vote::permission_denied");return}await n(this,Mn).votePoll(t,e)}},Rd=new WeakSet,lf=function(){return n(this,_o).getValue("connectionHandler")},bd=new WeakSet,uf=function(){var t;return((t=n(this,Rd,lf))==null?void 0:t.socketJoined)===!0},An=new WeakMap,Mn=new WeakMap,_o=new WeakMap,lg);Pu=IM([at("0700")],Pu);var AM=Object.defineProperty,MM=Object.getOwnPropertyDescriptor,DM=(s,t,e,r)=>{for(var i=r>1?void 0:r?MM(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&AM(t,e,i),i},br,Dn,hi,ug;const ln=(ug=class{constructor(s,t,e){u(this,"polls");g(this,br,void 0);g(this,Dn,void 0);g(this,hi,void 0);this.polls=new Pu(s,t,e),m(this,Dn,t),m(this,br,s),m(this,hi,e),this.setupEvents()}get telemetry(){return n(this,br).getValue("telemetry")}get logger(){return n(this,br).getValue("logger")}static async init(s,t,e){return new ln(s,t,e)}canViewPolls(){return n(this,Dn).permissions.polls.canView}setupEvents(){const s={[$s.createPoll]:r=>{r.poll&&this.updatePoll(ln.formatSocketServicePoll(r.poll))},[$s.updatePoll]:r=>{r.poll&&this.updatePoll(ln.formatSocketServicePoll(r.poll))},[$s.votePoll]:r=>{r.poll&&this.updatePoll(ln.formatSocketServicePoll(r.poll))}},t=()=>{n(this,br).getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{n(this,hi).on(r,s[r])})},e=()=>{n(this,br).getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{n(this,hi).removeListeners(r)})};n(this,Dn).permissions.on("permissionsUpdate",async r=>{var i;r!=null&&r.polls&&((i=r==null?void 0:r.polls)!=null&&i.canView?(await this.getPolls(),t()):(this.polls.items=[],e()))}),this.canViewPolls()&&t()}updatePoll(s){if(!this.canViewPolls())return;const t=this.polls.items.findIndex(e=>e.id===s.id);if(t>-1){const e=JSON.stringify(this.polls.items[t]);this.polls.items[t]=s,e!==JSON.stringify(s)&&this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!1});return}this.polls.items=[...this.polls.items,s],this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!0})}async getPolls(){const s=await n(this,hi).getPolls();if(!(s!=null&&s.payload))return;const{polls:t}=KA.fromBinary(s.payload);this.polls.items=t.map(e=>ln.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}}},br=new WeakMap,Dn=new WeakMap,hi=new WeakMap,ug);let hf=ln;DM([y.trace("PollController.setupEvents")],hf.prototype,"setupEvents",1);var OM=Object.defineProperty,NM=Object.getOwnPropertyDescriptor,VM=(s,t,e,r)=>{for(var i=r>1?void 0:r?NM(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&OM(t,e,i),i},pf=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))(pf||{}),On,Co,Cu,pi,wo,hg;let _u=(hg=class extends Ut{constructor(t,e,r,i,a){const o=t.getValue("logger");super(o);g(this,Co);u(this,"selfActiveTab");u(this,"broadcastTabChanges");g(this,On,void 0);g(this,pi,void 0);g(this,wo,void 0);u(this,"viewType");u(this,"meetingStartedTimestamp");u(this,"meetingTitle");u(this,"sessionId");m(this,On,t),m(this,pi,e),this.viewType=r,m(this,wo,i),this.meetingTitle=a,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return n(this,Co,Cu).socketState}get mediaState(){return n(this,Co,Cu).mediaState}get meetingId(){return n(this,On).getValue("meetingId")}setBroadcastTabChanges(t){if(!n(this,pi).permissions.canSpotlight)throw this.logger.error("Spotlight::setSpotlighted::permission_denied"),new b("User does not have permission to toggle spotlight","0801");this.broadcastTabChanges=t,this.emit("broadcastTabChangesUpdate",this.broadcastTabChanges),this.broadcastTabChanges&&this.assertActiveTabToRoom()}setSelfActiveTab(t,e){var r;this.logger.info("Spotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(r=n(this,pi).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){n(this,wo).broadcastMessage("spotlight",{userId:n(this,pi).userId,currentTab:this.selfActiveTab})}},On=new WeakMap,Co=new WeakSet,Cu=function(){return n(this,On).getValue("connectionHandler")},pi=new WeakMap,wo=new WeakMap,hg);_u=VM([at("0800")],_u);function LM(s){let t="",e=[""];const r=[e];let i=0,a=0,o=!0,c;for(c of s)c==='"'?(o&&c===t&&(e[i]+=c),o=!o):c===","&&o?c=e[++i]="":c===`
|
|
6
6
|
`&&o?(t==="\r"&&(e[i]=e[i].slice(0,-1)),e=r[++a]=[c=""],i=0):e[i]+=c,t=c;return r}var xM=Object.defineProperty,UM=Object.getOwnPropertyDescriptor,gf=(s,t,e,r)=>{for(var i=r>1?void 0:r?UM(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&xM(t,e,i),i},Ro,pg;let Kr=(pg=class extends Ut{constructor(t){const e=t.getValue("logger");super(e);u(this,"transcripts");g(this,Ro,void 0);m(this,Ro,t),this.transcripts=[]}get telemetry(){return n(this,Ro).getValue("telemetry")}static async init(t,e){const r=new Kr(t),i=t.getValue("logger");try{e&&r.getActiveTranscript()}catch(a){i.error("Error fetching active transcriptions ",a)}return r}static parseTranscript(t,e=!1){if(!t)return;const[[r,i,a,o,c,d]]=LM(t);return{id:ur.v4(),name:c,peerId:i,userId:a,customParticipantId:o,transcript:d,isPartialTranscript:e,date:new Date(parseInt(r,10)*1e3)}}static parseTranscripts(t){return t?t.split(`
|
|
7
7
|
`).map(e=>Kr.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=it(),{transcript:e}=await t.getActiveTranscript();this.transcripts=Kr.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)}},Ro=new WeakMap,pg);gf([y.trace("Ai.getActiveTranscript")],Kr.prototype,"getActiveTranscript",1);Kr=gf([at("0000")],Kr);var $M=Object.defineProperty,FM=Object.getOwnPropertyDescriptor,BM=(s,t,e,r)=>{for(var i=r>1?void 0:r?FM(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&$M(t,e,i),i},kr,Nn,It,gg;const mf=(gg=class{constructor(s,t,e,r,i,a){u(this,"meta");u(this,"ai");g(this,kr,void 0);g(this,Nn,void 0);u(this,"aiSocketHandler");g(this,It,void 0);m(this,It,s),this.meta=new _u(s,t,t.config.viewType,e,a),this.ai=r,m(this,kr,t),m(this,Nn,e),this.aiSocketHandler=i,this.setupEvents()}get telemetry(){return n(this,It).getValue("telemetry")}get logger(){return n(this,It).getValue("logger")}static async init(s,t,e,r,i){const a=await Kr.init(s,t.permissions.transcriptionEnabled);return new mf(s,t,e,a,r,i)}conditionallySetActiveTab(s){var t;s!=null&&s.currentTab&&((t=this.meta.selfActiveTab)==null?void 0:t.id)!==s.currentTab.id&&(this.meta.setSelfActiveTab(s.currentTab,pf.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){n(this,It).getValue("peerSessionStore").on(w.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),n(this,It).getValue("peerSessionStore").on(w.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),n(this,It).getValue("peerSessionStore").on(w.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})}}),n(this,It).getValue("peerSessionStore").on(w.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),n(this,kr).permissions.canSpotlight&&(this.logger.info("MetaController::Asserting Spotlight"),this.meta.selfActiveTab&&n(this,Nn).broadcastMessage("spotlight",{userId:n(this,kr).userId,currentTab:this.meta.selfActiveTab})),n(this,It).getValue("peerSessionStore").on(w.PEER_JOINED_INTERNAL,async s=>{n(this,kr).permissions.canSpotlight&&this.meta.selfActiveTab&&n(this,Nn).broadcastToPeers("spotlight",[s.id],{userId:n(this,kr).userId,currentTab:this.meta.selfActiveTab})}),n(this,It).getValue("peerSessionStore").on(w.ROOM_MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),n(this,It).getValue("peerSessionStore").on(w.MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),this.aiSocketHandler.on(L.transcript,s=>{const{meetingId:t,transcript:e,isPartial:r}=s;let i;try{i=Kr.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:a,name:o,transcript:c}=i;this.logger.debug(`${t} Received transcript for peer ${a} - ${o}: ${c}`)})}},kr=new WeakMap,Nn=new WeakMap,It=new WeakMap,gg);let ff=mf;BM([y.trace("MetaController.setupEvents")],ff.prototype,"setupEvents",1);const Qa={},vr={executeWithLock({methodName:s,lockName:t,timeout:e}){return(r,i,a)=>{const o=a.value;return a.value=function(...d){var E,C;const l=(C=(this==null?void 0:this.peerId)||((E=d[0])==null?void 0:E.authToken))!=null?C:"",h=`${t}-${l}`,p=this==null?void 0:this.logger;if(Qa[h]){const _=new Error(`Unsupported concurrent calls on method: ${s}.`);throw _.name="UnsupportedConcurrentMethodExecution",p==null||p.error("Locker::UnsupportedConcurrentMethodExecution",{error:{stack:_.stack},locker:{methodName:s,lockName:h}}),_}Qa[h]=!0;const f=setTimeout(()=>delete Qa[h],e),T=o.apply(this,d);return Promise.resolve(T).then(()=>{delete Qa[h],clearTimeout(f)}).catch(()=>{delete Qa[h],clearTimeout(f)}),T},a}}};var HM=Object.defineProperty,qM=Object.getOwnPropertyDescriptor,nn=(s,t,e,r)=>{for(var i=r>1?void 0:r?qM(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&HM(t,e,i),i},Gt,kd,te,bo,Rs,qe,ko,wu,Vn,ed;class Xr extends Ut{constructor(e,r,i,a,o){const c=e.getValue("logger");super(c);g(this,ko);g(this,Vn);g(this,Gt,void 0);g(this,kd,void 0);g(this,te,void 0);g(this,bo,void 0);g(this,Rs,void 0);g(this,qe,void 0);m(this,qe,e),m(this,Gt,a),m(this,kd,o),m(this,te,r),m(this,bo,i),m(this,Rs,[]),this.setupEvents()}get telemetry(){return n(this,qe).getValue("telemetry")}get status(){return n(this,qe).getValue("stageStatus")}setupEvents(){const e={[w.GET_STAGE_REQUESTS]:async a=>{m(this,Rs,a)},[w.UPDATE_STAGE_REQUESTS]:async({add:a})=>{const o=n(this,Rs).length,{stageRequests:c}=this.getAccessRequests();(a||c.length>o)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)}},r=()=>{Object.entries(e).forEach(([a,o])=>{n(this,qe).getValue("peerSessionStore").onAsync(a,o)})},i=()=>{Object.entries(e).forEach(([a,o])=>{n(this,qe).getValue("peerSessionStore").removeListener(a,o)})};n(this,te).permissions.on("permissionsUpdate",a=>{const{canAcceptProductionRequests:o}=a;o!==void 0&&(n(this,te).permissions.acceptStageRequests?(r(),n(this,Gt).getStageRequests()):(i(),m(this,Rs,[]),this.emit("stageAccessRequestUpdate",n(this,Rs))))}),n(this,te).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!n(this,te).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new b("Stage is disabled","2003");if(!n(this,te).permissions.acceptStageRequests)throw this.logger.error("Stage::get_access_request::permission_denied"),new b("You do not have permission to perform this action","2001");const e=n(this,bo).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return m(this,Rs,e),{stageRequests:n(this,Rs)}}async requestAccess(){if(!n(this,te).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new b("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new b(`Unable to request access you are currently ${this.status}`,"2006");if(n(this,te).permissions.stageAccess===F.Allowed){V(this,Vn,ed).call(this,"ACCEPTED_TO_JOIN_STAGE");return}n(this,Gt).requestAccess(),V(this,Vn,ed).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!n(this,te).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new b("Stage is disabled","2003");n(this,Gt).cancelRequestAccess(),V(this,Vn,ed).call(this,"OFF_STAGE")}grantAccess(e){if(!n(this,te).roomJoined)throw new b("Can`t grant for participant without joining room");if(!n(this,te).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new b("Stage is disabled","2003");if(!n(this,te).permissions.acceptStageRequests)throw this.logger.error("Stage::grant_access::permission_denied"),new b("You do not have permission to perform this action","2001");return n(this,Gt).grantAccess(e)}denyAccess(e){if(!n(this,te).roomJoined)throw new b("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!n(this,te).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new b("Stage is disabled","2003");if(!n(this,te).permissions.acceptStageRequests)throw this.logger.error("Stage::deny_access::permission_denied"),new b("You do not have permission to perform this action","2001");return n(this,Gt).denyAccess(e)}get peerId(){return n(this,qe).getValue("peerId")}async join(){const e=n(this,qe).getValue("viewType");if(this.status==="ON_STAGE")throw new b("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||n(this,te).permissions.stageAccess===F.NotAllowed)throw new b(`Unable to join stage you are currently ${this.status}`,"2006");if(n(this,qe).setValue("stageStatus","ON_STAGE",!1),await n(this,Gt).joinStage(),e===lr.Livestream){await n(this,qe).getValue("selfController").joinRoom();return}n(this,qe).notify("stageStatus"),n(this,te).audioEnabled&&n(this,ko,wu).shareMic(n(this,te).audioTrack),n(this,te).videoEnabled&&n(this,ko,wu).shareWebcam(n(this,te).videoTrack)}async leave(){if(!n(this,te).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new b("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new b(`Unable to leave stage you are currently ${this.status}`,"2006");n(this,te).setIsPinned(!1),n(this,qe).setValue("stageStatus","OFF_STAGE",!1),await n(this,Gt).leaveStage(n(this,te).userId);try{await n(this,qe).getValue("peerSessionStore").emitAsync(w.LEAVE_MEDIA_ROOM,"stageLeft")}catch(e){this.logger.error("Stage::leave::emitAsync::failed",{error:e})}n(this,qe).notify("stageStatus")}async kick(e){if(!n(this,te).roomJoined)throw new b("Can`t kick participant without joining room","2005");if(!n(this,te).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new b("Stage is disabled","2003");if(!n(this,te).permissions.acceptStageRequests)throw this.logger.error("Stage::kick::permission_denied"),new b("You do not have permissions for kick","2001");return n(this,Gt).kick(e)}}Gt=new WeakMap,kd=new WeakMap,te=new WeakMap,bo=new WeakMap,Rs=new WeakMap,qe=new WeakMap,ko=new WeakSet,wu=function(){return n(this,qe).getValue("roomNodeClient")},Vn=new WeakSet,ed=async function(e){this.status!==e&&n(this,qe).setValue("stageStatus",e)};nn([y.trace("Stage.getStageRequests")],Xr.prototype,"getAccessRequests",1);nn([y.trace("Stage.requestAccess")],Xr.prototype,"requestAccess",1);nn([y.trace("Stage.cancelRequestAccess")],Xr.prototype,"cancelRequestAccess",1);nn([y.trace("Stage.grantAccess")],Xr.prototype,"grantAccess",1);nn([y.trace("Stage.denyAccess")],Xr.prototype,"denyAccess",1);nn([vr.executeWithLock({methodName:"joinStage",lockName:"Stage.join",timeout:5e3}),y.trace("Stage.joinStage")],Xr.prototype,"join",1);nn([y.trace("Stage.leaveStage")],Xr.prototype,"leave",1);function jM(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function vh(s){switch(s){case ar.UNSPECIFIED:return"OFF_STAGE";case ar.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case ar.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case ar.OFF_STAGE:return"OFF_STAGE";case ar.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var GM=Object.defineProperty,WM=Object.getOwnPropertyDescriptor,JM=(s,t,e,r)=>{for(var i=r>1?void 0:r?WM(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&GM(t,e,i),i},Ir,ds,Ar,Io,dt;class Tf{constructor(t,e,r,i,a){u(this,"stage");g(this,Ir,void 0);g(this,ds,void 0);g(this,Ar,void 0);g(this,Io,0);g(this,dt,void 0);m(this,dt,t),this.stage=new Xr(t,i,a,e,r),m(this,Ar,e),m(this,Ir,i),m(this,ds,a),this.setupEvents()}get telemetry(){return n(this,dt).getValue("telemetry")}get logger(){return n(this,dt).getValue("logger")}setupEvents(){n(this,dt).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),n(this,Ar).on(L.grantStageAccess,()=>{n(this,Ir).permissions.stageAccess!==F.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),n(this,Ar).on(L.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===n(this,Ir).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),n(this,Ar).on(L.denyStageAccess,()=>{n(this,Ir).permissions.stageAccess!==F.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),n(this,Ar).on(L.getStageRequests,async t=>{var r;if(n(this,Ir).permissions.stageAccess!==F.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await n(this,dt).getValue("peerSessionStore").emitAsync(w.GET_STAGE_REQUESTS,e),n(this,Io)<e.length&&e.length>0&&this.stage.emit("newStageRequest",{count:e.length}),m(this,Io,e.length),this.stage.emit("stageAccessRequestUpdate",e)})}getCurrentStageRequests(){return n(this,ds).joined.toArray().filter(e=>e.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(e=>({displayName:e.name,userId:e.userId,peerId:e.id}))}async setStageStatus(t){this.stage.status!==t&&n(this,dt).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=vh(t.stageType),r=n(this,dt).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:n(this,dt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(r);break;case 0:case 4:default:n(this,dt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}async peerStageStatusHandler(t){const e=n(this,ds).joined.get(t.peerId),r=n(this,ds).viewMode==="ACTIVE_GRID";if(!e){this.logger.warn("err::peerStageStatusUpdate: participant not found");return}switch(t.stageType){case 1:e.setStageStatus("ON_STAGE"),r&&n(this,dt).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:n(this,ds).viewMode,page:n(this,ds).currentPage});break;case 2:e.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:e.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:e.setStageStatus("OFF_STAGE"),r&&n(this,dt).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:n(this,ds).viewMode,page:n(this,ds).currentPage});break}n(this,dt).getValue("peerSessionStore").emit(w.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}Ir=new WeakMap,ds=new WeakMap,Ar=new WeakMap,Io=new WeakMap,dt=new WeakMap;JM([y.trace("Stage.setupEvents")],Tf.prototype,"setupEvents",1);var KM=Object.defineProperty,zM=Object.getOwnPropertyDescriptor,Al=(s,t,e,r)=>{for(var i=r>1?void 0:r?zM(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&KM(t,e,i),i};const we={getPeer:14,getPeers:15,chatMessage:16,getRoomName:17,getDisplayTitle:18,getPluginInitiator:19,customPluginEventToParent:20,peerJoined:22,peerLeft:23,sendData:24,stageStatusUpdate:25,peerStageStatusUpdate:26};var Ze,At,Ln,xn,js,Un,Mr,$n,mg;let ka=(mg=class extends Ia{constructor(t,{baseURL:e,createdAt:r,description:i,id:a,name:o,organizationId:c,picture:d,private:l,published:h,staggered:p,tags:f,type:T,updatedAt:E},C,_,I,M,x){const N=t.getValue("logger");super(N);g(this,Ze,void 0);u(this,"baseURL");u(this,"createdAt");u(this,"description");u(this,"id");u(this,"name");g(this,At,void 0);g(this,Ln,void 0);g(this,xn,void 0);u(this,"organizationId");u(this,"picture");u(this,"private");u(this,"published");u(this,"staggered");u(this,"tags");u(this,"type");u(this,"updatedAt");g(this,js,void 0);u(this,"config");g(this,Un,void 0);u(this,"active");u(this,"iframes");u(this,"enabledBy");g(this,Mr,void 0);g(this,$n,void 0);m(this,Mr,t),this.baseURL=e,this.createdAt=new Date(r),this.description=i,this.id=a,this.name=o,m(this,At,_),this.organizationId=c,this.picture=d,this.private=l,this.published=h,this.staggered=p,this.tags=f,this.type=T,this.updatedAt=new Date(E),this.active=!1,this.iframes=new Map,m(this,Ze,C),m(this,Ln,I),m(this,xn,M),this.enabledBy="",m(this,$n,x)}get telemetry(){return n(this,Mr).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:a}=e;switch(a){case j.customPluginEventToRoom:{n(this,Ze).customPluginEventToRoom(this.id,r,i);break}case j.customPluginEventToPeers:{n(this,Ze).customPluginEventToPeers(this.id,r.peerIds,r,i);break}case j.enablePluginForRoom:{n(this,Ze).enablePluginForRoom(this.id,i);break}case j.enablePluginForPeers:{n(this,Ze).enablePluginForPeers(this.id,r.peerIds,i);break}case j.disablePluginForRoom:{n(this,Ze).disablePluginForRoom(this.id,i);break}case j.disablePluginForPeers:{n(this,Ze).disablePluginForPeers(this.id,r.peerIds,i);break}case j.storeInsertKeys:{n(this,Ze).storeInsertKeys(this.id,r.store,r.insertKeys,i);break}case j.storeGetKeys:{n(this,Ze).storeGetKeys(this.id,r.store,r.getKeys,i);break}case j.storeDeleteKeys:{n(this,Ze).storeDeleteKeys(this.id,r.store,r.deleteKeys,i);break}case j.storeDelete:{n(this,Ze).storeDelete(this.id,r.store,i);break}case we.chatMessage:{const{messagePayload:c,peerIds:d}=r;if(!n(this,xn)){this.sendIframeEvent({type:we.chatMessage,uuid:e.uuid,payload:{error:"Chat is disabled for this room."}});return}try{await n(this,xn).sendMessage(c,d),this.sendIframeEvent({type:we.chatMessage,uuid:e.uuid,payload:{success:!0}})}catch(l){this.sendIframeEvent({type:we.chatMessage,uuid:e.uuid,payload:{error:l}})}break}case we.getPeer:{let c;const{peerId:d}=r,l={...n(this,At),id:n(this,At).id,isRecorder:(o=n(this,At).permissions)==null?void 0:o.isRecorder,isHidden:n(this,At).permissions.hiddenParticipant,stageStatus:n(this,At).stageStatus};d?(c=n(this,Ln).joined.get(r.peerId),n(this,At).id===d&&(c=l)):c=l,this.sendIframeEvent({type:we.getPeer,payload:{peer:c&&md(c)},uuid:e.uuid});break}case we.getPeers:{const c=n(this,Ln).joined.toArray().map(d=>md(d));this.sendIframeEvent({type:we.getPeers,payload:{peers:c},uuid:e.uuid});break}case we.getPluginInitiator:{this.sendIframeEvent({type:we.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:e.uuid});break}case we.getDisplayTitle:{this.sendIframeEvent({type:we.getDisplayTitle,payload:{displayTitle:n(this,$n)},uuid:e.uuid});break}case we.getRoomName:{this.sendIframeEvent({type:we.getRoomName,payload:{roomName:n(this,Mr).getValue("meetingId")},uuid:e.uuid});break}case we.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:we.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(!n(this,Un))throw this.logger.error("Plugin::addPluginView::no_auth_token_set_for_plugin"),new b("No auth token set for plugin.","0602");if(!t)throw this.logger.error("Plugin::addPluginView::iframe_was_not_provided"),new b("Iframe was not provided.","0603");this.removePluginView(e);const r=t,i=new URL(this.baseURL),a={auth:n(this,Un),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:n(this,Mr).getValue("apiBase"),pluginId:this.id,roomName:(o=n(this,Mr).getValue("meetingId"))!=null?o:"",displayTitle:n(this,$n)};if(Object.keys(a).forEach(c=>{i.searchParams.set(c,a[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=it(),e=await t.authorizePlugin(this.id);m(this,Un,e),m(this,js,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)}),m(this,js,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=n(this,At).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(n(this,Ze).addPlugin(this.id,this.staggered),m(this,js,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=n(this,At).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==n(this,At).id||(n(this,Ze).removePlugin(this.id),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:n(this,js)?new Date().getTime()-n(this,js).getTime():0}}),m(this,js,void 0)))}},Ze=new WeakMap,At=new WeakMap,Ln=new WeakMap,xn=new WeakMap,js=new WeakMap,Un=new WeakMap,Mr=new WeakMap,$n=new WeakMap,mg);Al([_t({maxInvocations:5,period:1})],ka.prototype,"sendData",1);Al([y.trace("Plugin.activatePlugin")],ka.prototype,"activate",1);Al([y.trace("Plugin.deactivatePlugin")],ka.prototype,"deactivate",1);ka=Al([at("0600")],ka);var Ae,gi;class vf extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:a,onClearEvent:o}=e;super();g(this,Ae,void 0);g(this,gi,void 0);u(this,"onAddEvent");u(this,"onDeleteEvent");u(this,"onClearEvent");m(this,Ae,new Ia(r)),this.onAddEvent=i,this.onDeleteEvent=a,this.onClearEvent=o,m(this,gi,new Map)}emit(e,...r){return n(this,Ae).emit(e,...r)}on(e,r){return n(this,Ae).on(e,r)}addListener(e,r){return n(this,Ae).addListener(e,r)}off(e,r){return n(this,Ae).off(e,r)}once(e,r){return n(this,Ae).once(e,r)}prependListener(e,r){return n(this,Ae).prependListener(e,r)}prependOnceListener(e,r){return n(this,Ae).prependOnceListener(e,r)}removeListener(e,r){return n(this,Ae).removeListener(e,r)}removeAllListeners(e){return n(this,Ae).removeAllListeners(e)}listeners(e){return n(this,Ae).listeners(e)}listenerCount(e){return n(this,Ae).listenerCount(e)}getMaxListeners(){return n(this,Ae).getMaxListeners()}setMaxListeners(e){return n(this,Ae).setMaxListeners(e)}eventNames(){return n(this,Ae).eventNames()}add(e,r=!0){return this.set(e.id,e,r)}set(e,r,i=!0){const a=super.set(e,r),o=(c,...d)=>{this.emit(c,r,...d)};return n(this,gi).set(e,o),r.on("*",o),i&&n(this,Ae).emit(this.onAddEvent,r),a}delete(e,r=!0,i=!1){const a=this.get(e);if(!a)return!1;a.removeListener("*",n(this,gi).get(e));const o=super.delete(e);return i&&a.removeAllListeners(),r&&n(this,Ae).emit(this.onDeleteEvent,a),o}clear(e=!0,r=!1){this.forEach(a=>{a.removeListener("*",n(this,gi).get(a.id)),r&&a.removeAllListeners()});const i=super.clear();return e&&n(this,Ae).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}Ae=new WeakMap,gi=new WeakMap;class Wp extends vf{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 YM=Object.defineProperty,QM=Object.getOwnPropertyDescriptor,XM=(s,t,e,r)=>{for(var i=r>1?void 0:r?QM(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&YM(t,e,i),i};let Ru=class{constructor(s){u(this,"all");u(this,"active");this.all=new Wp(s),this.active=new Wp(s)}};Ru=XM([at("0600")],Ru);var ZM=Object.defineProperty,e0=Object.getOwnPropertyDescriptor,Ml=(s,t,e,r)=>{for(var i=r>1?void 0:r?e0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ZM(t,e,i),i},Wt,Fn,ls,fg;const Sf=(fg=class{constructor(s,t,e,r){u(this,"plugins");g(this,Wt,void 0);g(this,Fn,void 0);g(this,ls,void 0);m(this,Wt,t),m(this,Fn,e),m(this,ls,s),this.plugins=r,this.setupEvents()}get telemetry(){return n(this,ls).getValue("telemetry")}get logger(){return n(this,ls).getValue("logger")}static async init(s,t,e,r,i,a,o,c){const d=s.getValue("logger"),l=new Ru(d);return t.forEach(h=>{const p=new ka(s,h,e,a,o,i,c);l.all.add(p)}),new Sf(s,e,r,l)}async getRoomPlugins(){var t;const{plugins:s}=await n(this,Wt).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)}),n(this,ls).getValue("peerSessionStore").onAsync(w.SOCKET_SERVICE_ROOM_JOINED,async()=>{await this.getRoomPlugins(),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")}),n(this,Wt).on(j.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})}),n(this,Wt).on(j.removePlugin,async s=>{var e;const t=s.pluginId;(e=this.plugins.all.get(t))!=null&&e.active&&await this.disablePlugin({id:t})}),[j.enablePluginForPeers,j.enablePluginForRoom].forEach(s=>{n(this,Wt).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{enabledBy:t.enabledBy})})}),[j.disablePluginForPeers,j.disablePluginForRoom].forEach(s=>{n(this,Wt).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{disabledBy:t.disabledBy})})}),[j.customPluginEventToPeers,j.customPluginEventToRoom].forEach(s=>{n(this,Wt).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{data:JSON.parse(new TextDecoder().decode(t.pluginData))})})}),[j.storeInsertKeys,j.storeGetKeys,j.storeDeleteKeys].forEach(s=>{n(this,Wt).on(s,async(t,e)=>{var i;const r=(i=t.storeItems)==null?void 0:i.map(a=>{var o;return{timestamp:a.timestamp,peerId:a.peerId,payload:JSON.parse((o=a.payload)!=null&&o.length?new TextDecoder().decode(a.payload):"{}"),key:a.storeKey}});this.sendIframeEvent(s,t.pluginId,e,{storeName:t.storeName,storeItems:r})})}),n(this,Wt).on(j.storeDelete,async(s,t)=>{this.sendIframeEvent(j.storeDelete,s.pluginId,t,{storeName:s.storeName})}),n(this,Fn).on(Le.sendMessageToPeers,s=>{const t=ts==null?void 0:ts.formatSocketPeerMessage(s.message);this.broadcastIframeEvent(we.chatMessage,{message:t})}),n(this,Fn).on(Le.sendMessageToRoom,s=>{const t=ts==null?void 0:ts.formatSocketPeerMessage(s.message);this.broadcastIframeEvent(we.chatMessage,{message:t})}),n(this,ls).getValue("peerSessionStore").on(w.PEER_JOINED_INTERNAL,s=>{const t=md(s);this.broadcastIframeEvent(we.peerJoined,t)}),n(this,ls).getValue("peerSessionStore").on(w.PEER_CLOSED,s=>{this.broadcastIframeEvent(we.peerLeft,s)}),n(this,ls).getValue("peerSessionStore").on(w.UPDATE_PEER_STAGE_STATUS,s=>{this.broadcastIframeEvent(we.peerStageStatusUpdate,s)}),n(this,ls).subscribe("stageStatus",s=>{this.broadcastIframeEvent(we.stageStatusUpdate,s)})}},Wt=new WeakMap,Fn=new WeakMap,ls=new WeakMap,fg);let Mc=Sf;Ml([y.trace("PluginController.getRoomPlugins")],Mc.prototype,"getRoomPlugins",1);Ml([y.trace("PluginController.enableForSelf")],Mc.prototype,"enablePlugin",1);Ml([y.trace("PluginController.disableForSelf")],Mc.prototype,"disablePlugin",1);Ml([y.trace("PluginController.setupEvents")],Mc.prototype,"setupEvents",1);var Ao;class t0{constructor(t){u(this,"mediaJoined");u(this,"socketJoined");u(this,"socketJoinAttempted");u(this,"mediaJoinAttempted");u(this,"socketState");u(this,"mediaState");g(this,Ao,void 0);this.mediaJoined=!1,this.socketJoined=!1,this.socketJoinAttempted=!1,this.mediaJoinAttempted=!1,this.socketState={state:void 0,reconnected:!1,reconnectionAttempt:void 0},this.mediaState={recv:void 0,send:void 0},m(this,Ao,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&&(n(this,Ao).getValue("peerSessionStore").emit(w.SOCKET_STATE_UPDATE,r),this.socketState=r)}}Ao=new WeakMap;var s0=Object.defineProperty,r0=Object.getOwnPropertyDescriptor,Dc=(s,t,e,r)=>{for(var i=r>1?void 0:r?r0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&s0(t,e,i),i},Bn,Hn,qn,td,Tg;let en=(Tg=class extends Ut{constructor(t,e){const r=t.getValue("logger");super(r);g(this,qn);g(this,Bn,void 0);g(this,Hn,void 0);u(this,"recordingPeerIds",[]);u(this,"recordings",[]);m(this,Hn,t),m(this,Bn,e)}get recordingState(){return this.recordings.some(t=>t.state==="RECORDING")?"RECORDING":this.recordings.some(t=>t.state==="PAUSED")?"PAUSED":this.recordings.some(t=>t.state==="STARTING")?"STARTING":this.recordings.some(t=>t.state==="STOPPING")?"STOPPING":"IDLE"}get telemetry(){return n(this,Hn).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!n(this,Bn).permissions.canRecord)throw this.logger.error("Recording::start::permission_denied"),new b("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 b(`Cant start recording, recordingState irregular: ${this.recordingState}`,"1005");try{const e=it(),{recording:r={}}=n(this,Hn).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 b("Error while starting recording","1000",this.logger)}}async stop(t){await V(this,qn,td).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await V(this,qn,td).call(this,"pause",["RECORDING"],t)}async resume(t){await V(this,qn,td).call(this,"resume",["PAUSED"],t)}},Bn=new WeakMap,Hn=new WeakMap,qn=new WeakSet,td=async function(t,e,r){if(!n(this,Bn).permissions.canRecord)throw this.logger.error("Recording::stop::permission_denied"),new b("User does not have permission to stop recording","1001");let i=[];if(r!==void 0){const a=this.recordings.find(o=>o.id===r);if(a===void 0)throw new b("Could not find the specified recording","1004");if(e.includes(a.state)){this.logger.error("Recording::stop::recording_not_in_expected_state",{recording:{state:a.state}});return}i.push(a)}else i=this.recordings.filter(a=>e.includes(a.state));i.forEach(async a=>{const o=a.state;t==="stop"&&(a.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{await it().updateRecording(a.id,t)}catch(c){throw this.logger.error("Recording::stop::recording_failed_to_stop",{error:c}),a.state!==o&&(a.state=o,this.emit("recordingUpdate",o)),new b("Error while stopping recording","1000",this.logger)}})},Tg);Dc([y.trace("Recording.start")],en.prototype,"start",1);Dc([y.trace("Recording.stop")],en.prototype,"stop",1);Dc([y.trace("Recording.stop")],en.prototype,"pause",1);Dc([y.trace("Recording.stop")],en.prototype,"resume",1);en=Dc([at("1000")],en);var i0=Object.defineProperty,n0=Object.getOwnPropertyDescriptor,a0=(s,t,e,r)=>{for(var i=r>1?void 0:r?n0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&i0(t,e,i),i},mi;class yf{constructor(t,e,r){u(this,"recording");u(this,"room");g(this,mi,void 0);m(this,mi,t),this.recording=new en(t,e),this.room=r,this.setupEvents()}get telemetry(){return n(this,mi).getValue("telemetry")}get logger(){return n(this,mi).getValue("logger")}getRecordingTypeFromProtoType(t){let e;switch(t){case Qi.BROWSER:e="BROWSER";break;case Qi.COMPOSITE:e="COMPOSITE";break;case Qi.TRACK:e="TRACK";break;default:e="BROWSER"}return e}setupEvents(){n(this,mi).getValue("peerSessionStore").on(w.ROOM_STATE,t=>{t.activeRecordings.length!==0?this.recording.updateRecordings(t.activeRecordings.map(e=>{const r=this.getRecordingTypeFromProtoType(e.recordingType);return{id:e.recordingId,state:e.recordingStatus,type:r}})):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on(L.recordingStarted,t=>{let e=!1;const r=[...this.recording.recordings];if(r.forEach(i=>{i.id===t.recordingId&&(e=!0,i.state="RECORDING")}),e===!1){const i=this.getRecordingTypeFromProtoType(t.recordingType);r.push({id:t.recordingId,state:"RECORDING",type:i})}this.recording.updateRecordings(r)}),this.room.on(L.recordingPaused,t=>{const e=[...this.recording.recordings];e.forEach(r=>{r.id===t.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(e)}),this.room.on(L.recordingStopped,t=>{const e=[...this.recording.recordings.filter(r=>r.id!==t.recordingId)];this.recording.updateRecordings(e)})}}mi=new WeakMap;a0([y.trace("RecordingController.setupEvents")],yf.prototype,"setupEvents",1);var fi;class o0{constructor(t){g(this,fi,void 0);m(this,fi,t)}hasFeature(t){var e;return(e=n(this,fi).getValue("flagsmith").hasFeature(t))!=null?e:!1}getFeatureValue(t){return n(this,fi).getValue("flagsmith").getValue(t)}getAllFeatures(){return n(this,fi).getValue("flagsmith").getAllFlags()}}fi=new WeakMap;class Sh{constructor(t,e,r){u(this,"logger");u(this,"features");u(this,"browserSpecs");u(this,"callStats");this.logger=t,this.features=e,this.browserSpecs=fe,this.callStats=r}static init(t){return new Sh(t.getValue("logger"),new o0(t),t.getValue("callstats"))}}class yh{constructor(t){u(this,"internals");this.internals=t}static async init(t){const e=Sh.init(t);return new yh(e)}}var c0=Object.defineProperty,d0=Object.getOwnPropertyDescriptor,Ft=(s,t,e,r)=>{for(var i=r>1?void 0:r?d0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&c0(t,e,i),i},Ue,ge,de,Gs,Jt,Mo,Ce;class Ct extends Ia{constructor(e,r,i=fd,a=!0){const o=e.getValue("logger");super(o);g(this,Ue,void 0);g(this,ge,void 0);g(this,de,void 0);g(this,Gs,void 0);g(this,Jt,void 0);g(this,Mo,void 0);g(this,Ce,void 0);u(this,"audioUpdateInProgress");u(this,"videoUpdateInProgress");m(this,Ce,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,m(this,Ue,new Ef(e,r)),m(this,ge,new M0(e,n(this,Ue),void 0,i)),m(this,de,new U0(e,n(this,Ue),void 0,i)),m(this,Jt,new V0(n(this,Ce),n(this,Ue))),m(this,Gs,new O0(e,n(this,Ue))),m(this,Mo,a),n(this,ge).on("trackMuted",this.onAudioTrackMuted.bind(this)),n(this,ge).on("trackChanged",this.onAudioTrackChanged.bind(this)),n(this,de).on("trackChanged",this.onVideoTrackChanged.bind(this)),n(this,de).on("trackEnded",this.onVideoTrackEnded.bind(this)),n(this,Jt).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return n(this,Ce).getValue("telemetry")}set context(e){m(this,Ce,e)}async onVisibilityChange(){n(this,Ce).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?n(this,Ce).getValue("callstats").browserBackgrounded():(n(this,Ce).getValue("callstats").browserForegrounded(),await this.setupSpeaker())}async repopulateAvailableDevices(){return!0}async setupStreams({audio:e,video:r}){var o;e?n(this,Ce).getValue("callstats").audioOn():n(this,Ce).getValue("callstats").audioOff(),r?n(this,Ce).getValue("callstats").videoOn():n(this,Ce).getValue("callstats").videoOff();let i,a;if(e&&r)try{const c=await n(this,Ue).getAudioAndVideoTrack(n(this,ge).userSelectedDevice,n(this,de).userSelectedDevice);i=c.audioTrack,a=c.videoTrack}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!i&&e)try{i=await n(this,Ue).getAudioTrack(!1,n(this,ge).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!a&&r)try{a=await n(this,Ue).getVideoTrack(n(this,de).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}e&&!i&&n(this,Ce).getValue("callstats").audioOff(),r&&!a&&n(this,Ce).getValue("callstats").videoOff(),await n(this,ge).setMediaTrack(i),await n(this,de).setMediaTrack(a);try{await this.setupSpeaker()}catch(c){}if(a){const c=await this.getDeviceById(a.getSettings().deviceId);n(this,Ce).getValue("callstats").selectedDevice("VIDEO",c)}if(i){const c=await this.getDeviceById(i.getSettings().deviceId);n(this,Ce).getValue("callstats").selectedDevice("AUDIO",c)}(o=n(this,Gs).currentDevice)!=null&&o.deviceId&&n(this,Ce).getValue("callstats").selectedDevice("SPEAKER",n(this,Gs).currentDevice),n(this,Ue).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})}getCurrentDevices(){return{audio:n(this,ge).currentDevice,video:n(this,de).currentDevice,speaker:n(this,Gs).currentDevice}}get permissions(){return n(this,Ue).permissions}getAllDevices(){return n(this,Ue).getAvailableDevices()}getDeviceById(e,r){return n(this,Ue).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return n(this,ge).mediaTrack}get audioTrack(){return n(this,ge).transformedMediaTrack}get audioEnabled(){return n(this,ge).trackEnabled}async enableAudio(e){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?await n(this,ge).enableTrack(!1,e):await n(this,ge).unmuteTrack()}catch(r){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){n(this,ge).mediaTrack&&!n(this,ge).isCustomTrack?n(this,ge).muteTrack():n(this,ge).disableTrack()}getAudioDevices(e){return n(this,Ue).getAudioInputDevices(e)}async setAudioDevice(e,{saveDevicePreference:r}){await n(this,ge).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&n(this,Ce).getValue("callstats").selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async setupSpeaker(){const{speaker:e}=this.getCurrentDevices();await n(this,Gs).setPreferredSpeaker();const{speaker:r}=this.getCurrentDevices();(e==null?void 0:e.deviceId)!==(r==null?void 0:r.deviceId)&&r&&this.emit("DEVICE_CHANGE",{device:r})}async setSpeakerDevice(e,{saveDevicePreference:r}){await n(this,Gs).setupSpeaker(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&n(this,Ce).getValue("callstats").selectedDevice("SPEAKER",e),this.emit("DEVICE_CHANGE",{device:e})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return n(this,de).mediaTrack}get videoTrack(){return n(this,de).transformedMediaTrack}get videoEnabled(){return n(this,de).trackEnabled}async enableVideo(e){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?await n(this,de).enableTrack(!1,e):await n(this,de).unmuteTrack()}catch(r){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){n(this,de).disableTrack()}getVideoDevices(e){return n(this,Ue).getVideoInputDevices(e)}async setVideoDevice(e,{saveDevicePreference:r}){await n(this,de).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&n(this,Ce).getValue("callstats").selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async updateVideoConstraints(e){await n(this,de).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:n(this,Jt).audioMediaTrack,video:n(this,Jt).videoMediaTrack}}get screenShareEnabled(){return n(this,Jt).trackEnabled}async enableScreenShare(){await n(this,Jt).enableScreenShare()}async disableScreenShare(){n(this,Jt).disableScreenShare()}async updateScreenshareConstraints(e){await n(this,Jt).updateConstraints(e)}getSpeakerDevices(e){return n(this,Ue).getAudioOutputDevices(e)}addAudioMiddleware(e){return n(this,ge).addMiddleware(e)}removeAudioMiddleware(e){return n(this,ge).removeMiddleware(e)}removeAllAudioMiddlewares(){return n(this,ge).removeAllMiddlewares()}addVideoMiddleware(e){return n(this,de).addMiddleware(e)}removeVideoMiddleware(e){return n(this,de).removeMiddleware(e)}removeAllVideoMiddlewares(){return n(this,de).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return n(this,de).setVideoMiddlewareGlobalConfig(e)}destruct(){n(this,ge).disableTrack(),n(this,de).disableTrack(),n(this,de).terminateMiddlewareWebWorker(),n(this,Jt).disableScreenShare(),n(this,Ue).destruct()}async onDeviceChange(e,r){var a,o;if(this.emit("DEVICE_LIST_UPDATED",e),r||!n(this,Mo))return;let i=!1;(a=e==null?void 0:e.added)==null||a.reverse().forEach(async c=>{var d;c&&!fd(c)&&(c.kind==="audioinput"&&((d=this.audioTrack)==null?void 0:d.enabled)===!0?await this.setAudioDevice(c,{saveDevicePreference:!1}):c.kind==="audiooutput"&&(i=!0,await this.setSpeakerDevice(c,{saveDevicePreference:!1})))}),i||(o=e==null?void 0:e.removed)==null||o.forEach(async c=>{var d;if(c.kind==="audiooutput"&&((d=this.getCurrentDevices().speaker)==null?void 0:d.deviceId)===c.deviceId){const l=await this.getSpeakerDevices();(l==null?void 0:l.length)>0&&await this.setSpeakerDevice(l[0],{saveDevicePreference:!1})}})}removeAllTracks(){this.destruct()}removeAudioTrack(){n(this,ge).disableTrack()}removeVideoTrack(){n(this,de).disableTrack(),n(this,de).terminateMiddlewareWebWorker()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}Ue=new WeakMap,ge=new WeakMap,de=new WeakMap,Gs=new WeakMap,Jt=new WeakMap,Mo=new WeakMap,Ce=new WeakMap;Ft([y.trace("MediaHandler.setupStreams")],Ct.prototype,"setupStreams",1);Ft([y.trace("MediaHandler.enableAudio")],Ct.prototype,"enableAudio",1);Ft([y.trace("MediaHandler.disableAudio")],Ct.prototype,"disableAudio",1);Ft([y.trace("MediaHandler.setAudioDevice")],Ct.prototype,"setAudioDevice",1);Ft([y.trace("MediaHandler.enableVideo")],Ct.prototype,"enableVideo",1);Ft([y.trace("MediaHandler.disableVideo")],Ct.prototype,"disableVideo",1);Ft([y.trace("MediaHandler.setVideoDevice")],Ct.prototype,"setVideoDevice",1);Ft([y.trace("MediaHandler.updateVideoConstraints")],Ct.prototype,"updateVideoConstraints",1);Ft([y.trace("MediaHandler.enableScreenShare")],Ct.prototype,"enableScreenShare",1);Ft([y.trace("MediaHandler.disableScreenShare")],Ct.prototype,"disableScreenShare",1);Ft([y.trace("MediaHandler.updateScreenshareConstraints")],Ct.prototype,"updateScreenshareConstraints",1);Ft([y.trace("MediaHandler.destruct")],Ct.prototype,"destruct",1);Ft([y.trace("MediaHandler.onDeviceChange")],Ct.prototype,"onDeviceChange",1);function jc(s,t,e){switch(!0){case fe.isChromiumBased():switch(t){case"NotAllowedError":return e.includes("by system")?"SYSTEM_DENIED":s==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case fe.isSafari():switch(t){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case fe.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 l0=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function fd(s){var e,r;const t=(e=s.label)==null?void 0:e.toLowerCase();return((r=fe._bowser)==null?void 0:r.getOSName())==="macOS"&&t.includes("iphone")?!0:l0.some(i=>t==null?void 0:t.includes(i))}async function u0(s,t,e){if(!(t!=null&&t.length))return e;const r=s.getValue("logger"),i=new AudioContext,a=await Promise.all(t==null?void 0:t.map(d=>d(i))),o=i.createMediaStreamSource(new MediaStream([e])),c=i.createMediaStreamDestination();try{let d=o;for(let l=0;l<a.length;l+=1)d.connect(a[l]),d=a[l];d.connect(c)}catch(d){return r.error("getTransformedAudioTrack::middleware_execution_failed",{error:d}),e}return c.stream.getAudioTracks()[0]}var Ti,Do;class h0{constructor(t){g(this,Ti,void 0);g(this,Do,void 0);m(this,Do,t)}get logger(){return n(this,Do).getValue("logger")}terminateMiddlewareWebWorker(){if(n(this,Ti))try{Jc.clearInterval(n(this,Ti)),m(this,Ti,void 0)}catch(t){this.logger.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}async getTransformedVideoTrack(t,e,r){if(!(t!=null&&t.length))return e;const i=document.createElement("canvas"),a=await Promise.all(t==null?void 0:t.map(f=>f({canvas:i,WorkerTimers:Jc})));if(r.disablePerFrameCanvasRendering){const T=i.captureStream().getVideoTracks()[0];return Object.defineProperty(T,"originalSettings",{value:e.getSettings()}),T}const o=document.createElement("video"),c=new MediaStream;c.addTrack(e);const d=i.getContext("2d");o.srcObject=c,o.autoplay=!0,this.terminateMiddlewareWebWorker();const l=async()=>{if(e.enabled===!1||e.readyState==="ended"){this.terminateMiddlewareWebWorker(),o.remove(),i.remove();return}try{d.drawImage(o,0,0);for(let f=0;f<a.length;f+=1)typeof a[f]=="function"&&await a[f](i,d)}catch(f){this.logger.error("getTransformedVideoTrack::middleware_execution_failed",{error:f})}};try{o.play()}catch(f){}o.addEventListener("play",()=>{i.width=o.width||e.getSettings().width,i.height=o.width||e.getSettings().height,m(this,Ti,Jc.setInterval(l,50))},!1);const p=i.captureStream().getVideoTracks()[0];return Object.defineProperty(p,"originalSettings",{value:e.getSettings()}),p}}Ti=new WeakMap,Do=new WeakMap;const Jp={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}}},p0=[[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"}]]],g0=(s,t)=>{var d,l,h;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&&((h=t.originalSettings)==null?void 0:h.width);let i=p0;s.getValue("flagsmith").hasFeature(Y.OVERRIDE_SIMULCAST_DYNAMIC)&&(i=JSON.parse(s.getValue("flagsmith").getValue(Y.OVERRIDE_SIMULCAST_DYNAMIC)));const a=i.map(([p])=>p).sort((p,f)=>p-f);let o=Number.MAX_VALUE,c=0;return a.forEach((p,f)=>{Math.abs(p-r)<o&&(o=Math.abs(p-r),c=f)}),i[c][1]};var ce=(s=>(s.WEBCAM="webcam",s.WEBCAM_BACKUP="webcam_backup",s.MIC="mic",s.SCREENSHARE_VIDEO="screenshare_video",s.SCREENSHARE_AUDIO="screenshare_audio",s))(ce||{});const m0=GP(),cn=ys(m0.config.media);function f0(s){var e,r;const t={};return s.audio&&(t.audio={enableStereo:(e=s.audio.enableStereo)!=null?e:!1,enableHighBitrate:(r=s.audio.enableHighBitrate)!=null?r:!1}),t.video=s.video.quality,t}var vi,bs;class T0{constructor(t,e){g(this,vi,void 0);g(this,bs,void 0);u(this,"getScreenShareConstraints",()=>{var l,h,p,f,T,E,C,_,I,M,x;const t=(l=n(this,vi))==null?void 0:l.screenshare,e=(p=(h=t==null?void 0:t.width)==null?void 0:h.max)!=null?p:1920,r=(T=(f=t==null?void 0:t.height)==null?void 0:f.max)!=null?T:1080,i=(C=(E=t==null?void 0:t.frameRate)==null?void 0:E.max)!=null?C:5;let a=(I=(_=t==null?void 0:t.frameRate)==null?void 0:_.ideal)!=null?I:5;const o=t==null?void 0:t.displaySurface,c=t==null?void 0:t.selfBrowserSurface;n(this,bs).getValue("flagsmith").getValue(Y.VAL_MIN_FRAMERATE)&&(a=parseInt((M=n(this,bs).getValue("flagsmith").getValue(Y.VAL_MIN_FRAMERATE))==null?void 0:M.toString(),10));let d={width:{max:e},height:{max:r},frameRate:{ideal:a,max:i}};if(n(this,bs).getValue("flagsmith").hasFeature(Y.SCREENSHARE_CONSTRAINTS)){const N=(x=n(this,bs).getValue("flagsmith").getValue(Y.SCREENSHARE_CONSTRAINTS))==null?void 0:x.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}});u(this,"getAudioConstraints",t=>{var a,o,c,d,l,h,p;const e={},r=(a=n(this,vi))==null?void 0:a.audio,i=r!=null&&r.enableStereo?2:1;return fe.isFirefox()||fe.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:(h=r==null?void 0:r.echoCancellation)!=null?h:!0,noiseSuppression:(p=r==null?void 0:r.noiseSupression)!=null?p:!0,channelCount:i},t&&(e.audio.deviceId={exact:t}),e)});u(this,"getVideoConstraints",t=>{var a,o,c,d;const e={},r=(a=n(this,vi))==null?void 0:a.video;let i=Jp.vga;if(typeof r=="string"?i=Jp[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},fe.isChromiumBased()&&(i.frameRate.max=30),n(this,bs).getValue("flagsmith").hasFeature(Y.VIDEO_CONSTRAINTS)){const l=(d=n(this,bs).getValue("flagsmith").getValue(Y.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});m(this,bs,t),m(this,vi,e)}getUpdatedVideoConstraints(t){return t}}vi=new WeakMap,bs=new WeakMap;class eu extends Error{constructor(e,r,i){super(r);u(this,"constraints");u(this,"name");this.name=e,this.constraints=i}}class v0{constructor(){u(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 S0=Object.defineProperty,y0=Object.getOwnPropertyDescriptor,ws=(s,t,e,r)=>{for(var i=r>1?void 0:r?y0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&S0(t,e,i),i},jn,Kt,Me,vg;let xt=(vg=class extends v0{constructor(t,e){super();g(this,jn,void 0);g(this,Kt,void 0);g(this,Me,void 0);m(this,Me,t),m(this,Kt,new T0(t,e)),m(this,jn,new AbortController)}get telemetry(){return n(this,Me).getValue("telemetry")}get logger(){return n(this,Me).getValue("logger")}get constraintsBuilder(){return n(this,Kt)}async destruct(){var t;(t=n(this,jn))==null||t.abort()}handlePermissionErrors(t,e){const r=jc(t,e.name,e.message);return this.permissions[t]=r,n(this,Me).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}async getAudioAndVideoTrack(t,e){var r,i,a,o;try{const c=await this.getAudioInputDevices(),d=await this.getVideoInputDevices(),l=!!(c!=null&&c.find(M=>M.deviceId===t));let h;t&&l?h=t:c&&((r=c[0])!=null&&r.deviceId)&&(h=(i=c[0])==null?void 0:i.deviceId);const p=!!(d!=null&&d.find(M=>M.deviceId===e));let f;e&&p?f=e:d&&((a=d[0])!=null&&a.deviceId)&&(f=(o=d[0])==null?void 0:o.deviceId);const T={audio:n(this,Kt).getAudioConstraints(h).audio,video:n(this,Kt).getVideoConstraints(f).video};this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(T)});const E=await navigator.mediaDevices.getUserMedia(T);this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(T)});const C=E.getAudioTracks()[0];let _=E.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",n(this,Me).getValue("flagsmith").hasFeature(Y.OBS_QUALITY)&&_.label.includes("OBS Virtual")){const x=(await this.getVideoInputDevices()).find(N=>N.label.includes("OBS Virtual"));_=await this.getVideoTrack(x.deviceId)}return n(this,Me).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),n(this,Me).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:C,videoTrack:_}}catch(c){throw this.logger.error("WebMediaInterface.getAudioAndVideoTrack",{error:c}),new b("Couldnt fetch audio and video track","1605")}}async getAudioTrack(t,e){var c,d;let r=await this.getAudioInputDevices();if(!(r!=null&&r.length))throw this.permissions.audio="NO_DEVICES_AVAILABLE",n(this,Me).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new b("No audio devices available","1606");const i=!!(r!=null&&r.find(l=>l.deviceId===e));let a;e&&i?a=e:(c=r[0])!=null&&c.deviceId&&(a=(d=r[0])==null?void 0:d.deviceId);const o=async l=>{let h;try{r=r.filter(f=>f.deviceId!==l),h=n(this,Kt).getAudioConstraints(l),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(h)});const[p]=(await navigator.mediaDevices.getUserMedia(h)).getAudioTracks();return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(h)}),p}catch(p){const f=jc("audio",p.name,p.message),T=new eu(p.name,p.message,h);if(f==="COULD_NOT_START"){const E=r.shift();if(!E)throw T;this.logger.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(h),error:p});const C=n(this,Kt).getAudioConstraints(E.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(C)}),o(E.deviceId)}throw T}};try{const l=await o(a);return l.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",n(this,Me).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),l}catch(l){throw l.constraints&&this.handlePermissionErrors("audio",l),new b(l.message,"1601")}}async getVideoTrack(t){var l,h,p;const e=n(this,Me).getValue("flagsmith").hasFeature(Y.OBS_QUALITY),r=(l=await this.getCurrentDeviceLabel(t))==null?void 0:l.includes("OBS Virtual"),i=e&&r,a=await this.getVideoInputDevices();if(!(a!=null&&a.length))throw this.permissions.video="NO_DEVICES_AVAILABLE",n(this,Me).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new b("No video devices available","1607");const o=!!(a!=null&&a.find(f=>f.deviceId===t));let c;t&&o?c=t:(h=a[0])!=null&&h.deviceId&&(c=(p=a[0])==null?void 0:p.deviceId);const d=async f=>{try{let T=f;const{video:E}=T;i&&typeof E!="boolean"&&(T={video:{deviceId:E.deviceId}}),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(T)});const[C]=(await navigator.mediaDevices.getUserMedia(T)).getVideoTracks();if(i&&typeof E!="boolean"&&typeof E.width=="object"){const{width:_,height:I}=C.getSettings(),{ideal:M}=E.width;C.applyConstraints({width:{ideal:M},height:{ideal:Math.floor(I*M/_)},frameRate:E.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(T)}),C}catch(T){const E=jc("video",T.name,T.message),C=new eu(T.name,T.message,f);if(E==="COULD_NOT_START"){const _=a.shift();if(!_)throw C;this.logger.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(f),error:T});const I=n(this,Kt).getVideoConstraints(_.deviceId);return this.logger.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(I)}),d({video:I.video})}throw C}};try{const f=n(this,Kt).getVideoConstraints(c),T=await d(f);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",n(this,Me).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),T}catch(f){throw f.constraints&&this.handlePermissionErrors("video",f),new b(f.message,"1602")}}async getScreenShareTracks(){const t=async e=>{try{this.logger.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),n(this,Me).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=jc("video",r.name,r.message),a=new eu(r.name,r.message,e),o={video:!0};if(DC(e,o)||!n(this,Me).getValue("flagsmith").hasFeature(Y.SCREEENSHARE_CONSTRAINTS_RETRY))throw a;if(i==="COULD_NOT_START")return t(o);throw a}};try{const e=n(this,Kt).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",n(this,Me).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:r.getAudioTracks()[0],videoTrack:r.getVideoTracks()[0]}}catch(e){throw e.constraints&&this.handlePermissionErrors("screenshare",e),new b(e.message,"1612")}}async getCurrentDeviceLabel(t){const e=await this.getDevice(t||"default");return e==null?void 0:e.label}async enumerateDevicesWithExternalFirst(){const t=await navigator.mediaDevices.enumerateDevices(),e=i=>{var o;const a=((o=i.label)==null?void 0:o.toLowerCase())||"";return fd(i)?4:a.includes("airpods")||a.includes("airdopes")||a.includes("bluetooth")||a.includes("wireless")||a.includes("headphones")||a.includes("headset")||a.includes("earbuds")||a.includes("usb")||a.includes("external")?0:i.deviceId==="default"||a.includes("default")?1:a.includes("built-in")||a.includes("internal")?2:3},r=i=>{var o;if(i.kind!=="videoinput")return!1;const a=((o=i.label)==null?void 0:o.toLowerCase())||"";return a.includes("front")||a.includes("user")||a.includes("selfie")?!0:!(a.includes("back")||a.includes("rear")||a.includes("environment"))};return t.sort((i,a)=>{var h,p;const o=e(i),c=e(a);if(o!==c)return o-c;const d=i.deviceId==="default"||((h=i.label)==null?void 0:h.toLowerCase().includes("default")),l=a.deviceId==="default"||((p=a.label)==null?void 0:p.toLowerCase().includes("default"));if(d&&!l)return-1;if(!d&&l)return 1;if(i.kind==="videoinput"&&a.kind==="videoinput"){const f=r(i),T=r(a);if(f&&!T)return-1;if(!f&&T)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 b("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 b("Failed to get device","1609")}}async onDeviceChange(t){if(fe.supportsDeviceChangeEvent()){let e=await this.getAvailableDevices();navigator.mediaDevices.addEventListener("devicechange",async r=>{var l,h;const i=p=>`${p.kind}-${p.label}-${p.deviceId}-${p.groupId}`,a=new Set(e.map(p=>i(p))),o=await this.getAvailableDevices(),c=new Set(o.map(p=>i(p))),d={added:o.filter(p=>!a.has(i(p))),removed:e.filter(p=>!c.has(i(p))),devices:o};if(e=o,(l=d.added)!=null&&l.length||(h=d.removed)!=null&&h.length){this.logger.info("repopulated_full_device_list",{devices:JSON.stringify(o)});const p=[...d.added,...d.removed];p.some(f=>f.kind==="audioinput")&&n(this,Me).getValue("callstats").devices("AUDIO",o==null?void 0:o.filter(f=>f.kind==="audioinput")),p.some(f=>f.kind==="videoinput")&&n(this,Me).getValue("callstats").devices("VIDEO",o==null?void 0:o.filter(f=>f.kind==="videoinput")),p.some(f=>f.kind==="audiooutput")&&n(this,Me).getValue("callstats").devices("SPEAKER",o==null?void 0:o.filter(f=>f.kind==="audiooutput")),t(r,d,!1)}},{signal:n(this,jn).signal})}}},jn=new WeakMap,Kt=new WeakMap,Me=new WeakMap,vg);ws([y.trace("WebMediaInterface.destruct")],xt.prototype,"destruct",1);ws([y.trace("WebMediaInterface.handlePermissionErrors")],xt.prototype,"handlePermissionErrors",1);ws([y.trace("WebMediaInterface.getAudioAndVideoTrack")],xt.prototype,"getAudioAndVideoTrack",1);ws([y.trace("WebMediaInterface.getAudioTrack")],xt.prototype,"getAudioTrack",1);ws([y.trace("WebMediaInterface.getVideoTrack")],xt.prototype,"getVideoTrack",1);ws([y.trace("WebMediaInterface.getScreenShareTracks")],xt.prototype,"getScreenShareTracks",1);ws([y.trace("WebMediaInterface.getAvailableDevices")],xt.prototype,"getAvailableDevices",1);ws([y.trace("WebMediaInterface.getAvailableDevicesByKind")],xt.prototype,"getAvailableDevicesByKind",1);ws([y.trace("WebMediaInterface.getDevice")],xt.prototype,"getDevice",1);ws([y.trace("WebMediaInterface.onDeviceChange")],xt.prototype,"onDeviceChange",1);xt=ws([at("1600")],xt);const Ef=xt,Xi={setItem:(s,t,e)=>{try{localStorage.setItem(s,t)}catch(r){e==null||e.error("LocalStorage::setItem::crashed",{error:r,localStorage:{key:s,value:t}})}},getItem:(s,t)=>{try{return localStorage.getItem(s)}catch(e){t==null||t.error("LocalStorage::getItem::crashed",{error:e,localStorage:{key:s}})}return null}},E0=(s=0)=>new Promise(t=>setTimeout(t,s)),P0=(s,t,e)=>{const r=typeof e=="number"?e:250,i=s.createMediaStreamSource(t),a=s.createAnalyser();a.fftSize=2048,i.connect(a);const o=new Uint8Array(a.fftSize);let c=!1;setTimeout(()=>{c=!0},r);function d(){return c?Promise.resolve(!0):(a.getByteTimeDomainData(o),o.some(l=>l!==128&&l!==0)?Promise.resolve(!1):E0().then(d))}return d().then(l=>(i.disconnect(),l),l=>{throw i.disconnect(),l})},_0=typeof AudioContext!="undefined"?AudioContext:null;class Eh{constructor(t){u(this,"_AudioContext");u(this,"audioContext");u(this,"_audioContextRefContainers");const e={AudioContext:_0,...t};Object.defineProperties(this,{_AudioContext:{value:e.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:Eh}})}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 Kp=new Eh,C0=3,w0=250;function R0(s){const t={},e=Kp.getOrCreate(t);let r=C0;function i(){return r-=1,P0(e,s.srcObject,w0).then(a=>a?r>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{Kp.release(t)})}async function zp(s,t){const e=new Audio,r=new MediaStream;r.addTrack(t),e.srcObject=r;let i=!1;try{const a=e.play();a&&await a,i=await R0(e),i&&s.info("checkIfAudioTrackIsSilent::silence_detected")}catch(a){s.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:a})}finally{e.pause(),e.remove()}return i}var b0=Object.defineProperty,k0=Object.getOwnPropertyDescriptor,Pf=(s,t,e,r)=>{for(var i=r>1?void 0:r?k0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&b0(t,e,i),i};let Td=class extends Ia{constructor(t,e,r,i){var o;const a=t.getValue("logger");super(a);u(this,"constructorName",this.constructor.name);u(this,"userSelectedDevice");u(this,"mediaInterface");u(this,"isNonPreferredDevice");u(this,"_mediaTrack");u(this,"transformedMediaTrack");u(this,"middlewares",[]);u(this,"currentDevice");u(this,"userPreferredDeviceKey",`Realtimekit::${this.constructorName}::UserDeviceID`);u(this,"setUserPreferredDevice",t=>Xi.setItem(this.userPreferredDeviceKey,t,this.logger));u(this,"getUserPreferredDevice",()=>Xi.getItem(this.userPreferredDeviceKey,this.logger));u(this,"isCustomTrack",!1);u(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 b("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 b("No device received!","1603");this.userSelectedDevice=t.deviceId,e&&this.setUserPreferredDevice(t.deviceId),await this.onSetDevice(t)}async addMiddleware(t){if(fe.isWebKitBased()&&!NP.hasFeature(Y.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))}};Pf([y.trace("BaseMediaHandler.unmuteTrack")],Td.prototype,"unmuteTrack",1);Td=Pf([at("1600")],Td);const _f=Td;var I0=Object.defineProperty,A0=Object.getOwnPropertyDescriptor,Ph=(s,t,e,r)=>{for(var i=r>1?void 0:r?A0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&I0(t,e,i),i};const tu="[Realtimekit]nonSilentDeviceLabels";class Dl extends _f{async onSetDevice(t){if(!t)throw this.logger.warn("AudioMediaHandler.setDevice No device received"),new b("No device received!","1603");if(t.kind!=="audioinput")throw this.logger.warn("AudioMediaHandler.setDevice Received non audio device"),new b("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 b(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 u0(this.context,this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(r){this.logger.error("AudioMediaHandler.setTransformedTrack",{error:r}),this.transformedMediaTrack=this.mediaTrack}}async onTrackEnded(){this.logger.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const t=this.mediaTrack.enabled;this.disableTrack(),await this.enableTrack(!t),await this.setTransformedTrack(),this.emit("trackChanged")}onTrackMuted(){this.logger.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(t,e=!1){var d;if(!t||this.userSelectedDevice||e)return t;let r=t;const i=await this.mediaInterface.getAudioInputDevices(),a=this.isNonPreferredDevice?i.filter(l=>l&&!this.isNonPreferredDevice(l)):i;if(!(a!=null&&a.length))return r;a.find(l=>l.deviceId===t.getSettings().deviceId)||(r.stop(),this.logger.info("localmediahandler::setupstreams::found_audio_non_preferred"),r=await this.mediaInterface.getAudioTrack(!1,a[0].deviceId));const o=JSON.parse(Xi.getItem(tu,this.logger));if(o!=null&&o.devices.some(l=>l.label===r.label))return r;if(!await zp(this.logger,r)){const l=(d=o==null?void 0:o.devices.concat({label:r.label}))!=null?d:[{label:r.label}];return Xi.setItem(tu,JSON.stringify({devices:l}),this.logger),r}this.logger.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const c=r.getSettings().deviceId;return a.filter(l=>l.deviceId!==c).some(async l=>{var h;if(r=await this.mediaInterface.getAudioTrack(!1,l.deviceId),!await zp(this.logger,r)){const p=(h=o==null?void 0:o.devices.concat({label:r.label}))!=null?h:[{label:r.label}];return Xi.setItem(tu,JSON.stringify({devices:p}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),r}}Ph([y.trace("AudioMediaHandler.setTransformedTrack")],Dl.prototype,"setTransformedTrack",1);Ph([y.trace("AudioMediaHandler.onTrackEnded")],Dl.prototype,"onTrackEnded",1);Ph([y.trace("AudioMediaHandler.conditionallyChangeTrack")],Dl.prototype,"conditionallyChangeTrack",1);const M0=Dl;var Si;class D0{constructor(t,e){g(this,Si,void 0);u(this,"currentDevice");u(this,"userPreferredDeviceKey","Realtimekit::speaker::UserDeviceID");u(this,"logger");u(this,"setUserPreferredDevice",t=>Xi.setItem(this.userPreferredDeviceKey,t,this.logger));u(this,"getUserPreferredDevice",()=>Xi.getItem(this.userPreferredDeviceKey,this.logger));m(this,Si,e),this.logger=t.getValue("logger")}async setPreferredSpeaker(){const t=this.getUserPreferredDevice(),e=await n(this,Si).getAudioOutputDevices(),r=e==null?void 0:e.find(i=>i.deviceId===t);await this.setupSpeaker(r,{saveDevicePreference:!1})}async setupSpeaker(t,{saveDevicePreference:e}){var a,o;if(!(n(this,Si)instanceof Ef))return;let r=t;if(t||([r]=(await n(this,Si).getAvailableDevicesByKind("audiooutput")).filter(d=>!fd(d))),!r)throw new b("No speaker found","1608");if(((a=this.currentDevice)==null?void 0:a.deviceId)===r.deviceId)return;e&&this.setUserPreferredDevice(r.deviceId),this.currentDevice=r;const i=document.querySelectorAll("audio");(o=i[0])!=null&&o.setSinkId&&i.forEach(async c=>{if(typeof c.sinkId!="undefined"&&this.currentDevice.deviceId&&c.sinkId!==this.currentDevice.deviceId)try{await c.setSinkId(this.currentDevice.deviceId)}catch(d){}})}}Si=new WeakMap;const O0=D0;var Oo;class N0 extends Ia{constructor(e,r){const i=e.getValue("logger");super(i);u(this,"mediaInterface");u(this,"audioMediaTrack");u(this,"videoMediaTrack");g(this,Oo,void 0);m(this,Oo,e),this.mediaInterface=r}get trackEnabled(){return!!this.videoMediaTrack}async enableScreenShare(){var e,r;try{const{audioTrack:i,videoTrack:a}=await this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=i,this.videoMediaTrack=a,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",n(this,Oo).getValue("peerSessionStore").emit(w.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 b("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new b("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)),fe.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")}}Oo=new WeakMap;const V0=N0;var L0=Object.defineProperty,x0=Object.getOwnPropertyDescriptor,Ol=(s,t,e,r)=>{for(var i=r>1?void 0:r?x0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&L0(t,e,i),i},Gn,No;class Oc extends _f{constructor(e,r,i,a){super(e,r,i,a);g(this,Gn,void 0);g(this,No,{disablePerFrameCanvasRendering:!1});m(this,Gn,new h0(e))}async onSetDevice(e){if(!e)throw this.logger.warn("VideoMediaHandler.setDevice No device received"),new b("No device received!","1603");if(e.kind!=="videoinput")throw this.logger.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new b("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 b("Failed to change device","1600",this.logger)}}async enableTrack(e,r){if(this.trackEnabled){this.logger.warn("VideoMediaHandler.enableTrack Track already enabled!");return}if(r){this.isCustomTrack=!0,await this.setMediaTrack(r,!0);return}this.isCustomTrack=!1;const i=await this.mediaInterface.getVideoTrack(this.userSelectedDevice);await this.setMediaTrack(i)}async setTransformedTrack(e){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await n(this,Gn).getTransformedVideoTrack(this.middlewares,this.mediaTrack,n(this,No)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){m(this,No,e)}async updateConstraints(e){if(!this._mediaTrack)throw new b("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new b("update constraints not supported for non web clients","1100",this.logger);try{this._mediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),await this.setTransformedTrack(),this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(i){this.logger.error("VideoMediaHandler.updateConstraints.error",{error:i})}}terminateMiddlewareWebWorker(){n(this,Gn).terminateMiddlewareWebWorker()}async onTrackEnded(){this.logger.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")}onTrackMuted(){this.logger.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(e,r=!1){if(!e||this.userSelectedDevice||r)return e;let i=e;const a=await this.mediaInterface.getVideoInputDevices(),o=this.isNonPreferredDevice?a.filter(c=>!this.isNonPreferredDevice(c)):a;return!(o!=null&&o.length)||window.FAST_RTK||o.find(c=>c.deviceId===e.getSettings().deviceId)||(i.stop(),this.logger.info("localmediahandler::setupstreams::found_video_non_preferred"),i=await this.mediaInterface.getVideoTrack(o[0].deviceId)),i}}Gn=new WeakMap,No=new WeakMap;Ol([y.trace("VideoMediaHandler.setTransformedTrack")],Oc.prototype,"setTransformedTrack",1);Ol([y.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],Oc.prototype,"setVideoMiddlewareGlobalConfig",1);Ol([y.trace("VideoMediaHandler.onTrackEnded")],Oc.prototype,"onTrackEnded",1);Ol([y.trace("VideoMediaHandler.conditionallyChangeTrack")],Oc.prototype,"conditionallyChangeTrack",1);const U0=Oc,Yp=ys(uh());var Tt,yi,Vo,Wn;const fn=class{constructor(t){g(this,Tt,void 0);g(this,yi,void 0);g(this,Vo,void 0);g(this,Wn,void 0);if(!t)throw new b("Could not load preset.","0904");m(this,Tt,t.config),m(this,Vo,t.name),m(this,yi,t.ui||ys(uh().ui)),m(this,Wn,t.permissions.plugins.config)}static fromResponse(t){return new fn(t)}static default(){return new fn(Yp)}static init(t,e=!0){return!t||e?new fn(Yp):new fn(t)}get setupScreen(){return{isEnabled:!0}}get waitingRoom(){return{isEnabled:!0}}get controlBar(){return{isEnabled:!0,elements:{chat:!0,fullscreen:!0,invite:!1,layout:!1,participants:!0,plugins:!0,polls:!0,reactions:!1,screenshare:!0}}}get header(){return{isEnabled:!0,elements:{logo:n(this,yi).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return n(this,Tt).viewType}get livestreamViewerQualities(){return n(this,Tt).livestreamViewerQualities||[]}get maxVideoStreams(){return n(this,Tt).maxVideoStreams}get maxScreenShareCount(){return n(this,Tt).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(n(this,Wn)).filter(t=>n(this,Wn)[t].disabled)}get designTokens(){return n(this,yi).designTokens}get configDiff(){return n(this,yi).configDiff}get mediaConstraints(){var t,e,r,i,a,o,c,d,l,h,p,f,T,E,C,_,I,M,x,N,$,q,ee,Qe;return{audio:{enableStereo:(i=(r=(e=(t=n(this,Tt))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:cn.audio.enableStereo,enableHighBitrate:(d=(c=(o=(a=n(this,Tt))==null?void 0:a.media)==null?void 0:o.audio)==null?void 0:c.enableHighBitrate)!=null?d:cn.audio.enableHighBitrate},video:{quality:(f=(p=(h=(l=n(this,Tt))==null?void 0:l.media)==null?void 0:h.video)==null?void 0:p.quality)!=null?f:cn.video.quality,frameRate:(_=(C=(E=(T=n(this,Tt))==null?void 0:T.media)==null?void 0:E.video)==null?void 0:C.frameRate)!=null?_:cn.video.frameRate},screenshare:{quality:(N=(x=(M=(I=n(this,Tt))==null?void 0:I.media)==null?void 0:M.screenshare)==null?void 0:x.quality)!=null?N:cn.screenshare.quality,frameRate:(Qe=(ee=(q=($=n(this,Tt))==null?void 0:$.media)==null?void 0:q.screenshare)==null?void 0:ee.frameRate)!=null?Qe:cn.screenshare.frameRate}}}get name(){return n(this,Vo)}};let bu=fn;Tt=new WeakMap,yi=new WeakMap,Vo=new WeakMap,Wn=new WeakMap;var $0=Object.defineProperty,F0=Object.getOwnPropertyDescriptor,Cf=(s,t,e,r)=>{for(var i=r>1?void 0:r?F0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&$0(t,e,i),i},Jn,Lo;class _h extends Ut{constructor(e,r){const i=e.getValue("logger");super(i);g(this,Jn,void 0);u(this,"state","IDLE");u(this,"playbackUrl");u(this,"ingestionCredentials");u(this,"viewerCount");g(this,Lo,void 0);m(this,Jn,r),m(this,Lo,e),this.viewerCount=0}get telemetry(){return n(this,Lo).getValue("telemetry")}setLivestreamState(e){const r=this.state;this.state=e,r!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}async start(e={manualIngestion:!1}){if(!n(this,Jn).permissions.canLivestream)throw this.logger.error("Livestream::start::permission_denied"),new b("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const r=it(),{playbackUrl:i,ingestionCredentials:a}=await r.startLivestreaming(e);this.playbackUrl=i,this.ingestionCredentials=a,e!=null&&e.manualIngestion&&this.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}catch(r){throw this.logger.error("Recording::stop::livestream_failed_to_start",{error:r}),this.setLivestreamState("IDLE"),new b("Error while starting livestream","1900",this.logger)}}async stop(){if(!n(this,Jn).permissions.canLivestream)throw this.logger.error("Livestream::stop::permission_denied"),new b("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 b("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),await it().stopLivestreaming()}catch(e){throw this.logger.error("Livestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new b("Error while stopping livestream","1900",this.logger)}}}Jn=new WeakMap,Lo=new WeakMap;Cf([y.trace("livestream.start")],_h.prototype,"start",1);Cf([y.trace("livestream.stop")],_h.prototype,"stop",1);var B0=Object.defineProperty,H0=Object.getOwnPropertyDescriptor,q0=(s,t,e,r)=>{for(var i=r>1?void 0:r?H0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&B0(t,e,i),i},Kn,zn,Ws,ks;class wf{constructor(t,e,r){u(this,"livestream");g(this,Kn,void 0);g(this,zn,void 0);g(this,Ws,void 0);g(this,ks,void 0);m(this,ks,t),m(this,zn,e),this.livestream=new _h(t,e),m(this,Ws,r),this.setupEvents()}get logger(){return n(this,ks).getValue("logger")}get telemetry(){return n(this,ks).getValue("telemetry")}async fetchInitialLivestreamingState(){const t=it(),{status:e,playbackUrl:r,manualIngest:i,ingestionCredentials:a}=await t.getActiveLivestream();this.livestream.playbackUrl=r,this.livestream.ingestionCredentials=a,e==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),e==="INVOKED"&&i&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}setupEvents(){n(this,Ws).on(L.startedLivestream,async t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{n(this,zn).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}}),n(this,Ws).on(L.livestreamingInvoked,async t=>{if(t.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{n(this,zn).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}}),n(this,Ws).on(L.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),n(this,Ws).on(L.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),n(this,Ws).on(L.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),n(this,ks).getValue("peerSessionStore").on(w.PEER_JOINED_INTERNAL,async t=>{var e;((e=t.flags)==null?void 0:e.hiddenParticipant)===!0&&t.recorderType==="LIVESTREAMER"&&(m(this,Kn,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),n(this,ks).getValue("peerSessionStore").on(w.PEER_CLOSED,t=>{t.id===n(this,Kn)&&(m(this,Kn,void 0),this.livestream.setLivestreamState("IDLE"))}),n(this,ks).getValue("peerSessionStore").onAsync(w.LEAVE_MEDIA_ROOM,async()=>{if(!this.livestream.playbackUrl){this.logger.info("Fetching livestreaming state on leave stage");try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Failed to fetch livestreaming state on leave stage",{error:t})}}}),n(this,ks).getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Error: LivestreamController.fetchLivestream")}})}}Kn=new WeakMap,zn=new WeakMap,Ws=new WeakMap,ks=new WeakMap;q0([y.trace("LivestreamController.setupEvents")],wf.prototype,"setupEvents",1);var j0=Object.defineProperty,G0=Object.getOwnPropertyDescriptor,Nc=(s,t,e,r)=>{for(var i=r>1?void 0:r?G0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&j0(t,e,i),i},et,Dr,Or,Id,Rf;class Ma{constructor({name:t,socketHandler:e,meetingId:r}){g(this,Id);u(this,"name","");g(this,et,{});g(this,Dr,"");g(this,Or,void 0);u(this,"rateLimitConfig",{maxInvocations:5,period:1});u(this,"bulkRateLimitConfig",{maxInvocations:5,period:1});u(this,"listeners",{});this.name=t,m(this,Or,e),m(this,Dr,r)}async set(t,e,r=!0,i=!1){n(this,et)[t]=e,r&&this.remoteSet(t,e),i&&(this.listeners[t]&&this.listeners[t].forEach(a=>a({[t]:n(this,et)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(a=>a({[t]:n(this,et)[t]})))}remoteSet(t,e){n(this,Or).storeInsertKeys(n(this,Dr),this.name,[{key:t,payload:e}])}async bulkSet(t){t.forEach(({key:e,payload:r})=>{n(this,et)[e]=r}),n(this,Or).storeInsertKeys(n(this,Dr),this.name,t)}async update(t,e,r=!0){V(this,Id,Rf).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(n(this,et)[t]&&delete n(this,et)[t],e)return n(this,Or).storeDeleteKeys(n(this,Dr),this.name,[{key:t}]);r&&(this.listeners[t]&&(this.listeners[t].forEach(i=>i({[t]:void 0})),delete this.listeners[t]),this.listeners["*"]&&this.listeners["*"].forEach(i=>i({[t]:void 0})))}async bulkDelete(t){return t.forEach(({key:e})=>{n(this,et)[e]&&delete n(this,et)[e]}),n(this,Or).storeDeleteKeys(n(this,Dr),this.name,t)}get(t){if(n(this,et)[t])return n(this,et)[t]}getAll(){return n(this,et)}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(t,e){this.bulkRateLimitConfig.maxInvocations=t,this.bulkRateLimitConfig.period=e}subscribe(t,e){if(this.listeners[t]){this.listeners[t].push(e);return}this.listeners[t]=[e]}unsubscribe(t,e){var r;if(e){this.listeners[t]=((r=this.listeners[t])==null?void 0:r.filter(i=>i!==e))||[];return}this.listeners[t]&&delete this.listeners[t]}populate(t){m(this,et,t)}}et=new WeakMap,Dr=new WeakMap,Or=new WeakMap,Id=new WeakSet,Rf=function(t,e,r=!0){let i;const a=n(this,et)[t],o=Object.prototype.toString.call(e),c=Object.prototype.toString.call(a);if(o!==c){this.set(t,e);return}switch(c){case"[object Array]":i=[...a,...e];break;case"[object Object]":i={...a,...e};break;case"[object Map]":i=new Map([...a,...e]);break;case"[object Set]":i=new Set([...a,...e]);break;default:i=e;break}this.set(t,i,r)};Nc([_t(Aa,"rateLimitConfig")],Ma.prototype,"remoteSet",1);Nc([_t(Aa,"bulkRateLimitConfig")],Ma.prototype,"bulkSet",1);Nc([_t(Aa,"rateLimitConfig")],Ma.prototype,"update",1);Nc([_t(Aa,"rateLimitConfig")],Ma.prototype,"delete",1);Nc([_t(Aa,"bulkRateLimitConfig")],Ma.prototype,"bulkDelete",1);var Ei,Pi,xo,ku,Uo,Nr,Ad,bf;class W0{constructor(t,e){g(this,xo);g(this,Ad);u(this,"stores",new Map);g(this,Ei,void 0);g(this,Pi,"");g(this,Uo,void 0);g(this,Nr,new Map);m(this,Ei,e),m(this,Pi,t.getValue("meetingId")),m(this,Uo,t),V(this,Ad,bf).call(this)}create(t){const e=new Ma({name:t,socketHandler:n(this,Ei),meetingId:n(this,Pi)});return n(this,Ei).storeGetKeys(n(this,Pi),t,[]),new Promise((i,a)=>{const o=setTimeout(()=>a(Error("Failed")),3e3);n(this,Nr).set(t,{rejectTimeout:o,resolve:i,store:e})})}}Ei=new WeakMap,Pi=new WeakMap,xo=new WeakSet,ku=function(){return n(this,Uo).getValue("peerId")},Uo=new WeakMap,Nr=new WeakMap,Ad=new WeakSet,bf=function(){[j.storeInsertKeys,j.storeGetKeys,j.storeDeleteKeys].forEach(t=>{n(this,Ei).on(t,async e=>{var a,o;if(e.pluginId!==n(this,Pi))return;const r=(a=e.storeItems)==null?void 0:a.map(c=>{var d;return{timestamp:c.timestamp,peerId:c.peerId,payload:JSON.parse((d=c.payload)!=null&&d.length?new TextDecoder().decode(c.payload):"{}"),key:c.storeKey}});if(t===j.storeGetKeys){const c=n(this,Nr).get(e.storeName),d=this.stores.get(e.storeName)||(c==null?void 0:c.store);n(this,Nr).get(e.storeName)&&(this.stores.set(e.storeName,c.store),c.resolve(d),clearTimeout(c.rejectTimeout),n(this,Nr).delete(e.storeName)),r.forEach(l=>{d.set(l.key,l.payload,!1,!1)});return}const i=this.stores.get(e.storeName)||((o=n(this,Nr).get(e.storeName))==null?void 0:o.store);i!==void 0&&(t===j.storeInsertKeys&&r.forEach(({key:c,peerId:d,payload:l})=>{d!==n(this,xo,ku)&&i.set(c,l,!1,!0)}),t===j.storeDeleteKeys&&r.forEach(({key:c,peerId:d})=>{d!==n(this,xo,ku)&&i.delete(c,!1,!0)}))})})};function ai(s){var t,e,r,i,a,o,c,d,l,h,p,f,T;return s?{media:{audio:{enabled:s.audioEnabled,trackId:(t=s.audioTrack)==null?void 0:t.id,permission:"mediaPermissions"in s?(e=s.mediaPermissions)==null?void 0:e.audio:null},video:{enabled:s.videoEnabled,trackId:(r=s.videoTrack)==null?void 0:r.id,permission:"mediaPermissions"in s?(i=s.mediaPermissions)==null?void 0:i.video:null},screenshare:{enabled:s.screenShareEnabled,permission:"mediaPermissions"in s?(a=s.mediaPermissions)==null?void 0:a.screenshare:null,audio:{enabled:(c=(o=s.screenShareTracks)==null?void 0:o.audio)==null?void 0:c.enabled,trackId:(l=(d=s.screenShareTracks)==null?void 0:d.audio)==null?void 0:l.id},video:{enabled:(p=(h=s.screenShareTracks)==null?void 0:h.video)==null?void 0:p.enabled,trackId:(T=(f=s.screenShareTracks)==null?void 0:f.video)==null?void 0:T.id}}}}:{}}var J0=Object.defineProperty,K0=Object.getOwnPropertyDescriptor,Da=(s,t,e,r)=>{for(var i=r>1?void 0:r?K0(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&J0(t,e,i),i};const z0=.8,Y0=1.2;var Yn,Qn,Mt,_i,Za,Vr,un,Ci,eo,Md,kf,Js,$o,Lr,wi,to,Ks,Dd,Fo,Iu,Od,If,Nd,Af,Sg;let gr=(Sg=class extends Ut{constructor(t,e,r,i){const a=t.getValue("logger");super(a);g(this,_i);g(this,Vr);g(this,Ci);g(this,Md);g(this,wi);g(this,Fo);g(this,Od);g(this,Nd);u(this,"id");u(this,"userId");u(this,"name");u(this,"picture");u(this,"isHost");u(this,"customParticipantId");u(this,"flags");u(this,"device");u(this,"videoTrack");u(this,"audioTrack");u(this,"screenShareTracks");u(this,"videoEnabled");u(this,"audioEnabled");u(this,"screenShareEnabled");u(this,"producers");u(this,"manualProducerConfig");g(this,Yn,void 0);u(this,"supportsRemoteControl",!1);g(this,Qn,void 0);u(this,"presetName");g(this,Mt,void 0);g(this,Js,void 0);g(this,$o,void 0);g(this,Lr,new Map);g(this,Ks,1);g(this,Dd,gh(t=>{if(!this.videoTrack)return;const{clientWidth:e,clientHeight:r}=t,{width:i,height:a}=this.videoTrack.getSettings();if(!i||!a)return;const o=a/r,c=i/e,d=Math.max(o,c);d>Y0&&n(this,Ks)===1?(m(this,Ks,0),n(this,Mt).getValue("peerSessionStore").emit(w.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:n(this,Ks)})):d<z0&&n(this,Ks)===0&&(m(this,Ks,1),n(this,Mt).getValue("peerSessionStore").emit(w.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:n(this,Ks)}))},2e3));m(this,Mt,t);const{id:o,userId:c,displayName:d,device:l,picture:h,isHost:p,flags:f,clientSpecificId:T,stageStatus:E,customParticipantId:C,audioMuted:_,audioTrack:I,videoEnabled:M=!1,videoTrack:x,producers:N,metadata:$}=e;this.id=o,this.userId=c,this.name=d,this.device=l,this.picture=h,this.isHost=p,this.flags=f,this.manualProducerConfig=FC,m(this,Qn,E!=null?E:"ON_STAGE"),this.customParticipantId=C!=null?C:T,this.audioEnabled=!_,this.audioTrack=I,this.videoEnabled=M,this.videoTrack=x,this.screenShareTracks={audio:void 0,video:void 0},this.producers=N!=null?N:[],this.presetName=$==null?void 0:$.preset_name,m(this,Yn,!1),m(this,Js,r),m(this,$o,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),V(this,Fo,Iu).call(this)}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return n(this,Qn)}get telemetry(){return n(this,Mt).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("Participant::setVideoEnabled::videoUpdate",{...ai(this)}),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(this.logger.info("Participant::setAudioEnabled::audioUpdate",{...ai(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",V(this,Fo,Iu)),n(this,Vr,un)&&(this.on("audioUpdate",V(this,Od,If)),this.on("screenShareUpdate",V(this,Nd,Af)))}async pin(){if(!n(this,Ci,eo))throw new b("Can`t pin participant without joining room","1205");if(!n(this,Js).permissions.pinParticipant)throw new b("You do not have permission to pin participants.","1201");return n(this,_i,Za).pinPeer(this.id)}async unpin(){if(!n(this,Ci,eo))throw new b("Can`t unpin participant without joining room","1205");if(!n(this,Js).permissions.pinParticipant)throw new b("You do not have permission to unpin participants.","1201");return n(this,_i,Za).pinPeer(null)}setIsPinned(t,e=!0){var i;m(this,Yn,t);const r=t?"pinned":"unpinned";(i=n(this,wi,to))==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}}),!n(this,Ci,eo))throw new b("Can`t disable participant audio without joining room","1205");if(n(this,Js).permissions.canDisableParticipantAudio)return n(this,_i,Za).disableAudio(t);throw this.logger.error("Participant::unauthorized_disable_audio",{participant:{id:t}}),new b("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}}),!n(this,Md,kf))throw new b("Can`t kick participant without joining room","1205");if(n(this,Js).permissions.kickParticipant){await n(this,Mt).getValue("peerSessionStore").emitAsync(w.KICK_PEER,{peerId:t});return}throw this.logger.error("Participant::unauthorized_kick",{participant:{id:t}}),new b("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}}),!n(this,Ci,eo))throw new b("Can`t disable participant video without joining room","1205");if(n(this,Js).permissions.canDisableParticipantVideo)return n(this,_i,Za).disableVideo(t);throw this.logger.error("Participant::unauthorized_disable_video",{participant:{id:t}}),new b("Unauthorized: User does not have permission to disable participant video.","1201")}async getPermissions(){return n(this,$o).getUserPermissions(this.userId)}setStageStatus(t){m(this,Qn,t),this.emit("stageStatusUpdate",this)}get isPinned(){return n(this,Yn)}registerVideoElement(t){var r,i,a,o;if(!t)return;let e;(i=(r=n(this,Lr).get(t))==null?void 0:r.observer)==null||i.disconnect(),"ResizeObserver"in window&&(e=new ResizeObserver(()=>n(this,Dd).call(this,t)),e.observe(t)),n(this,Lr).set(t,{observer:e}),this.updateVideo(t),(o=n(this,wi,to))==null||o.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(a=this.raised)!=null?a:!1)}deregisterVideoElement(t){var e,r,i,a;if(!t){(e=n(this,wi,to))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=n(this,Lr).get(t))==null?void 0:r.observer)==null||i.disconnect(),n(this,Lr).delete(t),(a=n(this,wi,to))==null||a.removeSource(this.id)}updateVideo(t){var e;if(this.videoEnabled){if(this.videoTrack==null)return;const r=(e=t.srcObject)==null?void 0:e.getTracks()[0];if((r==null?void 0:r.id)===this.videoTrack.id)return;const i=new MediaStream;i.addTrack(this.videoTrack),t.srcObject=i}else t.srcObject=void 0;t.style.display=this.videoEnabled?"block":"none"}},Yn=new WeakMap,Qn=new WeakMap,Mt=new WeakMap,_i=new WeakSet,Za=function(){return n(this,Mt).getValue("roomNodeClient")},Vr=new WeakSet,un=function(){return n(this,Mt).getValue("audioPlayback")},Ci=new WeakSet,eo=function(){return n(this,Mt).getValue("connectionHandler").mediaJoined},Md=new WeakSet,kf=function(){return n(this,Mt).getValue("connectionHandler").socketJoined},Js=new WeakMap,$o=new WeakMap,Lr=new WeakMap,wi=new WeakSet,to=function(){return n(this,Mt).getValue("pip")},Ks=new WeakMap,Dd=new WeakMap,Fo=new WeakSet,Iu=function(){Array.from(n(this,Lr).keys()).forEach(this.updateVideo)},Od=new WeakSet,If=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=n(this,Vr,un))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=n(this,Vr,un))==null||e.removeParticipantTrack(this.id)},Nd=new WeakSet,Af=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=n(this,Vr,un))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=n(this,Vr,un))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},Sg);Da([y.trace("Participant.disableAudio")],gr.prototype,"disableAudio",1);Da([y.trace("Participant.kick")],gr.prototype,"kick",1);Da([y.trace("Participant.disableVideo")],gr.prototype,"disableVideo",1);Da([y.trace("Participant.getPermissions")],gr.prototype,"getPermissions",1);Da([y.trace("Participant.setStageStatus")],gr.prototype,"setStageStatus",1);gr=Da([at("1200")],gr);class Xa extends vf{constructor(t,e){const{onAddEvent:r="participantJoined",onDeleteEvent:i="participantLeft",onClearEvent:a="participantsCleared"}=e!=null?e:{};super({onAddEvent:r,onDeleteEvent:i,onClearEvent:a},t)}add(t,e=!0){return this.has(t.id)&&Object.is(this.get(t.id),t)===!1&&this.delete(t.id),super.add(t,e)}clear(t=!0,e=!1){return super.clear(t,e)}delete(t,e=!0,r=!1){return super.delete(t,e,r)}}var xr;class Q0 extends Ia{constructor(e){super(e);g(this,xr,void 0);m(this,xr,new Map)}__set(e,r){return n(this,xr).set(e,r)}__clear(){return n(this,xr).clear()}get(e){return n(this,xr).get(e)}toArray(){return Array.from(n(this,xr).values())}}xr=new WeakMap;class X0{constructor(){u(this,"_orderedArray");u(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 Z0{constructor(){u(this,"_activeSpeakerPeers");u(this,"_compulsoryPeers");this._activeSpeakerPeers=new X0,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 Mf=new Z0;var eD=Object.defineProperty,tD=Object.getOwnPropertyDescriptor,Bt=(s,t,e,r)=>{for(var i=r>1?void 0:r?tD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&eD(t,e,i),i};const sD=["ACTIVE_GRID","PAGINATED","MANUAL"];var ve,Bo,Au,Ri,so,Xn,sd,bi,vt,yg;let mt=(yg=class extends Ut{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,Bo);g(this,Ri);g(this,Xn);u(this,"waitlisted");u(this,"joined");u(this,"active");u(this,"videoSubscribed");u(this,"audioSubscribed");u(this,"pinned");u(this,"all");g(this,ve,void 0);g(this,bi,void 0);g(this,vt,void 0);u(this,"rateLimitConfig",{maxInvocations:5,period:1});u(this,"viewMode");u(this,"currentPage");u(this,"lastActiveSpeaker");u(this,"selectedPeers",Mf);m(this,ve,t),m(this,bi,e),m(this,vt,r),this.waitlisted=new Xa(i),this.joined=new Xa(i),this.videoSubscribed=new Xa(i),this.audioSubscribed=new Xa(i),this.active=this.videoSubscribed,this.pinned=new Xa(i),this.all=new Q0(i),this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return n(this,ve).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return n(this,ve).getValue("telemetry")}setupEvents(){n(this,ve).getValue("peerSessionStore").on(w.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=n(this,ve).getValue("modules").e2ee)==null?void 0:r.enabled)!==!0&&this.emit("media_decode_error",{reason:`Got encrypted media for participantId ${e}, but encryption wasn't enabled in init.defaults`,code:"1702"})});const t=n(this,ve).getValue("audioPlayback");t&&this.audioSubscribed.on("participantLeft",e=>{t.removeParticipantTrack(e.id)})}get count(){return this.joined.size}get maxActiveParticipantsCount(){var t;return(t=n(this,ve))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new b("0 <= Max active participants count limit <= 24","1203");n(this,ve).setValue("maxPreferredStreams",t),n(this,Xn,sd)&&n(this,ve).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.selectedPeers.compulsoryPeers.length,e=this.joined.toArray().filter(r=>r.stageStatus==="ON_STAGE");return Math.ceil((e.length-t)/Math.max(this.maxActiveParticipantsCount-t,1))}return 0}acceptWaitingRoomRequest(t){var r,i;if(!n(this,Ri,so))throw new b("Can`t accept waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;return n(this,vt).acceptWaitingRoomRequest([e])}async acceptAllWaitingRoomRequest(t){const e=t.map(r=>{var i,a;return(a=(i=this.waitlisted.get(r))==null?void 0:i.userId)!=null?a:r});return n(this,vt).acceptWaitingRoomRequest(e)}async rejectWaitingRoomRequest(t){var r,i;if(!n(this,Ri,so))throw new b("Can`t reject waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;n(this,vt).rejectWaitingRoomRequest([e])}async setViewMode(t){if(this.logger.info("Participants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(r=>sD.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 b(`Invalid view mode: ${t}. Try ACTIVE_GRID, PAGINATED or MANUAL.`,"1207");if(this.viewMode===t){this.logger.info("Participants::setViewMode::view_mode_same_as_previous");return}this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,n(this,ve).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,n(this,ve).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,n(this,ve).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})}async subscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new b("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)))}),n(this,ve).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}async unsubscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new b("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!1},i.manualProducerConfig.screenshareAudio||this.audioSubscribed.delete(i.id)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!1},i.manualProducerConfig.screenshareVideo||this.videoSubscribed.delete(i.id)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!1},i.manualProducerConfig.audio||this.audioSubscribed.delete(i.id)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!1},i.manualProducerConfig.video||this.videoSubscribed.delete(i.id)))}),n(this,ve).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}getPeerIdsForCurrentPage(){this.logger.info("Participants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(c=>this.joined.has(c)),r=Array.from(this.pinned.keys()).filter(c=>!e.includes(c)),i=Array.from(this.joined.toArray().filter(c=>c.stageStatus==="ON_STAGE").map(c=>c.id)),a=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),o=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,i.slice(a,o))}async setPage(t){if(this.logger.info("Participants::set_page",{pageNavigation:{settingPage:t,viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),this.viewMode==="PAGINATED"){if(!Number.isInteger(t))throw this.logger.error("Participants::invalid_page_number"),new b(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`,"1202");this.currentPage=t,n(this,ve).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.viewMode,page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}}async disableAllAudio(t){if(this.logger.info("Participants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!n(this,Xn,sd))throw new b("Can`t disable all audio without joining room","1205");if(n(this,bi).permissions.canAllowParticipantAudio)return n(this,Bo,Au).muteAll(t);throw this.logger.error("Participants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new b("Unauthorized: User does not have permission to disable peer audio.","1201")}async disableAllVideo(){if(this.logger.info("Participants::disable_all_video"),!n(this,Xn,sd))throw new b("Can`t disable all video without joining room","1205");if(n(this,bi).permissions.canAllowParticipantVideo)return n(this,Bo,Au).muteAllVideo();throw this.logger.error("Participants::unauthorized_disable_all_video"),new b("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 n(this,ve).getValue("peerSessionStore").emitAsync(w.KICK_PEER,{peerId:t})}async kickAll(){if(this.logger.info("Participants::kick_all"),n(this,ve).getValue("viewType")!=="LIVESTREAM"&&!n(this,Ri,so))throw new b("Can`t kick all without joining room","1205");if(!n(this,bi).permissions.kickParticipant)throw this.logger.error("Participants::unauthorized_kick_all"),new b("Unauthorized: User does not have permission to kick peers.","1201");const e=n(this,ve).getValue("flagsmith").hasFeature(Y.PROPAGATE_KICK_ALL);n(this,vt).kickAll(e)}async broadcastMessage(t,e,r){if(this.logger.info("Participants::broadcastMessage"),!n(this,Ri,so))throw new b("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new b("`type` must be a non-empty string.","1209");if(r)if("meetingIds"in r)await n(this,vt).broadcastToMeetings(t,r.meetingIds,e);else{let i=[];"participantIds"in r?i=r.participantIds:i=this.joined.toArray().filter(a=>{var o;return(o=r.presetNames)==null?void 0:o.includes(a.presetName)}).map(a=>a.id),await n(this,vt).broadcastToPeers(t,i,e)}else await n(this,vt).broadcastMessage(t,e)}async getAllJoinedPeers(t,e,r){return(await n(this,vt).getRoomPeers(t,e,r)).peers.map(Sr.formatSocketPeerMessage)}async updatePermissions(t,e){const r=this.joined.toArray().filter(a=>t.includes(a.id)).map(a=>a.userId),i=[...new Set(r)];if(!i.length)throw new b("Cannot update permissions, no valid userIDs found","1204");n(this,vt).updatePermissions(i,e)}async getParticipantsInMeetingPreJoin(){return n(this,vt).getRoomPeersNonPaginated()}},ve=new WeakMap,Bo=new WeakSet,Au=function(){return n(this,ve).getValue("roomNodeClient")},Ri=new WeakSet,so=function(){var t;return((t=n(this,ve).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},Xn=new WeakSet,sd=function(){var t;return((t=n(this,ve).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},bi=new WeakMap,vt=new WeakMap,yg);Bt([y.trace("Participants.setViewMode")],mt.prototype,"setViewMode",1);Bt([y.trace("Participants.setPage")],mt.prototype,"setPage",1);Bt([y.trace("Participants.disableAllAudio")],mt.prototype,"disableAllAudio",1);Bt([y.trace("Participants.disableAllVideo")],mt.prototype,"disableAllVideo",1);Bt([y.trace("Participants.disablePeerAudio")],mt.prototype,"disableAudio",1);Bt([y.trace("Participants.disablePeerVideo")],mt.prototype,"disableVideo",1);Bt([y.trace("Participants.kickPeer")],mt.prototype,"kick",1);Bt([y.trace("Participants.kickAll")],mt.prototype,"kickAll",1);Bt([y.trace("Participants.broadcastMessage"),_t(Aa,"rateLimitConfig")],mt.prototype,"broadcastMessage",1);Bt([y.trace("Participants.getAllJoinedPeers"),_t({maxInvocations:10,period:60})],mt.prototype,"getAllJoinedPeers",1);Bt([y.trace("Participant.updatePermissions"),_t({maxInvocations:1e3,period:60})],mt.prototype,"updatePermissions",1);Bt([y.trace("Participants.getParticipantsInMeetingPreJoin")],mt.prototype,"getParticipantsInMeetingPreJoin",1);mt=Bt([at("1200")],mt);var rD=Object.defineProperty,iD=Object.getOwnPropertyDescriptor,an=(s,t,e,r)=>{for(var i=r>1?void 0:r?iD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&rD(t,e,i),i},zt,us,Zn,Eg;const Df=(Eg=class{constructor(s,t,e){u(this,"participants");u(this,"self");u(this,"selectedPeers",Mf);u(this,"maxSpatialLayerUpdates",new Map);u(this,"consumerPeerMap");u(this,"events");u(this,"roomSocketHandler");u(this,"context");u(this,"videoPeerConsumerMap",new Map);g(this,zt,{mode:"ACTIVE_GRID",page:0});g(this,us,!1);g(this,Zn,!1);u(this,"updateConsumerSpatialLayers",gh(()=>{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));u(this,"updateConsumers",async(s,t)=>{this.logger.info(`updateConsumers: Starting consumer updates - AddProducers: ${s.length}, RemoveProducers: ${t.length}, ConsumersSyncing: ${n(this,us)}`);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 mt(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,this.events=Ss,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(L.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),this.context.getValue("peerSessionStore").on(w.SOCKET_PEERS,async s=>{const t=this.context.getValue("flagsmith").hasFeature(Y.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(Y.DEBUG_SOCKET_JOIN)){const a=s&&(s==null?void 0:s.length)<20?{peers:JSON.stringify(s.map(o=>o.peerId))}:void 0;this.logger.info("events.selfJoinComplete",a)}s.forEach(({peerId:a,producerStates:o,capabilities:c})=>this.onParticipantMediaJoined(a,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(w.UPDATE_ACTIVE,{createAllConsumers:!0})}),this.context.getValue("peerSessionStore").on(w.MAX_SPATIAL_LAYER_CHANGE,({peerId:s,maxSpatialLayer:t})=>{const e=this.videoPeerConsumerMap.get(s);e&&(this.context.getValue("flagsmith").hasFeature(Y.DISABLE_LAYER_SWITCH)||(this.maxSpatialLayerUpdates.set(e,t),this.updateConsumerSpatialLayers()))}),this.context.getValue("peerSessionStore").on(w.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: ${n(this,us)}, 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(w.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(w.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 a=i.producers.find(o=>o.producerId===t);a&&(a.pause=e),r==="video"&&this.context.getValue("peerSessionStore").emit(w.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: ${n(this,us)}, 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 gr(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)),a=Math.max((s-1)*(this.maxPreferredStreams-e.length-r.length)),o=s*(this.maxPreferredStreams-e.length-r.length);return e.concat(r,i.slice(a,o))}selectActivePeers(s){const t=new Map,e=Array.from(this.participants.joined.toArray().filter(h=>h.stageStatus==="ON_STAGE").map(h=>(t.set(h.id,!0),h.id))),r=this.selectedPeers.peers,i=this.participants.pinned.toArray().reduce((h,p)=>(p.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(p.id):h.push(p.id),h),[]),a=this.self.stageStatus==="ON_STAGE"?1:0,o=s-a,c=new Set(r.concat(i).filter(h=>h!==this.self.id&&t.has(h)));let d=Array.from(c);const l=o-c.size;if(l>=0){const h=e.filter(p=>!c.has(p)&&p!==this.self.id).slice(0,l);d=Array.from(c).concat(h)}else d=d.slice(0,o);return d}updateMediaSubscribedMaps(s,t){const{page:e}=t!=null?t:{};s&&n(this,zt).mode!==s&&(n(this,zt).mode=s),e&&n(this,zt).page!==e&&(n(this,zt).page=e);const{mode:r,page:i}=n(this,zt);switch(r){case"PAGINATED":{if(!i)return;const a=this.selectPagePeers(i),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMap(this.participants.videoSubscribed,a),this.updateParticipantsMap(this.participants.audioSubscribed,o),this.logger.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:a});break}case"ACTIVE_GRID":{const a=this.selectActivePeers(this.participants.maxActiveParticipantsCount),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMapMinReplacement(this.participants.videoSubscribed,a),this.updateParticipantsMap(this.participants.audioSubscribed,o);break}case"MANUAL":break;default:throw new Error(`View mode ${s} not supported`)}}async scheduleSyncConsumers({source:s}){var e,r,i;const t=((e=n(this,zt))==null?void 0:e.mode)==="PAGINATED"&&!n(this,us)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${s}, ViewMode: ${(r=n(this,zt))==null?void 0:r.mode}, ConsumersSyncing: ${n(this,us)}, Delay: ${t}, Page: ${(i=n(this,zt))==null?void 0:i.page}`),setTimeout(()=>this.syncConsumers(),t)}async syncConsumers(){var o,c,d,l,h;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(n(this,us)){m(this,Zn,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),m(this,us,!0),m(this,Zn,!1);let s=[];this.participants.videoSubscribed.forEach(p=>{var E,C;const f=this.participants.joined.get(p.id),T=(C=(E=p.producers)==null?void 0:E.filter(_=>_.kind==="video"))!=null?C:[];f&&(T!=null&&T.length)&&T.forEach(_=>{var x,N,$,q;const I=((N=(x=f.manualProducerConfig)==null?void 0:x.video)!=null?N:!0)&&_.kind==="video"&&!_.screenShare,M=((q=($=f.manualProducerConfig)==null?void 0:$.screenshareVideo)!=null?q:!0)&&_.kind==="video"&&_.screenShare;(I||M)&&(_.pause||s.push(_))})}),this.participants.audioSubscribed.forEach(p=>{var E,C;const f=this.participants.joined.get(p.id),T=(C=(E=p.producers)==null?void 0:E.filter(_=>_.kind==="audio"))!=null?C:[];f&&(T!=null&&T.length)&&T.forEach(_=>{var x,N,$,q;const I=((N=(x=f.manualProducerConfig)==null?void 0:x.audio)!=null?N:!0)&&_.kind==="audio"&&!_.screenShare,M=((q=($=f.manualProducerConfig)==null?void 0:$.screenshareAudio)!=null?q:!0)&&_.kind==="audio"&&_.screenShare;(I||M)&&s.push(_)})}),s=$C(s,p=>p.producerId);const t=new Map;s.forEach(p=>{t.set(p.producerId,p)});const e=(l=this.roomNodeClient)==null?void 0:l.getConsumers(),r=s.filter(p=>!(e!=null&&e.has(p.producerId))),i=[];let a=Array.from((h=e==null?void 0:e.values())!=null?h:[]).map(p=>p.peerId);a=UC(a),a==null||a.forEach(p=>{var T;const f=this.participants.joined.get(p);if(!f){this.logger.warn(`Peer with ${p} doesn't exist in joined list but producers of it are being consumed.`);return}(T=f.producers)!=null&&T.length&&f.producers.forEach(E=>{const C=E.consumer&&e.has(E.consumer.id);!t.has(E.producerId)&&(e.has(E.producerId)||C)&&i.push(E)})}),this.logger.info(`syncConsumers: Computed changes - AddProducers: ${r.length} [${r.map(p=>p.producerId).join(", ")}], RemoveProducers: ${i.length} [${i.map(p=>p.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(p){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:p})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),m(this,us,!1)}n(this,Zn)&&(this.logger.info("syncConsumers: Resync required, calling syncConsumers again."),this.syncConsumers())}computeActivateParticipants(s,t){const e=s.map((i,a)=>({peerId:i,priority:a+1})),r=t==null?void 0:t.map((i,a)=>({peerId:i,priority:-(a+1)}));e.push(...r!=null?r:[]),e.length>0&&this.updateActiveParticipantsWithPriorities(e)}createParticipantObjFromSocketPeer(s){const t=Df.formatSocketPeerMessage(s);return new gr(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,a)=>a%2?"*":i).join("")}}),this.logger.info(`onParticipantMediaJoined: peer ${s} has joined media room. Processing.`),t.forEach(i=>{i.kind===Ns.AUDIO&&!i.screenShare?r.setAudioEnabled(!i.pause):i.kind===Ns.VIDEO&&!i.screenShare&&(r.setVideoEnabled(!i.pause),this.updatePipSource(r.id,!i.pause)),r.producers.push({...i,producingTransportId:i.producingTransportId,kind:i.kind===Ns.AUDIO?"audio":"video",producingPeerId:s,mimeType:i.mimeType})}),this.roomNodeClient.handlePeerCapabilities(s,e),this.context.getValue("flagsmith").hasFeature(Y.FORCE_VIDEO_CODEC)||this.roomNodeClient.shareWebcam(this.self.videoTrack),this.logger.info(`onParticipantMediaJoined: Emitting UPDATE_ACTIVE for peer ${s}`),this.context.getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}updateParticipantsMapMinReplacement(s,t){const e=Array.from(s.keys()),r=new Map(s),i=new Set(t),a=[];e.forEach((o,c)=>{(!i.has(o)||!this.participants.joined.get(o))&&a.push(c)}),t.forEach(o=>{if(s.get(o))return;if(e.length<t.length){e.push(o);return}const c=a.shift();e[c]=o}),a.forEach(o=>{e.splice(o,1)}),Array.from(s.keys()).forEach(o=>{s.delete(o,!i.has(o))}),e.forEach(o=>{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(L.joinRoom,({peer:s})=>{if(!s.waitlisted){const t=this.context.getValue("flagsmith").hasFeature(Y.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(L.leaveRoom,s=>{const{peerId:t}=s.peer;this.selectedPeers.delete(t,this.context),this.onParticipantLeave(t)}),this.context.getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.self.permissions.acceptWaitingRequests&&this.roomSocketHandler.getWaitingRoomRequests()}),this.self.permissions.on("permissionsUpdate",s=>{const{acceptWaitingRequests:t}=s;t!==void 0&&(t?this.roomSocketHandler.getWaitingRoomRequests():this.participants.waitlisted.clear())}),this.context.getValue("peerSessionStore").on(w.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(w.CONSUMER_PAUSED,({id:s})=>{this.processConsumerPaused(s)}),this.context.getValue("peerSessionStore").on(w.CONSUMER_RESUMED,({id:s})=>{this.processConsumerResumed(s)}),this.context.getValue("peerSessionStore").on(w.NEW_CONSUMER,({id:s})=>{this.processNewConsumer(s)}),this.context.getValue("peerSessionStore").on(w.CONSUMER_CLOSED,({id:s})=>{this.processConsumerClosed(s)}),this.context.getValue("peerSessionStore").on(w.ROOM_MESSAGE,async({payload:s,type:t,timestamp:e})=>{this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(w.MESSAGE,async({payload:s,type:t,timestamp:e})=>{t!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(w.LOW_CONSUMER_SCORE,({peerId:s,score:t,kind:e})=>{const r=this.participants.joined.get(s);r&&(r.emit("poorConnection",{score:t,kind:e}),this.participants.emit("poorConnection",{participantId:s,score:t,kind:e}))}),this.context.getValue("peerSessionStore").on(w.CONSUMER_SCORE_UPDATE,({score:s,kind:t,appData:e,peerId:r,scoreStats:i})=>{var c;const a=t==="video"&&((c=e==null?void 0:e.screenShare)!=null?c:!1),o=this.participants.joined.get(r);o&&(o.emit("mediaScoreUpdate",{kind:t,isScreenshare:a,score:s,participantId:r,scoreStats:i}),this.participants.emit("mediaScoreUpdate",{kind:t,isScreenshare:a,score:s,participantId:r,scoreStats:i}))}),this.context.getValue("peerSessionStore").onAsync(w.KICK_PEER,async({peerId:s})=>{const t=this.participants.joined.get(s);this.roomNodeClient.kick(s),await this.roomSocketHandler.kick(s),t?t.emit("kicked"):this.participants.joined.emit("kicked",{id:s})}),this.context.getValue("peerSessionStore").on(w.UPDATE_ACTIVE,async({viewMode:s,page:t,createAllConsumers:e}={viewMode:"ACTIVE_GRID",page:0,createAllConsumers:!1})=>{this.logger.info(`UPDATE_ACTIVE event received - viewMode: ${n(this,zt).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(w.UPDATE_STAGE_REQUESTS,{request:{displayName:s.name,userId:s.userId,peerId:s.id},add:!0})),this.context.getValue("peerSessionStore").emit(w.PEER_JOINED_INTERNAL,s)}async onParticipantLeave(s){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(w.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(w.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(w.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:e})}processMedia(s){var p;const t=this.roomNodeClient.getConsumers(),{peerId:e,kind:r,appData:i,track:a,producerId:o,rtpReceiver:c,paused:d,localId:l}=(p=t.get(s))!=null?p:{};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 h=i;return r==="video"&&h.screenShare!==!0&&this.videoPeerConsumerMap.set(e,s),this.logger.info("ParticipantController::processMedia",{consumer:{id:s,peerId:e,kind:r,appData:h,remotelyPaused:d,producerId:o}}),this.consumerPeerMap.set(s,{type:r,peerId:e,appData:h,remotelyPaused:d,producerId:o}),{peerId:e,kind:r,appData:h,remotelyPaused:d,track:a,producerId:o,rtpReceiver:c,localId:l}}processConsumerClosed(s){const{peerId:t,type:e,appData:r,remotelyPaused:i,producerId:a}=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:a}}),this.consumerPeerMap.delete(s),e==="video"&&r.screenShare!==!0&&this.videoPeerConsumerMap.delete(t),!o)return;const c=o.producers.find(l=>l.producerId===a);c&&(c.consumer={id:s,peerId:t,kind:void 0,appData:r,paused:i,producerId:a,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(w.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:l})})}processConsumerResumed(s){var f;const t=this.processMedia(s),{peerId:e,kind:r,appData:i,track:a,remotelyPaused:o,producerId:c,rtpReceiver:d,localId:l}=t;if(!e)return;this.logger.info("ParticipantController::processConsumerResumed",{consumer:{id:s,peerId:e,kind:r,appData:i,remotelyPaused:o,producerId:c}});const h=this.participants.joined.get(e);if(!h)return;const p=h.producers.find(T=>T.producerId===c);if(p&&(p.consumer={id:s,peerId:e,kind:r,appData:i,paused:o,producerId:c,rtpReceiver:d,localId:l}),i.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:d,track:a}),i.screenShare){r==="video"?h.screenShareTracks.video=a:r==="audio"&&(h.screenShareTracks.audio=a),h.setScreenShareEnabled(!0),(f=this.context)==null||f.getValue("callstats").consumerSharedMediaState(s,{screen:!0});return}r==="video"?(h.videoTrack=a,h.setVideoEnabled(!0),this.updatePipSource(h.id,!0),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!0})):r==="audio"&&(h.audioTrack=a,h.setAudioEnabled(h.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:h.audioEnabled}))}processConsumerPaused(s){this.logger.info(`ParticipantController::processConsumerPaused called for consumerId: ${s}`);const{peerId:t,kind:e,track:r,appData:i,remotelyPaused:a,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processConsumerPaused",{consumer:{id:s,peerId:t,kind:e,appData:i,remotelyPaused:a,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const h=l.producers.find(p=>p.producerId===o);h&&(h.consumer={id:s,peerId:t,kind:e,appData:i,paused:a,producerId:o,rtpReceiver:c,localId:d}),r&&i.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:r.id}),e==="video"?(l.videoTrack=r,l.setVideoEnabled(!1),this.updatePipSource(l.id,!1),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1})):e==="audio"&&(l.audioTrack=r,l.setAudioEnabled(l.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:l.audioEnabled}))}processNewConsumer(s){const{peerId:t,kind:e,remotelyPaused:r,track:i,appData:a,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processNewConsumer",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:a,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const h=l.producers.find(p=>p.producerId===o);if(h&&(h.consumer={id:s,peerId:t,kind:e,appData:a,paused:r,producerId:o,rtpReceiver:c,localId:d}),a.screenShare){e==="video"?l.screenShareTracks.video=i:e==="audio"&&(l.screenShareTracks.audio=i),(!r||this.self.permissions.isRecorder||this.context.getValue("flagsmith").hasFeature(Y.SCREEENSHARE_ERR_HACK))&&l.setScreenShareEnabled(!0),a.supportsRemoteControl&&(l.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:o,peerId:t,screenShare:!0,consumerId:s,consumerPeerId:this.self.id}),this.logger.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:a,producerId:o}});return}e==="video"?(l.videoTrack=i,r||(l.setVideoEnabled(!0),this.updatePipSource(l.id,!0)),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!r})):e==="audio"&&(l.audioTrack=i,r||l.setAudioEnabled(!0),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!r})),!r&&a.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:c,track:i})}static formatSocketPeerMessage(s){var e,r,i,a,o,c;if(!s)return;const t=vh(s.stageType);return{id:s.peerId,userId:s.userId,name:s.displayName,displayName:s.displayName,stageType:t,customParticipantId:s.customParticipantId,presetId:s.presetId,picture:s.displayPictureUrl,waitlisted:s.waitlisted,stageStatus:t,metadata:{preset_name:(e=s.flags)==null?void 0:e.presetName},recorderType:(r=s.flags)==null?void 0:r.recorderType,flags:{hiddenParticipant:(i=s.flags)==null?void 0:i.hiddenParticipant,hidden_participant:(a=s.flags)==null?void 0:a.hiddenParticipant,recorder:((o=s.flags)==null?void 0:o.recorderType)!==void 0&&((c=s.flags)==null?void 0:c.recorderType)!=="NONE"}}}async onSelectedPeers(s,t){this.participants.viewMode==="ACTIVE_GRID"&&this.computeActivateParticipants(s,t)}updateActiveParticipantsWithPriorities(s,t=!1){if(this.participants.viewMode==="MANUAL")return;if(!this.mediaJoined){this.logger.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.mediaJoined});return}s.forEach(r=>{this.selectedPeers.add(r.peerId,r.priority,this.context)});const e=this.selectedPeers.activeSpeakerPeers.at(0);e!==void 0&&e!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=e,this.participants.emit("activeSpeaker",{peerId:e,volume:1})),t&&this.context.getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}},zt=new WeakMap,us=new WeakMap,Zn=new WeakMap,Eg);let Sr=Df;an([y.trace("ParticipantController.setupEvents")],Sr.prototype,"setupEvents",1);an([y.trace("ParticipantController.setupEvents")],Sr.prototype,"setupEventsGlobal",1);an([y.trace("ParticipantController.processMedia")],Sr.prototype,"processMedia",1);an([y.trace("ParticipantController.processConsumerClosed")],Sr.prototype,"processConsumerClosed",1);an([y.trace("ParticipantController.processConsumerResumed")],Sr.prototype,"processConsumerResumed",1);an([y.trace("ParticipantController.processConsumerPaused")],Sr.prototype,"processConsumerPaused",1);an([y.trace("ParticipantController.processNewConsumer")],Sr.prototype,"processNewConsumer",1);const he=ys(uh().permissions);var B,ea,ta,Vd,lt,Rt;const Tn=class extends Ut{constructor(e,r,i,a=!1){const o=e.getValue("logger");super(o);g(this,lt);g(this,B,void 0);g(this,ea,void 0);g(this,ta,void 0);g(this,Vd,e=>{var l,h,p;const{chat:r,connectedMeetings:i,plugins:a,polls:o,media:c,...d}=e;if(r&&(r.private&&Er(n(this,B).chat.private,r.private),r.public&&Er(n(this,B).chat.public,r.public),this.emit("chatUpdate")),i&&Er(n(this,B).connectedMeetings,i),c){const f=E=>{switch(E){case Gr.NONE:return F.Allowed;case Gr.ALLOWED:return F.Allowed;case Gr.NOT_ALLOWED:return F.NotAllowed;case Gr.CAN_REQUEST:return F.CanRequest;default:return}},T={audio:void 0,video:void 0,screenshare:void 0};(l=c.audio)!=null&&l.canProduce&&(T.audio={canProduce:f(c.audio.canProduce)}),(h=c.video)!=null&&h.canProduce&&(T.video={canProduce:f(c.video.canProduce)}),(p=c.screenshare)!=null&&p.canProduce&&(T.screenshare={canProduce:f(c.screenshare.canProduce)}),Er(n(this,B).media,T)}a&&(Er(n(this,B).plugins,a),this.emit("pluginsUpdate")),o&&(Er(n(this,B).polls,o),this.emit("pollsUpdate")),Object.keys(d).length!==0&&Er(n(this,B),d),this.emit("permissionsUpdate",e)});if(!r)throw this.logger.error("PermissionPreset::load_preset_permissions_failed"),new b("Could not load preset permissions.","0904");m(this,ta,e),m(this,ea,i),m(this,B,r),a&&this.setupEvents()}setupEvents(){n(this,ta).getValue("peerSessionStore").on(w.UPDATE_PERMISSIONS,n(this,Vd))}static fromResponse(e,r,i){return new Tn(i,e,r,!0)}static default(e,r){return new Tn(e,he,r)}static init(e,r,i){let a;return i?a=new Tn(e,i,r,!0):a=new Tn(e,he,r),a}get mediaRoomType(){return"CF"}get stageEnabled(){var e;return((e=n(this,B))==null?void 0:e.stageEnabled)||n(this,ea)===lr.Webinar||n(this,ea)===lr.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=n(this,B))==null?void 0:e.acceptStageRequests)||((r=n(this,B))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,i;return((e=n(this,B))==null?void 0:e.stageAccess)===F.NotAllowed?F.NotAllowed:((r=n(this,B))==null?void 0:r.stageAccess)===F.CanRequest?F.CanRequest:((i=n(this,B))==null?void 0:i.stageAccess)===F.Allowed||n(this,B).media.audio.canProduce===F.Allowed||n(this,B).media.video.canProduce===F.Allowed||n(this,B).media.screenshare.canProduce===F.Allowed?F.Allowed:n(this,B).media.audio.canProduce===F.CanRequest||n(this,B).media.video.canProduce===F.CanRequest||n(this,B).media.screenshare.canProduce===F.CanRequest?F.CanRequest:F.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=n(this,B))==null?void 0:e.acceptWaitingRequests)!=null?r:he.acceptWaitingRequests}get requestProduceVideo(){var e,r,i;return((i=(r=(e=n(this,B))==null?void 0:e.media)==null?void 0:r.video)==null?void 0:i.canProduce)===F.CanRequest}get requestProduceAudio(){var e,r,i;return((i=(r=(e=n(this,B))==null?void 0:e.media)==null?void 0:r.audio)==null?void 0:i.canProduce)===F.CanRequest}get requestProduceScreenshare(){var e,r,i;return((i=(r=(e=n(this,B))==null?void 0:e.media)==null?void 0:r.screenshare)==null?void 0:i.canProduce)===F.CanRequest}get canAllowParticipantAudio(){var e,r;return(r=(e=n(this,B))==null?void 0:e.disableParticipantAudio)!=null?r:he.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=n(this,B))==null?void 0:e.canAcceptProductionRequests)!=null?r:he.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=n(this,B))==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=n(this,B))==null?void 0:e.kickParticipant)!=null?r:he.kickParticipant}get pinParticipant(){var e,r;return(r=(e=n(this,B))==null?void 0:e.pinParticipant)!=null?r:he.pinParticipant}get canRecord(){var e,r;return(r=(e=n(this,B))==null?void 0:e.canRecord)!=null?r:he.canRecord}get waitingRoomType(){var e,r;return(r=(e=n(this,B))==null?void 0:e.waitingRoomType)!=null?r:he.waitingRoomType}get waitingRoomBehaviour(){var e,r;return(r=(e=n(this,B))==null?void 0:e.waitingRoomType)!=null?r:he.waitingRoomType}get plugins(){var e,r;return(r=(e=n(this,B))==null?void 0:e.plugins)!=null?r:he.plugins}get polls(){var e,r;return(r=(e=n(this,B))==null?void 0:e.polls)!=null?r:he.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return n(this,B).media.audio.canProduce===F.CanRequest||n(this,B).media.video.canProduce===F.CanRequest||n(this,B).media.screenshare.canProduce===F.CanRequest}get canProduceVideo(){var r;const e=(r=n(this,B).media.video.canProduce)!=null?r:he.media.video.canProduce;return this.stageEnabled&&(n(this,lt,Rt)==="ACCEPTED_TO_JOIN_STAGE"||n(this,lt,Rt)==="ON_STAGE")&&e===F.CanRequest?F.Allowed:this.stageEnabled&&(n(this,lt,Rt)==="OFF_STAGE"||n(this,lt,Rt)==="REQUESTED_TO_JOIN_STAGE")&&e===F.Allowed?F.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var r;const e=(r=n(this,B).media.screenshare.canProduce)!=null?r:he.media.screenshare.canProduce;return this.stageEnabled&&(n(this,lt,Rt)==="ACCEPTED_TO_JOIN_STAGE"||n(this,lt,Rt)==="ON_STAGE")&&e===F.CanRequest?F.Allowed:this.stageEnabled&&(n(this,lt,Rt)==="OFF_STAGE"||n(this,lt,Rt)==="REQUESTED_TO_JOIN_STAGE")&&e===F.Allowed?F.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var r;const e=(r=n(this,B).media.audio.canProduce)!=null?r:he.media.audio.canProduce;return this.stageEnabled&&(n(this,lt,Rt)==="ACCEPTED_TO_JOIN_STAGE"||n(this,lt,Rt)==="ON_STAGE")&&e===F.CanRequest?F.Allowed:this.stageEnabled&&(n(this,lt,Rt)==="OFF_STAGE"||n(this,lt,Rt)==="REQUESTED_TO_JOIN_STAGE")&&e===F.Allowed?F.NotAllowed:e}get chatPublic(){var e,r,i;return(i=(r=(e=n(this,B))==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=n(this,B))==null?void 0:e.chat)==null?void 0:r.private)!=null?i:he.chat.private}get connectedMeetings(){var e,r;return(r=(e=n(this,B))==null?void 0:e.connectedMeetings)!=null?r:he==null?void 0:he.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=n(this,B))==null?void 0:e.hiddenParticipant)!=null?r:he.hiddenParticipant}get showParticipantList(){var e;return(e=n(this,B).showParticipantList)!=null?e:he.showParticipantList}get canChangeParticipantRole(){var e,r;return(r=(e=n(this,B))==null?void 0:e.canChangeParticipantPermissions)!=null?r:he.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var e,r;return(r=(e=n(this,B))==null?void 0:e.canChangeParticipantPermissions)!=null?r:he.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return n(this,B).media.audio.canProduce===F.Allowed||n(this,B).media.video.canProduce===F.Allowed||n(this,B).media.screenshare.canProduce===F.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var e;return(e=n(this,B).canEditDisplayName)!=null?e:!1}get maxScreenShareCount(){return 1}get isRecorder(){return n(this,B).isRecorder}get canSpotlight(){return n(this,B).canSpotlight}get canLivestream(){return n(this,B).canLivestream}get transcriptionEnabled(){return n(this,B).transcriptionEnabled}};let Mu=Tn;B=new WeakMap,ea=new WeakMap,ta=new WeakMap,Vd=new WeakMap,lt=new WeakSet,Rt=function(){return n(this,ta).getValue("stageStatus")};var Dt;class Of extends Ut{constructor(e,r){super(r);u(this,"localMediaHandler");g(this,Dt,void 0);m(this,Dt,e)}async updatePermission(){var d,l;const e=(h,p)=>{this.mediaPermissions[h]=p;const f={message:this.mediaPermissions[h],kind:h};p==="DENIED"?n(this,Dt).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_ERROR,f):n(this,Dt).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,f)};if(fe.getName()==="firefox")return;const r="microphone",i="camera",a=await((d=navigator==null?void 0:navigator.permissions)==null?void 0:d.query({name:r})),o=await((l=navigator==null?void 0:navigator.permissions)==null?void 0:l.query({name:i})),c=(h,p)=>{switch(p){case"granted":e(h,"ACCEPTED");break;case"denied":e(h,"DENIED");break;case"prompt":e(h,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};a&&(a.onchange=()=>c("audio",a.state)),o&&(o.onchange=()=>c("video",o.state))}async populateMediaPermissionsInCallstats({message:e,kind:r}){var i,a,o,c;switch(r){case"audio":{(i=n(this,Dt))==null||i.getValue("callstats").mediaPermission("AUDIO",e),(a=n(this,Dt))==null||a.getValue("callstats").mediaPermission("SPEAKER",e);break}case"video":{(o=n(this,Dt))==null||o.getValue("callstats").mediaPermission("VIDEO",e);break}case"screenshare":{(c=n(this,Dt))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",e);break}}}get peerId(){var e;return(e=n(this,Dt))==null?void 0:e.getValue("peerId")}async init(e={},r=!1,i=null){var a,o,c,d,l,h,p;if(fe.init(),i&&m(this,Dt,i),!this.localMediaHandler)try{let f=!0;if((a=i==null?void 0:i.getValue("defaults"))!=null&&a.mediaHandler)f=!1,this.localMediaHandler=i.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:T}=navigator;this.localMediaHandler=await T.init(e)}else this.localMediaHandler=new Ct(i,e.constraints,(o=i==null?void 0:i.getValue("defaults"))==null?void 0:o.isNonPreferredDevice,(c=i==null?void 0:i.getValue("defaults"))==null?void 0:c.autoSwitchAudioDevice);if(i==null||i.getValue("peerSessionStore").on(w.MEDIA_PERMISSION_UPDATE,async T=>{if(this.populateMediaPermissionsInCallstats({message:T.message,kind:T.kind}),T.message==="NOT_REQUESTED")switch(T==null?void 0:T.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",T)}),i==null||i.getValue("peerSessionStore").on(w.MEDIA_PERMISSION_ERROR,async T=>{const{kind:E,message:C,constraints:_}=T;this.populateMediaPermissionsInCallstats({message:C,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:C},constraints:_,mediaPermissionsErrors:{kind:E,message:C}}),this.emit("mediaPermissionError",T),this.emit("mediaPermissionUpdate",{message:C,kind:E})}),f){this.logger.info(`Setting up SelfMedia streams using media handler. audio:${(d=e==null?void 0:e.audio)!=null?d:!0} video:${(l=e==null?void 0:e.video)!=null?l:!0}`);const T=this.localMediaHandler.setupStreams({video:(h=e==null?void 0:e.video)!=null?h:!0,audio:(p=e==null?void 0:e.audio)!=null?p:!0});r||await T}}catch(f){this.logger.error("Self::init::Failed To Setup Streams",{error:{name:f.name,message:f.message}})}}set context(e){m(this,Dt,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})}}Dt=new WeakMap;var nD=Object.defineProperty,aD=Object.getOwnPropertyDescriptor,ft=(s,t,e,r)=>{for(var i=r>1?void 0:r?aD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&nD(t,e,i),i},sa,ut,ra,Ve,zs,si,$e,Je,ia,rd,De,xe,na,aa,Ho,Du,Pg;let We=(Pg=class extends Of{constructor(t,e,r,i,a){var c;const o=t.getValue("logger");super(t,o);g(this,zs);g(this,$e);g(this,ia);g(this,De);g(this,Ho);u(this,"name");u(this,"picture");u(this,"customParticipantId");u(this,"waitlistStatus");g(this,sa,void 0);g(this,ut,void 0);g(this,ra,void 0);u(this,"role");u(this,"userId");u(this,"organizationId");u(this,"supportsRemoteControl",!1);u(this,"device");g(this,Ve,void 0);u(this,"hidden",!1);u(this,"presetName");u(this,"roomState","init");g(this,na,new Set);g(this,aa,new Set);m(this,Ve,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",m(this,ut,r),m(this,sa,i),this.hidden=!1,m(this,ra,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=fe.isElectron(),this.device=fe.getDeviceInfo(),this.presetName=a,this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),V(this,Ho,Du).call(this)}get telemetry(){return n(this,Ve).getValue("telemetry")}get stageStatus(){return n(this,Ve).getValue("stageStatus")}get producers(){var t,e;return Array.from((e=(t=n(this,$e,Je).getProducers())==null?void 0:t.values())!=null?e:[])}get id(){return this.peerId}get peerId(){return n(this,Ve).getValue("peerId")}static async __init__(t,e,r,i,a,o=!1){var f,T,E,C,_,I;let c=(T=(f=t.getValue("defaults"))==null?void 0:f.audio)!=null?T:!0,d=(C=(E=t.getValue("defaults"))==null?void 0:E.video)!=null?C:!0;r.canProduceAudio!=="ALLOWED"&&(c=!1),r.canProduceVideo!=="ALLOWED"&&(d=!1);const l=new We(t,e,r,i,a),h=f0(i.mediaConstraints);Er(h,(_=t.getValue("defaults"))==null?void 0:_.mediaConfiguration);const p=(I=t.getValue("defaults"))==null?void 0:I.mediaHandler;return p&&(p.context=t),await l.init({audio:c,video:d,constraints:h},o,t),l.setupEvents(),l}cleanupEvents(){this.removeAllListeners("videoUpdate"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("VIDEO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_LIST_UPDATED"),this.localMediaHandler.removeAllListeners("SCREENSHARE_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("SCREENSHARE_ENDED"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_SILENT"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_AUDIO"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_VIDEO"),n(this,ut).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",V(this,Ho,Du));const t=n(this,ia,rd);t&&t.onError(e=>{this.emit("autoplayError",e)}),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::AUDIO_TRACK_CHANGE",{...ai(this)}),n(this,De,xe)&&this.audioEnabled)try{await n(this,$e,Je).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",{...ai(this)}),n(this,De,xe)&&this.rawVideoTrack===void 0)this.logger.info("Self::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&n(this,De,xe))try{const e=await n(this,$e,Je).shareWebcam(this.videoTrack);e&&e.id!==this.videoTrack.id&&n(this,Ve).getValue("flagsmith").hasFeature(Y.EXP_RESHARE)&&await n(this,$e,Je).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=n(this,ia,rd))==null||r.setSpeakerDevice(e.deviceId))}),this.localMediaHandler.on("DEVICE_LIST_UPDATED",e=>{this.emit("deviceListUpdate",e)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",async()=>{if(!n(this,De,xe)){this.logger.error("Self.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await n(this,$e,Je).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",{...ai(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",{...ai(this)})}),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{var e;(e=n(this,Ve))==null||e.getValue("callstats").mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",async()=>{var e;n(this,De,xe)&&await n(this,$e,Je).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(e=n(this,Ve))==null||e.getValue("callstats").videoOff()}),n(this,ut).on("permissionsUpdate",e=>{var r,i,a;(r=e==null?void 0:e.media)!=null&&r.audio&&n(this,ut).canProduceAudio!==F.Allowed&&(this.disableAudio(),this.logger.info(`Disabled audio due to dynamic preset change: canProduceAudio: ${this.permissions.canProduceAudio}`)),(i=e==null?void 0:e.media)!=null&&i.video&&n(this,ut).canProduceVideo!==F.Allowed&&(this.disableVideo(),this.logger.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(a=e==null?void 0:e.media)!=null&&a.screenshare&&n(this,ut).canProduceScreenshare!==F.Allowed&&(this.disableScreenShare(),this.logger.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return n(this,ut)}get config(){return n(this,sa)}get roomJoined(){var t;return n(this,sa).viewType===lr.Livestream&&this.stageStatus!=="ON_STAGE"?((t=n(this,Ve).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:n(this,De,xe)}setName(t){if(!t)throw new b("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!==F.NotAllowed&&!(n(this,ut).canProduceAudio===F.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if((e=n(this,Ve))==null||e.getValue("callstats").audioOn(),await this.localMediaHandler.enableAudio(t),n(this,De,xe)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await n(this,$e,Je).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(n(this,ut).canProduceVideo!==F.NotAllowed&&!(n(this,ut).canProduceVideo===F.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if((e=n(this,Ve))==null||e.getValue("callstats").videoOn(),await this.localMediaHandler.enableVideo(t),n(this,De,xe)&&this.stageStatus==="ON_STAGE")try{await n(this,$e,Je).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",{...ai(this)})}}async updateVideoConstraints(t){if(!this.localMediaHandler.updateVideoConstraints)throw new b("Unsupported","1102");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){if(!n(this,De,xe))throw new b("Can`t enable screenshare without joining room","1105");if(n(this,ut).canProduceScreenshare!==F.NotAllowed&&!(n(this,ut).canProduceScreenshare===F.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 n(this,$e,Je).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 b("Unsupported","1102");await this.localMediaHandler.updateScreenshareConstraints(t)}async disableAudio(){var t;this.audioEnabled&&(this.localMediaHandler.disableAudio(),n(this,De,xe)&&n(this,$e,Je).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),(t=n(this,Ve))==null||t.getValue("callstats").audioOff())}async disableVideo(){var t;this.videoEnabled&&(await this.localMediaHandler.disableVideo(),n(this,De,xe)&&await n(this,$e,Je).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(t=n(this,Ve))==null||t.getValue("callstats").videoOff())}async disableScreenShare(){this.screenShareEnabled&&(await this.localMediaHandler.disableScreenShare(),n(this,De,xe)&&await n(this,$e,Je).disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var i;m(this,ra,t);const r=t?"pinned":"unpinned";(i=n(this,zs,si))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return n(this,ra)}async pin(){if(!n(this,De,xe))throw new b("Can`t pin participants without joining room","1105");return this.show(),n(this,$e,Je).pinPeer(this.id)}async unpin(){if(!n(this,De,xe))throw new b("Can`t unpin participants without joining room","1105");return n(this,$e,Je).pinPeer(null)}async hide(){if(!n(this,De,xe))throw new b("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})}show(){if(!n(this,De,xe))throw new b("Can`t toggle participant tile without joining room","1105");this.hidden=!1,this.emit("toggleTile",{hidden:this.hidden})}async setDevice(t){var r,i,a;if(!t)throw new b("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||((a=e==null?void 0:e.speaker)==null?void 0:a.deviceId)===t.deviceId)&&(this.logger.warn("Self.setDevice.setting_to_in_use_device",{devices:[t]}),n(this,Ve).getValue("flagsmith").hasFeature(Y.SKIP_SETTING_IN_USE_DEVICE)))throw new b("Cannot set device currently in use","1106");switch(t.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(t,{saveDevicePreference:!0})}catch(o){n(this,De,xe)&&await n(this,$e,Je).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){n(this,De,xe)&&await n(this,$e,Je).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=n(this,ia,rd))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?n(this,na).add(t):n(this,aa).add(t),this.updateVideo(t),e||(i=n(this,zs,si))==null||i.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(r=this.raised)!=null?r:!1))}deregisterVideoElement(t,e=!1){if(!t){n(this,zs,si).removeSource(this.id);return}t.srcObject=void 0,e?n(this,na).delete(t):(n(this,aa).delete(t),n(this,zs,si).removeSource(this.id))}updateVideo(t,e=!1){var r,i,a;if(this.videoEnabled){if(this.videoTrack==null)return;const o=(r=t.srcObject)==null?void 0:r.getTracks()[0];if((o==null?void 0:o.id)===this.videoTrack.id)return;const c=new MediaStream;c.addTrack(this.videoTrack),t.srcObject=c,e||(i=n(this,zs,si))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(a=n(this,zs,si))==null||a.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},sa=new WeakMap,ut=new WeakMap,ra=new WeakMap,Ve=new WeakMap,zs=new WeakSet,si=function(){return n(this,Ve).getValue("pip")},$e=new WeakSet,Je=function(){return n(this,Ve).getValue("roomNodeClient")},ia=new WeakSet,rd=function(){return n(this,Ve).getValue("audioPlayback")},De=new WeakSet,xe=function(){var t;return((t=n(this,Ve).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},na=new WeakMap,aa=new WeakMap,Ho=new WeakSet,Du=function(){Array.from(n(this,aa)).forEach(t=>this.updateVideo(t,!1)),Array.from(n(this,na)).forEach(t=>this.updateVideo(t,!0))},Pg);ft([y.trace("Self.cleanupEvents")],We.prototype,"cleanupEvents",1);ft([y.trace("Self.setupEvents")],We.prototype,"setupEvents",1);ft([y.trace("Self.setupTracks")],We.prototype,"setupTracks",1);ft([y.trace("Self.destructMediaHandler")],We.prototype,"destructMediaHandler",1);ft([y.trace("Self.removeDocumentEventListeners")],We.prototype,"removeDocumentEventListeners",1);ft([vr.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"Self.toggleAudio",timeout:3e3}),y.trace("Self.enableAudio")],We.prototype,"enableAudio",1);ft([vr.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"Self.toggleVideo",timeout:3e3}),y.trace("Self.enableVideo")],We.prototype,"enableVideo",1);ft([y.trace("Self.updateVideoConstraints")],We.prototype,"updateVideoConstraints",1);ft([y.trace("Self.enableScreenShare"),vr.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3})],We.prototype,"enableScreenShare",1);ft([y.trace("Self.updateScreenshareConstraints")],We.prototype,"updateScreenshareConstraints",1);ft([vr.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"Self.toggleAudio",timeout:3e3}),y.trace("Self.disableAudio")],We.prototype,"disableAudio",1);ft([vr.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"Self.toggleVideo",timeout:3e3}),y.trace("Self.disableVideo")],We.prototype,"disableVideo",1);ft([vr.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3}),y.trace("Self.disableScreenShare")],We.prototype,"disableScreenShare",1);ft([y.trace("Self.setDevice")],We.prototype,"setDevice",1);We=ft([at("1100")],We);class Ch extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Ch)}}class wh extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,wh)}}var qo;class Ou{constructor(t,e=!1){u(this,"pendingTasks",new Map);u(this,"nextTaskId",0);u(this,"stopping",!1);g(this,qo,void 0);this.log=e,m(this,qo,{info:e&&t?t.info:()=>{}})}get size(){return this.pendingTasks.size}async push(t,e,r){if(e=e!=null?e:t.name,typeof t!="function")throw new TypeError("given task is not a function");if(e)try{Object.defineProperty(t,"name",{value:e})}catch(i){}return new Promise((i,a)=>{const o={id:this.nextTaskId++,task:t,metadata:r,name:e,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:c=>{if(o.completed)return;o.completed=!0,this.pendingTasks.delete(o.id),i(c);const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)},reject:c=>{if(!o.completed&&(o.completed=!0,this.pendingTasks.delete(o.id),a(c),!this.stopping)){const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)}}};this.pendingTasks.set(o.id,o),this.pendingTasks.size===1&&this.execute(o)})}stop(){this.stopping=!0;for(const t of this.pendingTasks.values())t.reject(new Ch);this.stopping=!1}remove(t){const e=Array.from(this.pendingTasks.values())[t];e&&e.reject(new wh)}get(t){return Array.from(this.pendingTasks.values())[t]}dump(){const t=Date.now();let e=0;return Array.from(this.pendingTasks.values()).map(r=>({idx:e++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:t-r.enqueuedAt,executionTime:r.executedAt?t-r.executedAt:0}))}async execute(t){if(t.executedAt)throw new Error("task already being executed");t.executedAt=Date.now();try{const e=this.pendingTasks.size,r=await t.task(),i=Date.now();n(this,qo).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)}}}qo=new WeakMap;function oD(s,t){const e=new Error(t);return e.name=s,e}class yo extends Error{constructor(t){super(t),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,yo):this.stack=new Error(t).stack}}class Pt extends Error{constructor(t){super(t),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Pt):this.stack=new Error(t).stack}}class oi extends Error{constructor(t){super(t),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Pt):this.stack=new Error(t).stack}}const Qp=s=>new Promise(t=>setTimeout(t,s));async function Nf(s,t){return new Promise(async(e,r)=>{const{strategy:i,maxRetryCount:a,delayTime:o}={strategy:"linear",maxRetryCount:3,delayTime:10,...t};let c=0,d,l=!1;const h=p=>{l=!0,r(p)};for(;c<a;){try{const p=await s(c,h);return e(p)}catch(p){if(d=p,l)break;if(c<a)i==="linear"?await Qp(o*(c+1)):i==="exponential"&&await Qp(o*(c+Math.max(0,c-1)));else break}c+=1}return r(d)})}function cD(s){return s.map(t=>({channels:t.channels,clockRate:t.clockRate,mimeType:t.mimeType,sdpFmtpLine:t.sdpFmtpLine}))}function dD(s){return s.map(t=>({uri:t.uri}))}function Gc(s){return{codecs:cD(s.codecs),headerExtensions:dD(s.headerExtensions?s.headerExtensions:[])}}function lD(s){const t=RTCRtpReceiver.getCapabilities("audio"),e=RTCRtpReceiver.getCapabilities("video"),r=RTCRtpSender.getCapabilities("audio"),i=RTCRtpSender.getCapabilities("video");s&&(e.codecs=e.codecs.filter(({mimeType:d})=>s===d),i.codecs=i.codecs.filter(({mimeType:d})=>s===d));const a={audio:Gc(t),video:Gc(e)};return{sender:{audio:Gc(r),video:Gc(i)},receiver:a}}var je;class uD{constructor(t){g(this,je,void 0);u(this,"events");m(this,je,t),this.events=Ss}async joinRoom(t,e,r,i=!1,a=null){const o={roomUuid:t,displayName:e,prejoined:i,capabilities:r};return a&&(o.location=a),(await n(this,je).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:Vw.toBinary(o),timeout:5e3})).payload}async connectTransport(t){const e=(await n(this,je).sendMessagePromise(this.events.createWebRTCTransport,dw.toBinary(t))).payload,{transportId:r,description:i,producerIds:a}=Wm.fromBinary(e),o={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:r,answer:o,producerIds:a}}async produce(t){var a,o;const e=(await n(this,je).sendMessagePromise(this.events.produce,Yw.toBinary(t))).payload,r=DR.fromBinary(e);return{answer:{sdp:(a=r==null?void 0:r.description)==null?void 0:a.sdp,type:(o=r==null?void 0:r.description)==null?void 0:o.type},producerId:r.producerId}}async consume(t){const e=(await n(this,je).sendMessagePromise(this.events.consume,jw.toBinary(t))).payload,{consumerIdsMap:{map:r},description:i}=AR.fromBinary(e);return{consumerStateMap:r,sessionDescription:i}}async closeProducer(t){const e=(await n(this,je).sendMessagePromise(this.events.closeProducer,rR.toBinary(t))).payload,{description:r}=$R.fromBinary(e);return r}async closeConsumer(t){return(await n(this,je).sendMessagePromise(this.events.closeConsumer,nR.toBinary(t))).payload}async updateConsumersSimulcastConfig(t){return(await n(this,je).sendMessagePromise(this.events.updateConsumersSimulcastConfig,Kw.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},i=(await n(this,je).sendMessagePromise(this.events.hostControlPeer,uR.toBinary(r))).payload;if(!i)return!1;const{status:a}=WR.fromBinary(i);return a==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await n(this,je).sendMessagePromise(this.events.hostControlAllPeers,pR.toBinary(e))).payload;if(!r)return!1;const{status:i}=KR.fromBinary(r);return i==="success"}async kickAll(){const t={propagateKickAcrossRooms:!1};n(this,je).sendMessagePromise(L.kickAll,Ym.toBinary(t))}async kickPeer(t){n(this,je).sendMessagePromise(L.kick,tf.toBinary(t))}async changeDisplayName(t){const e=(await n(this,je).sendMessagePromise(this.events.changeDisplayName,dR.toBinary(t))).payload;if(!e)return!1;const{status:r}=YR.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await n(this,je).sendMessagePromise(this.events.selfJoinComplete,xw.toBinary(t))).payload;return pu.fromBinary(e)}async audioActivity(t){n(this,je).sendMessage(this.events.audioActivity,uw.toBinary(t))}}je=new WeakMap;var Pn=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s.CLOSED="closed",s))(Pn||{}),jo;class Nl extends nt.EventEmitter{constructor(e){super();g(this,jo,void 0);m(this,jo,e),this.setMaxListeners(1/0)}get logger(){return n(this,jo).getValue("logger")}safeEmit(e,...r){const i=this.listenerCount(e);try{return this.emit(e,...r)}catch(a){return this.logger.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:a}),Boolean(i)}}async safeEmitAsPromise(e,...r){const i={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,i,...r)}async safeEmitAsPromiseWithTimeout(e,r,...i){return new Promise((a,o)=>{setTimeout(o,r,"event request timeout");try{this.emit(e.toString(),...i,a,o)}catch(c){this.logger.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:c}),o(c)}})}}jo=new WeakMap;class Rh extends Nl{constructor(){super(...arguments);u(this,"_sendWebStream",new MediaStream);u(this,"_sendScreenShareStream",new MediaStream);u(this,"_direction");u(this,"pc");u(this,"_transportReady",!1);u(this,"_mapMidTransceiver",new Map);u(this,"enableHighBitrate",!1);u(this,"enableStereo",!1);u(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:a,proprietaryConstraints:o,onTrackHandler:c}){this.logger.debug("HandlerInterface::init()"),this._direction=e,this.pc=new RTCPeerConnection({iceServers:r||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a},o),c&&this.pc.addEventListener("track",d=>{c(d)}),this._addEventListeners()}async connect(){this.pc.addTransceiver("audio",{direction:"sendonly"}),this.pc.addTransceiver("video",{direction:"sendonly"});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 a=i.sender.getParameters();a.encodings.forEach((o,c)=>{c<=r?o.active=!0:o.active=!1}),await i.sender.setParameters(a)}async setRtpEncodingParameters(e,r){this._assertSendDirection(),this.logger.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const a=i.sender.getParameters();a.encodings.forEach((o,c)=>{a.encodings[c]={...o,...r}}),await i.sender.setParameters(a)}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}_addEventListeners(){this.pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this.pc.addEventListener("iceconnectionstatechange",()=>{switch(this.pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),this.logger.debug("negotiationneeded")}),this.pc.addEventListener("icegatheringstatechange",()=>{switch(this.pc.iceGatheringState){case"gathering":this.logger.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":this.logger.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("icecandidateerror",e=>{this.logger.warn("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),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 bh extends Rh{static createFactory(t){return()=>new bh(t)}get name(){return"Chrome74"}init({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:i,proprietaryConstraints:a,onTrackHandler:o}){this._direction=t,this.pc=new RTCPeerConnection({iceServers:e||[],iceTransportPolicy:r||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...i},a),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection();const a=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e});if(!navigator.isReactNative){this.logger.debug("creating new transceiver");const d=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`senders available params: ${JSON.stringify(d)}`);const l=[];r&&r.length&&r.forEach(h=>{var f;const p=d.codecs.find(T=>T.mimeType.includes(h.name));if(h.parameters){this.logger.debug(`codecOption.parameters:${JSON.stringify(h.parameters)}`);const T=((f=p.sdpFmtpLine)==null?void 0:f.split(";"))||[];T.push(...h.parameters);const E=Array.from(new Set(T).values());p.sdpFmtpLine=E.join(";")}l.push(p)}),this.logger.info(`selected codecs: ${JSON.stringify(l)}`),a.setCodecPreferences(l)}const o=await this.pc.createOffer();if(await this.pc.setLocalDescription(o),r&&r.findIndex(({name:d})=>d==="opus")>=0){const{enableDtx:d,enableStereo:l}=this,h=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=${h}`),o.sdp+=`a=rtcp-fb:111 nack\r
|
|
@@ -10,4 +10,4 @@ ${this.message}`;try{let d=a&&!!i;r&&r.endsWith("00")&&i&&(d=!0),d&&i.error("Cli
|
|
|
10
10
|
maxEnergy: ${n(this,Br)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!n(this,tr)||i<n(this,tr))&&m(this,tr,i),(!n(this,Br)||i>n(this,Br))&&m(this,Br,i),{energy:(i-n(this,tr))/(n(this,Br)-n(this,tr))*10||0,isVoice:r})},hc=new WeakSet,Bu=function(t){return t<5},il=new WeakSet,Zf=function(t=n(this,Ui)){var r;if(!n(this,ms)||!t){n(this,sr).getValue("flagsmith").hasFeature(Y.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${n(this,ms)}`);return}const e={producerId:n(this,ms),energy:Math.round(t),silent:V(r=go,hc,Bu).call(r,t)};m(this,Ea,e.silent),this.reportRequest(e)},nl=new WeakSet,eT=function(t){const e=Math.log10(t);return Math.round(e)},g(io,hc),g(io,nl);const RD=(s=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const e=new window.MediaStreamTrackGenerator({kind:"audio"}),r=e.writable.getWriter(),i=48e3,a=128,o=1;let c=0,d=null;const l=async()=>{try{const f=new Float32Array(a*o),T=new window.AudioData({format:"f32",sampleRate:i,numberOfFrames:a,numberOfChannels:o,timestamp:c,data:f});c+=a/i*1e6,await r.ready,await r.write(T)}catch(f){d&&clearInterval(d),r.releaseLock(),e.writable.abort()}};d=window.setInterval(l,100);const p=new MediaStream([e]).getAudioTracks()[0];return p.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),e.writable.abort()}),Object.assign(p,{fakeTracks:"fakeTracks:fakeAudioTrack"}),p.enabled=s,p}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 a=e.createMediaStreamDestination();i.connect(a),r.start();const o=a.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=s,o):void 0}catch(e){return}},bD=(s=!1)=>{var a,o;const t=new MediaStream().getVideoTracks()[0],e=document.createElement("canvas");e.height=(a=t==null?void 0:t.getSettings().height)!=null?a: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 kD=Object.defineProperty,ID=Object.getOwnPropertyDescriptor,ae=(s,t,e,r)=>{for(var i=r>1?void 0:r?ID(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&kD(t,e,i),i};const wt=["video/VP9","video/VP8"];var pc,gc,rt,H,Pa,ht,$i,Fi,Bi,mc,Xt,ir,fc,Hi,qi,pt,yt,Hr,hn,al,sT,ol,rT,cl,iT,Tc,Hu,dl,ru,nT,ll,aT,ul,oT,hl,cT,ze,ot,ji,no,pl,dT,gl,lT,ml,uT;const tT=(ru=class{constructor(s,t){g(this,Hr);g(this,al);g(this,ol);g(this,cl);g(this,Tc);g(this,ll);g(this,ul);g(this,hl);g(this,ze);g(this,ji);g(this,pl);g(this,gl);g(this,ml);u(this,"context");u(this,"authToken");u(this,"e2ee");g(this,pc,void 0);g(this,gc,void 0);g(this,rt,void 0);g(this,H,void 0);g(this,Pa,void 0);g(this,ht,void 0);g(this,$i,void 0);g(this,Fi,void 0);g(this,Bi,void 0);g(this,mc,void 0);g(this,Xt,null);g(this,ir,void 0);g(this,fc,void 0);g(this,Hi,void 0);g(this,qi,void 0);g(this,pt,void 0);g(this,yt,void 0);var r,i;this.context=s;const{socket:e}=t;this.mediaJoined=!1,m(this,Hi,new Map([["video/VP9",new Set],["video/VP8",new Set]])),m(this,qi,new Map([["video/VP9",new Set],["video/VP8",new Set]])),m(this,rt,e),m(this,$i,!1),m(this,H,new PD(s,e)),m(this,ht,n(this,H).events),m(this,ir,new Set),m(this,pt,new Map),m(this,Fi,!1),m(this,Bi,new Ou(s.getValue("logger"))),m(this,yt,new io(this.context,n(this,H).socketHandler.audioActivity.bind(n(this,H).socketHandler))),this.e2ee=(i=(r=s.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?i:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),m(this,mc,gh(async()=>{if(!n(this,Hr,hn).mediaJoinAttempted)return;const{roomJoined:a}=await this.joinRoom(n(this,gc),n(this,pc),!0,!0);a&&(this.context.getValue("peerSessionStore").emit(w.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return n(this,Hr,hn).mediaJoined}set mediaJoined(s){n(this,Hr,hn).mediaJoined=s}reset(){n(this,H).closeAllProducers(),n(this,H).closeAllConsumers(),n(this,pt).clear(),n(this,ir).clear(),m(this,Xt,null),n(this,Bi).stop(),n(this,H).stopAllTransports(),n(this,H).reset(),m(this,Bi,new Ou)}async joinRoom(s,t,e=!1,r=!1,i={}){n(this,Hr,hn).mediaJoinAttempted=!0,m(this,$i,!0),e&&this.reset();try{return await n(this,Bi).push(()=>V(this,al,sT).call(this,s,t,r,i),"joinRoom")}catch(a){return this.logger.error("Error in room joining process",{error:a}),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_FAILED),{roomJoined:!1,error:a}}}async initializeConnection(s,t,e=!1,r={}){return n(this,Xt)?n(this,Xt):(m(this,Xt,(async()=>{try{await V(this,Tc,Hu).call(this,s,t,e,r)}catch(i){throw m(this,Xt,null),i}})()),n(this,Xt))}getConsumers(){return n(this,H).consumers}getProducers(){return n(this,H).producers}async leaveRoom(){n(this,H).stopAllTransports(),m(this,Fi,!1),n(this,Hr,hn).mediaJoinAttempted=!1;const s={closeRoom:!1};n(this,rt).sendMessagePromise(n(this,ht).leaveRoom,$w.toBinary(s)).then(e=>{var r;(r=bR.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():n(this,H).createConsumers(s)}async closeConsumers(s){if(!s.length)return;const t=s.reduce((e,r)=>{const i=n(this,H).producerIdToConsumerIdMap.get(r.producerId);return i?(e.push(i),e):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),e)},[]);await n(this,H).closeConsumers(t)}async _shareWebcam(s,t){var p,f;const e=t==="video/VP9"?ce.WEBCAM:ce.WEBCAM_BACKUP,r=V(this,ze,ot).call(this,e);if(r){const T=await r;if(n(this,H).producers.has(T)){const E=n(this,H).producers.get(T);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(wt.filter(T=>T!==t)),a=V(this,ml,uT).call(this,s,i),o=ba(this.context,"disableSimulcast"),c=(f=(p=this.context)==null?void 0:p.getValue("overrides"))==null?void 0:f.simulcastConfig;!(o||c&&c.disable)&&this.context.getValue("flagsmith").hasFeature(Y.ENABLE_CF_SIMULCAST)?(this.logger.info("Simulcast enabled for SFU: CF"),a.encodings=g0(this.context,s)):this.logger.info("Simulcast disabled for webcam producer, SFU: CF"),this.context.getValue("flagsmith").hasFeature(Y.TRACK_HINT)&&(a.track.contentHint=this.context.getValue("flagsmith").getValue(Y.TRACK_HINT));const l=()=>{this.logger.info("Disabling video due to the producer closure"),n(this,pt).delete(e)},h=n(this,H).createProducer(a,l);return V(this,ji,no).call(this,e,h.then(T=>T.id)),h.then(T=>T.track)}async shareWebcam(s){var r;if(s===void 0)return null;const t=(r=this.context.getValue("flagsmith").getValue(Y.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=wt.filter(i=>{var a,o;return((o=(a=n(this,Pa).sender)==null?void 0:a.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===i))>=0&&n(this,qi).get(i).size>0});return e.length===0&&e.push(wt[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:fe.isElectron()},stopTracks:!1},i=()=>{this.logger.info("Disabling screenShare due to the producer closure"),n(this,pt).delete(ce.SCREENSHARE_VIDEO),n(this,pt).delete(ce.SCREENSHARE_AUDIO)},a=n(this,H).createProducer(r,i);V(this,ji,no).call(this,ce.SCREENSHARE_VIDEO,a.then(c=>c.id));let o;if(e){const c={track:e,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:fe.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},d=()=>{};o=n(this,H).createProducer(c,d),V(this,ji,no).call(this,ce.SCREENSHARE_AUDIO,o.then(l=>l.id))}await Promise.all([a,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()}async shareMic(s){try{if(s===void 0)throw new Pt("track undefined");const t=V(this,ze,ot).call(this,ce.MIC);if(t){const a=await t;if(n(this,H).producers.has(a)){const o=n(this,H).producers.get(a);if(!o.closed){await o.replaceTrack({track:s}),await this.resumeMic(),n(this,yt)&&(n(this,yt).audioTrack=s,n(this,yt).producerId=a,n(this,yt).start());return}await n(this,H).closeProducer(a,{stopTrack:!1})}await this.shareMic(s);return}const e=V(this,gl,lT).call(this,s),r=()=>{n(this,pt).delete(ce.MIC)},i=n(this,H).createProducer(e,r);V(this,ji,no).call(this,ce.MIC,i.then(a=>a.id)),await i.then(a=>{n(this,yt)&&(n(this,yt).audioTrack=a.track,n(this,yt).producerId=a.id,n(this,yt).start())})}catch(t){throw new b(t)}}async pauseMic(){var r;const s=await V(this,ze,ot).call(this,ce.MIC),t=n(this,H).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=n(this,yt))==null||r.stop();const e={producerId:t.id,pause:!0};n(this,rt).sendMessage(n(this,ht).toggleProducer,Fc.toBinary(e))}async pauseWebcam(){const s=await V(this,ze,ot).call(this,ce.WEBCAM),t=await V(this,ze,ot).call(this,ce.WEBCAM_BACKUP),e=n(this,H).producers.get(s),r=n(this,H).producers.get(t);if(!e&&!r){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const i=a=>{const o={producerId:a.id,pause:!0};n(this,rt).sendMessage(n(this,ht).toggleProducer,Fc.toBinary(o))};e&&(e.pause(),i(e)),r&&(r.pause(),i(r))}async resumeMic(){const s=await V(this,ze,ot).call(this,ce.MIC),t=n(this,H).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(w.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};n(this,rt).sendMessage(n(this,ht).toggleProducer,Fc.toBinary(e))}async resumeWebcam(s=ce.WEBCAM){const t=await V(this,ze,ot).call(this,s),e=n(this,H).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(w.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};n(this,rt).sendMessage(n(this,ht).toggleProducer,Fc.toBinary(r))}async disableWebcam(s){const t=s==="video/VP9"?ce.WEBCAM:ce.WEBCAM_BACKUP,e=await V(this,ze,ot).call(this,t);V(this,pl,dT).call(this,t),e&&await n(this,H).closeProducer(e)}async disableMic(){var t;const s=await V(this,ze,ot).call(this,ce.MIC);s&&await n(this,H).closeProducer(s),(t=n(this,yt))==null||t.stop(),n(this,pt).delete(ce.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=await V(this,ze,ot).call(this,ce.SCREENSHARE_VIDEO),t=await V(this,ze,ot).call(this,ce.SCREENSHARE_AUDIO);s&&await n(this,H).closeProducer(s),t&&await n(this,H).closeProducer(t),n(this,ir).clear(),n(this,pt).delete(ce.SCREENSHARE_VIDEO),n(this,pt).delete(ce.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(s,t){if(s){const e=await V(this,ze,ot).call(this,ce.WEBCAM),r=await V(this,ze,ot).call(this,ce.WEBCAM_BACKUP);await n(this,H).closeProducer(e,{stopTrack:!1}),await n(this,H).closeProducer(r,{stopTrack:!1}),this.shareWebcam(s)}if(t){const e=await V(this,ze,ot).call(this,ce.SCREENSHARE_VIDEO);await n(this,H).closeProducer(e,{stopTrack:!1}),this.shareScreen({video:t})}}async changeDisplayName(s,t){const e={displayName:s,participantId:t!=null?t:this.peerId};if(!await n(this,H).socketHandler.changeDisplayName(e))throw new Error("failed to change display name!")}kick(s){const t={peerIds:[s]};n(this,H).socketHandler.kickPeer(t)}kickAll(){n(this,H).socketHandler.kickAll()}async muteAll(s){if(!await n(this,H).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await n(this,H).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(s){if(!await n(this,H).socketHandler.hostControlForPeer(s,"audio"))throw new Error("failed to mute given participant")}async disableVideo(s){if(!await n(this,H).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 n(this,rt).sendMessagePromise(n(this,ht).globalPinPeer,Zw.toBinary(t))}catch(e){this.logger.error("Error in pinning peer:",{error:e})}}validateScreenShare(s){return this.peerId===s.peerId&&n(this,H).producers.get(s.producerId)&&n(this,ir).add(s.consumerPeerId),n(this,ir).size}async switchConsumersToLayer(s,t){const e=s.map(r=>this.getConsumers().get(r));n(this,H).switchConsumersToLayer(e,t)}async handleSocketEvents(){n(this,rt).on(n(this,ht).peerProducerCreateBroadcast,({payload:s})=>{var t,e;if(this.mediaJoined)try{const{participantId:r,producerState:i}=rb.fromBinary(s);if(r===this.peerId)return;if(i!=null&&i.mimeType||(i.mimeType=i.kind===Ns.AUDIO?"audio/opus":"video/VP8"),i.kind===Ns.VIDEO&&!i.screenShare&&((e=(t=n(this,Pa).receiver)==null?void 0:t.video)==null?void 0:e.codecs.findIndex(a=>a.mimeType===wt[0]))>=0&&n(this,Hi).get(wt[0]).has(r)&&i.mimeType!==wt[0]){this.logger.warn(`Ignoring producer: ${i.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${i}`),this.context.getValue("peerSessionStore").emit(w.NEW_PRODUCER,{peerId:r,producer:{...i,kind:i.kind===Ns.AUDIO?"audio":"video",producingPeerId:r}})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),n(this,rt).on(n(this,ht).peerProducerToggleBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,initiatorParticipantId:e,producerState:{kind:r,pause:i,producerId:a,screenShare:o}}=bp.fromBinary(s);if(o)return;const c=r===Ns.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${t}, producerId: ${a}, kind:${c}, paused:${i} payload: ${JSON.stringify(bp.fromBinary(s))}`),t===this.peerId&&e!==this.peerId&&i&&this.context.getValue("peerSessionStore").emit(c==="audio"?w.MUTE_SELF:w.MUTE_SELF_VIDEO),t===this.peerId)return;this.context.getValue("peerSessionStore").emit(w.PRODUCER_TOGGLE,{peerId:t,producerId:a,paused:i,kind:c}),Array.from(this.getConsumers().values()).filter(l=>l.producerId===a).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(w.CONSUMER_PAUSED,{id:l.id})):(l.resume(),this.context.getValue("peerSessionStore").emit(w.CONSUMER_RESUMED,{id:l.id})))})}catch(t){this.logger.error("error in producer toggle broadcast handler",{error:t})}}),n(this,rt).on(n(this,ht).peerLeaveBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t}=gu.fromBinary(s);if(t===this.peerId)return;this.logger.info(`peer left broadcast:${t}`),n(this,ir).delete(t),n(this,H).consumers.forEach(e=>{e.peerId===t&&e.close()}),this.context.getValue("peerSessionStore").emit(w.PEER_CLOSED,{id:t})}catch(t){this.logger.error("error in peer left broadcast",{error:t})}}),n(this,rt).on(n(this,ht).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=ab.fromBinary(s);if(t===this.peerId)return;this.logger.info(`producer closed broadcast:${t}`),this.context.getValue("peerSessionStore").emit(w.PRODUCER_CLOSED,{peerId:t,producerId:e});const r=n(this,H).producerIdToConsumerIdMap.get(e);if(!r){this.logger.warn(`no consumer found for producer:${e}`);return}this.logger.info(`closing consumer ${r}, producer id: ${e}`),n(this,H).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),n(this,H).producerIdToConsumerIdMap.delete(e),this.context.getValue("peerSessionStore").emit(w.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})}}),n(this,rt).on(n(this,ht).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!n(this,$i)&&!n(this,Fi)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_DISCONNECTED),n(this,mc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(s=>{s.forEach((t,e)=>{const r=n(this,H).consumers.get(e);r&&this.context.getValue("peerSessionStore").emit(w.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(n(this,H).producers.values()).find(i=>i.id===e);r&&this.context.getValue("peerSessionStore").emit(w.PRODUCER_SCORE_UPDATE,{id:e,kind:r.kind,appData:r.appData,score:t.score,scoreStats:t})})})}handlePeerCapabilities(s,t){var e,r,i,a;for(let o=0;o<=wt.length;o+=1){const c=wt[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===wt.length-1){n(this,qi).get(c).add(s);break}}for(let o=0;o<=wt.length;o+=1){const c=wt[o];if(((a=(i=t==null?void 0:t.sender)==null?void 0:i.video)==null?void 0:a.codecs.findIndex(d=>d.mimeType===c))>=0||o===wt.length-1){n(this,Hi).get(c).add(s);break}}}handlePeerLeaving(s){this.context.getValue("flagsmith").hasFeature(Y.FORCE_VIDEO_CODEC)||(n(this,Hi).forEach(t=>t.delete(s)),n(this,qi).forEach((t,e)=>{t.delete(s),!(t.size!==0||e===wt[0])&&this.disableWebcam(e)}))}},pc=new WeakMap,gc=new WeakMap,rt=new WeakMap,H=new WeakMap,Pa=new WeakMap,ht=new WeakMap,$i=new WeakMap,Fi=new WeakMap,Bi=new WeakMap,mc=new WeakMap,Xt=new WeakMap,ir=new WeakMap,fc=new WeakMap,Hi=new WeakMap,qi=new WeakMap,pt=new WeakMap,yt=new WeakMap,Hr=new WeakSet,hn=function(){return this.context.getValue("connectionHandler")},al=new WeakSet,sT=async function(s,t,e,r){m(this,gc,s);try{return n(this,Xt)?await n(this,Xt):await V(this,Tc,Hu).call(this,s,t,e,r),V(this,cl,iT).call(this,t),{roomJoined:await V(this,ol,rT).call(this)}}catch(i){return this.logger.error("Failed to complete room join",{error:i}),{roomJoined:!1,error:i}}finally{m(this,Xt,null)}},ol=new WeakSet,rT=async function(){try{this.mediaJoined=!0;const{roomState:s}=await n(this,H).socketHandler.notifySelfJoinComplete();return m(this,pc,s.roomUuid),m(this,Fi,!0),m(this,$i,!1),!0}catch(s){return this.logger.error("Error completing room join",{error:s}),this.mediaJoined=!1,!1}},cl=new WeakSet,iT=function(s){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:{...fe.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)},Tc=new WeakSet,Hu=async function(s,t,e,r){var i,a;try{(a=n(this,fc))!=null||m(this,fc,V(i=tT,dl,nT).call(i));const o=V(this,ll,aT).call(this);await V(this,ul,oT).call(this,s,t,e,o),await n(this,H).setupTransports({send:!0,recv:!0}),await V(this,hl,cT).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},dl=new WeakSet,nT=function(){const{ipInfo:s}=it();if(!(s!=null&&s.loc))return;const[t,e]=s.loc.split(",").map(parseFloat);return{latitude:t,longitude:e}},ll=new WeakSet,aT=function(){var e;const s=(e=this.context.getValue("flagsmith").getValue(Y.FORCE_VIDEO_CODEC))==null?void 0:e.toString(),t=lD(s);return m(this,Pa,t),t},ul=new WeakSet,oT=async function(s,t,e,r){await Nf(async(i,a)=>{if(!n(this,rt).isConnected){a(new Error("Socket is not connected"));return}i>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${i}`});try{await n(this,H).socketHandler.joinRoom(t,s,r,e,n(this,fc))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}},{delayTime:1e3,strategy:"exponential",maxRetryCount:15})},hl=new WeakSet,cT=async function(s){if(!(!this.context.getValue("flagsmith").hasFeature(Y.PRECREATE_PRODUCERS)||!s))try{const e=[];if(s.canProduceVideo===F.Allowed&&e.push(this.shareWebcam(bD(!1))),s.canProduceAudio===F.Allowed){const r=RD(!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})}},ze=new WeakSet,ot=function(s){return n(this,pt).get(s)},ji=new WeakSet,no=function(s,t){return n(this,pt).set(s,t)},pl=new WeakSet,dT=function(s){return n(this,pt).delete(s)},gl=new WeakSet,lT=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},ml=new WeakSet,uT=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}},g(ru,dl),ru);let re=tT;ae([y.trace("MediaNodeClient.reset",{country:y.location.country})],re.prototype,"reset",1);ae([y.trace("MediaNodeClient.joinRoom")],re.prototype,"joinRoom",1);ae([y.trace("MediaNodeClient.leaveRoom")],re.prototype,"leaveRoom",1);ae([y.trace("MediaNodeClient.activatePeers")],re.prototype,"activatePeers",1);ae([y.trace("MediaNodeClient.createConsumers")],re.prototype,"createConsumers",1);ae([y.trace("MediaNodeClient.closeConsumers")],re.prototype,"closeConsumers",1);ae([y.trace("MediaNodeClient._shareWebcam")],re.prototype,"_shareWebcam",1);ae([y.trace("MediaNodeClient.shareWebcam")],re.prototype,"shareWebcam",1);ae([y.trace("MediaNodeClient.shareScreen")],re.prototype,"shareScreen",1);ae([y.trace("MediaNodeClient.shareMic")],re.prototype,"shareMic",1);ae([y.trace("MediaNodeClient.pauseMic")],re.prototype,"pauseMic",1);ae([y.trace("MediaNodeClient.pauseWebcam")],re.prototype,"pauseWebcam",1);ae([y.trace("MediaNodeClient.resumeMic")],re.prototype,"resumeMic",1);ae([y.trace("MediaNodeClient.resumeWebcam")],re.prototype,"resumeWebcam",1);ae([y.trace("MediaNodeClient.disableWebcam")],re.prototype,"disableWebcam",1);ae([y.trace("MediaNodeClient.disableMic")],re.prototype,"disableMic",1);ae([y.trace("MediaNodeClient.disableScreenShare")],re.prototype,"disableScreenShare",1);ae([y.trace("MediaNodeClient.muteSelf")],re.prototype,"muteSelf",1);ae([y.trace("MediaNodeClient.resetVideoProducers")],re.prototype,"resetVideoProducers",1);ae([y.trace("MediaNodeClient.changeDisplayName")],re.prototype,"changeDisplayName",1);ae([y.trace("MediaNodeClient.kickPeer")],re.prototype,"kick",1);ae([y.trace("MediaNodeClient.kickAllPeers")],re.prototype,"kickAll",1);ae([y.trace("MediaNodeClient.muteAll")],re.prototype,"muteAll",1);ae([y.trace("MediaNodeClient.muteAllVideo")],re.prototype,"muteAllVideo",1);ae([y.trace("MediaNodeClient.disableAudio")],re.prototype,"disableAudio",1);ae([y.trace("MediaNodeClient.disableVideo")],re.prototype,"disableVideo",1);ae([y.trace("MediaNodeClient.pinPeer")],re.prototype,"pinPeer",1);ae([y.trace("MediaNodeClient.validateScreenShare")],re.prototype,"validateScreenShare",1);function hT(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 pT(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 AD=Object.defineProperty,MD=Object.getOwnPropertyDescriptor,on=(s,t,e,r)=>{for(var i=r>1?void 0:r?MD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&AD(t,e,i),i},Gi,fs,Q,gt,bt,_g;const gT=(_g=class{constructor(s,t,e,r){g(this,gt);u(this,"self");u(this,"authToken");g(this,Gi,void 0);u(this,"viewType");g(this,fs,void 0);g(this,Q,void 0);const{socket:i}=e,a=s.getValue("authToken");this.self=t,m(this,Q,s),this.viewType=r,this.authToken=a,m(this,Gi,i),m(this,fs,e),this.setupEvents()}get peerId(){return n(this,Q).getValue("peerId")}get telemetry(){return n(this,Q).getValue("telemetry")}get logger(){return n(this,Q).getValue("logger")}get mediaJoined(){return n(this,Q).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const a=it(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await We.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");if(navigator.product!=="ReactNative"){const h=!s.getValue("flagsmith").hasFeature(Y.PRECALL_BANDWIDTH_TEST);setTimeout(async()=>{const p=await d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(p)}),s.getValue("callstats").devices("AUDIO",p==null?void 0:p.filter(f=>f.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",p==null?void 0:p.filter(f=>f.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",p==null?void 0:p.filter(f=>f.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:fe.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:await a.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:qm(s),skipConnectivityChecks:h}),l.info("Callstats:: initialized")}catch(f){l.error("Callstats:: initialization failed",{error:f})}},0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new gT(s,d,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:a,screenShareTracks:o}=this.self;if(e.canProduceAudio===F.Allowed&&r)try{await n(this,gt,bt).shareMic(s),this.self.audioEnabled||n(this,gt,bt).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===F.Allowed&&i)try{const d=await n(this,gt,bt).shareWebcam(t);d&&d.id!==t.id&&n(this,Q).getValue("flagsmith").hasFeature(Y.EXP_RESHARE)&&await n(this,gt,bt).shareWebcam(d),this.self.videoEnabled||n(this,gt,bt).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===F.Allowed&&a)try{await((c=n(this,gt,bt))==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){n(this,Q).getValue("callstats").callEnded(),n(this,gt,bt).reset(),s&&await this.joinRoom(s)}setupEvents(){n(this,Q).getValue("peerSessionStore").on(w.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),n(this,Q).getValue("peerSessionStore").on(w.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),n(this,Q).getValue("peerSessionStore").on(w.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),n(this,Q).getValue("peerSessionStore").on(w.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,Q).getValue("peerSessionStore").on(w.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),n(this,Q).getValue("peerSessionStore").on(w.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&n(this,Q).getValue("flagsmith").hasFeature(Y.REFRESH_ID_ON_DISCONNECTION)&&(t=ur.v4()),n(this,Gi).updateURL(t),n(this,Q).getValue("telemetry").resetPeerId(t),it().setHeader("tracing-id",t),cr.remapContext(t,n(this,Q)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),n(this,Q).getValue("peerSessionStore").on(w.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,fs).on(L.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),n(this,fs).on(Xc.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&n(this,Q).getValue("peerSessionStore").emit(w.UPDATE_PERMISSIONS,t.patch)})}),n(this,fs).on(L.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),n(this,fs).on(L.kick,()=>{this.kickHandler({kickType:"kick"})}),n(this,fs).on(L.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),n(this,Q).getValue("peerSessionStore").onAsync(w.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),n(this,Q).getValue("peerSessionStore").on(w.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var a;const i=(a=e==null?void 0:e.screenShare)!=null?a:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),n(this,Q).getValue("peerSessionStore").on(w.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),n(this,Q).getValue("callstats").audioOff())}),n(this,Q).getValue("peerSessionStore").on(w.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),n(this,Q).getValue("callstats").videoOff())}),n(this,Q).getValue("peerSessionStore").onAsync(w.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),n(this,Q).getValue("peerSessionStore").on(w.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await n(this,fs).joinRoom(this.self);n(this,fs).socket.flush();const e=vh(t.stageType);if(n(this,Q).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}await this.joinMediaRoom(s),n(this,Q).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=n(this,Q).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),n(this,Q).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),n(this,Q).notify("stageStatus");try{(e=n(this,Gi))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}pT(n(this,Q)),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var a,o,c;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=n(this,Q).getAllValues();try{if(e===lr.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}hT(n(this,Q),{socket:n(this,Gi),peerId:t})}const{canProduceAudio:d,canProduceVideo:l,canProduceScreenshare:h}=this.self.permissions,{roomJoined:p,error:f}=(o=await((a=n(this,gt,bt))==null?void 0:a.joinRoom(this.self.name,r,s,s,{canProduceAudio:d,canProduceVideo:l,canProduceScreenshare:h})))!=null?o:{};if(!p)throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:f}),f;i==="ON_STAGE"&&await this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(d){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:d}),new b(`${(c=d==null?void 0:d.message)!=null?c:"could not connect to media servers"}`,"0002")}}async leaveMediaRoom(s){const t=n(this,Q).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===lr.Webinar)&&n(this,gt,bt)&&(n(this,gt,bt).mediaJoined&&s!=="disconnected"&&await n(this,gt,bt).leaveRoom(),!(s==="stageLeft"&&t===lr.Livestream)&&(n(this,gt,bt).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()}},Gi=new WeakMap,fs=new WeakMap,Q=new WeakMap,gt=new WeakSet,bt=function(){return n(this,Q).getValue("roomNodeClient")},_g);let Zr=gT;on([y.trace("SelfController.resetSelf")],Zr.prototype,"resetSelf",1);on([y.trace("SelfController.setupEvents")],Zr.prototype,"setupEvents",1);on([y.trace("SelfController.joinRoom")],Zr.prototype,"joinRoom",1);on([y.trace("SelfController.leaveRoom")],Zr.prototype,"leaveRoom",1);on([y.trace("SelfController.joinMediaRoom")],Zr.prototype,"joinMediaRoom",1);on([y.trace("SelfController.leaveMediaRoom")],Zr.prototype,"leaveMediaRoom",1);on([y.trace("SelfController.init")],Zr,"init",1);var vc;class DD{constructor(t){g(this,vc,void 0);m(this,vc,t)}on(t,e){let r;t===L.roomPeerCount?r=Ap.fromBinary.bind(Ap):r=Bp.fromBinary.bind(Bp),n(this,vc).on(t,({payload:i})=>{if(t===L.roomPeerCount&&!i)return;const a=r(i);e(a)})}}vc=new WeakMap;var Sc,yc;class OD{constructor(t,e){g(this,Sc,void 0);g(this,yc,void 0);m(this,Sc,e),m(this,yc,t)}get logger(){return n(this,yc).getValue("logger")}on(t,e){let r,i;switch(t){case L.transcript:{r=Jl.fromBinary.bind(Jl),i=Jl.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}n(this,Sc).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}Sc=new WeakMap,yc=new WeakMap;var ND=Object.defineProperty,VD=Object.getOwnPropertyDescriptor,Ah=(s,t,e,r)=>{for(var i=r>1?void 0:r?VD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ND(t,e,i),i},nr,_a;class Vl{constructor(t,e){g(this,nr,void 0);g(this,_a,void 0);m(this,nr,e),m(this,_a,t)}get logger(){return n(this,_a).getValue("logger")}get telemetry(){return n(this,_a).getValue("telemetry")}getPolls(){return n(this,nr).sendMessagePromise($s.getPolls)}createPoll(t,e,r=!1,i=!1){const a={anonymous:r,hideVotes:i,question:t,options:e};return n(this,nr).sendMessage($s.createPoll,qA.toBinary(a))}votePoll(t,e){const r={index:e,pollId:t};return n(this,nr).sendMessage($s.votePoll,GA.toBinary(r))}on(t,e){let r,i;switch(t){case $s.updatePoll:case $s.createPoll:case $s.votePoll:{r=Zl.fromBinary.bind(Zl),i=Zl.create();break}}n(this,nr).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){n(this,nr).removeListeners(t)}}nr=new WeakMap,_a=new WeakMap;Ah([y.trace("PollSocketHandler.getPolls")],Vl.prototype,"getPolls",1);Ah([y.trace("PollSocketHandler.createPoll")],Vl.prototype,"createPoll",1);Ah([y.trace("PollSocketHandler.votePoll")],Vl.prototype,"votePoll",1);var LD=Object.defineProperty,xD=Object.getOwnPropertyDescriptor,UD=(s,t,e,r)=>{for(var i=r>1?void 0:r?xD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&LD(t,e,i),i},Nt;class mT{constructor(t,e){u(this,"socket");g(this,Nt,void 0);m(this,Nt,t),this.socket=e,this.handleSocketEvents(),n(this,Nt).setValue("roomSocketHandler",this)}get telemetry(){return n(this,Nt).getValue("telemetry")}get logger(){return n(this,Nt).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}async joinRoom(t){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(L.joinRoom,Vb.toBinary(e));try{const{peer:a}=dn.fromBinary((await r).payload);n(this,Nt).getValue("connectionHandler").socketJoined=!0,n(this,Nt).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_ROOM_JOINED,{peer:a});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return n(this,Nt).getValue("peerSessionStore").emit(w.ROOM_STATE,d),n(this,Nt).getValue("peerSessionStore").emit(w.SOCKET_PEERS,l),{peer:a}}catch(a){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:a}),new b("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,a)}}async getAllAddedParticipants(){try{return Sk.fromBinary((await this.socket.sendMessagePromise(L.getAllAddedParticipants)).payload).participants.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}async getRoomPeers(t,e,r){let i;try{const a={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise(L.getRoomPeersInfo,wb.toBinary(a));i=Kl.fromBinary(o.payload)}catch(a){this.logger.error("getRoomPeers::binary_decode_error",{error:a})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise(L.getRoomPeersInfo);t=Kl.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getStagePeers(){let t;try{const e=await this.socket.sendMessagePromise(L.getRoomPeersInfo);t=Kl.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getPeerInfo(t){let e;try{const r=await this.socket.sendMessagePromise(L.getPeerInfo,Zm.toBinary({peerId:t}));e=dn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=Mp.create();try{const e=await this.socket.sendMessagePromise(L.getRoomInfo);t=Mp.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=Vp.create();try{const e=await this.socket.sendMessagePromise(L.getRoomStageState);t=Vp.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(L.broadcastMessage,Ya.toBinary(r))}async broadcastToMeetings(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(L.broadcastToEntity,Ya.toBinary(i))}async broadcastToPeers(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(L.broadcastToEntity,Ya.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(L.leaveRoom,xb.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(L.kick,tf.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(L.kickAll,Ym.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(L.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(L.acceptWaitingRoomRequests,wk.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(L.denyWaitingRoomRequests,bk.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Xc.updateUserPreset,sI.toBinary(r))}handleSocketEvents(){this.socket.on(L.broadcastMessage,({payload:t})=>{try{const e=Ya.fromBinary(t);n(this,Nt).getValue("peerSessionStore").emit(w.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on(L.broadcastToEntity,({payload:t})=>{try{const e=Ya.fromBinary(t);n(this,Nt).getValue("peerSessionStore").emit(w.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case L.joinRoom:case L.leaveRoom:case L.kick:case L.kickAll:{r=dn.fromBinary.bind(dn),i=dn.create();break}case L.getWaitingRoomRequests:{r=(a,o)=>a?Np.fromBinary(a,o):{requests:[]},i=Np.create();break}case L.recordingPaused:case L.recordingStarted:case L.recordingStopped:{r=jp.fromBinary.bind(jp);break}case Xc.updateUserPreset:{r=Lp.fromBinary.bind(Lp);break}case Ss.peerJoinedBroadcast:case Rr.peerJoinedBroadcast:{r=wp.fromBinary.bind(wp);break}case Ss.selfJoinComplete:case Rr.selfJoinComplete:{r=pu.fromBinary.bind(pu);break}case Ss.globalPeerPinBroadcast:case Rr.globalPeerPinBroadcast:{r=kp.fromBinary.bind(kp);break}case Ss.selectedPeer:case Rr.selectedPeer:{r=hu.fromBinary.bind(hu);break}case Ss.selectedPeerDiff:case Rr.selectedPeerDiff:{r=Cp.fromBinary.bind(Cp);break}case Ss.leaveRoom:case Rr.leaveRoom:{r=gu.fromBinary.bind(gu);break}}this.socket.on(t,({payload:a})=>{let o=i;if(!r)return e(void 0);try{o=r(a)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}async getUserPermissions(t){const e={userIds:[t]};try{const r=await this.socket.sendMessagePromise(Xc.getUserPresets,zk.toBinary(e)),i=Zk.fromBinary(r.payload).peerPresets[0],a=new TextDecoder().decode(i.preset),o=JSON.parse(a).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}}}Nt=new WeakMap;UD([y.trace("RoomSocketHandler.joinRoom")],mT.prototype,"joinRoom",1);var Et;class $D{constructor(t){g(this,Et,void 0);m(this,Et,t)}async getStageRequests(){const{payload:t}=await n(this,Et).sendMessagePromise(L.getStageRequests);return t?Xl.fromBinary(t):{stageRequests:[]}}requestAccess(){n(this,Et).sendMessage(L.requestStageAccess)}cancelRequestAccess(){n(this,Et).sendMessage(L.cancelStageRequest)}async grantAccess(t){const e={userIds:t};n(this,Et).sendMessage(L.grantStageAccess,OA.toBinary(e))}async denyAccess(t){const e={userIds:t};n(this,Et).sendMessage(L.denyStageAccess,VA.toBinary(e))}joinStage(){return n(this,Et).sendMessagePromise(L.joinStage,void 0,void 0,L.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return n(this,Et).sendMessagePromise(L.leaveStage,qp.toBinary(e),void 0,L.peerStageStatusUpdate)}kick(t){const e={userIds:t};return n(this,Et).sendMessagePromise(L.leaveStage,qp.toBinary(e))}on(t,e){let r;switch(t){case L.grantStageAccess:case L.denyStageAccess:{r=void 0;break}case L.getStagePeers:{r=Hp.fromBinary.bind(Hp);break}case L.getStageRequests:case L.requestStageAccess:case L.cancelStageRequest:{r=Xl.fromBinary.bind(Xl);break}case L.peerStageStatusUpdate:{r=Ip.fromBinary.bind(Ip);break}}n(this,Et).on(t,({payload:i,id:a})=>{if(!i||!r)return e(void 0,a);const o=r(i);return e(o,a)})}async getPeerInfo(t){const e=await n(this,Et).sendMessagePromise(L.getPeerInfo,Zm.toBinary({peerId:t}));return dn.fromBinary(e.payload)}}Et=new WeakMap;var Fe,Ec;class FD{constructor(t,e){g(this,Fe,void 0);g(this,Ec,void 0);m(this,Fe,e),m(this,Ec,t)}get logger(){return n(this,Ec).getValue("logger")}addPlugin(t,e){n(this,Fe).sendMessage(j.addPlugin,YI.toBinary({pluginId:t,staggered:e}))}removePlugin(t){n(this,Fe).sendMessage(j.removePlugin,XI.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await n(this,Fe).sendMessagePromise(j.getPlugins);return t?EA.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};n(this,Fe).sendMessage(j.customPluginEventToRoom,cA.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const a={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};n(this,Fe).sendMessage(j.customPluginEventToPeers,lA.toBinary(a),i)}enablePluginForRoom(t,e){n(this,Fe).sendMessage(j.enablePluginForRoom,eA.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){n(this,Fe).sendMessage(j.enablePluginForPeers,iA.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){n(this,Fe).sendMessage(j.disablePluginForRoom,sA.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){n(this,Fe).sendMessage(j.disablePluginForPeers,aA.toBinary({pluginId:t,peerIds:e}),r)}storeInsertKeys(t,e,r,i){const a={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};n(this,Fe).sendMessage(j.storeInsertKeys,xp.toBinary(a),i)}storeGetKeys(t,e,r,i){const a={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};n(this,Fe).sendMessage(j.storeGetKeys,gA.toBinary(a),i)}storeDeleteKeys(t,e,r,i){const a={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};n(this,Fe).sendMessage(j.storeDeleteKeys,fA.toBinary(a),i)}storeDelete(t,e,r){n(this,Fe).sendMessage(j.storeDelete,vA.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))}]};n(this,Fe).sendMessage(j.storeInsertKeys,xp.toBinary(i))}on(t,e){let r;switch(t){case j.addPlugin:case j.enablePluginForPeers:case j.enablePluginForRoom:{r=vu.fromBinary.bind(vu);break}case j.removePlugin:case j.disablePluginForPeers:case j.disablePluginForRoom:{r=Up.fromBinary.bind(Up);break}case j.customPluginEventToPeers:case j.customPluginEventToRoom:{r=Fp.fromBinary.bind(Fp);break}case j.storeInsertKeys:case j.storeGetKeys:case j.storeDeleteKeys:case j.storeDelete:{r=$p.fromBinary.bind($p);break}}n(this,Fe).on(t,({payload:i,id:a})=>{const o=r(i);return e(o,a)})}}Fe=new WeakMap,Ec=new WeakMap;var BD=Object.defineProperty,HD=(s,t,e)=>t in s?BD(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,qD=(s,t,e)=>(HD(s,typeof t!="symbol"?t+"":t,e),e),Mh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},A=(s,t,e)=>(Mh(s,t,"read from private field"),e?e.call(s):t.get(s)),pe=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},se=(s,t,e,r)=>(Mh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),ye=(s,t,e)=>(Mh(s,t,"access private method"),e),yd={},jD={get exports(){return yd},set exports(s){yd=s}},_n=typeof Reflect=="object"?Reflect:null,tg=_n&&typeof _n.apply=="function"?_n.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},nd;_n&&typeof _n.ownKeys=="function"?nd=_n.ownKeys:Object.getOwnPropertySymbols?nd=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:nd=function(s){return Object.getOwnPropertyNames(s)};function GD(s){console&&console.warn&&console.warn(s)}var fT=Number.isNaN||function(s){return s!==s};function ne(){ne.init.call(this)}jD.exports=ne;yd.once=zD;ne.EventEmitter=ne;ne.prototype._events=void 0;ne.prototype._eventsCount=0;ne.prototype._maxListeners=void 0;var sg=10;function Ll(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ne,"defaultMaxListeners",{enumerable:!0,get:function(){return sg},set:function(s){if(typeof s!="number"||s<0||fT(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");sg=s}});ne.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};ne.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||fT(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 TT(s){return s._maxListeners===void 0?ne.defaultMaxListeners:s._maxListeners}ne.prototype.getMaxListeners=function(){return TT(this)};ne.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")tg(c,this,t);else for(var d=c.length,l=PT(c,d),e=0;e<d;++e)tg(l[e],this,t);return!0};function vT(s,t,e,r){var i,a,o;if(Ll(e),a=s._events,a===void 0?(a=s._events=Object.create(null),s._eventsCount=0):(a.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),a=s._events),o=a[t]),o===void 0)o=a[t]=e,++s._eventsCount;else if(typeof o=="function"?o=a[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=TT(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,GD(c)}return s}ne.prototype.addListener=function(s,t){return vT(this,s,t,!1)};ne.prototype.on=ne.prototype.addListener;ne.prototype.prependListener=function(s,t){return vT(this,s,t,!0)};function WD(){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 ST(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=WD.bind(r);return i.listener=e,r.wrapFn=i,i}ne.prototype.once=function(s,t){return Ll(t),this.on(s,ST(this,s,t)),this};ne.prototype.prependOnceListener=function(s,t){return Ll(t),this.prependListener(s,ST(this,s,t)),this};ne.prototype.removeListener=function(s,t){var e,r,i,a,o;if(Ll(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,a=e.length-1;a>=0;a--)if(e[a]===t||e[a].listener===t){o=e[a].listener,i=a;break}if(i<0)return this;i===0?e.shift():JD(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this};ne.prototype.off=ne.prototype.removeListener;ne.prototype.removeAllListeners=function(s){var t,e,r;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[s]),this;if(arguments.length===0){var i=Object.keys(e),a;for(r=0;r<i.length;++r)a=i[r],a!=="removeListener"&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=e[s],typeof t=="function")this.removeListener(s,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(s,t[r]);return this};function yT(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?KD(i):PT(i,i.length)}ne.prototype.listeners=function(s){return yT(this,s,!0)};ne.prototype.rawListeners=function(s){return yT(this,s,!1)};ne.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):ET.call(s,t)};ne.prototype.listenerCount=ET;function ET(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}ne.prototype.eventNames=function(){return this._eventsCount>0?nd(this._events):[]};function PT(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function JD(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function KD(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function zD(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,a),r(o)}function a(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}_T(s,t,a,{once:!0}),t!=="error"&&YD(s,i,{once:!0})})}function YD(s,t,e){typeof s.on=="function"&&_T(s,"error",t,e)}function _T(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(a){r.once&&s.removeEventListener(t,i),e(a)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class QD extends v.MessageType{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const rg=new QD;class CT{static encode(t){return rg.toBinary(t)}static decode(t){return rg.fromBinary(new Uint8Array(t))}}function XD(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Cr;class ZD{constructor(t={}){qD(this,"opts"),pe(this,Cr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},se(this,Cr,0)}async wait(){se(this,Cr,A(this,Cr)+1);const t=XD(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**A(this,Cr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return A(this,Cr)}reset(){se(this,Cr,0)}}Cr=new WeakMap;const yr={debug:0,info:1,warn:2,error:3};var ii,ni;class eO{constructor(t){pe(this,ii,void 0),pe(this,ni,void 0),se(this,ii,console),se(this,ni,t)}debug(...t){yr[A(this,ni)]>yr.debug||A(this,ii).debug("[Sockrates]:",...t)}info(...t){yr[A(this,ni)]>yr.info||A(this,ii).info("[Sockrates]:",...t)}warn(...t){yr[A(this,ni)]>yr.warn||A(this,ii).warn("[Sockrates]:",...t)}error(...t){yr[A(this,ni)]>yr.error||A(this,ii).error("[Sockrates]:",...t)}}ii=new WeakMap,ni=new WeakMap;var wT=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(wT||{});const tO="2",sO="3";var Re,pn,Se,Oe,wr,Ge,or,Wr,vs,gn,Us,qu,RT,ao,ad,ju,bT,Gu,ig,Ed,Wu,Ju,kT,lo,od,uo,Pd,_d,Ku,Cn,ho,po,Cd;class rO{constructor(t,e){var f,T,E,C,_,I,M,x,N,$;pe(this,qu),pe(this,ao),pe(this,ju),pe(this,Gu),pe(this,Ed),pe(this,Ju),pe(this,lo),pe(this,uo),pe(this,_d),pe(this,Cn),pe(this,po),pe(this,Re,void 0),pe(this,pn,void 0),pe(this,Se,void 0),pe(this,Oe,void 0),pe(this,wr,void 0),pe(this,Ge,void 0),pe(this,or,void 0),pe(this,Wr,void 0),pe(this,vs,void 0),pe(this,gn,void 0),pe(this,Us,void 0);var r,i,a,o,c,d,l,h,p;se(this,pn,t),se(this,wr,[]),se(this,Ge,new yd),se(this,or,!0),se(this,vs,!1),se(this,Se,e!=null?e:{}),(f=(r=A(this,Se)).autoReconnect)!=null||(r.autoReconnect=!0),(T=(i=A(this,Se)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(E=(a=A(this,Se)).pingTimeout)!=null||(a.pingTimeout=3e4),(C=(o=A(this,Se)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(_=(c=A(this,Se)).debug)!=null||(c.debug=!0),(I=(d=A(this,Se)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(M=(l=A(this,Se)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(x=(h=A(this,Se)).queueOnDisconnect)!=null||(h.queueOnDisconnect=!1),(N=(p=A(this,Se)).flushOnReconnect)!=null||(p.flushOnReconnect=!1),se(this,Wr,{code:void 0,reason:void 0}),se(this,Oe,($=A(this,Se).logger)!=null?$:new eO(A(this,Se).debug?"debug":"info")),se(this,Us,new ZD)}get readyState(){var t;return(t=A(this,Re))==null?void 0:t.readyState}get url(){return A(this,pn)}updateURL(t){se(this,pn,t),ye(this,Ju,kT).call(this)}get config(){return A(this,Se)}get sendQueue(){return A(this,wr)}flush(){if(!A(this,Se).queueOnDisconnect)return!1;const t=[];return A(this,wr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),se(this,wr,t),A(this,wr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){A(this,Oe).debug("Websocket was already connecting or connected.");return}if(A(this,or)!==!1)return new Promise((e,r)=>{ye(this,Cn,ho).call(this),ye(this,po,Cd).call(this);try{se(this,Re,new WebSocket(ye(this,qu,RT).call(this,A(this,pn)))),A(this,Re).binaryType="arraybuffer",A(this,Oe).debug("Connecting");const i=setTimeout(()=>{A(this,Oe).debug("Connection timeout. Closing socket"),se(this,or,!0),ye(this,po,Cd).call(this),A(this,Re).close(3001,"Connection Timeout"),A(this,Se).autoReconnect&&!A(this,vs)&&(A(this,Ge).emit("reconnecting"),ye(this,lo,od).call(this)),r(new Error("Connection timed out!"))},A(this,Se).connectionTimeout);A(this,Re).onopen=()=>{A(this,Oe).debug(`Ready State: ${wT[A(this,Re).readyState]}`),i&&clearTimeout(i),ye(this,_d,Ku).call(this),se(this,Wr,{code:void 0,reason:void 0}),A(this,Ge).emit("connected"),A(this,Se).flushOnReconnect&&this.flush(),e()},A(this,Re).onclose=a=>{try{i&&clearTimeout(i);const{code:o,reason:c}=a;r(c),A(this,Oe).debug("Socket closed. Close event:",{event:a}),A(this,Oe).debug(`Connection closed code: ${o}`),A(this,Oe).debug(`Connection closed reason: ${c}`),A(this,vs)||ye(this,Ed,Wu).call(this,o,c)}catch(o){ye(this,ao,ad).call(this,o)}},A(this,Re).onerror=a=>{ye(this,ao,ad).call(this,a)},A(this,Re).onmessage=a=>ye(this,ju,bT).call(this,a)}catch(i){ye(this,ao,ad).call(this,i,r)}})}send(t,e,r,i){const a={event:t,id:e,payload:r,metadata:i};if(A(this,Se).queueOnDisconnect&&(!A(this,Re)||A(this,Re).readyState!==1))return A(this,Oe).debug("Queuing message since socket is not connected!",a),A(this,wr).push(a),!1;const o=CT.encode(a);return ye(this,uo,Pd).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return ye(this,uo,Pd).call(this,t)}receive(t,e){return A(this,Ge).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){A(this,Ge).on(t,e);return}this.receive(t,e)}removeAllListeners(){A(this,Ge).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){A(this,Ge).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){A(this,Ge).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){se(this,or,!1),ye(this,Cn,ho).call(this),this.removeAllListeners(),se(this,Wr,{code:1e3,reason:"Sockrates disconnect method called"}),A(this,Re).close(1e3,"Sockrates disconnect method called.")}}Re=new WeakMap,pn=new WeakMap,Se=new WeakMap,Oe=new WeakMap,wr=new WeakMap,Ge=new WeakMap,or=new WeakMap,Wr=new WeakMap,vs=new WeakMap,gn=new WeakMap,Us=new WeakMap,qu=new WeakSet,RT=function(s){if(s.startsWith("ws://")||s.startsWith("wss://"))return s;if(s.startsWith("https://"))return`wss://${s.substring(8)}`;if(s.startsWith("http://"))return`ws://${s.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},ao=new WeakSet,ad=function(s,t){A(this,Oe).error("Error:",{error:s}),A(this,Ge).emit("errored",{error:s}),t==null||t(s)},ju=new WeakSet,bT=function(s){if(ye(this,_d,Ku).call(this),s.data===tO){A(this,Oe).debug("Received ping from server"),ye(this,uo,Pd).call(this,sO);return}const t=CT.decode(s.data),{id:e,payload:r}=t;A(this,Oe).debug("Received message",{event:t.event,messageID:e}),A(this,Ge).emit(t.event.toString(),{id:e,payload:r})},Gu=new WeakSet,ig=function(){return A(this,Re).readyState===1},Ed=new WeakSet,Wu=function(s,t){se(this,Wr,{reason:t,code:s}),A(this,Ge).emit("disconnected",{code:s,reason:t})},Ju=new WeakSet,kT=function(){const{reason:s,code:t}=A(this,Wr);t&&t!==1e3&&A(this,or)&&A(this,Se).autoReconnect&&!A(this,vs)&&(A(this,Oe).debug(`Triggering reconnection due to ${s}.`),A(this,Ge).emit("reconnecting"),ye(this,lo,od).call(this))},lo=new WeakSet,od=async function(s=!0){if(s&&A(this,vs)){A(this,Oe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(A(this,vs)||A(this,Us).reset(),A(this,Se).maxReconnectionAttempts!==null&&A(this,Us).getAttempts()>=A(this,Se).maxReconnectionAttempts){A(this,Ge).emit("failed"),se(this,vs,!1);return}se(this,vs,!0),ye(this,po,Cd).call(this),ye(this,Cn,ho).call(this);try{if(await A(this,Us).wait(),A(this,or)===!1)return;if(A(this,Oe).debug(`Reconnection attempt ${A(this,Us).getAttempts()}`),A(this,Ge).emit("reconnectAttempt",{attempt:A(this,Us).getAttempts()}),await this.connect(),!ye(this,Gu,ig).call(this))throw Error("Reconnect Failed");se(this,vs,!1),se(this,Wr,{code:void 0,reason:void 0}),A(this,Ge).emit("reconnected")}catch(t){A(this,Oe).debug("Failed to reconnect."),A(this,Ge).emit("reconnectFailure",{attempt:A(this,Us).getAttempts()}),ye(this,lo,od).call(this,!1)}},uo=new WeakSet,Pd=function(s){try{return A(this,Re).send(s),!0}catch(t){return A(this,Oe).error(t.message),!1}},_d=new WeakSet,Ku=function(){this.config.disconnectOnPingTimeout&&(A(this,Oe).debug("Resetting ping timeout"),ye(this,Cn,ho).call(this),se(this,gn,setTimeout(()=>{var s;A(this,Oe).debug("Disconnecting the socket due to ping timeout"),se(this,or,!0);const t=3002,e="Ping timeout";(s=A(this,Re))==null||s.close(t,e),ye(this,Ed,Wu).call(this,t,e)},A(this,Se).pingTimeout)))},Cn=new WeakSet,ho=function(){A(this,gn)&&(clearTimeout(A(this,gn)),se(this,gn,void 0))},po=new WeakSet,Cd=function(){A(this,Re)&&(A(this,Re).onopen=void 0,A(this,Re).onerror=void 0,A(this,Re).onmessage=void 0,A(this,Re).onclose=void 0)};var iO=Object.defineProperty,nO=Object.getOwnPropertyDescriptor,xl=(s,t,e,r)=>{for(var i=r>1?void 0:r?nO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&iO(t,e,i),i};const ng=65535,aO=3e3;var qr,Ee,Pe,ke,Zt,Ye,Pc,zu,_c,Yu,Cg;const IT=(Cg=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,Pe);g(this,Pc);g(this,_c);g(this,qr,void 0);g(this,Ee,void 0);u(this,"roomName");u(this,"authToken");u(this,"capabilities");g(this,Zt,void 0);g(this,Ye,void 0);var a;if(!t||!e||!r)throw new b("peerId, meetingId, or authToken can not be empty","0404");m(this,Zt,void 0),m(this,Ye,s),this.capabilities=i,this.roomName=e,this.authToken=r,m(this,qr,V(this,Pc,zu).call(this,t)),m(this,Ee,new rO(n(this,qr),{autoReconnect:!0,disconnectOnPingTimeout:(a=i.includes("PING"))!=null?a:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return n(this,Pe,ke).socketJoinAttempted}set joinAttempted(s){n(this,Pe,ke).socketJoinAttempted=s}get telemetry(){return n(this,Ye).getValue("telemetry")}get logger(){return n(this,Ye).getValue("logger")}get peerId(){return n(this,Ye).getValue("peerId")}updateURL(s){s!==this.peerId&&(m(this,qr,V(this,Pc,zu).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),n(this,Ee).updateURL(n(this,qr))}static getSocketEdgeDomain(s){return Yi({servicePrefix:"socket-edge",baseURI:s})}get url(){return n(this,qr)}async connect(){n(this,Pe,ke).socketJoinAttempted=!0,await n(this,Ee).connect(),n(this,Pe,ke).socketJoinAttempted=!0,n(this,Pe,ke).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){n(this,Pe,ke).socketJoinAttempted=!1,n(this,Ee).disconnect(),n(this,Pe,ke).socketJoinAttempted=!0,n(this,Pe,ke).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return n(this,Ee).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return n(this,Ye).getValue("telemetry").injectContext(r),n(this,Ee).send(s,e!=null?e:V(this,_c,Yu).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 a=i!=null?i:s;return new Promise((o,c)=>{const d=(E,C)=>{n(this,Ee).removeListener(a,E),n(this,Ee).removeListener(ng,C),n(this,Ee).removeListener(Rr.errorResponse,C),n(this,Ee).removeListener(Ss.errorResponse,C)},l=r!=null?r:V(this,_c,Yu).call(this),h={};n(this,Ye).getValue("telemetry").injectContext(h);const f=({id:E,payload:C})=>{if(l===E){let _;try{const I=TR.fromBinary(C);_=new Error(I.errorMessage)}catch(I){_=new Error("failed to parse error message",{cause:I});try{const M=vb.fromBinary(C);_=new Error(M.message)}catch(M){_=new Error("failed to parse error message",{cause:M})}}c(_),d(T,f)}},T=({id:E,payload:C})=>{l===E&&(o({id:E,payload:C}),d(T,f))};n(this,Ee).on(a,T),n(this,Ee).on(ng,f),n(this,Ee).on(Rr.errorResponse,f),n(this,Ee).on(Ss.errorResponse,f),setTimeout(()=>{d(T,f),c(new Error(`request timeout for callback eventId:${s}`))},t),n(this,Ee).send(s,l,e,new TextEncoder().encode(JSON.stringify(h)))})}on(s,t){n(this,Ee).on(s,t)}onStateEvent(s,t){n(this,Ee).on(s,t)}removeListener(s,t){n(this,Ee).removeListener(s,t)}removeListeners(s){n(this,Ee).removeListeners(s)}flush(){return n(this,Ee).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),n(this,Zt)&&(clearTimeout(n(this,Zt)),m(this,Zt,void 0)),n(this,Pe,ke).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:y.location.country});const{recv:e,send:r}=(i=n(this,Pe,ke).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Pn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Pn.CONNECTED?n(this,Ye).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,Pe,ke).joinAttempted}):m(this,Zt,setTimeout(()=>{n(this,Ye).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,Pe,ke).joinAttempted}),m(this,Zt,void 0)},aO)),n(this,Pe,ke).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge",{country:y.location.country}),n(this,Pe,ke).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),n(this,Pe,ke).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),n(this,Pe,ke).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:n(this,Pe,ke).mediaJoinAttempted}}),n(this,Zt)&&(clearTimeout(n(this,Zt)),m(this,Zt,void 0)),n(this,Ye).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:n(this,Pe,ke).mediaJoinAttempted}),n(this,Pe,ke).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge",{country:y.location.country}),n(this,Ye).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_FAILED),n(this,Pe,ke).updateSocketConnectionState("failed")})}},qr=new WeakMap,Ee=new WeakMap,Pe=new WeakSet,ke=function(){return n(this,Ye).getValue("connectionHandler")},Zt=new WeakMap,Ye=new WeakMap,Pc=new WeakSet,zu=function(s){let t=IT.getSocketEdgeDomain(n(this,Ye).getValue("baseURI"));typeof ba(n(this,Ye),"socket_server_base")=="string"&&(t=ba(n(this,Ye),"socket_server_base"));const e=`wss://${t}`,r=new URL(`${e}/ws`),i=this.peerId,a={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(a).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},_c=new WeakSet,Yu=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Cg);let Vc=IT;xl([y.trace("SocketService.connect")],Vc.prototype,"connect",1);xl([y.trace("SocketService.disconnect")],Vc.prototype,"disconnect",1);xl([y.trace("SocketService.sendMessagePromise")],Vc.prototype,"sendMessagePromise",1);xl([y.trace("SocketService.sendMessagePromiseWithTimeout")],Vc.prototype,"sendMessagePromiseWithTimeout",1);class oO{constructor(t){u(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var a;const e=Gb.fromBinary(t),r=e.meetings.map(o=>{var c;return{id:o.id,title:o.title,participants:(c=o.participants)!=null?c:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(a=e.parentMeeting.participants)!=null?a:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=Tk.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=ef.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return Op.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return ok.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(L.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(L.createConnectedRooms,zb.toBinary({payloads:t}));return Op.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(L.deleteConnectedRooms,nk.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(L.movePeers,pk.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 cO=Object.defineProperty,dO=Object.getOwnPropertyDescriptor,lO=(s,t,e,r)=>{for(var i=r>1?void 0:r?dO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&cO(t,e,i),i},Ts;class AT extends Ut{constructor(e){const r=e.getValue("logger");super(r);u(this,"meetings",[]);u(this,"parentMeeting",null);g(this,Ts,void 0);m(this,Ts,e)}get supportsConnectedMeetings(){return n(this,Ts).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.
|
|
11
11
|
Please connect with our support team to enable connected meetings.`)}async getConnectedMeetings(){this.validateConnectedMeetingsAction(),this.logger.info("Getting connected meetings dump");const e=await n(this,Ts).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 n(this,Ts).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 n(this,Ts).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(a=>e.includes(a.id)&&a.participants.length!==0?this.moveParticipants(a.id,this.parentMeeting.id,a.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),await Promise.all(r);const i=await n(this,Ts).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 a=await n(this,Ts).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return a.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),a}async moveParticipantsWithCustomPreset(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const a=await n(this,Ts).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return a.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),a}moveSuccessHandler(e,r,i){const a=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>a.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>a.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>a.get(d)));return{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}Ts=new WeakMap;lO([_t({maxInvocations:60,period:60})],AT.prototype,"getConnectedMeetings",1);var uO=Object.defineProperty,hO=Object.getOwnPropertyDescriptor,Dh=(s,t,e,r)=>{for(var i=r>1?void 0:r?hO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&uO(t,e,i),i},le,wg;const MT=(wg=class{constructor(s){u(this,"connectedMeetings");g(this,le,void 0);m(this,le,s),this.connectedMeetings=new AT(s)}get telemetry(){return n(this,le).getValue("telemetry")}get logger(){return n(this,le).getValue("logger")}static init(s){const t=new MT(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){n(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(L.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),n(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(L.transferPeer,this.handleTransferPeer.bind(this)),n(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(L.movedPeer,this.handleMovedPeer.bind(this)),n(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(L.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),n(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(L.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=n(this,le).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,a,o,c;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
|
|
12
12
|
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:n(this,le).getValue("self").videoEnabled,audio:n(this,le).getValue("self").audioEnabled};try{n(this,le).getValue("self").cleanupEvents(),await n(this,le).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(a=(i=n(this,le).getValue("meeting"))==null?void 0:i.meta)==null?void 0:a.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await OT.init({...n(this,le).getValue("options"),cachedUserDetails:null,defaults:{...n(this,le).getValue("options").defaults,...e,mediaHandler:n(this,le).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=n(this,le).getValue("self");r.self.setName(n(this,le).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=n(this,le).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return n(this,le).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=n(this,le).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=n(this,le).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})}},le=new WeakMap,wg);let Ul=MT;Dh([y.trace("ConnectedMeetingsController.getConnectedMeetings")],Ul.prototype,"getConnectedMeetings",1);Dh([y.trace("ConnectedMeetingsController.setupEvents")],Ul.prototype,"setupEvents",1);Dh([y.trace("ConnectedMeetingsController.switchMeeting")],Ul.prototype,"switchMeeting",1);var pO=Object.defineProperty,gO=Object.getOwnPropertyDescriptor,$l=(s,t,e,r)=>{for(var i=r>1?void 0:r?gO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&pO(t,e,i),i};const mn=class{constructor(s,t,e){u(this,"apiBase");u(this,"selfController");u(this,"pollController");u(this,"chatController");u(this,"metaController");u(this,"storesManager");u(this,"stageController");u(this,"pluginController");u(this,"internalsController");u(this,"recordingController");u(this,"livestreamController");u(this,"participantController");u(this,"connectedMeetingsController");u(this,"telemetry");u(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,$;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:a,cachedUserDetails:o,logger:c}=s.getAllValues();if(pT(s),fe.isSupported()===!1)throw new b("Browser not supported","0010",c,!0);const d=yM(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(a),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new t0(s);s.setValue("connectionHandler",l);const h=mn.createSocketService(s),p=h.connect(),f=d.getUserDetails(),T=d.getPlugins();let E,C="";try{await mn.setupFlagsmith(s)}catch(q){c.error("Failed to setup flagsmith",{error:q})}try{await p}catch(q){c.error("[Controller]: Failed to connect to socket server:",{error:q})}try{({meetingTitle:C}=await d.getRoomNodeData()),E=await f,c.info("CF SFU is being used."),s.setValue("presetName",E.preset.name)}catch(q){c.error("Failed to get room metadata",{error:q})}const _=bu.init(E.preset,!s.getValue("modules").theme),I=Mu.init(s,_.viewType,E.preset.permissions),M=mn.setupControllers(h,s,E,T,C,_,I);jM(_)&&((N=mn.createRoomNodeClient(s,h).initializeConnection(E.participant.name,i,!1,I))==null||N.catch(ee=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:ee})})),y.location.country=($=d.ipInfo)==null?void 0:$.country;const{controllers:x}=await M;return XC(),new mn(e,x,s)}static async setupFlagsmith(s){var l;const{peerId:t,baseURI:e,overrides:r,meetingId:i,organizationId:a,logger:o}=s.getAllValues(),c=QC(i),d={entity:lu.PEER,clientId:a,isAnonUser:!a,sdkVersion:s.getValue("sdkVersion"),presetName:s.getValue("presetName"),meetingHash:c,roomName:i,...fe.getDeviceInfo(),isReactNative:navigator.isReactNative};try{const h=(l=r==null?void 0:r.whitelabelled_flags_endpoint)==null||l?Yi({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";await s.getValue("flagsmith").identify(`${lu.PEER}_${t}`,JSON.parse(JSON.stringify(d)),!1,5e3,h,o),o.info("flagsmith::allFlags",{flags:JSON.stringify(s.getValue("flagsmith").getAllFlags())},!0)}catch(h){o.error("Failed to fetch flagsmith flags")}}static async setupControllers(s,t,e,r,i,a,o){var O,R,Ne;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),h=t.getValue("logger"),{viewType:p,mediaConstraints:{audio:f}}=a;t.setValue("viewType",p),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(O=f.enableHighBitrate)!=null?O:!1,enableStereo:(R=f.enableStereo)!=null?R:!1}},...l}),t.setValue("maxPreferredStreams",fe.isMobile()?a.maxVideoStreams.mobile:a.maxVideoStreams.desktop);let T,E,C,_,I,M,x,N,$;const q=new OD(t,s),ee=new oO(s);t.setValue("connectedMeetingsSocketHandler",ee);const Qe=new Vl(t,s),is=new Tr(t,s),ei=new $D(s),ns=new mT(t,s),k=new FD(t,s),S=new DD(s),P=await Zr.init(t,ns,d,o,a);t.setValue("selfController",P);const U=await ff.init(t,P.self,ns,q,i);if(c.participant&&(N=new Sr(t,P.self,ns)),(Ne=c.e2ee)!=null&&Ne.enabled&&c.e2ee.manager.init(h,t.getValue("peerSessionStore")),c.chat&&(E=await ts.init(t,is,P.self,N.participants)),c.internals&&(I=await yh.init(t)),c.livestream&&a.viewType===lr.Livestream&&t.getValue("flagsmith").hasFeature(Y.LIVESTREAM)&&(x=new wf(t,P.self,S)),c.poll&&(T=await hf.init(t,P.self,Qe)),c.recording&&(M=new yf(t,P.self,ns)),c.stage&&(C=new Tf(t,ei,ns,P.self,N.participants)),c.plugin){if(!N)throw new b("The plugin module cannot be initialized without the `participant` module","0102");const xs=await r;_=await Mc.init(t,xs,k,is,E==null?void 0:E.chat,P.self,N.participants,i)}if(c.connectedMeetings&&($=await Ul.init(t)),c.pip){const xs=await uu._init(t,P.self);t.setValue("pip",xs)}const be={storesManager:new W0(t,k),pollController:T,selfController:P,metaController:U,chatController:E,stageController:C,pluginController:_,recordingController:M,internalsController:I,livestreamController:x,participantController:N,connectedMeetingsController:$};return{theme:a,permissions:o,controllers:be}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return hT(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=["PING"];return new Vc(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Lc=mn;$l([y.trace("Controller.init")],Lc,"init",1);$l([y.trace("setupFlagsmith")],Lc,"setupFlagsmith",1);$l([y.trace("Controller.createRoomNodeClient")],Lc,"createRoomNodeClient",1);$l([y.trace("Controller.createSocketService")],Lc,"createSocketService",1);class mO{constructor(){u(this,"battery");u(this,"logger");u(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)}});u(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});u(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});u(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 ag=new mO;function fO(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 a=ci.baseURI.prod;t&&(a=t);const o=`https://${Yi({servicePrefix:"api",baseURI:a})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:a,apiBase:o}}catch(e){throw new b("Invalid auth token","0004")}}var jr,Wi,Ji,Cc,fl,DT;class TO{constructor(){g(this,fl);g(this,jr,new Audio);g(this,Wi,new MediaStream);g(this,Ji,new Map);g(this,Cc,void 0);n(this,jr).srcObject=n(this,Wi),n(this,jr).autoplay=!0}async playTracks(t){return t.forEach(e=>{n(this,Ji).has(e.id)||(n(this,Wi).addTrack(e),n(this,Ji).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&n(this,jr).setSinkId(t)}removeTrack(t){const e=n(this,Ji).get(t);e&&(n(this,Wi).removeTrack(e),n(this,Ji).delete(t))}async play(){return n(this,jr).srcObject=n(this,Wi),n(this,jr).play().catch(t=>{V(this,fl,DT).call(this,t)})}onError(t){m(this,Cc,t)}}jr=new WeakMap,Wi=new WeakMap,Ji=new WeakMap,Cc=new WeakMap,fl=new WeakSet,DT=function(t){var e;(e=n(this,Cc))==null||e.call(this,t)};var Ki;class vO extends TO{constructor(){super();g(this,Ki,void 0);m(this,Ki,new Map)}addParticipantTrack(e,r){n(this,Ki).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=n(this,Ki).get(e);r&&this.removeTrack(r),n(this,Ki).delete(e)}}Ki=new WeakMap;var SO=Object.defineProperty,yO=Object.getOwnPropertyDescriptor,Fl=(s,t,e,r)=>{for(var i=r>1?void 0:r?yO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&SO(t,e,i),i},Be,zi,Rg;let zr=(Rg=class{constructor(t,e){g(this,Be,void 0);g(this,zi,void 0);m(this,zi,t),m(this,Be,e)}get peerId(){return n(this,zi).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:ur.v4(),a=cr.createContext(i,{peerId:i}),o=a.getValue("logger");o.init(a);const c=new Of(a,o);return await c.init(t,e,a),a.setValue("defaults",{mediaHandler:c}),c}static async init(t){var f,T,E,C,_,I;fe.init();const e=(T=(f=t==null?void 0:t.cachedUserDetails)==null?void 0:f.peerId)!=null?T:ur.v4(),{authToken:r,baseURI:i}=t,{meetingId:a,...o}=fO(r,i);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=zr.setupContext(e,t,a,o),d=c.getValue("telemetry"),l=c.getValue("logger");FT(l),ag.init(l),d.init(c,{roomName:a,userId:o.participantId,organizationId:o.orgId,peerId:e},(C=(E=t.modules)==null?void 0:E.tracing)!=null?C:!0),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(_=t.authToken)==null?void 0:_.slice(0,10)}...
|
|
13
|
-
${(I=t.authToken)==null?void 0:I.slice(-10)}`}});const h=await Lc.init(c),p=new zr(c,h);return c.setValue("meeting",p),p}static setupContext(t,e,r,i){var d,l;const a=cr.createContext(t,e),o={...BC,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return a.setValue("options",e),a.setValue("peerId",t),a.setValue("modules",o),a.setValue("sdkName","web-core"),a.setValue("meetingId",r),a.setValue("apiBase",i.apiBase),a.setValue("baseURI",i.baseURI),a.setValue("userId",i.participantId),a.setValue("organizationId",i.orgId),a.setValue("authToken",e.authToken),a.setValue("overrides",(d=e.overrides)!=null?d:{}),a.setValue("env",HC({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",ys(e.cachedUserDetails)),a.setValue("sdkVersion","1.2.
|
|
13
|
+
${(I=t.authToken)==null?void 0:I.slice(-10)}`}});const h=await Lc.init(c),p=new zr(c,h);return c.setValue("meeting",p),p}static setupContext(t,e,r,i){var d,l;const a=cr.createContext(t,e),o={...BC,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return a.setValue("options",e),a.setValue("peerId",t),a.setValue("modules",o),a.setValue("sdkName","web-core"),a.setValue("meetingId",r),a.setValue("apiBase",i.apiBase),a.setValue("baseURI",i.baseURI),a.setValue("userId",i.participantId),a.setValue("organizationId",i.orgId),a.setValue("authToken",e.authToken),a.setValue("overrides",(d=e.overrides)!=null?d:{}),a.setValue("env",HC({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",ys(e.cachedUserDetails)),a.setValue("sdkVersion","1.2.6-staging.1"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new vO),a}async join(){const{selfController:t}=n(this,Be);return t.self.roomJoined?null:t.joinRoom()}async leave(t){ag.cleanup(),n(this,zi).getValue("peerSessionStore").reset();const{selfController:e}=n(this,Be);return e.leaveRoom(t)}get participants(){var t;return(t=n(this,Be).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,Be).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,Be).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,Be).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,Be).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,Be).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,Be).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,Be).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,Be).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,Be).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,Be).stageController)==null?void 0:t.stage}get stores(){return n(this,Be).storesManager}get audio(){return n(this,zi).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,Be).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Be=new WeakMap,zi=new WeakMap,Rg);Fl([at("0002"),vr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],zr.prototype,"join",1);Fl([at("0003")],zr.prototype,"leave",1);Fl([at("0001"),vr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],zr,"init",1);zr=Fl([at("0000")],zr);const OT=zr;module.exports=OT;
|